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 "cmd/Util.h"
18
19 #include <vector>
20
21 #include "android-base/logging.h"
22 #include "androidfw/ConfigDescription.h"
23 #include "androidfw/Locale.h"
24 #include "ResourceUtils.h"
25 #include "ValueVisitor.h"
26 #include "split/TableSplitter.h"
27
28 #include "util/Util.h"
29
30 using ::android::ConfigDescription;
31 using ::android::LocaleValue;
32 using ::android::StringPiece;
33 using ::android::base::StringPrintf;
34
35 namespace aapt {
36
ParseTargetDensityParameter(const StringPiece & arg,IDiagnostics * diag)37 std::optional<uint16_t> ParseTargetDensityParameter(const StringPiece& arg, IDiagnostics* diag) {
38 ConfigDescription preferred_density_config;
39 if (!ConfigDescription::Parse(arg, &preferred_density_config)) {
40 diag->Error(DiagMessage() << "invalid density '" << arg << "' for --preferred-density option");
41 return {};
42 }
43
44 // Clear the version that can be automatically added.
45 preferred_density_config.sdkVersion = 0;
46
47 if (preferred_density_config.diff(ConfigDescription::DefaultConfig()) !=
48 ConfigDescription::CONFIG_DENSITY) {
49 diag->Error(DiagMessage() << "invalid preferred density '" << arg << "'. "
50 << "Preferred density must only be a density value");
51 return {};
52 }
53 return preferred_density_config.density;
54 }
55
ParseSplitParameter(const StringPiece & arg,IDiagnostics * diag,std::string * out_path,SplitConstraints * out_split)56 bool ParseSplitParameter(const StringPiece& arg, IDiagnostics* diag, std::string* out_path,
57 SplitConstraints* out_split) {
58 CHECK(diag != nullptr);
59 CHECK(out_path != nullptr);
60 CHECK(out_split != nullptr);
61
62 #ifdef _WIN32
63 const char sSeparator = ';';
64 #else
65 const char sSeparator = ':';
66 #endif
67
68 std::vector<std::string> parts = util::Split(arg, sSeparator);
69 if (parts.size() != 2) {
70 diag->Error(DiagMessage() << "invalid split parameter '" << arg << "'");
71 diag->Note(DiagMessage() << "should be --split path/to/output.apk" << sSeparator
72 << "<config>[,<config>...].");
73 return false;
74 }
75
76 *out_path = parts[0];
77 out_split->name = parts[1];
78 for (const StringPiece& config_str : util::Tokenize(parts[1], ',')) {
79 ConfigDescription config;
80 if (!ConfigDescription::Parse(config_str, &config)) {
81 diag->Error(DiagMessage() << "invalid config '" << config_str << "' in split parameter '"
82 << arg << "'");
83 return false;
84 }
85 out_split->configs.insert(config);
86 }
87 return true;
88 }
89
ParseConfigFilterParameters(const std::vector<std::string> & args,IDiagnostics * diag)90 std::unique_ptr<IConfigFilter> ParseConfigFilterParameters(const std::vector<std::string>& args,
91 IDiagnostics* diag) {
92 std::unique_ptr<AxisConfigFilter> filter = util::make_unique<AxisConfigFilter>();
93 for (const std::string& config_arg : args) {
94 for (const StringPiece& config_str : util::Tokenize(config_arg, ',')) {
95 ConfigDescription config;
96 LocaleValue lv;
97 if (lv.InitFromFilterString(config_str)) {
98 lv.WriteTo(&config);
99 } else if (!ConfigDescription::Parse(config_str, &config)) {
100 diag->Error(DiagMessage() << "invalid config '" << config_str << "' for -c option");
101 return {};
102 }
103
104 if (config.density != 0) {
105 diag->Warn(DiagMessage() << "ignoring density '" << config << "' for -c option");
106 } else {
107 filter->AddConfig(config);
108 }
109 }
110 }
111 return std::move(filter);
112 }
113
114 // Adjust the SplitConstraints so that their SDK version is stripped if it
115 // is less than or equal to the minSdk. Otherwise the resources that have had
116 // their SDK version stripped due to minSdk won't ever match.
AdjustSplitConstraintsForMinSdk(int min_sdk,const std::vector<SplitConstraints> & split_constraints)117 std::vector<SplitConstraints> AdjustSplitConstraintsForMinSdk(
118 int min_sdk, const std::vector<SplitConstraints>& split_constraints) {
119 std::vector<SplitConstraints> adjusted_constraints;
120 adjusted_constraints.reserve(split_constraints.size());
121 for (const SplitConstraints& constraints : split_constraints) {
122 SplitConstraints constraint;
123 for (const ConfigDescription& config : constraints.configs) {
124 const ConfigDescription &configToInsert = (config.sdkVersion <= min_sdk)
125 ? config.CopyWithoutSdkVersion()
126 : config;
127 // only add the config if it actually selects something
128 if (configToInsert != ConfigDescription::DefaultConfig()) {
129 constraint.configs.insert(configToInsert);
130 }
131 }
132 constraint.name = constraints.name;
133 adjusted_constraints.push_back(std::move(constraint));
134 }
135 return adjusted_constraints;
136 }
137
CreateAttributeWithId(const ResourceId & id)138 static xml::AaptAttribute CreateAttributeWithId(const ResourceId& id) {
139 return xml::AaptAttribute(Attribute(), id);
140 }
141
CreateAndroidNamespaceDecl()142 static xml::NamespaceDecl CreateAndroidNamespaceDecl() {
143 xml::NamespaceDecl decl;
144 decl.prefix = "android";
145 decl.uri = xml::kSchemaAndroid;
146 return decl;
147 }
148
149 // Returns a copy of 'name' which conforms to the regex '[a-zA-Z]+[a-zA-Z0-9_]*' by
150 // replacing nonconforming characters with underscores.
151 //
152 // See frameworks/base/core/java/android/content/pm/PackageParser.java which
153 // checks this at runtime.
MakePackageSafeName(const std::string & name)154 std::string MakePackageSafeName(const std::string &name) {
155 std::string result(name);
156 bool first = true;
157 for (char &c : result) {
158 if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
159 first = false;
160 continue;
161 }
162 if (!first) {
163 if (c >= '0' && c <= '9') {
164 continue;
165 }
166 }
167
168 c = '_';
169 first = false;
170 }
171 return result;
172 }
173
GenerateSplitManifest(const AppInfo & app_info,const SplitConstraints & constraints)174 std::unique_ptr<xml::XmlResource> GenerateSplitManifest(const AppInfo& app_info,
175 const SplitConstraints& constraints) {
176 const ResourceId kVersionCode(0x0101021b);
177 const ResourceId kVersionCodeMajor(0x01010576);
178 const ResourceId kRevisionCode(0x010104d5);
179 const ResourceId kHasCode(0x0101000c);
180
181 std::unique_ptr<xml::Element> manifest_el = util::make_unique<xml::Element>();
182 manifest_el->namespace_decls.push_back(CreateAndroidNamespaceDecl());
183 manifest_el->name = "manifest";
184 manifest_el->attributes.push_back(xml::Attribute{"", "package", app_info.package});
185
186 if (app_info.version_code) {
187 const uint32_t version_code = app_info.version_code.value();
188 manifest_el->attributes.push_back(xml::Attribute{
189 xml::kSchemaAndroid, "versionCode", std::to_string(version_code),
190 CreateAttributeWithId(kVersionCode),
191 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, version_code)});
192 }
193
194 if (app_info.version_code_major) {
195 const uint32_t version_code_major = app_info.version_code_major.value();
196 manifest_el->attributes.push_back(xml::Attribute{
197 xml::kSchemaAndroid, "versionCodeMajor", std::to_string(version_code_major),
198 CreateAttributeWithId(kVersionCodeMajor),
199 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, version_code_major)});
200 }
201
202 if (app_info.revision_code) {
203 const uint32_t revision_code = app_info.revision_code.value();
204 manifest_el->attributes.push_back(xml::Attribute{
205 xml::kSchemaAndroid, "revisionCode", std::to_string(revision_code),
206 CreateAttributeWithId(kRevisionCode),
207 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_DEC, revision_code)});
208 }
209
210 std::stringstream split_name;
211 if (app_info.split_name) {
212 split_name << app_info.split_name.value() << ".";
213 }
214 std::vector<std::string> sanitized_config_names;
215 for (const auto &config : constraints.configs) {
216 sanitized_config_names.push_back(MakePackageSafeName(config.toString().string()));
217 }
218 split_name << "config." << util::Joiner(sanitized_config_names, "_");
219
220 manifest_el->attributes.push_back(xml::Attribute{"", "split", split_name.str()});
221
222 if (app_info.split_name) {
223 manifest_el->attributes.push_back(
224 xml::Attribute{"", "configForSplit", app_info.split_name.value()});
225 }
226
227 // Splits may contain more configurations than originally desired (fall-back densities, etc.).
228 // This makes programmatic discovery of split targeting difficult. Encode the original
229 // split constraints intended for this split.
230 std::stringstream target_config_str;
231 target_config_str << util::Joiner(constraints.configs, ",");
232 manifest_el->attributes.push_back(xml::Attribute{"", "targetConfig", target_config_str.str()});
233
234 std::unique_ptr<xml::Element> application_el = util::make_unique<xml::Element>();
235 application_el->name = "application";
236 application_el->attributes.push_back(
237 xml::Attribute{xml::kSchemaAndroid, "hasCode", "false", CreateAttributeWithId(kHasCode),
238 util::make_unique<BinaryPrimitive>(android::Res_value::TYPE_INT_BOOLEAN, 0u)});
239
240 manifest_el->AppendChild(std::move(application_el));
241
242 std::unique_ptr<xml::XmlResource> doc = util::make_unique<xml::XmlResource>();
243 doc->root = std::move(manifest_el);
244 return doc;
245 }
246
ExtractCompiledString(const xml::Attribute & attr,std::string * out_error)247 static std::optional<std::string> ExtractCompiledString(const xml::Attribute& attr,
248 std::string* out_error) {
249 if (attr.compiled_value != nullptr) {
250 const String* compiled_str = ValueCast<String>(attr.compiled_value.get());
251 if (compiled_str != nullptr) {
252 if (!compiled_str->value->empty()) {
253 return *compiled_str->value;
254 } else {
255 *out_error = "compiled value is an empty string";
256 return {};
257 }
258 }
259 *out_error = "compiled value is not a string";
260 return {};
261 }
262
263 // Fallback to the plain text value if there is one.
264 if (!attr.value.empty()) {
265 return attr.value;
266 }
267 *out_error = "value is an empty string";
268 return {};
269 }
270
ExtractCompiledInt(const xml::Attribute & attr,std::string * out_error)271 static std::optional<uint32_t> ExtractCompiledInt(const xml::Attribute& attr,
272 std::string* out_error) {
273 if (attr.compiled_value != nullptr) {
274 const BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr.compiled_value.get());
275 if (compiled_prim != nullptr) {
276 if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
277 compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
278 return compiled_prim->value.data;
279 }
280 }
281 *out_error = "compiled value is not an integer";
282 return {};
283 }
284
285 // Fallback to the plain text value if there is one.
286 std::optional<uint32_t> integer = ResourceUtils::ParseInt(attr.value);
287 if (integer) {
288 return integer;
289 }
290 std::stringstream error_msg;
291 error_msg << "'" << attr.value << "' is not a valid integer";
292 *out_error = error_msg.str();
293 return {};
294 }
295
ExtractSdkVersion(const xml::Attribute & attr,std::string * out_error)296 static std::optional<int> ExtractSdkVersion(const xml::Attribute& attr, std::string* out_error) {
297 if (attr.compiled_value != nullptr) {
298 const BinaryPrimitive* compiled_prim = ValueCast<BinaryPrimitive>(attr.compiled_value.get());
299 if (compiled_prim != nullptr) {
300 if (compiled_prim->value.dataType >= android::Res_value::TYPE_FIRST_INT &&
301 compiled_prim->value.dataType <= android::Res_value::TYPE_LAST_INT) {
302 return compiled_prim->value.data;
303 }
304 *out_error = "compiled value is not an integer or string";
305 return {};
306 }
307
308 const String* compiled_str = ValueCast<String>(attr.compiled_value.get());
309 if (compiled_str != nullptr) {
310 std::optional<int> sdk_version = ResourceUtils::ParseSdkVersion(*compiled_str->value);
311 if (sdk_version) {
312 return sdk_version;
313 }
314
315 *out_error = "compiled string value is not a valid SDK version";
316 return {};
317 }
318 *out_error = "compiled value is not an integer or string";
319 return {};
320 }
321
322 // Fallback to the plain text value if there is one.
323 std::optional<int> sdk_version = ResourceUtils::ParseSdkVersion(attr.value);
324 if (sdk_version) {
325 return sdk_version;
326 }
327 std::stringstream error_msg;
328 error_msg << "'" << attr.value << "' is not a valid SDK version";
329 *out_error = error_msg.str();
330 return {};
331 }
332
ExtractAppInfoFromBinaryManifest(const xml::XmlResource & xml_res,IDiagnostics * diag)333 std::optional<AppInfo> ExtractAppInfoFromBinaryManifest(const xml::XmlResource& xml_res,
334 IDiagnostics* diag) {
335 // Make sure the first element is <manifest> with package attribute.
336 const xml::Element* manifest_el = xml_res.root.get();
337 if (manifest_el == nullptr) {
338 return {};
339 }
340
341 AppInfo app_info;
342
343 if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
344 diag->Error(DiagMessage(xml_res.file.source) << "root tag must be <manifest>");
345 return {};
346 }
347
348 const xml::Attribute* package_attr = manifest_el->FindAttribute({}, "package");
349 if (!package_attr) {
350 diag->Error(DiagMessage(xml_res.file.source) << "<manifest> must have a 'package' attribute");
351 return {};
352 }
353
354 std::string error_msg;
355 std::optional<std::string> maybe_package = ExtractCompiledString(*package_attr, &error_msg);
356 if (!maybe_package) {
357 diag->Error(DiagMessage(xml_res.file.source.WithLine(manifest_el->line_number))
358 << "invalid package name: " << error_msg);
359 return {};
360 }
361 app_info.package = maybe_package.value();
362
363 if (const xml::Attribute* version_code_attr =
364 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCode")) {
365 std::optional<uint32_t> maybe_code = ExtractCompiledInt(*version_code_attr, &error_msg);
366 if (!maybe_code) {
367 diag->Error(DiagMessage(xml_res.file.source.WithLine(manifest_el->line_number))
368 << "invalid android:versionCode: " << error_msg);
369 return {};
370 }
371 app_info.version_code = maybe_code.value();
372 }
373
374 if (const xml::Attribute* version_code_major_attr =
375 manifest_el->FindAttribute(xml::kSchemaAndroid, "versionCodeMajor")) {
376 std::optional<uint32_t> maybe_code = ExtractCompiledInt(*version_code_major_attr, &error_msg);
377 if (!maybe_code) {
378 diag->Error(DiagMessage(xml_res.file.source.WithLine(manifest_el->line_number))
379 << "invalid android:versionCodeMajor: " << error_msg);
380 return {};
381 }
382 app_info.version_code_major = maybe_code.value();
383 }
384
385 if (const xml::Attribute* revision_code_attr =
386 manifest_el->FindAttribute(xml::kSchemaAndroid, "revisionCode")) {
387 std::optional<uint32_t> maybe_code = ExtractCompiledInt(*revision_code_attr, &error_msg);
388 if (!maybe_code) {
389 diag->Error(DiagMessage(xml_res.file.source.WithLine(manifest_el->line_number))
390 << "invalid android:revisionCode: " << error_msg);
391 return {};
392 }
393 app_info.revision_code = maybe_code.value();
394 }
395
396 if (const xml::Attribute* split_name_attr = manifest_el->FindAttribute({}, "split")) {
397 std::optional<std::string> maybe_split_name =
398 ExtractCompiledString(*split_name_attr, &error_msg);
399 if (!maybe_split_name) {
400 diag->Error(DiagMessage(xml_res.file.source.WithLine(manifest_el->line_number))
401 << "invalid split name: " << error_msg);
402 return {};
403 }
404 app_info.split_name = maybe_split_name.value();
405 }
406
407 if (const xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
408 if (const xml::Attribute* min_sdk =
409 uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
410 std::optional<int> maybe_sdk = ExtractSdkVersion(*min_sdk, &error_msg);
411 if (!maybe_sdk) {
412 diag->Error(DiagMessage(xml_res.file.source.WithLine(uses_sdk_el->line_number))
413 << "invalid android:minSdkVersion: " << error_msg);
414 return {};
415 }
416 app_info.min_sdk_version = maybe_sdk.value();
417 }
418 }
419 return app_info;
420 }
421
SetLongVersionCode(xml::Element * manifest,uint64_t version)422 void SetLongVersionCode(xml::Element* manifest, uint64_t version) {
423 // Write the low bits of the version code to android:versionCode
424 auto version_code = manifest->FindOrCreateAttribute(xml::kSchemaAndroid, "versionCode");
425 version_code->value = StringPrintf("0x%08x", (uint32_t) (version & 0xffffffff));
426 version_code->compiled_value = ResourceUtils::TryParseInt(version_code->value);
427
428 auto version_high = (uint32_t) (version >> 32);
429 if (version_high != 0) {
430 // Write the high bits of the version code to android:versionCodeMajor
431 auto version_major = manifest->FindOrCreateAttribute(xml::kSchemaAndroid, "versionCodeMajor");
432 version_major->value = StringPrintf("0x%08x", version_high);
433 version_major->compiled_value = ResourceUtils::TryParseInt(version_major->value);
434 } else {
435 manifest->RemoveAttribute(xml::kSchemaAndroid, "versionCodeMajor");
436 }
437 }
438
GetRegularExpression(const std::string & input)439 std::regex GetRegularExpression(const std::string &input) {
440 // Standard ECMAScript grammar.
441 std::regex case_insensitive(
442 input, std::regex_constants::ECMAScript);
443 return case_insensitive;
444 }
445
446 } // namespace aapt
447