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         if (attr.namespace_uri == xml::kSchemaAndroid) {
159           if ((attr.name == "actionViewClass" || attr.name == "actionProviderClass") &&
160               util::IsJavaClassName(attr.value)) {
161             AddClass(node->line_number, attr.value, "android.content.Context");
162           } else if (attr.name == "onClick") {
163             AddMethod(node->line_number, attr.value, "android.view.MenuItem");
164           }
165         }
166       }
167     }
168 
169     BaseVisitor::Visit(node);
170   }
171 
172  private:
173   DISALLOW_COPY_AND_ASSIGN(MenuVisitor);
174 };
175 
176 class XmlResourceVisitor : public BaseVisitor {
177  public:
XmlResourceVisitor(const ResourceFile & file,KeepSet * keep_set)178   XmlResourceVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set) {
179   }
180 
Visit(xml::Element * node)181   void Visit(xml::Element* node) override {
182     bool check_fragment = false;
183     if (node->namespace_uri.empty()) {
184       check_fragment =
185           node->name == "PreferenceScreen" || node->name == "header";
186     }
187 
188     if (check_fragment) {
189       xml::Attribute* attr =
190           node->FindAttribute(xml::kSchemaAndroid, "fragment");
191       if (attr && util::IsJavaClassName(attr->value)) {
192         AddClass(node->line_number, attr->value, "");
193       }
194     }
195 
196     BaseVisitor::Visit(node);
197   }
198 
199  private:
200   DISALLOW_COPY_AND_ASSIGN(XmlResourceVisitor);
201 };
202 
203 class NavigationVisitor : public BaseVisitor {
204  public:
NavigationVisitor(const ResourceFile & file,KeepSet * keep_set,const std::string & package)205   NavigationVisitor(const ResourceFile& file, KeepSet* keep_set, const std::string& package)
206       : BaseVisitor(file, keep_set), package_(package) {
207   }
208 
Visit(xml::Element * node)209   void Visit(xml::Element* node) override {
210     const auto& attr = node->FindAttribute(xml::kSchemaAndroid, "name");
211     if (attr != nullptr && !attr->value.empty()) {
212       std::string name = (attr->value[0] == '.') ? package_ + attr->value : attr->value;
213       if (util::IsJavaClassName(name)) {
214         AddClass(node->line_number, name, "...");
215       }
216     }
217 
218     BaseVisitor::Visit(node);
219   }
220 
221  private:
222   DISALLOW_COPY_AND_ASSIGN(NavigationVisitor);
223   const std::string package_;
224 };
225 
226 class TransitionVisitor : public BaseVisitor {
227  public:
TransitionVisitor(const ResourceFile & file,KeepSet * keep_set)228   TransitionVisitor(const ResourceFile& file, KeepSet* keep_set) : BaseVisitor(file, keep_set) {
229   }
230 
Visit(xml::Element * node)231   void Visit(xml::Element* node) override {
232     bool check_class =
233         node->namespace_uri.empty() && (node->name == "transition" || node->name == "pathMotion");
234     if (check_class) {
235       xml::Attribute* attr = node->FindAttribute({}, "class");
236       if (attr && util::IsJavaClassName(attr->value)) {
237         AddClass(node->line_number, attr->value,
238             "android.content.Context, android.util.AttributeSet");
239       }
240     }
241 
242     BaseVisitor::Visit(node);
243   }
244 
245  private:
246   DISALLOW_COPY_AND_ASSIGN(TransitionVisitor);
247 };
248 
249 class ManifestVisitor : public BaseVisitor {
250  public:
ManifestVisitor(const ResourceFile & file,KeepSet * keep_set,bool main_dex_only)251   ManifestVisitor(const ResourceFile& file, KeepSet* keep_set, bool main_dex_only)
252       : BaseVisitor(file, keep_set), main_dex_only_(main_dex_only) {
253   }
254 
Visit(xml::Element * node)255   void Visit(xml::Element* node) override {
256     if (node->namespace_uri.empty()) {
257       bool get_name = false;
258       if (node->name == "manifest") {
259         xml::Attribute* attr = node->FindAttribute({}, "package");
260         if (attr) {
261           package_ = attr->value;
262         }
263       } else if (node->name == "application") {
264         get_name = true;
265         xml::Attribute* attr = node->FindAttribute(xml::kSchemaAndroid, "backupAgent");
266         if (attr) {
267           Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
268           if (result) {
269             AddClass(node->line_number, result.value(), "");
270           }
271         }
272         attr = node->FindAttribute(xml::kSchemaAndroid, "appComponentFactory");
273         if (attr) {
274           Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
275           if (result) {
276             AddClass(node->line_number, result.value(), "");
277           }
278         }
279 
280         attr = node->FindAttribute(xml::kSchemaAndroid, "zygotePreloadName");
281         if (attr) {
282           Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
283           if (result) {
284             AddClass(node->line_number, result.value(), "");
285           }
286         }
287 
288         if (main_dex_only_) {
289           xml::Attribute* default_process = node->FindAttribute(xml::kSchemaAndroid, "process");
290           if (default_process) {
291             default_process_ = default_process->value;
292           }
293         }
294       } else if (node->name == "activity" || node->name == "service" ||
295                  node->name == "receiver" || node->name == "provider") {
296         get_name = true;
297 
298         if (main_dex_only_) {
299           xml::Attribute* component_process = node->FindAttribute(xml::kSchemaAndroid, "process");
300 
301           const std::string& process =
302               component_process ? component_process->value : default_process_;
303           get_name = !process.empty() && process[0] != ':';
304         }
305       } else if (node->name == "instrumentation") {
306         get_name = true;
307       }
308 
309       if (get_name) {
310         xml::Attribute* attr = node->FindAttribute(xml::kSchemaAndroid, "name");
311         get_name = attr != nullptr;
312 
313         if (get_name) {
314           Maybe<std::string> result = util::GetFullyQualifiedClassName(package_, attr->value);
315           if (result) {
316             AddClass(node->line_number, result.value(), "");
317           }
318         }
319       }
320     }
321     BaseVisitor::Visit(node);
322   }
323 
AddClass(size_t line_number,const std::string & class_name,const std::string & ctor_signature)324   virtual void AddClass(size_t line_number, const std::string& class_name,
325                         const std::string& ctor_signature) override {
326     keep_set_->AddManifestClass({file_.name, file_.source.WithLine(line_number)}, class_name);
327   }
328 
329  private:
330   DISALLOW_COPY_AND_ASSIGN(ManifestVisitor);
331 
332   std::string package_;
333   const bool main_dex_only_;
334   std::string default_process_;
335 };
336 
CollectProguardRulesForManifest(xml::XmlResource * res,KeepSet * keep_set,bool main_dex_only)337 bool CollectProguardRulesForManifest(xml::XmlResource* res, KeepSet* keep_set, bool main_dex_only) {
338   ManifestVisitor visitor(res->file, keep_set, main_dex_only);
339   if (res->root) {
340     res->root->Accept(&visitor);
341     return true;
342   }
343   return false;
344 }
345 
CollectProguardRules(IAaptContext * context_,xml::XmlResource * res,KeepSet * keep_set)346 bool CollectProguardRules(IAaptContext* context_, xml::XmlResource* res, KeepSet* keep_set) {
347   if (!res->root) {
348     return false;
349   }
350 
351   switch (res->file.name.type) {
352     case ResourceType::kLayout: {
353       LayoutVisitor visitor(res->file, keep_set);
354       res->root->Accept(&visitor);
355       break;
356     }
357 
358     case ResourceType::kXml: {
359       XmlResourceVisitor visitor(res->file, keep_set);
360       res->root->Accept(&visitor);
361       break;
362     }
363 
364     case ResourceType::kNavigation: {
365       NavigationVisitor visitor(res->file, keep_set, context_->GetCompilationPackage());
366       res->root->Accept(&visitor);
367       break;
368     }
369 
370     case ResourceType::kTransition: {
371       TransitionVisitor visitor(res->file, keep_set);
372       res->root->Accept(&visitor);
373       break;
374     }
375 
376     case ResourceType::kMenu: {
377       MenuVisitor visitor(res->file, keep_set);
378       res->root->Accept(&visitor);
379       break;
380     }
381 
382     default: {
383       BaseVisitor visitor(res->file, keep_set);
384       res->root->Accept(&visitor);
385       break;
386     }
387   }
388   return true;
389 }
390 
WriteKeepSet(const KeepSet & keep_set,OutputStream * out,bool minimal_keep)391 void WriteKeepSet(const KeepSet& keep_set, OutputStream* out, bool minimal_keep) {
392   Printer printer(out);
393   for (const auto& entry : keep_set.manifest_class_set_) {
394     for (const UsageLocation& location : entry.second) {
395       printer.Print("# Referenced at ").Println(location.source.to_string());
396     }
397     printer.Print("-keep class ").Print(entry.first).Println(" { <init>(); }");
398   }
399 
400   for (const auto& entry : keep_set.conditional_class_set_) {
401     std::set<UsageLocation> locations;
402     bool can_be_conditional = false;
403     if (keep_set.conditional_keep_rules_) {
404       can_be_conditional = true;
405       for (const UsageLocation& location : entry.second) {
406         can_be_conditional &= CollectLocations(location, keep_set, &locations);
407       }
408     }
409 
410     if (can_be_conditional) {
411       for (const UsageLocation& location : locations) {
412         printer.Print("# Referenced at ").Println(location.source.to_string());
413         printer.Print("-if class **.R$layout { int ")
414             .Print(JavaClassGenerator::TransformToFieldName(location.name.entry))
415             .Println("; }");
416 
417         printer.Print("-keep class ").Print(entry.first.name).Print(" { <init>(");
418         printer.Print((minimal_keep) ? entry.first.signature : "...");
419         printer.Println("); }");
420       }
421     } else {
422       for (const UsageLocation& location : entry.second) {
423         printer.Print("# Referenced at ").Println(location.source.to_string());
424       }
425 
426       printer.Print("-keep class ").Print(entry.first.name).Print(" { <init>(");
427       printer.Print((minimal_keep) ? entry.first.signature : "...");
428       printer.Println("); }");
429     }
430     printer.Println();
431   }
432 
433   for (const auto& entry : keep_set.method_set_) {
434     for (const UsageLocation& location : entry.second) {
435       printer.Print("# Referenced at ").Println(location.source.to_string());
436     }
437     printer.Print("-keepclassmembers class * { *** ").Print(entry.first.name)
438         .Print("(").Print(entry.first.signature).Println("); }");
439     printer.Println();
440   }
441 }
442 
CollectLocations(const UsageLocation & location,const KeepSet & keep_set,std::set<UsageLocation> * locations)443 bool CollectLocations(const UsageLocation& location, const KeepSet& keep_set,
444                       std::set<UsageLocation>* locations) {
445   locations->insert(location);
446 
447   // TODO: allow for more reference types if we can determine its safe.
448   if (location.name.type != ResourceType::kLayout) {
449     return false;
450   }
451 
452   for (const auto& entry : keep_set.reference_set_) {
453     if (entry.first == location.name) {
454       for (auto& refLocation : entry.second) {
455         // Don't get stuck in loops
456         if (locations->find(refLocation) != locations->end()) {
457           return false;
458         }
459         if (!CollectLocations(refLocation, keep_set, locations)) {
460           return false;
461         }
462       }
463     }
464   }
465 
466   return true;
467 }
468 
469 class ReferenceVisitor : public ValueVisitor {
470  public:
471   using ValueVisitor::Visit;
472 
ReferenceVisitor(aapt::IAaptContext * context,ResourceName from,KeepSet * keep_set)473   ReferenceVisitor(aapt::IAaptContext* context, ResourceName from, KeepSet* keep_set)
474       : context_(context), from_(from), keep_set_(keep_set) {
475   }
476 
Visit(Reference * reference)477   void Visit(Reference* reference) override {
478     if (reference->name) {
479       ResourceName reference_name = reference->name.value();
480       if (reference_name.package.empty()) {
481         reference_name = ResourceName(context_->GetCompilationPackage(), reference_name.type,
482                                       reference_name.entry);
483       }
484       keep_set_->AddReference({from_, reference->GetSource()}, reference_name);
485     }
486   }
487 
488  private:
489   aapt::IAaptContext* context_;
490   ResourceName from_;
491   KeepSet* keep_set_;
492 };
493 
CollectResourceReferences(aapt::IAaptContext * context,ResourceTable * table,KeepSet * keep_set)494 bool CollectResourceReferences(aapt::IAaptContext* context, ResourceTable* table,
495                                KeepSet* keep_set) {
496   for (auto& pkg : table->packages) {
497     for (auto& type : pkg->types) {
498       for (auto& entry : type->entries) {
499         for (auto& config_value : entry->values) {
500           ResourceName from(pkg->name, type->type, entry->name);
501           ReferenceVisitor visitor(context, from, keep_set);
502           config_value->value->Accept(&visitor);
503         }
504       }
505     }
506   }
507   return true;
508 }
509 
510 }  // namespace proguard
511 }  // namespace aapt
512