1 /* Generates a random, valid protobuf message. Useful to seed
2 * external fuzzers such as afl-fuzz.
12 #include "alltypes_static.pb.h"
14 static uint64_t random_seed;
16 /* Uses xorshift64 here instead of rand() for both speed and
17 * reproducibility across platforms. */
18 static uint32_t rand_word()
20 random_seed ^= random_seed >> 12;
21 random_seed ^= random_seed << 25;
22 random_seed ^= random_seed >> 27;
23 return random_seed * 2685821657736338717ULL;
26 /* Fills a buffer with random data. */
27 static void rand_fill(uint8_t *buf, size_t count)
31 *buf++ = rand_word() & 0xff;
35 /* Check that size/count fields do not exceed their max size.
36 * Otherwise we would have to loop pretty long in generate_message().
37 * Note that there may still be a few encoding errors from submessages.
39 static void limit_sizes(alltypes_static_AllTypes *msg)
42 pb_field_iter_begin(&iter, alltypes_static_AllTypes_fields, msg);
43 while (pb_field_iter_next(&iter))
45 if (PB_LTYPE(iter.pos->type) == PB_LTYPE_BYTES)
47 ((pb_bytes_array_t*)iter.pData)->size %= iter.pos->data_size - PB_BYTES_ARRAY_T_ALLOCSIZE(0);
50 if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED)
52 *((pb_size_t*)iter.pSize) %= iter.pos->array_size;
55 if (PB_HTYPE(iter.pos->type) == PB_HTYPE_ONEOF)
57 /* Set the oneof to this message type with 50% chance. */
60 *((pb_size_t*)iter.pSize) = iter.pos->tag;
66 static void generate_message()
68 alltypes_static_AllTypes msg;
70 pb_ostream_t stream = {0};
74 fprintf(stderr, "Encoder error: %s\n", stream.errmsg);
76 stream = pb_ostream_from_buffer(buf, sizeof(buf));
77 rand_fill((void*)&msg, sizeof(msg));
79 } while (!pb_encode(&stream, alltypes_static_AllTypes_fields, &msg));
81 fwrite(buf, 1, stream.bytes_written, stdout);
84 int main(int argc, char **argv)
88 random_seed = atol(argv[1]);
92 random_seed = time(NULL);
95 fprintf(stderr, "Random seed: %llu\n", (long long unsigned)random_seed);