blob: e2d738aec5a27fbeb08f54596ac965487c653984 [file] [log] [blame]
Shane Farmer0a5b2012017-06-22 12:24:12 -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
17#include "MultiApkGenerator.h"
18
19#include <algorithm>
Shane Farmer3ff44432017-09-29 11:59:25 -070020#include <regex>
Shane Farmer0a5b2012017-06-22 12:24:12 -070021#include <string>
22
23#include "androidfw/StringPiece.h"
24
25#include "LoadedApk.h"
Shane Farmer3edd4722017-09-01 14:34:22 -070026#include "ResourceUtils.h"
Shane Farmer810fd182017-09-21 14:37:44 -070027#include "ValueVisitor.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070028#include "configuration/ConfigurationParser.h"
29#include "filter/AbiFilter.h"
30#include "filter/Filter.h"
Adam Lesinski46708052017-09-29 14:49:15 -070031#include "format/Archive.h"
32#include "format/binary/XmlFlattener.h"
Shane Farmerefe45392017-08-21 14:39:28 -070033#include "optimize/VersionCollapser.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070034#include "process/IResourceTableConsumer.h"
35#include "split/TableSplitter.h"
36#include "util/Files.h"
Shane Farmer3edd4722017-09-01 14:34:22 -070037#include "xml/XmlDom.h"
Shane Farmer810fd182017-09-21 14:37:44 -070038#include "xml/XmlUtil.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070039
40namespace aapt {
41
Shane Farmerefe45392017-08-21 14:39:28 -070042using ::aapt::configuration::AndroidSdk;
Shane Farmer0a5b2012017-06-22 12:24:12 -070043using ::aapt::configuration::Artifact;
44using ::aapt::configuration::PostProcessingConfiguration;
Shane Farmer810fd182017-09-21 14:37:44 -070045using ::aapt::xml::kSchemaAndroid;
Shane Farmer3edd4722017-09-01 14:34:22 -070046using ::aapt::xml::XmlResource;
Shane Farmer0a5b2012017-06-22 12:24:12 -070047using ::android::StringPiece;
48
Shane Farmer3edd4722017-09-01 14:34:22 -070049namespace {
50
51Maybe<AndroidSdk> GetAndroidSdk(const Artifact& artifact, const PostProcessingConfiguration& config,
52 IDiagnostics* diag) {
53 if (!artifact.android_sdk_group) {
54 return {};
55 }
56
57 const std::string& group_name = artifact.android_sdk_group.value();
58 auto group = config.android_sdk_groups.find(group_name);
59 // TODO: Remove validation when configuration parser ensures referential integrity.
60 if (group == config.android_sdk_groups.end()) {
61 diag->Error(DiagMessage() << "could not find referenced group '" << group_name << "'");
62 return {};
63 }
64
65 return group->second;
66}
67
68} // namespace
69
Shane Farmerefe45392017-08-21 14:39:28 -070070/**
71 * Context wrapper that allows the min Android SDK value to be overridden.
72 */
73class ContextWrapper : public IAaptContext {
74 public:
75 explicit ContextWrapper(IAaptContext* context)
76 : context_(context), min_sdk_(context_->GetMinSdkVersion()) {
77 }
78
79 PackageType GetPackageType() override {
80 return context_->GetPackageType();
81 }
82
83 SymbolTable* GetExternalSymbols() override {
84 return context_->GetExternalSymbols();
85 }
86
87 IDiagnostics* GetDiagnostics() override {
Shane Farmer20ac0342017-11-29 16:55:05 -080088 if (source_diag_) {
89 return source_diag_.get();
90 }
Shane Farmerefe45392017-08-21 14:39:28 -070091 return context_->GetDiagnostics();
92 }
93
94 const std::string& GetCompilationPackage() override {
95 return context_->GetCompilationPackage();
96 }
97
98 uint8_t GetPackageId() override {
99 return context_->GetPackageId();
100 }
101
102 NameMangler* GetNameMangler() override {
103 return context_->GetNameMangler();
104 }
105
106 bool IsVerbose() override {
107 return context_->IsVerbose();
108 }
109
110 int GetMinSdkVersion() override {
111 return min_sdk_;
112 }
113
114 void SetMinSdkVersion(int min_sdk) {
115 min_sdk_ = min_sdk;
116 }
117
Shane Farmer20ac0342017-11-29 16:55:05 -0800118 void SetSource(const Source& source) {
119 source_diag_ = util::make_unique<SourcePathDiagnostics>(source, context_->GetDiagnostics());
120 }
121
Shane Farmerefe45392017-08-21 14:39:28 -0700122 private:
123 IAaptContext* context_;
Shane Farmer20ac0342017-11-29 16:55:05 -0800124 std::unique_ptr<SourcePathDiagnostics> source_diag_;
Shane Farmerefe45392017-08-21 14:39:28 -0700125
126 int min_sdk_ = -1;
127};
128
Shane Farmer3ff44432017-09-29 11:59:25 -0700129class SignatureFilter : public IPathFilter {
130 bool Keep(const std::string& path) override {
131 static std::regex signature_regex(R"regex(^META-INF/.*\.(RSA|DSA|EC|SF)$)regex");
132 if (std::regex_search(path, signature_regex)) {
133 return false;
134 }
135 return !(path == "META-INF/MANIFEST.MF");
136 }
137};
138
Shane Farmer0a5b2012017-06-22 12:24:12 -0700139MultiApkGenerator::MultiApkGenerator(LoadedApk* apk, IAaptContext* context)
140 : apk_(apk), context_(context) {
141}
142
Shane Farmerefe45392017-08-21 14:39:28 -0700143bool MultiApkGenerator::FromBaseApk(const MultiApkGeneratorOptions& options) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700144 // TODO(safarmer): Handle APK version codes for the generated APKs.
Shane Farmerefe45392017-08-21 14:39:28 -0700145 const PostProcessingConfiguration& config = options.config;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700146
Shane Farmer9ecc0752017-08-24 15:55:36 -0700147 const std::string& apk_name = file::GetFilename(apk_->GetSource().path).to_string();
148 const StringPiece ext = file::GetExtension(apk_name);
149 const std::string base_name = apk_name.substr(0, apk_name.rfind(ext.to_string()));
Shane Farmer0a5b2012017-06-22 12:24:12 -0700150
Shane Farmer666de342017-11-29 16:07:51 -0800151 std::unordered_set<std::string> artifacts_to_keep = options.kept_artifacts;
152 std::unordered_set<std::string> filtered_artifacts;
153 std::unordered_set<std::string> kept_artifacts;
154
Shane Farmer0a5b2012017-06-22 12:24:12 -0700155 // For now, just write out the stripped APK since ABI splitting doesn't modify anything else.
156 for (const Artifact& artifact : config.artifacts) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800157 SourcePathDiagnostics diag{{apk_name}, context_->GetDiagnostics()};
158
Shane Farmer0a5b2012017-06-22 12:24:12 -0700159 FilterChain filters;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700160
161 if (!artifact.name && !config.artifact_format) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800162 diag.Error(
Shane Farmer0a5b2012017-06-22 12:24:12 -0700163 DiagMessage() << "Artifact does not have a name and no global name template defined");
164 return false;
165 }
166
Shane Farmer20ac0342017-11-29 16:55:05 -0800167 Maybe<std::string> maybe_artifact_name =
168 (artifact.name) ? artifact.Name(apk_name, &diag)
169 : artifact.ToArtifactName(config.artifact_format.value(), apk_name, &diag);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700170
Shane Farmer20ac0342017-11-29 16:55:05 -0800171 if (!maybe_artifact_name) {
172 diag.Error(DiagMessage() << "Could not determine split APK artifact name");
Shane Farmer0a5b2012017-06-22 12:24:12 -0700173 return false;
174 }
175
Shane Farmer20ac0342017-11-29 16:55:05 -0800176 const std::string& artifact_name = maybe_artifact_name.value();
177
178 ContextWrapper wrapped_context{context_};
179 wrapped_context.SetSource({artifact_name});
180
Shane Farmer666de342017-11-29 16:07:51 -0800181 if (!options.kept_artifacts.empty()) {
182 const auto& it = artifacts_to_keep.find(artifact_name);
183 if (it == artifacts_to_keep.end()) {
184 filtered_artifacts.insert(artifact_name);
185 if (context_->IsVerbose()) {
186 context_->GetDiagnostics()->Note(DiagMessage(artifact_name) << "skipping artifact");
187 }
188 continue;
189 } else {
190 artifacts_to_keep.erase(it);
191 kept_artifacts.insert(artifact_name);
192 }
193 }
194
Shane Farmerefe45392017-08-21 14:39:28 -0700195 std::unique_ptr<ResourceTable> table =
Shane Farmer20ac0342017-11-29 16:55:05 -0800196 FilterTable(artifact, config, *apk_->GetResourceTable(), &wrapped_context, &filters);
Shane Farmerefe45392017-08-21 14:39:28 -0700197 if (!table) {
198 return false;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700199 }
200
Shane Farmer3edd4722017-09-01 14:34:22 -0700201 std::unique_ptr<XmlResource> manifest;
Shane Farmer20ac0342017-11-29 16:55:05 -0800202 if (!UpdateManifest(artifact, config, &manifest, &diag)) {
203 diag.Error(DiagMessage() << "could not update AndroidManifest.xml for output artifact");
Shane Farmer810fd182017-09-21 14:37:44 -0700204 return false;
Shane Farmer3edd4722017-09-01 14:34:22 -0700205 }
206
Shane Farmerefe45392017-08-21 14:39:28 -0700207 std::string out = options.out_dir;
Shane Farmer3d66afe2017-08-24 11:04:35 -0700208 if (!file::mkdirs(out)) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800209 diag.Warn(DiagMessage() << "could not create out dir: " << out);
Shane Farmer3d66afe2017-08-24 11:04:35 -0700210 }
Shane Farmer20ac0342017-11-29 16:55:05 -0800211 file::AppendPath(&out, artifact_name);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700212
Shane Farmerefe45392017-08-21 14:39:28 -0700213 if (context_->IsVerbose()) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800214 diag.Note(DiagMessage() << "Generating split: " << out);
Shane Farmerefe45392017-08-21 14:39:28 -0700215 }
216
Shane Farmer20ac0342017-11-29 16:55:05 -0800217 std::unique_ptr<IArchiveWriter> writer = CreateZipFileArchiveWriter(&diag, out);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700218
219 if (context_->IsVerbose()) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800220 diag.Note(DiagMessage() << "Writing output: " << out);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700221 }
222
Shane Farmer3ff44432017-09-29 11:59:25 -0700223 filters.AddFilter(util::make_unique<SignatureFilter>());
Shane Farmer20ac0342017-11-29 16:55:05 -0800224 if (!apk_->WriteToArchive(&wrapped_context, table.get(), options.table_flattener_options,
225 &filters, writer.get(), manifest.get())) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700226 return false;
227 }
228 }
229
Shane Farmer666de342017-11-29 16:07:51 -0800230 // Make sure all of the requested artifacts were valid. If there are any kept artifacts left,
231 // either the config or the command line was wrong.
232 if (!artifacts_to_keep.empty()) {
233 context_->GetDiagnostics()->Error(
234 DiagMessage() << "The configuration and command line to filter artifacts do not match");
235
236 context_->GetDiagnostics()->Error(DiagMessage() << kept_artifacts.size() << " kept:");
237 for (const auto& artifact : kept_artifacts) {
238 context_->GetDiagnostics()->Error(DiagMessage() << " " << artifact);
239 }
240
241 context_->GetDiagnostics()->Error(DiagMessage() << filtered_artifacts.size() << " filtered:");
242 for (const auto& artifact : filtered_artifacts) {
243 context_->GetDiagnostics()->Error(DiagMessage() << " " << artifact);
244 }
245
246 context_->GetDiagnostics()->Error(DiagMessage() << artifacts_to_keep.size() << " missing:");
247 for (const auto& artifact : artifacts_to_keep) {
248 context_->GetDiagnostics()->Error(DiagMessage() << " " << artifact);
249 }
250
251 return false;
252 }
253
Shane Farmer0a5b2012017-06-22 12:24:12 -0700254 return true;
255}
256
Shane Farmerefe45392017-08-21 14:39:28 -0700257std::unique_ptr<ResourceTable> MultiApkGenerator::FilterTable(
258 const configuration::Artifact& artifact,
259 const configuration::PostProcessingConfiguration& config, const ResourceTable& old_table,
Shane Farmer20ac0342017-11-29 16:55:05 -0800260 IAaptContext* context, FilterChain* filters) {
Shane Farmerefe45392017-08-21 14:39:28 -0700261 TableSplitterOptions splits;
262 AxisConfigFilter axis_filter;
Shane Farmer20ac0342017-11-29 16:55:05 -0800263 ContextWrapper wrapped_context{context};
Shane Farmerefe45392017-08-21 14:39:28 -0700264
265 if (artifact.abi_group) {
266 const std::string& group_name = artifact.abi_group.value();
267
268 auto group = config.abi_groups.find(group_name);
269 // TODO: Remove validation when configuration parser ensures referential integrity.
270 if (group == config.abi_groups.end()) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800271 context->GetDiagnostics()->Error(DiagMessage() << "could not find referenced ABI group '"
272 << group_name << "'");
Shane Farmerefe45392017-08-21 14:39:28 -0700273 return {};
274 }
275 filters->AddFilter(AbiFilter::FromAbiList(group->second));
276 }
277
278 if (artifact.screen_density_group) {
279 const std::string& group_name = artifact.screen_density_group.value();
280
281 auto group = config.screen_density_groups.find(group_name);
282 // TODO: Remove validation when configuration parser ensures referential integrity.
283 if (group == config.screen_density_groups.end()) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800284 context->GetDiagnostics()->Error(DiagMessage()
285 << "could not find referenced group '" << group_name << "'");
Shane Farmerefe45392017-08-21 14:39:28 -0700286 return {};
287 }
288
289 const std::vector<ConfigDescription>& densities = group->second;
Shane Farmer20ac0342017-11-29 16:55:05 -0800290 for (const auto& density_config : densities) {
Shane Farmerefe45392017-08-21 14:39:28 -0700291 splits.preferred_densities.push_back(density_config.density);
292 }
293 }
294
295 if (artifact.locale_group) {
296 const std::string& group_name = artifact.locale_group.value();
297 auto group = config.locale_groups.find(group_name);
298 // TODO: Remove validation when configuration parser ensures referential integrity.
299 if (group == config.locale_groups.end()) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800300 context->GetDiagnostics()->Error(DiagMessage()
301 << "could not find referenced group '" << group_name << "'");
Shane Farmerefe45392017-08-21 14:39:28 -0700302 return {};
303 }
304
305 const std::vector<ConfigDescription>& locales = group->second;
306 for (const auto& locale : locales) {
307 axis_filter.AddConfig(locale);
308 }
309 splits.config_filter = &axis_filter;
310 }
311
Shane Farmer20ac0342017-11-29 16:55:05 -0800312 Maybe<AndroidSdk> sdk = GetAndroidSdk(artifact, config, context->GetDiagnostics());
Shane Farmer3edd4722017-09-01 14:34:22 -0700313 if (sdk && sdk.value().min_sdk_version) {
Shane Farmer20ac0342017-11-29 16:55:05 -0800314 wrapped_context.SetMinSdkVersion(sdk.value().min_sdk_version.value());
Shane Farmerefe45392017-08-21 14:39:28 -0700315 }
316
317 std::unique_ptr<ResourceTable> table = old_table.Clone();
318
319 VersionCollapser collapser;
Shane Farmer20ac0342017-11-29 16:55:05 -0800320 if (!collapser.Consume(&wrapped_context, table.get())) {
321 context->GetDiagnostics()->Error(DiagMessage() << "Failed to strip versioned resources");
Shane Farmerefe45392017-08-21 14:39:28 -0700322 return {};
323 }
324
325 TableSplitter splitter{{}, splits};
326 splitter.SplitTable(table.get());
327 return table;
328}
329
Shane Farmer810fd182017-09-21 14:37:44 -0700330bool MultiApkGenerator::UpdateManifest(const Artifact& artifact,
331 const PostProcessingConfiguration& config,
332 std::unique_ptr<XmlResource>* updated_manifest,
333 IDiagnostics* diag) {
Adam Lesinski8780eb62017-10-31 17:44:39 -0700334 const xml::XmlResource* apk_manifest = apk_->GetManifest();
335 if (apk_manifest == nullptr) {
Shane Farmer810fd182017-09-21 14:37:44 -0700336 return false;
337 }
338
Adam Lesinski8780eb62017-10-31 17:44:39 -0700339 *updated_manifest = apk_manifest->Clone();
340 XmlResource* manifest = updated_manifest->get();
341
Shane Farmer810fd182017-09-21 14:37:44 -0700342 // Make sure the first element is <manifest> with package attribute.
343 xml::Element* manifest_el = manifest->root.get();
344 if (manifest_el == nullptr) {
345 return false;
346 }
347
348 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
349 diag->Error(DiagMessage(manifest->file.source) << "root tag must be <manifest>");
350 return false;
351 }
352
353 // Update the versionCode attribute.
354 xml::Attribute* versionCode = manifest_el->FindAttribute(kSchemaAndroid, "versionCode");
355 if (versionCode == nullptr) {
356 diag->Error(DiagMessage(manifest->file.source) << "manifest must have a versionCode attribute");
357 return false;
358 }
359
360 auto* compiled_version = ValueCast<BinaryPrimitive>(versionCode->compiled_value.get());
361 if (compiled_version == nullptr) {
362 diag->Error(DiagMessage(manifest->file.source) << "versionCode is invalid");
363 return false;
364 }
365
366 int new_version = compiled_version->value.data + artifact.version;
367 versionCode->compiled_value = ResourceUtils::TryParseInt(std::to_string(new_version));
368
369 // Check to see if the minSdkVersion needs to be updated.
370 Maybe<AndroidSdk> maybe_sdk = GetAndroidSdk(artifact, config, diag);
371 if (maybe_sdk) {
372 // TODO(safarmer): Handle the rest of the Android SDK.
373 const AndroidSdk& android_sdk = maybe_sdk.value();
374
375 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
376 if (xml::Attribute* min_sdk_attr =
377 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
378 // Populate with a pre-compiles attribute to we don't need to relink etc.
379 const std::string& min_sdk_str = std::to_string(android_sdk.min_sdk_version.value());
380 min_sdk_attr->compiled_value = ResourceUtils::TryParseInt(min_sdk_str);
381 } else {
382 // There was no minSdkVersion. This is strange since at this point we should have been
383 // through the manifest fixer which sets the default minSdkVersion.
384 diag->Error(DiagMessage(manifest->file.source) << "missing minSdkVersion from <uses-sdk>");
385 return false;
386 }
387 } else {
388 // No uses-sdk present. This is strange since at this point we should have been
389 // through the manifest fixer which should have added it.
390 diag->Error(DiagMessage(manifest->file.source) << "missing <uses-sdk> from <manifest>");
391 return false;
392 }
393 }
394
Shane Farmere1799352017-09-25 14:19:03 -0700395 if (artifact.screen_density_group) {
396 auto densities = config.screen_density_groups.find(artifact.screen_density_group.value());
397 CHECK(densities != config.screen_density_groups.end()) << "Missing density group";
398
399 xml::Element* screens_el = manifest_el->FindChild({}, "compatible-screens");
400 if (!screens_el) {
401 // create a new element.
402 std::unique_ptr<xml::Element> new_screens_el = util::make_unique<xml::Element>();
403 new_screens_el->name = "compatible-screens";
404 screens_el = new_screens_el.get();
405 manifest_el->InsertChild(0, std::move(new_screens_el));
406 } else {
407 // clear out the old element.
408 screens_el->GetChildElements().clear();
409 }
410
411 for (const auto& density : densities->second) {
412 std::unique_ptr<xml::Element> screen_el = util::make_unique<xml::Element>();
413 screen_el->name = "screen";
414 const char* density_str = density.toString().string();
415 screen_el->attributes.push_back(xml::Attribute{kSchemaAndroid, "screenDensity", density_str});
416 screens_el->AppendChild(std::move(screen_el));
417 }
418 }
Shane Farmer810fd182017-09-21 14:37:44 -0700419
420 return true;
421}
422
Shane Farmer0a5b2012017-06-22 12:24:12 -0700423} // namespace aapt