fuzz_json_decode_encode.cc 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. *
  5. * Copyright 2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  6. */
  7. #include <open62541/types.h>
  8. #include <open62541/types_generated_handling.h>
  9. #include "ua_types_encoding_json.h"
  10. /* Decode a message, then encode, decode, encode.
  11. * The two encodings must be bit-equal. */
  12. extern "C" int
  13. LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
  14. UA_ByteString buf;
  15. buf.data = (UA_Byte*)data;
  16. buf.length = size;
  17. UA_Variant value;
  18. UA_Variant_init(&value);
  19. UA_StatusCode retval = UA_decodeJson(&buf, &value, &UA_TYPES[UA_TYPES_VARIANT]);
  20. if(retval != UA_STATUSCODE_GOOD)
  21. return 0;
  22. size_t jsonSize = UA_calcSizeJson(&value, &UA_TYPES[UA_TYPES_VARIANT],
  23. NULL, 0, NULL, 0, true);
  24. UA_ByteString buf2 = UA_BYTESTRING_NULL;
  25. retval = UA_ByteString_allocBuffer(&buf2, jsonSize);
  26. if(retval != UA_STATUSCODE_GOOD) {
  27. UA_Variant_deleteMembers(&value);
  28. return 0;
  29. }
  30. uint8_t *bufPos = buf2.data;
  31. const uint8_t *bufEnd = &buf2.data[buf2.length];
  32. retval = UA_encodeJson(&value, &UA_TYPES[UA_TYPES_VARIANT],
  33. &bufPos, &bufEnd, NULL, 0, NULL, 0, true);
  34. UA_Variant_deleteMembers(&value);
  35. if(retval != UA_STATUSCODE_GOOD || bufPos != bufEnd) {
  36. return 0;
  37. }
  38. UA_Variant value2;
  39. UA_Variant_init(&value2);
  40. retval = UA_decodeJson(&buf2, &value2, &UA_TYPES[UA_TYPES_VARIANT]);
  41. if(retval != UA_STATUSCODE_GOOD) {
  42. return 0;
  43. }
  44. UA_ByteString buf3 = UA_BYTESTRING_NULL;
  45. retval = UA_ByteString_allocBuffer(&buf3, jsonSize);
  46. if(retval != UA_STATUSCODE_GOOD) {
  47. UA_Variant_deleteMembers(&value2);
  48. UA_ByteString_deleteMembers(&buf2);
  49. return 0;
  50. }
  51. bufPos = buf3.data;
  52. bufEnd = &buf3.data[buf3.length];
  53. retval = UA_encodeJson(&value2, &UA_TYPES[UA_TYPES_VARIANT],
  54. &bufPos, &bufEnd, NULL, 0, NULL, 0, true);
  55. UA_Variant_deleteMembers(&value2);
  56. if(retval != UA_STATUSCODE_GOOD) {
  57. UA_ByteString_deleteMembers(&buf2);
  58. UA_ByteString_deleteMembers(&buf3);
  59. return 0;
  60. }
  61. UA_assert(buf2.length == buf3.length);
  62. UA_assert(memcmp(buf2.data, buf3.data, buf2.length) == 0);
  63. UA_ByteString_deleteMembers(&buf2);
  64. UA_ByteString_deleteMembers(&buf3);
  65. return 0;
  66. }