fuzz-json.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (C) 2023 Teluu Inc. (http://www.teluu.com)
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. #include <stdio.h>
  19. #include <stdint.h>
  20. #include <stdlib.h>
  21. #include <pjlib.h>
  22. #include <pjlib-util.h>
  23. #define kMinInputLength 10
  24. #define kMaxInputLength 5120
  25. pj_pool_factory *mem;
  26. int Json_parse(uint8_t *data, size_t Size) {
  27. pj_pool_t *pool;
  28. pj_json_elem *elem;
  29. pj_json_err_info err;
  30. char *output;
  31. unsigned int output_size;
  32. pool = pj_pool_create(mem, "json", 1000, 1000, NULL);
  33. elem = pj_json_parse(pool, (char *)data, (unsigned *)&Size, &err);
  34. if (!elem) {
  35. goto on_error;
  36. }
  37. output_size = Size * 2;
  38. output = pj_pool_alloc(pool, output_size);
  39. if (pj_json_write(elem, output, &output_size)) {
  40. goto on_error;
  41. }
  42. pj_pool_release(pool);
  43. return 0;
  44. on_error:
  45. pj_pool_release(pool);
  46. return 1;
  47. }
  48. extern int
  49. LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
  50. {
  51. if (Size < kMinInputLength || Size > kMaxInputLength) {
  52. return 1;
  53. }
  54. int ret = 0;
  55. uint8_t *data;
  56. pj_caching_pool caching_pool;
  57. /* Add NULL byte */
  58. data = (uint8_t *)calloc((Size+1), sizeof(uint8_t));
  59. memcpy((void *)data, (void *)Data, Size);
  60. /* init Calls */
  61. pj_init();
  62. pj_caching_pool_init( &caching_pool, &pj_pool_factory_default_policy, 0);
  63. pj_log_set_level(0);
  64. mem = &caching_pool.factory;
  65. /* Call fuzzer */
  66. ret = Json_parse(data, Size);
  67. free(data);
  68. pj_caching_pool_destroy(&caching_pool);
  69. return ret;
  70. }