1 /*
2 * Copyright (C) 2015 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 "java/ProguardRules.h"
18
19 #include <memory>
20 #include <string>
21
22 #include "android-base/macros.h"
23 #include "androidfw/StringPiece.h"
24
25 #include "JavaClassGenerator.h"
26 #include "ResourceUtils.h"
27 #include "ValueVisitor.h"
28 #include "text/Printer.h"
29 #include "util/Util.h"
30 #include "xml/XmlDom.h"
31
32 using ::aapt::io::OutputStream;
33 using ::aapt::text::Printer;
34
35 namespace aapt {
36 namespace proguard {
37
38 class BaseVisitor : public xml::Visitor {
39 public:
40 using xml::Visitor::Visit;
41
BaseVisitor(const ResourceFile & file,KeepSet * keep_set)42 BaseVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set, "...") {
43 }
44
BaseVisitor(const ResourceFile & file,KeepSet * keep_set,const std::string & ctor_signature)45 BaseVisitor(const ResourceFile& file, KeepSet* keep_set, const std::string& ctor_signature)
46 : file_(file), keep_set_(keep_set), ctor_signature_(ctor_signature) {
47 }
48
Visit(xml::Element * node)49 void Visit(xml::Element* node) override {
50 if (!node->namespace_uri.empty()) {
51 Maybe<xml::ExtractedPackage> maybe_package =
52 xml::ExtractPackageFromNamespace(node->namespace_uri);
53 if (maybe_package) {
54 // This is a custom view, let's figure out the class name from this.
55 std::string package = maybe_package.value().package + "." + node->name;
56 if (util::IsJavaClassName(package)) {
57 AddClass(node->line_number, package, ctor_signature_);
58 }
59 }
60 } else if (util::IsJavaClassName(node->name)) {
61 AddClass(node->line_number, node->name, ctor_signature_);
62 }
63
64 for (const auto& child : node->children) {
65 child->Accept(this);
66 }
67
68 for (const auto& attr : node->attributes) {
69 if (attr.compiled_value) {
70 auto ref = ValueCast<Reference>(attr.compiled_value.get());
71 if (ref) {
72 AddReference(node->line_number, ref);
73 }
74 }
75 }
76 }
77
78 protected:
79 ResourceFile file_;
80 KeepSet* keep_set_;
81 std::string ctor_signature_;
82
AddClass(size_t line_number,const std::string & class_name,const std::string & ctor_signature)83 virtual void AddClass(size_t line_number, const std::string& class_name,
84 const std::string& ctor_signature) {
85 keep_set_->AddConditionalClass({file_.name, file_.source.WithLine(line_number)},
86 {class_name, ctor_signature});
87 }
88
AddMethod(size_t line_number,const std::string & method_name,const std::string & method_signature)89 void AddMethod(size_t line_number, const std::string& method_name,
90 const std::string& method_signature) {
91 keep_set_->AddMethod({file_.name, file_.source.WithLine(line_number)},
92 {method_name, method_signature});
93 }
94
AddReference(size_t line_number,Reference * ref)95 void AddReference(size_t line_number, Reference* ref) {
96 if (ref && ref->name) {
97 ResourceName ref_name = ref->name.value();
98 if (ref_name.package.empty()) {
99 ref_name = ResourceName(file_.name.package, ref_name.type, ref_name.entry);
100 }
101 keep_set_->AddReference({file_.name, file_.source.WithLine(line_number)}, ref_name);
102 }
103 }
104
105 private:
106 DISALLOW_COPY_AND_ASSIGN(BaseVisitor);
107
108 };
109
110 class LayoutVisitor : public BaseVisitor {
111 public:
LayoutVisitor(const ResourceFile & file,KeepSet * keep_set)112 LayoutVisitor(const ResourceFile& file, KeepSet* keep_set)
113 : BaseVisitor(file, keep_set, "android.content.Context, android.util.AttributeSet") {
114 }
115
Visit(xml::Element * node)116 void Visit(xml::Element* node) override {
117 bool is_view = false;
118 if (node->namespace_uri.empty()) {
119 if (node->name == "view") {
120 is_view = true;
121 }
122 }
123
124 for (const auto& attr : node->attributes) {
125 if (attr.namespace_uri.empty() && attr.name == "class") {
126 if (util::IsJavaClassName(attr.value)) {
127 if (is_view) {
128 AddClass(node->line_number, attr.value,
129 "android.content.Context, android.util.AttributeSet");
130 } else {
131 AddClass(node->line_number, attr.value, "");
132 }
133 }
134 } else if (attr.namespace_uri == xml::kSchemaAndroid && attr.name == "name") {
135 if (util::IsJavaClassName(attr.value)) {
136 AddClass(node->line_number, attr.value, "");
137 }
138 } else if (attr.namespace_uri == xml::kSchemaAndroid && attr.name == "onClick") {
139 AddMethod(node->line_number, attr.value, "android.view.View");
140 }
141 }
142
143 BaseVisitor::Visit(node);
144 }
145
146 private:
147 DISALLOW_COPY_AND_ASSIGN(LayoutVisitor);
148 };
149
150 class MenuVisitor : public BaseVisitor {
151 public:
MenuVisitor(const ResourceFile & file,KeepSet * keep_set)152 MenuVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set) {
153 }
154
Visit(xml::Element * node)155 void Visit(xml::Element* node) override {
156 if (node->namespace_uri.empty() && node->name == "item") {
157 for (const auto& attr : node->attributes) {
158 // AppCompat-v7 defines its own versions of Android attributes if
159 // they're defined after SDK 7 (the below are from 11 and 14,
160 // respectively), so don't bother checking the XML namespace.
161 //
162 // Given the names of the containing XML files and the attribute
163 // names, it's unlikely that keeping these classes would be wrong.
164 if ((attr.name == "actionViewClass" || attr.name == "actionProviderClass") &&
165 util::IsJavaClassName(attr.value)) {
166 AddClass(node->line_number, attr.value, "android.content.Context");
167 }
168
169 if (attr.namespace_uri == xml::kSchemaAndroid && attr.name == "onClick") {
170 AddMethod(node->line_number, attr.value, "android.view.MenuItem");
171 }
172 }
173 }
174
175 BaseVisitor::Visit(node);
176 }
177
178 private:
179 DISALLOW_COPY_AND_ASSIGN(MenuVisitor);
180 };
181
182 class XmlResourceVisitor : public BaseVisitor {
183 public:
XmlResourceVisitor(const ResourceFile & file,KeepSet * keep_set)184 XmlResourceVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set) {
185 }
186
Visit(xml::Element * node)187 void Visit(xml::Element* node) override {
188 bool check_fragment = false;
189 if (node->namespace_uri.empty()) {
190 check_fragment =
191 node->name == "PreferenceScreen" || node->name == "header";
192 }
193
194 if (check_fragment) {
195 xml::Attribute* attr =
196 node->FindAttribute(xml::kSchemaAndroid, "fragment");
197 if (attr && util::IsJavaClassName(attr->value)) {
198 AddClass(node->line_number, attr->value, "");
199 }
200 }
201
202 BaseVisitor::Visit(node);
203 }
204
205 private:
206 DISALLOW_COPY_AND_ASSIGN(XmlResourceVisitor);
207 };
208
209 class NavigationVisitor : public BaseVisitor {
210 public:
NavigationVisitor(const ResourceFile & file,KeepSet * keep_set,const std::string & package)211 NavigationVisitor(const ResourceFile& file, KeepSet* keep_set, const std::string& package)
212 : BaseVisitor(file, keep_set), package_(package) {
213 }
214
Visit(xml::Element * node)215 void Visit(xml::Element* node) override {
216 const auto& attr = node->FindAttribute(xml::kSchemaAndroid, "name");
217 if (attr != nullptr && !attr->value.empty()) {
218 std::string name = (attr->value[0] == '.') ? package_ + attr->value : attr->value;
219 if (util::IsJavaClassName(name)) {
220 AddClass(node->line_number, name, "...");
221 }
222 }
223
224 BaseVisitor::Visit(node);
225 }
226
227 private:
228 DISALLOW_COPY_AND_ASSIGN(NavigationVisitor);
229 const std::string package_;
230 };
231
232 class TransitionVisitor : public BaseVisitor {
233 public:
TransitionVisitor(const ResourceFile & file,KeepSet * keep_set)234 TransitionVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set) {
235 }
236
Visit(xml::Element * node)237 void Visit(xml::Element* node) override {
238 bool check_class =
239 node->namespace_uri.empty() && (node->name == "transition" || node->name == "pathMotion");
240 if (check_class) {
241 xml::Attribute* attr = node->FindAttribute({}, "class");
242 if (attr && util::IsJavaClassName(attr->value)) {
243 AddClass(node->line_number, attr->value,
244 "android.content.Context, android.util.AttributeSet");
245 }
246 }
247
248 BaseVisitor::Visit(node);
249 }
250
251 private:
252 DISALLOW_COPY_AND_ASSIGN(TransitionVisitor);
253 };
254
255 class ManifestVisitor : public BaseVisitor {
256 public:
ManifestVisitor(const ResourceFile & file,KeepSet * keep_set,bool main_dex_only)257 ManifestVisitor(const ResourceFile& file, KeepSet* keep_set, bool main_dex_only)
258 : BaseVisitor(file, keep_set), main_dex_only_(main_dex_only) {
259 }
260
Visit(xml::Element * node)261 void Visit(xml::Element* node) override {
262 if (node->namespace_uri.empty()) {
263 bool get_name = false;
264 if (node->name == "manifest") {
265 xml::Attribute* attr = node->FindAttribute({}, "package");
266 if (attr) {
267 package_ = attr->value;
268 }
269 } else if (node->name == "application") {
270 get_name = true;
271 xml::Attribute* attr = node->FindAttribute(xml::kSchemaAndroid, "backupAgent");
272 if (attr) {
273 Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
274 if (result) {
275 AddClass(node->line_number, result.value(), "");
276 }
277 }
278 attr = node->FindAttribute(xml::kSchemaAndroid, "appComponentFactory");
279 if (attr) {
280 Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
281 if (result) {
282 AddClass(node->line_number, result.value(), "");
283 }
284 }
285
286 attr = node->FindAttribute(xml::kSchemaAndroid, "zygotePreloadName");
287 if (attr) {
288 Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
289 if (result) {
290 AddClass(node->line_number, result.value(), "");
291 }
292 }
293
294 if (main_dex_only_) {
295 xml::Attribute* default_process = node->FindAttribute(xml::kSchemaAndroid, "process");
296 if (default_process) {
297 default_process_ = default_process->value;
298 }
299 }
300 } else if (node->name == "activity" || node->name == "service" ||
301 node->name == "receiver" || node->name == "provider") {
302 get_name = true;
303
304 if (main_dex_only_) {
305 xml::Attribute* component_process = node->FindAttribute(xml::kSchemaAndroid, "process");
306
307 const std::string& process =
308 component_process ? component_process->value : default_process_;
309 get_name = !process.empty() && process[0] != ':';
310 }
311 } else if (node->name == "instrumentation") {
312 get_name = true;
313 }
314
315 if (get_name) {
316 xml::Attribute* attr = node->FindAttribute(xml::kSchemaAndroid, "name");
317 get_name = attr != nullptr;
318
319 if (get_name) {
320 Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
321 if (result) {
322 AddClass(node->line_number, result.value(), "");
323 }
324 }
325 }
326 }
327 BaseVisitor::Visit(node);
328 }
329
AddClass(size_t line_number,const std::string & class_name,const std::string & ctor_signature)330 virtual void AddClass(size_t line_number, const std::string& class_name,
331 const std::string& ctor_signature) override {
332 keep_set_->AddManifestClass({file_.name, file_.source.WithLine(line_number)}, class_name);
333 }
334
335 private:
336 DISALLOW_COPY_AND_ASSIGN(ManifestVisitor);
337
338 std::string package_;
339 const bool main_dex_only_;
340 std::string default_process_;
341 };
342
CollectProguardRulesForManifest(xml::XmlResource * res,KeepSet * keep_set,bool main_dex_only)343 bool CollectProguardRulesForManifest(xml::XmlResource* res, KeepSet* keep_set, bool main_dex_only) {
344 ManifestVisitor visitor(res->file, keep_set, main_dex_only);
345 if (res->root) {
346 res->root->Accept(&visitor);
347 return true;
348 }
349 return false;
350 }
351
CollectProguardRules(IAaptContext * context_,xml::XmlResource * res,KeepSet * keep_set)352 bool CollectProguardRules(IAaptContext* context_, xml::XmlResource* res, KeepSet* keep_set) {
353 if (!res->root) {
354 return false;
355 }
356
357 switch (res->file.name.type) {
358 case ResourceType::kLayout: {
359 LayoutVisitor visitor(res->file, keep_set);
360 res->root->Accept(&visitor);
361 break;
362 }
363
364 case ResourceType::kXml: {
365 XmlResourceVisitor visitor(res->file, keep_set);
366 res->root->Accept(&visitor);
367 break;
368 }
369
370 case ResourceType::kNavigation: {
371 NavigationVisitor visitor(res->file, keep_set, context_->GetCompilationPackage());
372 res->root->Accept(&visitor);
373 break;
374 }
375
376 case ResourceType::kTransition: {
377 TransitionVisitor visitor(res->file, keep_set);
378 res->root->Accept(&visitor);
379 break;
380 }
381
382 case ResourceType::kMenu: {
383 MenuVisitor visitor(res->file, keep_set);
384 res->root->Accept(&visitor);
385 break;
386 }
387
388 default: {
389 BaseVisitor visitor(res->file, keep_set);
390 res->root->Accept(&visitor);
391 break;
392 }
393 }
394 return true;
395 }
396
WriteKeepSet(const KeepSet & keep_set,OutputStream * out,bool minimal_keep,bool no_location_reference)397 void WriteKeepSet(const KeepSet& keep_set, OutputStream* out, bool minimal_keep,
398 bool no_location_reference) {
399
400 Printer printer(out);
401 for (const auto& entry : keep_set.manifest_class_set_) {
402 if (!no_location_reference) {
403 for (const UsageLocation& location : entry.second) {
404 printer.Print("# Referenced at ").Println(location.source.to_string());
405 }
406 }
407 printer.Print("-keep class ").Print(entry.first).Println(" { <init>(); }");
408 }
409
410 for (const auto& entry : keep_set.conditional_class_set_) {
411 std::set<UsageLocation> locations;
412 bool can_be_conditional = false;
413 if (keep_set.conditional_keep_rules_) {
414 can_be_conditional = true;
415 for (const UsageLocation& location : entry.second) {
416 can_be_conditional &= CollectLocations(location, keep_set, &locations);
417 }
418 }
419
420 if (can_be_conditional) {
421 for (const UsageLocation& location : locations) {
422 if (!no_location_reference) {
423 printer.Print("# Referenced at ").Println(location.source.to_string());
424 }
425 printer.Print("-if class **.R$layout { int ")
426 .Print(JavaClassGenerator::TransformToFieldName(location.name.entry))
427 .Println("; }");
428
429 printer.Print("-keep class ").Print(entry.first.name).Print(" { <init>(");
430 printer.Print((minimal_keep) ? entry.first.signature : "...");
431 printer.Println("); }");
432 }
433 } else {
434 if (!no_location_reference) {
435 for (const UsageLocation& location : entry.second) {
436 printer.Print("# Referenced at ").Println(location.source.to_string());
437 }
438 }
439
440 printer.Print("-keep class ").Print(entry.first.name).Print(" { <init>(");
441 printer.Print((minimal_keep) ? entry.first.signature : "...");
442 printer.Println("); }");
443 }
444 printer.Println();
445 }
446
447 for (const auto& entry : keep_set.method_set_) {
448 if (!no_location_reference) {
449 for (const UsageLocation& location : entry.second) {
450 printer.Print("# Referenced at ").Println(location.source.to_string());
451 }
452 }
453 printer.Print("-keepclassmembers class * { *** ").Print(entry.first.name)
454 .Print("(").Print(entry.first.signature).Println("); }");
455 printer.Println();
456 }
457 }
458
CollectLocations(const UsageLocation & location,const KeepSet & keep_set,std::set<UsageLocation> * locations)459 bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set,
460 std::set<UsageLocation>* locations) {
461 locations->insert(location);
462
463 // TODO: allow for more reference types if we can determine its safe.
464 if (location.name.type != ResourceType::kLayout) {
465 return false;
466 }
467
468 for (const auto& entry : keep_set.reference_set_) {
469 if (entry.first == location.name) {
470 for (auto& refLocation : entry.second) {
471 // Don't get stuck in loops
472 if (locations->find(refLocation) != locations->end()) {
473 return false;
474 }
475 if (!CollectLocations(refLocation, keep_set, locations)) {
476 return false;
477 }
478 }
479 }
480 }
481
482 return true;
483 }
484
485 class ReferenceVisitor : public ValueVisitor {
486 public:
487 using ValueVisitor::Visit;
488
ReferenceVisitor(aapt::IAaptContext * context,ResourceName from,KeepSet * keep_set)489 ReferenceVisitor(aapt::IAaptContext* context, ResourceName from, KeepSet* keep_set)
490 : context_(context), from_(from), keep_set_(keep_set) {
491 }
492
Visit(Reference * reference)493 void Visit(Reference* reference) override {
494 if (reference->name) {
495 ResourceName reference_name = reference->name.value();
496 if (reference_name.package.empty()) {
497 reference_name = ResourceName(context_->GetCompilationPackage(), reference_name.type,
498 reference_name.entry);
499 }
500 keep_set_->AddReference({from_, reference->GetSource()}, reference_name);
501 }
502 }
503
504 private:
505 aapt::IAaptContext* context_;
506 ResourceName from_;
507 KeepSet* keep_set_;
508 };
509
CollectResourceReferences(aapt::IAaptContext * context,ResourceTable * table,KeepSet * keep_set)510 bool CollectResourceReferences(aapt::IAaptContext* context, ResourceTable* table,
511 KeepSet* keep_set) {
512 for (auto& pkg : table->packages) {
513 for (auto& type : pkg->types) {
514 for (auto& entry : type->entries) {
515 for (auto& config_value : entry->values) {
516 ResourceName from(pkg->name, type->type, entry->name);
517 ReferenceVisitor visitor(context, from, keep_set);
518 config_value->value->Accept(&visitor);
519 }
520 }
521 }
522 }
523 return true;
524 }
525
526 } // namespace proguard
527 } // namespace aapt
528