blob: 8e4b82c6c261f34237aa7d1055cb6f9a418cc2bd [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>
20#include <string>
21
22#include "androidfw/StringPiece.h"
23
24#include "LoadedApk.h"
Shane Farmer3edd4722017-09-01 14:34:22 -070025#include "ResourceUtils.h"
Shane Farmer810fd182017-09-21 14:37:44 -070026#include "ValueVisitor.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070027#include "configuration/ConfigurationParser.h"
28#include "filter/AbiFilter.h"
29#include "filter/Filter.h"
30#include "flatten/Archive.h"
Shane Farmer3edd4722017-09-01 14:34:22 -070031#include "flatten/XmlFlattener.h"
Shane Farmerefe45392017-08-21 14:39:28 -070032#include "optimize/VersionCollapser.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070033#include "process/IResourceTableConsumer.h"
34#include "split/TableSplitter.h"
35#include "util/Files.h"
Shane Farmer3edd4722017-09-01 14:34:22 -070036#include "xml/XmlDom.h"
Shane Farmer810fd182017-09-21 14:37:44 -070037#include "xml/XmlUtil.h"
Shane Farmer0a5b2012017-06-22 12:24:12 -070038
39namespace aapt {
40
Shane Farmerefe45392017-08-21 14:39:28 -070041using ::aapt::configuration::AndroidSdk;
Shane Farmer0a5b2012017-06-22 12:24:12 -070042using ::aapt::configuration::Artifact;
43using ::aapt::configuration::PostProcessingConfiguration;
Shane Farmer810fd182017-09-21 14:37:44 -070044using ::aapt::xml::kSchemaAndroid;
Shane Farmer3edd4722017-09-01 14:34:22 -070045using ::aapt::xml::XmlResource;
Shane Farmer0a5b2012017-06-22 12:24:12 -070046using ::android::StringPiece;
47
Shane Farmer3edd4722017-09-01 14:34:22 -070048namespace {
49
50Maybe<AndroidSdk> GetAndroidSdk(const Artifact& artifact, const PostProcessingConfiguration& config,
51 IDiagnostics* diag) {
52 if (!artifact.android_sdk_group) {
53 return {};
54 }
55
56 const std::string& group_name = artifact.android_sdk_group.value();
57 auto group = config.android_sdk_groups.find(group_name);
58 // TODO: Remove validation when configuration parser ensures referential integrity.
59 if (group == config.android_sdk_groups.end()) {
60 diag->Error(DiagMessage() << "could not find referenced group '" << group_name << "'");
61 return {};
62 }
63
64 return group->second;
65}
66
67} // namespace
68
Shane Farmerefe45392017-08-21 14:39:28 -070069/**
70 * Context wrapper that allows the min Android SDK value to be overridden.
71 */
72class ContextWrapper : public IAaptContext {
73 public:
74 explicit ContextWrapper(IAaptContext* context)
75 : context_(context), min_sdk_(context_->GetMinSdkVersion()) {
76 }
77
78 PackageType GetPackageType() override {
79 return context_->GetPackageType();
80 }
81
82 SymbolTable* GetExternalSymbols() override {
83 return context_->GetExternalSymbols();
84 }
85
86 IDiagnostics* GetDiagnostics() override {
87 return context_->GetDiagnostics();
88 }
89
90 const std::string& GetCompilationPackage() override {
91 return context_->GetCompilationPackage();
92 }
93
94 uint8_t GetPackageId() override {
95 return context_->GetPackageId();
96 }
97
98 NameMangler* GetNameMangler() override {
99 return context_->GetNameMangler();
100 }
101
102 bool IsVerbose() override {
103 return context_->IsVerbose();
104 }
105
106 int GetMinSdkVersion() override {
107 return min_sdk_;
108 }
109
110 void SetMinSdkVersion(int min_sdk) {
111 min_sdk_ = min_sdk;
112 }
113
114 private:
115 IAaptContext* context_;
116
117 int min_sdk_ = -1;
118};
119
Shane Farmer0a5b2012017-06-22 12:24:12 -0700120MultiApkGenerator::MultiApkGenerator(LoadedApk* apk, IAaptContext* context)
121 : apk_(apk), context_(context) {
122}
123
Shane Farmerefe45392017-08-21 14:39:28 -0700124bool MultiApkGenerator::FromBaseApk(const MultiApkGeneratorOptions& options) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700125 // TODO(safarmer): Handle APK version codes for the generated APKs.
Shane Farmer9ecc0752017-08-24 15:55:36 -0700126 IDiagnostics* diag = context_->GetDiagnostics();
Shane Farmerefe45392017-08-21 14:39:28 -0700127 const PostProcessingConfiguration& config = options.config;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700128
Shane Farmer9ecc0752017-08-24 15:55:36 -0700129 const std::string& apk_name = file::GetFilename(apk_->GetSource().path).to_string();
130 const StringPiece ext = file::GetExtension(apk_name);
131 const std::string base_name = apk_name.substr(0, apk_name.rfind(ext.to_string()));
Shane Farmer0a5b2012017-06-22 12:24:12 -0700132
133 // For now, just write out the stripped APK since ABI splitting doesn't modify anything else.
134 for (const Artifact& artifact : config.artifacts) {
135 FilterChain filters;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700136
137 if (!artifact.name && !config.artifact_format) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700138 diag->Error(
Shane Farmer0a5b2012017-06-22 12:24:12 -0700139 DiagMessage() << "Artifact does not have a name and no global name template defined");
140 return false;
141 }
142
143 Maybe<std::string> artifact_name =
Shane Farmer9ecc0752017-08-24 15:55:36 -0700144 (artifact.name) ? artifact.Name(apk_name, diag)
145 : artifact.ToArtifactName(config.artifact_format.value(), apk_name, diag);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700146
147 if (!artifact_name) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700148 diag->Error(DiagMessage() << "Could not determine split APK artifact name");
Shane Farmer0a5b2012017-06-22 12:24:12 -0700149 return false;
150 }
151
Shane Farmerefe45392017-08-21 14:39:28 -0700152 std::unique_ptr<ResourceTable> table =
153 FilterTable(artifact, config, *apk_->GetResourceTable(), &filters);
154 if (!table) {
155 return false;
Shane Farmer0a5b2012017-06-22 12:24:12 -0700156 }
157
Shane Farmer3edd4722017-09-01 14:34:22 -0700158 std::unique_ptr<XmlResource> manifest;
Shane Farmer810fd182017-09-21 14:37:44 -0700159 if (!UpdateManifest(artifact, config, &manifest, diag)) {
160 diag->Error(DiagMessage() << "could not update AndroidManifest.xml for "
161 << artifact_name.value());
162 return false;
Shane Farmer3edd4722017-09-01 14:34:22 -0700163 }
164
Shane Farmerefe45392017-08-21 14:39:28 -0700165 std::string out = options.out_dir;
Shane Farmer3d66afe2017-08-24 11:04:35 -0700166 if (!file::mkdirs(out)) {
167 context_->GetDiagnostics()->Warn(DiagMessage() << "could not create out dir: " << out);
168 }
Shane Farmer0a5b2012017-06-22 12:24:12 -0700169 file::AppendPath(&out, artifact_name.value());
170
Shane Farmerefe45392017-08-21 14:39:28 -0700171 if (context_->IsVerbose()) {
172 context_->GetDiagnostics()->Note(DiagMessage() << "Generating split: " << out);
173 }
174
175 std::unique_ptr<IArchiveWriter> writer =
176 CreateZipFileArchiveWriter(context_->GetDiagnostics(), out);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700177
178 if (context_->IsVerbose()) {
Shane Farmer9ecc0752017-08-24 15:55:36 -0700179 diag->Note(DiagMessage() << "Writing output: " << out);
Shane Farmer0a5b2012017-06-22 12:24:12 -0700180 }
181
Shane Farmerefe45392017-08-21 14:39:28 -0700182 if (!apk_->WriteToArchive(context_, table.get(), options.table_flattener_options, &filters,
Shane Farmer3edd4722017-09-01 14:34:22 -0700183 writer.get(), manifest.get())) {
Shane Farmer0a5b2012017-06-22 12:24:12 -0700184 return false;
185 }
186 }
187
188 return true;
189}
190
Shane Farmerefe45392017-08-21 14:39:28 -0700191std::unique_ptr<ResourceTable> MultiApkGenerator::FilterTable(
192 const configuration::Artifact& artifact,
193 const configuration::PostProcessingConfiguration& config, const ResourceTable& old_table,
194 FilterChain* filters) {
195 TableSplitterOptions splits;
196 AxisConfigFilter axis_filter;
197 ContextWrapper wrappedContext{context_};
198
199 if (artifact.abi_group) {
200 const std::string& group_name = artifact.abi_group.value();
201
202 auto group = config.abi_groups.find(group_name);
203 // TODO: Remove validation when configuration parser ensures referential integrity.
204 if (group == config.abi_groups.end()) {
205 context_->GetDiagnostics()->Error(DiagMessage() << "could not find referenced ABI group '"
206 << group_name << "'");
207 return {};
208 }
209 filters->AddFilter(AbiFilter::FromAbiList(group->second));
210 }
211
212 if (artifact.screen_density_group) {
213 const std::string& group_name = artifact.screen_density_group.value();
214
215 auto group = config.screen_density_groups.find(group_name);
216 // TODO: Remove validation when configuration parser ensures referential integrity.
217 if (group == config.screen_density_groups.end()) {
218 context_->GetDiagnostics()->Error(DiagMessage() << "could not find referenced group '"
219 << group_name << "'");
220 return {};
221 }
222
223 const std::vector<ConfigDescription>& densities = group->second;
224 for(const auto& density_config : densities) {
225 splits.preferred_densities.push_back(density_config.density);
226 }
227 }
228
229 if (artifact.locale_group) {
230 const std::string& group_name = artifact.locale_group.value();
231 auto group = config.locale_groups.find(group_name);
232 // TODO: Remove validation when configuration parser ensures referential integrity.
233 if (group == config.locale_groups.end()) {
234 context_->GetDiagnostics()->Error(DiagMessage() << "could not find referenced group '"
235 << group_name << "'");
236 return {};
237 }
238
239 const std::vector<ConfigDescription>& locales = group->second;
240 for (const auto& locale : locales) {
241 axis_filter.AddConfig(locale);
242 }
243 splits.config_filter = &axis_filter;
244 }
245
Shane Farmer3edd4722017-09-01 14:34:22 -0700246 Maybe<AndroidSdk> sdk = GetAndroidSdk(artifact, config, context_->GetDiagnostics());
247 if (sdk && sdk.value().min_sdk_version) {
248 wrappedContext.SetMinSdkVersion(sdk.value().min_sdk_version.value());
Shane Farmerefe45392017-08-21 14:39:28 -0700249 }
250
251 std::unique_ptr<ResourceTable> table = old_table.Clone();
252
253 VersionCollapser collapser;
Shane Farmer3edd4722017-09-01 14:34:22 -0700254 if (!collapser.Consume(&wrappedContext, table.get())) {
Shane Farmerefe45392017-08-21 14:39:28 -0700255 context_->GetDiagnostics()->Error(DiagMessage() << "Failed to strip versioned resources");
256 return {};
257 }
258
259 TableSplitter splitter{{}, splits};
260 splitter.SplitTable(table.get());
261 return table;
262}
263
Shane Farmer810fd182017-09-21 14:37:44 -0700264bool MultiApkGenerator::UpdateManifest(const Artifact& artifact,
265 const PostProcessingConfiguration& config,
266 std::unique_ptr<XmlResource>* updated_manifest,
267 IDiagnostics* diag) {
268 *updated_manifest = apk_->InflateManifest(context_);
269 XmlResource* manifest = updated_manifest->get();
270 if (manifest == nullptr) {
271 return false;
272 }
273
274 // Make sure the first element is <manifest> with package attribute.
275 xml::Element* manifest_el = manifest->root.get();
276 if (manifest_el == nullptr) {
277 return false;
278 }
279
280 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
281 diag->Error(DiagMessage(manifest->file.source) << "root tag must be <manifest>");
282 return false;
283 }
284
285 // Update the versionCode attribute.
286 xml::Attribute* versionCode = manifest_el->FindAttribute(kSchemaAndroid, "versionCode");
287 if (versionCode == nullptr) {
288 diag->Error(DiagMessage(manifest->file.source) << "manifest must have a versionCode attribute");
289 return false;
290 }
291
292 auto* compiled_version = ValueCast<BinaryPrimitive>(versionCode->compiled_value.get());
293 if (compiled_version == nullptr) {
294 diag->Error(DiagMessage(manifest->file.source) << "versionCode is invalid");
295 return false;
296 }
297
298 int new_version = compiled_version->value.data + artifact.version;
299 versionCode->compiled_value = ResourceUtils::TryParseInt(std::to_string(new_version));
300
301 // Check to see if the minSdkVersion needs to be updated.
302 Maybe<AndroidSdk> maybe_sdk = GetAndroidSdk(artifact, config, diag);
303 if (maybe_sdk) {
304 // TODO(safarmer): Handle the rest of the Android SDK.
305 const AndroidSdk& android_sdk = maybe_sdk.value();
306
307 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
308 if (xml::Attribute* min_sdk_attr =
309 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
310 // Populate with a pre-compiles attribute to we don't need to relink etc.
311 const std::string& min_sdk_str = std::to_string(android_sdk.min_sdk_version.value());
312 min_sdk_attr->compiled_value = ResourceUtils::TryParseInt(min_sdk_str);
313 } else {
314 // There was no minSdkVersion. This is strange since at this point we should have been
315 // through the manifest fixer which sets the default minSdkVersion.
316 diag->Error(DiagMessage(manifest->file.source) << "missing minSdkVersion from <uses-sdk>");
317 return false;
318 }
319 } else {
320 // No uses-sdk present. This is strange since at this point we should have been
321 // through the manifest fixer which should have added it.
322 diag->Error(DiagMessage(manifest->file.source) << "missing <uses-sdk> from <manifest>");
323 return false;
324 }
325 }
326
Shane Farmere1799352017-09-25 14:19:03 -0700327 if (artifact.screen_density_group) {
328 auto densities = config.screen_density_groups.find(artifact.screen_density_group.value());
329 CHECK(densities != config.screen_density_groups.end()) << "Missing density group";
330
331 xml::Element* screens_el = manifest_el->FindChild({}, "compatible-screens");
332 if (!screens_el) {
333 // create a new element.
334 std::unique_ptr<xml::Element> new_screens_el = util::make_unique<xml::Element>();
335 new_screens_el->name = "compatible-screens";
336 screens_el = new_screens_el.get();
337 manifest_el->InsertChild(0, std::move(new_screens_el));
338 } else {
339 // clear out the old element.
340 screens_el->GetChildElements().clear();
341 }
342
343 for (const auto& density : densities->second) {
344 std::unique_ptr<xml::Element> screen_el = util::make_unique<xml::Element>();
345 screen_el->name = "screen";
346 const char* density_str = density.toString().string();
347 screen_el->attributes.push_back(xml::Attribute{kSchemaAndroid, "screenDensity", density_str});
348 screens_el->AppendChild(std::move(screen_el));
349 }
350 }
Shane Farmer810fd182017-09-21 14:37:44 -0700351
352 return true;
353}
354
Shane Farmer0a5b2012017-06-22 12:24:12 -0700355} // namespace aapt