Debian Codegraph @

src/test/test-sizeof.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <time.h>
4 #include <sched.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/resource.h>
9 #include <sys/socket.h>
10 #include <sys/timex.h>
11
12 #define __STDC_WANT_IEC_60559_TYPES_EXT__
13 #include <float.h>
14
15 #include "shared-forward.h"
16
17 /* Print information about various types. Useful when diagnosing
18 * gcc diagnostics on an unfamiliar architecture. */
19
20 DISABLE_WARNING_TYPE_LIMITS;
21
22 #define info_no_sign(t) \
23 printf("%s → %zu bits, %zu byte alignment\n", STRINGIFY(t), \
24 sizeof(t)*CHAR_BIT, \
25 alignof(t))
26
27 #define info(t) \
28 printf("%s → %zu bits%s, %zu byte alignment\n", STRINGIFY(t), \
29 sizeof(t)*CHAR_BIT, \
30 strstr(STRINGIFY(t), "signed") ? "" : \
31 (t)-1 < (t)0 ? ", signed" : ", unsigned", \
32 alignof(t))
33
34 #define check_no_sign(t, size) \
35 do { \
36 info_no_sign(t); \
37 assert_se(sizeof(t) == size); \
38 } while (false)
39
40 #define check(t, size) \
41 do { \
42 info(t); \
43 assert_se(sizeof(t) == size); \
44 } while (false)
45
46 enum Enum {
47 enum_value,
48 };
49
50 enum BigEnum {
51 big_enum_value = UINT64_C(1),
52 };
53
54 enum BigEnum2 {
55 big_enum2_pos = UINT64_C(1),
56 big_enum2_neg = UINT64_C(-1),
57 };
58
59 int main(void) {
60 int (*function_pointer)(void);
61
62 check_no_sign(dev_t, SIZEOF_DEV_T);
63 check_no_sign(ino_t, SIZEOF_INO_T);
64 check_no_sign(rlim_t, SIZEOF_RLIM_T);
65 check(time_t, SIZEOF_TIME_T);
66 check(typeof_field(struct timex, freq), SIZEOF_TIMEX_MEMBER);
67
68 info_no_sign(typeof(function_pointer));
69 info_no_sign(void*);
70 info(char*);
71
72 info(char);
73 info(signed char);
74 info(unsigned char);
75 info(short unsigned);
76 info(unsigned);
77 info(unsigned long);
78 info(unsigned long long);
79 #ifdef __GLIBC__
80 info(__syscall_ulong_t);
81 info(__syscall_slong_t);
82 #endif
83 info(intmax_t);
84 info(uintmax_t);
85
86 info(float);
87 info(double);
88 info(long double);
89
90 #ifdef FLT128_MAX
91 info(_Float128);
92 info(_Float64);
93 info(_Float64x);
94 info(_Float32);
95 info(_Float32x);
96 #endif
97
98 info(size_t);
99 info(ssize_t);
100 info(usec_t);
101 #ifdef __GLIBC__
102 info(__time_t);
103 #endif
104 info(pid_t);
105 info(uid_t);
106 info(gid_t);
107 info(socklen_t);
108
109 #ifdef __GLIBC__
110 info(__cpu_mask);
111 #endif
112
113 info(enum Enum);
114 info(enum BigEnum);
115 info(enum BigEnum2);
116 assert_cc(sizeof(enum BigEnum2) == 8);
117 printf("big_enum2_pos → %zu\n", sizeof(big_enum2_pos));
118 printf("big_enum2_neg → %zu\n", sizeof(big_enum2_neg));
119
120 printf("timeval: %zu\n", sizeof(struct timeval));
121 printf("timespec: %zu\n", sizeof(struct timespec));
122
123 void *x = malloc(100);
124
125 printf("local variable: %p\n", &function_pointer);
126 printf("glibc function: %p\n", memcpy);
127 printf("heap allocation: %p\n", x);
128 free(x);
129
130 return 0;
131 }