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