blob: 90fc10add7e6d170e804b6e51f29c17bdaf48644 [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
17#include "cmd/Util.h"
18
19#include <vector>
20
21#include "android-base/logging.h"
22
23#include "ConfigDescription.h"
24#include "Locale.h"
25#include "ResourceUtils.h"
26#include "ValueVisitor.h"
27#include "split/TableSplitter.h"
28#include "util/Maybe.h"
29#include "util/Util.h"
30
Adam Lesinski5c33fb52017-08-09 10:54:23 -070031using ::android::StringPiece;
Adam Lesinskid0f492d2017-04-03 18:12:45 -070032
33namespace aapt {
34
35Maybe<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, IDiagnostics* diag) {
36 ConfigDescription preferred_density_config;
37 if (!ConfigDescription::Parse(arg, &preferred_density_config)) {
38 diag->Error(DiagMessage() << "invalid density '" << arg << "' for --preferred-density option");
39 return {};
40 }
41
42 // Clear the version that can be automatically added.
43 preferred_density_config.sdkVersion = 0;
44
45 if (preferred_density_config.diff(ConfigDescription::DefaultConfig()) !=
46 ConfigDescription::CONFIG_DENSITY) {
47 diag->Error(DiagMessage() << "invalid preferred density '" << arg << "'. "
48 << "Preferred density must only be a density value");
49 return {};
50 }
51 return preferred_density_config.density;
52}
53
54bool ParseSplitParameter(const StringPiece& arg, IDiagnostics* diag, std::string* out_path,
55 SplitConstraints* out_split) {
56 CHECK(diag != nullptr);
57 CHECK(out_path != nullptr);
58 CHECK(out_split != nullptr);
59
Adam Lesinskidb091572017-04-13 12:48:56 -070060#ifdef _WIN32
61 const char sSeparator = ';';
62#else
63 const char sSeparator = ':';
64#endif
65
66 std::vector<std::string> parts = util::Split(arg, sSeparator);
Adam Lesinskid0f492d2017-04-03 18:12:45 -070067 if (parts.size() != 2) {
68 diag->Error(DiagMessage() << "invalid split parameter '" << arg << "'");
Adam Lesinskidb091572017-04-13 12:48:56 -070069 diag->Note(DiagMessage() << "should be --split path/to/output.apk" << sSeparator
70 << "<config>[,<config>...].");
Adam Lesinskid0f492d2017-04-03 18:12:45 -070071 return false;
72 }
73
74 *out_path = parts[0];
Adam Lesinskid0f492d2017-04-03 18:12:45 -070075 for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) {
76 ConfigDescription config;
77 if (!ConfigDescription::Parse(config_str, &config)) {
78 diag->Error(DiagMessage() << "invalid config '" << config_str << "' in split parameter '"
79 << arg << "'");
80 return false;
81 }
82 out_split->configs.insert(config);
83 }
84 return true;
85}
86
87std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
88 IDiagnostics* diag) {
89 std::unique_ptr<AxisConfigFilter> filter = util::make_unique<AxisConfigFilter>();
90 for (const std::string& config_arg : args) {
91 for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
92 ConfigDescription config;
93 LocaleValue lv;
94 if (lv.InitFromFilterString(config_str)) {
95 lv.WriteTo(&config);
96 } else if (!ConfigDescription::Parse(config_str, &config)) {
97 diag->Error(DiagMessage() << "invalid config '" << config_str << "' for -c option");
98 return {};
99 }
100
101 if (config.density != 0) {
102 diag->Warn(DiagMessage() << "ignoring density '" << config << "' for -c option");
103 } else {
104 filter->AddConfig(config);
105 }
106 }
107 }
108 return std::move(filter);
109}
110
111// Adjust the SplitConstraints so that their SDK version is stripped if it
112// is less than or equal to the minSdk. Otherwise the resources that have had
113// their SDK version stripped due to minSdk won't ever match.
114std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
115 int min_sdk, const std::vector<SplitConstraints>& split_constraints) {
116 std::vector<SplitConstraints> adjusted_constraints;
117 adjusted_constraints.reserve(split_constraints.size());
118 for (const SplitConstraints& constraints : split_constraints) {
119 SplitConstraints constraint;
120 for (const ConfigDescription& config : constraints.configs) {
121 if (config.sdkVersion <= min_sdk) {
122 constraint.configs.insert(config.CopyWithoutSdkVersion());
123 } else {
124 constraint.configs.insert(config);
125 }
126 }
127 adjusted_constraints.push_back(std::move(constraint));
128 }
129 return adjusted_constraints;
130}
131
132static xml::AaptAttribute CreateAttributeWithId(const ResourceId& id) {
Adam Lesinskic744ae82017-05-17 19:28:38 -0700133 return xml::AaptAttribute(Attribute(), id);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700134}
135
Adam Lesinski5c33fb52017-08-09 10:54:23 -0700136static xml::NamespaceDecl CreateAndroidNamespaceDecl() {
137 xml::NamespaceDecl decl;
138 decl.prefix = "android";
139 decl.uri = xml::kSchemaAndroid;
140 return decl;
141}
142
Donald Chai2ba1bc52017-11-09 21:06:52 -0800143// Returns a copy of 'name' which conforms to the regex '[a-zA-Z]+[a-zA-Z0-9_]*' by
144// replacing nonconforming characters with underscores.
145//
146// See frameworks/base/core/java/android/content/pm/PackageParser.java which
147// checks this at runtime.
Donald Chai50bae7912017-10-18 23:51:18 -0700148static std::string MakePackageSafeName(const std::string &name) {
149 std::string result(name);
Donald Chai2ba1bc52017-11-09 21:06:52 -0800150 bool first = true;
Donald Chai50bae7912017-10-18 23:51:18 -0700151 for (char &c : result) {
Donald Chai2ba1bc52017-11-09 21:06:52 -0800152 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
153 first = false;
154 continue;
Donald Chai50bae7912017-10-18 23:51:18 -0700155 }
Donald Chai2ba1bc52017-11-09 21:06:52 -0800156 if (!first) {
157 if (c >= '0' && c <= '9') {
158 continue;
159 }
160 }
161
162 c = '_';
163 first = false;
Donald Chai50bae7912017-10-18 23:51:18 -0700164 }
165 return result;
166}
167
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700168std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
169 const SplitConstraints& constraints) {
170 const ResourceId kVersionCode(0x0101021b);
171 const ResourceId kRevisionCode(0x010104d5);
172 const ResourceId kHasCode(0x0101000c);
173
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700174 std::unique_ptr<xml::Element> manifest_el = util::make_unique<xml::Element>();
Adam Lesinski5c33fb52017-08-09 10:54:23 -0700175 manifest_el->namespace_decls.push_back(CreateAndroidNamespaceDecl());
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700176 manifest_el->name = "manifest";
177 manifest_el->attributes.push_back(xml::Attribute{"", "package", app_info.package});
178
179 if (app_info.version_code) {
180 const uint32_t version_code = app_info.version_code.value();
181 manifest_el->attributes.push_back(xml::Attribute{
182 xml::kSchemaAndroid, "versionCode", std::to_string(version_code),
183 CreateAttributeWithId(kVersionCode),
184 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, version_code)});
185 }
186
187 if (app_info.revision_code) {
188 const uint32_t revision_code = app_info.revision_code.value();
189 manifest_el->attributes.push_back(xml::Attribute{
190 xml::kSchemaAndroid, "revisionCode", std::to_string(revision_code),
191 CreateAttributeWithId(kRevisionCode),
192 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, revision_code)});
193 }
194
195 std::stringstream split_name;
196 if (app_info.split_name) {
197 split_name << app_info.split_name.value() << ".";
198 }
Donald Chai50bae7912017-10-18 23:51:18 -0700199 std::vector<std::string> sanitized_config_names;
200 for (const auto &config : constraints.configs) {
201 sanitized_config_names.push_back(MakePackageSafeName(config.toString().string()));
202 }
203 split_name << "config." << util::Joiner(sanitized_config_names, "_");
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700204
205 manifest_el->attributes.push_back(xml::Attribute{"", "split", split_name.str()});
206
207 if (app_info.split_name) {
208 manifest_el->attributes.push_back(
209 xml::Attribute{"", "configForSplit", app_info.split_name.value()});
210 }
211
Adam Lesinski5c33fb52017-08-09 10:54:23 -0700212 // Splits may contain more configurations than originally desired (fall-back densities, etc.).
213 // This makes programmatic discovery of split targeting difficult. Encode the original
Adam Lesinski55f27612017-07-24 17:08:32 -0700214 // split constraints intended for this split.
215 std::stringstream target_config_str;
216 target_config_str << util::Joiner(constraints.configs, ",");
217 manifest_el->attributes.push_back(xml::Attribute{"", "targetConfig", target_config_str.str()});
218
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700219 std::unique_ptr<xml::Element> application_el = util::make_unique<xml::Element>();
220 application_el->name = "application";
221 application_el->attributes.push_back(
222 xml::Attribute{xml::kSchemaAndroid, "hasCode", "false", CreateAttributeWithId(kHasCode),
223 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_BOOLEAN, 0u)});
224
225 manifest_el->AppendChild(std::move(application_el));
Adam Lesinski5c33fb52017-08-09 10:54:23 -0700226
227 std::unique_ptr<xml::XmlResource> doc = util::make_unique<xml::XmlResource>();
228 doc->root = std::move(manifest_el);
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700229 return doc;
230}
231
232static Maybe<std::string> ExtractCompiledString(xml::Attribute* attr, std::string* out_error) {
233 if (attr->compiled_value != nullptr) {
234 String* compiled_str = ValueCast<String>(attr->compiled_value.get());
235 if (compiled_str != nullptr) {
236 if (!compiled_str->value->empty()) {
237 return *compiled_str->value;
238 } else {
239 *out_error = "compiled value is an empty string";
240 return {};
241 }
242 }
243 *out_error = "compiled value is not a string";
244 return {};
245 }
246
247 // Fallback to the plain text value if there is one.
248 if (!attr->value.empty()) {
249 return attr->value;
250 }
251 *out_error = "value is an empty string";
252 return {};
253}
254
255static Maybe<uint32_t> ExtractCompiledInt(xml::Attribute* attr, std::string* out_error) {
256 if (attr->compiled_value != nullptr) {
257 BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
258 if (compiled_prim != nullptr) {
259 if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
260 compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
261 return compiled_prim->value.data;
262 }
263 }
264 *out_error = "compiled value is not an integer";
265 return {};
266 }
267
268 // Fallback to the plain text value if there is one.
269 Maybe<uint32_t> integer = ResourceUtils::ParseInt(attr->value);
270 if (integer) {
271 return integer;
272 }
273 std::stringstream error_msg;
274 error_msg << "'" << attr->value << "' is not a valid integer";
275 *out_error = error_msg.str();
276 return {};
277}
278
279static Maybe<int> ExtractSdkVersion(xml::Attribute* attr, std::string* out_error) {
280 if (attr->compiled_value != nullptr) {
281 BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr->compiled_value.get());
282 if (compiled_prim != nullptr) {
283 if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
284 compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
285 return compiled_prim->value.data;
286 }
287 *out_error = "compiled value is not an integer or string";
288 return {};
289 }
290
291 String* compiled_str = ValueCast<String>(attr->compiled_value.get());
292 if (compiled_str != nullptr) {
293 Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(*compiled_str->value);
294 if (sdk_version) {
295 return sdk_version;
296 }
297
298 *out_error = "compiled string value is not a valid SDK version";
299 return {};
300 }
301 *out_error = "compiled value is not an integer or string";
302 return {};
303 }
304
305 // Fallback to the plain text value if there is one.
306 Maybe<int> sdk_version = ResourceUtils::ParseSdkVersion(attr->value);
307 if (sdk_version) {
308 return sdk_version;
309 }
310 std::stringstream error_msg;
311 error_msg << "'" << attr->value << "' is not a valid SDK version";
312 *out_error = error_msg.str();
313 return {};
314}
315
316Maybe<AppInfo> ExtractAppInfoFromBinaryManifest(xml::XmlResource* xml_res, IDiagnostics* diag) {
317 // Make sure the first element is <manifest> with package attribute.
Adam Lesinski5c33fb52017-08-09 10:54:23 -0700318 xml::Element* manifest_el = xml_res->root.get();
Adam Lesinskid0f492d2017-04-03 18:12:45 -0700319 if (manifest_el == nullptr) {
320 return {};
321 }
322
323 AppInfo app_info;
324
325 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
326 diag->Error(DiagMessage(xml_res->file.source) << "root tag must be <manifest>");
327 return {};
328 }
329
330 xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
331 if (!package_attr) {
332 diag->Error(DiagMessage(xml_res->file.source) << "<manifest> must have a 'package' attribute");
333 return {};
334 }
335
336 std::string error_msg;
337 Maybe<std::string> maybe_package = ExtractCompiledString(package_attr, &error_msg);
338 if (!maybe_package) {
339 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
340 << "invalid package name: " << error_msg);
341 return {};
342 }
343 app_info.package = maybe_package.value();
344
345 if (xml::Attribute* version_code_attr =
346 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
347 Maybe<uint32_t> maybe_code = ExtractCompiledInt(version_code_attr, &error_msg);
348 if (!maybe_code) {
349 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
350 << "invalid android:versionCode: " << error_msg);
351 return {};
352 }
353 app_info.version_code = maybe_code.value();
354 }
355
356 if (xml::Attribute* revision_code_attr =
357 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
358 Maybe<uint32_t> maybe_code = ExtractCompiledInt(revision_code_attr, &error_msg);
359 if (!maybe_code) {
360 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
361 << "invalid android:revisionCode: " << error_msg);
362 return {};
363 }
364 app_info.revision_code = maybe_code.value();
365 }
366
367 if (xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
368 Maybe<std::string> maybe_split_name = ExtractCompiledString(split_name_attr, &error_msg);
369 if (!maybe_split_name) {
370 diag->Error(DiagMessage(xml_res->file.source.WithLine(manifest_el->line_number))
371 << "invalid split name: " << error_msg);
372 return {};
373 }
374 app_info.split_name = maybe_split_name.value();
375 }
376
377 if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
378 if (xml::Attribute* min_sdk =
379 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
380 Maybe<int> maybe_sdk = ExtractSdkVersion(min_sdk, &error_msg);
381 if (!maybe_sdk) {
382 diag->Error(DiagMessage(xml_res->file.source.WithLine(uses_sdk_el->line_number))
383 << "invalid android:minSdkVersion: " << error_msg);
384 return {};
385 }
386 app_info.min_sdk_version = maybe_sdk.value();
387 }
388 }
389 return app_info;
390}
391
392} // namespace aapt