blob: 47288ec092dec147f4f1e90d1059f8186cbd4308 [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
107 private:
Adam Lesinskib522f042017-04-21 16:57:59 -0700108 DISALLOW_COPY_AND_ASSIGN(OptimizeContext);
109
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700110 StdErrDiagnostics diagnostics_;
111 bool verbose_ = false;
112 int sdk_version_ = 0;
113};
114
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700115class Optimizer {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700116 public:
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700117 Optimizer(OptimizeContext* context, const OptimizeOptions& options)
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700118 : options_(options), context_(context) {
119 }
120
121 int Run(std::unique_ptr<LoadedApk> apk) {
122 if (context_->IsVerbose()) {
123 context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
124 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500125 if (!options_.resources_blacklist.empty()) {
126 ResourceFilter filter(options_.resources_blacklist);
127 if (!filter.Consume(context_, apk->GetResourceTable())) {
128 context_->GetDiagnostics()->Error(DiagMessage() << "failed filtering resources");
129 return 1;
130 }
131 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700132
133 VersionCollapser collapser;
134 if (!collapser.Consume(context_, apk->GetResourceTable())) {
135 return 1;
136 }
137
138 ResourceDeduper deduper;
139 if (!deduper.Consume(context_, apk->GetResourceTable())) {
140 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
141 return 1;
142 }
143
144 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
145 // equal to the minSdk.
146 options_.split_constraints =
147 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
148
149 // Stripping the APK using the TableSplitter. The resource table is modified in place in the
150 // LoadedApk.
151 TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
152 if (!splitter.VerifySplitConstraints(context_)) {
153 return 1;
154 }
155 splitter.SplitTable(apk->GetResourceTable());
156
157 auto path_iter = options_.split_paths.begin();
158 auto split_constraints_iter = options_.split_constraints.begin();
159 for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
160 if (context_->IsVerbose()) {
161 context_->GetDiagnostics()->Note(
162 DiagMessage(*path_iter) << "generating split with configurations '"
163 << util::Joiner(split_constraints_iter->configs, ", ") << "'");
164 }
165
166 // Generate an AndroidManifest.xml for each split.
167 std::unique_ptr<xml::XmlResource> split_manifest =
168 GenerateSplitManifest(options_.app_info, *split_constraints_iter);
169 std::unique_ptr<IArchiveWriter> split_writer =
170 CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
171 if (!split_writer) {
172 return 1;
173 }
174
175 if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
176 return 1;
177 }
178
179 ++path_iter;
180 ++split_constraints_iter;
181 }
182
Shane Farmercb6c3f92017-11-27 13:19:36 -0800183 if (options_.apk_artifacts && options_.output_dir) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700184 MultiApkGenerator generator{apk.get(), context_};
Shane Farmer666de342017-11-29 16:07:51 -0800185 MultiApkGeneratorOptions generator_options = {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800186 options_.output_dir.value(), options_.apk_artifacts.value(),
187 options_.table_flattener_options, options_.kept_artifacts};
Shane Farmerefe45392017-08-21 14:39:28 -0700188 if (!generator.FromBaseApk(generator_options)) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700189 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700190 }
191 }
192
193 if (options_.output_path) {
194 std::unique_ptr<IArchiveWriter> writer =
195 CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path.value());
196 if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
197 return 1;
198 }
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700199 }
200
201 return 0;
202 }
203
204 private:
205 bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
206 BigBuffer manifest_buffer(4096);
207 XmlFlattener xml_flattener(&manifest_buffer, {});
208 if (!xml_flattener.Consume(context_, manifest)) {
209 return false;
210 }
211
212 io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
213 if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
214 ArchiveEntry::kCompress, writer)) {
215 return false;
216 }
217
218 std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
219 for (auto& pkg : table->packages) {
220 for (auto& type : pkg->types) {
221 // Sort by config and name, so that we get better locality in the zip file.
222 config_sorted_files.clear();
223
224 for (auto& entry : type->entries) {
225 for (auto& config_value : entry->values) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700226 auto* file_ref = ValueCast<FileReference>(config_value->value.get());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700227 if (file_ref == nullptr) {
228 continue;
229 }
230
231 if (file_ref->file == nullptr) {
232 ResourceNameRef name(pkg->name, type->type, entry->name);
Adam Lesinski742888f2017-04-28 15:34:52 -0700233 context_->GetDiagnostics()->Warn(DiagMessage(file_ref->GetSource())
Shane Farmer57669432017-06-19 12:52:04 -0700234 << "file for resource " << name << " with config '"
235 << config_value->config << "' not found");
Adam Lesinski742888f2017-04-28 15:34:52 -0700236 continue;
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700237 }
238
239 const StringPiece entry_name = entry->name;
240 config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
241 }
242 }
243
244 for (auto& entry : config_sorted_files) {
245 FileReference* file_ref = entry.second;
Pierre Lecesned55bef72017-11-10 22:31:01 +0000246 if (!io::CopyFileToArchivePreserveCompression(context_, file_ref->file, *file_ref->path,
247 writer)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700248 return false;
249 }
250 }
251 }
252 }
253
254 BigBuffer table_buffer(4096);
255 TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
256 if (!table_flattener.Consume(context_, table)) {
257 return false;
258 }
259
260 io::BigBufferInputStream table_buffer_in(&table_buffer);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700261 return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
262 ArchiveEntry::kAlign, writer);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700263 }
264
265 OptimizeOptions options_;
266 OptimizeContext* context_;
267};
268
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500269bool ExtractObfuscationWhitelistFromConfig(const std::string& path, OptimizeContext* context,
270 OptimizeOptions* options) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800271 std::string contents;
272 if (!ReadFileToString(path, &contents, true)) {
273 context->GetDiagnostics()->Error(DiagMessage()
274 << "failed to parse whitelist from config file: " << path);
275 return false;
276 }
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500277 for (StringPiece resource_name : util::Tokenize(contents, ',')) {
278 options->table_flattener_options.whitelisted_resources.insert(
279 resource_name.to_string());
280 }
281 return true;
282}
283
284bool ExtractConfig(const std::string& path, OptimizeContext* context,
285 OptimizeOptions* options) {
286 std::string content;
287 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
288 context->GetDiagnostics()->Error(DiagMessage(path) << "failed reading whitelist");
289 return false;
290 }
291
292 size_t line_no = 0;
293 for (StringPiece line : util::Tokenize(content, '\n')) {
294 line_no++;
295 line = util::TrimWhitespace(line);
296 if (line.empty()) {
297 continue;
298 }
299
300 auto split_line = util::Split(line, '#');
301 if (split_line.size() < 2) {
302 context->GetDiagnostics()->Error(DiagMessage(line) << "No # found in line");
303 return false;
304 }
305 StringPiece resource_string = split_line[0];
306 StringPiece directives = split_line[1];
307 ResourceNameRef resource_name;
308 if (!ResourceUtils::ParseResourceName(resource_string, &resource_name)) {
309 context->GetDiagnostics()->Error(DiagMessage(line) << "Malformed resource name");
310 return false;
311 }
312 if (!resource_name.package.empty()) {
313 context->GetDiagnostics()->Error(DiagMessage(line)
314 << "Package set for resource. Only use type/name");
315 return false;
316 }
317 for (StringPiece directive : util::Tokenize(directives, ',')) {
318 if (directive == "remove") {
319 options->resources_blacklist.insert(resource_name.ToResourceName());
320 } else if (directive == "no_obfuscate") {
321 options->table_flattener_options.whitelisted_resources.insert(
322 resource_name.entry.to_string());
323 }
324 }
Luke Nicholsonb0643302017-12-01 15:29:03 -0800325 }
326 return true;
327}
328
Adam Lesinski8780eb62017-10-31 17:44:39 -0700329bool ExtractAppDataFromManifest(OptimizeContext* context, const LoadedApk* apk,
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700330 OptimizeOptions* out_options) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700331 const xml::XmlResource* manifest = apk->GetManifest();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700332 if (manifest == nullptr) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700333 return false;
334 }
335
Adam Lesinski8780eb62017-10-31 17:44:39 -0700336 Maybe<AppInfo> app_info = ExtractAppInfoFromBinaryManifest(*manifest, context->GetDiagnostics());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700337 if (!app_info) {
338 context->GetDiagnostics()->Error(DiagMessage()
339 << "failed to extract data from AndroidManifest.xml");
340 return false;
341 }
342
343 out_options->app_info = std::move(app_info.value());
344 context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
345 return true;
346}
347
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700348int OptimizeCommand::Action(const std::vector<std::string>& args) {
349 if (args.size() != 1u) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700350 std::cerr << "must have one APK as argument.\n\n";
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700351 Usage(&std::cerr);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700352 return 1;
353 }
354
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700355 const std::string& apk_path = args[0];
356 OptimizeContext context;
357 context.SetVerbose(verbose_);
Shane Farmer9ecc0752017-08-24 15:55:36 -0700358 IDiagnostics* diag = context.GetDiagnostics();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700359
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700360 if (config_path_) {
361 std::string& path = config_path_.value();
Shane Farmer57669432017-06-19 12:52:04 -0700362 Maybe<ConfigurationParser> for_path = ConfigurationParser::ForPath(path);
363 if (for_path) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700364 options_.apk_artifacts = for_path.value().WithDiagnostics(diag).Parse(apk_path);
365 if (!options_.apk_artifacts) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800366 diag->Error(DiagMessage() << "Failed to parse the output artifact list");
367 return 1;
368 }
369
Shane Farmer57669432017-06-19 12:52:04 -0700370 } else {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700371 diag->Error(DiagMessage() << "Could not parse config file " << path);
Shane Farmer57669432017-06-19 12:52:04 -0700372 return 1;
373 }
Shane Farmer9ecc0752017-08-24 15:55:36 -0700374
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700375 if (print_only_) {
376 for (const OutputArtifact& artifact : options_.apk_artifacts.value()) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800377 std::cout << artifact.name << std::endl;
Shane Farmer9ecc0752017-08-24 15:55:36 -0700378 }
379 return 0;
380 }
381
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700382 if (!kept_artifacts_.empty()) {
383 for (const std::string& artifact_str : kept_artifacts_) {
Shane Farmercb6c3f92017-11-27 13:19:36 -0800384 for (const StringPiece& artifact : util::Tokenize(artifact_str, ',')) {
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700385 options_.kept_artifacts.insert(artifact.to_string());
Shane Farmer666de342017-11-29 16:07:51 -0800386 }
387 }
388 }
389
Shane Farmer9ecc0752017-08-24 15:55:36 -0700390 // Since we know that we are going to process the APK (not just print targets), make sure we
391 // have somewhere to write them to.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700392 if (!options_.output_dir) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700393 diag->Error(DiagMessage() << "Output directory is required when using a configuration file");
394 return 1;
395 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700396 } else if (print_only_) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700397 diag->Error(DiagMessage() << "Asked to print artifacts without providing a configurations");
398 return 1;
Shane Farmer57669432017-06-19 12:52:04 -0700399 }
400
Shane Farmer2c122412017-12-15 16:55:54 -0800401 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(apk_path, context.GetDiagnostics());
402 if (!apk) {
403 return 1;
404 }
405
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700406 if (target_densities_) {
Shane Farmer2c122412017-12-15 16:55:54 -0800407 // Parse the target screen densities.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700408 for (const StringPiece& config_str : util::Tokenize(target_densities_.value(), ',')) {
Shane Farmer2c122412017-12-15 16:55:54 -0800409 Maybe<uint16_t> target_density = ParseTargetDensityParameter(config_str, diag);
410 if (!target_density) {
411 return 1;
412 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700413 options_.table_splitter_options.preferred_densities.push_back(target_density.value());
Shane Farmer2c122412017-12-15 16:55:54 -0800414 }
415 }
416
417 std::unique_ptr<IConfigFilter> filter;
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700418 if (!configs_.empty()) {
419 filter = ParseConfigFilterParameters(configs_, diag);
Shane Farmer2c122412017-12-15 16:55:54 -0800420 if (filter == nullptr) {
421 return 1;
422 }
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700423 options_.table_splitter_options.config_filter = filter.get();
Shane Farmer2c122412017-12-15 16:55:54 -0800424 }
425
426 // Parse the split parameters.
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700427 for (const std::string& split_arg : split_args_) {
428 options_.split_paths.emplace_back();
429 options_.split_constraints.emplace_back();
430 if (!ParseSplitParameter(split_arg, diag, &options_.split_paths.back(),
431 &options_.split_constraints.back())) {
Shane Farmer2c122412017-12-15 16:55:54 -0800432 return 1;
433 }
434 }
435
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700436 if (options_.table_flattener_options.collapse_key_stringpool) {
437 if (whitelist_path_) {
438 std::string& path = whitelist_path_.value();
439 if (!ExtractObfuscationWhitelistFromConfig(path, &context, &options_)) {
Luke Nicholsonb0643302017-12-01 15:29:03 -0800440 return 1;
441 }
442 }
443 }
444
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700445 if (resources_config_path_) {
446 std::string& path = resources_config_path_.value();
447 if (!ExtractConfig(path, &context, &options_)) {
Mohamed Heikald3c5fb62018-01-12 11:37:26 -0500448 return 1;
449 }
450 }
451
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700452 if (!ExtractAppDataFromManifest(&context, apk.get(), &options_)) {
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700453 return 1;
454 }
455
Ryan Mitchell833a1a62018-07-10 13:51:36 -0700456 Optimizer cmd(&context, options_);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700457 return cmd.Run(std::move(apk));
458}
459
460} // namespace aapt