xref: /aosp_15_r20/external/grpc-grpc/test/core/util/fuzzer_util.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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/util/fuzzer_util.h"
20 
21 #include <stddef.h>
22 
23 #include <algorithm>
24 
25 #include <grpc/support/alloc.h>
26 
27 namespace grpc_core {
28 namespace testing {
29 
grpc_fuzzer_get_next_byte(input_stream * inp)30 uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) {
31   if (inp->cur == inp->end) {
32     return 0;
33   }
34   return *inp->cur++;
35 }
36 
grpc_fuzzer_get_next_string(input_stream * inp,bool * special)37 char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) {
38   char* str = nullptr;
39   size_t cap = 0;
40   size_t sz = 0;
41   char c;
42   do {
43     if (cap == sz) {
44       cap = std::max(3 * cap / 2, cap + 8);
45       str = static_cast<char*>(gpr_realloc(str, cap));
46     }
47     c = static_cast<char>(grpc_fuzzer_get_next_byte(inp));
48     str[sz++] = c;
49   } while (c != 0 && c != 1);
50   if (special != nullptr) {
51     *special = (c == 1);
52   }
53   if (c == 1) {
54     str[sz - 1] = 0;
55   }
56   return str;
57 }
58 
grpc_fuzzer_get_next_uint32(input_stream * inp)59 uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) {
60   uint8_t b = grpc_fuzzer_get_next_byte(inp);
61   uint32_t x = b & 0x7f;
62   if (b & 0x80) {
63     x <<= 7;
64     b = grpc_fuzzer_get_next_byte(inp);
65     x |= b & 0x7f;
66     if (b & 0x80) {
67       x <<= 7;
68       b = grpc_fuzzer_get_next_byte(inp);
69       x |= b & 0x7f;
70       if (b & 0x80) {
71         x <<= 7;
72         b = grpc_fuzzer_get_next_byte(inp);
73         x |= b & 0x7f;
74         if (b & 0x80) {
75           x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f);
76         }
77       }
78     }
79   }
80   return x;
81 }
82 
83 }  // namespace testing
84 }  // namespace grpc_core
85