• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 "src/profiling/deobfuscator.h"
18 
19 #include "perfetto/base/status.h"
20 #include "perfetto/ext/base/file_utils.h"
21 #include "perfetto/ext/base/scoped_file.h"
22 #include "perfetto/ext/base/string_splitter.h"
23 
24 #include "perfetto/ext/base/optional.h"
25 #include "perfetto/protozero/scattered_heap_buffer.h"
26 #include "protos/perfetto/trace/profiling/deobfuscation.pbzero.h"
27 #include "protos/perfetto/trace/trace.pbzero.h"
28 #include "protos/perfetto/trace/trace_packet.pbzero.h"
29 
30 namespace perfetto {
31 namespace profiling {
32 namespace {
33 
34 struct ProguardClass {
35   std::string obfuscated_name;
36   std::string deobfuscated_name;
37 };
38 
ParseClass(std::string line)39 base::Optional<ProguardClass> ParseClass(std::string line) {
40   base::StringSplitter ss(std::move(line), ' ');
41 
42   if (!ss.Next()) {
43     PERFETTO_ELOG("Missing deobfuscated name.");
44     return base::nullopt;
45   }
46   std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
47 
48   if (!ss.Next() || ss.cur_token_size() != 2 ||
49       strncmp("->", ss.cur_token(), 2) != 0) {
50     PERFETTO_ELOG("Missing ->");
51     return base::nullopt;
52   }
53 
54   if (!ss.Next()) {
55     PERFETTO_ELOG("Missing obfuscated name.");
56     return base::nullopt;
57   }
58   std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
59   if (obfuscated_name.empty()) {
60     PERFETTO_ELOG("Empty obfuscated name.");
61     return base::nullopt;
62   }
63   if (obfuscated_name.back() != ':') {
64     PERFETTO_ELOG("Expected colon.");
65     return base::nullopt;
66   }
67 
68   obfuscated_name.resize(obfuscated_name.size() - 1);
69   if (ss.Next()) {
70     PERFETTO_ELOG("Unexpected data.");
71     return base::nullopt;
72   }
73   return ProguardClass{std::move(obfuscated_name),
74                        std::move(deobfuscated_name)};
75 }
76 
77 enum class ProguardMemberType {
78   kField,
79   kMethod,
80 };
81 
82 struct ProguardMember {
83   ProguardMemberType type;
84   std::string obfuscated_name;
85   std::string deobfuscated_name;
86 };
87 
ParseMember(std::string line)88 base::Optional<ProguardMember> ParseMember(std::string line) {
89   base::StringSplitter ss(std::move(line), ' ');
90 
91   if (!ss.Next()) {
92     PERFETTO_ELOG("Missing type name.");
93     return base::nullopt;
94   }
95   std::string type_name(ss.cur_token(), ss.cur_token_size());
96 
97   if (!ss.Next()) {
98     PERFETTO_ELOG("Missing deobfuscated name.");
99     return base::nullopt;
100   }
101   std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());
102 
103   if (!ss.Next() || ss.cur_token_size() != 2 ||
104       strncmp("->", ss.cur_token(), 2) != 0) {
105     PERFETTO_ELOG("Missing ->");
106     return base::nullopt;
107   }
108 
109   if (!ss.Next()) {
110     PERFETTO_ELOG("Missing obfuscated name.");
111     return base::nullopt;
112   }
113   std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
114 
115   if (ss.Next()) {
116     PERFETTO_ELOG("Unexpected data.");
117     return base::nullopt;
118   }
119 
120   ProguardMemberType member_type;
121   auto paren_idx = deobfuscated_name.find('(');
122   if (paren_idx != std::string::npos) {
123     member_type = ProguardMemberType::kMethod;
124     deobfuscated_name = deobfuscated_name.substr(0, paren_idx);
125     auto colon_idx = type_name.find(':');
126     if (colon_idx != std::string::npos) {
127       type_name = type_name.substr(colon_idx + 1);
128     }
129   } else {
130     member_type = ProguardMemberType::kField;
131   }
132   return ProguardMember{member_type, std::move(obfuscated_name),
133                         std::move(deobfuscated_name)};
134 }
135 
FlattenMethods(const std::vector<std::string> & v)136 std::string FlattenMethods(const std::vector<std::string>& v) {
137   if (v.size() == 1) {
138     return v[0];
139   }
140   return "[ambiguous]";
141 }
142 
143 }  // namespace
144 
FlattenClasses(const std::map<std::string,std::vector<std::string>> & m)145 std::string FlattenClasses(
146     const std::map<std::string, std::vector<std::string>>& m) {
147   std::string result;
148   bool first = true;
149   for (const auto& p : m) {
150     if (!first) {
151       result += " | ";
152     }
153     result += p.first + "." + FlattenMethods(p.second);
154     first = false;
155   }
156   return result;
157 }
158 
159 // See https://www.guardsquare.com/en/products/proguard/manual/retrace for the
160 // file format we are parsing.
AddLine(std::string line)161 base::Status ProguardParser::AddLine(std::string line) {
162   if (line.length() == 0 || line[0] == '#')
163     return base::Status();
164   bool is_member = line[0] == ' ';
165   if (is_member && !current_class_) {
166     return base::Status(
167         "Failed to parse proguard map. Saw member before class.");
168   }
169   if (!is_member) {
170     auto opt_cls = ParseClass(std::move(line));
171     if (!opt_cls)
172       return base::Status("Class not found.");
173     auto p = mapping_.emplace(std::move(opt_cls->obfuscated_name),
174                               std::move(opt_cls->deobfuscated_name));
175     if (!p.second) {
176       return base::Status("Duplicate class.");
177     }
178     current_class_ = &p.first->second;
179   } else {
180     auto opt_member = ParseMember(std::move(line));
181     if (!opt_member)
182       return base::Status("Failed to parse member.");
183     switch (opt_member->type) {
184       case (ProguardMemberType::kField): {
185         if (!current_class_->AddField(opt_member->obfuscated_name,
186                                       opt_member->deobfuscated_name)) {
187           return base::Status(std::string("Member redefinition: ") +
188                               current_class_->deobfuscated_name().c_str() +
189                               "." + opt_member->deobfuscated_name.c_str() +
190                               " Proguard map invalid");
191         }
192         break;
193       }
194       case (ProguardMemberType::kMethod): {
195         current_class_->AddMethod(opt_member->obfuscated_name,
196                                   opt_member->deobfuscated_name);
197         break;
198       }
199     }
200   }
201   return base::Status();
202 }
203 
AddLines(std::string contents)204 bool ProguardParser::AddLines(std::string contents) {
205   size_t lineno = 1;
206   for (base::StringSplitter lines(std::move(contents), '\n'); lines.Next();) {
207     auto status = AddLine(lines.cur_token());
208     if (!status.ok()) {
209       PERFETTO_ELOG("Failed to parse proguard map (line %zu): %s", lineno,
210                     status.c_message());
211       return false;
212     }
213     lineno++;
214   }
215   return true;
216 }
217 
MakeDeobfuscationPackets(const std::string & package_name,const std::map<std::string,profiling::ObfuscatedClass> & mapping,std::function<void (const std::string &)> callback)218 void MakeDeobfuscationPackets(
219     const std::string& package_name,
220     const std::map<std::string, profiling::ObfuscatedClass>& mapping,
221     std::function<void(const std::string&)> callback) {
222   protozero::HeapBuffered<perfetto::protos::pbzero::Trace> trace;
223   auto* packet = trace->add_packet();
224   // TODO(fmayer): Add handling for package name and version code here so we
225   // can support multiple dumps in the same trace.
226   auto* proto_mapping = packet->set_deobfuscation_mapping();
227   proto_mapping->set_package_name(package_name);
228   for (const auto& p : mapping) {
229     const std::string& obfuscated_class_name = p.first;
230     const profiling::ObfuscatedClass& cls = p.second;
231 
232     auto* proto_class = proto_mapping->add_obfuscated_classes();
233     proto_class->set_obfuscated_name(obfuscated_class_name);
234     proto_class->set_deobfuscated_name(cls.deobfuscated_name());
235     for (const auto& field_p : cls.deobfuscated_fields()) {
236       const std::string& obfuscated_field_name = field_p.first;
237       const std::string& deobfuscated_field_name = field_p.second;
238       auto* proto_member = proto_class->add_obfuscated_members();
239       proto_member->set_obfuscated_name(obfuscated_field_name);
240       proto_member->set_deobfuscated_name(deobfuscated_field_name);
241     }
242     for (const auto& field_p : cls.deobfuscated_methods()) {
243       const std::string& obfuscated_method_name = field_p.first;
244       const std::string& deobfuscated_method_name = field_p.second;
245       auto* proto_member = proto_class->add_obfuscated_methods();
246       proto_member->set_obfuscated_name(obfuscated_method_name);
247       proto_member->set_deobfuscated_name(deobfuscated_method_name);
248     }
249   }
250   callback(trace.SerializeAsString());
251 }
252 
ReadProguardMapsToDeobfuscationPackets(const std::vector<ProguardMap> & maps,std::function<void (std::string)> fn)253 bool ReadProguardMapsToDeobfuscationPackets(
254     const std::vector<ProguardMap>& maps,
255     std::function<void(std::string)> fn) {
256   for (const ProguardMap& map : maps) {
257     const char* filename = map.filename.c_str();
258     base::ScopedFstream f(fopen(filename, "re"));
259     if (!f) {
260       PERFETTO_ELOG("Failed to open %s", filename);
261       return false;
262     }
263     profiling::ProguardParser parser;
264     std::string contents;
265     PERFETTO_CHECK(base::ReadFileStream(*f, &contents));
266     if (!parser.AddLines(std::move(contents))) {
267       PERFETTO_ELOG("Failed to parse %s", filename);
268       return false;
269     }
270     std::map<std::string, profiling::ObfuscatedClass> obfuscation_map =
271         parser.ConsumeMapping();
272 
273     // TODO(fmayer): right now, we don't use the profile we are given. We can
274     // filter the output to only contain the classes actually seen in the
275     // profile.
276     MakeDeobfuscationPackets(map.package, obfuscation_map, fn);
277   }
278   return true;
279 }
280 
GetPerfettoProguardMapPath()281 std::vector<ProguardMap> GetPerfettoProguardMapPath() {
282   const char* env = getenv("PERFETTO_PROGUARD_MAP");
283   if (env == nullptr)
284     return {};
285   std::vector<ProguardMap> res;
286   for (base::StringSplitter sp(std::string(env), ':'); sp.Next();) {
287     std::string token(sp.cur_token(), sp.cur_token_size());
288     size_t eq = token.find('=');
289     if (eq == std::string::npos) {
290       PERFETTO_ELOG(
291           "Invalid PERFETTO_PROGUARD_MAP. "
292           "Expected format packagename=filename[:packagename=filename...], "
293           "e.g. com.example.package1=foo.txt:com.example.package2=bar.txt.");
294       return {};
295     }
296     res.emplace_back(ProguardMap{token.substr(0, eq), token.substr(eq + 1)});
297   }
298   return res;  // for Wreturn-std-move-in-c++11.
299 }
300 
301 }  // namespace profiling
302 }  // namespace perfetto
303