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