1 #include <stdio.h>
2 #include <string.h>
3 
4 int
main()5 main() {
6 	/*
7 	 * Make sure a complete storage unit is allocated
8 	 */
9 	struct foo {
10 		int	bf:1;
11 		unsigned	:0;
12 	};
13 	struct bar {
14 		int	bf:1;
15 		unsigned	:0;
16 		char	x;
17 	};
18 	struct baz {
19 		int	bf:1;
20 		signed	:0;
21 		char	x;
22 		short	y;
23 	};
24 	struct bleh {
25 		int	bf:1;
26 		signed	:0;
27 		signed	:0;
28 		signed	:0;
29 		signed	:0;
30 		signed	:0;
31 		signed	:0;
32 		signed	:0;
33 		signed	:0;
34 		signed	:0;
35 		signed	:0;
36 		signed	:0;
37 		signed	:0;
38 		signed	:0;
39 		signed	:0;
40 		signed	:0;
41 		signed	:0;
42 		signed	:0;
43 		int	lolz:1;
44 		char	x;
45 		short	y;
46 	};
47 	struct bleh2 {
48 		int	x;
49 		signed	:0;  /* should have no effect */
50 		int	bf:1;
51 	};
52 
53 	/*
54 	 * Make sure the storage unit holding bf is correctly
55 	 * considered complete at the end of the struct (i.e.
56 	 * not padded)
57 	 */
58 	struct gnu {
59 		int	bf:1;
60 		char	x;
61 		char	y[2];
62 
63 		char 	z[4];
64 	};
65 
66 	printf("%d\n", (int)sizeof(struct foo));
67 	printf("%d\n", (int)sizeof(struct bar));
68 	printf("%d\n", (int)sizeof(struct baz));
69 	printf("%d\n", (int)sizeof(struct gnu));
70 	printf("%d\n", (int)sizeof(struct bleh));
71 	printf("%d\n", (int)sizeof(struct bleh2));
72 
73 	{
74 		struct foo	f;
75 		struct bar	b;
76 		struct baz	bz;
77 		struct bleh	bleh;
78 		printf("locations:\n");
79 
80 		memset(&f, 0, sizeof f);
81 		f.bf = 1;
82 		printf("%d ", find_loc(&f, sizeof f));
83 
84 		memset(&b, 0, sizeof b);
85 		b.bf = 1;
86 		printf("%d ", find_loc(&b, sizeof b));
87 
88 		memset(&bz, 0, sizeof bz);
89 		bz.bf = 1;
90 		printf("%d\n", find_loc(&bz, sizeof bz));
91 
92 		memset(&bleh, 0, sizeof bleh);
93 		bleh.lolz = 1;
94 		printf("%d\n", find_loc(&bleh, sizeof bleh));
95 	}
96 	return 0;
97 }
98 
99 int
find_loc(void * buf,int size)100 find_loc(void *buf, int size) {
101         unsigned char   *cp;
102 
103         for (cp = buf; cp < (unsigned char *)buf + size; ++cp) {
104                 printf("%02x ", *cp);
105         }
106         putchar('\n');
107         for (cp = buf; cp < (unsigned char *)buf + size; ++cp) {
108                 if (*cp != 0) {
109                         int     mask;
110                         int     i = 0;
111 
112                         for (mask = 1; mask <= 0x80; mask <<= 1) {
113                                 if (*cp & mask) {
114                                         break;
115                                 }
116                                 ++i;
117                         }
118                         return (cp - (unsigned char *)buf) * 8 + i;
119                 }
120         }
121         return -1;
122 }
123 
124