blob: 328b0beda372348e9978e21bd203601f2714c607 [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
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020025#include "androidfw/ConfigDescription.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070026#include "androidfw/ResourceTypes.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070027#include "androidfw/StringPiece.h"
28
29#include "Diagnostics.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070030#include "LoadedApk.h"
31#include "ResourceUtils.h"
32#include "SdkConstants.h"
33#include "ValueVisitor.h"
34#include "cmd/Util.h"
Shane Farmer57669432017-06-19 12:52:04 -070035#include "configuration/ConfigurationParser.h"
36#include "filter/AbiFilter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070037#include "format/binary/TableFlattener.h"
38#include "format/binary/XmlFlattener.h"
Adam Lesinski00451162017-10-03 07:44:08 -070039#include "io/BigBufferStream.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070040#include "io/Util.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070041#include "optimize/MultiApkGenerator.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070042#include "optimize/ResourceDeduper.h"
Mohamed Heikald3c5fb62018-01-12 11:37:26 -050043#include "optimize/ResourceFilter.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070044#include "optimize/VersionCollapser.h"
45#include "split/TableSplitter.h"
Shane Farmer57669432017-06-19 12:52:04 -070046#include "util/Files.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070047#include "util/Util.h"
Adam Lesinskid0f492d2017-04-03 18:12:45 -070048
Shane Farmer57669432017-06-19 12:52:04 -070049using ::aapt::configuration::Abi;
Shane Farmercb6c3f92017-11-27 13:19:36 -080050using ::aapt::configuration::OutputArtifact;
Mårten Kongstad24c9aa62018-06-20 08:46:41 +020051using ::android::ConfigDescription;
Shane Farmer0a5b2012017-06-22 12:24:12 -070052using ::android::ResTable_config;
Shane Farmer57669432017-06-19 12:52:04 -070053using ::android::StringPiece;
Luke Nicholsonb0643302017-12-01 15:29:03 -080054using ::android::base::ReadFileToString;
Shane Farmer0a5b2012017-06-22 12:24:12 -070055using ::android::base::StringAppendF;
Shane Farmer57669432017-06-19 12:52:04 -070056using ::android::base::StringPrintf;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070057
58namespace aapt {
59
Adam Lesinskid0f492d2017-04-03 18:12:45 -070060class OptimizeContext : public IAaptContext {
61 public:
Adam Lesinskib522f042017-04-21 16:57:59 -070062 OptimizeContext() = default;
63
64 PackageType GetPackageType() override {
65 // Not important here. Using anything other than kApp adds EXTRA validation, which we want to
66 // avoid.
67 return PackageType::kApp;
68 }
69
Adam Lesinskid0f492d2017-04-03 18:12:45 -070070 IDiagnostics* GetDiagnostics() override {
71 return &diagnostics_;
72 }
73
74 NameMangler* GetNameMangler() override {
75 UNIMPLEMENTED(FATAL);
76 return nullptr;
77 }
78
79 const std::string& GetCompilationPackage() override {
80 static std::string empty;
81 return empty;
82 }
83
84 uint8_t GetPackageId() override {
85 return 0;
86 }
87
88 SymbolTable* GetExternalSymbols() override {
89 UNIMPLEMENTED(FATAL);
90 return nullptr;
91 }
92
93 bool IsVerbose() override {
94 return verbose_;
95 }
96
97 void SetVerbose(bool val) {
98 verbose_ = val;
99 }
100
101 void SetMinSdkVersion(int sdk_version) {
102 sdk_version_ = sdk_version;
103 }
104
105 int GetMinSdkVersion() override {
106 return sdk_version_;
107 }
108
109 private:
Adam Lesinskib522f042017-04-21 16:57:59 -0700110 DISALLOW_COPY_AND_ASSIGN(OptimizeContext);
111
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700112 StdErrDiagnostics diagnostics_;
113 bool verbose_ = false;
114 int sdk_version_ = 0;
115};
116
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700117class Optimizer {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700118 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700119 Optimizer(OptimizeContext* context, const OptimizeOptions& options)
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700120 : options_(options), context_(context) {
121 }
122
123 int Run(std::unique_ptr<LoadedApk> apk) {
124 if (context_->IsVerbose()) {
125 context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
126 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500127 if (!options_.resources_blacklist.empty()) {
128 ResourceFilter filter(options_.resources_blacklist);
129 if (!filter.Consume(context_, apk->GetResourceTable())) {
130 context_->GetDiagnostics()->Error(DiagMessage() << "failed filtering resources");
131 return 1;
132 }
133 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700134
135 VersionCollapser collapser;
136 if (!collapser.Consume(context_, apk->GetResourceTable())) {
137 return 1;
138 }
139
140 ResourceDeduper deduper;
141 if (!deduper.Consume(context_, apk->GetResourceTable())) {
142 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
143 return 1;
144 }
145
146 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
147 // equal to the minSdk.
148 options_.split_constraints =
149 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
150
151 // Stripping the APK using the TableSplitter. The resource table is modified in place in the
152 // LoadedApk.
153 TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
154 if (!splitter.VerifySplitConstraints(context_)) {
155 return 1;
156 }
157 splitter.SplitTable(apk->GetResourceTable());
158
159 auto path_iter = options_.split_paths.begin();
160 auto split_constraints_iter = options_.split_constraints.begin();
161 for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
162 if (context_->IsVerbose()) {
163 context_->GetDiagnostics()->Note(
164 DiagMessage(*path_iter) << "generating split with configurations '"
165 << util::Joiner(split_constraints_iter->configs, ", ") << "'");
166 }
167
168 // Generate an AndroidManifest.xml for each split.
169 std::unique_ptr<xml::XmlResource> split_manifest =
170 GenerateSplitManifest(options_.app_info, *split_constraints_iter);
171 std::unique_ptr<IArchiveWriter> split_writer =
172 CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
173 if (!split_writer) {
174 return 1;
175 }
176
177 if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
178 return 1;
179 }
180
181 ++path_iter;
182 ++split_constraints_iter;
183 }
184
Shane Farmercb6c3f92017-11-27 13:19:36 -0800185 if (options_.apk_artifacts && options_.output_dir) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700186 MultiApkGenerator generator{apk.get(), context_};
Shane Farmer666de342017-11-29 16:07:51 -0800187 MultiApkGeneratorOptions generator_options = {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800188 options_.output_dir.value(), options_.apk_artifacts.value(),
189 options_.table_flattener_options, options_.kept_artifacts};
Shane Farmerefe45392017-08-21 14:39:28 -0700190 if (!generator.FromBaseApk(generator_options)) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700191 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700192 }
193 }
194
195 if (options_.output_path) {
196 std::unique_ptr<IArchiveWriter> writer =
197 CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path.value());
198 if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
199 return 1;
200 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700201 }
202
203 return 0;
204 }
205
206 private:
207 bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
208 BigBuffer manifest_buffer(4096);
209 XmlFlattener xml_flattener(&manifest_buffer, {});
210 if (!xml_flattener.Consume(context_, manifest)) {
211 return false;
212 }
213
214 io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
215 if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
216 ArchiveEntry::kCompress, writer)) {
217 return false;
218 }
219
220 std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
221 for (auto& pkg : table->packages) {
222 for (auto& type : pkg->types) {
223 // Sort by config and name, so that we get better locality in the zip file.
224 config_sorted_files.clear();
225
226 for (auto& entry : type->entries) {
227 for (auto& config_value : entry->values) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700228 auto* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700229 if (file_ref == nullptr) {
230 continue;
231 }
232
233 if (file_ref->file == nullptr) {
234 ResourceNameRef name(pkg->name, type->type, entry->name);
Adam Lesinski742888f2017-04-28 15:34:52 -0700235 context_->GetDiagnostics()->Warn(DiagMessage(file_ref->GetSource())
Shane Farmer57669432017-06-19 12:52:04 -0700236 << "file for resource " << name << " with config '"
237 << config_value->config << "' not found");
Adam Lesinski742888f2017-04-28 15:34:52 -0700238 continue;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700239 }
240
241 const StringPiece entry_name = entry->name;
242 config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
243 }
244 }
245
246 for (auto& entry : config_sorted_files) {
247 FileReference* file_ref = entry.second;
Pierre Lecesned55bef72017-11-10 22:31:01 +0000248 if (!io::CopyFileToArchivePreserveCompression(context_, file_ref->file, *file_ref->path,
249 writer)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700250 return false;
251 }
252 }
253 }
254 }
255
256 BigBuffer table_buffer(4096);
257 TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
258 if (!table_flattener.Consume(context_, table)) {
259 return false;
260 }
261
262 io::BigBufferInputStream table_buffer_in(&table_buffer);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700263 return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
264 ArchiveEntry::kAlign, writer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700265 }
266
267 OptimizeOptions options_;
268 OptimizeContext* context_;
269};
270
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500271bool ExtractObfuscationWhitelistFromConfig(const std::string& path, OptimizeContext* context,
272 OptimizeOptions* options) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800273 std::string contents;
274 if (!ReadFileToString(path, &contents, true)) {
275 context->GetDiagnostics()->Error(DiagMessage()
276 << "failed to parse whitelist from config file: " << path);
277 return false;
278 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500279 for (StringPiece resource_name : util::Tokenize(contents, ',')) {
280 options->table_flattener_options.whitelisted_resources.insert(
281 resource_name.to_string());
282 }
283 return true;
284}
285
286bool ExtractConfig(const std::string& path, OptimizeContext* context,
287 OptimizeOptions* options) {
288 std::string content;
289 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
290 context->GetDiagnostics()->Error(DiagMessage(path) << "failed reading whitelist");
291 return false;
292 }
293
294 size_t line_no = 0;
295 for (StringPiece line : util::Tokenize(content, '\n')) {
296 line_no++;
297 line = util::TrimWhitespace(line);
298 if (line.empty()) {
299 continue;
300 }
301
302 auto split_line = util::Split(line, '#');
303 if (split_line.size() < 2) {
304 context->GetDiagnostics()->Error(DiagMessage(line) << "No # found in line");
305 return false;
306 }
307 StringPiece resource_string = split_line[0];
308 StringPiece directives = split_line[1];
309 ResourceNameRef resource_name;
310 if (!ResourceUtils::ParseResourceName(resource_string, &resource_name)) {
311 context->GetDiagnostics()->Error(DiagMessage(line) << "Malformed resource name");
312 return false;
313 }
314 if (!resource_name.package.empty()) {
315 context->GetDiagnostics()->Error(DiagMessage(line)
316 << "Package set for resource. Only use type/name");
317 return false;
318 }
319 for (StringPiece directive : util::Tokenize(directives, ',')) {
320 if (directive == "remove") {
321 options->resources_blacklist.insert(resource_name.ToResourceName());
322 } else if (directive == "no_obfuscate") {
323 options->table_flattener_options.whitelisted_resources.insert(
324 resource_name.entry.to_string());
325 }
326 }
Luke Nicholsonb0643302017-12-01 15:29:03 -0800327 }
328 return true;
329}
330
Adam Lesinski8780eb62017-10-31 17:44:39 -0700331bool ExtractAppDataFromManifest(OptimizeContext* context, const LoadedApk* apk,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700332 OptimizeOptions* out_options) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700333 const xml::XmlResource* manifest = apk->GetManifest();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700334 if (manifest == nullptr) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700335 return false;
336 }
337
Adam Lesinski8780eb62017-10-31 17:44:39 -0700338 Maybe<AppInfo> app_info = ExtractAppInfoFromBinaryManifest(*manifest, context->GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700339 if (!app_info) {
340 context->GetDiagnostics()->Error(DiagMessage()
341 << "failed to extract data from AndroidManifest.xml");
342 return false;
343 }
344
345 out_options->app_info = std::move(app_info.value());
346 context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
347 return true;
348}
349
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700350int OptimizeCommand::Action(const std::vector<std::string>& args) {
351 if (args.size() != 1u) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700352 std::cerr << "must have one APK as argument.\n\n";
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700353 Usage(&std::cerr);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700354 return 1;
355 }
356
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700357 const std::string& apk_path = args[0];
358 OptimizeContext context;
359 context.SetVerbose(verbose_);
Shane Farmer9ecc0752017-08-24 15:55:36 -0700360 IDiagnostics* diag = context.GetDiagnostics();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700361
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700362 if (config_path_) {
363 std::string& path = config_path_.value();
Shane Farmer57669432017-06-19 12:52:04 -0700364 Maybe<ConfigurationParser> for_path = ConfigurationParser::ForPath(path);
365 if (for_path) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700366 options_.apk_artifacts = for_path.value().WithDiagnostics(diag).Parse(apk_path);
367 if (!options_.apk_artifacts) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800368 diag->Error(DiagMessage() << "Failed to parse the output artifact list");
369 return 1;
370 }
371
Shane Farmer57669432017-06-19 12:52:04 -0700372 } else {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700373 diag->Error(DiagMessage() << "Could not parse config file " << path);
Shane Farmer57669432017-06-19 12:52:04 -0700374 return 1;
375 }
Shane Farmer9ecc0752017-08-24 15:55:36 -0700376
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700377 if (print_only_) {
378 for (const OutputArtifact& artifact : options_.apk_artifacts.value()) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800379 std::cout << artifact.name << std::endl;
Shane Farmer9ecc0752017-08-24 15:55:36 -0700380 }
381 return 0;
382 }
383
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700384 if (!kept_artifacts_.empty()) {
385 for (const std::string& artifact_str : kept_artifacts_) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800386 for (const StringPiece& artifact : util::Tokenize(artifact_str, ',')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700387 options_.kept_artifacts.insert(artifact.to_string());
Shane Farmer666de342017-11-29 16:07:51 -0800388 }
389 }
390 }
391
Shane Farmer9ecc0752017-08-24 15:55:36 -0700392 // Since we know that we are going to process the APK (not just print targets), make sure we
393 // have somewhere to write them to.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700394 if (!options_.output_dir) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700395 diag->Error(DiagMessage() << "Output directory is required when using a configuration file");
396 return 1;
397 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700398 } else if (print_only_) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700399 diag->Error(DiagMessage() << "Asked to print artifacts without providing a configurations");
400 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700401 }
402
Shane Farmer2c122412017-12-15 16:55:54 -0800403 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(apk_path, context.GetDiagnostics());
404 if (!apk) {
405 return 1;
406 }
407
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700408 if (target_densities_) {
Shane Farmer2c122412017-12-15 16:55:54 -0800409 // Parse the target screen densities.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700410 for (const StringPiece& config_str : util::Tokenize(target_densities_.value(), ',')) {
Shane Farmer2c122412017-12-15 16:55:54 -0800411 Maybe<uint16_t> target_density = ParseTargetDensityParameter(config_str, diag);
412 if (!target_density) {
413 return 1;
414 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700415 options_.table_splitter_options.preferred_densities.push_back(target_density.value());
Shane Farmer2c122412017-12-15 16:55:54 -0800416 }
417 }
418
419 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700420 if (!configs_.empty()) {
421 filter = ParseConfigFilterParameters(configs_, diag);
Shane Farmer2c122412017-12-15 16:55:54 -0800422 if (filter == nullptr) {
423 return 1;
424 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700425 options_.table_splitter_options.config_filter = filter.get();
Shane Farmer2c122412017-12-15 16:55:54 -0800426 }
427
428 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700429 for (const std::string& split_arg : split_args_) {
430 options_.split_paths.emplace_back();
431 options_.split_constraints.emplace_back();
432 if (!ParseSplitParameter(split_arg, diag, &options_.split_paths.back(),
433 &options_.split_constraints.back())) {
Shane Farmer2c122412017-12-15 16:55:54 -0800434 return 1;
435 }
436 }
437
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700438 if (options_.table_flattener_options.collapse_key_stringpool) {
439 if (whitelist_path_) {
440 std::string& path = whitelist_path_.value();
441 if (!ExtractObfuscationWhitelistFromConfig(path, &context, &options_)) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800442 return 1;
443 }
444 }
445 }
446
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700447 if (resources_config_path_) {
448 std::string& path = resources_config_path_.value();
449 if (!ExtractConfig(path, &context, &options_)) {
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500450 return 1;
451 }
452 }
453
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700454 if (!ExtractAppDataFromManifest(&context, apk.get(), &options_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700455 return 1;
456 }
457
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700458 Optimizer cmd(&context, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700459 return cmd.Run(std::move(apk));
460}
461
462} // namespace aapt