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 <google/protobuf/compiler/importer.h>
18#include <google/protobuf/dynamic_message.h>
19#include <google/protobuf/io/printer.h>
20#include <google/protobuf/io/zero_copy_stream_impl.h>
21#include <google/protobuf/stubs/strutil.h>
22#include <google/protobuf/util/field_comparator.h>
23#include <google/protobuf/util/message_differencer.h>
24
25#include <stdio.h>
26
27#include <fstream>
28#include <iostream>
29
30#include "perfetto/base/logging.h"
31
32using namespace google::protobuf;
33using namespace google::protobuf::compiler;
34using namespace google::protobuf::io;
35
36namespace {
37
38static const char kHeader[] = R"(/*
39 * Copyright (C) 2017 The Android Open Source Project
40 *
41 * Licensed under the Apache License, Version 2.0 (the "License");
42 * you may not use this file except in compliance with the License.
43 * You may obtain a copy of the License at
44 *
45 *      http://www.apache.org/licenses/LICENSE-2.0
46 *
47 * Unless required by applicable law or agreed to in writing, software
48 * distributed under the License is distributed on an "AS IS" BASIS,
49 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
50 * See the License for the specific language governing permissions and
51 * limitations under the License.
52 */
53
54/*******************************************************************************
55 * AUTOGENERATED - DO NOT EDIT
56 *******************************************************************************
57 * This file has been generated from the protobuf message
58 * $p$
59 * by
60 * $f$.
61 * If you need to make changes here, change the .proto file and then run
62 * ./tools/gen_tracing_cpp_headers_from_protos.py
63 */
64
65)";
66
67class ErrorPrinter : public MultiFileErrorCollector {
68  virtual void AddError(const string& filename,
69                        int line,
70                        int col,
71                        const string& msg) {
72    PERFETTO_ELOG("%s %d:%d: %s", filename.c_str(), line, col, msg.c_str());
73  }
74  virtual void AddWarning(const string& filename,
75                          int line,
76                          int col,
77                          const string& msg) {
78    PERFETTO_ILOG("%s %d:%d: %s", filename.c_str(), line, col, msg.c_str());
79  }
80};
81
82std::string GetProtoHeader(const FileDescriptor* proto_file) {
83  return StringReplace(proto_file->name(), ".proto", ".pb.h", false);
84}
85
86std::string GetFwdDeclType(const Descriptor* msg, bool with_namespace = false) {
87  std::string full_type;
88  full_type.append(msg->name());
89  for (const Descriptor* par = msg->containing_type(); par;
90       par = par->containing_type()) {
91    full_type.insert(0, par->name() + "_");
92  }
93  if (with_namespace) {
94    std::vector<std::string> namespaces = Split(msg->file()->package(), ".");
95    for (auto it = namespaces.rbegin(); it != namespaces.rend(); it++) {
96      full_type.insert(0, *it + "::");
97    }
98  }
99  return full_type;
100}
101
102void GenFwdDecl(const Descriptor* msg, Printer* p) {
103  p->Print("class $n$;", "n", GetFwdDeclType(msg));
104
105  // Recurse into subtypes
106  for (int i = 0; i < msg->field_count(); i++) {
107    const FieldDescriptor* field = msg->field(i);
108    if (field->type() == FieldDescriptor::TYPE_MESSAGE)
109      GenFwdDecl(field->message_type(), p);
110  }
111}
112
113}  // namespace
114
115class ProtoToCpp {
116 public:
117  ProtoToCpp(const std::string& header_dir,
118             const std::string& cpp_dir,
119             const std::string& include_path);
120
121  static std::string GetCppType(const FieldDescriptor* field, bool constref);
122
123  void Convert(const std::string& src_proto);
124  std::string GetHeaderPath(const FileDescriptor*);
125  std::string GetCppPath(const FileDescriptor*);
126  std::string GetIncludePath(const FileDescriptor*);
127  void GenHeader(const Descriptor*, Printer*);
128  void GenCpp(const Descriptor*, Printer*, std::string prefix);
129
130 private:
131  std::string header_dir_;
132  std::string cpp_dir_;
133  std::string include_path_;
134  DiskSourceTree dst_;
135  ErrorPrinter error_printer_;
136  Importer importer_;
137};
138
139ProtoToCpp::ProtoToCpp(const std::string& header_dir,
140                       const std::string& cpp_dir,
141                       const std::string& include_path)
142    : header_dir_(header_dir),
143      cpp_dir_(cpp_dir),
144      include_path_(include_path),
145      importer_(&dst_, &error_printer_) {
146  dst_.MapPath("", "protos");
147}
148
149std::string ProtoToCpp::GetHeaderPath(const FileDescriptor* proto_file) {
150  std::string basename = Split(proto_file->name(), "/").back();
151  return header_dir_ + "/" + StringReplace(basename, ".proto", ".h", false);
152}
153
154std::string ProtoToCpp::GetCppPath(const FileDescriptor* proto_file) {
155  std::string basename = Split(proto_file->name(), "/").back();
156  return cpp_dir_ + "/" + StringReplace(basename, ".proto", ".cc", false);
157}
158
159std::string ProtoToCpp::GetIncludePath(const FileDescriptor* proto_file) {
160  std::string basename = Split(proto_file->name(), "/").back();
161  return include_path_ + "/" + StringReplace(basename, ".proto", ".h", false);
162}
163
164std::string ProtoToCpp::GetCppType(const FieldDescriptor* field,
165                                   bool constref) {
166  switch (field->type()) {
167    case FieldDescriptor::TYPE_DOUBLE:
168      return "double";
169    case FieldDescriptor::TYPE_FLOAT:
170      return "float";
171    case FieldDescriptor::TYPE_FIXED32:
172    case FieldDescriptor::TYPE_UINT32:
173      return "uint32_t";
174    case FieldDescriptor::TYPE_SFIXED32:
175    case FieldDescriptor::TYPE_INT32:
176    case FieldDescriptor::TYPE_SINT32:
177      return "int32_t";
178    case FieldDescriptor::TYPE_FIXED64:
179    case FieldDescriptor::TYPE_UINT64:
180      return "uint64_t";
181    case FieldDescriptor::TYPE_SFIXED64:
182    case FieldDescriptor::TYPE_SINT64:
183    case FieldDescriptor::TYPE_INT64:
184      return "int64_t";
185    case FieldDescriptor::TYPE_BOOL:
186      return "bool";
187    case FieldDescriptor::TYPE_STRING:
188    case FieldDescriptor::TYPE_BYTES:
189      return constref ? "const std::string&" : "std::string";
190    case FieldDescriptor::TYPE_MESSAGE:
191      return constref ? "const " + field->message_type()->name() + "&"
192                      : field->message_type()->name();
193    case FieldDescriptor::TYPE_ENUM:
194      return field->enum_type()->name();
195    case FieldDescriptor::TYPE_GROUP:
196      PERFETTO_FATAL("No cpp type for a group field.");
197  }
198  PERFETTO_CHECK(false);
199}
200
201void ProtoToCpp::Convert(const std::string& src_proto) {
202  const FileDescriptor* proto_file = importer_.Import(src_proto);
203  if (!proto_file) {
204    PERFETTO_ELOG("Failed to load %s", src_proto.c_str());
205    exit(1);
206  }
207
208  std::string dst_header = GetHeaderPath(proto_file);
209  std::string dst_cpp = GetCppPath(proto_file);
210
211  std::ofstream header_ostr;
212  header_ostr.open(dst_header);
213  PERFETTO_CHECK(header_ostr.is_open());
214  OstreamOutputStream header_proto_ostr(&header_ostr);
215  Printer header_printer(&header_proto_ostr, '$');
216
217  std::ofstream cpp_ostr;
218  cpp_ostr.open(dst_cpp);
219  PERFETTO_CHECK(cpp_ostr.is_open());
220  OstreamOutputStream cpp_proto_ostr(&cpp_ostr);
221  Printer cpp_printer(&cpp_proto_ostr, '$');
222
223  std::string include_guard = dst_header + "_";
224  UpperString(&include_guard);
225  StripString(&include_guard, ".-/\\", '_');
226  header_printer.Print(kHeader, "f", __FILE__, "p", src_proto);
227  header_printer.Print("#ifndef $g$\n#define $g$\n\n", "g", include_guard);
228  header_printer.Print("#include <stdint.h>\n");
229  header_printer.Print("#include <vector>\n");
230  header_printer.Print("#include <string>\n");
231  header_printer.Print("#include <type_traits>\n\n");
232  header_printer.Print("#include \"perfetto/base/export.h\"\n\n");
233
234  cpp_printer.Print(kHeader, "f", __FILE__, "p", src_proto);
235  PERFETTO_CHECK(dst_header.find("include/") == 0);
236  cpp_printer.Print("#include \"$f$\"\n", "f",
237                    dst_header.substr(strlen("include/")));
238
239  // Generate includes for translated types of dependencies.
240  for (int i = 0; i < proto_file->dependency_count(); i++) {
241    const FileDescriptor* dep = proto_file->dependency(i);
242    header_printer.Print("#include \"$f$\"\n", "f", GetIncludePath(dep));
243  }
244  header_printer.Print("\n");
245
246  cpp_printer.Print("\n#include \"$f$\"\n", "f", GetProtoHeader(proto_file));
247  for (int i = 0; i < proto_file->dependency_count(); i++) {
248    const FileDescriptor* dep = proto_file->dependency(i);
249    cpp_printer.Print("#include \"$f$\"\n", "f", GetProtoHeader(dep));
250  }
251
252  // Generate forward declarations in the header for proto types.
253  header_printer.Print("// Forward declarations for protobuf types.\n");
254  std::vector<std::string> namespaces = Split(proto_file->package(), ".");
255  for (size_t i = 0; i < namespaces.size(); i++)
256    header_printer.Print("namespace $n$ {\n", "n", namespaces[i]);
257  for (int i = 0; i < proto_file->message_type_count(); i++)
258    GenFwdDecl(proto_file->message_type(i), &header_printer);
259  for (size_t i = 0; i < namespaces.size(); i++)
260    header_printer.Print("}\n");
261
262  header_printer.Print("\nnamespace perfetto {\n");
263  cpp_printer.Print("\nnamespace perfetto {\n");
264
265  for (int i = 0; i < proto_file->message_type_count(); i++) {
266    const Descriptor* msg = proto_file->message_type(i);
267    GenHeader(msg, &header_printer);
268    GenCpp(msg, &cpp_printer, "");
269  }
270
271  cpp_printer.Print("}  // namespace perfetto\n");
272  header_printer.Print("}  // namespace perfetto\n");
273  header_printer.Print("#endif  // $g$\n", "g", include_guard);
274}
275
276void ProtoToCpp::GenHeader(const Descriptor* msg, Printer* p) {
277  PERFETTO_ILOG("GEN %s %s", msg->name().c_str(), msg->file()->name().c_str());
278  p->Print("\nclass PERFETTO_EXPORT $n$ {\n", "n", msg->name());
279  p->Print(" public:\n");
280  p->Indent();
281  // Do a first pass to generate nested types.
282  for (int i = 0; i < msg->field_count(); i++) {
283    const FieldDescriptor* field = msg->field(i);
284    if (field->has_default_value()) {
285      PERFETTO_FATAL(
286          "Error on field %s: Explicitly declared default values are not "
287          "supported",
288          field->name().c_str());
289    }
290
291    if (field->type() == FieldDescriptor::TYPE_ENUM) {
292      const EnumDescriptor* enum_desc = field->enum_type();
293      p->Print("enum $n$ {\n", "n", enum_desc->name());
294      for (int e = 0; e < enum_desc->value_count(); e++) {
295        const EnumValueDescriptor* value = enum_desc->value(e);
296        p->Print("  $n$ = $v$,\n", "n", value->name(), "v",
297                 std::to_string(value->number()));
298      }
299      p->Print("};\n");
300    } else if (field->type() == FieldDescriptor::TYPE_MESSAGE &&
301               field->message_type()->file() == msg->file()) {
302      GenHeader(field->message_type(), p);
303    }
304  }
305
306  p->Print("$n$();\n", "n", msg->name());
307  p->Print("~$n$();\n", "n", msg->name());
308  p->Print("$n$($n$&&) noexcept;\n", "n", msg->name());
309  p->Print("$n$& operator=($n$&&);\n", "n", msg->name());
310  p->Print("$n$(const $n$&);\n", "n", msg->name());
311  p->Print("$n$& operator=(const $n$&);\n", "n", msg->name());
312  p->Print("\n");
313
314  std::string proto_type = GetFwdDeclType(msg, true);
315  p->Print("// Conversion methods from/to the corresponding protobuf types.\n");
316  p->Print("void FromProto(const $p$&);\n", "n", msg->name(), "p", proto_type);
317  p->Print("void ToProto($p$*) const;\n", "p", proto_type);
318
319  // Generate accessors.
320  for (int i = 0; i < msg->field_count(); i++) {
321    const FieldDescriptor* field = msg->field(i);
322    p->Print("\n");
323    if (!field->is_repeated()) {
324      p->Print("$t$ $n$() const { return $n$_; }\n", "t",
325               GetCppType(field, true), "n", field->lowercase_name());
326      if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
327        p->Print("$t$* mutable_$n$() { return &$n$_; }\n", "t",
328                 GetCppType(field, false), "n", field->lowercase_name());
329      } else {
330        p->Print("void set_$n$($t$ value) { $n$_ = value; }\n", "t",
331                 GetCppType(field, true), "n", field->lowercase_name());
332        if (field->type() == FieldDescriptor::TYPE_BYTES) {
333          p->Print(
334              "void set_$n$(const void* p, size_t s) { "
335              "$n$_.assign(reinterpret_cast<const char*>(p), s); }\n",
336              "n", field->lowercase_name());
337        }
338      }
339    } else {  // is_repeated()
340      p->Print(
341          "int $n$_size() const { return static_cast<int>($n$_.size()); }\n",
342          "t", GetCppType(field, false), "n", field->lowercase_name());
343      p->Print("const std::vector<$t$>& $n$() const { return $n$_; }\n", "t",
344               GetCppType(field, false), "n", field->lowercase_name());
345      p->Print("$t$* add_$n$() { $n$_.emplace_back(); return &$n$_.back(); }\n",
346               "t", GetCppType(field, false), "n", field->lowercase_name());
347    }
348  }
349  p->Outdent();
350  p->Print("\n private:\n");
351  p->Indent();
352
353  // Generate fields.
354  for (int i = 0; i < msg->field_count(); i++) {
355    const FieldDescriptor* field = msg->field(i);
356    if (!field->is_repeated()) {
357      p->Print("$t$ $n$_ = {};\n", "t", GetCppType(field, false), "n",
358               field->lowercase_name());
359    } else {  // is_repeated()
360      p->Print("std::vector<$t$> $n$_;\n", "t", GetCppType(field, false), "n",
361               field->lowercase_name());
362    }
363  }
364  p->Print("\n");
365  p->Print("// Allows to preserve unknown protobuf fields for compatibility\n");
366  p->Print("// with future versions of .proto files.\n");
367  p->Print("std::string unknown_fields_;\n");
368  p->Outdent();
369  p->Print("};\n\n");
370}
371
372void ProtoToCpp::GenCpp(const Descriptor* msg, Printer* p, std::string prefix) {
373  p->Print("\n");
374  std::string full_name = prefix + msg->name();
375  p->Print("$f$::$n$() = default;\n", "f", full_name, "n", msg->name());
376  p->Print("$f$::~$n$() = default;\n", "f", full_name, "n", msg->name());
377  p->Print("$f$::$n$(const $f$&) = default;\n", "f", full_name, "n",
378           msg->name());
379  p->Print("$f$& $f$::operator=(const $f$&) = default;\n", "f", full_name, "n",
380           msg->name());
381  p->Print("$f$::$n$($f$&&) noexcept = default;\n", "f", full_name, "n",
382           msg->name());
383  p->Print("$f$& $f$::operator=($f$&&) = default;\n", "f", full_name, "n",
384           msg->name());
385
386  p->Print("\n");
387
388  std::string proto_type = GetFwdDeclType(msg, true);
389
390  // Genrate the FromProto() method definition.
391  p->Print("void $f$::FromProto(const $p$& proto) {\n", "f", full_name, "p",
392           proto_type);
393  p->Indent();
394  for (int i = 0; i < msg->field_count(); i++) {
395    p->Print("\n");
396    const FieldDescriptor* field = msg->field(i);
397    if (!field->is_repeated()) {
398      if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
399        p->Print("$n$_.FromProto(proto.$n$());\n", "n", field->name());
400      } else {
401        p->Print(
402            "static_assert(sizeof($n$_) == sizeof(proto.$n$()), \"size "
403            "mismatch\");\n",
404            "n", field->name());
405        p->Print("$n$_ = static_cast<decltype($n$_)>(proto.$n$());\n", "n",
406                 field->name());
407      }
408    } else {  // is_repeated()
409      p->Print("$n$_.clear();\n", "n", field->name());
410      p->Print("for (const auto& field : proto.$n$()) {\n", "n", field->name());
411      p->Print("  $n$_.emplace_back();\n", "n", field->name());
412      if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
413        p->Print("  $n$_.back().FromProto(field);\n", "n", field->name());
414      } else {
415        p->Print(
416            "static_assert(sizeof($n$_.back()) == sizeof(proto.$n$(0)), \"size "
417            "mismatch\");\n",
418            "n", field->name());
419        p->Print(
420            "  $n$_.back() = static_cast<decltype($n$_)::value_type>(field);\n",
421            "n", field->name());
422      }
423      p->Print("}\n");
424    }
425  }
426  p->Print("unknown_fields_ = proto.unknown_fields();\n");
427  p->Outdent();
428  p->Print("}\n\n");
429
430  // Genrate the ToProto() method definition.
431  p->Print("void $f$::ToProto($p$* proto) const {\n", "f", full_name, "p",
432           proto_type);
433  p->Indent();
434  p->Print("proto->Clear();\n");
435  for (int i = 0; i < msg->field_count(); i++) {
436    p->Print("\n");
437    const FieldDescriptor* field = msg->field(i);
438    if (!field->is_repeated()) {
439      if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
440        p->Print("$n$_.ToProto(proto->mutable_$n$());\n", "n", field->name());
441      } else {
442        p->Print(
443            "static_assert(sizeof($n$_) == sizeof(proto->$n$()), \"size "
444            "mismatch\");\n",
445            "n", field->name());
446        p->Print("proto->set_$n$(static_cast<decltype(proto->$n$())>($n$_));\n",
447                 "n", field->name());
448      }
449    } else {  // is_repeated()
450      p->Print("for (const auto& it : $n$_) {\n", "n", field->name());
451      if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
452        p->Print("  auto* entry = proto->add_$n$();\n", "n", field->name());
453        p->Print("  it.ToProto(entry);\n");
454      } else {
455        p->Print(
456            "  proto->add_$n$(static_cast<decltype(proto->$n$(0))>(it));\n",
457            "n", field->name());
458        p->Print(
459            "static_assert(sizeof(it) == sizeof(proto->$n$(0)), \"size "
460            "mismatch\");\n",
461            "n", field->name());
462      }
463      p->Print("}\n");
464    }
465  }
466  p->Print("*(proto->mutable_unknown_fields()) = unknown_fields_;\n");
467  p->Outdent();
468  p->Print("}\n\n");
469
470  // Recurse into nested types.
471  for (int i = 0; i < msg->field_count(); i++) {
472    const FieldDescriptor* field = msg->field(i);
473
474    if (field->type() == FieldDescriptor::TYPE_MESSAGE &&
475        field->message_type()->file() == msg->file()) {
476      std::string child_prefix = prefix + msg->name() + "::";
477      GenCpp(field->message_type(), p, child_prefix);
478    }
479  }
480}
481
482int main(int argc, char** argv) {
483  if (argc <= 4) {
484    PERFETTO_ELOG(
485        "Usage: %s source.proto dir/for/header dir/for/cc include/path",
486        argv[0]);
487    return 1;
488  }
489  ProtoToCpp proto_to_cpp(argv[2], argv[3], argv[4]);
490  proto_to_cpp.Convert(argv[1]);
491  return 0;
492}
493