fuzz_json_decode_encode.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. assert(retval == UA_STATUSCODE_GOOD);
  35. assert(bufPos == bufEnd);
  36. UA_Variant value2;
  37. UA_Variant_init(&value2);
  38. retval = UA_decodeJson(&buf2, &value2, &UA_TYPES[UA_TYPES_VARIANT]);
  39. assert(retval == UA_STATUSCODE_GOOD);
  40. UA_ByteString buf3 = UA_BYTESTRING_NULL;
  41. retval = UA_ByteString_allocBuffer(&buf3, jsonSize);
  42. if(retval != UA_STATUSCODE_GOOD) {
  43. UA_Variant_deleteMembers(&value);
  44. UA_Variant_deleteMembers(&value2);
  45. UA_ByteString_deleteMembers(&buf2);
  46. return 0;
  47. }
  48. bufPos = buf3.data;
  49. bufEnd = &buf3.data[buf3.length];
  50. retval = UA_encodeJson(&value2, &UA_TYPES[UA_TYPES_VARIANT],
  51. &bufPos, &bufEnd, NULL, 0, NULL, 0, true);
  52. assert(retval == UA_STATUSCODE_GOOD);
  53. assert(bufPos == bufEnd);
  54. assert(memcmp(buf2.data, buf3.data, buf.length) == 0);
  55. UA_Variant_deleteMembers(&value);
  56. UA_Variant_deleteMembers(&value2);
  57. UA_ByteString_deleteMembers(&buf2);
  58. UA_ByteString_deleteMembers(&buf3);
  59. return 0;
  60. }