conformance_test.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. #include <errno.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <string>
  34. #include "conformance.pb.h"
  35. #include <google/protobuf/stubs/common.h>
  36. #include <google/protobuf/wire_format_lite.h>
  37. using conformance::ConformanceRequest;
  38. using conformance::ConformanceResponse;
  39. using conformance::TestAllTypes;
  40. using google::protobuf::Descriptor;
  41. using google::protobuf::FieldDescriptor;
  42. using google::protobuf::internal::WireFormatLite;
  43. using std::string;
  44. int write_fd;
  45. int read_fd;
  46. int successes;
  47. int failures;
  48. bool verbose = false;
  49. string Escape(const string& str) {
  50. // TODO.
  51. return str;
  52. }
  53. #define STRINGIFY(x) #x
  54. #define TOSTRING(x) STRINGIFY(x)
  55. #define CHECK_SYSCALL(call) \
  56. if (call < 0) { \
  57. perror(#call " " __FILE__ ":" TOSTRING(__LINE__)); \
  58. exit(1); \
  59. }
  60. // TODO(haberman): make this work on Windows, instead of using these
  61. // UNIX-specific APIs.
  62. //
  63. // There is a platform-agnostic API in
  64. // src/google/protobuf/compiler/subprocess.h
  65. //
  66. // However that API only supports sending a single message to the subprocess.
  67. // We really want to be able to send messages and receive responses one at a
  68. // time:
  69. //
  70. // 1. Spawning a new process for each test would take way too long for thousands
  71. // of tests and subprocesses like java that can take 100ms or more to start
  72. // up.
  73. //
  74. // 2. Sending all the tests in one big message and receiving all results in one
  75. // big message would take away our visibility about which test(s) caused a
  76. // crash or other fatal error. It would also give us only a single failure
  77. // instead of all of them.
  78. void SpawnTestProgram(char *executable) {
  79. int toproc_pipe_fd[2];
  80. int fromproc_pipe_fd[2];
  81. if (pipe(toproc_pipe_fd) < 0 || pipe(fromproc_pipe_fd) < 0) {
  82. perror("pipe");
  83. exit(1);
  84. }
  85. pid_t pid = fork();
  86. if (pid < 0) {
  87. perror("fork");
  88. exit(1);
  89. }
  90. if (pid) {
  91. // Parent.
  92. CHECK_SYSCALL(close(toproc_pipe_fd[0]));
  93. CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
  94. write_fd = toproc_pipe_fd[1];
  95. read_fd = fromproc_pipe_fd[0];
  96. } else {
  97. // Child.
  98. CHECK_SYSCALL(close(STDIN_FILENO));
  99. CHECK_SYSCALL(close(STDOUT_FILENO));
  100. CHECK_SYSCALL(dup2(toproc_pipe_fd[0], STDIN_FILENO));
  101. CHECK_SYSCALL(dup2(fromproc_pipe_fd[1], STDOUT_FILENO));
  102. CHECK_SYSCALL(close(toproc_pipe_fd[0]));
  103. CHECK_SYSCALL(close(fromproc_pipe_fd[1]));
  104. CHECK_SYSCALL(close(toproc_pipe_fd[1]));
  105. CHECK_SYSCALL(close(fromproc_pipe_fd[0]));
  106. char *const argv[] = {executable, NULL};
  107. CHECK_SYSCALL(execv(executable, argv)); // Never returns.
  108. }
  109. }
  110. /* Invoking of tests **********************************************************/
  111. void ReportSuccess() {
  112. successes++;
  113. }
  114. void ReportFailure(const char *fmt, ...) {
  115. va_list args;
  116. va_start(args, fmt);
  117. vfprintf(stderr, fmt, args);
  118. va_end(args);
  119. failures++;
  120. }
  121. void CheckedWrite(int fd, const void *buf, size_t len) {
  122. if (write(fd, buf, len) != len) {
  123. GOOGLE_LOG(FATAL) << "Error writing to test program: " << strerror(errno);
  124. }
  125. }
  126. void CheckedRead(int fd, void *buf, size_t len) {
  127. size_t ofs = 0;
  128. while (len > 0) {
  129. ssize_t bytes_read = read(fd, (char*)buf + ofs, len);
  130. if (bytes_read == 0) {
  131. GOOGLE_LOG(FATAL) << "Unexpected EOF from test program";
  132. } else if (bytes_read < 0) {
  133. GOOGLE_LOG(FATAL) << "Error reading from test program: " << strerror(errno);
  134. }
  135. len -= bytes_read;
  136. ofs += bytes_read;
  137. }
  138. }
  139. void RunTest(const ConformanceRequest& request, ConformanceResponse* response) {
  140. string serialized;
  141. request.SerializeToString(&serialized);
  142. uint32_t len = serialized.size();
  143. CheckedWrite(write_fd, &len, sizeof(uint32_t));
  144. CheckedWrite(write_fd, serialized.c_str(), serialized.size());
  145. CheckedRead(read_fd, &len, sizeof(uint32_t));
  146. serialized.resize(len);
  147. CheckedRead(read_fd, (void*)serialized.c_str(), len);
  148. if (!response->ParseFromString(serialized)) {
  149. GOOGLE_LOG(FATAL) << "Could not parse response proto from tested process.";
  150. }
  151. if (verbose) {
  152. fprintf(stderr, "conformance_test: request=%s, response=%s\n",
  153. request.ShortDebugString().c_str(),
  154. response->ShortDebugString().c_str());
  155. }
  156. }
  157. void DoExpectParseFailureForProto(const string& proto, int line) {
  158. ConformanceRequest request;
  159. ConformanceResponse response;
  160. request.set_protobuf_payload(proto);
  161. // We don't expect output, but if the program erroneously accepts the protobuf
  162. // we let it send its response as this. We must not leave it unspecified.
  163. request.set_requested_output(ConformanceRequest::PROTOBUF);
  164. RunTest(request, &response);
  165. if (response.result_case() == ConformanceResponse::kParseError) {
  166. ReportSuccess();
  167. } else {
  168. ReportFailure("Should have failed, but didn't. Line: %d, Request: %s, "
  169. "response: %s\n",
  170. line,
  171. request.ShortDebugString().c_str(),
  172. response.ShortDebugString().c_str());
  173. }
  174. }
  175. // Expect that this precise protobuf will cause a parse error.
  176. #define ExpectParseFailureForProto(proto) DoExpectParseFailureForProto(proto, __LINE__)
  177. // Expect that this protobuf will cause a parse error, even if it is followed
  178. // by valid protobuf data. We can try running this twice: once with this
  179. // data verbatim and once with this data followed by some valid data.
  180. //
  181. // TODO(haberman): implement the second of these.
  182. #define ExpectHardParseFailureForProto(proto) DoExpectParseFailureForProto(proto, __LINE__)
  183. /* Routines for building arbitrary protos *************************************/
  184. // We would use CodedOutputStream except that we want more freedom to build
  185. // arbitrary protos (even invalid ones).
  186. const string empty;
  187. string cat(const string& a, const string& b,
  188. const string& c = empty,
  189. const string& d = empty,
  190. const string& e = empty,
  191. const string& f = empty,
  192. const string& g = empty,
  193. const string& h = empty,
  194. const string& i = empty,
  195. const string& j = empty,
  196. const string& k = empty,
  197. const string& l = empty) {
  198. string ret;
  199. ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
  200. g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  201. ret.append(a);
  202. ret.append(b);
  203. ret.append(c);
  204. ret.append(d);
  205. ret.append(e);
  206. ret.append(f);
  207. ret.append(g);
  208. ret.append(h);
  209. ret.append(i);
  210. ret.append(j);
  211. ret.append(k);
  212. ret.append(l);
  213. return ret;
  214. }
  215. // The maximum number of bytes that it takes to encode a 64-bit varint.
  216. #define VARINT_MAX_LEN 10
  217. size_t vencode64(uint64_t val, char *buf) {
  218. if (val == 0) { buf[0] = 0; return 1; }
  219. size_t i = 0;
  220. while (val) {
  221. uint8_t byte = val & 0x7fU;
  222. val >>= 7;
  223. if (val) byte |= 0x80U;
  224. buf[i++] = byte;
  225. }
  226. return i;
  227. }
  228. string varint(uint64_t x) {
  229. char buf[VARINT_MAX_LEN];
  230. size_t len = vencode64(x, buf);
  231. return string(buf, len);
  232. }
  233. // TODO: proper byte-swapping for big-endian machines.
  234. string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
  235. string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
  236. string delim(const string& buf) { return cat(varint(buf.size()), buf); }
  237. string uint32(uint32_t u32) { return fixed32(&u32); }
  238. string uint64(uint64_t u64) { return fixed64(&u64); }
  239. string flt(float f) { return fixed32(&f); }
  240. string dbl(double d) { return fixed64(&d); }
  241. string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
  242. string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
  243. string tag(uint32_t fieldnum, char wire_type) {
  244. return varint((fieldnum << 3) | wire_type);
  245. }
  246. string submsg(uint32_t fn, const string& buf) {
  247. return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
  248. }
  249. #define UNKNOWN_FIELD 666
  250. uint32_t GetFieldNumberForType(WireFormatLite::FieldType type, bool repeated) {
  251. const Descriptor* d = TestAllTypes().GetDescriptor();
  252. for (int i = 0; i < d->field_count(); i++) {
  253. const FieldDescriptor* f = d->field(i);
  254. if (static_cast<WireFormatLite::FieldType>(f->type()) == type &&
  255. f->is_repeated() == repeated) {
  256. return f->number();
  257. }
  258. }
  259. GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
  260. return 0;
  261. }
  262. void TestPrematureEOFForType(WireFormatLite::FieldType type) {
  263. // Incomplete values for each wire type.
  264. static const string incompletes[6] = {
  265. string("\x80"), // VARINT
  266. string("abcdefg"), // 64BIT
  267. string("\x80"), // DELIMITED (partial length)
  268. string(), // START_GROUP (no value required)
  269. string(), // END_GROUP (no value required)
  270. string("abc") // 32BIT
  271. };
  272. uint32_t fieldnum = GetFieldNumberForType(type, false);
  273. uint32_t rep_fieldnum = GetFieldNumberForType(type, true);
  274. WireFormatLite::WireType wire_type =
  275. WireFormatLite::WireTypeForFieldType(type);
  276. const string& incomplete = incompletes[wire_type];
  277. // EOF before a known non-repeated value.
  278. ExpectParseFailureForProto(tag(fieldnum, wire_type));
  279. // EOF before a known repeated value.
  280. ExpectParseFailureForProto(tag(rep_fieldnum, wire_type));
  281. // EOF before an unknown value.
  282. ExpectParseFailureForProto(tag(UNKNOWN_FIELD, wire_type));
  283. // EOF inside a known non-repeated value.
  284. ExpectParseFailureForProto(
  285. cat( tag(fieldnum, wire_type), incomplete ));
  286. // EOF inside a known repeated value.
  287. ExpectParseFailureForProto(
  288. cat( tag(rep_fieldnum, wire_type), incomplete ));
  289. // EOF inside an unknown value.
  290. ExpectParseFailureForProto(
  291. cat( tag(UNKNOWN_FIELD, wire_type), incomplete ));
  292. if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
  293. // EOF in the middle of delimited data for known non-repeated value.
  294. ExpectParseFailureForProto(
  295. cat( tag(fieldnum, wire_type), varint(1) ));
  296. // EOF in the middle of delimited data for known repeated value.
  297. ExpectParseFailureForProto(
  298. cat( tag(rep_fieldnum, wire_type), varint(1) ));
  299. // EOF in the middle of delimited data for unknown value.
  300. ExpectParseFailureForProto(
  301. cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ));
  302. if (type == WireFormatLite::TYPE_MESSAGE) {
  303. // Submessage ends in the middle of a value.
  304. string incomplete_submsg =
  305. cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
  306. incompletes[WireFormatLite::WIRETYPE_VARINT] );
  307. ExpectHardParseFailureForProto(
  308. cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  309. varint(incomplete_submsg.size()),
  310. incomplete_submsg ));
  311. }
  312. } else if (type != WireFormatLite::TYPE_GROUP) {
  313. // Non-delimited, non-group: eligible for packing.
  314. // Packed region ends in the middle of a value.
  315. ExpectHardParseFailureForProto(
  316. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  317. varint(incomplete.size()),
  318. incomplete ));
  319. // EOF in the middle of packed region.
  320. ExpectParseFailureForProto(
  321. cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
  322. varint(1) ));
  323. }
  324. }
  325. int main(int argc, char *argv[]) {
  326. if (argc < 2) {
  327. fprintf(stderr, "Usage: conformance_test <test-program>\n");
  328. exit(1);
  329. }
  330. SpawnTestProgram(argv[1]);
  331. for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
  332. TestPrematureEOFForType(static_cast<WireFormatLite::FieldType>(i));
  333. }
  334. fprintf(stderr, "conformance_test: completed %d tests for %s, %d successes, "
  335. "%d failures.\n", successes + failures, argv[1], successes,
  336. failures);
  337. }