test.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <pb_encode.h>
  5. #include "test.pb.h"
  6. #include "unittests.h"
  7. const char STR[] = "test str";
  8. #define ALIGN 0x100
  9. int main(int argc, char **argv)
  10. {
  11. int status = 0;
  12. uint8_t buffer[512] = {0};
  13. int i;
  14. {
  15. pb_ostream_t ostream;
  16. MyMessage msg = MyMessage_init_zero;
  17. char *pStr, *pStrAligned;
  18. COMMENT("Test for false negatives with pointer value low byte 0x00")
  19. ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  20. /* copy STR to a malloced 0x100 aligned address */
  21. pStr = malloc(sizeof(STR) + ALIGN);
  22. pStrAligned = (char*)((uintptr_t)(pStr + ALIGN) & ~(ALIGN - 1));
  23. memcpy(pStrAligned, STR, sizeof(STR));
  24. msg.submessage.somestring = pStrAligned;
  25. printf("%p: '%s'\n", msg.submessage.somestring, msg.submessage.somestring);
  26. if (!pb_encode(&ostream, MyMessage_fields, &msg)) {
  27. fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&ostream));
  28. return 1;
  29. }
  30. free(pStr);
  31. msg.submessage.somestring = NULL;
  32. printf("response payload (%d):", (int)ostream.bytes_written);
  33. for (i = 0; i < ostream.bytes_written; i++) {
  34. printf("%02X", buffer[i]);
  35. }
  36. printf("\n");
  37. TEST(ostream.bytes_written != 0);
  38. }
  39. {
  40. pb_ostream_t ostream;
  41. struct {
  42. MyMessage msg;
  43. uint32_t bar;
  44. } msg = {MyMessage_init_zero, 0};
  45. COMMENT("Test for false positives with data after end of struct")
  46. ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
  47. msg.bar = 0xFFFFFFFF;
  48. if (!pb_encode(&ostream, MyMessage_fields, &msg)) {
  49. fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&ostream));
  50. return 1;
  51. }
  52. printf("response payload (%d):", (int)ostream.bytes_written);
  53. for (i = 0; i < ostream.bytes_written; i++) {
  54. printf("%02X", buffer[i]);
  55. }
  56. printf("\n");
  57. TEST(ostream.bytes_written == 0);
  58. }
  59. return status;
  60. }