blob: 740a401f9b57cc35247681c2379975734e48f57e [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
Adam Lesinskice5e56e2016-10-21 17:56:45 -070017#include <sys/stat.h>
18
19#include <fstream>
20#include <queue>
21#include <unordered_map>
22#include <vector>
23
24#include "android-base/errors.h"
25#include "android-base/file.h"
Adam Lesinskif34b6f42017-03-03 16:33:26 -080026#include "android-base/stringprintf.h"
Adam Lesinskid5083f62017-01-16 15:07:21 -080027#include "androidfw/StringPiece.h"
Adam Lesinskice5e56e2016-10-21 17:56:45 -070028#include "google/protobuf/io/coded_stream.h"
29
Adam Lesinski1ab598f2015-08-14 14:26:04 -070030#include "AppInfo.h"
31#include "Debug.h"
32#include "Flags.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080033#include "Locale.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070034#include "NameMangler.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080035#include "ResourceUtils.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070036#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070037#include "compile/IdAssigner.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080038#include "filter/ConfigFilter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "flatten/Archive.h"
40#include "flatten/TableFlattener.h"
41#include "flatten/XmlFlattener.h"
Adam Lesinski06460ef2017-03-14 18:52:13 -070042#include "io/BigBufferInputStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080043#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070044#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080045#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070046#include "java/JavaClassGenerator.h"
47#include "java/ManifestClassGenerator.h"
48#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070049#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070050#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080051#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070052#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070053#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080054#include "optimize/ResourceDeduper.h"
55#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "process/IResourceTableConsumer.h"
57#include "process/SymbolTable.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080058#include "proto/ProtoSerialize.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080059#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "unflatten/BinaryResourceParser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080062#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070063
Adam Lesinskid5083f62017-01-16 15:07:21 -080064using android::StringPiece;
Adam Lesinskif34b6f42017-03-03 16:33:26 -080065using android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070066
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067namespace aapt {
68
69struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070070 std::string output_path;
71 std::string manifest_path;
72 std::vector<std::string> include_paths;
73 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070074 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070075 bool output_to_directory = false;
76 bool auto_add_overlay = false;
Adam Lesinski36c73a52016-08-11 13:39:24 -070077
Adam Lesinskicacb28f2016-10-19 12:18:14 -070078 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070079 Maybe<std::string> generate_java_class_path;
80 Maybe<std::string> custom_java_package;
81 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070082 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070083 Maybe<std::string> generate_proguard_rules_path;
84 Maybe<std::string> generate_main_dex_proguard_rules_path;
85 bool generate_non_final_ids = false;
86 std::vector<std::string> javadoc_annotations;
87 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070088
Adam Lesinskice5e56e2016-10-21 17:56:45 -070089 // Optimizations/features.
90 bool no_auto_version = false;
91 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +090092 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070093 bool no_resource_deduping = false;
94 bool no_xml_namespaces = false;
95 bool do_not_compress_anything = false;
96 std::unordered_set<std::string> extensions_to_not_compress;
97
98 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070099 bool no_static_lib_packages = false;
100
101 // AndroidManifest.xml massaging options.
102 ManifestFixerOptions manifest_fixer_options;
103
104 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700105 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700106
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800107 // Flattening options.
108 TableFlattenerOptions table_flattener_options;
109
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700110 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700111 TableSplitterOptions table_splitter_options;
112 std::vector<SplitConstraints> split_constraints;
113 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700114
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700115 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700116 std::unordered_map<ResourceName, ResourceId> stable_id_map;
117 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700118};
119
Adam Lesinski64587af2016-02-18 18:33:06 -0800120class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700121 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100122 LinkContext(IDiagnostics* diagnostics)
123 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700124 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700125
Adam Lesinskib522f042017-04-21 16:57:59 -0700126 PackageType GetPackageType() override {
127 return package_type_;
128 }
129
130 void SetPackageType(PackageType type) {
131 package_type_ = type;
132 }
133
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700134 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100135 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700137
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 NameMangler* GetNameMangler() override {
139 return &name_mangler_;
140 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700141
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700142 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
143 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700144 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800145
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700146 const std::string& GetCompilationPackage() override {
147 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700148 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700149
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700150 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800151 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700152 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800153
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700154 uint8_t GetPackageId() override {
155 return package_id_;
156 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700157
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700158 void SetPackageId(uint8_t id) {
159 package_id_ = id;
160 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800161
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700162 SymbolTable* GetExternalSymbols() override {
163 return &symbols_;
164 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800165
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700166 bool IsVerbose() override {
167 return verbose_;
168 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800169
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700170 void SetVerbose(bool val) {
171 verbose_ = val;
172 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 int GetMinSdkVersion() override {
175 return min_sdk_version_;
176 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700177
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700178 void SetMinSdkVersion(int minSdk) {
179 min_sdk_version_ = minSdk;
180 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700181
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700182 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700183 DISALLOW_COPY_AND_ASSIGN(LinkContext);
184
Adam Lesinskib522f042017-04-21 16:57:59 -0700185 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100186 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700187 NameMangler name_mangler_;
188 std::string compilation_package_;
189 uint8_t package_id_ = 0x0;
190 SymbolTable symbols_;
191 bool verbose_ = false;
192 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700193};
194
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700195// A custom delegate that generates compatible pre-O IDs for use with feature splits.
196// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
197// is interpreted as a negative number. Some verification was wrongly assuming negative values
198// were invalid.
199//
200// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
201// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
202// an overlap exists.
203class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
204 public:
205 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
206 }
207
208 virtual ~FeatureSplitSymbolTableDelegate() = default;
209
210 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
211 const ResourceName& name,
212 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
213 std::unique_ptr<SymbolTable::Symbol> symbol =
214 DefaultSymbolTableDelegate::FindByName(name, sources);
215 if (symbol == nullptr) {
216 return {};
217 }
218
219 // Check to see if this is an 'id' with the target package.
220 if (name.type == ResourceType::kId && symbol->id) {
221 ResourceId* id = &symbol->id.value();
222 if (id->package_id() > kAppPackageId) {
223 // Rewrite the resource ID to be compatible pre-O.
224 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
225
226 // Check that this doesn't overlap another resource.
227 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
228 // The ID overlaps, so log a message (since this is a weird failure) and fail.
229 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
230 << " for pre-O feature split support");
231 return {};
232 }
233
234 if (context_->IsVerbose()) {
235 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
236 << ") -> (" << rewritten_id << ")");
237 }
238
239 *id = rewritten_id;
240 }
241 }
242 return symbol;
243 }
244
245 private:
246 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
247
248 IAaptContext* context_;
249};
250
Adam Lesinskic744ae82017-05-17 19:28:38 -0700251static bool FlattenXml(IAaptContext* context, xml::XmlResource* xml_res, const StringPiece& path,
252 bool keep_raw_values, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700253 BigBuffer buffer(1024);
254 XmlFlattenerOptions options = {};
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700255 options.keep_raw_values = keep_raw_values;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700256 XmlFlattener flattener(&buffer, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700257 if (!flattener.Consume(context, xml_res)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800258 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700259 }
260
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700261 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700262 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
263 << (keep_raw_values ? "true" : "false")
264 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700265 }
266
Adam Lesinski06460ef2017-03-14 18:52:13 -0700267 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700268 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
269 ArchiveEntry::kCompress, writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800270}
271
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700272static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
273 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700274 pb::ResourceTable pb_table;
275 if (!pb_table.ParseFromArray(data, len)) {
276 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700277 return {};
278 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800279
Adam Lesinski06460ef2017-03-14 18:52:13 -0700280 std::unique_ptr<ResourceTable> table = DeserializeTableFromPb(pb_table, source, diag);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700281 if (!table) {
282 return {};
283 }
284 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800285}
286
287/**
288 * Inflates an XML file from the source path.
289 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700290static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700291 std::ifstream fin(path, std::ifstream::binary);
292 if (!fin) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700293 diag->Error(DiagMessage(path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700294 return {};
295 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700296 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800297}
298
Adam Lesinski355f2852016-02-13 20:26:45 -0800299struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700300 bool no_auto_version = false;
301 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900302 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700303 bool no_xml_namespaces = false;
304 bool keep_raw_values = false;
305 bool do_not_compress_anything = false;
306 bool update_proguard_spec = false;
307 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800308};
309
Adam Lesinskic744ae82017-05-17 19:28:38 -0700310// A sampling of public framework resource IDs.
311struct R {
312 struct attr {
313 enum : uint32_t {
314 paddingLeft = 0x010100d6u,
315 paddingRight = 0x010100d8u,
316 paddingHorizontal = 0x0101053du,
317
318 paddingTop = 0x010100d7u,
319 paddingBottom = 0x010100d9u,
320 paddingVertical = 0x0101053eu,
321
322 layout_marginLeft = 0x010100f7u,
323 layout_marginRight = 0x010100f9u,
324 layout_marginHorizontal = 0x0101053bu,
325
326 layout_marginTop = 0x010100f8u,
327 layout_marginBottom = 0x010100fau,
328 layout_marginVertical = 0x0101053cu,
329 };
330 };
331};
332
Adam Lesinski355f2852016-02-13 20:26:45 -0800333class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700334 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700335 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700336 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800337
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700338 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800339
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700340 private:
341 struct FileOperation {
342 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700343
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700344 // The entry this file came from.
Adam Lesinskic744ae82017-05-17 19:28:38 -0700345 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700346
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700347 // The file to copy as-is.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700348 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700349
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700350 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700351 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700352
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700353 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700354 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700355 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800356
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700357 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800358
Adam Lesinskic744ae82017-05-17 19:28:38 -0700359 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
360 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800361
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700362 ResourceFileFlattenerOptions options_;
363 IAaptContext* context_;
364 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700365 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800366};
367
Adam Lesinskic744ae82017-05-17 19:28:38 -0700368ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
369 IAaptContext* context, proguard::KeepSet* keep_set)
370 : options_(options), context_(context), keep_set_(keep_set) {
371 SymbolTable* symm = context_->GetExternalSymbols();
372
373 // Build up the rules for degrading newer attributes to older ones.
374 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
375 // generated from the attribute definitions themselves (b/62028956).
376 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
377 std::vector<ReplacementAttr> replacements{
378 {"paddingLeft", R::attr::paddingLeft,
379 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
380 {"paddingRight", R::attr::paddingRight,
381 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
382 };
383 rules_[R::attr::paddingHorizontal] =
384 util::make_unique<DegradeToManyRule>(std::move(replacements));
385 }
386
387 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
388 std::vector<ReplacementAttr> replacements{
389 {"paddingTop", R::attr::paddingTop,
390 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
391 {"paddingBottom", R::attr::paddingBottom,
392 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
393 };
394 rules_[R::attr::paddingVertical] =
395 util::make_unique<DegradeToManyRule>(std::move(replacements));
396 }
397
398 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
399 std::vector<ReplacementAttr> replacements{
400 {"layout_marginLeft", R::attr::layout_marginLeft,
401 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
402 {"layout_marginRight", R::attr::layout_marginRight,
403 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
404 };
405 rules_[R::attr::layout_marginHorizontal] =
406 util::make_unique<DegradeToManyRule>(std::move(replacements));
407 }
408
409 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
410 std::vector<ReplacementAttr> replacements{
411 {"layout_marginTop", R::attr::layout_marginTop,
412 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
413 {"layout_marginBottom", R::attr::layout_marginBottom,
414 Attribute(false, android::ResTable_map::TYPE_DIMENSION)},
415 };
416 rules_[R::attr::layout_marginVertical] =
417 util::make_unique<DegradeToManyRule>(std::move(replacements));
418 }
419}
420
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700421uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
422 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700423 return 0;
424 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800425
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700426 for (const std::string& extension : options_.extensions_to_not_compress) {
427 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700428 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800429 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700430 }
431 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800432}
433
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900434static bool IsTransitionElement(const std::string& name) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700435 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
436 name == "changeImageTransform" || name == "changeTransform" ||
437 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
438 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
439 name == "transitionManager";
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900440}
441
Adam Lesinskic744ae82017-05-17 19:28:38 -0700442static bool IsVectorElement(const std::string& name) {
Adam Lesinski41ea44f2017-05-31 10:22:30 -0700443 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
444 name == "objectAnimator";
Adam Lesinskic744ae82017-05-17 19:28:38 -0700445}
446
447template <typename T>
448std::vector<T> make_singleton_vec(T&& val) {
449 std::vector<T> vec;
450 vec.emplace_back(std::forward<T>(val));
451 return vec;
452}
453
454std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
455 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700456 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700457 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700458
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700459 if (context_->IsVerbose()) {
460 context_->GetDiagnostics()->Note(DiagMessage() << "linking " << src.path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700461 }
462
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700463 XmlReferenceLinker xml_linker;
464 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700465 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700466 }
467
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700468 if (options_.update_proguard_spec && !proguard::CollectProguardRules(src, doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700469 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700470 }
471
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700472 if (options_.no_xml_namespaces) {
473 XmlNamespaceRemover namespace_remover;
474 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700475 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800476 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700477 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800478
Adam Lesinskic744ae82017-05-17 19:28:38 -0700479 if (options_.no_auto_version) {
480 return make_singleton_vec(std::move(file_op->xml_to_flatten));
481 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700482
Adam Lesinskic744ae82017-05-17 19:28:38 -0700483 if (options_.no_version_vectors || options_.no_version_transitions) {
484 // Skip this if it is a vector or animated-vector.
485 xml::Element* el = xml::FindRootElement(doc);
486 if (el && el->namespace_uri.empty()) {
487 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
488 (options_.no_version_transitions && IsTransitionElement(el->name))) {
489 return make_singleton_vec(std::move(file_op->xml_to_flatten));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700490 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800491 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700493
494 const ConfigDescription& config = file_op->config;
495 ResourceEntry* entry = file_op->entry;
496
497 XmlCompatVersioner xml_compat_versioner(&rules_);
498 const util::Range<ApiVersion> api_range{config.sdkVersion,
499 FindNextApiVersionForConfig(entry, config)};
500 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800501}
502
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700503bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700504 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700505 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800506
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700507 for (auto& pkg : table->packages) {
508 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700510 config_sorted_files.clear();
511 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800512
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700513 // Populate the queue with all files in the ResourceTable.
514 for (auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700515 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700516 // WARNING! Do not insert or remove any resources while executing in this scope. It will
517 // corrupt the iteration order.
518
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700519 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700520 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700521 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700522 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700523
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700524 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700525 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700526 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700527 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700528 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700529 }
530
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700531 FileOperation file_op;
532 file_op.entry = entry.get();
533 file_op.dst_path = *file_ref->path;
534 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700535 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700536
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700537 const StringPiece src_path = file->GetSource().path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 if (type->type != ResourceType::kRaw &&
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700539 (util::EndsWith(src_path, ".xml.flat") || util::EndsWith(src_path, ".xml"))) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700540 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700541 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700542 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 << "failed to open file");
544 return false;
545 }
546
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700547 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(),
548 context_->GetDiagnostics(), file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700549
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 if (!file_op.xml_to_flatten) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700551 return false;
552 }
553
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700554 file_op.xml_to_flatten->file.config = config_value->config;
555 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700556 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700558
559 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
560 // else we end up copying the string in the std::make_pair() method,
561 // then creating a StringPiece from the copy, which would cause us
562 // to end up referencing garbage in the map.
563 const StringPiece entry_name(entry->name);
564 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
565 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566 }
567 }
568
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700569 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 for (auto& map_entry : config_sorted_files) {
571 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700572 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700574 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700575 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
576 LinkAndVersionXmlFile(table, &file_op);
577 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
578 std::string dst_path = file_op.dst_path;
579 if (doc->file.config != file_op.config) {
580 // Only add the new versioned configurations.
581 if (context_->IsVerbose()) {
582 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
583 << "auto-versioning resource from config '"
584 << config << "' -> '" << doc->file.config << "'");
585 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700586
Adam Lesinskic744ae82017-05-17 19:28:38 -0700587 dst_path =
588 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
589 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
590 doc->file.source, dst_path, nullptr,
591 context_->GetDiagnostics());
592 if (!result) {
593 return false;
594 }
595 }
596 error |= !FlattenXml(context_, doc.get(), dst_path, options_.keep_raw_values,
597 archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700598 }
599 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700600 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
601 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700602 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700604 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700605 }
606 return !error;
607}
608
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700609static bool WriteStableIdMapToPath(IDiagnostics* diag,
610 const std::unordered_map<ResourceName, ResourceId>& id_map,
611 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700612 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700613 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700614 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700615 return false;
616 }
617
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700618 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700619 const ResourceName& name = entry.first;
620 const ResourceId& id = entry.second;
621 fout << name << " = " << id << "\n";
622 }
623
624 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700625 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
626 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700627 return false;
628 }
629
630 return true;
631}
632
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700633static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
634 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700635 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700636 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700637 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700638 return false;
639 }
640
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700641 out_id_map->clear();
642 size_t line_no = 0;
643 for (StringPiece line : util::Tokenize(content, '\n')) {
644 line_no++;
645 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700646 if (line.empty()) {
647 continue;
648 }
649
650 auto iter = std::find(line.begin(), line.end(), '=');
651 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700652 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700653 return false;
654 }
655
656 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700657 StringPiece res_name_str =
658 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
659 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700660 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
661 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700662 return false;
663 }
664
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700665 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
666 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700667 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700668
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700669 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
670 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700671 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
672 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673 return false;
674 }
675
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700676 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700677 }
678 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700679}
680
Adam Lesinskifb48d292015-11-07 15:52:13 -0800681class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 public:
683 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700684 : options_(options),
685 context_(context),
686 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700687 file_collection_(util::make_unique<io::FileCollection>()) {
688 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700689
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700690 /**
691 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700692 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700694 bool LoadSymbolsFromIncludePaths() {
695 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700696 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 for (const std::string& path : options_.include_paths) {
698 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700699 context_->GetDiagnostics()->Note(DiagMessage(path) << "loading include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700700 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700701
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700702 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700703 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800704 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
705 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700706 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800707 // Can't include static libraries when not building a static library (they have no IDs
708 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700709 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800710 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700711 return false;
712 }
713
714 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800715 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700716 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800717 // Since package names can differ, and multiple packages can exist in a ResourceTable,
718 // we place the requirement that all static libraries are built with the package
719 // ID 0x7f. So if one is not found, this is an error.
720 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800722 } else {
723 context_->GetDiagnostics()->Error(DiagMessage(path)
724 << "no package with ID 0x7f found in static library");
725 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700726 }
727 }
728
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700729 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800730 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800732 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700733
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700735 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700736 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700737 return false;
738 }
739
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700740 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800741 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 return false;
743 }
744 }
745
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800746 // Capture the shared libraries so that the final resource table can be properly flattened
747 // with support for shared libraries.
748 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800749 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800750 final_table_.included_packages_[entry.first] = entry.second;
751 }
752 }
753
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700754 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700755 return true;
756 }
757
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800758 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700759 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800760 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
761 if (manifest_el == nullptr) {
762 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700763 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800764
765 AppInfo app_info;
766
767 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
768 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
769 return {};
770 }
771
772 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
773 if (!package_attr) {
774 diag->Error(DiagMessage(xml_res->file.source)
775 << "<manifest> must have a 'package' attribute");
776 return {};
777 }
778 app_info.package = package_attr->value;
779
780 if (xml::Attribute* version_code_attr =
781 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
782 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
783 if (!maybe_code) {
784 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
785 << "invalid android:versionCode '" << version_code_attr->value << "'");
786 return {};
787 }
788 app_info.version_code = maybe_code.value();
789 }
790
791 if (xml::Attribute* revision_code_attr =
792 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
793 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
794 if (!maybe_code) {
795 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
796 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
797 return {};
798 }
799 app_info.revision_code = maybe_code.value();
800 }
801
802 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
803 if (!split_name_attr->value.empty()) {
804 app_info.split_name = split_name_attr->value;
805 }
806 }
807
808 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
809 if (xml::Attribute* min_sdk =
810 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700811 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800812 }
813 }
814 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700815 }
816
817 /**
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800818 * Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700819 * Postcondition: ResourceTable has only one package left. All others are
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700820 * stripped, or there is an error and false is returned.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700821 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700822 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700823 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700824 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
825 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700826 };
827
828 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700829 for (const auto& package : final_table_.packages) {
830 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700831 // We have a package that is not related to the one we're building!
832 for (const auto& type : package->types) {
833 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700834 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700835
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700836 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700837 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700838 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700839 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
840 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
841 << "generated id '" << res_name
842 << "' for external package '" << package->name
843 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700844 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700845 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
846 << "defined resource '" << res_name
847 << "' for external package '" << package->name
848 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700849 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700850 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700851 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700852 }
853 }
854 }
855 }
856
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700857 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
858 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700859 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700860 return !error;
861 }
862
863 /**
864 * Returns true if no IDs have been set, false otherwise.
865 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700866 bool VerifyNoIdsSet() {
867 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700868 for (const auto& type : package->types) {
869 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800870 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
871 << StringPrintf("%02x", type->id.value())
872 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700874 }
875
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700876 for (const auto& entry : type->entries) {
877 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700878 ResourceNameRef res_name(package->name, type->type, entry->name);
879 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800880 DiagMessage() << "entry " << res_name << " has ID "
881 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700882 return false;
883 }
884 }
885 }
886 }
887 return true;
888 }
889
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700890 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
891 if (options_.output_to_directory) {
892 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700893 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700894 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700895 }
896 }
897
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700898 bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700899 BigBuffer buffer(1024);
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800900 TableFlattener flattener(options_.table_flattener_options, &buffer);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700901 if (!flattener.Consume(context_, table)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700902 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700903 return false;
904 }
905
Adam Lesinski06460ef2017-03-14 18:52:13 -0700906 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700907 return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
908 ArchiveEntry::kAlign, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700909 }
910
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700911 bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700912 std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700913 return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700914 }
915
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700916 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700917 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
918 const Maybe<std::string> out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700919 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700920 return true;
921 }
922
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700923 std::string out_path = options_.generate_java_class_path.value();
924 file::AppendPath(&out_path, file::PackageToPath(out_package));
925 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700926 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
927 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700928 return false;
929 }
930
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700931 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700932
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700933 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700934 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700935 context_->GetDiagnostics()->Error(DiagMessage()
936 << "failed writing to '" << out_path
937 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700938 return false;
939 }
940
Adam Lesinski418763f2017-04-11 17:36:53 -0700941 std::unique_ptr<std::ofstream> fout_text;
942 if (out_text_symbols_path) {
943 fout_text =
944 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
945 if (!*fout_text) {
946 context_->GetDiagnostics()->Error(
947 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
948 << "': " << android::base::SystemErrorCodeToString(errno));
949 return false;
950 }
951 }
952
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700953 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -0700954 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700955 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700956 return false;
957 }
958
959 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700960 context_->GetDiagnostics()->Error(DiagMessage()
961 << "failed writing to '" << out_path
962 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700963 }
964 return true;
965 }
966
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700967 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
968 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700969 return true;
970 }
971
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700972 std::unique_ptr<ClassDefinition> manifest_class =
973 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700974
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700975 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700976 // Something bad happened, but we already logged it, so exit.
977 return false;
978 }
979
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700980 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700981 // Empty Manifest class, no need to generate it.
982 return true;
983 }
984
985 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700986 for (const std::string& annotation : options_.javadoc_annotations) {
987 std::string proper_annotation = "@";
988 proper_annotation += annotation;
989 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700990 }
991
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700992 const std::string& package_utf8 = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700993
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700994 std::string out_path = options_.generate_java_class_path.value();
995 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700997 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700998 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
999 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001000 return false;
1001 }
1002
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001003 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001004
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001005 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001006 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001007 context_->GetDiagnostics()->Error(DiagMessage()
1008 << "failed writing to '" << out_path
1009 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001010 return false;
1011 }
1012
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001013 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1014 context_->GetDiagnostics()->Error(DiagMessage()
1015 << "failed writing to '" << out_path
1016 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001017 return false;
1018 }
1019 return true;
1020 }
1021
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001022 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 if (!out) {
1024 return true;
1025 }
1026
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001027 const std::string& out_path = out.value();
1028 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001030 context_->GetDiagnostics()->Error(DiagMessage()
1031 << "failed to open '" << out_path
1032 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001033 return false;
1034 }
1035
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001036 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001038 context_->GetDiagnostics()->Error(DiagMessage()
1039 << "failed writing to '" << out_path
1040 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001041 return false;
1042 }
1043 return true;
1044 }
1045
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001046 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1047 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001048 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001049 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001050 if (!collection) {
1051 return {};
1052 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001053 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 }
1055
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001056 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001057 io::IFile* file = collection->FindFile("resources.arsc.flat");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001058 if (!file) {
1059 return {};
1060 }
1061
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001062 std::unique_ptr<io::IData> data = file->OpenAsData();
1063 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1064 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001065 }
1066
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001067 bool MergeStaticLibrary(const std::string& input, bool override) {
1068 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001069 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001070 }
1071
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001072 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001073 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001074 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001075 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001076 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001077 return false;
1078 }
1079
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001080 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001081 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001082 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001083 return false;
1084 }
1085
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001086 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001087 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001088 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001089 return false;
1090 }
1091
1092 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001093 if (options_.no_static_lib_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001094 // Merge all resources as if they were in the compilation package. This is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001095 // the old behavior of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001096
1097 // Add the package to the set of --extra-packages so we emit an R.java for
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001098 // each library package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001099 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001100 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001101 }
1102
1103 pkg->name = "";
1104 if (override) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001105 result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001106 } else {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001107 result = table_merger_->Merge(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001108 }
1109
1110 } else {
1111 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001112 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001113 result =
1114 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001115 }
1116
1117 if (!result) {
1118 return false;
1119 }
1120
1121 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001122 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001123 return true;
1124 }
1125
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001126 bool MergeResourceTable(io::IFile* file, bool override) {
1127 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001128 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1129 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001130 }
1131
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001132 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001133 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001134 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001135 return false;
1136 }
1137
1138 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001139 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001140 if (!table) {
1141 return false;
1142 }
1143
1144 bool result = false;
1145 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001146 result = table_merger_->MergeOverlay(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001147 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001148 result = table_merger_->Merge(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001149 }
1150 return result;
1151 }
1152
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001153 bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001154 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001155 context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
1156 << "' from compiled file "
1157 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001158 }
1159
1160 bool result = false;
1161 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001162 result = table_merger_->MergeFileOverlay(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001163 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001164 result = table_merger_->MergeFile(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001165 }
1166
1167 if (!result) {
1168 return false;
1169 }
1170
1171 // Add the exports of this file to the table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001172 for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
1173 if (exported_symbol.name.package.empty()) {
1174 exported_symbol.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001175 }
1176
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001177 ResourceNameRef res_name = exported_symbol.name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001178
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001179 Maybe<ResourceName> mangled_name =
1180 context_->GetNameMangler()->MangleName(exported_symbol.name);
1181 if (mangled_name) {
1182 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001183 }
1184
1185 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001186 id->SetSource(file_desc->source.WithLine(exported_symbol.line));
1187 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001188 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1189 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001190 if (!result) {
1191 return false;
1192 }
1193 }
1194 return true;
1195 }
1196
1197 /**
1198 * Takes a path to load as a ZIP file and merges the files within into the
1199 * master ResourceTable.
1200 * If override is true, conflicting resources are allowed to override each
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001201 * other, in order of last seen.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001202 *
1203 * An io::IFileCollection is created from the ZIP file and added to the set of
1204 * io::IFileCollections that are open.
1205 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001206 bool MergeArchive(const std::string& input, bool override) {
1207 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001208 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001209 }
1210
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001211 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001212 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001213 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001214 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001215 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001216 return false;
1217 }
1218
1219 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001220 for (auto iter = collection->Iterator(); iter->HasNext();) {
1221 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222 error = true;
1223 }
1224 }
1225
1226 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001227 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 return !error;
1229 }
1230
1231 /**
1232 * Takes a path to load and merge into the master ResourceTable. If override
1233 * is true,
1234 * conflicting resources are allowed to override each other, in order of last
1235 * seen.
1236 *
1237 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1238 * as ZIP archive
1239 * and the files within are merged individually.
1240 *
1241 * Otherwise the files is processed on its own.
1242 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001243 bool MergePath(const std::string& path, bool override) {
1244 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1245 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1246 return MergeArchive(path, override);
1247 } else if (util::EndsWith(path, ".apk")) {
1248 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249 }
1250
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001251 io::IFile* file = file_collection_->InsertFile(path);
1252 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253 }
1254
1255 /**
1256 * Takes a file to load and merge into the master ResourceTable. If override
1257 * is true,
1258 * conflicting resources are allowed to override each other, in order of last
1259 * seen.
1260 *
1261 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
1262 * merged into the
1263 * master ResourceTable. If the file ends with .flat, then it is treated like
1264 * a compiled file
1265 * and the header data is read and merged into the final ResourceTable.
1266 *
1267 * All other file types are ignored. This is because these files could be
1268 * coming from a zip,
1269 * where we could have other files like classes.dex.
1270 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001271 bool MergeFile(io::IFile* file, bool override) {
1272 const Source& src = file->GetSource();
1273 if (util::EndsWith(src.path, ".arsc.flat")) {
1274 return MergeResourceTable(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001275
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001276 } else if (util::EndsWith(src.path, ".flat")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001277 // Try opening the file and looking for an Export header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001278 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001279 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001280 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281 return false;
1282 }
1283
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001284 CompiledFileInputStream input_stream(data->data(), data->size());
1285 uint32_t num_files = 0;
1286 if (!input_stream.ReadLittleEndian32(&num_files)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001287 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001288 return false;
1289 }
1290
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001291 for (uint32_t i = 0; i < num_files; i++) {
1292 pb::CompiledFile compiled_file;
1293 if (!input_stream.ReadCompiledFile(&compiled_file)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001294 context_->GetDiagnostics()->Error(DiagMessage(src)
1295 << "failed to read compiled file header");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001296 return false;
Adam Lesinski467f1712015-11-16 17:35:44 -08001297 }
1298
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001299 uint64_t offset, len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001300 if (!input_stream.ReadDataMetaData(&offset, &len)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001301 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 return false;
1303 }
1304
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001305 std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
1306 compiled_file, file->GetSource(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001307 if (!resource_file) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 return false;
1309 }
1310
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001311 if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
1312 override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001313 return false;
1314 }
1315 }
1316 return true;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001317 } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001318 // Since AAPT compiles these file types and appends .flat to them, seeing
1319 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001320 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1321 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1322 << " file passed as argument. Must be "
1323 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001324 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001325 }
1326
1327 // Ignore non .flat files. This could be classes.dex or something else that
1328 // happens
1329 // to be in an archive.
1330 return true;
1331 }
1332
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001333 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1334 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1335 for (const std::string& assets_dir : options_.assets_dirs) {
1336 Maybe<std::vector<std::string>> files =
1337 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1338 if (!files) {
1339 return false;
1340 }
1341
1342 for (const std::string& file : files.value()) {
1343 std::string full_key = "assets/" + file;
1344 std::string full_path = assets_dir;
1345 file::AppendPath(&full_path, file);
1346
1347 auto iter = merged_assets.find(full_key);
1348 if (iter == merged_assets.end()) {
1349 merged_assets.emplace(std::move(full_key),
1350 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1351 } else if (context_->IsVerbose()) {
1352 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1353 << "asset file overrides '" << full_path << "'");
1354 }
1355 }
1356 }
1357
1358 for (auto& entry : merged_assets) {
1359 uint32_t compression_flags = ArchiveEntry::kCompress;
1360 std::string extension = file::GetExtension(entry.first).to_string();
1361 if (options_.extensions_to_not_compress.count(extension) > 0) {
1362 compression_flags = 0u;
1363 }
1364
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001365 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1366 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001367 return false;
1368 }
1369 }
1370 return true;
1371 }
1372
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001373 /**
1374 * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001375 * the ResourceTable to the IArchiveWriter.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001376 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001377 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1378 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001379 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskic744ae82017-05-17 19:28:38 -07001380 bool result = FlattenXml(context_, manifest, "AndroidManifest.xml", keep_raw_values, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001381 if (!result) {
1382 return false;
1383 }
1384
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001385 ResourceFileFlattenerOptions file_flattener_options;
1386 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001387 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1388 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 file_flattener_options.no_auto_version = options_.no_auto_version;
1390 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001391 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001392 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1393 file_flattener_options.update_proguard_spec =
1394 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001395
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001396 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001397
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001398 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001399 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001400 return false;
1401 }
1402
Adam Lesinskib522f042017-04-21 16:57:59 -07001403 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001404 if (!FlattenTableToPb(table, writer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001405 return false;
1406 }
1407 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001408 if (!FlattenTable(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001409 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001410 return false;
1411 }
1412 }
1413 return true;
1414 }
1415
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001416 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001417 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001418 std::unique_ptr<xml::XmlResource> manifest_xml =
1419 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1420 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001421 return 1;
1422 }
1423
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001424 // First extract the Package name without modifying it (via --rename-manifest-package).
1425 if (Maybe<AppInfo> maybe_app_info =
1426 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001427 const AppInfo& app_info = maybe_app_info.value();
1428 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429 }
1430
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001431 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1432 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001433 return 1;
1434 }
1435
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001436 Maybe<AppInfo> maybe_app_info =
1437 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001438 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001439 return 1;
1440 }
1441
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001442 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001443 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001444
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001445 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001446
1447 // Override the package ID when it is "android".
1448 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001449 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001450
1451 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001452 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001453 context_->GetDiagnostics()->Error(
1454 DiagMessage() << "package 'android' can only be built as a regular app");
1455 return 1;
1456 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001457 }
1458
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001459 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001460 return 1;
1461 }
1462
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001463 TableMergerOptions table_merger_options;
1464 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001465 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001466
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001467 if (context_->IsVerbose()) {
1468 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001469 << StringPrintf("linking package '%s' using package ID %02x",
1470 context_->GetCompilationPackage().data(),
1471 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001472 }
1473
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001474 for (const std::string& input : input_files) {
1475 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001476 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001477 return 1;
1478 }
1479 }
1480
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001481 for (const std::string& input : options_.overlay_files) {
1482 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001483 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001484 return 1;
1485 }
1486 }
1487
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001488 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001489 return 1;
1490 }
1491
Adam Lesinskib522f042017-04-21 16:57:59 -07001492 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001493 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001494 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001495 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001496 return 1;
1497 }
1498
1499 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001500 IdAssigner id_assigner(&options_.stable_id_map);
1501 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001502 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001503 return 1;
1504 }
1505
1506 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001507 if (options_.resource_id_map_path) {
1508 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001509 for (auto& type : package->types) {
1510 for (auto& entry : type->entries) {
1511 ResourceName name(package->name, type->type, entry->name);
1512 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001513 options_.stable_id_map[std::move(name)] =
1514 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001515 }
1516 }
1517 }
1518
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001519 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001520 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 return 1;
1522 }
1523 }
1524 } else {
1525 // Static libs are merged with other apps, and ID collisions are bad, so
1526 // verify that
1527 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001528 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001529 return 1;
1530 }
1531 }
1532
1533 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001534 context_->SetNameManglerPolicy(
1535 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001536
1537 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001538 context_->GetExternalSymbols()->PrependSource(
1539 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001540
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001541 // Workaround for pre-O runtime that would treat negative resource IDs
1542 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1543 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1544 // are just identifiers.
1545 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1546 if (context_->IsVerbose()) {
1547 context_->GetDiagnostics()->Note(DiagMessage()
1548 << "enabling pre-O feature split ID rewriting");
1549 }
1550 context_->GetExternalSymbols()->SetDelegate(
1551 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1552 }
1553
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001554 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001555 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001556 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001557 return 1;
1558 }
1559
Adam Lesinskib522f042017-04-21 16:57:59 -07001560 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001561 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001562 context_->GetDiagnostics()->Warn(DiagMessage()
1563 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001564 }
1565 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001566 ProductFilter product_filter(options_.products);
1567 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001568 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001569 return 1;
1570 }
1571 }
1572
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001573 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001574 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001575 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001576 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001577 return 1;
1578 }
1579 }
1580
Adam Lesinskib522f042017-04-21 16:57:59 -07001581 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001582 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001583 context_->GetDiagnostics()->Note(DiagMessage()
1584 << "collapsing resource versions for minimum SDK "
1585 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001586 }
1587
1588 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001589 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001590 return 1;
1591 }
1592 }
1593
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001594 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001595 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001596 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001597 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001598 return 1;
1599 }
1600 }
1601
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001602 proguard::KeepSet proguard_keep_set;
1603 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604
Adam Lesinskib522f042017-04-21 16:57:59 -07001605 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001606 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001607 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001608 context_->GetDiagnostics()->Warn(DiagMessage()
1609 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610 }
1611 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001612 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1613 // equal to the minSdk.
1614 options_.split_constraints =
1615 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001617 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001618 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001619 return 1;
1620 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001621 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001622
1623 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001624 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001625 auto split_constraints_iter = options_.split_constraints.begin();
1626 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001627 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001628 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1629 << "generating split with configurations '"
1630 << util::Joiner(split_constraints_iter->configs, ", ")
1631 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001632 }
1633
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001634 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001635 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001636 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001637 return 1;
1638 }
1639
1640 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001641 std::unique_ptr<xml::XmlResource> split_manifest =
1642 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001643
1644 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001645 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001646 context_->GetDiagnostics()->Error(DiagMessage()
1647 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001648 return 1;
1649 }
1650
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001651 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1652 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001653 return 1;
1654 }
1655
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001656 ++path_iter;
1657 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001658 }
1659 }
1660
1661 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001662 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001663 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001664 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001665 return 1;
1666 }
1667
1668 bool error = false;
1669 {
1670 // AndroidManifest.xml has no resource name, but the CallSite is built
1671 // from the name
1672 // (aka, which package the AndroidManifest.xml is coming from).
1673 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001674 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001675
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001676 XmlReferenceLinker manifest_linker;
1677 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1678 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001679 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1680 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681 error = true;
1682 }
1683
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001684 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001685 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1686 manifest_xml.get(),
1687 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001689 }
1690
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001691 if (options_.generate_java_class_path) {
1692 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001693 error = true;
1694 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001695 }
1696
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001697 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001698 // PackageParser will fail if URIs are removed from
1699 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001700 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1701 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001702 error = true;
1703 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001704 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001705 } else {
1706 error = true;
1707 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001708 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001709
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001710 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001711 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 return 1;
1713 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001714
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001715 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1716 return 1;
1717 }
1718
1719 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001720 return 1;
1721 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001722
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 if (options_.generate_java_class_path) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001724 // The set of packages whose R class to call in the main classes
1725 // onResourcesLoaded callback.
1726 std::vector<std::string> packages_to_callback;
1727
1728 JavaClassGeneratorOptions template_options;
1729 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1730 template_options.javadoc_annotations = options_.javadoc_annotations;
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001731
Adam Lesinskib522f042017-04-21 16:57:59 -07001732 if (context_->GetPackageType() == PackageType::kStaticLib ||
1733 options_.generate_non_final_ids) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001734 template_options.use_final = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001735 }
Adam Lesinski64587af2016-02-18 18:33:06 -08001736
Adam Lesinskib522f042017-04-21 16:57:59 -07001737 if (context_->GetPackageType() == PackageType::kSharedLib) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001738 template_options.use_final = false;
1739 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001740 }
1741
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 const StringPiece actual_package = context_->GetCompilationPackage();
1743 StringPiece output_package = context_->GetCompilationPackage();
1744 if (options_.custom_java_package) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001745 // Override the output java package to the custom one.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001746 output_package = options_.custom_java_package.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001747 }
1748
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001749 // Generate the private symbols if required.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001750 if (options_.private_symbols) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001751 packages_to_callback.push_back(options_.private_symbols.value());
1752
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 // If we defined a private symbols package, we only emit Public symbols
1754 // to the original package, and private and public symbols to the
1755 // private package.
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001756 JavaClassGeneratorOptions options = template_options;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001757 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001758 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001759 options)) {
1760 return 1;
1761 }
1762 }
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001763
1764 // Generate all the symbols for all extra packages.
1765 for (const std::string& extra_package : options_.extra_java_packages) {
1766 packages_to_callback.push_back(extra_package);
1767
1768 JavaClassGeneratorOptions options = template_options;
1769 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1770 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1771 return 1;
1772 }
1773 }
1774
1775 // Generate the main public R class.
1776 JavaClassGeneratorOptions options = template_options;
1777
1778 // Only generate public symbols if we have a private package.
1779 if (options_.private_symbols) {
1780 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1781 }
1782
1783 if (options.rewrite_callback_options) {
1784 options.rewrite_callback_options.value().packages_to_callback =
1785 std::move(packages_to_callback);
1786 }
1787
Adam Lesinski418763f2017-04-11 17:36:53 -07001788 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1789 options_.generate_text_symbols_path)) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001790 return 1;
1791 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001792 }
1793
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001794 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001795 return 1;
1796 }
1797
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001798 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1799 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 return 1;
1801 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001802 return 0;
1803 }
1804
1805 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001806 LinkOptions options_;
1807 LinkContext* context_;
1808 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001809
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001810 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001811
1812 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001813 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001814
1815 // A vector of IFileCollections. This is mainly here to keep ownership of the
1816 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001817 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001818
1819 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001820 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001821 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001822
1823 // The set of shared libraries being used, mapping their assigned package ID to package name.
1824 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001825};
1826
Chris Warrington820d72a2017-04-27 15:27:01 +01001827int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1828 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001830 std::vector<std::string> overlay_arg_list;
1831 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001832 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001833 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001834 Maybe<std::string> preferred_density;
1835 Maybe<std::string> product_list;
1836 bool legacy_x_flag = false;
1837 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001839 bool shared_lib = false;
1840 bool static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001841 Maybe<std::string> stable_id_file_path;
1842 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001843 Flags flags =
1844 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001845 .RequiredFlag("-o", "Output path.", &options.output_path)
1846 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001848 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001849 .OptionalFlagList("-A",
1850 "An assets directory to include in the APK. These are unprocessed.",
1851 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001852 .OptionalFlagList("-R",
1853 "Compilation unit to link, using `overlay` semantics.\n"
1854 "The last conflicting resource given takes precedence.",
1855 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001856 .OptionalFlag("--package-id",
1857 "Specify the package ID to use for this app. Must be greater or equal to\n"
1858 "0x7f and can't be used with --static-lib or --shared-lib.",
1859 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001860 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001861 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001862 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001863 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001864 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001865 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001866 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001867 .OptionalSwitch("--no-auto-version",
1868 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 &options.no_auto_version)
1870 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 "Disables automatic versioning of vector drawables. Use this only\n"
1872 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001873 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001874 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001875 "Disables automatic versioning of transition resources. Use this only\n"
1876 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001877 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001878 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001879 "Disables automatic deduping of resources with\n"
1880 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001881 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001882 .OptionalSwitch("--enable-sparse-encoding",
1883 "Enables encoding sparse entries using a binary search tree.\n"
1884 "This decreases APK size at the cost of resource retrieval performance.",
1885 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001886 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001887 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001888 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001889 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001890 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001891 "Comma separated list of configurations to include. The default\n"
1892 "is all configurations.",
1893 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001894 .OptionalFlag("--preferred-density",
1895 "Selects the closest matching density and strips out all others.",
1896 &preferred_density)
1897 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001898 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001899 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001900 &options.output_to_directory)
1901 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001902 "Removes XML namespace prefix and URI information from\n"
1903 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 &options.no_xml_namespaces)
1905 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001906 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001908 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001909 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001910 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001911 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1913 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001914 &options.manifest_fixer_options.version_code_default)
1915 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001916 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001917 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001918 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1919 &shared_lib)
1920 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001921 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 &options.no_static_lib_packages)
1924 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001925 "Generates R.java without the final modifier. This is implied when\n"
1926 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001928 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001930 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 "Emit a file at the given path with a list of name to ID mappings,\n"
1932 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001933 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001934 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001935 "Package name to use when generating R.java for private symbols.\n"
1936 "If not specified, public and private symbols will use the application's\n"
1937 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001939 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 &options.custom_java_package)
1941 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001942 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001943 &extra_java_packages)
1944 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001947 .OptionalFlag("--output-text-symbols",
1948 "Generates a text file containing the resource symbols of the R class in\n"
1949 "the specified folder.",
1950 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001951 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001952 "Allows the addition of new resources in overlays without\n"
1953 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001954 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001955 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001956 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001957 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001958 "Changes the name of the target package for instrumentation. Most useful\n"
1959 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001960 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001961 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001962 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001963 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001965 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1966 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001967 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001968 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001969
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001970 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001971 return 1;
1972 }
1973
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001974 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001975 std::vector<std::string> arg_list;
1976 for (const std::string& arg : flags.GetArgs()) {
1977 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001978 const std::string path = arg.substr(1, arg.size() - 1);
1979 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001980 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1981 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001982 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001983 }
1984 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001985 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001986 }
1987 }
1988
1989 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001990 for (const std::string& arg : overlay_arg_list) {
1991 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001992 const std::string path = arg.substr(1, arg.size() - 1);
1993 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001994 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
1995 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001996 return 1;
1997 }
1998 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001999 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002000 }
2001 }
2002
2003 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002004 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002005 }
2006
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002007 if (shared_lib && static_lib) {
2008 context.GetDiagnostics()->Error(DiagMessage()
2009 << "only one of --shared-lib and --static-lib can be defined");
2010 return 1;
2011 }
2012
2013 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002014 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002015 context.SetPackageId(0x00);
2016 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002017 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002018 context.SetPackageId(kAppPackageId);
2019 } else {
Adam Lesinskib522f042017-04-21 16:57:59 -07002020 context.SetPackageType(PackageType::kApp);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002021 context.SetPackageId(kAppPackageId);
2022 }
2023
2024 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002025 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002026 context.GetDiagnostics()->Error(
2027 DiagMessage() << "can't specify --package-id when not building a regular app");
2028 return 1;
2029 }
2030
2031 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2032 if (!maybe_package_id_int) {
2033 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2034 << "' is not a valid integer");
2035 return 1;
2036 }
2037
2038 const uint32_t package_id_int = maybe_package_id_int.value();
2039 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2040 context.GetDiagnostics()->Error(
2041 DiagMessage() << StringPrintf(
2042 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2043 return 1;
2044 }
2045 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2046 }
2047
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002048 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002049 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002050 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002051 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002052 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002053 }
2054 }
2055
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002056 if (product_list) {
2057 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002058 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002059 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002060 }
2061 }
2062 }
2063
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002064 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002065 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002066 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2067 if (filter == nullptr) {
2068 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002069 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002070 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002071 }
2072
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002073 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002074 Maybe<uint16_t> density =
2075 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2076 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002078 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002079 options.table_splitter_options.preferred_densities.push_back(density.value());
2080 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002081
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002082 // Parse the split parameters.
2083 for (const std::string& split_arg : split_args) {
2084 options.split_paths.push_back({});
2085 options.split_constraints.push_back({});
2086 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2087 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002088 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002089 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002090 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002091
Adam Lesinskib522f042017-04-21 16:57:59 -07002092 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002093 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2094 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002095 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002096 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002097 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002098
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002099 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002100 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002101 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2102 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2103 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2104 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2105
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002106 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002107 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002108 options.no_auto_version = true;
2109 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002110 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002111 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002112
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002113 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002115}
2116
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117} // namespace aapt