xml_parsebuffer_fuzzer.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2016 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <assert.h>
  17. #include <stdint.h>
  18. #include <string.h>
  19. #include "expat.h"
  20. #include "siphash.h"
  21. // Macros to convert preprocessor macros to string literals. See
  22. // https://gcc.gnu.org/onlinedocs/gcc-3.4.3/cpp/Stringification.html
  23. #define xstr(s) str(s)
  24. #define str(s) #s
  25. // The encoder type that we wish to fuzz should come from the compile-time
  26. // definition `ENCODING_FOR_FUZZING`. This allows us to have a separate fuzzer
  27. // binary for
  28. #ifndef ENCODING_FOR_FUZZING
  29. # error "ENCODING_FOR_FUZZING was not provided to this fuzz target."
  30. #endif
  31. // 16-byte deterministic hash key.
  32. static unsigned char hash_key[16] = "FUZZING IS FUN!";
  33. static void XMLCALL
  34. start(void *userData, const XML_Char *name, const XML_Char **atts) {
  35. (void)userData;
  36. (void)name;
  37. (void)atts;
  38. }
  39. static void XMLCALL
  40. end(void *userData, const XML_Char *name) {
  41. (void)userData;
  42. (void)name;
  43. }
  44. int
  45. LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  46. if (size == 0)
  47. return 0;
  48. XML_Parser p = XML_ParserCreate(xstr(ENCODING_FOR_FUZZING));
  49. assert(p);
  50. XML_SetElementHandler(p, start, end);
  51. // Set the hash salt using siphash to generate a deterministic hash.
  52. struct sipkey *key = sip_keyof(hash_key);
  53. XML_SetHashSalt(p, (unsigned long)siphash24(data, size, key));
  54. void *buf = XML_GetBuffer(p, size);
  55. assert(buf);
  56. memcpy(buf, data, size);
  57. XML_ParseBuffer(p, size, size == 0);
  58. XML_ParserFree(p);
  59. return 0;
  60. }