test_ptr_slow.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #include "core/or/or.h"
  7. #include "test/test.h"
  8. #include "test/ptr_helpers.h"
  9. #include <stdint.h>
  10. #include <limits.h>
  11. /** Assert that <b>a</b> can be cast to void * and back. */
  12. static void
  13. assert_int_voidptr_roundtrip(int a)
  14. {
  15. intptr_t ap = (intptr_t)a;
  16. void *b = cast_intptr_to_voidstar(ap);
  17. intptr_t c = cast_voidstar_to_intptr(b);
  18. void *d = cast_intptr_to_voidstar(c);
  19. tt_assert(ap == c);
  20. tt_assert(b == d);
  21. done:
  22. return;
  23. }
  24. /** Test for possibility of casting `int` to `void *` and back. */
  25. static void
  26. test_int_voidstar_interop(void *arg)
  27. {
  28. int a;
  29. (void)arg;
  30. for (a = -1024; a <= 1024; a++) {
  31. assert_int_voidptr_roundtrip(a);
  32. }
  33. for (a = INT_MIN; a <= INT_MIN+1024; a++) {
  34. assert_int_voidptr_roundtrip(a);
  35. }
  36. for (a = INT_MAX-1024; a < INT_MAX; a++) {
  37. assert_int_voidptr_roundtrip(a);
  38. }
  39. a = 1;
  40. for (unsigned long i = 0; i < sizeof(int) * 8; i++) {
  41. assert_int_voidptr_roundtrip(a);
  42. a = (a << 1);
  43. }
  44. }
  45. /** Assert that <b>a</b> can be cast to void * and back. */
  46. static void
  47. assert_uint_voidptr_roundtrip(unsigned int a)
  48. {
  49. uintptr_t ap = (uintptr_t)a;
  50. void *b = cast_uintptr_to_voidstar(ap);
  51. uintptr_t c = cast_voidstar_to_uintptr(b);
  52. void *d = cast_uintptr_to_voidstar(c);
  53. tt_assert(ap == c);
  54. tt_assert(b == d);
  55. done:
  56. return;
  57. }
  58. /** Test for possibility of casting `int` to `void *` and back. */
  59. static void
  60. test_uint_voidstar_interop(void *arg)
  61. {
  62. unsigned int a;
  63. (void)arg;
  64. for (a = 0; a <= 1024; a++) {
  65. assert_uint_voidptr_roundtrip(a);
  66. }
  67. for (a = UINT_MAX-1024; a < UINT_MAX; a++) {
  68. assert_uint_voidptr_roundtrip(a);
  69. }
  70. a = 1;
  71. for (unsigned long i = 0; i < sizeof(int) * 8; i++) {
  72. assert_uint_voidptr_roundtrip(a);
  73. a = (a << 1);
  74. }
  75. }
  76. struct testcase_t slow_ptr_tests[] = {
  77. { .name = "int_voidstar_interop",
  78. .fn = test_int_voidstar_interop,
  79. .flags = 0,
  80. .setup = NULL,
  81. .setup_data = NULL },
  82. { .name = "uint_voidstar_interop",
  83. .fn = test_uint_voidstar_interop,
  84. .flags = 0,
  85. .setup = NULL,
  86. .setup_data = NULL },
  87. END_OF_TESTCASES
  88. };