blob: 662743d1fbb788d41ccae643090c2da12b9c4a0b [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080020#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050022#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
27#include "android-base/errors.h"
28#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080029#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020030#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080031#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070032
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "AppInfo.h"
34#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080037#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070038#include "ResourceValues.h"
39#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070041#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080042#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080043#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070045#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070046#include "format/binary/TableFlattener.h"
47#include "format/binary/XmlFlattener.h"
48#include "format/proto/ProtoDeserialize.h"
49#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070050#include "io/BigBufferStream.h"
51#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070053#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080054#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070055#include "java/JavaClassGenerator.h"
56#include "java/ManifestClassGenerator.h"
57#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080060#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070063#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080064#include "optimize/ResourceDeduper.h"
65#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066#include "process/IResourceTableConsumer.h"
67#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080068#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080070#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070072using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020073using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::android::StringPiece;
75using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070076
Adam Lesinski1ab598f2015-08-14 14:26:04 -070077namespace aapt {
78
Adam Lesinski64587af2016-02-18 18:33:06 -080079class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070080 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -080081 explicit LinkContext(IDiagnostics* diagnostics)
Chris Warrington820d72a2017-04-27 15:27:01 +010082 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070083 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070084
Adam Lesinskib522f042017-04-21 16:57:59 -070085 PackageType GetPackageType() override {
86 return package_type_;
87 }
88
89 void SetPackageType(PackageType type) {
90 package_type_ = type;
91 }
92
Adam Lesinskid0f492d2017-04-03 18:12:45 -070093 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010094 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070095 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070096
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 NameMangler* GetNameMangler() override {
98 return &name_mangler_;
99 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
102 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800104
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 const std::string& GetCompilationPackage() override {
106 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700108
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700109 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800110 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700111 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800112
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700113 uint8_t GetPackageId() override {
114 return package_id_;
115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 void SetPackageId(uint8_t id) {
118 package_id_ = id;
119 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800120
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700121 SymbolTable* GetExternalSymbols() override {
122 return &symbols_;
123 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800124
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700125 bool IsVerbose() override {
126 return verbose_;
127 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800128
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700129 void SetVerbose(bool val) {
130 verbose_ = val;
131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 int GetMinSdkVersion() override {
134 return min_sdk_version_;
135 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetMinSdkVersion(int minSdk) {
138 min_sdk_version_ = minSdk;
139 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700140
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700142 DISALLOW_COPY_AND_ASSIGN(LinkContext);
143
Adam Lesinskib522f042017-04-21 16:57:59 -0700144 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100145 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700146 NameMangler name_mangler_;
147 std::string compilation_package_;
148 uint8_t package_id_ = 0x0;
149 SymbolTable symbols_;
150 bool verbose_ = false;
151 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152};
153
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700154// A custom delegate that generates compatible pre-O IDs for use with feature splits.
155// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
156// is interpreted as a negative number. Some verification was wrongly assuming negative values
157// were invalid.
158//
159// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
160// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
161// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800162//
163// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700164class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
165 public:
Chih-Hung Hsieh1fc78e12018-12-20 13:37:44 -0800166 explicit FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700167 }
168
169 virtual ~FeatureSplitSymbolTableDelegate() = default;
170
171 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
172 const ResourceName& name,
173 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
174 std::unique_ptr<SymbolTable::Symbol> symbol =
175 DefaultSymbolTableDelegate::FindByName(name, sources);
176 if (symbol == nullptr) {
177 return {};
178 }
179
180 // Check to see if this is an 'id' with the target package.
181 if (name.type == ResourceType::kId && symbol->id) {
182 ResourceId* id = &symbol->id.value();
183 if (id->package_id() > kAppPackageId) {
184 // Rewrite the resource ID to be compatible pre-O.
185 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
186
187 // Check that this doesn't overlap another resource.
188 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
189 // The ID overlaps, so log a message (since this is a weird failure) and fail.
190 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
191 << " for pre-O feature split support");
192 return {};
193 }
194
195 if (context_->IsVerbose()) {
196 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
197 << ") -> (" << rewritten_id << ")");
198 }
199
200 *id = rewritten_id;
201 }
202 }
203 return symbol;
204 }
205
206 private:
207 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
208
209 IAaptContext* context_;
210};
211
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700212static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
213 const StringPiece& path, bool keep_raw_values, bool utf16,
214 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700215 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700216 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
217 << (keep_raw_values ? "true" : "false")
218 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700219 }
220
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700221 switch (format) {
222 case OutputFormat::kApk: {
223 BigBuffer buffer(1024);
224 XmlFlattenerOptions options = {};
225 options.keep_raw_values = keep_raw_values;
226 options.use_utf16 = utf16;
227 XmlFlattener flattener(&buffer, options);
228 if (!flattener.Consume(context, &xml_res)) {
229 return false;
230 }
231
232 io::BigBufferInputStream input_stream(&buffer);
233 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
234 ArchiveEntry::kCompress, writer);
235 } break;
236
237 case OutputFormat::kProto: {
238 pb::XmlNode pb_node;
Ryan Mitchell467b6892018-11-09 15:52:07 -0800239 // Strip whitespace text nodes from tha AndroidManifest.xml
240 SerializeXmlOptions options;
241 options.remove_empty_text_nodes = (path == kAndroidManifestPath);
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700242 SerializeXmlResourceToPb(xml_res, &pb_node);
243 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
244 writer);
245 } break;
246 }
247 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800248}
249
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700250// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700251static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700252 FileInputStream fin(path);
253 if (fin.HadError()) {
254 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700255 return {};
256 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700257 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800258}
259
Adam Lesinski355f2852016-02-13 20:26:45 -0800260struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 bool no_auto_version = false;
262 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900263 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700264 bool no_xml_namespaces = false;
265 bool keep_raw_values = false;
266 bool do_not_compress_anything = false;
267 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700268 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700269 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800270};
271
Adam Lesinskic744ae82017-05-17 19:28:38 -0700272// A sampling of public framework resource IDs.
273struct R {
274 struct attr {
275 enum : uint32_t {
276 paddingLeft = 0x010100d6u,
277 paddingRight = 0x010100d8u,
278 paddingHorizontal = 0x0101053du,
279
280 paddingTop = 0x010100d7u,
281 paddingBottom = 0x010100d9u,
282 paddingVertical = 0x0101053eu,
283
284 layout_marginLeft = 0x010100f7u,
285 layout_marginRight = 0x010100f9u,
286 layout_marginHorizontal = 0x0101053bu,
287
288 layout_marginTop = 0x010100f8u,
289 layout_marginBottom = 0x010100fau,
290 layout_marginVertical = 0x0101053cu,
291 };
292 };
293};
294
Adam Lesinski355f2852016-02-13 20:26:45 -0800295class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700296 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700297 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700298 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800299
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700300 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800301
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700302 private:
303 struct FileOperation {
304 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700305
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700306 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700307 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700308
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700309 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700310 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700311
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700312 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700313 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700314
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700315 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700317 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800318
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700319 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800320
Adam Lesinskic744ae82017-05-17 19:28:38 -0700321 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
322 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800323
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700324 ResourceFileFlattenerOptions options_;
325 IAaptContext* context_;
326 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700327 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800328};
329
Adam Lesinskic744ae82017-05-17 19:28:38 -0700330ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
331 IAaptContext* context, proguard::KeepSet* keep_set)
332 : options_(options), context_(context), keep_set_(keep_set) {
333 SymbolTable* symm = context_->GetExternalSymbols();
334
335 // Build up the rules for degrading newer attributes to older ones.
336 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
337 // generated from the attribute definitions themselves (b/62028956).
338 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
339 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800340 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
341 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700342 };
343 rules_[R::attr::paddingHorizontal] =
344 util::make_unique<DegradeToManyRule>(std::move(replacements));
345 }
346
347 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
348 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800349 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
350 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700351 };
352 rules_[R::attr::paddingVertical] =
353 util::make_unique<DegradeToManyRule>(std::move(replacements));
354 }
355
356 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
357 std::vector<ReplacementAttr> replacements{
358 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800359 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700360 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800361 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700362 };
363 rules_[R::attr::layout_marginHorizontal] =
364 util::make_unique<DegradeToManyRule>(std::move(replacements));
365 }
366
367 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
368 std::vector<ReplacementAttr> replacements{
369 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800370 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700371 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800372 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700373 };
374 rules_[R::attr::layout_marginVertical] =
375 util::make_unique<DegradeToManyRule>(std::move(replacements));
376 }
377}
378
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700379uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
380 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700381 return 0;
382 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800383
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700384 for (const std::string& extension : options_.extensions_to_not_compress) {
385 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700386 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800387 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700388 }
389 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800390}
391
Adam Lesinskibb94f322017-07-12 07:41:55 -0700392static bool IsTransitionElement(const std::string& name) {
393 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
394 name == "changeImageTransform" || name == "changeTransform" ||
395 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
396 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
397 name == "transitionManager";
398}
399
400static bool IsVectorElement(const std::string& name) {
401 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Winsona00d9692019-01-24 15:55:29 -0800402 name == "objectAnimator" || name == "gradient" || name == "animated-selector" ||
403 name == "set";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700404}
405
Adam Lesinskic744ae82017-05-17 19:28:38 -0700406template <typename T>
407std::vector<T> make_singleton_vec(T&& val) {
408 std::vector<T> vec;
409 vec.emplace_back(std::forward<T>(val));
410 return vec;
411}
412
413std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
414 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700415 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700416 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700417
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700418 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700419 context_->GetDiagnostics()->Note(DiagMessage()
420 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700421 }
422
Adam Lesinski00451162017-10-03 07:44:08 -0700423 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
424 // that existing projects have out-of-date references which pass compilation.
425 xml::StripAndroidStudioAttributes(doc->root.get());
426
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700427 XmlReferenceLinker xml_linker;
428 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700429 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700430 }
431
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700432 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700433 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700434 }
435
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700436 if (options_.no_xml_namespaces) {
437 XmlNamespaceRemover namespace_remover;
438 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700439 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800440 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700441 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800442
Adam Lesinskibb94f322017-07-12 07:41:55 -0700443 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700444 return make_singleton_vec(std::move(file_op->xml_to_flatten));
445 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700446
Adam Lesinskibb94f322017-07-12 07:41:55 -0700447 if (options_.no_version_vectors || options_.no_version_transitions) {
448 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700449 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700450 if (el && el->namespace_uri.empty()) {
451 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
452 (options_.no_version_transitions && IsTransitionElement(el->name))) {
453 return make_singleton_vec(std::move(file_op->xml_to_flatten));
454 }
455 }
456 }
457
Adam Lesinskic744ae82017-05-17 19:28:38 -0700458 const ConfigDescription& config = file_op->config;
459 ResourceEntry* entry = file_op->entry;
460
461 XmlCompatVersioner xml_compat_versioner(&rules_);
462 const util::Range<ApiVersion> api_range{config.sdkVersion,
463 FindNextApiVersionForConfig(entry, config)};
464 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800465}
466
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800467ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
468 switch (format) {
469 case OutputFormat::kApk:
470 return ResourceFile::Type::kBinaryXml;
471 case OutputFormat::kProto:
472 return ResourceFile::Type::kProtoXml;
473 }
474 LOG_ALWAYS_FATAL("unreachable");
475 return ResourceFile::Type::kUnknown;
476}
477
Ryan Mitchell70f79722018-08-13 07:37:24 -0700478static auto kDrawableVersions = std::map<std::string, ApiVersion>{
479 { "adaptive-icon" , SDK_O },
480};
481
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700482bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700483 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700484 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800485
Adam Koskidc21dea2017-07-21 10:55:27 -0700486 proguard::CollectResourceReferences(context_, table, keep_set_);
487
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700488 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700489 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
490
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700491 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700492 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700493 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800495
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700496 // Populate the queue with all files in the ResourceTable.
497 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700498 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700499 // WARNING! Do not insert or remove any resources while executing in this scope. It will
500 // corrupt the iteration order.
501
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700502 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700503 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700504 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700505 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700506
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700507 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700508 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700509 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700510 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700511 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700512 }
513
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700514 FileOperation file_op;
515 file_op.entry = entry.get();
516 file_op.dst_path = *file_ref->path;
517 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700518 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700520 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700521 (file_ref->type == ResourceFile::Type::kBinaryXml ||
522 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700523 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700524 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700525 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700526 << "failed to open file");
527 return false;
528 }
529
Adam Lesinski00451162017-10-03 07:44:08 -0700530 if (file_ref->type == ResourceFile::Type::kProtoXml) {
531 pb::XmlNode pb_xml_node;
532 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
533 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700534 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700535 return false;
536 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700537
Adam Lesinski00451162017-10-03 07:44:08 -0700538 std::string error;
539 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
540 if (file_op.xml_to_flatten == nullptr) {
541 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700542 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700543 return false;
544 }
545 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700546 std::string error_str;
547 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700548 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700549 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
550 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700551 return false;
552 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700553 }
554
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800555 // Update the type that this file will be written as.
556 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
557
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700558 file_op.xml_to_flatten->file.config = config_value->config;
559 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700560 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700561 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700562
563 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
564 // else we end up copying the string in the std::make_pair() method,
565 // then creating a StringPiece from the copy, which would cause us
566 // to end up referencing garbage in the map.
567 const StringPiece entry_name(entry->name);
568 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
569 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700570 }
571 }
572
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700574 for (auto& map_entry : config_sorted_files) {
575 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700576 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700577
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700578 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700579 // Check minimum sdk versions supported for drawables
580 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
581 if (drawable_entry != kDrawableVersions.end()) {
582 if (drawable_entry->second > context_->GetMinSdkVersion()
583 && drawable_entry->second > config.sdkVersion) {
584 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
585 << "<" << drawable_entry->first << "> elements "
586 << "require a sdk version of at least "
587 << (int16_t) drawable_entry->second);
588 error = true;
589 continue;
590 }
591 }
592
Adam Lesinskic744ae82017-05-17 19:28:38 -0700593 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
594 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700595 if (versioned_docs.empty()) {
596 error = true;
597 continue;
598 }
599
Adam Lesinskic744ae82017-05-17 19:28:38 -0700600 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
601 std::string dst_path = file_op.dst_path;
602 if (doc->file.config != file_op.config) {
603 // Only add the new versioned configurations.
604 if (context_->IsVerbose()) {
605 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
606 << "auto-versioning resource from config '"
607 << config << "' -> '" << doc->file.config << "'");
608 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700609
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800610 const ResourceFile& file = doc->file;
611 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
612
613 std::unique_ptr<FileReference> file_ref =
614 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
615 file_ref->SetSource(doc->file.source);
616 // Update the output format of this XML file.
617 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
618 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
619 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700620 return false;
621 }
622 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700623
624 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
625 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700626 }
627 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700628 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
629 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700630 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700631 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700632 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700633 }
634 return !error;
635}
636
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700637static bool WriteStableIdMapToPath(IDiagnostics* diag,
638 const std::unordered_map<ResourceName, ResourceId>& id_map,
639 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800640 io::FileOutputStream fout(id_map_path);
641 if (fout.HadError()) {
642 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643 return false;
644 }
645
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800646 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700647 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700648 const ResourceName& name = entry.first;
649 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800650 printer.Print(name.to_string());
651 printer.Print(" = ");
652 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800654 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700655
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800656 if (fout.HadError()) {
657 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700658 return false;
659 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700660 return true;
661}
662
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700663static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
664 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700665 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700666 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700667 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700668 return false;
669 }
670
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700671 out_id_map->clear();
672 size_t line_no = 0;
673 for (StringPiece line : util::Tokenize(content, '\n')) {
674 line_no++;
675 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 if (line.empty()) {
677 continue;
678 }
679
680 auto iter = std::find(line.begin(), line.end(), '=');
681 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700682 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700683 return false;
684 }
685
686 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700687 StringPiece res_name_str =
688 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
689 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700690 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
691 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700692 return false;
693 }
694
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700695 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
696 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700697 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
700 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700701 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
702 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700703 return false;
704 }
705
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700706 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 }
708 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700709}
710
Adam Lesinskic6284372017-12-04 13:46:23 -0800711static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
712 using namespace android;
713
714 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
715 // we're looking for the first attribute resource in the system package.
716 const ResTable& table = assets.getResources(true);
717 Res_value val;
718 ssize_t idx = table.getResource(0x01010000, &val, true);
719 if (idx != NO_ERROR) {
720 // Try as a bag.
721 const ResTable::bag_entry* entry;
722 ssize_t cnt = table.lockBag(0x01010000, &entry);
723 if (cnt >= 0) {
724 idx = entry->stringBlock;
725 }
726 table.unlockBag(entry);
727 }
728
729 if (idx < 0) {
730 return 0;
731 }
732 return table.getTableCookie(idx);
733}
734
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700735class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700737 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700738 : options_(options),
739 context_(context),
740 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700741 file_collection_(util::make_unique<io::FileCollection>()) {
742 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700743
Adam Lesinskic6284372017-12-04 13:46:23 -0800744 void ExtractCompileSdkVersions(android::AssetManager* assets) {
745 using namespace android;
746
747 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
748 if (cookie == 0) {
749 // No Framework assets loaded. Not a failure.
750 return;
751 }
752
753 std::unique_ptr<Asset> manifest(
754 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
755 if (manifest == nullptr) {
756 // No errors.
757 return;
758 }
759
760 std::string error;
761 std::unique_ptr<xml::XmlResource> manifest_xml =
762 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
763 if (manifest_xml == nullptr) {
764 // No errors.
765 return;
766 }
767
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700768 if (!options_.manifest_fixer_options.compile_sdk_version) {
769 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
770 if (attr != nullptr) {
771 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
772 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
773 switch (prim->value.dataType) {
774 case Res_value::TYPE_INT_DEC:
775 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
776 break;
777 case Res_value::TYPE_INT_HEX:
778 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
779 break;
780 default:
781 break;
782 }
783 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
784 compile_sdk_version = *str->value;
785 } else {
786 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800787 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800788 }
789 }
790
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700791 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
792 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
793 if (attr != nullptr) {
794 Maybe<std::string>& compile_sdk_version_codename =
795 options_.manifest_fixer_options.compile_sdk_version_codename;
796 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
797 compile_sdk_version_codename = *str->value;
798 } else {
799 compile_sdk_version_codename = attr->value;
800 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800801 }
802 }
803 }
804
Adam Lesinski8780eb62017-10-31 17:44:39 -0700805 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800806 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700807 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700808 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700809 for (const std::string& path : options_.include_paths) {
810 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700811 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700812 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700813
Adam Lesinski8780eb62017-10-31 17:44:39 -0700814 std::string error;
815 auto zip_collection = io::ZipFileCollection::Create(path, &error);
816 if (zip_collection == nullptr) {
817 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
818 return false;
819 }
820
821 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
822 // Load this as a static library include.
823 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
824 Source(path), std::move(zip_collection), context_->GetDiagnostics());
825 if (static_apk == nullptr) {
826 return false;
827 }
828
Adam Lesinskib522f042017-04-21 16:57:59 -0700829 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800830 // Can't include static libraries when not building a static library (they have no IDs
831 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700832 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800833 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700834 return false;
835 }
836
Adam Lesinski8780eb62017-10-31 17:44:39 -0700837 ResourceTable* table = static_apk->GetResourceTable();
838
839 // If we are using --no-static-lib-packages, we need to rename the package of this table to
840 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700841 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800842 // Since package names can differ, and multiple packages can exist in a ResourceTable,
843 // we place the requirement that all static libraries are built with the package
844 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700845 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700846 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800847 } else {
848 context_->GetDiagnostics()->Error(DiagMessage(path)
849 << "no package with ID 0x7f found in static library");
850 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700851 }
852 }
853
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700854 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700855 util::make_unique<ResourceTableSymbolSource>(table));
856 static_library_includes_.push_back(std::move(static_apk));
857 } else {
858 if (!asset_source->AddAssetPath(path)) {
859 context_->GetDiagnostics()->Error(DiagMessage()
860 << "failed to load include path " << path);
861 return false;
862 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700863 }
864 }
865
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800866 // Capture the shared libraries so that the final resource table can be properly flattened
867 // with support for shared libraries.
868 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700869 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800870 // Capture the included base feature package.
871 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800872 } else if (entry.first == kFrameworkPackageId) {
873 // Try to embed which version of the framework we're compiling against.
874 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
875 // when linking our synthesized 'android:compileSdkVersion' attribute.
876 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
877 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
878 if (symbol != nullptr && symbol->is_public) {
879 // The symbol is present and public, extract the android:versionName and
880 // android:versionCode from the framework AndroidManifest.xml.
881 ExtractCompileSdkVersions(asset_source->GetAssetManager());
882 }
Todd Kennedy32512992018-04-25 16:45:59 -0700883 } else if (asset_source->IsPackageDynamic(entry.first)) {
884 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800885 }
886 }
887
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700888 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700889 return true;
890 }
891
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800892 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800894 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
895 if (manifest_el == nullptr) {
896 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700897 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800898
899 AppInfo app_info;
900
901 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
902 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
903 return {};
904 }
905
906 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
907 if (!package_attr) {
908 diag->Error(DiagMessage(xml_res->file.source)
909 << "<manifest> must have a 'package' attribute");
910 return {};
911 }
912 app_info.package = package_attr->value;
913
914 if (xml::Attribute* version_code_attr =
915 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
916 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
917 if (!maybe_code) {
918 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
919 << "invalid android:versionCode '" << version_code_attr->value << "'");
920 return {};
921 }
922 app_info.version_code = maybe_code.value();
923 }
924
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700925 if (xml::Attribute* version_code_major_attr =
926 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
927 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
928 if (!maybe_code) {
929 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
930 << "invalid android:versionCodeMajor '"
931 << version_code_major_attr->value << "'");
932 return {};
933 }
934 app_info.version_code_major = maybe_code.value();
935 }
936
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800937 if (xml::Attribute* revision_code_attr =
938 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
939 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
940 if (!maybe_code) {
941 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
942 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
943 return {};
944 }
945 app_info.revision_code = maybe_code.value();
946 }
947
948 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
949 if (!split_name_attr->value.empty()) {
950 app_info.split_name = split_name_attr->value;
951 }
952 }
953
954 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
955 if (xml::Attribute* min_sdk =
956 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700957 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800958 }
959 }
960 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700961 }
962
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700963 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
964 // Postcondition: ResourceTable has only one package left. All others are
965 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700966 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700967 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700968 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
969 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700970 };
971
972 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700973 for (const auto& package : final_table_.packages) {
974 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700975 // We have a package that is not related to the one we're building!
976 for (const auto& type : package->types) {
977 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700978 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700979
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700980 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700981 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700982 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700983 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
984 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
985 << "generated id '" << res_name
986 << "' for external package '" << package->name
987 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700988 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700989 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
990 << "defined resource '" << res_name
991 << "' for external package '" << package->name
992 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700993 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700994 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700995 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996 }
997 }
998 }
999 }
1000
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001001 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1002 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001003 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004 return !error;
1005 }
1006
1007 /**
1008 * Returns true if no IDs have been set, false otherwise.
1009 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001010 bool VerifyNoIdsSet() {
1011 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 for (const auto& type : package->types) {
1013 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001014 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1015 << StringPrintf("%02x", type->id.value())
1016 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001018 }
1019
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001020 for (const auto& entry : type->entries) {
1021 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001022 ResourceNameRef res_name(package->name, type->type, entry->name);
1023 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001024 DiagMessage() << "entry " << res_name << " has ID "
1025 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001026 return false;
1027 }
1028 }
1029 }
1030 }
1031 return true;
1032 }
1033
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001034 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1035 if (options_.output_to_directory) {
1036 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001038 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 }
1040 }
1041
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001042 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1043 switch (format) {
1044 case OutputFormat::kApk: {
1045 BigBuffer buffer(1024);
1046 TableFlattener flattener(options_.table_flattener_options, &buffer);
1047 if (!flattener.Consume(context_, table)) {
1048 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1049 return false;
1050 }
1051
1052 io::BigBufferInputStream input_stream(&buffer);
1053 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1054 ArchiveEntry::kAlign, writer);
1055 } break;
1056
1057 case OutputFormat::kProto: {
1058 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001059 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001060 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1061 ArchiveEntry::kCompress, writer);
1062 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001063 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001064 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 }
1066
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001067 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001068 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001069 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001070 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001071 return true;
1072 }
1073
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001074 std::string out_path;
1075 std::unique_ptr<io::FileOutputStream> fout;
1076 if (options_.generate_java_class_path) {
1077 out_path = options_.generate_java_class_path.value();
1078 file::AppendPath(&out_path, file::PackageToPath(out_package));
1079 if (!file::mkdirs(out_path)) {
1080 context_->GetDiagnostics()->Error(DiagMessage()
1081 << "failed to create directory '" << out_path << "'");
1082 return false;
1083 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001084
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001085 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001086
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001087 fout = util::make_unique<io::FileOutputStream>(out_path);
1088 if (fout->HadError()) {
1089 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1090 << "': " << fout->GetError());
1091 return false;
1092 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 }
1094
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001095 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001096 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001097 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1098 if (fout_text->HadError()) {
1099 context_->GetDiagnostics()->Error(DiagMessage()
1100 << "failed writing to '" << out_text_symbols_path.value()
1101 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001102 return false;
1103 }
1104 }
1105
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001106 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001107 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001108 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001109 return false;
1110 }
1111
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112 return true;
1113 }
1114
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001115 bool GenerateJavaClasses() {
1116 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1117 std::vector<std::string> packages_to_callback;
1118
1119 JavaClassGeneratorOptions template_options;
1120 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1121 template_options.javadoc_annotations = options_.javadoc_annotations;
1122
1123 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1124 template_options.use_final = false;
1125 }
1126
1127 if (context_->GetPackageType() == PackageType::kSharedLib) {
1128 template_options.use_final = false;
1129 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1130 }
1131
1132 const StringPiece actual_package = context_->GetCompilationPackage();
1133 StringPiece output_package = context_->GetCompilationPackage();
1134 if (options_.custom_java_package) {
1135 // Override the output java package to the custom one.
1136 output_package = options_.custom_java_package.value();
1137 }
1138
1139 // Generate the private symbols if required.
1140 if (options_.private_symbols) {
1141 packages_to_callback.push_back(options_.private_symbols.value());
1142
1143 // If we defined a private symbols package, we only emit Public symbols
1144 // to the original package, and private and public symbols to the private package.
1145 JavaClassGeneratorOptions options = template_options;
1146 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1147 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1148 options)) {
1149 return false;
1150 }
1151 }
1152
1153 // Generate copies of the original package R class but with different package names.
1154 // This is to support non-namespaced builds.
1155 for (const std::string& extra_package : options_.extra_java_packages) {
1156 packages_to_callback.push_back(extra_package);
1157
1158 JavaClassGeneratorOptions options = template_options;
1159 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1160 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1161 return false;
1162 }
1163 }
1164
1165 // Generate R classes for each package that was merged (static library).
1166 // Use the actual package's resources only.
1167 for (const std::string& package : table_merger_->merged_packages()) {
1168 packages_to_callback.push_back(package);
1169
1170 JavaClassGeneratorOptions options = template_options;
1171 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1172 if (!WriteJavaFile(&final_table_, package, package, options)) {
1173 return false;
1174 }
1175 }
1176
1177 // Generate the main public R class.
1178 JavaClassGeneratorOptions options = template_options;
1179
1180 // Only generate public symbols if we have a private package.
1181 if (options_.private_symbols) {
1182 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1183 }
1184
1185 if (options.rewrite_callback_options) {
1186 options.rewrite_callback_options.value().packages_to_callback =
1187 std::move(packages_to_callback);
1188 }
1189
1190 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1191 options_.generate_text_symbols_path)) {
1192 return false;
1193 }
1194
1195 return true;
1196 }
1197
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001198 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1199 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001200 return true;
1201 }
1202
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001203 std::unique_ptr<ClassDefinition> manifest_class =
1204 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001205
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001206 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001207 // Something bad happened, but we already logged it, so exit.
1208 return false;
1209 }
1210
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001211 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212 // Empty Manifest class, no need to generate it.
1213 return true;
1214 }
1215
1216 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001217 for (const std::string& annotation : options_.javadoc_annotations) {
1218 std::string proper_annotation = "@";
1219 proper_annotation += annotation;
1220 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001221 }
1222
Adam Lesinski0d81f702017-06-27 15:51:09 -07001223 const std::string package_utf8 =
1224 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001225
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001226 std::string out_path = options_.generate_java_class_path.value();
1227 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001229 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001230 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1231 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001232 return false;
1233 }
1234
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001235 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001236
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001237 io::FileOutputStream fout(out_path);
1238 if (fout.HadError()) {
1239 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1240 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001241 return false;
1242 }
1243
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001244 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1245 fout.Flush();
1246
1247 if (fout.HadError()) {
1248 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1249 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001250 return false;
1251 }
1252 return true;
1253 }
1254
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001255 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001256 if (!out) {
1257 return true;
1258 }
1259
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001260 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001261 io::FileOutputStream fout(out_path);
1262 if (fout.HadError()) {
1263 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1264 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001265 return false;
1266 }
1267
Ryan Mitchell7e5236d2018-09-25 15:20:59 -07001268 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001269 fout.Flush();
1270
1271 if (fout.HadError()) {
1272 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1273 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001274 return false;
1275 }
1276 return true;
1277 }
1278
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001279 bool MergeStaticLibrary(const std::string& input, bool override) {
1280 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001281 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 }
1283
Adam Lesinski8780eb62017-10-31 17:44:39 -07001284 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1285 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001286 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001287 return false;
1288 }
1289
Adam Lesinski8780eb62017-10-31 17:44:39 -07001290 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001291 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001292 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001293 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 return false;
1295 }
1296
1297 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001298 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001299 // Merge all resources as if they were in the compilation package. This is the old behavior
1300 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001301
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001302 // Add the package to the set of --extra-packages so we emit an R.java for each library
1303 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001304 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001305 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001306 }
1307
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001308 // Clear the package name, so as to make the resources look like they are coming from the
1309 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001310 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001311 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001312
1313 } else {
1314 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001315 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001316 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001317 }
1318
1319 if (!result) {
1320 return false;
1321 }
1322
1323 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001324 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001325 return true;
1326 }
1327
Adam Lesinski2427dce2017-11-30 15:10:28 -08001328 bool MergeExportedSymbols(const Source& source,
1329 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001330 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001331 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001332 ResourceName res_name = exported_symbol.name;
1333 if (res_name.package.empty()) {
1334 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001335 }
1336
Adam Lesinski00451162017-10-03 07:44:08 -07001337 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001338 if (mangled_name) {
1339 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001340 }
1341
1342 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001343 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001344 bool result =
1345 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1346 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001347 if (!result) {
1348 return false;
1349 }
1350 }
1351 return true;
1352 }
1353
Adam Lesinski2427dce2017-11-30 15:10:28 -08001354 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1355 if (context_->IsVerbose()) {
1356 context_->GetDiagnostics()->Note(DiagMessage()
1357 << "merging '" << compiled_file.name
1358 << "' from compiled file " << compiled_file.source);
1359 }
1360
1361 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1362 return false;
1363 }
1364 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1365 }
1366
Adam Lesinski00451162017-10-03 07:44:08 -07001367 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1368 // If override is true, conflicting resources are allowed to override each other, in order of last
1369 // seen.
1370 // An io::IFileCollection is created from the ZIP file and added to the set of
1371 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001372 bool MergeArchive(const std::string& input, bool override) {
1373 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001374 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001375 }
1376
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001377 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001378 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001379 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001380 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001381 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382 return false;
1383 }
1384
1385 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001386 for (auto iter = collection->Iterator(); iter->HasNext();) {
1387 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001388 error = true;
1389 }
1390 }
1391
1392 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001393 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001394 return !error;
1395 }
1396
Adam Lesinski00451162017-10-03 07:44:08 -07001397 // Takes a path to load and merge into the master ResourceTable. If override is true,
1398 // conflicting resources are allowed to override each other, in order of last seen.
1399 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1400 // as ZIP archive and the files within are merged individually.
1401 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001402 bool MergePath(const std::string& path, bool override) {
1403 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1404 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1405 return MergeArchive(path, override);
1406 } else if (util::EndsWith(path, ".apk")) {
1407 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001408 }
1409
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 io::IFile* file = file_collection_->InsertFile(path);
1411 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001412 }
1413
Adam Lesinski00451162017-10-03 07:44:08 -07001414 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1415 // If override is true, conflicting resources are allowed to override each other, in order of last
1416 // seen.
1417 // All other file types are ignored. This is because these files could be coming from a zip,
1418 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 bool MergeFile(io::IFile* file, bool override) {
1420 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001421
Adam Lesinski00451162017-10-03 07:44:08 -07001422 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001423 // Since AAPT compiles these file types and appends .flat to them, seeing
1424 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001425 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1426 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1427 << " file passed as argument. Must be "
1428 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001429 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001430 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1431 if (context_->IsVerbose()) {
1432 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1433 return true;
1434 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001435 }
1436
Adam Lesinski00451162017-10-03 07:44:08 -07001437 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1438 if (input_stream == nullptr) {
1439 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1440 return false;
1441 }
1442
1443 if (input_stream->HadError()) {
1444 context_->GetDiagnostics()->Error(DiagMessage(src)
1445 << "failed to open file: " << input_stream->GetError());
1446 return false;
1447 }
1448
1449 ContainerReaderEntry* entry;
1450 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001451
1452 if (reader.HadError()) {
1453 context_->GetDiagnostics()->Error(DiagMessage(src)
1454 << "failed to read file: " << reader.GetError());
1455 return false;
1456 }
1457
Adam Lesinski00451162017-10-03 07:44:08 -07001458 while ((entry = reader.Next()) != nullptr) {
1459 if (entry->Type() == ContainerEntryType::kResTable) {
1460 pb::ResourceTable pb_table;
1461 if (!entry->GetResTable(&pb_table)) {
1462 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1463 << entry->GetError());
1464 return false;
1465 }
1466
1467 ResourceTable table;
1468 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001469 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001470 context_->GetDiagnostics()->Error(DiagMessage(src)
1471 << "failed to deserialize resource table: " << error);
1472 return false;
1473 }
1474
1475 if (!table_merger_->Merge(src, &table, override)) {
1476 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1477 return false;
1478 }
1479 } else if (entry->Type() == ContainerEntryType::kResFile) {
1480 pb::internal::CompiledFile pb_compiled_file;
1481 off64_t offset;
1482 size_t len;
1483 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1484 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1485 << entry->GetError());
1486 return false;
1487 }
1488
1489 ResourceFile resource_file;
1490 std::string error;
1491 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1492 context_->GetDiagnostics()->Error(DiagMessage(src)
1493 << "failed to read compiled header: " << error);
1494 return false;
1495 }
1496
1497 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1498 return false;
1499 }
1500 }
1501 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001502 return true;
1503 }
1504
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001505 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1506 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1507 for (const std::string& assets_dir : options_.assets_dirs) {
1508 Maybe<std::vector<std::string>> files =
1509 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1510 if (!files) {
1511 return false;
1512 }
1513
1514 for (const std::string& file : files.value()) {
1515 std::string full_key = "assets/" + file;
1516 std::string full_path = assets_dir;
1517 file::AppendPath(&full_path, file);
1518
1519 auto iter = merged_assets.find(full_key);
1520 if (iter == merged_assets.end()) {
1521 merged_assets.emplace(std::move(full_key),
1522 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1523 } else if (context_->IsVerbose()) {
1524 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1525 << "asset file overrides '" << full_path << "'");
1526 }
1527 }
1528 }
1529
1530 for (auto& entry : merged_assets) {
1531 uint32_t compression_flags = ArchiveEntry::kCompress;
1532 std::string extension = file::GetExtension(entry.first).to_string();
1533 if (options_.extensions_to_not_compress.count(extension) > 0) {
1534 compression_flags = 0u;
1535 }
1536
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001537 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1538 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001539 return false;
1540 }
1541 }
1542 return true;
1543 }
1544
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001545 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1546 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001547 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1548 ResourceTable* table) {
Ryan Mitchell479fa392019-01-02 17:15:39 -08001549 const bool keep_raw_values = (context_->GetPackageType() == PackageType::kStaticLib)
1550 || options_.keep_raw_values;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001551 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001552 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001553 if (!result) {
1554 return false;
1555 }
1556
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001557 ResourceFileFlattenerOptions file_flattener_options;
1558 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001559 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1560 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001561 file_flattener_options.no_auto_version = options_.no_auto_version;
1562 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001563 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001564 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1565 file_flattener_options.update_proguard_spec =
1566 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001567 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001569 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001570
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001571 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001572 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001573 return false;
1574 }
1575
Adam Lesinski490595a2017-11-07 17:08:07 -08001576 // Hack to fix b/68820737.
1577 // We need to modify the ResourceTable's package name, but that should NOT affect
1578 // anything else being generated, which includes the Java classes.
1579 // If required, the package name is modifed before flattening, and then modified back
1580 // to its original name.
1581 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001582 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1583 // or higher] as invalid. In order to work around this limitation, we allow the use
1584 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1585 // definition of what a valid "split" package ID is to account for this.
1586 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1587 context_->GetPackageId() != kAppPackageId &&
1588 context_->GetPackageId() != kFrameworkPackageId)
1589 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1590 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001591 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1592 // The base APK is included, and this is a feature split. If the base package is
1593 // the same as this package, then we are building an old style Android Instant Apps feature
1594 // split and must apply this workaround to avoid requiring namespaces support.
1595 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1596 if (package_to_rewrite != nullptr) {
1597 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1598
1599 std::string new_package_name =
1600 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1601 app_info_.split_name.value_or_default("feature").c_str());
1602
1603 if (context_->IsVerbose()) {
1604 context_->GetDiagnostics()->Note(
1605 DiagMessage() << "rewriting resource package name for feature split to '"
1606 << new_package_name << "'");
1607 }
1608 package_to_rewrite->name = new_package_name;
1609 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001611
1612 bool success = FlattenTable(table, options_.output_format, writer);
1613
1614 if (package_to_rewrite != nullptr) {
1615 // Change the name back.
1616 package_to_rewrite->name = context_->GetCompilationPackage();
1617 if (package_to_rewrite->id) {
1618 table->included_packages_.erase(package_to_rewrite->id.value());
1619 }
1620 }
1621
1622 if (!success) {
1623 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1624 }
1625 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001626 }
1627
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001628 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001629 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001630 std::unique_ptr<xml::XmlResource> manifest_xml =
1631 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1632 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001633 return 1;
1634 }
1635
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001636 // First extract the Package name without modifying it (via --rename-manifest-package).
1637 if (Maybe<AppInfo> maybe_app_info =
1638 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001639 const AppInfo& app_info = maybe_app_info.value();
1640 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001641 }
1642
Adam Lesinskic6284372017-12-04 13:46:23 -08001643 // Now that the compilation package is set, load the dependencies. This will also extract
1644 // the Android framework's versionCode and versionName, if they exist.
1645 if (!LoadSymbolsFromIncludePaths()) {
1646 return 1;
1647 }
1648
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001649 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1650 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001651 return 1;
1652 }
1653
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001654 Maybe<AppInfo> maybe_app_info =
1655 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001657 return 1;
1658 }
1659
Adam Lesinski490595a2017-11-07 17:08:07 -08001660 app_info_ = maybe_app_info.value();
1661 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001662
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001663 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001664
1665 // Override the package ID when it is "android".
1666 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001667 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001668
1669 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001670 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001671 context_->GetDiagnostics()->Error(
1672 DiagMessage() << "package 'android' can only be built as a regular app");
1673 return 1;
1674 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001675 }
1676
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001677 TableMergerOptions table_merger_options;
1678 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001679 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001680 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001682 if (context_->IsVerbose()) {
1683 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001684 << StringPrintf("linking package '%s' using package ID %02x",
1685 context_->GetCompilationPackage().data(),
1686 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001687 }
1688
Adam Lesinski2427dce2017-11-30 15:10:28 -08001689 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1690 // in res/**/*.
1691 {
1692 XmlIdCollector collector;
1693 if (!collector.Consume(context_, manifest_xml.get())) {
1694 return false;
1695 }
1696
1697 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1698 return false;
1699 }
1700 }
1701
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001702 for (const std::string& input : input_files) {
1703 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001704 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001705 return 1;
1706 }
1707 }
1708
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 for (const std::string& input : options_.overlay_files) {
1710 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001711 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 return 1;
1713 }
1714 }
1715
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001717 return 1;
1718 }
1719
Adam Lesinskib522f042017-04-21 16:57:59 -07001720 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001721 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001722 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001723 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001724 return 1;
1725 }
1726
1727 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001728 IdAssigner id_assigner(&options_.stable_id_map);
1729 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001730 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 return 1;
1732 }
1733
1734 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 if (options_.resource_id_map_path) {
1736 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001737 for (auto& type : package->types) {
1738 for (auto& entry : type->entries) {
1739 ResourceName name(package->name, type->type, entry->name);
1740 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001741 options_.stable_id_map[std::move(name)] =
1742 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001743 }
1744 }
1745 }
1746
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001747 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001749 return 1;
1750 }
1751 }
1752 } else {
1753 // Static libs are merged with other apps, and ID collisions are bad, so
1754 // verify that
1755 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 return 1;
1758 }
1759 }
1760
1761 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001762 context_->SetNameManglerPolicy(
1763 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764
1765 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001766 context_->GetExternalSymbols()->PrependSource(
1767 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001768
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001769 // Workaround for pre-O runtime that would treat negative resource IDs
1770 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1771 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1772 // are just identifiers.
1773 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1774 if (context_->IsVerbose()) {
1775 context_->GetDiagnostics()->Note(DiagMessage()
1776 << "enabling pre-O feature split ID rewriting");
1777 }
1778 context_->GetExternalSymbols()->SetDelegate(
1779 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1780 }
1781
Adam Lesinski34a16872018-02-23 16:18:10 -08001782 // Before we process anything, remove the resources whose default values don't exist.
1783 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001784 if (!options_.no_resource_removal) {
1785 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1786 context_->GetDiagnostics()->Error(DiagMessage()
1787 << "failed removing resources with no defaults");
1788 return 1;
1789 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001790 }
1791
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001793 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001794 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 return 1;
1796 }
1797
Adam Lesinskib522f042017-04-21 16:57:59 -07001798 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001799 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001800 context_->GetDiagnostics()->Warn(DiagMessage()
1801 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 }
1803 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001804 ProductFilter product_filter(options_.products);
1805 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001806 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001807 return 1;
1808 }
1809 }
1810
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001811 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001812 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001813 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001814 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001815 return 1;
1816 }
1817 }
1818
Adam Lesinskib522f042017-04-21 16:57:59 -07001819 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001820 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001821 context_->GetDiagnostics()->Note(DiagMessage()
1822 << "collapsing resource versions for minimum SDK "
1823 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824 }
1825
1826 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001828 return 1;
1829 }
1830 }
1831
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001834 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001835 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001836 return 1;
1837 }
1838 }
1839
Adam Koskidc21dea2017-07-21 10:55:27 -07001840 proguard::KeepSet proguard_keep_set =
1841 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001842 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001843
Adam Lesinskib522f042017-04-21 16:57:59 -07001844 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001845 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001846 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001847 context_->GetDiagnostics()->Warn(DiagMessage()
1848 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 }
1850 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001851 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1852 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001853 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001854 options_.split_constraints =
1855 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001856
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001857 if (origConstraintSize != options_.split_constraints.size()) {
1858 context_->GetDiagnostics()->Warn(DiagMessage()
1859 << "requested to split resources prior to min sdk of "
1860 << context_->GetMinSdkVersion());
1861 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001862 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001863 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001864 return 1;
1865 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001866 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001867
1868 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001870 auto split_constraints_iter = options_.split_constraints.begin();
1871 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001872 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001873 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1874 << "generating split with configurations '"
1875 << util::Joiner(split_constraints_iter->configs, ", ")
1876 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001877 }
1878
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001879 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001880 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001881 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001882 return 1;
1883 }
1884
1885 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001886 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001887 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001888
1889 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001890 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001891 context_->GetDiagnostics()->Error(DiagMessage()
1892 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001893 return 1;
1894 }
1895
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001896 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1897 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001898 return 1;
1899 }
1900
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001901 ++path_iter;
1902 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001903 }
1904 }
1905
1906 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001907 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001908 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001909 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001910 return 1;
1911 }
1912
1913 bool error = false;
1914 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001915 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001916 // (aka, which package the AndroidManifest.xml is coming from).
1917 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001919
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 XmlReferenceLinker manifest_linker;
1921 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1922 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001923 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001924 error = true;
1925 }
1926
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001928 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001929 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001930 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001931 }
1932
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 if (options_.generate_java_class_path) {
1934 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001935 error = true;
1936 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001937 }
1938
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001939 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001940 // PackageParser will fail if URIs are removed from
1941 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001942 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1943 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001944 error = true;
1945 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001946 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001947 } else {
1948 error = true;
1949 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001950 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001951
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001953 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001954 return 1;
1955 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001956
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001957 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1958 return 1;
1959 }
1960
1961 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001962 return 1;
1963 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001964
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001965 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001966 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001967 return 1;
1968 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001969 }
1970
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001971 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001972 return 1;
1973 }
1974
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1976 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001977 return 1;
1978 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001979 return 0;
1980 }
1981
1982 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001983 LinkOptions options_;
1984 LinkContext* context_;
1985 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986
Adam Lesinski490595a2017-11-07 17:08:07 -08001987 AppInfo app_info_;
1988
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001989 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001990
1991 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001992 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993
Adam Lesinski8780eb62017-10-31 17:44:39 -07001994 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001995 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001997
Adam Lesinski8780eb62017-10-31 17:44:39 -07001998 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1999 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
2000
2001 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2002 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002003
2004 // The set of shared libraries being used, mapping their assigned package ID to package name.
2005 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002006
2007 // The package name of the base application, if it is included.
2008 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002009};
2010
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002011int LinkCommand::Action(const std::vector<std::string>& args) {
2012 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002013
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002014 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002016 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002018 const std::string path = arg.substr(1, arg.size() - 1);
2019 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002020 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2021 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002022 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002023 }
2024 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002025 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002026 }
2027 }
2028
2029 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002030 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002031 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002032 const std::string path = arg.substr(1, arg.size() - 1);
2033 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002034 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002035 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002036 return 1;
2037 }
2038 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002039 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002040 }
2041 }
2042
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002043 if (verbose_) {
2044 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002045 }
2046
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002047 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002048 context.GetDiagnostics()->Error(
2049 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002050 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002051 return 1;
2052 }
2053
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002054 // The default build type.
2055 context.SetPackageType(PackageType::kApp);
2056 context.SetPackageId(kAppPackageId);
2057
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002058 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002059 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002060 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002061 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002062 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002063 options_.output_format = OutputFormat::kProto;
2064 } else if (proto_format_) {
2065 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002066 }
2067
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002068 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002069 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002070 context.GetDiagnostics()->Error(
2071 DiagMessage() << "can't specify --package-id when not building a regular app");
2072 return 1;
2073 }
2074
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002075 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002076 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002077 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002078 << "' is not a valid integer");
2079 return 1;
2080 }
2081
2082 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002083 if (package_id_int > std::numeric_limits<uint8_t>::max()
2084 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002085 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002086 context.GetDiagnostics()->Error(
2087 DiagMessage() << StringPrintf(
2088 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2089 return 1;
2090 }
2091 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2092 }
2093
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002095 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002097 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002098 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099 }
2100 }
2101
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002102 if (product_list_) {
2103 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002105 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002106 }
2107 }
2108 }
2109
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002110 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002111 if (!configs_.empty()) {
2112 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 if (filter == nullptr) {
2114 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002115 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002116 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 }
2118
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002119 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002120 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002121 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002124 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002125 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002126 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002127
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002128 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002129 for (const std::string& split_arg : split_args_) {
2130 options_.split_paths.push_back({});
2131 options_.split_constraints.push_back({});
2132 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2133 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002134 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002135 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002136 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002137
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002138 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2139 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2140 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002142 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002143 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002144
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002146 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002147 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002148 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2149 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2150 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002151
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002152 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002153 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002154 options_.no_auto_version = true;
2155 options_.no_version_vectors = true;
2156 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002157 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002158
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002159 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002160 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002161}
2162
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002163} // namespace aapt