fuzzer_util.cc 2.0 KB

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