1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
| /** * Linux下对Alignment trap的处理有下面几种方式: 0 (ignored) 1 (warn) 2 (fixup) 3 (fixup+warn) 4 (signal) 5 (signal+warn)
使用方法: # echo 3 > /proc/cpu/alignment */
#include <stdio.h> #include <stdlib.h>
/// case 1 void fool(unsigned char* buf, int len) { unsigned int* p = (unsigned int*)buf; int i;
for (i = 0; i < len; i++) { *p++ = i+1; printf("%d ", *p); } }
void foolish() { unsigned char poor[100];
fool(poor, sizeof(poor)/sizeof(int)); }
// case 1 end ////////////////////////////////////////////////////////////////
/// case 2
struct rte_unpacked_struct_t { char c1; int i; char c2; short s1; char c3; };
struct rte_packed_struct_t { char c1; int i; char c2; short s1; char c3; }__attribute__((__packed__));
struct rte_unpacked_struct_t unpacked; struct rte_packed_struct_t packed;
void print_addr() { printf("sizeof(unpacked) = %d sizeof(packed) = %d\n", sizeof(unpacked), sizeof(packed)); printf("Addr of unpacked: %p\n", &unpacked); printf("Addr of unpacked.c1: %p\n", &unpacked.c1); printf("Addr of unpacked.i: %p\n", &unpacked.i); printf("Addr of unpacked.c2: %p\n", &unpacked.c2); printf("Addr of unpacked.s1: %p\n", &unpacked.s1); printf("Addr of unpacked.c3: %p\n", &unpacked.c3);
printf("Addr of packed: %p\n", &packed); printf("Addr of packed.c1: %p\n", &packed.c1); printf("Addr of packed.i: %p\n", &packed.i); printf("Addr of packed.c2: %p\n", &packed.c2); printf("Addr of packed.s1: %p\n", &packed.s1); printf("Addr of packed.c3: %p\n", &packed.c3);
}
short* rte_get_s1(void) { return &unpacked.s1; }
void case2() { print_addr();
int* val = (int *)rte_get_s1(); printf("val = %d\n", *val); } /// case 2 end ////////////////////////////////////////////////////////////////
/// case 3 struct foo_t { short a; short b; short c; short d; };
struct foo_t foo;
short* get_foo_c(void) { return &foo.c; }
void case3() { printf("sizeof(foo) = %d\n", sizeof(foo)); // 注意!!此处将short*强制转换为int*,造成出错 int* val = (int *)get_foo_c(); printf("val: %d\n", *val); }
// case 3 end //////////////////////////////////////////////////////////////
/// case 4
void case4() { char* str = "01234567"; unsigned* u = (unsigned *)(str+1); printf("0x%08x\n", *u); }
/// case 4 end
int main() { printf("test of alignment trap...\n");
//foolish();
//case2(); //case3(); case4();
return 0; }
|