Debian Codegraph @

extra/protobuf/protobuf-24.4/conformance/conformance_cpp.cc

raw
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <unistd.h>
34
35 #include <memory>
36 #include <string>
37 #include <utility>
38
39 #include "google/protobuf/message.h"
40 #include "google/protobuf/text_format.h"
41 #include "google/protobuf/util/json_util.h"
42 #include "google/protobuf/util/type_resolver_util.h"
43 #include "absl/log/absl_check.h"
44 #include "absl/log/absl_log.h"
45 #include "absl/status/status.h"
46 #include "absl/status/statusor.h"
47 #include "conformance/conformance.pb.h"
48 #include "conformance/conformance.pb.h"
49 #include "google/protobuf/test_messages_proto2.pb.h"
50 #include "google/protobuf/test_messages_proto3.pb.h"
51 #include "google/protobuf/test_messages_proto3.pb.h"
52 #include "google/protobuf/util/type_resolver.h"
53 #include "google/protobuf/stubs/status_macros.h"
54
55 // Must be included last.
56 #include "google/protobuf/port_def.inc"
57
58 namespace google {
59 namespace protobuf {
60 namespace {
61 using ::conformance::ConformanceRequest;
62 using ::conformance::ConformanceResponse;
63 using ::google::protobuf::util::BinaryToJsonString;
64 using ::google::protobuf::util::JsonParseOptions;
65 using ::google::protobuf::util::JsonToBinaryString;
66 using ::google::protobuf::util::NewTypeResolverForDescriptorPool;
67 using ::google::protobuf::util::TypeResolver;
68 using ::protobuf_test_messages::proto2::TestAllTypesProto2;
69 using ::protobuf_test_messages::proto3::TestAllTypesProto3;
70
71 absl::Status ReadFd(int fd, char* buf, size_t len) {
72 while (len > 0) {
73 ssize_t bytes_read = read(fd, buf, len);
74
75 if (bytes_read == 0) {
76 return absl::DataLossError("unexpected EOF");
77 }
78
79 if (bytes_read < 0) {
80 return absl::ErrnoToStatus(errno, "error reading from test runner");
81 }
82
83 len -= bytes_read;
84 buf += bytes_read;
85 }
86 return absl::OkStatus();
87 }
88
89 absl::Status WriteFd(int fd, const void* buf, size_t len) {
90 if (static_cast<size_t>(write(fd, buf, len)) != len) {
91 return absl::ErrnoToStatus(errno, "error reading to test runner");
92 }
93 return absl::OkStatus();
94 }
95
96 class Harness {
97 public:
98 Harness() {
99 google::protobuf::LinkMessageReflection<TestAllTypesProto2>();
100 google::protobuf::LinkMessageReflection<TestAllTypesProto3>();
101
102 resolver_.reset(NewTypeResolverForDescriptorPool(
103 "type.googleapis.com", DescriptorPool::generated_pool()));
104 type_url_ = absl::StrCat("type.googleapis.com/",
105 TestAllTypesProto3::GetDescriptor()->full_name());
106 }
107
108 absl::StatusOr<ConformanceResponse> RunTest(
109 const ConformanceRequest& request);
110
111 // Returns Ok(true) if we're done processing requests.
112 absl::StatusOr<bool> ServeConformanceRequest();
113
114 private:
115 bool verbose_ = false;
116 std::unique_ptr<TypeResolver> resolver_;
117 std::string type_url_;
118 };
119
120 absl::StatusOr<ConformanceResponse> Harness::RunTest(
121 const ConformanceRequest& request) {
122 const Descriptor* descriptor =
123 DescriptorPool::generated_pool()->FindMessageTypeByName(
124 request.message_type());
125 if (descriptor == nullptr) {
126 return absl::NotFoundError(
127 absl::StrCat("No such message type: ", request.message_type()));
128 }
129
130 std::unique_ptr<Message> test_message(
131 MessageFactory::generated_factory()->GetPrototype(descriptor)->New());
132 ConformanceResponse response;
133
134 switch (request.payload_case()) {
135 case ConformanceRequest::kProtobufPayload: {
136 if (!test_message->ParseFromString(request.protobuf_payload())) {
137 response.set_parse_error("parse error (no more details available)");
138 return response;
139 }
140 break;
141 }
142
143 case ConformanceRequest::kJsonPayload: {
144 JsonParseOptions options;
145 options.ignore_unknown_fields =
146 (request.test_category() ==
147 conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST);
148
149 std::string proto_binary;
150 absl::Status status =
151 JsonToBinaryString(resolver_.get(), type_url_, request.json_payload(),
152 &proto_binary, options);
153 if (!status.ok()) {
154 response.set_parse_error(
155 absl::StrCat("parse error: ", status.message()));
156 return response;
157 }
158
159 if (!test_message->ParseFromString(proto_binary)) {
160 response.set_runtime_error(
161 "parsing JSON generated invalid proto output");
162 return response;
163 }
164
165 break;
166 }
167
168 case ConformanceRequest::kTextPayload: {
169 if (!TextFormat::ParseFromString(request.text_payload(),
170 test_message.get())) {
171 response.set_parse_error("parse error (no more details available)");
172 return response;
173 }
174 break;
175 }
176
177 case ConformanceRequest::PAYLOAD_NOT_SET:
178 return absl::InvalidArgumentError("request didn't have payload");
179
180 default:
181 return absl::InvalidArgumentError(
182 absl::StrCat("unknown payload type", request.payload_case()));
183 }
184
185 switch (request.requested_output_format()) {
186 case conformance::UNSPECIFIED:
187 return absl::InvalidArgumentError("unspecified output format");
188
189 case conformance::PROTOBUF: {
190 ABSL_CHECK(
191 test_message->SerializeToString(response.mutable_protobuf_payload()));
192 break;
193 }
194
195 case conformance::JSON: {
196 std::string proto_binary;
197 ABSL_CHECK(test_message->SerializeToString(&proto_binary));
198 absl::Status status =
199 BinaryToJsonString(resolver_.get(), type_url_, proto_binary,
200 response.mutable_json_payload());
201 if (!status.ok()) {
202 response.set_serialize_error(absl::StrCat(
203 "failed to serialize JSON output: ", status.message()));
204 }
205 break;
206 }
207
208 case conformance::TEXT_FORMAT: {
209 TextFormat::Printer printer;
210 printer.SetHideUnknownFields(!request.print_unknown_fields());
211 ABSL_CHECK(printer.PrintToString(*test_message,
212 response.mutable_text_payload()));
213 break;
214 }
215
216 default:
217 return absl::InvalidArgumentError(absl::StrCat(
218 "unknown output format", request.requested_output_format()));
219 }
220
221 return response;
222 }
223
224 absl::StatusOr<bool> Harness::ServeConformanceRequest() {
225 uint32_t in_len;
226 if (!ReadFd(STDIN_FILENO, reinterpret_cast<char*>(&in_len), sizeof(in_len))
227 .ok()) {
228 // EOF means we're done.
229 return true;
230 }
231
232 std::string serialized_input;
233 serialized_input.resize(in_len);
234 RETURN_IF_ERROR(ReadFd(STDIN_FILENO, &serialized_input[0], in_len));
235
236 ConformanceRequest request;
237 ABSL_CHECK(request.ParseFromString(serialized_input));
238
239 absl::StatusOr<ConformanceResponse> response = RunTest(request);
240 RETURN_IF_ERROR(response.status());
241
242 std::string serialized_output;
243 response->SerializeToString(&serialized_output);
244
245 uint32_t out_len = static_cast<uint32_t>(serialized_output.size());
246 RETURN_IF_ERROR(WriteFd(STDOUT_FILENO, &out_len, sizeof(out_len)));
247 RETURN_IF_ERROR(WriteFd(STDOUT_FILENO, serialized_output.data(), out_len));
248
249 if (verbose_) {
250 ABSL_LOG(INFO) << "conformance-cpp: request=" << request.ShortDebugString()
251 << ", response=" << response->ShortDebugString();
252 }
253 return false;
254 }
255 } // namespace
256 } // namespace protobuf
257 } // namespace google
258
259 int main() {
260 google::protobuf::Harness harness;
261 int total_runs = 0;
262 while (true) {
263 auto is_done = harness.ServeConformanceRequest();
264 if (!is_done.ok()) {
265 ABSL_LOG(FATAL) << is_done.status();
266 }
267 if (*is_done) {
268 break;
269 }
270 total_runs++;
271 }
272 ABSL_LOG(INFO) << "conformance-cpp: received EOF from test runner after "
273 << total_runs << " tests";
274 }