• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //
3 // Copyright 2018 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "test/core/test_util/fuzzer_util.h"
20 
21 #include <grpc/support/alloc.h>
22 #include <stddef.h>
23 
24 #include <algorithm>
25 
26 namespace grpc_core {
27 namespace testing {
28 
grpc_fuzzer_get_next_byte(input_stream * inp)29 uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) {
30   if (inp->cur == inp->end) {
31     return 0;
32   }
33   return *inp->cur++;
34 }
35 
grpc_fuzzer_get_next_string(input_stream * inp,bool * special)36 char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) {
37   char* str = nullptr;
38   size_t cap = 0;
39   size_t sz = 0;
40   char c;
41   do {
42     if (cap == sz) {
43       cap = std::max(3 * cap / 2, cap + 8);
44       str = static_cast<char*>(gpr_realloc(str, cap));
45     }
46     c = static_cast<char>(grpc_fuzzer_get_next_byte(inp));
47     str[sz++] = c;
48   } while (c != 0 && c != 1);
49   if (special != nullptr) {
50     *special = (c == 1);
51   }
52   if (c == 1) {
53     str[sz - 1] = 0;
54   }
55   return str;
56 }
57 
grpc_fuzzer_get_next_uint32(input_stream * inp)58 uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) {
59   uint8_t b = grpc_fuzzer_get_next_byte(inp);
60   uint32_t x = b & 0x7f;
61   if (b & 0x80) {
62     x <<= 7;
63     b = grpc_fuzzer_get_next_byte(inp);
64     x |= b & 0x7f;
65     if (b & 0x80) {
66       x <<= 7;
67       b = grpc_fuzzer_get_next_byte(inp);
68       x |= b & 0x7f;
69       if (b & 0x80) {
70         x <<= 7;
71         b = grpc_fuzzer_get_next_byte(inp);
72         x |= b & 0x7f;
73         if (b & 0x80) {
74           x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f);
75         }
76       }
77     }
78   }
79   return x;
80 }
81 
82 }  // namespace testing
83 }  // namespace grpc_core
84