blob: 0839f6ff87ad8e7001566f46c6b37674fe61d644 [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>
Adam Lesinskic6284372017-12-04 13:46:23 -080018#include <cinttypes>
Adam Lesinskice5e56e2016-10-21 17:56:45 -070019
Adam Lesinskice5e56e2016-10-21 17:56:45 -070020#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
Adam Lesinski1ab598f2015-08-14 14:26:04 -070029#include "AppInfo.h"
30#include "Debug.h"
31#include "Flags.h"
Adam Lesinski8780eb62017-10-31 17:44:39 -070032#include "LoadedApk.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 Lesinskid3ffa8442017-09-28 13:34:35 -070036#include "ResourceValues.h"
37#include "ValueVisitor.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070038#include "cmd/Util.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070039#include "compile/IdAssigner.h"
Adam Lesinski2427dce2017-11-30 15:10:28 -080040#include "compile/XmlIdCollector.h"
Adam Lesinski6a008172016-02-02 17:02:58 -080041#include "filter/ConfigFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070042#include "format/Archive.h"
Adam Lesinski00451162017-10-03 07:44:08 -070043#include "format/Container.h"
Adam Lesinski46708052017-09-29 14:49:15 -070044#include "format/binary/TableFlattener.h"
45#include "format/binary/XmlFlattener.h"
46#include "format/proto/ProtoDeserialize.h"
47#include "format/proto/ProtoSerialize.h"
Adam Lesinski00451162017-10-03 07:44:08 -070048#include "io/BigBufferStream.h"
49#include "io/FileStream.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080050#include "io/FileSystem.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070051#include "io/Util.h"
Adam Lesinskia40e9722015-11-24 19:11:46 -080052#include "io/ZipArchive.h"
Adam Lesinskica5638f2015-10-21 14:42:43 -070053#include "java/JavaClassGenerator.h"
54#include "java/ManifestClassGenerator.h"
55#include "java/ProguardRules.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070056#include "link/Linkers.h"
Adam Lesinskicacb28f2016-10-19 12:18:14 -070057#include "link/ManifestFixer.h"
Adam Lesinski34a16872018-02-23 16:18:10 -080058#include "link/NoDefaultResourceRemover.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080059#include "link/ReferenceLinker.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070060#include "link/TableMerger.h"
Adam Lesinskic744ae82017-05-17 19:28:38 -070061#include "link/XmlCompatVersioner.h"
Adam Lesinskid48944a2017-02-21 14:22:30 -080062#include "optimize/ResourceDeduper.h"
63#include "optimize/VersionCollapser.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070064#include "process/IResourceTableConsumer.h"
65#include "process/SymbolTable.h"
Adam Lesinski355f2852016-02-13 20:26:45 -080066#include "split/TableSplitter.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070067#include "util/Files.h"
Adam Lesinski467f1712015-11-16 17:35:44 -080068#include "xml/XmlDom.h"
Adam Lesinski1ab598f2015-08-14 14:26:04 -070069
Adam Lesinskiefeb7af2017-08-02 14:57:43 -070070using ::aapt::io::FileInputStream;
71using ::android::StringPiece;
72using ::android::base::StringPrintf;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -070073
Adam Lesinski1ab598f2015-08-14 14:26:04 -070074namespace aapt {
75
Adam Lesinskie59f0d82017-10-13 09:36:53 -070076enum class OutputFormat {
77 kApk,
78 kProto,
79};
80
Adam Lesinski1ab598f2015-08-14 14:26:04 -070081struct LinkOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -070082 std::string output_path;
83 std::string manifest_path;
84 std::vector<std::string> include_paths;
85 std::vector<std::string> overlay_files;
Adam Lesinskib39ad7c2017-03-13 11:40:48 -070086 std::vector<std::string> assets_dirs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070087 bool output_to_directory = false;
88 bool auto_add_overlay = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -070089 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinski36c73a52016-08-11 13:39:24 -070090
Adam Lesinskicacb28f2016-10-19 12:18:14 -070091 // Java/Proguard options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -070092 Maybe<std::string> generate_java_class_path;
93 Maybe<std::string> custom_java_package;
94 std::set<std::string> extra_java_packages;
Adam Lesinski418763f2017-04-11 17:36:53 -070095 Maybe<std::string> generate_text_symbols_path;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070096 Maybe<std::string> generate_proguard_rules_path;
97 Maybe<std::string> generate_main_dex_proguard_rules_path;
Adam Koskidc21dea2017-07-21 10:55:27 -070098 bool generate_conditional_proguard_rules = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -070099 bool generate_non_final_ids = false;
100 std::vector<std::string> javadoc_annotations;
101 Maybe<std::string> private_symbols;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700102
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700103 // Optimizations/features.
104 bool no_auto_version = false;
105 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900106 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700107 bool no_resource_deduping = false;
108 bool no_xml_namespaces = false;
109 bool do_not_compress_anything = false;
110 std::unordered_set<std::string> extensions_to_not_compress;
111
112 // Static lib options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700113 bool no_static_lib_packages = false;
114
115 // AndroidManifest.xml massaging options.
116 ManifestFixerOptions manifest_fixer_options;
117
118 // Products to use/filter on.
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700119 std::unordered_set<std::string> products;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700120
Adam Lesinskic8f71aa2017-02-08 07:03:50 -0800121 // Flattening options.
122 TableFlattenerOptions table_flattener_options;
123
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700124 // Split APK options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700125 TableSplitterOptions table_splitter_options;
126 std::vector<SplitConstraints> split_constraints;
127 std::vector<std::string> split_paths;
Adam Lesinski36c73a52016-08-11 13:39:24 -0700128
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700129 // Stable ID options.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700130 std::unordered_map<ResourceName, ResourceId> stable_id_map;
131 Maybe<std::string> resource_id_map_path;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700132};
133
Adam Lesinski64587af2016-02-18 18:33:06 -0800134class LinkContext : public IAaptContext {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700135 public:
Chris Warrington820d72a2017-04-27 15:27:01 +0100136 LinkContext(IDiagnostics* diagnostics)
137 : diagnostics_(diagnostics), name_mangler_({}), symbols_(&name_mangler_) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700138 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700139
Adam Lesinskib522f042017-04-21 16:57:59 -0700140 PackageType GetPackageType() override {
141 return package_type_;
142 }
143
144 void SetPackageType(PackageType type) {
145 package_type_ = type;
146 }
147
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700148 IDiagnostics* GetDiagnostics() override {
Chris Warrington820d72a2017-04-27 15:27:01 +0100149 return diagnostics_;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700150 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700151
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700152 NameMangler* GetNameMangler() override {
153 return &name_mangler_;
154 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700155
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700156 void SetNameManglerPolicy(const NameManglerPolicy& policy) {
157 name_mangler_ = NameMangler(policy);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700158 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800159
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700160 const std::string& GetCompilationPackage() override {
161 return compilation_package_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700162 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700163
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700164 void SetCompilationPackage(const StringPiece& package_name) {
Adam Lesinskid5083f62017-01-16 15:07:21 -0800165 compilation_package_ = package_name.to_string();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700166 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168 uint8_t GetPackageId() override {
169 return package_id_;
170 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700171
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700172 void SetPackageId(uint8_t id) {
173 package_id_ = id;
174 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800175
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 SymbolTable* GetExternalSymbols() override {
177 return &symbols_;
178 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800179
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700180 bool IsVerbose() override {
181 return verbose_;
182 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800183
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700184 void SetVerbose(bool val) {
185 verbose_ = val;
186 }
Adam Lesinski64587af2016-02-18 18:33:06 -0800187
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700188 int GetMinSdkVersion() override {
189 return min_sdk_version_;
190 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700191
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700192 void SetMinSdkVersion(int minSdk) {
193 min_sdk_version_ = minSdk;
194 }
Adam Lesinskifb6312f2016-06-28 14:40:32 -0700195
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700196 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700197 DISALLOW_COPY_AND_ASSIGN(LinkContext);
198
Adam Lesinskib522f042017-04-21 16:57:59 -0700199 PackageType package_type_ = PackageType::kApp;
Chris Warrington820d72a2017-04-27 15:27:01 +0100200 IDiagnostics* diagnostics_;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700201 NameMangler name_mangler_;
202 std::string compilation_package_;
203 uint8_t package_id_ = 0x0;
204 SymbolTable symbols_;
205 bool verbose_ = false;
206 int min_sdk_version_ = 0;
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700207};
208
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700209// A custom delegate that generates compatible pre-O IDs for use with feature splits.
210// Feature splits use package IDs > 7f, which in Java (since Java doesn't have unsigned ints)
211// is interpreted as a negative number. Some verification was wrongly assuming negative values
212// were invalid.
213//
214// This delegate will attempt to masquerade any '@id/' references with ID 0xPPTTEEEE,
215// where PP > 7f, as 0x7fPPEEEE. Any potential overlapping is verified and an error occurs if such
216// an overlap exists.
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800217//
218// See b/37498913.
Adam Lesinski1e4b0e52017-04-27 15:01:10 -0700219class FeatureSplitSymbolTableDelegate : public DefaultSymbolTableDelegate {
220 public:
221 FeatureSplitSymbolTableDelegate(IAaptContext* context) : context_(context) {
222 }
223
224 virtual ~FeatureSplitSymbolTableDelegate() = default;
225
226 virtual std::unique_ptr<SymbolTable::Symbol> FindByName(
227 const ResourceName& name,
228 const std::vector<std::unique_ptr<ISymbolSource>>& sources) override {
229 std::unique_ptr<SymbolTable::Symbol> symbol =
230 DefaultSymbolTableDelegate::FindByName(name, sources);
231 if (symbol == nullptr) {
232 return {};
233 }
234
235 // Check to see if this is an 'id' with the target package.
236 if (name.type == ResourceType::kId && symbol->id) {
237 ResourceId* id = &symbol->id.value();
238 if (id->package_id() > kAppPackageId) {
239 // Rewrite the resource ID to be compatible pre-O.
240 ResourceId rewritten_id(kAppPackageId, id->package_id(), id->entry_id());
241
242 // Check that this doesn't overlap another resource.
243 if (DefaultSymbolTableDelegate::FindById(rewritten_id, sources) != nullptr) {
244 // The ID overlaps, so log a message (since this is a weird failure) and fail.
245 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to rewrite " << name
246 << " for pre-O feature split support");
247 return {};
248 }
249
250 if (context_->IsVerbose()) {
251 context_->GetDiagnostics()->Note(DiagMessage() << "rewriting " << name << " (" << *id
252 << ") -> (" << rewritten_id << ")");
253 }
254
255 *id = rewritten_id;
256 }
257 }
258 return symbol;
259 }
260
261 private:
262 DISALLOW_COPY_AND_ASSIGN(FeatureSplitSymbolTableDelegate);
263
264 IAaptContext* context_;
265};
266
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700267static bool FlattenXml(IAaptContext* context, const xml::XmlResource& xml_res,
268 const StringPiece& path, bool keep_raw_values, bool utf16,
269 OutputFormat format, IArchiveWriter* writer) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700270 if (context->IsVerbose()) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700271 context->GetDiagnostics()->Note(DiagMessage(path) << "writing to archive (keep_raw_values="
272 << (keep_raw_values ? "true" : "false")
273 << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700274 }
275
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700276 switch (format) {
277 case OutputFormat::kApk: {
278 BigBuffer buffer(1024);
279 XmlFlattenerOptions options = {};
280 options.keep_raw_values = keep_raw_values;
281 options.use_utf16 = utf16;
282 XmlFlattener flattener(&buffer, options);
283 if (!flattener.Consume(context, &xml_res)) {
284 return false;
285 }
286
287 io::BigBufferInputStream input_stream(&buffer);
288 return io::CopyInputStreamToArchive(context, &input_stream, path.to_string(),
289 ArchiveEntry::kCompress, writer);
290 } break;
291
292 case OutputFormat::kProto: {
293 pb::XmlNode pb_node;
294 SerializeXmlResourceToPb(xml_res, &pb_node);
295 return io::CopyProtoToArchive(context, &pb_node, path.to_string(), ArchiveEntry::kCompress,
296 writer);
297 } break;
298 }
299 return false;
Adam Lesinski355f2852016-02-13 20:26:45 -0800300}
301
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700302// Inflates an XML file from the source path.
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700303static std::unique_ptr<xml::XmlResource> LoadXml(const std::string& path, IDiagnostics* diag) {
Adam Lesinskiefeb7af2017-08-02 14:57:43 -0700304 FileInputStream fin(path);
305 if (fin.HadError()) {
306 diag->Error(DiagMessage(path) << "failed to load XML file: " << fin.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700307 return {};
308 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700309 return xml::Inflate(&fin, diag, Source(path));
Adam Lesinski355f2852016-02-13 20:26:45 -0800310}
311
Adam Lesinski355f2852016-02-13 20:26:45 -0800312struct ResourceFileFlattenerOptions {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700313 bool no_auto_version = false;
314 bool no_version_vectors = false;
Yuichi Araki4d35cca2017-01-18 20:42:17 +0900315 bool no_version_transitions = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700316 bool no_xml_namespaces = false;
317 bool keep_raw_values = false;
318 bool do_not_compress_anything = false;
319 bool update_proguard_spec = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700320 OutputFormat output_format = OutputFormat::kApk;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700321 std::unordered_set<std::string> extensions_to_not_compress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800322};
323
Adam Lesinskic744ae82017-05-17 19:28:38 -0700324// A sampling of public framework resource IDs.
325struct R {
326 struct attr {
327 enum : uint32_t {
328 paddingLeft = 0x010100d6u,
329 paddingRight = 0x010100d8u,
330 paddingHorizontal = 0x0101053du,
331
332 paddingTop = 0x010100d7u,
333 paddingBottom = 0x010100d9u,
334 paddingVertical = 0x0101053eu,
335
336 layout_marginLeft = 0x010100f7u,
337 layout_marginRight = 0x010100f9u,
338 layout_marginHorizontal = 0x0101053bu,
339
340 layout_marginTop = 0x010100f8u,
341 layout_marginBottom = 0x010100fau,
342 layout_marginVertical = 0x0101053cu,
343 };
344 };
345};
346
Adam Lesinski355f2852016-02-13 20:26:45 -0800347class ResourceFileFlattener {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700348 public:
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700349 ResourceFileFlattener(const ResourceFileFlattenerOptions& options, IAaptContext* context,
Adam Lesinskic744ae82017-05-17 19:28:38 -0700350 proguard::KeepSet* keep_set);
Adam Lesinski355f2852016-02-13 20:26:45 -0800351
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700352 bool Flatten(ResourceTable* table, IArchiveWriter* archive_writer);
Adam Lesinski355f2852016-02-13 20:26:45 -0800353
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700354 private:
355 struct FileOperation {
356 ConfigDescription config;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700357
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700358 // The entry this file came from.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700359 ResourceEntry* entry;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700360
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700361 // The file to copy as-is.
Adam Lesinskibb94f322017-07-12 07:41:55 -0700362 io::IFile* file_to_copy;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700363
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700364 // The XML to process and flatten.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700365 std::unique_ptr<xml::XmlResource> xml_to_flatten;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700366
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700367 // The destination to write this file to.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700368 std::string dst_path;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700369 };
Adam Lesinski355f2852016-02-13 20:26:45 -0800370
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700371 uint32_t GetCompressionFlags(const StringPiece& str);
Adam Lesinski355f2852016-02-13 20:26:45 -0800372
Adam Lesinskic744ae82017-05-17 19:28:38 -0700373 std::vector<std::unique_ptr<xml::XmlResource>> LinkAndVersionXmlFile(ResourceTable* table,
374 FileOperation* file_op);
Adam Lesinski355f2852016-02-13 20:26:45 -0800375
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700376 ResourceFileFlattenerOptions options_;
377 IAaptContext* context_;
378 proguard::KeepSet* keep_set_;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700379 XmlCompatVersioner::Rules rules_;
Adam Lesinski355f2852016-02-13 20:26:45 -0800380};
381
Adam Lesinskic744ae82017-05-17 19:28:38 -0700382ResourceFileFlattener::ResourceFileFlattener(const ResourceFileFlattenerOptions& options,
383 IAaptContext* context, proguard::KeepSet* keep_set)
384 : options_(options), context_(context), keep_set_(keep_set) {
385 SymbolTable* symm = context_->GetExternalSymbols();
386
387 // Build up the rules for degrading newer attributes to older ones.
388 // NOTE(adamlesinski): These rules are hardcoded right now, but they should be
389 // generated from the attribute definitions themselves (b/62028956).
390 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingHorizontal)) {
391 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800392 {"paddingLeft", R::attr::paddingLeft, Attribute(android::ResTable_map::TYPE_DIMENSION)},
393 {"paddingRight", R::attr::paddingRight, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700394 };
395 rules_[R::attr::paddingHorizontal] =
396 util::make_unique<DegradeToManyRule>(std::move(replacements));
397 }
398
399 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::paddingVertical)) {
400 std::vector<ReplacementAttr> replacements{
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800401 {"paddingTop", R::attr::paddingTop, Attribute(android::ResTable_map::TYPE_DIMENSION)},
402 {"paddingBottom", R::attr::paddingBottom, Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700403 };
404 rules_[R::attr::paddingVertical] =
405 util::make_unique<DegradeToManyRule>(std::move(replacements));
406 }
407
408 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginHorizontal)) {
409 std::vector<ReplacementAttr> replacements{
410 {"layout_marginLeft", R::attr::layout_marginLeft,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800411 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700412 {"layout_marginRight", R::attr::layout_marginRight,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800413 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700414 };
415 rules_[R::attr::layout_marginHorizontal] =
416 util::make_unique<DegradeToManyRule>(std::move(replacements));
417 }
418
419 if (const SymbolTable::Symbol* s = symm->FindById(R::attr::layout_marginVertical)) {
420 std::vector<ReplacementAttr> replacements{
421 {"layout_marginTop", R::attr::layout_marginTop,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800422 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700423 {"layout_marginBottom", R::attr::layout_marginBottom,
Adam Lesinski73bff1e2017-12-08 16:06:10 -0800424 Attribute(android::ResTable_map::TYPE_DIMENSION)},
Adam Lesinskic744ae82017-05-17 19:28:38 -0700425 };
426 rules_[R::attr::layout_marginVertical] =
427 util::make_unique<DegradeToManyRule>(std::move(replacements));
428 }
429}
430
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700431uint32_t ResourceFileFlattener::GetCompressionFlags(const StringPiece& str) {
432 if (options_.do_not_compress_anything) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700433 return 0;
434 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800435
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700436 for (const std::string& extension : options_.extensions_to_not_compress) {
437 if (util::EndsWith(str, extension)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700438 return 0;
Adam Lesinski355f2852016-02-13 20:26:45 -0800439 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700440 }
441 return ArchiveEntry::kCompress;
Adam Lesinski355f2852016-02-13 20:26:45 -0800442}
443
Adam Lesinskibb94f322017-07-12 07:41:55 -0700444static bool IsTransitionElement(const std::string& name) {
445 return name == "fade" || name == "changeBounds" || name == "slide" || name == "explode" ||
446 name == "changeImageTransform" || name == "changeTransform" ||
447 name == "changeClipBounds" || name == "autoTransition" || name == "recolor" ||
448 name == "changeScroll" || name == "transitionSet" || name == "transition" ||
449 name == "transitionManager";
450}
451
452static bool IsVectorElement(const std::string& name) {
453 return name == "vector" || name == "animated-vector" || name == "pathInterpolator" ||
Nick Butchere78a8162018-01-09 15:24:21 +0000454 name == "objectAnimator" || name == "gradient" || name == "animated-selector";
Adam Lesinskibb94f322017-07-12 07:41:55 -0700455}
456
Adam Lesinskic744ae82017-05-17 19:28:38 -0700457template <typename T>
458std::vector<T> make_singleton_vec(T&& val) {
459 std::vector<T> vec;
460 vec.emplace_back(std::forward<T>(val));
461 return vec;
462}
463
464std::vector<std::unique_ptr<xml::XmlResource>> ResourceFileFlattener::LinkAndVersionXmlFile(
465 ResourceTable* table, FileOperation* file_op) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700466 xml::XmlResource* doc = file_op->xml_to_flatten.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700467 const Source& src = doc->file.source;
Adam Lesinski5eeaadd2016-08-25 12:26:56 -0700468
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700469 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700470 context_->GetDiagnostics()->Note(DiagMessage()
471 << "linking " << src.path << " (" << doc->file.name << ")");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700472 }
473
Adam Lesinski00451162017-10-03 07:44:08 -0700474 // First, strip out any tools namespace attributes. AAPT stripped them out early, which means
475 // that existing projects have out-of-date references which pass compilation.
476 xml::StripAndroidStudioAttributes(doc->root.get());
477
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700478 XmlReferenceLinker xml_linker;
479 if (!xml_linker.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700480 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700481 }
482
Adam Koskidc21dea2017-07-21 10:55:27 -0700483 if (options_.update_proguard_spec && !proguard::CollectProguardRules(doc, keep_set_)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700484 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700485 }
486
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700487 if (options_.no_xml_namespaces) {
488 XmlNamespaceRemover namespace_remover;
489 if (!namespace_remover.Consume(context_, doc)) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700490 return {};
Adam Lesinski355f2852016-02-13 20:26:45 -0800491 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700492 }
Adam Lesinski355f2852016-02-13 20:26:45 -0800493
Adam Lesinskibb94f322017-07-12 07:41:55 -0700494 if (options_.no_auto_version) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700495 return make_singleton_vec(std::move(file_op->xml_to_flatten));
496 }
Alexandria Cornwalla7cc3f12016-08-16 13:33:32 -0700497
Adam Lesinskibb94f322017-07-12 07:41:55 -0700498 if (options_.no_version_vectors || options_.no_version_transitions) {
499 // Skip this if it is a vector or animated-vector.
Adam Lesinski6b372992017-08-09 10:54:23 -0700500 xml::Element* el = doc->root.get();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700501 if (el && el->namespace_uri.empty()) {
502 if ((options_.no_version_vectors && IsVectorElement(el->name)) ||
503 (options_.no_version_transitions && IsTransitionElement(el->name))) {
504 return make_singleton_vec(std::move(file_op->xml_to_flatten));
505 }
506 }
507 }
508
Adam Lesinskic744ae82017-05-17 19:28:38 -0700509 const ConfigDescription& config = file_op->config;
510 ResourceEntry* entry = file_op->entry;
511
512 XmlCompatVersioner xml_compat_versioner(&rules_);
513 const util::Range<ApiVersion> api_range{config.sdkVersion,
514 FindNextApiVersionForConfig(entry, config)};
515 return xml_compat_versioner.Process(context_, doc, api_range);
Adam Lesinski355f2852016-02-13 20:26:45 -0800516}
517
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800518ResourceFile::Type XmlFileTypeForOutputFormat(OutputFormat format) {
519 switch (format) {
520 case OutputFormat::kApk:
521 return ResourceFile::Type::kBinaryXml;
522 case OutputFormat::kProto:
523 return ResourceFile::Type::kProtoXml;
524 }
525 LOG_ALWAYS_FATAL("unreachable");
526 return ResourceFile::Type::kUnknown;
527}
528
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700529bool ResourceFileFlattener::Flatten(ResourceTable* table, IArchiveWriter* archive_writer) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700530 bool error = false;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700531 std::map<std::pair<ConfigDescription, StringPiece>, FileOperation> config_sorted_files;
Adam Lesinski355f2852016-02-13 20:26:45 -0800532
Adam Koskidc21dea2017-07-21 10:55:27 -0700533 proguard::CollectResourceReferences(context_, table, keep_set_);
534
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700535 for (auto& pkg : table->packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700536 CHECK(!pkg->name.empty()) << "Packages must have names when being linked";
537
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700538 for (auto& type : pkg->types) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700539 // Sort by config and name, so that we get better locality in the zip file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700540 config_sorted_files.clear();
Adam Lesinskibb94f322017-07-12 07:41:55 -0700541 std::queue<FileOperation> file_operations;
Adam Lesinski355f2852016-02-13 20:26:45 -0800542
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700543 // Populate the queue with all files in the ResourceTable.
544 for (auto& entry : type->entries) {
Adam Lesinskibb94f322017-07-12 07:41:55 -0700545 for (auto& config_value : entry->values) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700546 // WARNING! Do not insert or remove any resources while executing in this scope. It will
547 // corrupt the iteration order.
548
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700549 FileReference* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700550 if (!file_ref) {
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700551 continue;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700552 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700553
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700554 io::IFile* file = file_ref->file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700555 if (!file) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700556 context_->GetDiagnostics()->Error(DiagMessage(file_ref->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700557 << "file not found");
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700558 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700559 }
560
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700561 FileOperation file_op;
562 file_op.entry = entry.get();
563 file_op.dst_path = *file_ref->path;
564 file_op.config = config_value->config;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700565 file_op.file_to_copy = file;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700566
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700567 if (type->type != ResourceType::kRaw &&
Adam Lesinski00451162017-10-03 07:44:08 -0700568 (file_ref->type == ResourceFile::Type::kBinaryXml ||
569 file_ref->type == ResourceFile::Type::kProtoXml)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700570 std::unique_ptr<io::IData> data = file->OpenAsData();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700571 if (!data) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700572 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700573 << "failed to open file");
574 return false;
575 }
576
Adam Lesinski00451162017-10-03 07:44:08 -0700577 if (file_ref->type == ResourceFile::Type::kProtoXml) {
578 pb::XmlNode pb_xml_node;
579 if (!pb_xml_node.ParseFromArray(data->data(), static_cast<int>(data->size()))) {
580 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700581 << "failed to parse proto XML");
Adam Lesinski00451162017-10-03 07:44:08 -0700582 return false;
583 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700584
Adam Lesinski00451162017-10-03 07:44:08 -0700585 std::string error;
586 file_op.xml_to_flatten = DeserializeXmlResourceFromPb(pb_xml_node, &error);
587 if (file_op.xml_to_flatten == nullptr) {
588 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
Adam Lesinski8780eb62017-10-31 17:44:39 -0700589 << "failed to deserialize proto XML: " << error);
Adam Lesinski00451162017-10-03 07:44:08 -0700590 return false;
591 }
592 } else {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700593 std::string error_str;
594 file_op.xml_to_flatten = xml::Inflate(data->data(), data->size(), &error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700595 if (file_op.xml_to_flatten == nullptr) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700596 context_->GetDiagnostics()->Error(DiagMessage(file->GetSource())
597 << "failed to parse binary XML: " << error_str);
Adam Lesinski00451162017-10-03 07:44:08 -0700598 return false;
599 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700600 }
601
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800602 // Update the type that this file will be written as.
603 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
604
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700605 file_op.xml_to_flatten->file.config = config_value->config;
606 file_op.xml_to_flatten->file.source = file_ref->GetSource();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700607 file_op.xml_to_flatten->file.name = ResourceName(pkg->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700608 }
Adam Lesinskic744ae82017-05-17 19:28:38 -0700609
610 // NOTE(adamlesinski): Explicitly construct a StringPiece here, or
611 // else we end up copying the string in the std::make_pair() method,
612 // then creating a StringPiece from the copy, which would cause us
613 // to end up referencing garbage in the map.
614 const StringPiece entry_name(entry->name);
615 config_sorted_files[std::make_pair(config_value->config, entry_name)] =
616 std::move(file_op);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700617 }
618 }
619
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700620 // Now flatten the sorted values.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700621 for (auto& map_entry : config_sorted_files) {
622 const ConfigDescription& config = map_entry.first.first;
Adam Lesinskic744ae82017-05-17 19:28:38 -0700623 FileOperation& file_op = map_entry.second;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700624
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700625 if (file_op.xml_to_flatten) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700626 std::vector<std::unique_ptr<xml::XmlResource>> versioned_docs =
627 LinkAndVersionXmlFile(table, &file_op);
Adam Lesinskic0a5e1e2017-08-07 11:56:32 -0700628 if (versioned_docs.empty()) {
629 error = true;
630 continue;
631 }
632
Adam Lesinskic744ae82017-05-17 19:28:38 -0700633 for (std::unique_ptr<xml::XmlResource>& doc : versioned_docs) {
634 std::string dst_path = file_op.dst_path;
635 if (doc->file.config != file_op.config) {
636 // Only add the new versioned configurations.
637 if (context_->IsVerbose()) {
638 context_->GetDiagnostics()->Note(DiagMessage(doc->file.source)
639 << "auto-versioning resource from config '"
640 << config << "' -> '" << doc->file.config << "'");
641 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700642
Adam Lesinskia65bbdf2018-02-15 12:39:44 -0800643 const ResourceFile& file = doc->file;
644 dst_path = ResourceUtils::BuildResourceFileName(file, context_->GetNameMangler());
645
646 std::unique_ptr<FileReference> file_ref =
647 util::make_unique<FileReference>(table->string_pool.MakeRef(dst_path));
648 file_ref->SetSource(doc->file.source);
649 // Update the output format of this XML file.
650 file_ref->type = XmlFileTypeForOutputFormat(options_.output_format);
651 if (!table->AddResourceMangled(file.name, file.config, {}, std::move(file_ref),
652 context_->GetDiagnostics())) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700653 return false;
654 }
655 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -0700656
657 error |= !FlattenXml(context_, *doc, dst_path, options_.keep_raw_values,
658 false /*utf16*/, options_.output_format, archive_writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700659 }
660 } else {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700661 error |= !io::CopyFileToArchive(context_, file_op.file_to_copy, file_op.dst_path,
662 GetCompressionFlags(file_op.dst_path), archive_writer);
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700663 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700664 }
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700665 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700666 }
667 return !error;
668}
669
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700670static bool WriteStableIdMapToPath(IDiagnostics* diag,
671 const std::unordered_map<ResourceName, ResourceId>& id_map,
672 const std::string& id_map_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800673 io::FileOutputStream fout(id_map_path);
674 if (fout.HadError()) {
675 diag->Error(DiagMessage(id_map_path) << "failed to open: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700676 return false;
677 }
678
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800679 text::Printer printer(&fout);
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700680 for (const auto& entry : id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700681 const ResourceName& name = entry.first;
682 const ResourceId& id = entry.second;
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800683 printer.Print(name.to_string());
684 printer.Print(" = ");
685 printer.Println(id.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700686 }
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800687 fout.Flush();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700688
Adam Lesinskia693c4a2017-11-09 11:29:39 -0800689 if (fout.HadError()) {
690 diag->Error(DiagMessage(id_map_path) << "failed writing to file: " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700691 return false;
692 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700693 return true;
694}
695
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700696static bool LoadStableIdMap(IDiagnostics* diag, const std::string& path,
697 std::unordered_map<ResourceName, ResourceId>* out_id_map) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700698 std::string content;
Adam Lesinski2354b562017-05-26 16:31:38 -0700699 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700700 diag->Error(DiagMessage(path) << "failed reading stable ID file");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700701 return false;
702 }
703
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700704 out_id_map->clear();
705 size_t line_no = 0;
706 for (StringPiece line : util::Tokenize(content, '\n')) {
707 line_no++;
708 line = util::TrimWhitespace(line);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700709 if (line.empty()) {
710 continue;
711 }
712
713 auto iter = std::find(line.begin(), line.end(), '=');
714 if (iter == line.end()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700715 diag->Error(DiagMessage(Source(path, line_no)) << "missing '='");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700716 return false;
717 }
718
719 ResourceNameRef name;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700720 StringPiece res_name_str =
721 util::TrimWhitespace(line.substr(0, std::distance(line.begin(), iter)));
722 if (!ResourceUtils::ParseResourceName(res_name_str, &name)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700723 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource name '" << res_name_str
724 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700725 return false;
726 }
727
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700728 const size_t res_id_start_idx = std::distance(line.begin(), iter) + 1;
729 const size_t res_id_str_len = line.size() - res_id_start_idx;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700730 StringPiece res_id_str = util::TrimWhitespace(line.substr(res_id_start_idx, res_id_str_len));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700731
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700732 Maybe<ResourceId> maybe_id = ResourceUtils::ParseResourceId(res_id_str);
733 if (!maybe_id) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700734 diag->Error(DiagMessage(Source(path, line_no)) << "invalid resource ID '" << res_id_str
735 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700736 return false;
737 }
738
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700739 (*out_id_map)[name.ToResourceName()] = maybe_id.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700740 }
741 return true;
Adam Lesinskibf0bd0f2016-06-01 15:31:50 -0700742}
743
Adam Lesinskic6284372017-12-04 13:46:23 -0800744static int32_t FindFrameworkAssetManagerCookie(const android::AssetManager& assets) {
745 using namespace android;
746
747 // Find the system package (0x01). AAPT always generates attributes with the type 0x01, so
748 // we're looking for the first attribute resource in the system package.
749 const ResTable& table = assets.getResources(true);
750 Res_value val;
751 ssize_t idx = table.getResource(0x01010000, &val, true);
752 if (idx != NO_ERROR) {
753 // Try as a bag.
754 const ResTable::bag_entry* entry;
755 ssize_t cnt = table.lockBag(0x01010000, &entry);
756 if (cnt >= 0) {
757 idx = entry->stringBlock;
758 }
759 table.unlockBag(entry);
760 }
761
762 if (idx < 0) {
763 return 0;
764 }
765 return table.getTableCookie(idx);
766}
767
Adam Lesinskifb48d292015-11-07 15:52:13 -0800768class LinkCommand {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700769 public:
770 LinkCommand(LinkContext* context, const LinkOptions& options)
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700771 : options_(options),
772 context_(context),
773 final_table_(),
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700774 file_collection_(util::make_unique<io::FileCollection>()) {
775 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700776
Adam Lesinskic6284372017-12-04 13:46:23 -0800777 void ExtractCompileSdkVersions(android::AssetManager* assets) {
778 using namespace android;
779
780 int32_t cookie = FindFrameworkAssetManagerCookie(*assets);
781 if (cookie == 0) {
782 // No Framework assets loaded. Not a failure.
783 return;
784 }
785
786 std::unique_ptr<Asset> manifest(
787 assets->openNonAsset(cookie, kAndroidManifestPath, Asset::AccessMode::ACCESS_BUFFER));
788 if (manifest == nullptr) {
789 // No errors.
790 return;
791 }
792
793 std::string error;
794 std::unique_ptr<xml::XmlResource> manifest_xml =
795 xml::Inflate(manifest->getBuffer(true /*wordAligned*/), manifest->getLength(), &error);
796 if (manifest_xml == nullptr) {
797 // No errors.
798 return;
799 }
800
801 xml::Attribute* attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionCode");
802 if (attr != nullptr) {
803 Maybe<std::string>& compile_sdk_version = options_.manifest_fixer_options.compile_sdk_version;
804 if (BinaryPrimitive* prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get())) {
805 switch (prim->value.dataType) {
806 case Res_value::TYPE_INT_DEC:
807 compile_sdk_version = StringPrintf("%" PRId32, static_cast<int32_t>(prim->value.data));
808 break;
809 case Res_value::TYPE_INT_HEX:
810 compile_sdk_version = StringPrintf("%" PRIx32, prim->value.data);
811 break;
812 default:
813 break;
814 }
815 } else if (String* str = ValueCast<String>(attr->compiled_value.get())) {
816 compile_sdk_version = *str->value;
817 } else {
818 compile_sdk_version = attr->value;
819 }
820 }
821
822 attr = manifest_xml->root->FindAttribute(xml::kSchemaAndroid, "versionName");
823 if (attr != nullptr) {
824 Maybe<std::string>& compile_sdk_version_codename =
825 options_.manifest_fixer_options.compile_sdk_version_codename;
826 if (String* str = ValueCast<String>(attr->compiled_value.get())) {
827 compile_sdk_version_codename = *str->value;
828 } else {
829 compile_sdk_version_codename = attr->value;
830 }
831 }
832 }
833
Adam Lesinski8780eb62017-10-31 17:44:39 -0700834 // Creates a SymbolTable that loads symbols from the various APKs.
Adam Lesinskic6284372017-12-04 13:46:23 -0800835 // Pre-condition: context_->GetCompilationPackage() needs to be set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700836 bool LoadSymbolsFromIncludePaths() {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700837 auto asset_source = util::make_unique<AssetManagerSymbolSource>();
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700838 for (const std::string& path : options_.include_paths) {
839 if (context_->IsVerbose()) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700840 context_->GetDiagnostics()->Note(DiagMessage() << "including " << path);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700841 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700842
Adam Lesinski8780eb62017-10-31 17:44:39 -0700843 std::string error;
844 auto zip_collection = io::ZipFileCollection::Create(path, &error);
845 if (zip_collection == nullptr) {
846 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open APK: " << error);
847 return false;
848 }
849
850 if (zip_collection->FindFile(kProtoResourceTablePath) != nullptr) {
851 // Load this as a static library include.
852 std::unique_ptr<LoadedApk> static_apk = LoadedApk::LoadProtoApkFromFileCollection(
853 Source(path), std::move(zip_collection), context_->GetDiagnostics());
854 if (static_apk == nullptr) {
855 return false;
856 }
857
Adam Lesinskib522f042017-04-21 16:57:59 -0700858 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800859 // Can't include static libraries when not building a static library (they have no IDs
860 // assigned).
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700861 context_->GetDiagnostics()->Error(
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800862 DiagMessage(path) << "can't include static library when not building a static lib");
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700863 return false;
864 }
865
Adam Lesinski8780eb62017-10-31 17:44:39 -0700866 ResourceTable* table = static_apk->GetResourceTable();
867
868 // If we are using --no-static-lib-packages, we need to rename the package of this table to
869 // our compilation package.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700870 if (options_.no_static_lib_packages) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800871 // Since package names can differ, and multiple packages can exist in a ResourceTable,
872 // we place the requirement that all static libraries are built with the package
873 // ID 0x7f. So if one is not found, this is an error.
Adam Lesinski8780eb62017-10-31 17:44:39 -0700874 if (ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId)) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700875 pkg->name = context_->GetCompilationPackage();
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800876 } else {
877 context_->GetDiagnostics()->Error(DiagMessage(path)
878 << "no package with ID 0x7f found in static library");
879 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700880 }
881 }
882
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700883 context_->GetExternalSymbols()->AppendSource(
Adam Lesinski8780eb62017-10-31 17:44:39 -0700884 util::make_unique<ResourceTableSymbolSource>(table));
885 static_library_includes_.push_back(std::move(static_apk));
886 } else {
887 if (!asset_source->AddAssetPath(path)) {
888 context_->GetDiagnostics()->Error(DiagMessage()
889 << "failed to load include path " << path);
890 return false;
891 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700892 }
893 }
894
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800895 // Capture the shared libraries so that the final resource table can be properly flattened
896 // with support for shared libraries.
897 for (auto& entry : asset_source->GetAssignedPackageIds()) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -0800898 if (entry.first > kFrameworkPackageId && entry.first < kAppPackageId) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800899 final_table_.included_packages_[entry.first] = entry.second;
Adam Lesinski490595a2017-11-07 17:08:07 -0800900 } else if (entry.first == kAppPackageId) {
901 // Capture the included base feature package.
902 included_feature_base_ = entry.second;
Adam Lesinskic6284372017-12-04 13:46:23 -0800903 } else if (entry.first == kFrameworkPackageId) {
904 // Try to embed which version of the framework we're compiling against.
905 // First check if we should use compileSdkVersion at all. Otherwise compilation may fail
906 // when linking our synthesized 'android:compileSdkVersion' attribute.
907 std::unique_ptr<SymbolTable::Symbol> symbol = asset_source->FindByName(
908 ResourceName("android", ResourceType::kAttr, "compileSdkVersion"));
909 if (symbol != nullptr && symbol->is_public) {
910 // The symbol is present and public, extract the android:versionName and
911 // android:versionCode from the framework AndroidManifest.xml.
912 ExtractCompileSdkVersions(asset_source->GetAssetManager());
913 }
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -0800914 }
915 }
916
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700917 context_->GetExternalSymbols()->AppendSource(std::move(asset_source));
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700918 return true;
919 }
920
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800921 Maybe<AppInfo> ExtractAppInfoFromManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700922 // Make sure the first element is <manifest> with package attribute.
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800923 xml::Element* manifest_el = xml::FindRootElement(xml_res->root.get());
924 if (manifest_el == nullptr) {
925 return {};
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700926 }
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800927
928 AppInfo app_info;
929
930 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
931 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
932 return {};
933 }
934
935 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
936 if (!package_attr) {
937 diag->Error(DiagMessage(xml_res->file.source)
938 << "<manifest> must have a 'package' attribute");
939 return {};
940 }
941 app_info.package = package_attr->value;
942
943 if (xml::Attribute* version_code_attr =
944 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
945 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(version_code_attr->value);
946 if (!maybe_code) {
947 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
948 << "invalid android:versionCode '" << version_code_attr->value << "'");
949 return {};
950 }
951 app_info.version_code = maybe_code.value();
952 }
953
954 if (xml::Attribute* revision_code_attr =
955 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
956 Maybe<uint32_t> maybe_code = ResourceUtils::ParseInt(revision_code_attr->value);
957 if (!maybe_code) {
958 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
959 << "invalid android:revisionCode '" << revision_code_attr->value << "'");
960 return {};
961 }
962 app_info.revision_code = maybe_code.value();
963 }
964
965 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
966 if (!split_name_attr->value.empty()) {
967 app_info.split_name = split_name_attr->value;
968 }
969 }
970
971 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
972 if (xml::Attribute* min_sdk =
973 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700974 app_info.min_sdk_version = ResourceUtils::ParseSdkVersion(min_sdk->value);
Adam Lesinskib0c47ef2017-03-06 20:05:57 -0800975 }
976 }
977 return app_info;
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700978 }
979
Adam Lesinski1ef0fa92017-08-15 21:32:49 -0700980 // Precondition: ResourceTable doesn't have any IDs assigned yet, nor is it linked.
981 // Postcondition: ResourceTable has only one package left. All others are
982 // stripped, or there is an error and false is returned.
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700983 bool VerifyNoExternalPackages() {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700984 auto is_ext_package_func = [&](const std::unique_ptr<ResourceTablePackage>& pkg) -> bool {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700985 return context_->GetCompilationPackage() != pkg->name || !pkg->id ||
986 pkg->id.value() != context_->GetPackageId();
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700987 };
988
989 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700990 for (const auto& package : final_table_.packages) {
991 if (is_ext_package_func(package)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700992 // We have a package that is not related to the one we're building!
993 for (const auto& type : package->types) {
994 for (const auto& entry : type->entries) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700995 ResourceNameRef res_name(package->name, type->type, entry->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700996
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700997 for (const auto& config_value : entry->values) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -0700998 // Special case the occurrence of an ID that is being generated
Adam Lesinskice5e56e2016-10-21 17:56:45 -0700999 // for the 'android' package. This is due to legacy reasons.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001000 if (ValueCast<Id>(config_value->value.get()) && package->name == "android") {
1001 context_->GetDiagnostics()->Warn(DiagMessage(config_value->value->GetSource())
1002 << "generated id '" << res_name
1003 << "' for external package '" << package->name
1004 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001005 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001006 context_->GetDiagnostics()->Error(DiagMessage(config_value->value->GetSource())
1007 << "defined resource '" << res_name
1008 << "' for external package '" << package->name
1009 << "'");
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001010 error = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001011 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001012 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001013 }
1014 }
1015 }
1016 }
1017
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001018 auto new_end_iter = std::remove_if(final_table_.packages.begin(), final_table_.packages.end(),
1019 is_ext_package_func);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001020 final_table_.packages.erase(new_end_iter, final_table_.packages.end());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001021 return !error;
1022 }
1023
1024 /**
1025 * Returns true if no IDs have been set, false otherwise.
1026 */
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001027 bool VerifyNoIdsSet() {
1028 for (const auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001029 for (const auto& type : package->types) {
1030 if (type->id) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001031 context_->GetDiagnostics()->Error(DiagMessage() << "type " << type->type << " has ID "
1032 << StringPrintf("%02x", type->id.value())
1033 << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001034 return false;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001035 }
1036
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001037 for (const auto& entry : type->entries) {
1038 if (entry->id) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001039 ResourceNameRef res_name(package->name, type->type, entry->name);
1040 context_->GetDiagnostics()->Error(
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001041 DiagMessage() << "entry " << res_name << " has ID "
1042 << StringPrintf("%02x", entry->id.value()) << " assigned");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001043 return false;
1044 }
1045 }
1046 }
1047 }
1048 return true;
1049 }
1050
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001051 std::unique_ptr<IArchiveWriter> MakeArchiveWriter(const StringPiece& out) {
1052 if (options_.output_to_directory) {
1053 return CreateDirectoryArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001054 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001055 return CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001056 }
1057 }
1058
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001059 bool FlattenTable(ResourceTable* table, OutputFormat format, IArchiveWriter* writer) {
1060 switch (format) {
1061 case OutputFormat::kApk: {
1062 BigBuffer buffer(1024);
1063 TableFlattener flattener(options_.table_flattener_options, &buffer);
1064 if (!flattener.Consume(context_, table)) {
1065 context_->GetDiagnostics()->Error(DiagMessage() << "failed to flatten resource table");
1066 return false;
1067 }
1068
1069 io::BigBufferInputStream input_stream(&buffer);
1070 return io::CopyInputStreamToArchive(context_, &input_stream, kApkResourceTablePath,
1071 ArchiveEntry::kAlign, writer);
1072 } break;
1073
1074 case OutputFormat::kProto: {
1075 pb::ResourceTable pb_table;
1076 SerializeTableToPb(*table, &pb_table);
1077 return io::CopyProtoToArchive(context_, &pb_table, kProtoResourceTablePath,
1078 ArchiveEntry::kCompress, writer);
1079 } break;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001080 }
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001081 return false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001082 }
1083
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001084 bool WriteJavaFile(ResourceTable* table, const StringPiece& package_name_to_generate,
Adam Lesinski418763f2017-04-11 17:36:53 -07001085 const StringPiece& out_package, const JavaClassGeneratorOptions& java_options,
Chih-Hung Hsieh4dc58122017-08-03 16:28:10 -07001086 const Maybe<std::string>& out_text_symbols_path = {}) {
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001087 if (!options_.generate_java_class_path && !out_text_symbols_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001088 return true;
1089 }
1090
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001091 std::string out_path;
1092 std::unique_ptr<io::FileOutputStream> fout;
1093 if (options_.generate_java_class_path) {
1094 out_path = options_.generate_java_class_path.value();
1095 file::AppendPath(&out_path, file::PackageToPath(out_package));
1096 if (!file::mkdirs(out_path)) {
1097 context_->GetDiagnostics()->Error(DiagMessage()
1098 << "failed to create directory '" << out_path << "'");
1099 return false;
1100 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001101
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001102 file::AppendPath(&out_path, "R.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001103
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001104 fout = util::make_unique<io::FileOutputStream>(out_path);
1105 if (fout->HadError()) {
1106 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1107 << "': " << fout->GetError());
1108 return false;
1109 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001110 }
1111
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001112 std::unique_ptr<io::FileOutputStream> fout_text;
Adam Lesinski418763f2017-04-11 17:36:53 -07001113 if (out_text_symbols_path) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001114 fout_text = util::make_unique<io::FileOutputStream>(out_text_symbols_path.value());
1115 if (fout_text->HadError()) {
1116 context_->GetDiagnostics()->Error(DiagMessage()
1117 << "failed writing to '" << out_text_symbols_path.value()
1118 << "': " << fout_text->GetError());
Adam Lesinski418763f2017-04-11 17:36:53 -07001119 return false;
1120 }
1121 }
1122
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001123 JavaClassGenerator generator(context_, table, java_options);
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001124 if (!generator.Generate(package_name_to_generate, out_package, fout.get(), fout_text.get())) {
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001125 context_->GetDiagnostics()->Error(DiagMessage(out_path) << generator.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001126 return false;
1127 }
1128
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001129 return true;
1130 }
1131
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001132 bool GenerateJavaClasses() {
1133 // The set of packages whose R class to call in the main classes onResourcesLoaded callback.
1134 std::vector<std::string> packages_to_callback;
1135
1136 JavaClassGeneratorOptions template_options;
1137 template_options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1138 template_options.javadoc_annotations = options_.javadoc_annotations;
1139
1140 if (context_->GetPackageType() == PackageType::kStaticLib || options_.generate_non_final_ids) {
1141 template_options.use_final = false;
1142 }
1143
1144 if (context_->GetPackageType() == PackageType::kSharedLib) {
1145 template_options.use_final = false;
1146 template_options.rewrite_callback_options = OnResourcesLoadedCallbackOptions{};
1147 }
1148
1149 const StringPiece actual_package = context_->GetCompilationPackage();
1150 StringPiece output_package = context_->GetCompilationPackage();
1151 if (options_.custom_java_package) {
1152 // Override the output java package to the custom one.
1153 output_package = options_.custom_java_package.value();
1154 }
1155
1156 // Generate the private symbols if required.
1157 if (options_.private_symbols) {
1158 packages_to_callback.push_back(options_.private_symbols.value());
1159
1160 // If we defined a private symbols package, we only emit Public symbols
1161 // to the original package, and private and public symbols to the private package.
1162 JavaClassGeneratorOptions options = template_options;
1163 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublicPrivate;
1164 if (!WriteJavaFile(&final_table_, actual_package, options_.private_symbols.value(),
1165 options)) {
1166 return false;
1167 }
1168 }
1169
1170 // Generate copies of the original package R class but with different package names.
1171 // This is to support non-namespaced builds.
1172 for (const std::string& extra_package : options_.extra_java_packages) {
1173 packages_to_callback.push_back(extra_package);
1174
1175 JavaClassGeneratorOptions options = template_options;
1176 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1177 if (!WriteJavaFile(&final_table_, actual_package, extra_package, options)) {
1178 return false;
1179 }
1180 }
1181
1182 // Generate R classes for each package that was merged (static library).
1183 // Use the actual package's resources only.
1184 for (const std::string& package : table_merger_->merged_packages()) {
1185 packages_to_callback.push_back(package);
1186
1187 JavaClassGeneratorOptions options = template_options;
1188 options.types = JavaClassGeneratorOptions::SymbolTypes::kAll;
1189 if (!WriteJavaFile(&final_table_, package, package, options)) {
1190 return false;
1191 }
1192 }
1193
1194 // Generate the main public R class.
1195 JavaClassGeneratorOptions options = template_options;
1196
1197 // Only generate public symbols if we have a private package.
1198 if (options_.private_symbols) {
1199 options.types = JavaClassGeneratorOptions::SymbolTypes::kPublic;
1200 }
1201
1202 if (options.rewrite_callback_options) {
1203 options.rewrite_callback_options.value().packages_to_callback =
1204 std::move(packages_to_callback);
1205 }
1206
1207 if (!WriteJavaFile(&final_table_, actual_package, output_package, options,
1208 options_.generate_text_symbols_path)) {
1209 return false;
1210 }
1211
1212 return true;
1213 }
1214
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001215 bool WriteManifestJavaFile(xml::XmlResource* manifest_xml) {
1216 if (!options_.generate_java_class_path) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001217 return true;
1218 }
1219
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001220 std::unique_ptr<ClassDefinition> manifest_class =
1221 GenerateManifestClass(context_->GetDiagnostics(), manifest_xml);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001222
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001223 if (!manifest_class) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001224 // Something bad happened, but we already logged it, so exit.
1225 return false;
1226 }
1227
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001228 if (manifest_class->empty()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001229 // Empty Manifest class, no need to generate it.
1230 return true;
1231 }
1232
1233 // Add any JavaDoc annotations to the generated class.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001234 for (const std::string& annotation : options_.javadoc_annotations) {
1235 std::string proper_annotation = "@";
1236 proper_annotation += annotation;
1237 manifest_class->GetCommentBuilder()->AppendComment(proper_annotation);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001238 }
1239
Adam Lesinski0d81f702017-06-27 15:51:09 -07001240 const std::string package_utf8 =
1241 options_.custom_java_package.value_or_default(context_->GetCompilationPackage());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001242
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001243 std::string out_path = options_.generate_java_class_path.value();
1244 file::AppendPath(&out_path, file::PackageToPath(package_utf8));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001245
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001246 if (!file::mkdirs(out_path)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001247 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create directory '" << out_path
1248 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001249 return false;
1250 }
1251
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001252 file::AppendPath(&out_path, "Manifest.java");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001253
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001254 io::FileOutputStream fout(out_path);
1255 if (fout.HadError()) {
1256 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1257 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001258 return false;
1259 }
1260
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001261 ClassDefinition::WriteJavaFile(manifest_class.get(), package_utf8, true, &fout);
1262 fout.Flush();
1263
1264 if (fout.HadError()) {
1265 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1266 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001267 return false;
1268 }
1269 return true;
1270 }
1271
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001272 bool WriteProguardFile(const Maybe<std::string>& out, const proguard::KeepSet& keep_set) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001273 if (!out) {
1274 return true;
1275 }
1276
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001277 const std::string& out_path = out.value();
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001278 io::FileOutputStream fout(out_path);
1279 if (fout.HadError()) {
1280 context_->GetDiagnostics()->Error(DiagMessage() << "failed to open '" << out_path
1281 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001282 return false;
1283 }
1284
Adam Lesinskia693c4a2017-11-09 11:29:39 -08001285 proguard::WriteKeepSet(keep_set, &fout);
1286 fout.Flush();
1287
1288 if (fout.HadError()) {
1289 context_->GetDiagnostics()->Error(DiagMessage() << "failed writing to '" << out_path
1290 << "': " << fout.GetError());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001291 return false;
1292 }
1293 return true;
1294 }
1295
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001296 bool MergeStaticLibrary(const std::string& input, bool override) {
1297 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001298 context_->GetDiagnostics()->Note(DiagMessage() << "merging static library " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001299 }
1300
Adam Lesinski8780eb62017-10-31 17:44:39 -07001301 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(input, context_->GetDiagnostics());
1302 if (apk == nullptr) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001303 context_->GetDiagnostics()->Error(DiagMessage(input) << "invalid static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001304 return false;
1305 }
1306
Adam Lesinski8780eb62017-10-31 17:44:39 -07001307 ResourceTable* table = apk->GetResourceTable();
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001308 ResourceTablePackage* pkg = table->FindPackageById(kAppPackageId);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001309 if (!pkg) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001310 context_->GetDiagnostics()->Error(DiagMessage(input) << "static library has no package");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001311 return false;
1312 }
1313
1314 bool result;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001315 if (options_.no_static_lib_packages) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001316 // Merge all resources as if they were in the compilation package. This is the old behavior
1317 // of aapt.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001318
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001319 // Add the package to the set of --extra-packages so we emit an R.java for each library
1320 // package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001321 if (!pkg->name.empty()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001322 options_.extra_java_packages.insert(pkg->name);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001323 }
1324
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001325 // Clear the package name, so as to make the resources look like they are coming from the
1326 // local package.
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001327 pkg->name = "";
Adam Lesinski8780eb62017-10-31 17:44:39 -07001328 result = table_merger_->Merge(Source(input), table, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001329
1330 } else {
1331 // This is the proper way to merge libraries, where the package name is
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001332 // preserved and resource names are mangled.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001333 result = table_merger_->MergeAndMangle(Source(input), pkg->name, table);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001334 }
1335
1336 if (!result) {
1337 return false;
1338 }
1339
1340 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinski8780eb62017-10-31 17:44:39 -07001341 merged_apks_.push_back(std::move(apk));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001342 return true;
1343 }
1344
Adam Lesinski2427dce2017-11-30 15:10:28 -08001345 bool MergeExportedSymbols(const Source& source,
1346 const std::vector<SourcedResourceName>& exported_symbols) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001347 // Add the exports of this file to the table.
Adam Lesinski2427dce2017-11-30 15:10:28 -08001348 for (const SourcedResourceName& exported_symbol : exported_symbols) {
Adam Lesinski00451162017-10-03 07:44:08 -07001349 ResourceName res_name = exported_symbol.name;
1350 if (res_name.package.empty()) {
1351 res_name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001352 }
1353
Adam Lesinski00451162017-10-03 07:44:08 -07001354 Maybe<ResourceName> mangled_name = context_->GetNameMangler()->MangleName(res_name);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001355 if (mangled_name) {
1356 res_name = mangled_name.value();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001357 }
1358
1359 std::unique_ptr<Id> id = util::make_unique<Id>();
Adam Lesinski2427dce2017-11-30 15:10:28 -08001360 id->SetSource(source.WithLine(exported_symbol.line));
Adam Lesinski71be7052017-12-12 16:48:07 -08001361 bool result =
1362 final_table_.AddResourceMangled(res_name, ConfigDescription::DefaultConfig(),
1363 std::string(), std::move(id), context_->GetDiagnostics());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001364 if (!result) {
1365 return false;
1366 }
1367 }
1368 return true;
1369 }
1370
Adam Lesinski2427dce2017-11-30 15:10:28 -08001371 bool MergeCompiledFile(const ResourceFile& compiled_file, io::IFile* file, bool override) {
1372 if (context_->IsVerbose()) {
1373 context_->GetDiagnostics()->Note(DiagMessage()
1374 << "merging '" << compiled_file.name
1375 << "' from compiled file " << compiled_file.source);
1376 }
1377
1378 if (!table_merger_->MergeFile(compiled_file, override, file)) {
1379 return false;
1380 }
1381 return MergeExportedSymbols(compiled_file.source, compiled_file.exported_symbols);
1382 }
1383
Adam Lesinski00451162017-10-03 07:44:08 -07001384 // Takes a path to load as a ZIP file and merges the files within into the master ResourceTable.
1385 // If override is true, conflicting resources are allowed to override each other, in order of last
1386 // seen.
1387 // An io::IFileCollection is created from the ZIP file and added to the set of
1388 // io::IFileCollections that are open.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001389 bool MergeArchive(const std::string& input, bool override) {
1390 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001391 context_->GetDiagnostics()->Note(DiagMessage() << "merging archive " << input);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001392 }
1393
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001394 std::string error_str;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001395 std::unique_ptr<io::ZipFileCollection> collection =
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001396 io::ZipFileCollection::Create(input, &error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001397 if (!collection) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001398 context_->GetDiagnostics()->Error(DiagMessage(input) << error_str);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001399 return false;
1400 }
1401
1402 bool error = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001403 for (auto iter = collection->Iterator(); iter->HasNext();) {
1404 if (!MergeFile(iter->Next(), override)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001405 error = true;
1406 }
1407 }
1408
1409 // Make sure to move the collection into the set of IFileCollections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001410 collections_.push_back(std::move(collection));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001411 return !error;
1412 }
1413
Adam Lesinski00451162017-10-03 07:44:08 -07001414 // Takes a path to load and merge into the master ResourceTable. If override is true,
1415 // conflicting resources are allowed to override each other, in order of last seen.
1416 // If the file path ends with .flata, .jar, .jack, or .zip the file is treated
1417 // as ZIP archive and the files within are merged individually.
1418 // Otherwise the file is processed on its own.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001419 bool MergePath(const std::string& path, bool override) {
1420 if (util::EndsWith(path, ".flata") || util::EndsWith(path, ".jar") ||
1421 util::EndsWith(path, ".jack") || util::EndsWith(path, ".zip")) {
1422 return MergeArchive(path, override);
1423 } else if (util::EndsWith(path, ".apk")) {
1424 return MergeStaticLibrary(path, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001425 }
1426
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001427 io::IFile* file = file_collection_->InsertFile(path);
1428 return MergeFile(file, override);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001429 }
1430
Adam Lesinski00451162017-10-03 07:44:08 -07001431 // Takes an AAPT Container file (.apc/.flat) to load and merge into the master ResourceTable.
1432 // If override is true, conflicting resources are allowed to override each other, in order of last
1433 // seen.
1434 // All other file types are ignored. This is because these files could be coming from a zip,
1435 // where we could have other files like classes.dex.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001436 bool MergeFile(io::IFile* file, bool override) {
1437 const Source& src = file->GetSource();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001438
Adam Lesinski00451162017-10-03 07:44:08 -07001439 if (util::EndsWith(src.path, ".xml") || util::EndsWith(src.path, ".png")) {
Adam Lesinski6a396c12016-10-20 14:38:23 -07001440 // Since AAPT compiles these file types and appends .flat to them, seeing
1441 // their raw extensions is a sign that they weren't compiled.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001442 const StringPiece file_type = util::EndsWith(src.path, ".xml") ? "XML" : "PNG";
1443 context_->GetDiagnostics()->Error(DiagMessage(src) << "uncompiled " << file_type
1444 << " file passed as argument. Must be "
1445 "compiled first into .flat file.");
Adam Lesinski6a396c12016-10-20 14:38:23 -07001446 return false;
Adam Lesinski00451162017-10-03 07:44:08 -07001447 } else if (!util::EndsWith(src.path, ".apc") && !util::EndsWith(src.path, ".flat")) {
1448 if (context_->IsVerbose()) {
1449 context_->GetDiagnostics()->Warn(DiagMessage(src) << "ignoring unrecognized file");
1450 return true;
1451 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001452 }
1453
Adam Lesinski00451162017-10-03 07:44:08 -07001454 std::unique_ptr<io::InputStream> input_stream = file->OpenInputStream();
1455 if (input_stream == nullptr) {
1456 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to open file");
1457 return false;
1458 }
1459
1460 if (input_stream->HadError()) {
1461 context_->GetDiagnostics()->Error(DiagMessage(src)
1462 << "failed to open file: " << input_stream->GetError());
1463 return false;
1464 }
1465
1466 ContainerReaderEntry* entry;
1467 ContainerReader reader(input_stream.get());
Mohamed Heikal10844322018-02-07 15:17:38 -05001468
1469 if (reader.HadError()) {
1470 context_->GetDiagnostics()->Error(DiagMessage(src)
1471 << "failed to read file: " << reader.GetError());
1472 return false;
1473 }
1474
Adam Lesinski00451162017-10-03 07:44:08 -07001475 while ((entry = reader.Next()) != nullptr) {
1476 if (entry->Type() == ContainerEntryType::kResTable) {
1477 pb::ResourceTable pb_table;
1478 if (!entry->GetResTable(&pb_table)) {
1479 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to read resource table: "
1480 << entry->GetError());
1481 return false;
1482 }
1483
1484 ResourceTable table;
1485 std::string error;
Adam Lesinski8780eb62017-10-31 17:44:39 -07001486 if (!DeserializeTableFromPb(pb_table, nullptr /*files*/, &table, &error)) {
Adam Lesinski00451162017-10-03 07:44:08 -07001487 context_->GetDiagnostics()->Error(DiagMessage(src)
1488 << "failed to deserialize resource table: " << error);
1489 return false;
1490 }
1491
1492 if (!table_merger_->Merge(src, &table, override)) {
1493 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to merge resource table");
1494 return false;
1495 }
1496 } else if (entry->Type() == ContainerEntryType::kResFile) {
1497 pb::internal::CompiledFile pb_compiled_file;
1498 off64_t offset;
1499 size_t len;
1500 if (!entry->GetResFileOffsets(&pb_compiled_file, &offset, &len)) {
1501 context_->GetDiagnostics()->Error(DiagMessage(src) << "failed to get resource file: "
1502 << entry->GetError());
1503 return false;
1504 }
1505
1506 ResourceFile resource_file;
1507 std::string error;
1508 if (!DeserializeCompiledFileFromPb(pb_compiled_file, &resource_file, &error)) {
1509 context_->GetDiagnostics()->Error(DiagMessage(src)
1510 << "failed to read compiled header: " << error);
1511 return false;
1512 }
1513
1514 if (!MergeCompiledFile(resource_file, file->CreateFileSegment(offset, len), override)) {
1515 return false;
1516 }
1517 }
1518 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001519 return true;
1520 }
1521
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001522 bool CopyAssetsDirsToApk(IArchiveWriter* writer) {
1523 std::map<std::string, std::unique_ptr<io::RegularFile>> merged_assets;
1524 for (const std::string& assets_dir : options_.assets_dirs) {
1525 Maybe<std::vector<std::string>> files =
1526 file::FindFiles(assets_dir, context_->GetDiagnostics(), nullptr);
1527 if (!files) {
1528 return false;
1529 }
1530
1531 for (const std::string& file : files.value()) {
1532 std::string full_key = "assets/" + file;
1533 std::string full_path = assets_dir;
1534 file::AppendPath(&full_path, file);
1535
1536 auto iter = merged_assets.find(full_key);
1537 if (iter == merged_assets.end()) {
1538 merged_assets.emplace(std::move(full_key),
1539 util::make_unique<io::RegularFile>(Source(std::move(full_path))));
1540 } else if (context_->IsVerbose()) {
1541 context_->GetDiagnostics()->Warn(DiagMessage(iter->second->GetSource())
1542 << "asset file overrides '" << full_path << "'");
1543 }
1544 }
1545 }
1546
1547 for (auto& entry : merged_assets) {
1548 uint32_t compression_flags = ArchiveEntry::kCompress;
1549 std::string extension = file::GetExtension(entry.first).to_string();
1550 if (options_.extensions_to_not_compress.count(extension) > 0) {
1551 compression_flags = 0u;
1552 }
1553
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001554 if (!io::CopyFileToArchive(context_, entry.second.get(), entry.first, compression_flags,
1555 writer)) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001556 return false;
1557 }
1558 }
1559 return true;
1560 }
1561
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001562 // Writes the AndroidManifest, ResourceTable, and all XML files referenced by the ResourceTable
1563 // to the IArchiveWriter.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001564 bool WriteApk(IArchiveWriter* writer, proguard::KeepSet* keep_set, xml::XmlResource* manifest,
1565 ResourceTable* table) {
Adam Lesinskib522f042017-04-21 16:57:59 -07001566 const bool keep_raw_values = context_->GetPackageType() == PackageType::kStaticLib;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001567 bool result = FlattenXml(context_, *manifest, "AndroidManifest.xml", keep_raw_values,
1568 true /*utf16*/, options_.output_format, writer);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001569 if (!result) {
1570 return false;
1571 }
1572
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001573 ResourceFileFlattenerOptions file_flattener_options;
1574 file_flattener_options.keep_raw_values = keep_raw_values;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001575 file_flattener_options.do_not_compress_anything = options_.do_not_compress_anything;
1576 file_flattener_options.extensions_to_not_compress = options_.extensions_to_not_compress;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001577 file_flattener_options.no_auto_version = options_.no_auto_version;
1578 file_flattener_options.no_version_vectors = options_.no_version_vectors;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09001579 file_flattener_options.no_version_transitions = options_.no_version_transitions;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001580 file_flattener_options.no_xml_namespaces = options_.no_xml_namespaces;
1581 file_flattener_options.update_proguard_spec =
1582 static_cast<bool>(options_.generate_proguard_rules_path);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07001583 file_flattener_options.output_format = options_.output_format;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001584
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001585 ResourceFileFlattener file_flattener(file_flattener_options, context_, keep_set);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001586
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001587 if (!file_flattener.Flatten(table, writer)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001588 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking file resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001589 return false;
1590 }
1591
Adam Lesinski490595a2017-11-07 17:08:07 -08001592 // Hack to fix b/68820737.
1593 // We need to modify the ResourceTable's package name, but that should NOT affect
1594 // anything else being generated, which includes the Java classes.
1595 // If required, the package name is modifed before flattening, and then modified back
1596 // to its original name.
1597 ResourceTablePackage* package_to_rewrite = nullptr;
1598 if (context_->GetPackageId() > kAppPackageId &&
1599 included_feature_base_ == make_value(context_->GetCompilationPackage())) {
1600 // The base APK is included, and this is a feature split. If the base package is
1601 // the same as this package, then we are building an old style Android Instant Apps feature
1602 // split and must apply this workaround to avoid requiring namespaces support.
1603 package_to_rewrite = table->FindPackage(context_->GetCompilationPackage());
1604 if (package_to_rewrite != nullptr) {
1605 CHECK_EQ(1u, table->packages.size()) << "can't change name of package when > 1 package";
1606
1607 std::string new_package_name =
1608 StringPrintf("%s.%s", package_to_rewrite->name.c_str(),
1609 app_info_.split_name.value_or_default("feature").c_str());
1610
1611 if (context_->IsVerbose()) {
1612 context_->GetDiagnostics()->Note(
1613 DiagMessage() << "rewriting resource package name for feature split to '"
1614 << new_package_name << "'");
1615 }
1616 package_to_rewrite->name = new_package_name;
1617 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001618 }
Adam Lesinski490595a2017-11-07 17:08:07 -08001619
1620 bool success = FlattenTable(table, options_.output_format, writer);
1621
1622 if (package_to_rewrite != nullptr) {
1623 // Change the name back.
1624 package_to_rewrite->name = context_->GetCompilationPackage();
1625 if (package_to_rewrite->id) {
1626 table->included_packages_.erase(package_to_rewrite->id.value());
1627 }
1628 }
1629
1630 if (!success) {
1631 context_->GetDiagnostics()->Error(DiagMessage() << "failed to write resource table");
1632 }
1633 return success;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001634 }
1635
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001636 int Run(const std::vector<std::string>& input_files) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001637 // Load the AndroidManifest.xml
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001638 std::unique_ptr<xml::XmlResource> manifest_xml =
1639 LoadXml(options_.manifest_path, context_->GetDiagnostics());
1640 if (!manifest_xml) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001641 return 1;
1642 }
1643
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001644 // First extract the Package name without modifying it (via --rename-manifest-package).
1645 if (Maybe<AppInfo> maybe_app_info =
1646 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics())) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001647 const AppInfo& app_info = maybe_app_info.value();
1648 context_->SetCompilationPackage(app_info.package);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001649 }
1650
Adam Lesinskic6284372017-12-04 13:46:23 -08001651 // Now that the compilation package is set, load the dependencies. This will also extract
1652 // the Android framework's versionCode and versionName, if they exist.
1653 if (!LoadSymbolsFromIncludePaths()) {
1654 return 1;
1655 }
1656
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001657 ManifestFixer manifest_fixer(options_.manifest_fixer_options);
1658 if (!manifest_fixer.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001659 return 1;
1660 }
1661
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001662 Maybe<AppInfo> maybe_app_info =
1663 ExtractAppInfoFromManifest(manifest_xml.get(), context_->GetDiagnostics());
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001664 if (!maybe_app_info) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001665 return 1;
1666 }
1667
Adam Lesinski490595a2017-11-07 17:08:07 -08001668 app_info_ = maybe_app_info.value();
1669 context_->SetMinSdkVersion(app_info_.min_sdk_version.value_or_default(0));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001670
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001671 context_->SetNameManglerPolicy(NameManglerPolicy{context_->GetCompilationPackage()});
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001672
1673 // Override the package ID when it is "android".
1674 if (context_->GetCompilationPackage() == "android") {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001675 context_->SetPackageId(0x01);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001676
1677 // Verify we're building a regular app.
Adam Lesinskib522f042017-04-21 16:57:59 -07001678 if (context_->GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001679 context_->GetDiagnostics()->Error(
1680 DiagMessage() << "package 'android' can only be built as a regular app");
1681 return 1;
1682 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001683 }
1684
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001685 TableMergerOptions table_merger_options;
1686 table_merger_options.auto_add_overlay = options_.auto_add_overlay;
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001687 table_merger_ = util::make_unique<TableMerger>(context_, &final_table_, table_merger_options);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001688
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001689 if (context_->IsVerbose()) {
1690 context_->GetDiagnostics()->Note(DiagMessage()
Adam Lesinskif34b6f42017-03-03 16:33:26 -08001691 << StringPrintf("linking package '%s' using package ID %02x",
1692 context_->GetCompilationPackage().data(),
1693 context_->GetPackageId()));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001694 }
1695
Adam Lesinski2427dce2017-11-30 15:10:28 -08001696 // Extract symbols from AndroidManifest.xml, since this isn't merged like the other XML files
1697 // in res/**/*.
1698 {
1699 XmlIdCollector collector;
1700 if (!collector.Consume(context_, manifest_xml.get())) {
1701 return false;
1702 }
1703
1704 if (!MergeExportedSymbols(manifest_xml->file.source, manifest_xml->file.exported_symbols)) {
1705 return false;
1706 }
1707 }
1708
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001709 for (const std::string& input : input_files) {
1710 if (!MergePath(input, false)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001711 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing input");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001712 return 1;
1713 }
1714 }
1715
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001716 for (const std::string& input : options_.overlay_files) {
1717 if (!MergePath(input, true)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001718 context_->GetDiagnostics()->Error(DiagMessage() << "failed parsing overlays");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001719 return 1;
1720 }
1721 }
1722
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001723 if (!VerifyNoExternalPackages()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001724 return 1;
1725 }
1726
Adam Lesinskib522f042017-04-21 16:57:59 -07001727 if (context_->GetPackageType() != PackageType::kStaticLib) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001728 PrivateAttributeMover mover;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001729 if (!mover.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001730 context_->GetDiagnostics()->Error(DiagMessage() << "failed moving private attributes");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001731 return 1;
1732 }
1733
1734 // Assign IDs if we are building a regular app.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001735 IdAssigner id_assigner(&options_.stable_id_map);
1736 if (!id_assigner.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001737 context_->GetDiagnostics()->Error(DiagMessage() << "failed assigning IDs");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001738 return 1;
1739 }
1740
1741 // Now grab each ID and emit it as a file.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001742 if (options_.resource_id_map_path) {
1743 for (auto& package : final_table_.packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001744 for (auto& type : package->types) {
1745 for (auto& entry : type->entries) {
1746 ResourceName name(package->name, type->type, entry->name);
1747 // The IDs are guaranteed to exist.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001748 options_.stable_id_map[std::move(name)] =
1749 ResourceId(package->id.value(), type->id.value(), entry->id.value());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001750 }
1751 }
1752 }
1753
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001754 if (!WriteStableIdMapToPath(context_->GetDiagnostics(), options_.stable_id_map,
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001755 options_.resource_id_map_path.value())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001756 return 1;
1757 }
1758 }
1759 } else {
1760 // Static libs are merged with other apps, and ID collisions are bad, so
1761 // verify that
1762 // no IDs have been set.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001763 if (!VerifyNoIdsSet()) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001764 return 1;
1765 }
1766 }
1767
1768 // Add the names to mangle based on our source merge earlier.
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001769 context_->SetNameManglerPolicy(
1770 NameManglerPolicy{context_->GetCompilationPackage(), table_merger_->merged_packages()});
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001771
1772 // Add our table to the symbol table.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001773 context_->GetExternalSymbols()->PrependSource(
1774 util::make_unique<ResourceTableSymbolSource>(&final_table_));
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001775
Adam Lesinski1e4b0e52017-04-27 15:01:10 -07001776 // Workaround for pre-O runtime that would treat negative resource IDs
1777 // (any ID with a package ID > 7f) as invalid. Intercept any ID (PPTTEEEE) with PP > 0x7f
1778 // and type == 'id', and return the ID 0x7fPPEEEE. IDs don't need to be real resources, they
1779 // are just identifiers.
1780 if (context_->GetMinSdkVersion() < SDK_O && context_->GetPackageType() == PackageType::kApp) {
1781 if (context_->IsVerbose()) {
1782 context_->GetDiagnostics()->Note(DiagMessage()
1783 << "enabling pre-O feature split ID rewriting");
1784 }
1785 context_->GetExternalSymbols()->SetDelegate(
1786 util::make_unique<FeatureSplitSymbolTableDelegate>(context_));
1787 }
1788
Adam Lesinski34a16872018-02-23 16:18:10 -08001789 // Before we process anything, remove the resources whose default values don't exist.
1790 // We want to force any references to these to fail the build.
1791 if (!NoDefaultResourceRemover{}.Consume(context_, &final_table_)) {
1792 context_->GetDiagnostics()->Error(DiagMessage()
1793 << "failed removing resources with no defaults");
1794 return 1;
1795 }
1796
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001797 ReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001798 if (!linker.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001799 context_->GetDiagnostics()->Error(DiagMessage() << "failed linking references");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001800 return 1;
1801 }
1802
Adam Lesinskib522f042017-04-21 16:57:59 -07001803 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001804 if (!options_.products.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001805 context_->GetDiagnostics()->Warn(DiagMessage()
1806 << "can't select products when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001807 }
1808 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001809 ProductFilter product_filter(options_.products);
1810 if (!product_filter.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001811 context_->GetDiagnostics()->Error(DiagMessage() << "failed stripping products");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001812 return 1;
1813 }
1814 }
1815
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001816 if (!options_.no_auto_version) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001817 AutoVersioner versioner;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001818 if (!versioner.Consume(context_, &final_table_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001819 context_->GetDiagnostics()->Error(DiagMessage() << "failed versioning styles");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001820 return 1;
1821 }
1822 }
1823
Adam Lesinskib522f042017-04-21 16:57:59 -07001824 if (context_->GetPackageType() != PackageType::kStaticLib && context_->GetMinSdkVersion() > 0) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001825 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001826 context_->GetDiagnostics()->Note(DiagMessage()
1827 << "collapsing resource versions for minimum SDK "
1828 << context_->GetMinSdkVersion());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001829 }
1830
1831 VersionCollapser collapser;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001832 if (!collapser.Consume(context_, &final_table_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001833 return 1;
1834 }
1835 }
1836
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001837 if (!options_.no_resource_deduping) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001838 ResourceDeduper deduper;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001839 if (!deduper.Consume(context_, &final_table_)) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001840 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001841 return 1;
1842 }
1843 }
1844
Adam Koskidc21dea2017-07-21 10:55:27 -07001845 proguard::KeepSet proguard_keep_set =
1846 proguard::KeepSet(options_.generate_conditional_proguard_rules);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001847 proguard::KeepSet proguard_main_dex_keep_set;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001848
Adam Lesinskib522f042017-04-21 16:57:59 -07001849 if (context_->GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001850 if (options_.table_splitter_options.config_filter != nullptr ||
Pierre Lecesne672384b2017-02-06 10:29:02 +00001851 !options_.table_splitter_options.preferred_densities.empty()) {
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08001852 context_->GetDiagnostics()->Warn(DiagMessage()
1853 << "can't strip resources when building static library");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001854 }
1855 } else {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001856 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
1857 // equal to the minSdk.
1858 options_.split_constraints =
1859 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001860
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001861 TableSplitter table_splitter(options_.split_constraints, options_.table_splitter_options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001862 if (!table_splitter.VerifySplitConstraints(context_)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001863 return 1;
1864 }
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001865 table_splitter.SplitTable(&final_table_);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001866
1867 // Now we need to write out the Split APKs.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001868 auto path_iter = options_.split_paths.begin();
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001869 auto split_constraints_iter = options_.split_constraints.begin();
1870 for (std::unique_ptr<ResourceTable>& split_table : table_splitter.splits()) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001871 if (context_->IsVerbose()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001872 context_->GetDiagnostics()->Note(DiagMessage(*path_iter)
1873 << "generating split with configurations '"
1874 << util::Joiner(split_constraints_iter->configs, ", ")
1875 << "'");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001876 }
1877
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001878 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(*path_iter);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001879 if (!archive_writer) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001880 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001881 return 1;
1882 }
1883
1884 // Generate an AndroidManifest.xml for each split.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001885 std::unique_ptr<xml::XmlResource> split_manifest =
Adam Lesinski490595a2017-11-07 17:08:07 -08001886 GenerateSplitManifest(app_info_, *split_constraints_iter);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001887
1888 XmlReferenceLinker linker;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001889 if (!linker.Consume(context_, split_manifest.get())) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001890 context_->GetDiagnostics()->Error(DiagMessage()
1891 << "failed to create Split AndroidManifest.xml");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001892 return 1;
1893 }
1894
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001895 if (!WriteApk(archive_writer.get(), &proguard_keep_set, split_manifest.get(),
1896 split_table.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001897 return 1;
1898 }
1899
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001900 ++path_iter;
1901 ++split_constraints_iter;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001902 }
1903 }
1904
1905 // Start writing the base APK.
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001906 std::unique_ptr<IArchiveWriter> archive_writer = MakeArchiveWriter(options_.output_path);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001907 if (!archive_writer) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001908 context_->GetDiagnostics()->Error(DiagMessage() << "failed to create archive");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001909 return 1;
1910 }
1911
1912 bool error = false;
1913 {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001914 // AndroidManifest.xml has no resource name, but the CallSite is built from the name
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001915 // (aka, which package the AndroidManifest.xml is coming from).
1916 // So we give it a package name so it can see local resources.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001917 manifest_xml->file.name.package = context_->GetCompilationPackage();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001918
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001919 XmlReferenceLinker manifest_linker;
1920 if (manifest_linker.Consume(context_, manifest_xml.get())) {
1921 if (options_.generate_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001922 !proguard::CollectProguardRulesForManifest(manifest_xml.get(), &proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001923 error = true;
1924 }
1925
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001926 if (options_.generate_main_dex_proguard_rules_path &&
Adam Koskidc21dea2017-07-21 10:55:27 -07001927 !proguard::CollectProguardRulesForManifest(manifest_xml.get(),
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001928 &proguard_main_dex_keep_set, true)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001929 error = true;
Alexandria Cornwall637b4822016-08-11 09:53:16 -07001930 }
1931
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001932 if (options_.generate_java_class_path) {
1933 if (!WriteManifestJavaFile(manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001934 error = true;
1935 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001936 }
1937
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001938 if (options_.no_xml_namespaces) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001939 // PackageParser will fail if URIs are removed from
1940 // AndroidManifest.xml.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001941 XmlNamespaceRemover namespace_remover(true /* keepUris */);
1942 if (!namespace_remover.Consume(context_, manifest_xml.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001943 error = true;
1944 }
Rohit Agrawale49bb302016-04-22 12:27:55 -07001945 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001946 } else {
1947 error = true;
1948 }
Adam Lesinski1ab598f2015-08-14 14:26:04 -07001949 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001950
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001951 if (error) {
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001952 context_->GetDiagnostics()->Error(DiagMessage() << "failed processing manifest");
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001953 return 1;
1954 }
Adam Lesinskia6fe3452015-12-09 15:20:52 -08001955
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07001956 if (!WriteApk(archive_writer.get(), &proguard_keep_set, manifest_xml.get(), &final_table_)) {
1957 return 1;
1958 }
1959
1960 if (!CopyAssetsDirsToApk(archive_writer.get())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001961 return 1;
1962 }
Adam Lesinskifb48d292015-11-07 15:52:13 -08001963
Izabela Orlowska23a6e1e2017-12-05 14:52:07 +00001964 if (options_.generate_java_class_path || options_.generate_text_symbols_path) {
Adam Lesinski1ef0fa92017-08-15 21:32:49 -07001965 if (!GenerateJavaClasses()) {
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001966 return 1;
1967 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001968 }
1969
Adam Lesinskib5dc4bd2017-02-22 19:29:29 -08001970 if (!WriteProguardFile(options_.generate_proguard_rules_path, proguard_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001971 return 1;
1972 }
1973
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001974 if (!WriteProguardFile(options_.generate_main_dex_proguard_rules_path,
1975 proguard_main_dex_keep_set)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001976 return 1;
1977 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001978 return 0;
1979 }
1980
1981 private:
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001982 LinkOptions options_;
1983 LinkContext* context_;
1984 ResourceTable final_table_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001985
Adam Lesinski490595a2017-11-07 17:08:07 -08001986 AppInfo app_info_;
1987
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001988 std::unique_ptr<TableMerger> table_merger_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001989
1990 // A pointer to the FileCollection representing the filesystem (not archives).
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001991 std::unique_ptr<io::FileCollection> file_collection_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001992
Adam Lesinski8780eb62017-10-31 17:44:39 -07001993 // A vector of IFileCollections. This is mainly here to retain ownership of the
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001994 // collections.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07001995 std::vector<std::unique_ptr<io::IFileCollection>> collections_;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07001996
Adam Lesinski8780eb62017-10-31 17:44:39 -07001997 // The set of merged APKs. This is mainly here to retain ownership of the APKs.
1998 std::vector<std::unique_ptr<LoadedApk>> merged_apks_;
1999
2000 // The set of included APKs (not merged). This is mainly here to retain ownership of the APKs.
2001 std::vector<std::unique_ptr<LoadedApk>> static_library_includes_;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002002
2003 // The set of shared libraries being used, mapping their assigned package ID to package name.
2004 std::map<size_t, std::string> shared_libs_;
Adam Lesinski490595a2017-11-07 17:08:07 -08002005
2006 // The package name of the base application, if it is included.
2007 Maybe<std::string> included_feature_base_;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002008};
2009
Chris Warrington820d72a2017-04-27 15:27:01 +01002010int Link(const std::vector<StringPiece>& args, IDiagnostics* diagnostics) {
2011 LinkContext context(diagnostics);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002012 LinkOptions options;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002013 std::vector<std::string> overlay_arg_list;
2014 std::vector<std::string> extra_java_packages;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002015 Maybe<std::string> package_id;
Adam Lesinski113ee092017-04-03 19:38:25 -07002016 std::vector<std::string> configs;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002017 Maybe<std::string> preferred_density;
2018 Maybe<std::string> product_list;
2019 bool legacy_x_flag = false;
2020 bool require_localization = false;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002021 bool verbose = false;
Adam Lesinskiceb9b2f2017-02-16 12:05:42 -08002022 bool shared_lib = false;
2023 bool static_lib = false;
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002024 bool proto_format = false;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002025 Maybe<std::string> stable_id_file_path;
2026 std::vector<std::string> split_args;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002027 Flags flags =
2028 Flags()
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002029 .RequiredFlag("-o", "Output path.", &options.output_path)
2030 .RequiredFlag("--manifest", "Path to the Android manifest to build.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002031 &options.manifest_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002032 .OptionalFlagList("-I", "Adds an Android APK to link against.", &options.include_paths)
Adam Lesinskib39ad7c2017-03-13 11:40:48 -07002033 .OptionalFlagList("-A",
2034 "An assets directory to include in the APK. These are unprocessed.",
2035 &options.assets_dirs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002036 .OptionalFlagList("-R",
2037 "Compilation unit to link, using `overlay` semantics.\n"
2038 "The last conflicting resource given takes precedence.",
2039 &overlay_arg_list)
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002040 .OptionalFlag("--package-id",
2041 "Specify the package ID to use for this app. Must be greater or equal to\n"
2042 "0x7f and can't be used with --static-lib or --shared-lib.",
2043 &package_id)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002044 .OptionalFlag("--java", "Directory in which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002045 &options.generate_java_class_path)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002046 .OptionalFlag("--proguard", "Output file for generated Proguard rules.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002047 &options.generate_proguard_rules_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002048 .OptionalFlag("--proguard-main-dex",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002049 "Output file for generated Proguard rules for the main dex.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002050 &options.generate_main_dex_proguard_rules_path)
Adam Koskidc21dea2017-07-21 10:55:27 -07002051 .OptionalSwitch("--proguard-conditional-keep-rules",
2052 "Generate conditional Proguard keep rules.",
2053 &options.generate_conditional_proguard_rules)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002054 .OptionalSwitch("--no-auto-version",
2055 "Disables automatic style and layout SDK versioning.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002056 &options.no_auto_version)
2057 .OptionalSwitch("--no-version-vectors",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002058 "Disables automatic versioning of vector drawables. Use this only\n"
2059 "when building with vector drawable support library.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002060 &options.no_version_vectors)
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002061 .OptionalSwitch("--no-version-transitions",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002062 "Disables automatic versioning of transition resources. Use this only\n"
2063 "when building with transition support library.",
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002064 &options.no_version_transitions)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002065 .OptionalSwitch("--no-resource-deduping",
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002066 "Disables automatic deduping of resources with\n"
2067 "identical values across compatible configurations.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002068 &options.no_resource_deduping)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002069 .OptionalSwitch("--enable-sparse-encoding",
2070 "Enables encoding sparse entries using a binary search tree.\n"
2071 "This decreases APK size at the cost of resource retrieval performance.",
2072 &options.table_flattener_options.use_sparse_entries)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002073 .OptionalSwitch("-x", "Legacy flag that specifies to use the package identifier 0x01.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002074 &legacy_x_flag)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002075 .OptionalSwitch("-z", "Require localization of strings marked 'suggested'.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002076 &require_localization)
Adam Lesinski113ee092017-04-03 19:38:25 -07002077 .OptionalFlagList("-c",
Adam Lesinski418763f2017-04-11 17:36:53 -07002078 "Comma separated list of configurations to include. The default\n"
2079 "is all configurations.",
2080 &configs)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002081 .OptionalFlag("--preferred-density",
2082 "Selects the closest matching density and strips out all others.",
2083 &preferred_density)
2084 .OptionalFlag("--product", "Comma separated list of product names to keep", &product_list)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002085 .OptionalSwitch("--output-to-dir",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002086 "Outputs the APK contents to a directory specified by -o.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002087 &options.output_to_directory)
2088 .OptionalSwitch("--no-xml-namespaces",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002089 "Removes XML namespace prefix and URI information from\n"
2090 "AndroidManifest.xml and XML binaries in res/*.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002091 &options.no_xml_namespaces)
2092 .OptionalFlag("--min-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002093 "Default minimum SDK version to use for AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002094 &options.manifest_fixer_options.min_sdk_version_default)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002095 .OptionalFlag("--target-sdk-version",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002096 "Default target SDK version to use for AndroidManifest.xml.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002097 &options.manifest_fixer_options.target_sdk_version_default)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002098 .OptionalFlag("--version-code",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002099 "Version code (integer) to inject into the AndroidManifest.xml if none is\n"
2100 "present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002101 &options.manifest_fixer_options.version_code_default)
2102 .OptionalFlag("--version-name",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002103 "Version name to inject into the AndroidManifest.xml if none is present.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002104 &options.manifest_fixer_options.version_name_default)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002105 .OptionalSwitch("--shared-lib", "Generates a shared Android runtime library.",
2106 &shared_lib)
2107 .OptionalSwitch("--static-lib", "Generate a static Android library.", &static_lib)
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002108 .OptionalSwitch("--proto-format",
2109 "Generates compiled resources in Protobuf format.\n"
2110 "Suitable as input to the bundle tool for generating an App Bundle.",
2111 &proto_format)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002112 .OptionalSwitch("--no-static-lib-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002113 "Merge all library resources under the app's package.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002114 &options.no_static_lib_packages)
2115 .OptionalSwitch("--non-final-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002116 "Generates R.java without the final modifier. This is implied when\n"
2117 "--static-lib is specified.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002118 &options.generate_non_final_ids)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002119 .OptionalFlag("--stable-ids", "File containing a list of name to ID mapping.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002120 &stable_id_file_path)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002121 .OptionalFlag("--emit-ids",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002122 "Emit a file at the given path with a list of name to ID mappings,\n"
2123 "suitable for use with --stable-ids.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002124 &options.resource_id_map_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002125 .OptionalFlag("--private-symbols",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002126 "Package name to use when generating R.java for private symbols.\n"
2127 "If not specified, public and private symbols will use the application's\n"
2128 "package name.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002129 &options.private_symbols)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002130 .OptionalFlag("--custom-package", "Custom Java package under which to generate R.java.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002131 &options.custom_java_package)
2132 .OptionalFlagList("--extra-packages",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002133 "Generate the same R.java but with different package names.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002134 &extra_java_packages)
2135 .OptionalFlagList("--add-javadoc-annotation",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002136 "Adds a JavaDoc annotation to all generated Java classes.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002137 &options.javadoc_annotations)
Adam Lesinski418763f2017-04-11 17:36:53 -07002138 .OptionalFlag("--output-text-symbols",
2139 "Generates a text file containing the resource symbols of the R class in\n"
2140 "the specified folder.",
2141 &options.generate_text_symbols_path)
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002142 .OptionalSwitch("--auto-add-overlay",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002143 "Allows the addition of new resources in overlays without\n"
2144 "<add-resource> tags.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002145 &options.auto_add_overlay)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002146 .OptionalFlag("--rename-manifest-package", "Renames the package in AndroidManifest.xml.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002147 &options.manifest_fixer_options.rename_manifest_package)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002148 .OptionalFlag("--rename-instrumentation-target-package",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002149 "Changes the name of the target package for instrumentation. Most useful\n"
2150 "when used in conjunction with --rename-manifest-package.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002151 &options.manifest_fixer_options.rename_instrumentation_target_package)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002152 .OptionalFlagList("-0", "File extensions not to compress.",
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002153 &options.extensions_to_not_compress)
Izabela Orlowskaad9e1322017-12-19 16:22:42 +00002154 .OptionalSwitch("--warn-manifest-validation",
2155 "Treat manifest validation errors as warnings.",
2156 &options.manifest_fixer_options.warn_validation)
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002157 .OptionalFlagList("--split",
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002158 "Split resources matching a set of configs out to a Split APK.\n"
Adam Lesinskidb091572017-04-13 12:48:56 -07002159 "Syntax: path/to/output.apk:<config>[,<config>[...]].\n"
2160 "On Windows, use a semicolon ';' separator instead.",
Adam Lesinskic8f71aa2017-02-08 07:03:50 -08002161 &split_args)
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002162 .OptionalSwitch("-v", "Enables verbose logging.", &verbose);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002163
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002164 if (!flags.Parse("aapt2 link", args, &std::cerr)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002165 return 1;
2166 }
2167
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002168 // Expand all argument-files passed into the command line. These start with '@'.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002169 std::vector<std::string> arg_list;
2170 for (const std::string& arg : flags.GetArgs()) {
2171 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002172 const std::string path = arg.substr(1, arg.size() - 1);
2173 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002174 if (!file::AppendArgsFromFile(path, &arg_list, &error)) {
2175 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002176 return 1;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002177 }
2178 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002179 arg_list.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002180 }
2181 }
2182
2183 // Expand all argument-files passed to -R.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002184 for (const std::string& arg : overlay_arg_list) {
2185 if (util::StartsWith(arg, "@")) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002186 const std::string path = arg.substr(1, arg.size() - 1);
2187 std::string error;
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002188 if (!file::AppendArgsFromFile(path, &options.overlay_files, &error)) {
2189 context.GetDiagnostics()->Error(DiagMessage(path) << error);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002190 return 1;
2191 }
2192 } else {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002193 options.overlay_files.push_back(arg);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002194 }
2195 }
2196
2197 if (verbose) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002198 context.SetVerbose(verbose);
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002199 }
2200
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002201 if (int{shared_lib} + int{static_lib} + int{proto_format} > 1) {
2202 context.GetDiagnostics()->Error(
2203 DiagMessage()
2204 << "only one of --shared-lib, --static-lib, or --proto_format can be defined");
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002205 return 1;
2206 }
2207
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002208 // The default build type.
2209 context.SetPackageType(PackageType::kApp);
2210 context.SetPackageId(kAppPackageId);
2211
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002212 if (shared_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002213 context.SetPackageType(PackageType::kSharedLib);
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002214 context.SetPackageId(0x00);
2215 } else if (static_lib) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002216 context.SetPackageType(PackageType::kStaticLib);
Adam Lesinskie59f0d82017-10-13 09:36:53 -07002217 options.output_format = OutputFormat::kProto;
2218 } else if (proto_format) {
2219 options.output_format = OutputFormat::kProto;
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002220 }
2221
2222 if (package_id) {
Adam Lesinskib522f042017-04-21 16:57:59 -07002223 if (context.GetPackageType() != PackageType::kApp) {
Adam Lesinskif34b6f42017-03-03 16:33:26 -08002224 context.GetDiagnostics()->Error(
2225 DiagMessage() << "can't specify --package-id when not building a regular app");
2226 return 1;
2227 }
2228
2229 const Maybe<uint32_t> maybe_package_id_int = ResourceUtils::ParseInt(package_id.value());
2230 if (!maybe_package_id_int) {
2231 context.GetDiagnostics()->Error(DiagMessage() << "package ID '" << package_id.value()
2232 << "' is not a valid integer");
2233 return 1;
2234 }
2235
2236 const uint32_t package_id_int = maybe_package_id_int.value();
2237 if (package_id_int < kAppPackageId || package_id_int > std::numeric_limits<uint8_t>::max()) {
2238 context.GetDiagnostics()->Error(
2239 DiagMessage() << StringPrintf(
2240 "invalid package ID 0x%02x. Must be in the range 0x7f-0xff.", package_id_int));
2241 return 1;
2242 }
2243 context.SetPackageId(static_cast<uint8_t>(package_id_int));
2244 }
2245
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002246 // Populate the set of extra packages for which to generate R.java.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002247 for (std::string& extra_package : extra_java_packages) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002248 // A given package can actually be a colon separated list of packages.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002249 for (StringPiece package : util::Split(extra_package, ':')) {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002250 options.extra_java_packages.insert(package.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002251 }
2252 }
2253
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002254 if (product_list) {
2255 for (StringPiece product : util::Tokenize(product_list.value(), ',')) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002256 if (product != "" && product != "default") {
Adam Lesinskid5083f62017-01-16 15:07:21 -08002257 options.products.insert(product.to_string());
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002258 }
2259 }
2260 }
2261
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002262 std::unique_ptr<IConfigFilter> filter;
Mihai Nitaf4dacf22017-04-07 08:25:06 -07002263 if (!configs.empty()) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002264 filter = ParseConfigFilterParameters(configs, context.GetDiagnostics());
2265 if (filter == nullptr) {
2266 return 1;
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002267 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002268 options.table_splitter_options.config_filter = filter.get();
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002269 }
2270
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002271 if (preferred_density) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002272 Maybe<uint16_t> density =
2273 ParseTargetDensityParameter(preferred_density.value(), context.GetDiagnostics());
2274 if (!density) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002275 return 1;
Adam Lesinskic51562c2016-04-28 11:12:38 -07002276 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002277 options.table_splitter_options.preferred_densities.push_back(density.value());
2278 }
Adam Lesinskic51562c2016-04-28 11:12:38 -07002279
Adam Lesinskid0f492d2017-04-03 18:12:45 -07002280 // Parse the split parameters.
2281 for (const std::string& split_arg : split_args) {
2282 options.split_paths.push_back({});
2283 options.split_constraints.push_back({});
2284 if (!ParseSplitParameter(split_arg, context.GetDiagnostics(), &options.split_paths.back(),
2285 &options.split_constraints.back())) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002286 return 1;
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002287 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002288 }
Adam Lesinski1e21ff02016-06-24 14:57:58 -07002289
Adam Lesinskib522f042017-04-21 16:57:59 -07002290 if (context.GetPackageType() != PackageType::kStaticLib && stable_id_file_path) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002291 if (!LoadStableIdMap(context.GetDiagnostics(), stable_id_file_path.value(),
2292 &options.stable_id_map)) {
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002293 return 1;
Adam Lesinski64587af2016-02-18 18:33:06 -08002294 }
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002295 }
Adam Lesinski64587af2016-02-18 18:33:06 -08002296
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002297 // Populate some default no-compress extensions that are already compressed.
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002298 options.extensions_to_not_compress.insert(
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002299 {".jpg", ".jpeg", ".png", ".gif", ".wav", ".mp2", ".mp3", ".ogg",
2300 ".aac", ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet", ".rtttl",
2301 ".imy", ".xmf", ".mp4", ".m4a", ".m4v", ".3gp", ".3gpp", ".3g2",
2302 ".3gpp2", ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"});
2303
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002304 // Turn off auto versioning for static-libs.
Adam Lesinskib522f042017-04-21 16:57:59 -07002305 if (context.GetPackageType() == PackageType::kStaticLib) {
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002306 options.no_auto_version = true;
2307 options.no_version_vectors = true;
Yuichi Araki4d35cca2017-01-18 20:42:17 +09002308 options.no_version_transitions = true;
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002309 }
Adam Lesinskie4bb9eb2016-02-12 22:18:51 -08002310
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002311 LinkCommand cmd(&context, options);
Adam Lesinskice5e56e2016-10-21 17:56:45 -07002312 return cmd.Run(arg_list);
Adam Lesinski1ab598f2015-08-14 14:26:04 -07002313}
2314
Adam Lesinskicacb28f2016-10-19 12:18:14 -07002315} // namespace aapt