blob: 1b5601d451a73a3c105f53d1cec2de375e88f6bb [file] [log] [blame]
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Link.h"
18
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019#include <sys/stat.h>
Adam Lesinskic6284372017-12-04 13:46:23 -080020#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070021
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050022#include <algorithm>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070023#include <queue>
24#include <unordered_map>
25#include <vector>
26
27#include "android-base/errors.h"
28#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080029#include "android-base/stringprintf.h"
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020030#include "androidfw/Locale.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080031#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070032
Adam Lesinski1ab598f2015-08-14 14:26:04 -070033#include "AppInfo.h"
34#include "Debug.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070035#include "LoadedApk.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070036#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080037#include "ResourceUtils.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070038#include "ResourceValues.h"
39#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070041#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080042#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080043#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070045#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070046#include "format/binary/TableFlattener.h"
47#include "format/binary/XmlFlattener.h"
48#include "format/proto/ProtoDeserialize.h"
49#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070050#include "io/BigBufferStream.h"
51#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070053#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080054#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070055#include "java/JavaClassGenerator.h"
56#include "java/ManifestClassGenerator.h"
57#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070058#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070059#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080060#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080061#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070063#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080064#include "optimize/ResourceDeduper.h"
65#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070066#include "process/IResourceTableConsumer.h"
67#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080068#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080070#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070071
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070072using ::aapt::io::FileInputStream;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020073using ::android::ConfigDescription;
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070074using ::android::StringPiece;
75using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070076
Adam Lesinski1ab598f2015-08-14 14:26:04 -070077namespace aapt {
78
Adam Lesinski64587af2016-02-18 18:33:06 -080079class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -070080 public:
Chris Warrington820d72a2017-04-27 15:27:01 +010081 LinkContext(IDiagnostics* diagnostics)
82 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -070083 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070084
Adam Lesinskib522f042017-04-21 16:57:59 -070085 PackageType GetPackageType() override {
86 return package_type_;
87 }
88
89 void SetPackageType(PackageType type) {
90 package_type_ = type;
91 }
92
Adam Lesinskid0f492d2017-04-03 18:12:45 -070093 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +010094 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070095 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -070096
Adam Lesinskid0f492d2017-04-03 18:12:45 -070097 NameMangler* GetNameMangler() override {
98 return &name_mangler_;
99 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700100
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
102 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700103 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800104
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700105 const std::string& GetCompilationPackage() override {
106 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700108
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700109 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800110 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700111 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800112
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700113 uint8_t GetPackageId() override {
114 return package_id_;
115 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700116
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700117 void SetPackageId(uint8_t id) {
118 package_id_ = id;
119 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800120
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700121 SymbolTable* GetExternalSymbols() override {
122 return &symbols_;
123 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800124
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700125 bool IsVerbose() override {
126 return verbose_;
127 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800128
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700129 void SetVerbose(bool val) {
130 verbose_ = val;
131 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800132
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700133 int GetMinSdkVersion() override {
134 return min_sdk_version_;
135 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700136
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700137 void SetMinSdkVersion(int minSdk) {
138 min_sdk_version_ = minSdk;
139 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700140
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700141 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700142 DISALLOW_COPY_AND_ASSIGN(LinkContext);
143
Adam Lesinskib522f042017-04-21 16:57:59 -0700144 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100145 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700146 NameMangler name_mangler_;
147 std::string compilation_package_;
148 uint8_t package_id_ = 0x0;
149 SymbolTable symbols_;
150 bool verbose_ = false;
151 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700152};
153
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700154// A custom delegate that generates compatible pre-O IDs for use with feature splits.
155// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
156// is interpreted as a negative number. Some verification was wrongly assuming negative values
157// were invalid.
158//
159// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
160// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
161// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800162//
163// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700164class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
165 public:
166 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
167 }
168
169 virtual ~FeatureSplitSymbolTableDelegate() = default;
170
171 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
172 const ResourceName& name,
173 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
174 std::unique_ptr<SymbolTable::Symbol> symbol =
175 DefaultSymbolTableDelegate::FindByName(name, sources);
176 if (symbol == nullptr) {
177 return {};
178 }
179
180 // Check to see if this is an 'id' with the target package.
181 if (name.type == ResourceType::kId && symbol->id) {
182 ResourceId* id = &symbol->id.value();
183 if (id->package_id() > kAppPackageId) {
184 // Rewrite the resource ID to be compatible pre-O.
185 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
186
187 // Check that this doesn't overlap another resource.
188 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
189 // The ID overlaps, so log a message (since this is a weird failure) and fail.
190 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
191 << " for pre-O feature split support");
192 return {};
193 }
194
195 if (context_->IsVerbose()) {
196 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
197 << ") -> (" << rewritten_id << ")");
198 }
199
200 *id = rewritten_id;
201 }
202 }
203 return symbol;
204 }
205
206 private:
207 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
208
209 IAaptContext* context_;
210};
211
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700212static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
213 const StringPiece& path, bool keep_raw_values, bool utf16,
214 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700215 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700216 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
217 << (keep_raw_values ? "true" : "false")
218 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700219 }
220
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700221 switch (format) {
222 case OutputFormat::kApk: {
223 BigBuffer buffer(1024);
224 XmlFlattenerOptions options = {};
225 options.keep_raw_values = keep_raw_values;
226 options.use_utf16 = utf16;
227 XmlFlattener flattener(&buffer, options);
228 if (!flattener.Consume(context, &xml_res)) {
229 return false;
230 }
231
232 io::BigBufferInputStream input_stream(&buffer);
233 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
234 ArchiveEntry::kCompress, writer);
235 } break;
236
237 case OutputFormat::kProto: {
238 pb::XmlNode pb_node;
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" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000402 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700403}
404
Adam Lesinskic744ae82017-05-17 19:28:38 -0700405template <typename T>
406std::vector<T> make_singleton_vec(T&& val) {
407 std::vector<T> vec;
408 vec.emplace_back(std::forward<T>(val));
409 return vec;
410}
411
412std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
413 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700414 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700415 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700416
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700417 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700418 context_->GetDiagnostics()->Note(DiagMessage()
419 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700420 }
421
Adam Lesinski00451162017-10-03 07:44:08 -0700422 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
423 // that existing projects have out-of-date references which pass compilation.
424 xml::StripAndroidStudioAttributes(doc->root.get());
425
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700426 XmlReferenceLinker xml_linker;
427 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700428 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700429 }
430
Ryan Mitchell9a2f6e62018-05-23 14:23:18 -0700431 if (options_.update_proguard_spec && !proguard::CollectProguardRules(context_, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700432 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 }
434
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700435 if (options_.no_xml_namespaces) {
436 XmlNamespaceRemover namespace_remover;
437 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700438 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800439 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800441
Adam Lesinskibb94f322017-07-12 07:41:55 -0700442 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700443 return make_singleton_vec(std::move(file_op->xml_to_flatten));
444 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700445
Adam Lesinskibb94f322017-07-12 07:41:55 -0700446 if (options_.no_version_vectors || options_.no_version_transitions) {
447 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700448 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700449 if (el && el->namespace_uri.empty()) {
450 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
451 (options_.no_version_transitions && IsTransitionElement(el->name))) {
452 return make_singleton_vec(std::move(file_op->xml_to_flatten));
453 }
454 }
455 }
456
Adam Lesinskic744ae82017-05-17 19:28:38 -0700457 const ConfigDescription& config = file_op->config;
458 ResourceEntry* entry = file_op->entry;
459
460 XmlCompatVersioner xml_compat_versioner(&rules_);
461 const util::Range<ApiVersion> api_range{config.sdkVersion,
462 FindNextApiVersionForConfig(entry, config)};
463 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800464}
465
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800466ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
467 switch (format) {
468 case OutputFormat::kApk:
469 return ResourceFile::Type::kBinaryXml;
470 case OutputFormat::kProto:
471 return ResourceFile::Type::kProtoXml;
472 }
473 LOG_ALWAYS_FATAL("unreachable");
474 return ResourceFile::Type::kUnknown;
475}
476
Ryan Mitchell70f79722018-08-13 07:37:24 -0700477static auto kDrawableVersions = std::map<std::string, ApiVersion>{
478 { "adaptive-icon" , SDK_O },
479};
480
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700481bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700482 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700483 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800484
Adam Koskidc21dea2017-07-21 10:55:27 -0700485 proguard::CollectResourceReferences(context_, table, keep_set_);
486
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700487 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700488 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
489
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700490 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700491 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700492 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700493 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800494
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700495 // Populate the queue with all files in the ResourceTable.
496 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700497 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700498 // WARNING! Do not insert or remove any resources while executing in this scope. It will
499 // corrupt the iteration order.
500
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700501 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700502 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700503 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700505
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700506 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700507 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700508 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700509 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700510 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700511 }
512
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700513 FileOperation file_op;
514 file_op.entry = entry.get();
515 file_op.dst_path = *file_ref->path;
516 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700517 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700518
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700519 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700520 (file_ref->type == ResourceFile::Type::kBinaryXml ||
521 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700522 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700523 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700524 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700525 << "failed to open file");
526 return false;
527 }
528
Adam Lesinski00451162017-10-03 07:44:08 -0700529 if (file_ref->type == ResourceFile::Type::kProtoXml) {
530 pb::XmlNode pb_xml_node;
531 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
532 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700533 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700534 return false;
535 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700536
Adam Lesinski00451162017-10-03 07:44:08 -0700537 std::string error;
538 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
539 if (file_op.xml_to_flatten == nullptr) {
540 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700541 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700542 return false;
543 }
544 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700545 std::string error_str;
546 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700547 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700548 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
549 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700550 return false;
551 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 }
553
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800554 // Update the type that this file will be written as.
555 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
556
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700557 file_op.xml_to_flatten->file.config = config_value->config;
558 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700559 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700560 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700561
562 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
563 // else we end up copying the string in the std::make_pair() method,
564 // then creating a StringPiece from the copy, which would cause us
565 // to end up referencing garbage in the map.
566 const StringPiece entry_name(entry->name);
567 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
568 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 }
570 }
571
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700572 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700573 for (auto& map_entry : config_sorted_files) {
574 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700575 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700576
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700577 if (file_op.xml_to_flatten) {
Ryan Mitchell70f79722018-08-13 07:37:24 -0700578 // Check minimum sdk versions supported for drawables
579 auto drawable_entry = kDrawableVersions.find(file_op.xml_to_flatten->root->name);
580 if (drawable_entry != kDrawableVersions.end()) {
581 if (drawable_entry->second > context_->GetMinSdkVersion()
582 && drawable_entry->second > config.sdkVersion) {
583 context_->GetDiagnostics()->Error(DiagMessage(file_op.xml_to_flatten->file.source)
584 << "<" << drawable_entry->first << "> elements "
585 << "require a sdk version of at least "
586 << (int16_t) drawable_entry->second);
587 error = true;
588 continue;
589 }
590 }
591
Adam Lesinskic744ae82017-05-17 19:28:38 -0700592 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
593 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700594 if (versioned_docs.empty()) {
595 error = true;
596 continue;
597 }
598
Adam Lesinskic744ae82017-05-17 19:28:38 -0700599 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
600 std::string dst_path = file_op.dst_path;
601 if (doc->file.config != file_op.config) {
602 // Only add the new versioned configurations.
603 if (context_->IsVerbose()) {
604 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
605 << "auto-versioning resource from config '"
606 << config << "' -> '" << doc->file.config << "'");
607 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800609 const ResourceFile& file = doc->file;
610 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
611
612 std::unique_ptr<FileReference> file_ref =
613 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
614 file_ref->SetSource(doc->file.source);
615 // Update the output format of this XML file.
616 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
617 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
618 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700619 return false;
620 }
621 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700622
623 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
624 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700625 }
626 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700627 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
628 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700629 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700630 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700631 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632 }
633 return !error;
634}
635
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700636static bool WriteStableIdMapToPath(IDiagnostics* diag,
637 const std::unordered_map<ResourceName, ResourceId>& id_map,
638 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800639 io::FileOutputStream fout(id_map_path);
640 if (fout.HadError()) {
641 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642 return false;
643 }
644
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800645 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700646 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700647 const ResourceName& name = entry.first;
648 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800649 printer.Print(name.to_string());
650 printer.Print(" = ");
651 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700652 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800653 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700654
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800655 if (fout.HadError()) {
656 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700657 return false;
658 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 return true;
660}
661
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700662static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
663 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700665 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700666 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 return false;
668 }
669
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700670 out_id_map->clear();
671 size_t line_no = 0;
672 for (StringPiece line : util::Tokenize(content, '\n')) {
673 line_no++;
674 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700675 if (line.empty()) {
676 continue;
677 }
678
679 auto iter = std::find(line.begin(), line.end(), '=');
680 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700681 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 return false;
683 }
684
685 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700686 StringPiece res_name_str =
687 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
688 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700689 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
690 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 return false;
692 }
693
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700694 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
695 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700696 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700697
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700698 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
699 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700700 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
701 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700702 return false;
703 }
704
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700705 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700706 }
707 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700708}
709
Adam Lesinskic6284372017-12-04 13:46:23 -0800710static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
711 using namespace android;
712
713 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
714 // we're looking for the first attribute resource in the system package.
715 const ResTable& table = assets.getResources(true);
716 Res_value val;
717 ssize_t idx = table.getResource(0x01010000, &val, true);
718 if (idx != NO_ERROR) {
719 // Try as a bag.
720 const ResTable::bag_entry* entry;
721 ssize_t cnt = table.lockBag(0x01010000, &entry);
722 if (cnt >= 0) {
723 idx = entry->stringBlock;
724 }
725 table.unlockBag(entry);
726 }
727
728 if (idx < 0) {
729 return 0;
730 }
731 return table.getTableCookie(idx);
732}
733
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700734class Linker {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700736 Linker(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700737 : options_(options),
738 context_(context),
739 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700740 file_collection_(util::make_unique<io::FileCollection>()) {
741 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700742
Adam Lesinskic6284372017-12-04 13:46:23 -0800743 void ExtractCompileSdkVersions(android::AssetManager* assets) {
744 using namespace android;
745
746 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
747 if (cookie == 0) {
748 // No Framework assets loaded. Not a failure.
749 return;
750 }
751
752 std::unique_ptr<Asset> manifest(
753 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
754 if (manifest == nullptr) {
755 // No errors.
756 return;
757 }
758
759 std::string error;
760 std::unique_ptr<xml::XmlResource> manifest_xml =
761 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
762 if (manifest_xml == nullptr) {
763 // No errors.
764 return;
765 }
766
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700767 if (!options_.manifest_fixer_options.compile_sdk_version) {
768 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
769 if (attr != nullptr) {
770 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
771 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
772 switch (prim->value.dataType) {
773 case Res_value::TYPE_INT_DEC:
774 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
775 break;
776 case Res_value::TYPE_INT_HEX:
777 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
778 break;
779 default:
780 break;
781 }
782 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
783 compile_sdk_version = *str->value;
784 } else {
785 compile_sdk_version = attr->value;
Adam Lesinskic6284372017-12-04 13:46:23 -0800786 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800787 }
788 }
789
Todd Kennedy9f6dec12018-04-20 12:29:29 -0700790 if (!options_.manifest_fixer_options.compile_sdk_version_codename) {
791 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
792 if (attr != nullptr) {
793 Maybe<std::string>& compile_sdk_version_codename =
794 options_.manifest_fixer_options.compile_sdk_version_codename;
795 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
796 compile_sdk_version_codename = *str->value;
797 } else {
798 compile_sdk_version_codename = attr->value;
799 }
Adam Lesinskic6284372017-12-04 13:46:23 -0800800 }
801 }
802 }
803
Adam Lesinski8780eb62017-10-31 17:44:39 -0700804 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800805 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700806 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700807 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700808 for (const std::string& path : options_.include_paths) {
809 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700810 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700811 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700812
Adam Lesinski8780eb62017-10-31 17:44:39 -0700813 std::string error;
814 auto zip_collection = io::ZipFileCollection::Create(path, &error);
815 if (zip_collection == nullptr) {
816 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
817 return false;
818 }
819
820 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
821 // Load this as a static library include.
822 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
823 Source(path), std::move(zip_collection), context_->GetDiagnostics());
824 if (static_apk == nullptr) {
825 return false;
826 }
827
Adam Lesinskib522f042017-04-21 16:57:59 -0700828 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800829 // Can't include static libraries when not building a static library (they have no IDs
830 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700831 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800832 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700833 return false;
834 }
835
Adam Lesinski8780eb62017-10-31 17:44:39 -0700836 ResourceTable* table = static_apk->GetResourceTable();
837
838 // If we are using --no-static-lib-packages, we need to rename the package of this table to
839 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700840 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800841 // Since package names can differ, and multiple packages can exist in a ResourceTable,
842 // we place the requirement that all static libraries are built with the package
843 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700844 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700845 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800846 } else {
847 context_->GetDiagnostics()->Error(DiagMessage(path)
848 << "no package with ID 0x7f found in static library");
849 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700850 }
851 }
852
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700853 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700854 util::make_unique<ResourceTableSymbolSource>(table));
855 static_library_includes_.push_back(std::move(static_apk));
856 } else {
857 if (!asset_source->AddAssetPath(path)) {
858 context_->GetDiagnostics()->Error(DiagMessage()
859 << "failed to load include path " << path);
860 return false;
861 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700862 }
863 }
864
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800865 // Capture the shared libraries so that the final resource table can be properly flattened
866 // with support for shared libraries.
867 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Todd Kennedy32512992018-04-25 16:45:59 -0700868 if (entry.first == kAppPackageId) {
Adam Lesinski490595a2017-11-07 17:08:07 -0800869 // Capture the included base feature package.
870 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800871 } else if (entry.first == kFrameworkPackageId) {
872 // Try to embed which version of the framework we're compiling against.
873 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
874 // when linking our synthesized 'android:compileSdkVersion' attribute.
875 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
876 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
877 if (symbol != nullptr && symbol->is_public) {
878 // The symbol is present and public, extract the android:versionName and
879 // android:versionCode from the framework AndroidManifest.xml.
880 ExtractCompileSdkVersions(asset_source->GetAssetManager());
881 }
Todd Kennedy32512992018-04-25 16:45:59 -0700882 } else if (asset_source->IsPackageDynamic(entry.first)) {
883 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800884 }
885 }
886
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700887 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700888 return true;
889 }
890
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800891 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800893 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
894 if (manifest_el == nullptr) {
895 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700896 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800897
898 AppInfo app_info;
899
900 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
901 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
902 return {};
903 }
904
905 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
906 if (!package_attr) {
907 diag->Error(DiagMessage(xml_res->file.source)
908 << "<manifest> must have a 'package' attribute");
909 return {};
910 }
911 app_info.package = package_attr->value;
912
913 if (xml::Attribute* version_code_attr =
914 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
915 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
916 if (!maybe_code) {
917 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
918 << "invalid android:versionCode '" << version_code_attr->value << "'");
919 return {};
920 }
921 app_info.version_code = maybe_code.value();
922 }
923
Ryan Mitchell5fa2bb12018-07-12 11:24:51 -0700924 if (xml::Attribute* version_code_major_attr =
925 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
926 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_major_attr->value);
927 if (!maybe_code) {
928 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
929 << "invalid android:versionCodeMajor '"
930 << version_code_major_attr->value << "'");
931 return {};
932 }
933 app_info.version_code_major = maybe_code.value();
934 }
935
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800936 if (xml::Attribute* revision_code_attr =
937 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
938 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
939 if (!maybe_code) {
940 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
941 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
942 return {};
943 }
944 app_info.revision_code = maybe_code.value();
945 }
946
947 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
948 if (!split_name_attr->value.empty()) {
949 app_info.split_name = split_name_attr->value;
950 }
951 }
952
953 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
954 if (xml::Attribute* min_sdk =
955 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700956 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800957 }
958 }
959 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700960 }
961
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700962 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
963 // Postcondition: ResourceTable has only one package left. All others are
964 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700965 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700966 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700967 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
968 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700969 };
970
971 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700972 for (const auto& package : final_table_.packages) {
973 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700974 // We have a package that is not related to the one we're building!
975 for (const auto& type : package->types) {
976 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700977 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700979 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700980 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700981 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700982 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
983 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
984 << "generated id '" << res_name
985 << "' for external package '" << package->name
986 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700988 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
989 << "defined resource '" << res_name
990 << "' for external package '" << package->name
991 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700992 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700993 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700994 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700995 }
996 }
997 }
998 }
999
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001000 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1001 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001002 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001003 return !error;
1004 }
1005
1006 /**
1007 * Returns true if no IDs have been set, false otherwise.
1008 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 bool VerifyNoIdsSet() {
1010 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 for (const auto& type : package->types) {
1012 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001013 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1014 << StringPrintf("%02x", type->id.value())
1015 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001017 }
1018
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001019 for (const auto& entry : type->entries) {
1020 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001021 ResourceNameRef res_name(package->name, type->type, entry->name);
1022 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001023 DiagMessage() << "entry " << res_name << " has ID "
1024 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001025 return false;
1026 }
1027 }
1028 }
1029 }
1030 return true;
1031 }
1032
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001033 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1034 if (options_.output_to_directory) {
1035 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001036 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001037 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001038 }
1039 }
1040
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001041 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1042 switch (format) {
1043 case OutputFormat::kApk: {
1044 BigBuffer buffer(1024);
1045 TableFlattener flattener(options_.table_flattener_options, &buffer);
1046 if (!flattener.Consume(context_, table)) {
1047 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1048 return false;
1049 }
1050
1051 io::BigBufferInputStream input_stream(&buffer);
1052 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1053 ArchiveEntry::kAlign, writer);
1054 } break;
1055
1056 case OutputFormat::kProto: {
1057 pb::ResourceTable pb_table;
Ryan Mitchella15c2a82018-03-26 11:05:31 -07001058 SerializeTableToPb(*table, &pb_table, context_->GetDiagnostics());
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001059 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1060 ArchiveEntry::kCompress, writer);
1061 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001062 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001063 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001064 }
1065
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001066 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001067 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001068 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001069 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001070 return true;
1071 }
1072
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001073 std::string out_path;
1074 std::unique_ptr<io::FileOutputStream> fout;
1075 if (options_.generate_java_class_path) {
1076 out_path = options_.generate_java_class_path.value();
1077 file::AppendPath(&out_path, file::PackageToPath(out_package));
1078 if (!file::mkdirs(out_path)) {
1079 context_->GetDiagnostics()->Error(DiagMessage()
1080 << "failed to create directory '" << out_path << "'");
1081 return false;
1082 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001083
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001084 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001085
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001086 fout = util::make_unique<io::FileOutputStream>(out_path);
1087 if (fout->HadError()) {
1088 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1089 << "': " << fout->GetError());
1090 return false;
1091 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001092 }
1093
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001094 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001095 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001096 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1097 if (fout_text->HadError()) {
1098 context_->GetDiagnostics()->Error(DiagMessage()
1099 << "failed writing to '" << out_text_symbols_path.value()
1100 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001101 return false;
1102 }
1103 }
1104
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001105 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001106 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001107 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001108 return false;
1109 }
1110
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001111 return true;
1112 }
1113
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001114 bool GenerateJavaClasses() {
1115 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1116 std::vector<std::string> packages_to_callback;
1117
1118 JavaClassGeneratorOptions template_options;
1119 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1120 template_options.javadoc_annotations = options_.javadoc_annotations;
1121
1122 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1123 template_options.use_final = false;
1124 }
1125
1126 if (context_->GetPackageType() == PackageType::kSharedLib) {
1127 template_options.use_final = false;
1128 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1129 }
1130
1131 const StringPiece actual_package = context_->GetCompilationPackage();
1132 StringPiece output_package = context_->GetCompilationPackage();
1133 if (options_.custom_java_package) {
1134 // Override the output java package to the custom one.
1135 output_package = options_.custom_java_package.value();
1136 }
1137
1138 // Generate the private symbols if required.
1139 if (options_.private_symbols) {
1140 packages_to_callback.push_back(options_.private_symbols.value());
1141
1142 // If we defined a private symbols package, we only emit Public symbols
1143 // to the original package, and private and public symbols to the private package.
1144 JavaClassGeneratorOptions options = template_options;
1145 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1146 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1147 options)) {
1148 return false;
1149 }
1150 }
1151
1152 // Generate copies of the original package R class but with different package names.
1153 // This is to support non-namespaced builds.
1154 for (const std::string& extra_package : options_.extra_java_packages) {
1155 packages_to_callback.push_back(extra_package);
1156
1157 JavaClassGeneratorOptions options = template_options;
1158 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1159 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1160 return false;
1161 }
1162 }
1163
1164 // Generate R classes for each package that was merged (static library).
1165 // Use the actual package's resources only.
1166 for (const std::string& package : table_merger_->merged_packages()) {
1167 packages_to_callback.push_back(package);
1168
1169 JavaClassGeneratorOptions options = template_options;
1170 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1171 if (!WriteJavaFile(&final_table_, package, package, options)) {
1172 return false;
1173 }
1174 }
1175
1176 // Generate the main public R class.
1177 JavaClassGeneratorOptions options = template_options;
1178
1179 // Only generate public symbols if we have a private package.
1180 if (options_.private_symbols) {
1181 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1182 }
1183
1184 if (options.rewrite_callback_options) {
1185 options.rewrite_callback_options.value().packages_to_callback =
1186 std::move(packages_to_callback);
1187 }
1188
1189 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1190 options_.generate_text_symbols_path)) {
1191 return false;
1192 }
1193
1194 return true;
1195 }
1196
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001197 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1198 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001199 return true;
1200 }
1201
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001202 std::unique_ptr<ClassDefinition> manifest_class =
1203 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001204
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001205 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001206 // Something bad happened, but we already logged it, so exit.
1207 return false;
1208 }
1209
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001210 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001211 // Empty Manifest class, no need to generate it.
1212 return true;
1213 }
1214
1215 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001216 for (const std::string& annotation : options_.javadoc_annotations) {
1217 std::string proper_annotation = "@";
1218 proper_annotation += annotation;
1219 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001220 }
1221
Adam Lesinski0d81f702017-06-27 15:51:09 -07001222 const std::string package_utf8 =
1223 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001224
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001225 std::string out_path = options_.generate_java_class_path.value();
1226 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001227
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001228 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001229 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1230 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001231 return false;
1232 }
1233
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001234 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001235
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001236 io::FileOutputStream fout(out_path);
1237 if (fout.HadError()) {
1238 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1239 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001240 return false;
1241 }
1242
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001243 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1244 fout.Flush();
1245
1246 if (fout.HadError()) {
1247 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1248 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249 return false;
1250 }
1251 return true;
1252 }
1253
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001254 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255 if (!out) {
1256 return true;
1257 }
1258
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001259 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001260 io::FileOutputStream fout(out_path);
1261 if (fout.HadError()) {
1262 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1263 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001264 return false;
1265 }
1266
Ryan Mitchell7e5236d2018-09-25 15:20:59 -07001267 proguard::WriteKeepSet(keep_set, &fout, options_.generate_minimal_proguard_rules);
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001268 fout.Flush();
1269
1270 if (fout.HadError()) {
1271 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1272 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001273 return false;
1274 }
1275 return true;
1276 }
1277
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 bool MergeStaticLibrary(const std::string& input, bool override) {
1279 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001280 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 }
1282
Adam Lesinski8780eb62017-10-31 17:44:39 -07001283 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1284 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001285 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001286 return false;
1287 }
1288
Adam Lesinski8780eb62017-10-31 17:44:39 -07001289 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001290 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001292 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001293 return false;
1294 }
1295
1296 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001297 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001298 // Merge all resources as if they were in the compilation package. This is the old behavior
1299 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001300
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001301 // Add the package to the set of --extra-packages so we emit an R.java for each library
1302 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001303 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001304 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 }
1306
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001307 // Clear the package name, so as to make the resources look like they are coming from the
1308 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001309 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001310 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311
1312 } else {
1313 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001314 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001315 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001316 }
1317
1318 if (!result) {
1319 return false;
1320 }
1321
1322 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001323 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001324 return true;
1325 }
1326
Adam Lesinski2427dce2017-11-30 15:10:28 -08001327 bool MergeExportedSymbols(const Source& source,
1328 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001330 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001331 ResourceName res_name = exported_symbol.name;
1332 if (res_name.package.empty()) {
1333 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001334 }
1335
Adam Lesinski00451162017-10-03 07:44:08 -07001336 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001337 if (mangled_name) {
1338 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001339 }
1340
1341 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001342 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001343 bool result =
1344 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1345 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001346 if (!result) {
1347 return false;
1348 }
1349 }
1350 return true;
1351 }
1352
Adam Lesinski2427dce2017-11-30 15:10:28 -08001353 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1354 if (context_->IsVerbose()) {
1355 context_->GetDiagnostics()->Note(DiagMessage()
1356 << "merging '" << compiled_file.name
1357 << "' from compiled file " << compiled_file.source);
1358 }
1359
1360 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1361 return false;
1362 }
1363 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1364 }
1365
Adam Lesinski00451162017-10-03 07:44:08 -07001366 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1367 // If override is true, conflicting resources are allowed to override each other, in order of last
1368 // seen.
1369 // An io::IFileCollection is created from the ZIP file and added to the set of
1370 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001371 bool MergeArchive(const std::string& input, bool override) {
1372 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001373 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001374 }
1375
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001376 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001377 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001378 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001379 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001380 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001381 return false;
1382 }
1383
1384 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001385 for (auto iter = collection->Iterator(); iter->HasNext();) {
1386 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001387 error = true;
1388 }
1389 }
1390
1391 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001392 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001393 return !error;
1394 }
1395
Adam Lesinski00451162017-10-03 07:44:08 -07001396 // Takes a path to load and merge into the master ResourceTable. If override is true,
1397 // conflicting resources are allowed to override each other, in order of last seen.
1398 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1399 // as ZIP archive and the files within are merged individually.
1400 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001401 bool MergePath(const std::string& path, bool override) {
1402 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1403 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1404 return MergeArchive(path, override);
1405 } else if (util::EndsWith(path, ".apk")) {
1406 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001407 }
1408
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001409 io::IFile* file = file_collection_->InsertFile(path);
1410 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 }
1412
Adam Lesinski00451162017-10-03 07:44:08 -07001413 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1414 // If override is true, conflicting resources are allowed to override each other, in order of last
1415 // seen.
1416 // All other file types are ignored. This is because these files could be coming from a zip,
1417 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 bool MergeFile(io::IFile* file, bool override) {
1419 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001420
Adam Lesinski00451162017-10-03 07:44:08 -07001421 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001422 // Since AAPT compiles these file types and appends .flat to them, seeing
1423 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001424 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1425 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1426 << " file passed as argument. Must be "
1427 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001428 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001429 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1430 if (context_->IsVerbose()) {
1431 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1432 return true;
1433 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001434 }
1435
Adam Lesinski00451162017-10-03 07:44:08 -07001436 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1437 if (input_stream == nullptr) {
1438 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1439 return false;
1440 }
1441
1442 if (input_stream->HadError()) {
1443 context_->GetDiagnostics()->Error(DiagMessage(src)
1444 << "failed to open file: " << input_stream->GetError());
1445 return false;
1446 }
1447
1448 ContainerReaderEntry* entry;
1449 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001450
1451 if (reader.HadError()) {
1452 context_->GetDiagnostics()->Error(DiagMessage(src)
1453 << "failed to read file: " << reader.GetError());
1454 return false;
1455 }
1456
Adam Lesinski00451162017-10-03 07:44:08 -07001457 while ((entry = reader.Next()) != nullptr) {
1458 if (entry->Type() == ContainerEntryType::kResTable) {
1459 pb::ResourceTable pb_table;
1460 if (!entry->GetResTable(&pb_table)) {
1461 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1462 << entry->GetError());
1463 return false;
1464 }
1465
1466 ResourceTable table;
1467 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001468 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001469 context_->GetDiagnostics()->Error(DiagMessage(src)
1470 << "failed to deserialize resource table: " << error);
1471 return false;
1472 }
1473
1474 if (!table_merger_->Merge(src, &table, override)) {
1475 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1476 return false;
1477 }
1478 } else if (entry->Type() == ContainerEntryType::kResFile) {
1479 pb::internal::CompiledFile pb_compiled_file;
1480 off64_t offset;
1481 size_t len;
1482 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1483 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1484 << entry->GetError());
1485 return false;
1486 }
1487
1488 ResourceFile resource_file;
1489 std::string error;
1490 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1491 context_->GetDiagnostics()->Error(DiagMessage(src)
1492 << "failed to read compiled header: " << error);
1493 return false;
1494 }
1495
1496 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1497 return false;
1498 }
1499 }
1500 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001501 return true;
1502 }
1503
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001504 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1505 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1506 for (const std::string& assets_dir : options_.assets_dirs) {
1507 Maybe<std::vector<std::string>> files =
1508 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1509 if (!files) {
1510 return false;
1511 }
1512
1513 for (const std::string& file : files.value()) {
1514 std::string full_key = "assets/" + file;
1515 std::string full_path = assets_dir;
1516 file::AppendPath(&full_path, file);
1517
1518 auto iter = merged_assets.find(full_key);
1519 if (iter == merged_assets.end()) {
1520 merged_assets.emplace(std::move(full_key),
1521 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1522 } else if (context_->IsVerbose()) {
1523 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1524 << "asset file overrides '" << full_path << "'");
1525 }
1526 }
1527 }
1528
1529 for (auto& entry : merged_assets) {
1530 uint32_t compression_flags = ArchiveEntry::kCompress;
1531 std::string extension = file::GetExtension(entry.first).to_string();
1532 if (options_.extensions_to_not_compress.count(extension) > 0) {
1533 compression_flags = 0u;
1534 }
1535
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001536 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1537 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001538 return false;
1539 }
1540 }
1541 return true;
1542 }
1543
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001544 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1545 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001546 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1547 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001548 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Ryan Mitchell467b6892018-11-09 15:52:07 -08001549 bool result = FlattenXml(context_, *manifest, kAndroidManifestPath, keep_raw_values,
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001550 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001551 if (!result) {
1552 return false;
1553 }
1554
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001555 ResourceFileFlattenerOptions file_flattener_options;
1556 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001557 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1558 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001559 file_flattener_options.no_auto_version = options_.no_auto_version;
1560 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001561 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001562 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1563 file_flattener_options.update_proguard_spec =
1564 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001565 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001566
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001567 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001568
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001569 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001570 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001571 return false;
1572 }
1573
Adam Lesinski490595a2017-11-07 17:08:07 -08001574 // Hack to fix b/68820737.
1575 // We need to modify the ResourceTable's package name, but that should NOT affect
1576 // anything else being generated, which includes the Java classes.
1577 // If required, the package name is modifed before flattening, and then modified back
1578 // to its original name.
1579 ResourceTablePackage* package_to_rewrite = nullptr;
Todd Kennedy32512992018-04-25 16:45:59 -07001580 // Pre-O, the platform treats negative resource IDs [those with a package ID of 0x80
1581 // or higher] as invalid. In order to work around this limitation, we allow the use
1582 // of traditionally reserved resource IDs [those between 0x02 and 0x7E]. Allow the
1583 // definition of what a valid "split" package ID is to account for this.
1584 const bool isSplitPackage = (options_.allow_reserved_package_id &&
1585 context_->GetPackageId() != kAppPackageId &&
1586 context_->GetPackageId() != kFrameworkPackageId)
1587 || (!options_.allow_reserved_package_id && context_->GetPackageId() > kAppPackageId);
1588 if (isSplitPackage &&
Adam Lesinski490595a2017-11-07 17:08:07 -08001589 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1590 // The base APK is included, and this is a feature split. If the base package is
1591 // the same as this package, then we are building an old style Android Instant Apps feature
1592 // split and must apply this workaround to avoid requiring namespaces support.
1593 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1594 if (package_to_rewrite != nullptr) {
1595 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1596
1597 std::string new_package_name =
1598 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1599 app_info_.split_name.value_or_default("feature").c_str());
1600
1601 if (context_->IsVerbose()) {
1602 context_->GetDiagnostics()->Note(
1603 DiagMessage() << "rewriting resource package name for feature split to '"
1604 << new_package_name << "'");
1605 }
1606 package_to_rewrite->name = new_package_name;
1607 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001608 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001609
1610 bool success = FlattenTable(table, options_.output_format, writer);
1611
1612 if (package_to_rewrite != nullptr) {
1613 // Change the name back.
1614 package_to_rewrite->name = context_->GetCompilationPackage();
1615 if (package_to_rewrite->id) {
1616 table->included_packages_.erase(package_to_rewrite->id.value());
1617 }
1618 }
1619
1620 if (!success) {
1621 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1622 }
1623 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001624 }
1625
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001626 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001627 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001628 std::unique_ptr<xml::XmlResource> manifest_xml =
1629 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1630 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001631 return 1;
1632 }
1633
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001634 // First extract the Package name without modifying it (via --rename-manifest-package).
1635 if (Maybe<AppInfo> maybe_app_info =
1636 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001637 const AppInfo& app_info = maybe_app_info.value();
1638 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001639 }
1640
Adam Lesinskic6284372017-12-04 13:46:23 -08001641 // Now that the compilation package is set, load the dependencies. This will also extract
1642 // the Android framework's versionCode and versionName, if they exist.
1643 if (!LoadSymbolsFromIncludePaths()) {
1644 return 1;
1645 }
1646
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001647 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1648 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 return 1;
1650 }
1651
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001652 Maybe<AppInfo> maybe_app_info =
1653 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001654 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001655 return 1;
1656 }
1657
Adam Lesinski490595a2017-11-07 17:08:07 -08001658 app_info_ = maybe_app_info.value();
1659 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001660
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001661 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001662
1663 // Override the package ID when it is "android".
1664 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001665 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001666
1667 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001668 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001669 context_->GetDiagnostics()->Error(
1670 DiagMessage() << "package 'android' can only be built as a regular app");
1671 return 1;
1672 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001673 }
1674
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 TableMergerOptions table_merger_options;
1676 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Izabela Orlowskad51efe82018-04-24 18:18:29 +01001677 table_merger_options.strict_visibility = options_.strict_visibility;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001678 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001679
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001680 if (context_->IsVerbose()) {
1681 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001682 << StringPrintf("linking package '%s' using package ID %02x",
1683 context_->GetCompilationPackage().data(),
1684 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001685 }
1686
Adam Lesinski2427dce2017-11-30 15:10:28 -08001687 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1688 // in res/**/*.
1689 {
1690 XmlIdCollector collector;
1691 if (!collector.Consume(context_, manifest_xml.get())) {
1692 return false;
1693 }
1694
1695 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1696 return false;
1697 }
1698 }
1699
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001700 for (const std::string& input : input_files) {
1701 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001702 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001703 return 1;
1704 }
1705 }
1706
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001707 for (const std::string& input : options_.overlay_files) {
1708 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001709 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 return 1;
1711 }
1712 }
1713
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001714 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001715 return 1;
1716 }
1717
Adam Lesinskib522f042017-04-21 16:57:59 -07001718 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001720 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001721 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001722 return 1;
1723 }
1724
1725 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001726 IdAssigner id_assigner(&options_.stable_id_map);
1727 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001728 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001729 return 1;
1730 }
1731
1732 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001733 if (options_.resource_id_map_path) {
1734 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001735 for (auto& type : package->types) {
1736 for (auto& entry : type->entries) {
1737 ResourceName name(package->name, type->type, entry->name);
1738 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001739 options_.stable_id_map[std::move(name)] =
1740 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001741 }
1742 }
1743 }
1744
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001745 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001746 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001747 return 1;
1748 }
1749 }
1750 } else {
1751 // Static libs are merged with other apps, and ID collisions are bad, so
1752 // verify that
1753 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001754 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001755 return 1;
1756 }
1757 }
1758
1759 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001760 context_->SetNameManglerPolicy(
1761 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001762
1763 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001764 context_->GetExternalSymbols()->PrependSource(
1765 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001766
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001767 // Workaround for pre-O runtime that would treat negative resource IDs
1768 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1769 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1770 // are just identifiers.
1771 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1772 if (context_->IsVerbose()) {
1773 context_->GetDiagnostics()->Note(DiagMessage()
1774 << "enabling pre-O feature split ID rewriting");
1775 }
1776 context_->GetExternalSymbols()->SetDelegate(
1777 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1778 }
1779
Adam Lesinski34a16872018-02-23 16:18:10 -08001780 // Before we process anything, remove the resources whose default values don't exist.
1781 // We want to force any references to these to fail the build.
Mårten Kongstadd8d29012018-06-11 14:13:37 +02001782 if (!options_.no_resource_removal) {
1783 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1784 context_->GetDiagnostics()->Error(DiagMessage()
1785 << "failed removing resources with no defaults");
1786 return 1;
1787 }
Adam Lesinski34a16872018-02-23 16:18:10 -08001788 }
1789
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001790 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001791 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001792 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001793 return 1;
1794 }
1795
Adam Lesinskib522f042017-04-21 16:57:59 -07001796 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001797 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001798 context_->GetDiagnostics()->Warn(DiagMessage()
1799 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 }
1801 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001802 ProductFilter product_filter(options_.products);
1803 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001804 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001805 return 1;
1806 }
1807 }
1808
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001809 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001810 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001811 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001812 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001813 return 1;
1814 }
1815 }
1816
Adam Lesinskib522f042017-04-21 16:57:59 -07001817 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001819 context_->GetDiagnostics()->Note(DiagMessage()
1820 << "collapsing resource versions for minimum SDK "
1821 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001822 }
1823
1824 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001825 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001826 return 1;
1827 }
1828 }
1829
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001831 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001833 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001834 return 1;
1835 }
1836 }
1837
Adam Koskidc21dea2017-07-21 10:55:27 -07001838 proguard::KeepSet proguard_keep_set =
1839 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841
Adam Lesinskib522f042017-04-21 16:57:59 -07001842 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001843 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001844 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001845 context_->GetDiagnostics()->Warn(DiagMessage()
1846 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001847 }
1848 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001849 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1850 // equal to the minSdk.
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001851 const size_t origConstraintSize = options_.split_constraints.size();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001852 options_.split_constraints =
1853 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001854
Todd Kennedy9fbdf892018-08-28 16:31:15 -07001855 if (origConstraintSize != options_.split_constraints.size()) {
1856 context_->GetDiagnostics()->Warn(DiagMessage()
1857 << "requested to split resources prior to min sdk of "
1858 << context_->GetMinSdkVersion());
1859 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001862 return 1;
1863 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001864 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001865
1866 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001867 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001868 auto split_constraints_iter = options_.split_constraints.begin();
1869 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001870 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1872 << "generating split with configurations '"
1873 << util::Joiner(split_constraints_iter->configs, ", ")
1874 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001875 }
1876
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001877 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001878 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001879 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001880 return 1;
1881 }
1882
1883 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001885 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001886
1887 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001888 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001889 context_->GetDiagnostics()->Error(DiagMessage()
1890 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001891 return 1;
1892 }
1893
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1895 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001896 return 1;
1897 }
1898
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001899 ++path_iter;
1900 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001901 }
1902 }
1903
1904 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001905 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001906 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001907 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001908 return 1;
1909 }
1910
1911 bool error = false;
1912 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001913 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001914 // (aka, which package the AndroidManifest.xml is coming from).
1915 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001916 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001917
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001918 XmlReferenceLinker manifest_linker;
1919 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1920 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001921 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001922 error = true;
1923 }
1924
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001925 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001926 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001927 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001928 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001929 }
1930
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001931 if (options_.generate_java_class_path) {
1932 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001933 error = true;
1934 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001935 }
1936
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001937 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001938 // PackageParser will fail if URIs are removed from
1939 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1941 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001942 error = true;
1943 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001944 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001945 } else {
1946 error = true;
1947 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001948 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001949
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001950 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001951 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001952 return 1;
1953 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001954
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001955 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1956 return 1;
1957 }
1958
1959 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001960 return 1;
1961 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001962
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001963 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001964 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001965 return 1;
1966 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001967 }
1968
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001969 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001970 return 1;
1971 }
1972
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001973 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1974 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001975 return 1;
1976 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001977 return 0;
1978 }
1979
1980 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 LinkOptions options_;
1982 LinkContext* context_;
1983 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001984
Adam Lesinski490595a2017-11-07 17:08:07 -08001985 AppInfo app_info_;
1986
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001987 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001988
1989 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001990 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001991
Adam Lesinski8780eb62017-10-31 17:44:39 -07001992 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001993 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001994 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001995
Adam Lesinski8780eb62017-10-31 17:44:39 -07001996 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1997 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1998
1999 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2000 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002001
2002 // The set of shared libraries being used, mapping their assigned package ID to package name.
2003 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002004
2005 // The package name of the base application, if it is included.
2006 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002007};
2008
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002009int LinkCommand::Action(const std::vector<std::string>& args) {
2010 LinkContext context(diag_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002012 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 std::vector<std::string> arg_list;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002014 for (const std::string& arg : args) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002015 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002016 const std::string path = arg.substr(1, arg.size() - 1);
2017 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002018 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2019 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002020 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021 }
2022 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002023 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002024 }
2025 }
2026
2027 // Expand all argument-files passed to -R.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002028 for (const std::string& arg : overlay_arg_list_) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002029 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002030 const std::string path = arg.substr(1, arg.size() - 1);
2031 std::string error;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002032 if (!file::AppendArgsFromFile(path, &options_.overlay_files, &error)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002033 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002034 return 1;
2035 }
2036 } else {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002037 options_.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002038 }
2039 }
2040
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002041 if (verbose_) {
2042 context.SetVerbose(verbose_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002043 }
2044
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002045 if (int{shared_lib_} + int{static_lib_} + int{proto_format_} > 1) {
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002046 context.GetDiagnostics()->Error(
2047 DiagMessage()
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002048 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002049 return 1;
2050 }
2051
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002052 // The default build type.
2053 context.SetPackageType(PackageType::kApp);
2054 context.SetPackageId(kAppPackageId);
2055
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002056 if (shared_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002057 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002058 context.SetPackageId(0x00);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002059 } else if (static_lib_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002060 context.SetPackageType(PackageType::kStaticLib);
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002061 options_.output_format = OutputFormat::kProto;
2062 } else if (proto_format_) {
2063 options_.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002064 }
2065
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002066 if (package_id_) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002067 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002068 context.GetDiagnostics()->Error(
2069 DiagMessage() << "can't specify --package-id when not building a regular app");
2070 return 1;
2071 }
2072
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002073 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id_.value());
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002074 if (!maybe_package_id_int) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002075 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id_.value()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002076 << "' is not a valid integer");
2077 return 1;
2078 }
2079
2080 const uint32_t package_id_int = maybe_package_id_int.value();
Todd Kennedy32512992018-04-25 16:45:59 -07002081 if (package_id_int > std::numeric_limits<uint8_t>::max()
2082 || package_id_int == kFrameworkPackageId
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002083 || (!options_.allow_reserved_package_id && package_id_int < kAppPackageId)) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002084 context.GetDiagnostics()->Error(
2085 DiagMessage() << StringPrintf(
2086 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2087 return 1;
2088 }
2089 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2090 }
2091
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002092 // Populate the set of extra packages for which to generate R.java.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002093 for (std::string& extra_package : extra_java_packages_) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002095 for (StringPiece package : util::Split(extra_package, ':')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002096 options_.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002097 }
2098 }
2099
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002100 if (product_list_) {
2101 for (StringPiece product : util::Tokenize(product_list_.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002102 if (product != "" && product != "default") {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002103 options_.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002104 }
2105 }
2106 }
2107
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002108 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002109 if (!configs_.empty()) {
2110 filter = ParseConfigFilterParameters(configs_, context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002111 if (filter == nullptr) {
2112 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002113 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002114 options_.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002115 }
2116
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002117 if (preferred_density_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002118 Maybe<uint16_t> density =
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002119 ParseTargetDensityParameter(preferred_density_.value(), context.GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002120 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002121 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002122 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002123 options_.table_splitter_options.preferred_densities.push_back(density.value());
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002124 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002125
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002126 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002127 for (const std::string& split_arg : split_args_) {
2128 options_.split_paths.push_back({});
2129 options_.split_constraints.push_back({});
2130 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options_.split_paths.back(),
2131 &options_.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002132 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002133 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002134 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002135
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002136 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path_) {
2137 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path_.value(),
2138 &options_.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002139 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002140 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002141 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002142
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002143 // Populate some default no-compress extensions that are already compressed.
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002144 options_.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002145 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002146 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2147 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2148 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002149
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002150 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002151 if (context.GetPackageType() == PackageType::kStaticLib) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002152 options_.no_auto_version = true;
2153 options_.no_version_vectors = true;
2154 options_.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002155 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002156
Ryan Mitchell833a1a62018-07-10 13:51:36 -07002157 Linker cmd(&context, options_);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002158 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002159}
2160
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002161} // namespace aapt