blob: b4cba8c2801cc4cd34d55bcb2d44b2ff4cd85351 [file] [log] [blame]
Adam Lesinskid0f492d2017-04-03 18:12:45 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ryan Mitchell833a1a62018-07-10 13:51:36 -070017#include "Optimize.h"
18
Adam Lesinskid0f492d2017-04-03 18:12:45 -070019#include <memory>
20#include <vector>
21
Luke Nicholsonb0643302017-12-01 15:29:03 -080022#include "android-base/file.h"
Shane Farmer57669432017-06-19 12:52:04 -070023#include "android-base/stringprintf.h"
Adam Lesinskid3ffa8442017-09-28 13:34:35 -070024
Shane Farmer0a5b2012017-06-22 12:24:12 -070025#include "androidfw/ResourceTypes.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070026#include "androidfw/StringPiece.h"
27
28#include "Diagnostics.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070029#include "LoadedApk.h"
30#include "ResourceUtils.h"
31#include "SdkConstants.h"
32#include "ValueVisitor.h"
33#include "cmd/Util.h"
Shane Farmer57669432017-06-19 12:52:04 -070034#include "configuration/ConfigurationParser.h"
35#include "filter/AbiFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070036#include "format/binary/TableFlattener.h"
37#include "format/binary/XmlFlattener.h"
Adam Lesinski00451162017-10-03 07:44:08 -070038#include "io/BigBufferStream.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070039#include "io/Util.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070040#include "optimize/MultiApkGenerator.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070041#include "optimize/ResourceDeduper.h"
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050042#include "optimize/ResourceFilter.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070043#include "optimize/VersionCollapser.h"
44#include "split/TableSplitter.h"
Shane Farmer57669432017-06-19 12:52:04 -070045#include "util/Files.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070046#include "util/Util.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070047
Shane Farmer57669432017-06-19 12:52:04 -070048using ::aapt::configuration::Abi;
Shane Farmercb6c3f92017-11-27 13:19:36 -080049using ::aapt::configuration::OutputArtifact;
Shane Farmer0a5b2012017-06-22 12:24:12 -070050using ::android::ResTable_config;
Shane Farmer57669432017-06-19 12:52:04 -070051using ::android::StringPiece;
Luke Nicholsonb0643302017-12-01 15:29:03 -080052using ::android::base::ReadFileToString;
Shane Farmer0a5b2012017-06-22 12:24:12 -070053using ::android::base::StringAppendF;
Shane Farmer57669432017-06-19 12:52:04 -070054using ::android::base::StringPrintf;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070055
56namespace aapt {
57
Adam Lesinskid0f492d2017-04-03 18:12:45 -070058class OptimizeContext : public IAaptContext {
59 public:
Adam Lesinskib522f042017-04-21 16:57:59 -070060 OptimizeContext() = default;
61
62 PackageType GetPackageType() override {
63 // Not important here. Using anything other than kApp adds EXTRA validation, which we want to
64 // avoid.
65 return PackageType::kApp;
66 }
67
Adam Lesinskid0f492d2017-04-03 18:12:45 -070068 IDiagnostics* GetDiagnostics() override {
69 return &diagnostics_;
70 }
71
72 NameMangler* GetNameMangler() override {
73 UNIMPLEMENTED(FATAL);
74 return nullptr;
75 }
76
77 const std::string& GetCompilationPackage() override {
78 static std::string empty;
79 return empty;
80 }
81
82 uint8_t GetPackageId() override {
83 return 0;
84 }
85
86 SymbolTable* GetExternalSymbols() override {
87 UNIMPLEMENTED(FATAL);
88 return nullptr;
89 }
90
91 bool IsVerbose() override {
92 return verbose_;
93 }
94
95 void SetVerbose(bool val) {
96 verbose_ = val;
97 }
98
99 void SetMinSdkVersion(int sdk_version) {
100 sdk_version_ = sdk_version;
101 }
102
103 int GetMinSdkVersion() override {
104 return sdk_version_;
105 }
106
Chris Warrington481f0272018-02-06 14:03:39 +0000107 bool IsAutoNamespace() override {
108 return false;
109 }
110
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700111 private:
Adam Lesinskib522f042017-04-21 16:57:59 -0700112 DISALLOW_COPY_AND_ASSIGN(OptimizeContext);
113
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700114 StdErrDiagnostics diagnostics_;
115 bool verbose_ = false;
116 int sdk_version_ = 0;
117};
118
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700119class Optimizer {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700120 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700121 Optimizer(OptimizeContext* context, const OptimizeOptions& options)
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700122 : options_(options), context_(context) {
123 }
124
125 int Run(std::unique_ptr<LoadedApk> apk) {
126 if (context_->IsVerbose()) {
127 context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
128 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500129 if (!options_.resources_blacklist.empty()) {
130 ResourceFilter filter(options_.resources_blacklist);
131 if (!filter.Consume(context_, apk->GetResourceTable())) {
132 context_->GetDiagnostics()->Error(DiagMessage() << "failed filtering resources");
133 return 1;
134 }
135 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700136
137 VersionCollapser collapser;
138 if (!collapser.Consume(context_, apk->GetResourceTable())) {
139 return 1;
140 }
141
142 ResourceDeduper deduper;
143 if (!deduper.Consume(context_, apk->GetResourceTable())) {
144 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
145 return 1;
146 }
147
148 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
149 // equal to the minSdk.
150 options_.split_constraints =
151 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
152
153 // Stripping the APK using the TableSplitter. The resource table is modified in place in the
154 // LoadedApk.
155 TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
156 if (!splitter.VerifySplitConstraints(context_)) {
157 return 1;
158 }
159 splitter.SplitTable(apk->GetResourceTable());
160
161 auto path_iter = options_.split_paths.begin();
162 auto split_constraints_iter = options_.split_constraints.begin();
163 for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
164 if (context_->IsVerbose()) {
165 context_->GetDiagnostics()->Note(
166 DiagMessage(*path_iter) << "generating split with configurations '"
167 << util::Joiner(split_constraints_iter->configs, ", ") << "'");
168 }
169
170 // Generate an AndroidManifest.xml for each split.
171 std::unique_ptr<xml::XmlResource> split_manifest =
172 GenerateSplitManifest(options_.app_info, *split_constraints_iter);
173 std::unique_ptr<IArchiveWriter> split_writer =
174 CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
175 if (!split_writer) {
176 return 1;
177 }
178
179 if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
180 return 1;
181 }
182
183 ++path_iter;
184 ++split_constraints_iter;
185 }
186
Shane Farmercb6c3f92017-11-27 13:19:36 -0800187 if (options_.apk_artifacts && options_.output_dir) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700188 MultiApkGenerator generator{apk.get(), context_};
Shane Farmer666de342017-11-29 16:07:51 -0800189 MultiApkGeneratorOptions generator_options = {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800190 options_.output_dir.value(), options_.apk_artifacts.value(),
191 options_.table_flattener_options, options_.kept_artifacts};
Shane Farmerefe45392017-08-21 14:39:28 -0700192 if (!generator.FromBaseApk(generator_options)) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700193 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700194 }
195 }
196
197 if (options_.output_path) {
198 std::unique_ptr<IArchiveWriter> writer =
199 CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path.value());
200 if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
201 return 1;
202 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700203 }
204
205 return 0;
206 }
207
208 private:
209 bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
210 BigBuffer manifest_buffer(4096);
211 XmlFlattener xml_flattener(&manifest_buffer, {});
212 if (!xml_flattener.Consume(context_, manifest)) {
213 return false;
214 }
215
216 io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
217 if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
218 ArchiveEntry::kCompress, writer)) {
219 return false;
220 }
221
222 std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
223 for (auto& pkg : table->packages) {
224 for (auto& type : pkg->types) {
225 // Sort by config and name, so that we get better locality in the zip file.
226 config_sorted_files.clear();
227
228 for (auto& entry : type->entries) {
229 for (auto& config_value : entry->values) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700230 auto* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700231 if (file_ref == nullptr) {
232 continue;
233 }
234
235 if (file_ref->file == nullptr) {
236 ResourceNameRef name(pkg->name, type->type, entry->name);
Adam Lesinski742888f2017-04-28 15:34:52 -0700237 context_->GetDiagnostics()->Warn(DiagMessage(file_ref->GetSource())
Shane Farmer57669432017-06-19 12:52:04 -0700238 << "file for resource " << name << " with config '"
239 << config_value->config << "' not found");
Adam Lesinski742888f2017-04-28 15:34:52 -0700240 continue;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700241 }
242
243 const StringPiece entry_name = entry->name;
244 config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
245 }
246 }
247
248 for (auto& entry : config_sorted_files) {
249 FileReference* file_ref = entry.second;
Pierre Lecesned55bef72017-11-10 22:31:01 +0000250 if (!io::CopyFileToArchivePreserveCompression(context_, file_ref->file, *file_ref->path,
251 writer)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700252 return false;
253 }
254 }
255 }
256 }
257
258 BigBuffer table_buffer(4096);
259 TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
260 if (!table_flattener.Consume(context_, table)) {
261 return false;
262 }
263
264 io::BigBufferInputStream table_buffer_in(&table_buffer);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700265 return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
266 ArchiveEntry::kAlign, writer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700267 }
268
269 OptimizeOptions options_;
270 OptimizeContext* context_;
271};
272
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500273bool ExtractObfuscationWhitelistFromConfig(const std::string& path, OptimizeContext* context,
274 OptimizeOptions* options) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800275 std::string contents;
276 if (!ReadFileToString(path, &contents, true)) {
277 context->GetDiagnostics()->Error(DiagMessage()
278 << "failed to parse whitelist from config file: " << path);
279 return false;
280 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500281 for (StringPiece resource_name : util::Tokenize(contents, ',')) {
282 options->table_flattener_options.whitelisted_resources.insert(
283 resource_name.to_string());
284 }
285 return true;
286}
287
288bool ExtractConfig(const std::string& path, OptimizeContext* context,
289 OptimizeOptions* options) {
290 std::string content;
291 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
292 context->GetDiagnostics()->Error(DiagMessage(path) << "failed reading whitelist");
293 return false;
294 }
295
296 size_t line_no = 0;
297 for (StringPiece line : util::Tokenize(content, '\n')) {
298 line_no++;
299 line = util::TrimWhitespace(line);
300 if (line.empty()) {
301 continue;
302 }
303
304 auto split_line = util::Split(line, '#');
305 if (split_line.size() < 2) {
306 context->GetDiagnostics()->Error(DiagMessage(line) << "No # found in line");
307 return false;
308 }
309 StringPiece resource_string = split_line[0];
310 StringPiece directives = split_line[1];
311 ResourceNameRef resource_name;
312 if (!ResourceUtils::ParseResourceName(resource_string, &resource_name)) {
313 context->GetDiagnostics()->Error(DiagMessage(line) << "Malformed resource name");
314 return false;
315 }
316 if (!resource_name.package.empty()) {
317 context->GetDiagnostics()->Error(DiagMessage(line)
318 << "Package set for resource. Only use type/name");
319 return false;
320 }
321 for (StringPiece directive : util::Tokenize(directives, ',')) {
322 if (directive == "remove") {
323 options->resources_blacklist.insert(resource_name.ToResourceName());
324 } else if (directive == "no_obfuscate") {
325 options->table_flattener_options.whitelisted_resources.insert(
326 resource_name.entry.to_string());
327 }
328 }
Luke Nicholsonb0643302017-12-01 15:29:03 -0800329 }
330 return true;
331}
332
Adam Lesinski8780eb62017-10-31 17:44:39 -0700333bool ExtractAppDataFromManifest(OptimizeContext* context, const LoadedApk* apk,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700334 OptimizeOptions* out_options) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700335 const xml::XmlResource* manifest = apk->GetManifest();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700336 if (manifest == nullptr) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700337 return false;
338 }
339
Adam Lesinski8780eb62017-10-31 17:44:39 -0700340 Maybe<AppInfo> app_info = ExtractAppInfoFromBinaryManifest(*manifest, context->GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700341 if (!app_info) {
342 context->GetDiagnostics()->Error(DiagMessage()
343 << "failed to extract data from AndroidManifest.xml");
344 return false;
345 }
346
347 out_options->app_info = std::move(app_info.value());
348 context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
349 return true;
350}
351
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700352int OptimizeCommand::Action(const std::vector<std::string>& args) {
353 if (args.size() != 1u) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700354 std::cerr << "must have one APK as argument.\n\n";
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700355 Usage(&std::cerr);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700356 return 1;
357 }
358
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700359 const std::string& apk_path = args[0];
360 OptimizeContext context;
361 context.SetVerbose(verbose_);
Shane Farmer9ecc0752017-08-24 15:55:36 -0700362 IDiagnostics* diag = context.GetDiagnostics();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700363
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700364 if (config_path_) {
365 std::string& path = config_path_.value();
Shane Farmer57669432017-06-19 12:52:04 -0700366 Maybe<ConfigurationParser> for_path = ConfigurationParser::ForPath(path);
367 if (for_path) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700368 options_.apk_artifacts = for_path.value().WithDiagnostics(diag).Parse(apk_path);
369 if (!options_.apk_artifacts) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800370 diag->Error(DiagMessage() << "Failed to parse the output artifact list");
371 return 1;
372 }
373
Shane Farmer57669432017-06-19 12:52:04 -0700374 } else {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700375 diag->Error(DiagMessage() << "Could not parse config file " << path);
Shane Farmer57669432017-06-19 12:52:04 -0700376 return 1;
377 }
Shane Farmer9ecc0752017-08-24 15:55:36 -0700378
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700379 if (print_only_) {
380 for (const OutputArtifact& artifact : options_.apk_artifacts.value()) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800381 std::cout << artifact.name << std::endl;
Shane Farmer9ecc0752017-08-24 15:55:36 -0700382 }
383 return 0;
384 }
385
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700386 if (!kept_artifacts_.empty()) {
387 for (const std::string& artifact_str : kept_artifacts_) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800388 for (const StringPiece& artifact : util::Tokenize(artifact_str, ',')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700389 options_.kept_artifacts.insert(artifact.to_string());
Shane Farmer666de342017-11-29 16:07:51 -0800390 }
391 }
392 }
393
Shane Farmer9ecc0752017-08-24 15:55:36 -0700394 // Since we know that we are going to process the APK (not just print targets), make sure we
395 // have somewhere to write them to.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700396 if (!options_.output_dir) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700397 diag->Error(DiagMessage() << "Output directory is required when using a configuration file");
398 return 1;
399 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700400 } else if (print_only_) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700401 diag->Error(DiagMessage() << "Asked to print artifacts without providing a configurations");
402 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700403 }
404
Shane Farmer2c122412017-12-15 16:55:54 -0800405 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(apk_path, context.GetDiagnostics());
406 if (!apk) {
407 return 1;
408 }
409
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700410 if (target_densities_) {
Shane Farmer2c122412017-12-15 16:55:54 -0800411 // Parse the target screen densities.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700412 for (const StringPiece& config_str : util::Tokenize(target_densities_.value(), ',')) {
Shane Farmer2c122412017-12-15 16:55:54 -0800413 Maybe<uint16_t> target_density = ParseTargetDensityParameter(config_str, diag);
414 if (!target_density) {
415 return 1;
416 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700417 options_.table_splitter_options.preferred_densities.push_back(target_density.value());
Shane Farmer2c122412017-12-15 16:55:54 -0800418 }
419 }
420
421 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700422 if (!configs_.empty()) {
423 filter = ParseConfigFilterParameters(configs_, diag);
Shane Farmer2c122412017-12-15 16:55:54 -0800424 if (filter == nullptr) {
425 return 1;
426 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700427 options_.table_splitter_options.config_filter = filter.get();
Shane Farmer2c122412017-12-15 16:55:54 -0800428 }
429
430 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700431 for (const std::string& split_arg : split_args_) {
432 options_.split_paths.emplace_back();
433 options_.split_constraints.emplace_back();
434 if (!ParseSplitParameter(split_arg, diag, &options_.split_paths.back(),
435 &options_.split_constraints.back())) {
Shane Farmer2c122412017-12-15 16:55:54 -0800436 return 1;
437 }
438 }
439
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700440 if (options_.table_flattener_options.collapse_key_stringpool) {
441 if (whitelist_path_) {
442 std::string& path = whitelist_path_.value();
443 if (!ExtractObfuscationWhitelistFromConfig(path, &context, &options_)) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800444 return 1;
445 }
446 }
447 }
448
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700449 if (resources_config_path_) {
450 std::string& path = resources_config_path_.value();
451 if (!ExtractConfig(path, &context, &options_)) {
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500452 return 1;
453 }
454 }
455
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700456 if (!ExtractAppDataFromManifest(&context, apk.get(), &options_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700457 return 1;
458 }
459
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700460 Optimizer cmd(&context, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700461 return cmd.Run(std::move(apk));
462}
463
464} // namespace aapt