blob: d4ff6188d48dcbcd2c9266a3b6553d593219d9f4 [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 Lesinskiefeb7af2017-08-02 14:57:43 -070043#include "io/FileInputStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080044#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070045#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080046#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070047#include "java/JavaClassGenerator.h"
48#include "java/ManifestClassGenerator.h"
49#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070050#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070051#include "link/ManifestFixer.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080052#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070053#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070054#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080055#include "optimize/ResourceDeduper.h"
56#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070057#include "process/IResourceTableConsumer.h"
58#include "process/SymbolTable.h"
Adam Lesinski59e04c62016-02-04 15:59:23 -080059#include "proto/ProtoSerialize.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080060#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070061#include "unflatten/BinaryResourceParser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070062#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080063#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070065using ::aapt::io::FileInputStream;
66using ::android::StringPiece;
67using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070068
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069namespace aapt {
70
71struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070072 std::string output_path;
73 std::string manifest_path;
74 std::vector<std::string> include_paths;
75 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070076 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070077 bool output_to_directory = false;
78 bool auto_add_overlay = false;
Adam Lesinski36c73a52016-08-11 13:39:24 -070079
Adam Lesinskicacb28f2016-10-19 12:18:14 -070080 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070081 Maybe<std::string> generate_java_class_path;
82 Maybe<std::string> custom_java_package;
83 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070084 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070085 Maybe<std::string> generate_proguard_rules_path;
86 Maybe<std::string> generate_main_dex_proguard_rules_path;
87 bool generate_non_final_ids = false;
88 std::vector<std::string> javadoc_annotations;
89 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -070090
Adam Lesinskice5e56e2016-10-21 17:56:45 -070091 // Optimizations/features.
92 bool no_auto_version = false;
93 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +090094 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070095 bool no_resource_deduping = false;
96 bool no_xml_namespaces = false;
97 bool do_not_compress_anything = false;
98 std::unordered_set<std::string> extensions_to_not_compress;
99
100 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700101 bool no_static_lib_packages = false;
102
103 // AndroidManifest.xml massaging options.
104 ManifestFixerOptions manifest_fixer_options;
105
106 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700107 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700108
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800109 // Flattening options.
110 TableFlattenerOptions table_flattener_options;
111
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700112 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 TableSplitterOptions table_splitter_options;
114 std::vector<SplitConstraints> split_constraints;
115 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700116
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700117 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700118 std::unordered_map<ResourceName, ResourceId> stable_id_map;
119 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700120};
121
Adam Lesinski64587af2016-02-18 18:33:06 -0800122class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700123 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100124 LinkContext(IDiagnostics* diagnostics)
125 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700126 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700127
Adam Lesinskib522f042017-04-21 16:57:59 -0700128 PackageType GetPackageType() override {
129 return package_type_;
130 }
131
132 void SetPackageType(PackageType type) {
133 package_type_ = type;
134 }
135
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100137 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700140 NameMangler* GetNameMangler() override {
141 return &name_mangler_;
142 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700143
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700144 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
145 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700146 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800147
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700148 const std::string& GetCompilationPackage() override {
149 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700150 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700151
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700152 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800153 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700154 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800155
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700156 uint8_t GetPackageId() override {
157 return package_id_;
158 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700159
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700160 void SetPackageId(uint8_t id) {
161 package_id_ = id;
162 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800163
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700164 SymbolTable* GetExternalSymbols() override {
165 return &symbols_;
166 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168 bool IsVerbose() override {
169 return verbose_;
170 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800171
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700172 void SetVerbose(bool val) {
173 verbose_ = val;
174 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 int GetMinSdkVersion() override {
177 return min_sdk_version_;
178 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700179
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700180 void SetMinSdkVersion(int minSdk) {
181 min_sdk_version_ = minSdk;
182 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700183
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700184 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700185 DISALLOW_COPY_AND_ASSIGN(LinkContext);
186
Adam Lesinskib522f042017-04-21 16:57:59 -0700187 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100188 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700189 NameMangler name_mangler_;
190 std::string compilation_package_;
191 uint8_t package_id_ = 0x0;
192 SymbolTable symbols_;
193 bool verbose_ = false;
194 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700195};
196
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700197// A custom delegate that generates compatible pre-O IDs for use with feature splits.
198// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
199// is interpreted as a negative number. Some verification was wrongly assuming negative values
200// were invalid.
201//
202// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
203// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
204// an overlap exists.
205class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
206 public:
207 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
208 }
209
210 virtual ~FeatureSplitSymbolTableDelegate() = default;
211
212 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
213 const ResourceName& name,
214 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
215 std::unique_ptr<SymbolTable::Symbol> symbol =
216 DefaultSymbolTableDelegate::FindByName(name, sources);
217 if (symbol == nullptr) {
218 return {};
219 }
220
221 // Check to see if this is an 'id' with the target package.
222 if (name.type == ResourceType::kId && symbol->id) {
223 ResourceId* id = &symbol->id.value();
224 if (id->package_id() > kAppPackageId) {
225 // Rewrite the resource ID to be compatible pre-O.
226 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
227
228 // Check that this doesn't overlap another resource.
229 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
230 // The ID overlaps, so log a message (since this is a weird failure) and fail.
231 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
232 << " for pre-O feature split support");
233 return {};
234 }
235
236 if (context_->IsVerbose()) {
237 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
238 << ") -> (" << rewritten_id << ")");
239 }
240
241 *id = rewritten_id;
242 }
243 }
244 return symbol;
245 }
246
247 private:
248 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
249
250 IAaptContext* context_;
251};
252
Adam Lesinskic744ae82017-05-17 19:28:38 -0700253static bool FlattenXml(IAaptContext* context, xml::XmlResource* xml_res, const StringPiece& path,
254 bool keep_raw_values, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700255 BigBuffer buffer(1024);
256 XmlFlattenerOptions options = {};
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700257 options.keep_raw_values = keep_raw_values;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700258 XmlFlattener flattener(&buffer, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700259 if (!flattener.Consume(context, xml_res)) {
Adam Lesinski355f2852016-02-13 20:26:45 -0800260 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700261 }
262
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700263 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700264 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
265 << (keep_raw_values ? "true" : "false")
266 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700267 }
268
Adam Lesinski06460ef2017-03-14 18:52:13 -0700269 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700270 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
271 ArchiveEntry::kCompress, writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800272}
273
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700274static std::unique_ptr<ResourceTable> LoadTableFromPb(const Source& source, const void* data,
275 size_t len, IDiagnostics* diag) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700276 pb::ResourceTable pb_table;
277 if (!pb_table.ParseFromArray(data, len)) {
278 diag->Error(DiagMessage(source) << "invalid compiled table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700279 return {};
280 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800281
Adam Lesinski06460ef2017-03-14 18:52:13 -0700282 std::unique_ptr<ResourceTable> table = DeserializeTableFromPb(pb_table, source, diag);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700283 if (!table) {
284 return {};
285 }
286 return table;
Adam Lesinski355f2852016-02-13 20:26:45 -0800287}
288
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700289// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700290static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700291 FileInputStream fin(path);
292 if (fin.HadError()) {
293 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
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 Lesinskibb94f322017-07-12 07:41:55 -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 Lesinskibb94f322017-07-12 07:41:55 -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
Adam Lesinskibb94f322017-07-12 07:41:55 -0700434static bool IsTransitionElement(const std::string& name) {
435 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";
440}
441
442static bool IsVectorElement(const std::string& name) {
443 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
444 name == "objectAnimator";
445}
446
Adam Lesinskic744ae82017-05-17 19:28:38 -0700447template <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 Lesinskibb94f322017-07-12 07:41:55 -0700479 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 return make_singleton_vec(std::move(file_op->xml_to_flatten));
481 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700482
Adam Lesinskibb94f322017-07-12 07:41:55 -0700483 if (options_.no_version_vectors || options_.no_version_transitions) {
484 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700485 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700486 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));
490 }
491 }
492 }
493
Adam Lesinskic744ae82017-05-17 19:28:38 -0700494 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();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700511 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 Lesinskibb94f322017-07-12 07:41:55 -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);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700577 if (versioned_docs.empty()) {
578 error = true;
579 continue;
580 }
581
Adam Lesinskic744ae82017-05-17 19:28:38 -0700582 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
583 std::string dst_path = file_op.dst_path;
584 if (doc->file.config != file_op.config) {
585 // Only add the new versioned configurations.
586 if (context_->IsVerbose()) {
587 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
588 << "auto-versioning resource from config '"
589 << config << "' -> '" << doc->file.config << "'");
590 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700591
Adam Lesinskic744ae82017-05-17 19:28:38 -0700592 dst_path =
593 ResourceUtils::BuildResourceFileName(doc->file, context_->GetNameMangler());
594 bool result = table->AddFileReferenceAllowMangled(doc->file.name, doc->file.config,
595 doc->file.source, dst_path, nullptr,
596 context_->GetDiagnostics());
597 if (!result) {
598 return false;
599 }
600 }
601 error |= !FlattenXml(context_, doc.get(), dst_path, options_.keep_raw_values,
602 archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700603 }
604 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700605 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
606 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700607 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700609 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700610 }
611 return !error;
612}
613
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700614static bool WriteStableIdMapToPath(IDiagnostics* diag,
615 const std::unordered_map<ResourceName, ResourceId>& id_map,
616 const std::string& id_map_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700617 std::ofstream fout(id_map_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700618 if (!fout) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700619 diag->Error(DiagMessage(id_map_path) << strerror(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620 return false;
621 }
622
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700623 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624 const ResourceName& name = entry.first;
625 const ResourceId& id = entry.second;
626 fout << name << " = " << id << "\n";
627 }
628
629 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700630 diag->Error(DiagMessage(id_map_path) << "failed writing to file: "
631 << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700632 return false;
633 }
634
635 return true;
636}
637
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700638static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
639 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700640 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700641 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700642 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700643 return false;
644 }
645
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700646 out_id_map->clear();
647 size_t line_no = 0;
648 for (StringPiece line : util::Tokenize(content, '\n')) {
649 line_no++;
650 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700651 if (line.empty()) {
652 continue;
653 }
654
655 auto iter = std::find(line.begin(), line.end(), '=');
656 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700657 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700658 return false;
659 }
660
661 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700662 StringPiece res_name_str =
663 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
664 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700665 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
666 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700667 return false;
668 }
669
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700670 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
671 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700672 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700673
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700674 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
675 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700676 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
677 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700678 return false;
679 }
680
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700681 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700682 }
683 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700684}
685
Adam Lesinskifb48d292015-11-07 15:52:13 -0800686class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700687 public:
688 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700689 : options_(options),
690 context_(context),
691 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700692 file_collection_(util::make_unique<io::FileCollection>()) {
693 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700694
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700695 /**
696 * Creates a SymbolTable that loads symbols from the various APKs and caches
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700697 * the results for faster lookup.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700699 bool LoadSymbolsFromIncludePaths() {
700 std::unique_ptr<AssetManagerSymbolSource> asset_source =
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700702 for (const std::string& path : options_.include_paths) {
703 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700704 context_->GetDiagnostics()->Note(DiagMessage(path) << "loading include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700705 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700706
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700707 // First try to load the file as a static lib.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700708 std::string error_str;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800709 std::unique_ptr<ResourceTable> include_static = LoadStaticLibrary(path, &error_str);
710 if (include_static) {
Adam Lesinskib522f042017-04-21 16:57:59 -0700711 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800712 // Can't include static libraries when not building a static library (they have no IDs
713 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700714 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800715 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
719 // If we are using --no-static-lib-packages, we need to rename the
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800720 // package of this table to our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700721 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800722 // Since package names can differ, and multiple packages can exist in a ResourceTable,
723 // we place the requirement that all static libraries are built with the package
724 // ID 0x7f. So if one is not found, this is an error.
725 if (ResourceTablePackage* pkg = include_static->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700726 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800727 } else {
728 context_->GetDiagnostics()->Error(DiagMessage(path)
729 << "no package with ID 0x7f found in static library");
730 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731 }
732 }
733
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700734 context_->GetExternalSymbols()->AppendSource(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800735 util::make_unique<ResourceTableSymbolSource>(include_static.get()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800737 static_table_includes_.push_back(std::move(include_static));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700738
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 } else if (!error_str.empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 // We had an error with reading, so fail.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700741 context_->GetDiagnostics()->Error(DiagMessage(path) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700742 return false;
743 }
744
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700745 if (!asset_source->AddAssetPath(path)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800746 context_->GetDiagnostics()->Error(DiagMessage(path) << "failed to load include path");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700747 return false;
748 }
749 }
750
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800751 // Capture the shared libraries so that the final resource table can be properly flattened
752 // with support for shared libraries.
753 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800754 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800755 final_table_.included_packages_[entry.first] = entry.second;
756 }
757 }
758
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700759 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700760 return true;
761 }
762
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800763 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700764 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800765 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
766 if (manifest_el == nullptr) {
767 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700768 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800769
770 AppInfo app_info;
771
772 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
773 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
774 return {};
775 }
776
777 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
778 if (!package_attr) {
779 diag->Error(DiagMessage(xml_res->file.source)
780 << "<manifest> must have a 'package' attribute");
781 return {};
782 }
783 app_info.package = package_attr->value;
784
785 if (xml::Attribute* version_code_attr =
786 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
787 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
788 if (!maybe_code) {
789 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
790 << "invalid android:versionCode '" << version_code_attr->value << "'");
791 return {};
792 }
793 app_info.version_code = maybe_code.value();
794 }
795
796 if (xml::Attribute* revision_code_attr =
797 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
798 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
799 if (!maybe_code) {
800 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
801 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
802 return {};
803 }
804 app_info.revision_code = maybe_code.value();
805 }
806
807 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
808 if (!split_name_attr->value.empty()) {
809 app_info.split_name = split_name_attr->value;
810 }
811 }
812
813 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
814 if (xml::Attribute* min_sdk =
815 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700816 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800817 }
818 }
819 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700820 }
821
822 /**
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800823 * Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700824 * Postcondition: ResourceTable has only one package left. All others are
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700825 * stripped, or there is an error and false is returned.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700826 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700827 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700828 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700829 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
830 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700831 };
832
833 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700834 for (const auto& package : final_table_.packages) {
835 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700836 // We have a package that is not related to the one we're building!
837 for (const auto& type : package->types) {
838 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700839 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700840
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700841 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700842 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700843 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700844 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
845 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
846 << "generated id '" << res_name
847 << "' for external package '" << package->name
848 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700849 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700850 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
851 << "defined resource '" << res_name
852 << "' for external package '" << package->name
853 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700854 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700855 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700856 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700857 }
858 }
859 }
860 }
861
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700862 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
863 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700864 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700865 return !error;
866 }
867
868 /**
869 * Returns true if no IDs have been set, false otherwise.
870 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700871 bool VerifyNoIdsSet() {
872 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700873 for (const auto& type : package->types) {
874 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800875 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
876 << StringPrintf("%02x", type->id.value())
877 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700878 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700879 }
880
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700881 for (const auto& entry : type->entries) {
882 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700883 ResourceNameRef res_name(package->name, type->type, entry->name);
884 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800885 DiagMessage() << "entry " << res_name << " has ID "
886 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700887 return false;
888 }
889 }
890 }
891 }
892 return true;
893 }
894
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700895 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
896 if (options_.output_to_directory) {
897 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700898 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700899 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700900 }
901 }
902
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700903 bool FlattenTable(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700904 BigBuffer buffer(1024);
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800905 TableFlattener flattener(options_.table_flattener_options, &buffer);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700906 if (!flattener.Consume(context_, table)) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700907 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700908 return false;
909 }
910
Adam Lesinski06460ef2017-03-14 18:52:13 -0700911 io::BigBufferInputStream input_stream(&buffer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700912 return io::CopyInputStreamToArchive(context_, &input_stream, "resources.arsc",
913 ArchiveEntry::kAlign, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700914 }
915
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700916 bool FlattenTableToPb(ResourceTable* table, IArchiveWriter* writer) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700917 std::unique_ptr<pb::ResourceTable> pb_table = SerializeTableToPb(table);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700918 return io::CopyProtoToArchive(context_, pb_table.get(), "resources.arsc.flat", 0, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700919 }
920
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700921 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -0700922 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -0700923 const Maybe<std::string>& out_text_symbols_path = {}) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700924 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700925 return true;
926 }
927
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700928 std::string out_path = options_.generate_java_class_path.value();
929 file::AppendPath(&out_path, file::PackageToPath(out_package));
930 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700931 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
932 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700933 return false;
934 }
935
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700936 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700937
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700938 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700939 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700940 context_->GetDiagnostics()->Error(DiagMessage()
941 << "failed writing to '" << out_path
942 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700943 return false;
944 }
945
Adam Lesinski418763f2017-04-11 17:36:53 -0700946 std::unique_ptr<std::ofstream> fout_text;
947 if (out_text_symbols_path) {
948 fout_text =
949 util::make_unique<std::ofstream>(out_text_symbols_path.value(), std::ofstream::binary);
950 if (!*fout_text) {
951 context_->GetDiagnostics()->Error(
952 DiagMessage() << "failed writing to '" << out_text_symbols_path.value()
953 << "': " << android::base::SystemErrorCodeToString(errno));
954 return false;
955 }
956 }
957
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700958 JavaClassGenerator generator(context_, table, java_options);
Adam Lesinski418763f2017-04-11 17:36:53 -0700959 if (!generator.Generate(package_name_to_generate, out_package, &fout, fout_text.get())) {
Adam Lesinski06460ef2017-03-14 18:52:13 -0700960 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.getError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700961 return false;
962 }
963
964 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700965 context_->GetDiagnostics()->Error(DiagMessage()
966 << "failed writing to '" << out_path
967 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700968 }
969 return true;
970 }
971
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700972 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
973 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700974 return true;
975 }
976
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700977 std::unique_ptr<ClassDefinition> manifest_class =
978 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700979
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700980 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700981 // Something bad happened, but we already logged it, so exit.
982 return false;
983 }
984
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700986 // Empty Manifest class, no need to generate it.
987 return true;
988 }
989
990 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700991 for (const std::string& annotation : options_.javadoc_annotations) {
992 std::string proper_annotation = "@";
993 proper_annotation += annotation;
994 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700995 }
996
Adam Lesinski0d81f702017-06-27 15:51:09 -0700997 const std::string package_utf8 =
998 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700999
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001000 std::string out_path = options_.generate_java_class_path.value();
1001 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001002
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001003 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001004 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1005 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001006 return false;
1007 }
1008
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001009 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001010
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001011 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001012 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001013 context_->GetDiagnostics()->Error(DiagMessage()
1014 << "failed writing to '" << out_path
1015 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001016 return false;
1017 }
1018
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001019 if (!ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout)) {
1020 context_->GetDiagnostics()->Error(DiagMessage()
1021 << "failed writing to '" << out_path
1022 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001023 return false;
1024 }
1025 return true;
1026 }
1027
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001028 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 if (!out) {
1030 return true;
1031 }
1032
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001033 const std::string& out_path = out.value();
1034 std::ofstream fout(out_path, std::ofstream::binary);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001035 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001036 context_->GetDiagnostics()->Error(DiagMessage()
1037 << "failed to open '" << out_path
1038 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001039 return false;
1040 }
1041
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001042 proguard::WriteKeepSet(&fout, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001043 if (!fout) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001044 context_->GetDiagnostics()->Error(DiagMessage()
1045 << "failed writing to '" << out_path
1046 << "': " << android::base::SystemErrorCodeToString(errno));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001047 return false;
1048 }
1049 return true;
1050 }
1051
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001052 std::unique_ptr<ResourceTable> LoadStaticLibrary(const std::string& input,
1053 std::string* out_error) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001055 io::ZipFileCollection::Create(input, out_error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001056 if (!collection) {
1057 return {};
1058 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001059 return LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001060 }
1061
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001062 std::unique_ptr<ResourceTable> LoadTablePbFromCollection(io::IFileCollection* collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001063 io::IFile* file = collection->FindFile("resources.arsc.flat");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001064 if (!file) {
1065 return {};
1066 }
1067
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001068 std::unique_ptr<io::IData> data = file->OpenAsData();
1069 return LoadTableFromPb(file->GetSource(), data->data(), data->size(),
1070 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001071 }
1072
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001073 bool MergeStaticLibrary(const std::string& input, bool override) {
1074 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001075 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001076 }
1077
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001078 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001079 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001080 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001081 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001082 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001083 return false;
1084 }
1085
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001086 std::unique_ptr<ResourceTable> table = LoadTablePbFromCollection(collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001087 if (!table) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001088 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001089 return false;
1090 }
1091
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001092 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001093 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001094 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001095 return false;
1096 }
1097
1098 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001099 if (options_.no_static_lib_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001100 // Merge all resources as if they were in the compilation package. This is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001101 // the old behavior of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001102
1103 // Add the package to the set of --extra-packages so we emit an R.java for
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001104 // each library package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001105 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001106 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001107 }
1108
1109 pkg->name = "";
1110 if (override) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001111 result = table_merger_->MergeOverlay(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001112 } else {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001113 result = table_merger_->Merge(Source(input), table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001114 }
1115
1116 } else {
1117 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001118 // preserved and resource names are mangled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001119 result =
1120 table_merger_->MergeAndMangle(Source(input), pkg->name, table.get(), collection.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001121 }
1122
1123 if (!result) {
1124 return false;
1125 }
1126
1127 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001128 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001129 return true;
1130 }
1131
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001132 bool MergeResourceTable(io::IFile* file, bool override) {
1133 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001134 context_->GetDiagnostics()->Note(DiagMessage() << "merging resource table "
1135 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001136 }
1137
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001138 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001139 if (!data) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001140 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource()) << "failed to open file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001141 return false;
1142 }
1143
1144 std::unique_ptr<ResourceTable> table =
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001145 LoadTableFromPb(file->GetSource(), data->data(), data->size(), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001146 if (!table) {
1147 return false;
1148 }
1149
1150 bool result = false;
1151 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001152 result = table_merger_->MergeOverlay(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001153 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001154 result = table_merger_->Merge(file->GetSource(), table.get());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001155 }
1156 return result;
1157 }
1158
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001159 bool MergeCompiledFile(io::IFile* file, ResourceFile* file_desc, bool override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001160 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001161 context_->GetDiagnostics()->Note(DiagMessage() << "merging '" << file_desc->name
1162 << "' from compiled file "
1163 << file->GetSource());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001164 }
1165
1166 bool result = false;
1167 if (override) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001168 result = table_merger_->MergeFileOverlay(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001169 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001170 result = table_merger_->MergeFile(*file_desc, file);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001171 }
1172
1173 if (!result) {
1174 return false;
1175 }
1176
1177 // Add the exports of this file to the table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001178 for (SourcedResourceName& exported_symbol : file_desc->exported_symbols) {
1179 if (exported_symbol.name.package.empty()) {
1180 exported_symbol.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001181 }
1182
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001183 ResourceNameRef res_name = exported_symbol.name;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001184
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001185 Maybe<ResourceName> mangled_name =
1186 context_->GetNameMangler()->MangleName(exported_symbol.name);
1187 if (mangled_name) {
1188 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001189 }
1190
1191 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001192 id->SetSource(file_desc->source.WithLine(exported_symbol.line));
1193 bool result = final_table_.AddResourceAllowMangled(
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001194 res_name, ConfigDescription::DefaultConfig(), std::string(), std::move(id),
1195 context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001196 if (!result) {
1197 return false;
1198 }
1199 }
1200 return true;
1201 }
1202
1203 /**
1204 * Takes a path to load as a ZIP file and merges the files within into the
1205 * master ResourceTable.
1206 * If override is true, conflicting resources are allowed to override each
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001207 * other, in order of last seen.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001208 *
1209 * An io::IFileCollection is created from the ZIP file and added to the set of
1210 * io::IFileCollections that are open.
1211 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001212 bool MergeArchive(const std::string& input, bool override) {
1213 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001214 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001215 }
1216
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001217 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001218 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001219 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001220 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001221 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222 return false;
1223 }
1224
1225 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001226 for (auto iter = collection->Iterator(); iter->HasNext();) {
1227 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001228 error = true;
1229 }
1230 }
1231
1232 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001233 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001234 return !error;
1235 }
1236
1237 /**
1238 * Takes a path to load and merge into the master ResourceTable. If override
1239 * is true,
1240 * conflicting resources are allowed to override each other, in order of last
1241 * seen.
1242 *
1243 * If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1244 * as ZIP archive
1245 * and the files within are merged individually.
1246 *
1247 * Otherwise the files is processed on its own.
1248 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001249 bool MergePath(const std::string& path, bool override) {
1250 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1251 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1252 return MergeArchive(path, override);
1253 } else if (util::EndsWith(path, ".apk")) {
1254 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001255 }
1256
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001257 io::IFile* file = file_collection_->InsertFile(path);
1258 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001259 }
1260
1261 /**
1262 * Takes a file to load and merge into the master ResourceTable. If override
1263 * is true,
1264 * conflicting resources are allowed to override each other, in order of last
1265 * seen.
1266 *
1267 * If the file ends with .arsc.flat, then it is loaded as a ResourceTable and
1268 * merged into the
1269 * master ResourceTable. If the file ends with .flat, then it is treated like
1270 * a compiled file
1271 * and the header data is read and merged into the final ResourceTable.
1272 *
1273 * All other file types are ignored. This is because these files could be
1274 * coming from a zip,
1275 * where we could have other files like classes.dex.
1276 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001277 bool MergeFile(io::IFile* file, bool override) {
1278 const Source& src = file->GetSource();
1279 if (util::EndsWith(src.path, ".arsc.flat")) {
1280 return MergeResourceTable(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001281
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001282 } else if (util::EndsWith(src.path, ".flat")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001283 // Try opening the file and looking for an Export header.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001284 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001285 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001286 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001287 return false;
1288 }
1289
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001290 CompiledFileInputStream input_stream(data->data(), data->size());
1291 uint32_t num_files = 0;
1292 if (!input_stream.ReadLittleEndian32(&num_files)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001293 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed read num files");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001294 return false;
1295 }
1296
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001297 for (uint32_t i = 0; i < num_files; i++) {
Adam Lesinski4ffea042017-08-10 15:37:28 -07001298 pb::internal::CompiledFile compiled_file;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001299 if (!input_stream.ReadCompiledFile(&compiled_file)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001300 context_->GetDiagnostics()->Error(DiagMessage(src)
1301 << "failed to read compiled file header");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001302 return false;
Adam Lesinski467f1712015-11-16 17:35:44 -08001303 }
1304
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001305 uint64_t offset, len;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001306 if (!input_stream.ReadDataMetaData(&offset, &len)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001307 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read data meta data");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001308 return false;
1309 }
1310
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001311 std::unique_ptr<ResourceFile> resource_file = DeserializeCompiledFileFromPb(
1312 compiled_file, file->GetSource(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001313 if (!resource_file) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001314 return false;
1315 }
1316
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001317 if (!MergeCompiledFile(file->CreateFileSegment(offset, len), resource_file.get(),
1318 override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001319 return false;
1320 }
1321 }
1322 return true;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001323 } else if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001324 // Since AAPT compiles these file types and appends .flat to them, seeing
1325 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001326 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1327 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1328 << " file passed as argument. Must be "
1329 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001330 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001331 }
1332
1333 // Ignore non .flat files. This could be classes.dex or something else that
1334 // happens
1335 // to be in an archive.
1336 return true;
1337 }
1338
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001339 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1340 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1341 for (const std::string& assets_dir : options_.assets_dirs) {
1342 Maybe<std::vector<std::string>> files =
1343 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1344 if (!files) {
1345 return false;
1346 }
1347
1348 for (const std::string& file : files.value()) {
1349 std::string full_key = "assets/" + file;
1350 std::string full_path = assets_dir;
1351 file::AppendPath(&full_path, file);
1352
1353 auto iter = merged_assets.find(full_key);
1354 if (iter == merged_assets.end()) {
1355 merged_assets.emplace(std::move(full_key),
1356 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1357 } else if (context_->IsVerbose()) {
1358 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1359 << "asset file overrides '" << full_path << "'");
1360 }
1361 }
1362 }
1363
1364 for (auto& entry : merged_assets) {
1365 uint32_t compression_flags = ArchiveEntry::kCompress;
1366 std::string extension = file::GetExtension(entry.first).to_string();
1367 if (options_.extensions_to_not_compress.count(extension) > 0) {
1368 compression_flags = 0u;
1369 }
1370
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001371 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1372 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001373 return false;
1374 }
1375 }
1376 return true;
1377 }
1378
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001379 /**
1380 * Writes the AndroidManifest, ResourceTable, and all XML files referenced by
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001381 * the ResourceTable to the IArchiveWriter.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001382 */
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001383 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1384 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001385 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskic744ae82017-05-17 19:28:38 -07001386 bool result = FlattenXml(context_, manifest, "AndroidManifest.xml", keep_raw_values, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001387 if (!result) {
1388 return false;
1389 }
1390
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001391 ResourceFileFlattenerOptions file_flattener_options;
1392 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001393 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1394 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001395 file_flattener_options.no_auto_version = options_.no_auto_version;
1396 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001397 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001398 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1399 file_flattener_options.update_proguard_spec =
1400 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001401
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001402 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001403
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001404 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001405 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001406 return false;
1407 }
1408
Adam Lesinskib522f042017-04-21 16:57:59 -07001409 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 if (!FlattenTableToPb(table, writer)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 return false;
1412 }
1413 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001414 if (!FlattenTable(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001415 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resources.arsc");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001416 return false;
1417 }
1418 }
1419 return true;
1420 }
1421
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001422 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001423 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001424 std::unique_ptr<xml::XmlResource> manifest_xml =
1425 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1426 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001427 return 1;
1428 }
1429
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001430 // First extract the Package name without modifying it (via --rename-manifest-package).
1431 if (Maybe<AppInfo> maybe_app_info =
1432 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001433 const AppInfo& app_info = maybe_app_info.value();
1434 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001435 }
1436
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001437 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1438 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001439 return 1;
1440 }
1441
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001442 Maybe<AppInfo> maybe_app_info =
1443 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001444 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001445 return 1;
1446 }
1447
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001448 const AppInfo& app_info = maybe_app_info.value();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001449 context_->SetMinSdkVersion(app_info.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001450
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001451 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001452
1453 // Override the package ID when it is "android".
1454 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001455 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001456
1457 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001458 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001459 context_->GetDiagnostics()->Error(
1460 DiagMessage() << "package 'android' can only be built as a regular app");
1461 return 1;
1462 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001463 }
1464
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001465 if (!LoadSymbolsFromIncludePaths()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001466 return 1;
1467 }
1468
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001469 TableMergerOptions table_merger_options;
1470 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001471 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001472
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001473 if (context_->IsVerbose()) {
1474 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001475 << StringPrintf("linking package '%s' using package ID %02x",
1476 context_->GetCompilationPackage().data(),
1477 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001478 }
1479
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001480 for (const std::string& input : input_files) {
1481 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001482 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001483 return 1;
1484 }
1485 }
1486
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001487 for (const std::string& input : options_.overlay_files) {
1488 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001489 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001490 return 1;
1491 }
1492 }
1493
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001494 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001495 return 1;
1496 }
1497
Adam Lesinskib522f042017-04-21 16:57:59 -07001498 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001499 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001500 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001501 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001502 return 1;
1503 }
1504
1505 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001506 IdAssigner id_assigner(&options_.stable_id_map);
1507 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001508 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001509 return 1;
1510 }
1511
1512 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001513 if (options_.resource_id_map_path) {
1514 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001515 for (auto& type : package->types) {
1516 for (auto& entry : type->entries) {
1517 ResourceName name(package->name, type->type, entry->name);
1518 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001519 options_.stable_id_map[std::move(name)] =
1520 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001521 }
1522 }
1523 }
1524
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001525 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001526 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001527 return 1;
1528 }
1529 }
1530 } else {
1531 // Static libs are merged with other apps, and ID collisions are bad, so
1532 // verify that
1533 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001534 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001535 return 1;
1536 }
1537 }
1538
1539 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001540 context_->SetNameManglerPolicy(
1541 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001542
1543 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001544 context_->GetExternalSymbols()->PrependSource(
1545 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001546
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001547 // Workaround for pre-O runtime that would treat negative resource IDs
1548 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1549 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1550 // are just identifiers.
1551 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1552 if (context_->IsVerbose()) {
1553 context_->GetDiagnostics()->Note(DiagMessage()
1554 << "enabling pre-O feature split ID rewriting");
1555 }
1556 context_->GetExternalSymbols()->SetDelegate(
1557 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1558 }
1559
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001560 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001561 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001562 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001563 return 1;
1564 }
1565
Adam Lesinskib522f042017-04-21 16:57:59 -07001566 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001567 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001568 context_->GetDiagnostics()->Warn(DiagMessage()
1569 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001570 }
1571 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001572 ProductFilter product_filter(options_.products);
1573 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001574 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001575 return 1;
1576 }
1577 }
1578
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001579 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001580 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001581 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001582 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001583 return 1;
1584 }
1585 }
1586
Adam Lesinskib522f042017-04-21 16:57:59 -07001587 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001588 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001589 context_->GetDiagnostics()->Note(DiagMessage()
1590 << "collapsing resource versions for minimum SDK "
1591 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001592 }
1593
1594 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001595 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001596 return 1;
1597 }
1598 }
1599
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001600 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001601 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001602 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001603 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001604 return 1;
1605 }
1606 }
1607
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001608 proguard::KeepSet proguard_keep_set;
1609 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001610
Adam Lesinskib522f042017-04-21 16:57:59 -07001611 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001612 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001613 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001614 context_->GetDiagnostics()->Warn(DiagMessage()
1615 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001616 }
1617 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001618 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1619 // equal to the minSdk.
1620 options_.split_constraints =
1621 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001622
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001623 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001624 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001625 return 1;
1626 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001627 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001628
1629 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001630 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001631 auto split_constraints_iter = options_.split_constraints.begin();
1632 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001633 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001634 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1635 << "generating split with configurations '"
1636 << util::Joiner(split_constraints_iter->configs, ", ")
1637 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001638 }
1639
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001640 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001641 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001642 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001643 return 1;
1644 }
1645
1646 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001647 std::unique_ptr<xml::XmlResource> split_manifest =
1648 GenerateSplitManifest(app_info, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649
1650 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001651 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001652 context_->GetDiagnostics()->Error(DiagMessage()
1653 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001654 return 1;
1655 }
1656
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001657 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1658 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659 return 1;
1660 }
1661
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001662 ++path_iter;
1663 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001664 }
1665 }
1666
1667 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001668 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001669 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001670 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001671 return 1;
1672 }
1673
1674 bool error = false;
1675 {
1676 // AndroidManifest.xml has no resource name, but the CallSite is built
1677 // from the name
1678 // (aka, which package the AndroidManifest.xml is coming from).
1679 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001680 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001681
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001682 XmlReferenceLinker manifest_linker;
1683 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1684 if (options_.generate_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001685 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1686 manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001687 error = true;
1688 }
1689
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001690 if (options_.generate_main_dex_proguard_rules_path &&
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001691 !proguard::CollectProguardRulesForManifest(Source(options_.manifest_path),
1692 manifest_xml.get(),
1693 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001695 }
1696
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001697 if (options_.generate_java_class_path) {
1698 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001699 error = true;
1700 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001701 }
1702
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001703 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001704 // PackageParser will fail if URIs are removed from
1705 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001706 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1707 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001708 error = true;
1709 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001710 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001711 } else {
1712 error = true;
1713 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001714 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001715
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001716 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001717 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001718 return 1;
1719 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001720
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001721 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1722 return 1;
1723 }
1724
1725 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001726 return 1;
1727 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001728
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001729 if (options_.generate_java_class_path) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001730 // The set of packages whose R class to call in the main classes
1731 // onResourcesLoaded callback.
1732 std::vector<std::string> packages_to_callback;
1733
1734 JavaClassGeneratorOptions template_options;
1735 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1736 template_options.javadoc_annotations = options_.javadoc_annotations;
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001737
Adam Lesinskib522f042017-04-21 16:57:59 -07001738 if (context_->GetPackageType() == PackageType::kStaticLib ||
1739 options_.generate_non_final_ids) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001740 template_options.use_final = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001741 }
Adam Lesinski64587af2016-02-18 18:33:06 -08001742
Adam Lesinskib522f042017-04-21 16:57:59 -07001743 if (context_->GetPackageType() == PackageType::kSharedLib) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001744 template_options.use_final = false;
1745 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001746 }
1747
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001748 const StringPiece actual_package = context_->GetCompilationPackage();
1749 StringPiece output_package = context_->GetCompilationPackage();
1750 if (options_.custom_java_package) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001751 // Override the output java package to the custom one.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001752 output_package = options_.custom_java_package.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001753 }
1754
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001755 // Generate the private symbols if required.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001756 if (options_.private_symbols) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001757 packages_to_callback.push_back(options_.private_symbols.value());
1758
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001759 // If we defined a private symbols package, we only emit Public symbols
1760 // to the original package, and private and public symbols to the
1761 // private package.
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001762 JavaClassGeneratorOptions options = template_options;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001763 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001764 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001765 options)) {
1766 return 1;
1767 }
1768 }
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001769
1770 // Generate all the symbols for all extra packages.
1771 for (const std::string& extra_package : options_.extra_java_packages) {
1772 packages_to_callback.push_back(extra_package);
1773
1774 JavaClassGeneratorOptions options = template_options;
1775 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1776 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1777 return 1;
1778 }
1779 }
1780
1781 // Generate the main public R class.
1782 JavaClassGeneratorOptions options = template_options;
1783
1784 // Only generate public symbols if we have a private package.
1785 if (options_.private_symbols) {
1786 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1787 }
1788
1789 if (options.rewrite_callback_options) {
1790 options.rewrite_callback_options.value().packages_to_callback =
1791 std::move(packages_to_callback);
1792 }
1793
Adam Lesinski418763f2017-04-11 17:36:53 -07001794 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1795 options_.generate_text_symbols_path)) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001796 return 1;
1797 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001798 }
1799
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001800 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001801 return 1;
1802 }
1803
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001804 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1805 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001806 return 1;
1807 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001808 return 0;
1809 }
1810
1811 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001812 LinkOptions options_;
1813 LinkContext* context_;
1814 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001815
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817
1818 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001819 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820
1821 // A vector of IFileCollections. This is mainly here to keep ownership of the
1822 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001823 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001824
1825 // A vector of ResourceTables. This is here to retain ownership, so that the
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001826 // SymbolTable can use these.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001827 std::vector<std::unique_ptr<ResourceTable>> static_table_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001828
1829 // The set of shared libraries being used, mapping their assigned package ID to package name.
1830 std::map<size_t, std::string> shared_libs_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001831};
1832
Chris Warrington820d72a2017-04-27 15:27:01 +01001833int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
1834 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001835 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001836 std::vector<std::string> overlay_arg_list;
1837 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001838 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07001839 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001840 Maybe<std::string> preferred_density;
1841 Maybe<std::string> product_list;
1842 bool legacy_x_flag = false;
1843 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001844 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001845 bool shared_lib = false;
1846 bool static_lib = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 Maybe<std::string> stable_id_file_path;
1848 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001849 Flags flags =
1850 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001851 .RequiredFlag("-o", "Output path.", &options.output_path)
1852 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001853 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001854 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001855 .OptionalFlagList("-A",
1856 "An assets directory to include in the APK. These are unprocessed.",
1857 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001858 .OptionalFlagList("-R",
1859 "Compilation unit to link, using `overlay` semantics.\n"
1860 "The last conflicting resource given takes precedence.",
1861 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001862 .OptionalFlag("--package-id",
1863 "Specify the package ID to use for this app. Must be greater or equal to\n"
1864 "0x7f and can't be used with --static-lib or --shared-lib.",
1865 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001866 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001867 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001868 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001869 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001870 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001871 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001872 &options.generate_main_dex_proguard_rules_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001873 .OptionalSwitch("--no-auto-version",
1874 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001875 &options.no_auto_version)
1876 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001877 "Disables automatic versioning of vector drawables. Use this only\n"
1878 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001880 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001881 "Disables automatic versioning of transition resources. Use this only\n"
1882 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001883 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001884 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001885 "Disables automatic deduping of resources with\n"
1886 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001887 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001888 .OptionalSwitch("--enable-sparse-encoding",
1889 "Enables encoding sparse entries using a binary search tree.\n"
1890 "This decreases APK size at the cost of resource retrieval performance.",
1891 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001892 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001893 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001894 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001895 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07001896 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07001897 "Comma separated list of configurations to include. The default\n"
1898 "is all configurations.",
1899 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001900 .OptionalFlag("--preferred-density",
1901 "Selects the closest matching density and strips out all others.",
1902 &preferred_density)
1903 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001904 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001905 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001906 &options.output_to_directory)
1907 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001908 "Removes XML namespace prefix and URI information from\n"
1909 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001910 &options.no_xml_namespaces)
1911 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001912 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001913 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001914 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001915 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001916 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001917 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001918 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
1919 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001920 &options.manifest_fixer_options.version_code_default)
1921 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001922 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001923 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001924 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
1925 &shared_lib)
1926 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001927 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001928 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001929 &options.no_static_lib_packages)
1930 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001931 "Generates R.java without the final modifier. This is implied when\n"
1932 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001933 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001934 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001935 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001936 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001937 "Emit a file at the given path with a list of name to ID mappings,\n"
1938 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001939 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001940 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001941 "Package name to use when generating R.java for private symbols.\n"
1942 "If not specified, public and private symbols will use the application's\n"
1943 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001944 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001945 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001946 &options.custom_java_package)
1947 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001948 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001949 &extra_java_packages)
1950 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001951 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001952 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07001953 .OptionalFlag("--output-text-symbols",
1954 "Generates a text file containing the resource symbols of the R class in\n"
1955 "the specified folder.",
1956 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001957 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001958 "Allows the addition of new resources in overlays without\n"
1959 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001960 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001961 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001962 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001963 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001964 "Changes the name of the target package for instrumentation. Most useful\n"
1965 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001966 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001967 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001968 &options.extensions_to_not_compress)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001969 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001970 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07001971 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
1972 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08001973 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001974 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001975
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001976 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001977 return 1;
1978 }
1979
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001980 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001981 std::vector<std::string> arg_list;
1982 for (const std::string& arg : flags.GetArgs()) {
1983 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001984 const std::string path = arg.substr(1, arg.size() - 1);
1985 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001986 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
1987 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001988 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001989 }
1990 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001992 }
1993 }
1994
1995 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001996 for (const std::string& arg : overlay_arg_list) {
1997 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001998 const std::string path = arg.substr(1, arg.size() - 1);
1999 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002000 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2001 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002002 return 1;
2003 }
2004 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002005 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002006 }
2007 }
2008
2009 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002010 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002011 }
2012
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002013 if (shared_lib && static_lib) {
2014 context.GetDiagnostics()->Error(DiagMessage()
2015 << "only one of --shared-lib and --static-lib can be defined");
2016 return 1;
2017 }
2018
2019 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002020 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002021 context.SetPackageId(0x00);
2022 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002023 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002024 context.SetPackageId(kAppPackageId);
2025 } else {
Adam Lesinskib522f042017-04-21 16:57:59 -07002026 context.SetPackageType(PackageType::kApp);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002027 context.SetPackageId(kAppPackageId);
2028 }
2029
2030 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002031 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002032 context.GetDiagnostics()->Error(
2033 DiagMessage() << "can't specify --package-id when not building a regular app");
2034 return 1;
2035 }
2036
2037 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2038 if (!maybe_package_id_int) {
2039 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2040 << "' is not a valid integer");
2041 return 1;
2042 }
2043
2044 const uint32_t package_id_int = maybe_package_id_int.value();
2045 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2046 context.GetDiagnostics()->Error(
2047 DiagMessage() << StringPrintf(
2048 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2049 return 1;
2050 }
2051 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2052 }
2053
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002054 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002055 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002056 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002057 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002058 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002059 }
2060 }
2061
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002062 if (product_list) {
2063 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002064 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002065 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002066 }
2067 }
2068 }
2069
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002070 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002071 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002072 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2073 if (filter == nullptr) {
2074 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002075 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002076 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002077 }
2078
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002079 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002080 Maybe<uint16_t> density =
2081 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2082 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002083 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002084 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002085 options.table_splitter_options.preferred_densities.push_back(density.value());
2086 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002087
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002088 // Parse the split parameters.
2089 for (const std::string& split_arg : split_args) {
2090 options.split_paths.push_back({});
2091 options.split_constraints.push_back({});
2092 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2093 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002094 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002095 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002096 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002097
Adam Lesinskib522f042017-04-21 16:57:59 -07002098 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002099 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2100 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002101 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002102 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002103 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002104
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002105 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002106 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002107 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2108 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2109 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2110 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2111
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002112 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002113 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 options.no_auto_version = true;
2115 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002116 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002117 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002118
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002119 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002121}
2122
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002123} // namespace aapt