1 /*
2 * Copyright (C) 2021 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/protozero/filtering/filter_util.h"
18
19 #include <algorithm>
20 #include <deque>
21 #include <map>
22 #include <memory>
23 #include <set>
24
25 #include <google/protobuf/compiler/importer.h>
26
27 #include "perfetto/base/build_config.h"
28 #include "perfetto/ext/base/file_utils.h"
29 #include "perfetto/ext/base/getopt.h"
30 #include "perfetto/ext/base/string_utils.h"
31 #include "perfetto/protozero/proto_utils.h"
32 #include "src/protozero/filtering/filter_bytecode_generator.h"
33 #include "src/protozero/filtering/filter_bytecode_parser.h"
34
35 namespace protozero {
36
37 namespace {
38
39 class MultiFileErrorCollectorImpl
40 : public google::protobuf::compiler::MultiFileErrorCollector {
41 public:
42 ~MultiFileErrorCollectorImpl() override;
43 void AddError(const std::string&, int, int, const std::string&) override;
44 void AddWarning(const std::string&, int, int, const std::string&) override;
45 };
46
47 MultiFileErrorCollectorImpl::~MultiFileErrorCollectorImpl() = default;
48
AddError(const std::string & filename,int line,int column,const std::string & message)49 void MultiFileErrorCollectorImpl::AddError(const std::string& filename,
50 int line,
51 int column,
52 const std::string& message) {
53 PERFETTO_ELOG("Error %s %d:%d: %s", filename.c_str(), line, column,
54 message.c_str());
55 }
56
AddWarning(const std::string & filename,int line,int column,const std::string & message)57 void MultiFileErrorCollectorImpl::AddWarning(const std::string& filename,
58 int line,
59 int column,
60 const std::string& message) {
61 PERFETTO_ELOG("Warning %s %d:%d: %s", filename.c_str(), line, column,
62 message.c_str());
63 }
64
65 } // namespace
66
67 FilterUtil::FilterUtil() = default;
68 FilterUtil::~FilterUtil() = default;
69
LoadMessageDefinition(const std::string & proto_file,const std::string & root_message,const std::string & proto_dir_path,const std::set<std::string> & passthrough_fields)70 bool FilterUtil::LoadMessageDefinition(
71 const std::string& proto_file,
72 const std::string& root_message,
73 const std::string& proto_dir_path,
74 const std::set<std::string>& passthrough_fields) {
75 passthrough_fields_ = passthrough_fields;
76 passthrough_fields_seen_.clear();
77 // The protobuf compiler doesn't like backslashes and prints an error like:
78 // Error C:\it7mjanpw3\perfetto-a16500 -1:0: Backslashes, consecutive slashes,
79 // ".", or ".." are not allowed in the virtual path.
80 // Given that C:\foo\bar is a legit path on windows, fix it at this level
81 // because the problem is really the protobuf compiler being too picky.
82 static auto normalize_for_win = [](const std::string& path) {
83 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
84 return perfetto::base::ReplaceAll(path, "\\", "/");
85 #else
86 return path;
87 #endif
88 };
89
90 google::protobuf::compiler::DiskSourceTree dst;
91 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
92 // If the path is absolute, maps "C:/" -> "C:/" (without hardcoding 'C').
93 if (proto_file.size() > 3 && proto_file[1] == ':') {
94 char win_drive[4]{proto_file[0], ':', '/', '\0'};
95 dst.MapPath(win_drive, win_drive);
96 }
97 #endif
98 dst.MapPath("/", "/"); // We might still need this on Win under cygwin.
99 dst.MapPath("", normalize_for_win(proto_dir_path));
100 MultiFileErrorCollectorImpl mfe;
101 google::protobuf::compiler::Importer importer(&dst, &mfe);
102 const google::protobuf::FileDescriptor* root_file =
103 importer.Import(normalize_for_win(proto_file));
104 const google::protobuf::Descriptor* root_msg = nullptr;
105 if (!root_message.empty()) {
106 root_msg = importer.pool()->FindMessageTypeByName(root_message);
107 } else if (root_file->message_type_count() > 0) {
108 // The user didn't specfy the root type. Pick the first type in the file,
109 // most times it's the right guess.
110 root_msg = root_file->message_type(0);
111 if (root_msg)
112 PERFETTO_LOG(
113 "The guessed root message name is \"%s\". Pass -r com.MyName to "
114 "override",
115 root_msg->full_name().c_str());
116 }
117
118 if (!root_msg) {
119 PERFETTO_ELOG("Could not find the root message \"%s\" in %s",
120 root_message.c_str(), proto_file.c_str());
121 return false;
122 }
123
124 // |descriptors_by_full_name| is passed by argument rather than being a member
125 // field so that we don't risk leaving it out of sync (and depending on it in
126 // future without realizing) when performing the Dedupe() pass.
127 DescriptorsByNameMap descriptors_by_full_name;
128 ParseProtoDescriptor(root_msg, &descriptors_by_full_name);
129
130 // If the user specified a set of fields to pass through, print an error and
131 // fail if any of the passed fields have not been seen while recursing in the
132 // schema. This is to avoid typos or naming changes to be silently ignored.
133 std::vector<std::string> unused_passthrough;
134 std::set_difference(passthrough_fields_.begin(), passthrough_fields_.end(),
135 passthrough_fields_seen_.begin(),
136 passthrough_fields_seen_.end(),
137 std::back_inserter(unused_passthrough));
138 for (const std::string& message_and_field : unused_passthrough) {
139 PERFETTO_ELOG("Field not found %s", message_and_field.c_str());
140 }
141 if (!unused_passthrough.empty()) {
142 PERFETTO_ELOG("Syntax: perfetto.protos.MessageName:field_name");
143 return false;
144 }
145 return true;
146 }
147
148 // Generates a Message object for the given libprotobuf message descriptor.
149 // Recurses as needed into nested fields.
ParseProtoDescriptor(const google::protobuf::Descriptor * proto,DescriptorsByNameMap * descriptors_by_full_name)150 FilterUtil::Message* FilterUtil::ParseProtoDescriptor(
151 const google::protobuf::Descriptor* proto,
152 DescriptorsByNameMap* descriptors_by_full_name) {
153 auto descr_it = descriptors_by_full_name->find(proto->full_name());
154 if (descr_it != descriptors_by_full_name->end())
155 return descr_it->second;
156
157 descriptors_.emplace_back();
158 Message* msg = &descriptors_.back();
159 msg->full_name = proto->full_name();
160 (*descriptors_by_full_name)[msg->full_name] = msg;
161 for (int i = 0; i < proto->field_count(); ++i) {
162 const auto* proto_field = proto->field(i);
163 const uint32_t field_id = static_cast<uint32_t>(proto_field->number());
164 PERFETTO_CHECK(msg->fields.count(field_id) == 0);
165 auto& field = msg->fields[field_id];
166 field.name = proto_field->name();
167 field.type = proto_field->type_name();
168
169 std::string message_and_field = msg->full_name + ":" + field.name;
170 bool passthrough = false;
171 if (passthrough_fields_.count(message_and_field)) {
172 field.type = "bytes";
173 passthrough = true;
174 passthrough_fields_seen_.insert(message_and_field);
175 }
176 if (proto_field->message_type() && !passthrough) {
177 msg->has_nested_fields = true;
178 // Recurse.
179 field.nested_type = ParseProtoDescriptor(proto_field->message_type(),
180 descriptors_by_full_name);
181 }
182 }
183 return msg;
184 }
185
Dedupe()186 void FilterUtil::Dedupe() {
187 std::map<std::string /*identity*/, Message*> index;
188
189 std::map<Message*, Message*> dupe_graph; // K,V: K shall be duped against V.
190
191 // As a first pass, generate an |identity| string for each leaf message. The
192 // identity is simply the comma-separated stringification of its field ids.
193 // If another message with the same identity exists, add an edge to the graph.
194 const size_t initial_count = descriptors_.size();
195 size_t field_count = 0;
196 for (auto& descr : descriptors_) {
197 if (descr.has_nested_fields)
198 continue; // Dedupe only leaf messages without nested fields.
199 std::string identity;
200 for (const auto& id_and_field : descr.fields)
201 identity.append(std::to_string(id_and_field.first) + ",");
202 auto it_and_inserted = index.emplace(identity, &descr);
203 if (!it_and_inserted.second) {
204 // insertion failed, a dupe exists already.
205 Message* dupe_against = it_and_inserted.first->second;
206 dupe_graph.emplace(&descr, dupe_against);
207 }
208 }
209
210 // Now apply de-duplications by re-directing the nested_type pointer to the
211 // equivalent descriptors that have the same set of allowed field ids.
212 std::set<Message*> referenced_descriptors;
213 referenced_descriptors.emplace(&descriptors_.front()); // The root.
214 for (auto& descr : descriptors_) {
215 for (auto& id_and_field : descr.fields) {
216 Message* target = id_and_field.second.nested_type;
217 if (!target)
218 continue; // Only try to dedupe nested types.
219 auto it = dupe_graph.find(target);
220 if (it == dupe_graph.end()) {
221 referenced_descriptors.emplace(target);
222 continue;
223 }
224 ++field_count;
225 // Replace with the dupe.
226 id_and_field.second.nested_type = it->second;
227 } // for (nested_fields).
228 } // for (descriptors_).
229
230 // Remove unreferenced descriptors. We should much rather crash in the case of
231 // a logic bug rathern than trying to use them but don't emit them.
232 size_t removed_count = 0;
233 for (auto it = descriptors_.begin(); it != descriptors_.end();) {
234 if (referenced_descriptors.count(&*it)) {
235 ++it;
236 } else {
237 ++removed_count;
238 it = descriptors_.erase(it);
239 }
240 }
241 PERFETTO_LOG(
242 "Deduplication removed %zu duped descriptors out of %zu descriptors from "
243 "%zu fields",
244 removed_count, initial_count, field_count);
245 }
246
247 // Prints the list of messages and fields in a diff-friendly text format.
PrintAsText(std::optional<std::string> filter_bytecode)248 void FilterUtil::PrintAsText(std::optional<std::string> filter_bytecode) {
249 using perfetto::base::StripPrefix;
250 const std::string& root_name = descriptors_.front().full_name;
251 std::string root_prefix = root_name.substr(0, root_name.rfind('.'));
252 if (!root_prefix.empty())
253 root_prefix.append(".");
254
255 FilterBytecodeParser parser;
256 if (filter_bytecode) {
257 PERFETTO_CHECK(
258 parser.Load(filter_bytecode->data(), filter_bytecode->size()));
259 }
260
261 // <Filter msg_index, Message>
262 std::deque<std::pair<uint32_t, const Message*>> queue;
263 std::set<const Message*> seen_msgs{&descriptors_.front()};
264 queue.emplace_back(0u, &descriptors_.front());
265
266 while (!queue.empty()) {
267 auto index_and_descr = queue.front();
268 queue.pop_front();
269 uint32_t msg_index = index_and_descr.first;
270 const auto& descr = *index_and_descr.second;
271
272 for (const auto& id_and_field : descr.fields) {
273 const uint32_t field_id = id_and_field.first;
274 const auto& field = id_and_field.second;
275
276 FilterBytecodeParser::QueryResult result{};
277 if (filter_bytecode) {
278 result = parser.Query(msg_index, field_id);
279 if (!result.allowed)
280 continue;
281 }
282
283 const Message* nested_type = id_and_field.second.nested_type;
284 bool passthrough = false;
285 if (nested_type) {
286 // result.simple_field might be true if the generated bytecode is
287 // passing through a whole submessage without recursing.
288 passthrough = result.simple_field();
289 if (seen_msgs.find(nested_type) == seen_msgs.end()) {
290 seen_msgs.insert(nested_type);
291 queue.emplace_back(result.nested_msg_index, nested_type);
292 }
293 } else { // simple field
294 PERFETTO_CHECK(result.simple_field() || !filter_bytecode);
295 }
296
297 auto stripped_name = StripPrefix(descr.full_name, root_prefix);
298 std::string stripped_nested =
299 nested_type ? " " + StripPrefix(nested_type->full_name, root_prefix)
300 : "";
301 if (passthrough)
302 stripped_nested += " # PASSTHROUGH";
303 fprintf(print_stream_, "%-60s %3u %-8s %-32s%s\n", stripped_name.c_str(),
304 field_id, field.type.c_str(), field.name.c_str(),
305 stripped_nested.c_str());
306 }
307 }
308 }
309
GenerateFilterBytecode()310 std::string FilterUtil::GenerateFilterBytecode() {
311 protozero::FilterBytecodeGenerator bytecode_gen;
312
313 // Assign indexes to descriptors, simply by counting them in order;
314 std::map<Message*, uint32_t> descr_to_idx;
315 for (auto& descr : descriptors_)
316 descr_to_idx[&descr] = static_cast<uint32_t>(descr_to_idx.size());
317
318 for (auto& descr : descriptors_) {
319 for (auto it = descr.fields.begin(); it != descr.fields.end();) {
320 uint32_t field_id = it->first;
321 const Message::Field& field = it->second;
322 if (field.nested_type) {
323 // Append the index of the target submessage.
324 PERFETTO_CHECK(descr_to_idx.count(field.nested_type));
325 uint32_t nested_msg_index = descr_to_idx[field.nested_type];
326 bytecode_gen.AddNestedField(field_id, nested_msg_index);
327 ++it;
328 continue;
329 }
330 // Simple field. Lookahead to see if we have a range of contiguous simple
331 // fields.
332 for (uint32_t range_len = 1;; ++range_len) {
333 ++it;
334 if (it != descr.fields.end() && it->first == field_id + range_len &&
335 it->second.is_simple()) {
336 continue;
337 }
338 // At this point it points to either the end() of the vector or a
339 // non-contiguous or non-simple field (which will be picked up by the
340 // next iteration).
341 if (range_len == 1) {
342 bytecode_gen.AddSimpleField(field_id);
343 } else {
344 bytecode_gen.AddSimpleFieldRange(field_id, range_len);
345 }
346 break;
347 } // for (range_len)
348 } // for (descr.fields)
349 bytecode_gen.EndMessage();
350 } // for (descriptors)
351 return bytecode_gen.Serialize();
352 }
353
LookupField(const std::string & varint_encoded_path)354 std::string FilterUtil::LookupField(const std::string& varint_encoded_path) {
355 const uint8_t* ptr =
356 reinterpret_cast<const uint8_t*>(varint_encoded_path.data());
357 const uint8_t* const end = ptr + varint_encoded_path.size();
358
359 std::vector<uint32_t> fields;
360 while (ptr < end) {
361 uint64_t varint;
362 const uint8_t* next = proto_utils::ParseVarInt(ptr, end, &varint);
363 PERFETTO_CHECK(next != ptr);
364 fields.emplace_back(static_cast<uint32_t>(varint));
365 ptr = next;
366 }
367 return LookupField(fields.data(), fields.size());
368 }
369
LookupField(const uint32_t * field_ids,size_t num_fields)370 std::string FilterUtil::LookupField(const uint32_t* field_ids,
371 size_t num_fields) {
372 const Message* msg = descriptors_.empty() ? nullptr : &descriptors_.front();
373 std::string res;
374 for (size_t i = 0; i < num_fields; ++i) {
375 const uint32_t field_id = field_ids[i];
376 const Message::Field* field = nullptr;
377 if (msg) {
378 auto it = msg->fields.find(field_id);
379 field = it == msg->fields.end() ? nullptr : &it->second;
380 }
381 res.append(".");
382 if (field) {
383 res.append(field->name);
384 msg = field->nested_type;
385 } else {
386 res.append(std::to_string(field_id));
387 }
388 }
389 return res;
390 }
391
392 } // namespace protozero
393