-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.cpp
181 lines (160 loc) · 8.29 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#include "BinaryMetadataExtractor.h"
#include "FilesystemMetadataExtractor.h"
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/io/coded_stream.h>
#include <boost/filesystem/operations.hpp>
#include <fstream>
#include <iostream>
#include <unordered_map>
bool ParseFromCodedInputStreamWithDescriptorPool(google::protobuf::FileDescriptorProto& proto, google::protobuf::io::CodedInputStream* decoder)
{
decoder->SetExtensionRegistry(google::protobuf::DescriptorPool::generated_pool(), google::protobuf::MessageFactory::generated_factory());
return proto.ParseFromCodedStream(decoder) && decoder->ConsumedEntireMessage();
}
std::unordered_map<std::string, std::pair<google::protobuf::FileDescriptor const*, bool>> fileDescriptorsByName;
google::protobuf::DynamicMessageFactory* dynamicMessageFactory = new google::protobuf::DynamicMessageFactory(); // LEAKED ON PURPOSE, messages generated by this are double registered (and would be double freed)
int main(int argc, char* argv[])
{
// initialize Descriptor descriptors
google::protobuf::DescriptorProto().GetMetadata();
// first collect files
std::unique_ptr<MetadataExtractor> extractor;
if (argc > 1)
{
// parse protobuf metadata from binary
extractor = std::make_unique<BinaryMetadataExtractor>();
extractor->Parse(argv[1]);
}
else
{
extractor = std::make_unique<FilesystemMetadataExtractor>();
extractor->Parse(boost::filesystem::current_path());
}
if (extractor->GetMetadata().empty())
{
std::cout << "No .proto descriptors found" << std::endl;
return 1;
}
// its time to hack private members
google::protobuf::DescriptorPool* pool = google::protobuf::DescriptorPool::internal_generated_pool();
void* mutex_ = *reinterpret_cast<char**>(pool);
void* fallback_database_ = *(reinterpret_cast<void**>(pool) + 1);
*reinterpret_cast<void**>(pool) = nullptr; // mutex_
*(reinterpret_cast<void**>(pool) + 1) = nullptr; // fallback_database_
std::vector<std::pair<google::protobuf::FileDescriptorProto, bool>> descProtos;
std::set<std::string> parsed;
std::list<std::string> parsedSorted;
// then load everything into descriptor pool
for (size_t i = 0; i < extractor->GetMetadata().size(); ++i)
{
for (std::unique_ptr<MetadataExtractor::Metadata> const& meta : extractor->GetMetadata())
{
if (parsed.count(meta->GetId()))
continue;
std::shared_ptr<google::protobuf::io::CodedInputStream> in = meta->CreateCodedInputStream();
if (!in)
continue;
google::protobuf::FileDescriptorProto fileDescProto;
bool parseOk = false;
try
{
parseOk = ParseFromCodedInputStreamWithDescriptorPool(fileDescProto, in.get());
}
catch (...)
{
continue;
}
if (parseOk)
{
if (google::protobuf::FileDescriptor const* fileDesc = pool->BuildFile(fileDescProto))
{
if (fileDesc->name() != "google/protobuf/descriptor.proto" && fileDescriptorsByName.count(fileDesc->name()) == 0)
{
auto itr = fileDescriptorsByName.emplace(std::piecewise_construct, std::forward_as_tuple(fileDesc->name()), std::forward_as_tuple(fileDesc, false)).first;
google::protobuf::MessageFactory::InternalRegisterGeneratedFile(itr->first.c_str(), [](std::string const& name)
{
std::pair<google::protobuf::FileDescriptor const*, bool>& p = fileDescriptorsByName[name];
if (p.second)
return;
p.second = true;
google::protobuf::FileDescriptor const* desc = p.first;
for (int j = 0; j < desc->message_type_count(); ++j)
google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(desc->message_type(j), dynamicMessageFactory->GetPrototype(desc->message_type(j)));
});
}
for (int j = 0; j < fileDesc->extension_count(); ++j)
{
google::protobuf::FieldDescriptor const* extension = fileDesc->extension(j);
switch (extension->type())
{
case google::protobuf::FieldDescriptor::Type::TYPE_ENUM:
google::protobuf::internal::ExtensionSet::RegisterEnumExtension(
google::protobuf::MessageFactory::generated_factory()->GetPrototype(extension->containing_type()),
extension->number(),
extension->type(),
extension->is_repeated(),
extension->is_packed(),
[](int){ return true; });
break;
case google::protobuf::FieldDescriptor::Type::TYPE_MESSAGE:
case google::protobuf::FieldDescriptor::Type::TYPE_GROUP:
google::protobuf::internal::ExtensionSet::RegisterMessageExtension(
google::protobuf::MessageFactory::generated_factory()->GetPrototype(extension->containing_type()),
extension->number(),
extension->type(),
extension->is_repeated(),
extension->is_packed(),
google::protobuf::MessageFactory::generated_factory()->GetPrototype(extension->message_type()));
break;
default:
google::protobuf::internal::ExtensionSet::RegisterExtension(
google::protobuf::MessageFactory::generated_factory()->GetPrototype(extension->containing_type()),
extension->number(),
extension->type(),
extension->is_repeated(),
extension->is_packed());
break;
}
}
parsed.insert(meta->GetId());
if (fileDesc->name() != "google/protobuf/descriptor.proto")
parsedSorted.push_back(meta->GetId());
else
parsedSorted.push_front(meta->GetId());
}
}
}
}
// and finally rebuild all protos in a new pool with fully resolved dependencies and extensions
google::protobuf::DescriptorPool* pool2 = new google::protobuf::DescriptorPool();
for (std::string const& fileName : parsedSorted)
{
MetadataExtractor::Metadata const* meta = extractor->GetById(fileName);
if (!meta)
continue;
std::shared_ptr<google::protobuf::io::CodedInputStream> in = meta->CreateCodedInputStream();
if (!in)
continue;
google::protobuf::FileDescriptorProto fileDescProto;
if (ParseFromCodedInputStreamWithDescriptorPool(fileDescProto, in.get()))
{
fileDescProto.mutable_options()->set_optimize_for(google::protobuf::FileOptions_OptimizeMode_SPEED);
if (google::protobuf::FileDescriptor const* fileDesc = pool2->BuildFile(fileDescProto))
{
boost::filesystem::path parentPath = boost::filesystem::path(fileDesc->name()).parent_path();
if (!parentPath.empty())
boost::filesystem::create_directories(parentPath);
std::ofstream f(fileDesc->name());
f << fileDesc->DebugString() << std::endl;
f.close();
}
}
}
// unhack to free memory
*reinterpret_cast<void**>(pool) = mutex_;
*(reinterpret_cast<void**>(pool) + 1) = fallback_database_;
delete pool2;
google::protobuf::ShutdownProtobufLibrary();
return 0;
}