1 /*
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
17 #include "Optimize.h"
18
19 #include <memory>
20 #include <vector>
21
22 #include "android-base/file.h"
23 #include "android-base/stringprintf.h"
24
25 #include "androidfw/ConfigDescription.h"
26 #include "androidfw/ResourceTypes.h"
27 #include "androidfw/StringPiece.h"
28
29 #include "Diagnostics.h"
30 #include "LoadedApk.h"
31 #include "ResourceUtils.h"
32 #include "SdkConstants.h"
33 #include "ValueVisitor.h"
34 #include "cmd/Util.h"
35 #include "configuration/ConfigurationParser.h"
36 #include "filter/AbiFilter.h"
37 #include "format/binary/TableFlattener.h"
38 #include "format/binary/XmlFlattener.h"
39 #include "io/BigBufferStream.h"
40 #include "io/Util.h"
41 #include "optimize/MultiApkGenerator.h"
42 #include "optimize/ResourceDeduper.h"
43 #include "optimize/ResourceFilter.h"
44 #include "optimize/ResourcePathShortener.h"
45 #include "optimize/VersionCollapser.h"
46 #include "split/TableSplitter.h"
47 #include "util/Files.h"
48 #include "util/Util.h"
49
50 using ::aapt::configuration::Abi;
51 using ::aapt::configuration::OutputArtifact;
52 using ::android::ConfigDescription;
53 using ::android::ResTable_config;
54 using ::android::StringPiece;
55 using ::android::base::ReadFileToString;
56 using ::android::base::StringAppendF;
57 using ::android::base::StringPrintf;
58 using ::android::base::WriteStringToFile;
59
60 namespace aapt {
61
62 class OptimizeContext : public IAaptContext {
63 public:
64 OptimizeContext() = default;
65
GetPackageType()66 PackageType GetPackageType() override {
67 // Not important here. Using anything other than kApp adds EXTRA validation, which we want to
68 // avoid.
69 return PackageType::kApp;
70 }
71
GetDiagnostics()72 IDiagnostics* GetDiagnostics() override {
73 return &diagnostics_;
74 }
75
GetNameMangler()76 NameMangler* GetNameMangler() override {
77 UNIMPLEMENTED(FATAL);
78 return nullptr;
79 }
80
GetCompilationPackage()81 const std::string& GetCompilationPackage() override {
82 static std::string empty;
83 return empty;
84 }
85
GetPackageId()86 uint8_t GetPackageId() override {
87 return 0;
88 }
89
GetExternalSymbols()90 SymbolTable* GetExternalSymbols() override {
91 UNIMPLEMENTED(FATAL);
92 return nullptr;
93 }
94
IsVerbose()95 bool IsVerbose() override {
96 return verbose_;
97 }
98
SetVerbose(bool val)99 void SetVerbose(bool val) {
100 verbose_ = val;
101 }
102
SetMinSdkVersion(int sdk_version)103 void SetMinSdkVersion(int sdk_version) {
104 sdk_version_ = sdk_version;
105 }
106
GetMinSdkVersion()107 int GetMinSdkVersion() override {
108 return sdk_version_;
109 }
110
GetSplitNameDependencies()111 const std::set<std::string>& GetSplitNameDependencies() override {
112 UNIMPLEMENTED(FATAL) << "Split Name Dependencies should not be necessary";
113 static std::set<std::string> empty;
114 return empty;
115 }
116
117 private:
118 DISALLOW_COPY_AND_ASSIGN(OptimizeContext);
119
120 StdErrDiagnostics diagnostics_;
121 bool verbose_ = false;
122 int sdk_version_ = 0;
123 };
124
125 class Optimizer {
126 public:
Optimizer(OptimizeContext * context,const OptimizeOptions & options)127 Optimizer(OptimizeContext* context, const OptimizeOptions& options)
128 : options_(options), context_(context) {
129 }
130
Run(std::unique_ptr<LoadedApk> apk)131 int Run(std::unique_ptr<LoadedApk> apk) {
132 if (context_->IsVerbose()) {
133 context_->GetDiagnostics()->Note(DiagMessage() << "Optimizing APK...");
134 }
135 if (!options_.resources_blacklist.empty()) {
136 ResourceFilter filter(options_.resources_blacklist);
137 if (!filter.Consume(context_, apk->GetResourceTable())) {
138 context_->GetDiagnostics()->Error(DiagMessage() << "failed filtering resources");
139 return 1;
140 }
141 }
142
143 VersionCollapser collapser;
144 if (!collapser.Consume(context_, apk->GetResourceTable())) {
145 return 1;
146 }
147
148 ResourceDeduper deduper;
149 if (!deduper.Consume(context_, apk->GetResourceTable())) {
150 context_->GetDiagnostics()->Error(DiagMessage() << "failed deduping resources");
151 return 1;
152 }
153
154 if (options_.shorten_resource_paths) {
155 ResourcePathShortener shortener(options_.table_flattener_options.shortened_path_map);
156 if (!shortener.Consume(context_, apk->GetResourceTable())) {
157 context_->GetDiagnostics()->Error(DiagMessage() << "failed shortening resource paths");
158 return 1;
159 }
160 if (options_.shortened_paths_map_path
161 && !WriteShortenedPathsMap(options_.table_flattener_options.shortened_path_map,
162 options_.shortened_paths_map_path.value())) {
163 context_->GetDiagnostics()->Error(DiagMessage()
164 << "failed to write shortened resource paths to file");
165 return 1;
166 }
167 }
168
169 // Adjust the SplitConstraints so that their SDK version is stripped if it is less than or
170 // equal to the minSdk.
171 options_.split_constraints =
172 AdjustSplitConstraintsForMinSdk(context_->GetMinSdkVersion(), options_.split_constraints);
173
174 // Stripping the APK using the TableSplitter. The resource table is modified in place in the
175 // LoadedApk.
176 TableSplitter splitter(options_.split_constraints, options_.table_splitter_options);
177 if (!splitter.VerifySplitConstraints(context_)) {
178 return 1;
179 }
180 splitter.SplitTable(apk->GetResourceTable());
181
182 auto path_iter = options_.split_paths.begin();
183 auto split_constraints_iter = options_.split_constraints.begin();
184 for (std::unique_ptr<ResourceTable>& split_table : splitter.splits()) {
185 if (context_->IsVerbose()) {
186 context_->GetDiagnostics()->Note(
187 DiagMessage(*path_iter) << "generating split with configurations '"
188 << util::Joiner(split_constraints_iter->configs, ", ") << "'");
189 }
190
191 // Generate an AndroidManifest.xml for each split.
192 std::unique_ptr<xml::XmlResource> split_manifest =
193 GenerateSplitManifest(options_.app_info, *split_constraints_iter);
194 std::unique_ptr<IArchiveWriter> split_writer =
195 CreateZipFileArchiveWriter(context_->GetDiagnostics(), *path_iter);
196 if (!split_writer) {
197 return 1;
198 }
199
200 if (!WriteSplitApk(split_table.get(), split_manifest.get(), split_writer.get())) {
201 return 1;
202 }
203
204 ++path_iter;
205 ++split_constraints_iter;
206 }
207
208 if (options_.apk_artifacts && options_.output_dir) {
209 MultiApkGenerator generator{apk.get(), context_};
210 MultiApkGeneratorOptions generator_options = {
211 options_.output_dir.value(), options_.apk_artifacts.value(),
212 options_.table_flattener_options, options_.kept_artifacts};
213 if (!generator.FromBaseApk(generator_options)) {
214 return 1;
215 }
216 }
217
218 if (options_.output_path) {
219 std::unique_ptr<IArchiveWriter> writer =
220 CreateZipFileArchiveWriter(context_->GetDiagnostics(), options_.output_path.value());
221 if (!apk->WriteToArchive(context_, options_.table_flattener_options, writer.get())) {
222 return 1;
223 }
224 }
225
226 return 0;
227 }
228
229 private:
WriteSplitApk(ResourceTable * table,xml::XmlResource * manifest,IArchiveWriter * writer)230 bool WriteSplitApk(ResourceTable* table, xml::XmlResource* manifest, IArchiveWriter* writer) {
231 BigBuffer manifest_buffer(4096);
232 XmlFlattener xml_flattener(&manifest_buffer, {});
233 if (!xml_flattener.Consume(context_, manifest)) {
234 return false;
235 }
236
237 io::BigBufferInputStream manifest_buffer_in(&manifest_buffer);
238 if (!io::CopyInputStreamToArchive(context_, &manifest_buffer_in, "AndroidManifest.xml",
239 ArchiveEntry::kCompress, writer)) {
240 return false;
241 }
242
243 std::map<std::pair<ConfigDescription, StringPiece>, FileReference*> config_sorted_files;
244 for (auto& pkg : table->packages) {
245 for (auto& type : pkg->types) {
246 // Sort by config and name, so that we get better locality in the zip file.
247 config_sorted_files.clear();
248
249 for (auto& entry : type->entries) {
250 for (auto& config_value : entry->values) {
251 auto* file_ref = ValueCast<FileReference>(config_value->value.get());
252 if (file_ref == nullptr) {
253 continue;
254 }
255
256 if (file_ref->file == nullptr) {
257 ResourceNameRef name(pkg->name, type->type, entry->name);
258 context_->GetDiagnostics()->Warn(DiagMessage(file_ref->GetSource())
259 << "file for resource " << name << " with config '"
260 << config_value->config << "' not found");
261 continue;
262 }
263
264 const StringPiece entry_name = entry->name;
265 config_sorted_files[std::make_pair(config_value->config, entry_name)] = file_ref;
266 }
267 }
268
269 for (auto& entry : config_sorted_files) {
270 FileReference* file_ref = entry.second;
271 if (!io::CopyFileToArchivePreserveCompression(context_, file_ref->file, *file_ref->path,
272 writer)) {
273 return false;
274 }
275 }
276 }
277 }
278
279 BigBuffer table_buffer(4096);
280 TableFlattener table_flattener(options_.table_flattener_options, &table_buffer);
281 if (!table_flattener.Consume(context_, table)) {
282 return false;
283 }
284
285 io::BigBufferInputStream table_buffer_in(&table_buffer);
286 return io::CopyInputStreamToArchive(context_, &table_buffer_in, "resources.arsc",
287 ArchiveEntry::kAlign, writer);
288 }
289
WriteShortenedPathsMap(const std::map<std::string,std::string> & path_map,const std::string & file_path)290 bool WriteShortenedPathsMap(const std::map<std::string, std::string> &path_map,
291 const std::string &file_path) {
292 std::stringstream ss;
293 for (auto it = path_map.cbegin(); it != path_map.cend(); ++it) {
294 ss << it->first << " -> " << it->second << "\n";
295 }
296 return WriteStringToFile(ss.str(), file_path);
297 }
298
299 OptimizeOptions options_;
300 OptimizeContext* context_;
301 };
302
ParseConfig(const std::string & content,IAaptContext * context,OptimizeOptions * options)303 bool ParseConfig(const std::string& content, IAaptContext* context, OptimizeOptions* options) {
304 size_t line_no = 0;
305 for (StringPiece line : util::Tokenize(content, '\n')) {
306 line_no++;
307 line = util::TrimWhitespace(line);
308 if (line.empty()) {
309 continue;
310 }
311
312 auto split_line = util::Split(line, '#');
313 if (split_line.size() < 2) {
314 context->GetDiagnostics()->Error(DiagMessage(line) << "No # found in line");
315 return false;
316 }
317 StringPiece resource_string = split_line[0];
318 StringPiece directives = split_line[1];
319 ResourceNameRef resource_name;
320 if (!ResourceUtils::ParseResourceName(resource_string, &resource_name)) {
321 context->GetDiagnostics()->Error(DiagMessage(line) << "Malformed resource name");
322 return false;
323 }
324 if (!resource_name.package.empty()) {
325 context->GetDiagnostics()->Error(DiagMessage(line)
326 << "Package set for resource. Only use type/name");
327 return false;
328 }
329 for (StringPiece directive : util::Tokenize(directives, ',')) {
330 if (directive == "remove") {
331 options->resources_blacklist.insert(resource_name.ToResourceName());
332 } else if (directive == "no_collapse" || directive == "no_obfuscate") {
333 options->table_flattener_options.name_collapse_exemptions.insert(
334 resource_name.ToResourceName());
335 }
336 }
337 }
338 return true;
339 }
340
ExtractConfig(const std::string & path,IAaptContext * context,OptimizeOptions * options)341 bool ExtractConfig(const std::string& path, IAaptContext* context, OptimizeOptions* options) {
342 std::string content;
343 if (!android::base::ReadFileToString(path, &content, true /*follow_symlinks*/)) {
344 context->GetDiagnostics()->Error(DiagMessage(path) << "failed reading config file");
345 return false;
346 }
347 return ParseConfig(content, context, options);
348 }
349
ExtractAppDataFromManifest(OptimizeContext * context,const LoadedApk * apk,OptimizeOptions * out_options)350 bool ExtractAppDataFromManifest(OptimizeContext* context, const LoadedApk* apk,
351 OptimizeOptions* out_options) {
352 const xml::XmlResource* manifest = apk->GetManifest();
353 if (manifest == nullptr) {
354 return false;
355 }
356
357 Maybe<AppInfo> app_info = ExtractAppInfoFromBinaryManifest(*manifest, context->GetDiagnostics());
358 if (!app_info) {
359 context->GetDiagnostics()->Error(DiagMessage()
360 << "failed to extract data from AndroidManifest.xml");
361 return false;
362 }
363
364 out_options->app_info = std::move(app_info.value());
365 context->SetMinSdkVersion(out_options->app_info.min_sdk_version.value_or_default(0));
366 return true;
367 }
368
Action(const std::vector<std::string> & args)369 int OptimizeCommand::Action(const std::vector<std::string>& args) {
370 if (args.size() != 1u) {
371 std::cerr << "must have one APK as argument.\n\n";
372 Usage(&std::cerr);
373 return 1;
374 }
375
376 const std::string& apk_path = args[0];
377 OptimizeContext context;
378 context.SetVerbose(verbose_);
379 IDiagnostics* diag = context.GetDiagnostics();
380
381 if (config_path_) {
382 std::string& path = config_path_.value();
383 Maybe<ConfigurationParser> for_path = ConfigurationParser::ForPath(path);
384 if (for_path) {
385 options_.apk_artifacts = for_path.value().WithDiagnostics(diag).Parse(apk_path);
386 if (!options_.apk_artifacts) {
387 diag->Error(DiagMessage() << "Failed to parse the output artifact list");
388 return 1;
389 }
390
391 } else {
392 diag->Error(DiagMessage() << "Could not parse config file " << path);
393 return 1;
394 }
395
396 if (print_only_) {
397 for (const OutputArtifact& artifact : options_.apk_artifacts.value()) {
398 std::cout << artifact.name << std::endl;
399 }
400 return 0;
401 }
402
403 if (!kept_artifacts_.empty()) {
404 for (const std::string& artifact_str : kept_artifacts_) {
405 for (const StringPiece& artifact : util::Tokenize(artifact_str, ',')) {
406 options_.kept_artifacts.insert(artifact.to_string());
407 }
408 }
409 }
410
411 // Since we know that we are going to process the APK (not just print targets), make sure we
412 // have somewhere to write them to.
413 if (!options_.output_dir) {
414 diag->Error(DiagMessage() << "Output directory is required when using a configuration file");
415 return 1;
416 }
417 } else if (print_only_) {
418 diag->Error(DiagMessage() << "Asked to print artifacts without providing a configurations");
419 return 1;
420 }
421
422 std::unique_ptr<LoadedApk> apk = LoadedApk::LoadApkFromPath(apk_path, context.GetDiagnostics());
423 if (!apk) {
424 return 1;
425 }
426
427 if (target_densities_) {
428 // Parse the target screen densities.
429 for (const StringPiece& config_str : util::Tokenize(target_densities_.value(), ',')) {
430 Maybe<uint16_t> target_density = ParseTargetDensityParameter(config_str, diag);
431 if (!target_density) {
432 return 1;
433 }
434 options_.table_splitter_options.preferred_densities.push_back(target_density.value());
435 }
436 }
437
438 std::unique_ptr<IConfigFilter> filter;
439 if (!configs_.empty()) {
440 filter = ParseConfigFilterParameters(configs_, diag);
441 if (filter == nullptr) {
442 return 1;
443 }
444 options_.table_splitter_options.config_filter = filter.get();
445 }
446
447 // Parse the split parameters.
448 for (const std::string& split_arg : split_args_) {
449 options_.split_paths.emplace_back();
450 options_.split_constraints.emplace_back();
451 if (!ParseSplitParameter(split_arg, diag, &options_.split_paths.back(),
452 &options_.split_constraints.back())) {
453 return 1;
454 }
455 }
456
457 if (resources_config_path_) {
458 std::string& path = resources_config_path_.value();
459 if (!ExtractConfig(path, &context, &options_)) {
460 return 1;
461 }
462 }
463
464 if (!ExtractAppDataFromManifest(&context, apk.get(), &options_)) {
465 return 1;
466 }
467
468 Optimizer cmd(&context, options_);
469 return cmd.Run(std::move(apk));
470 }
471
472 } // namespace aapt
473