aboutsummaryrefslogtreecommitdiff
path: root/writeups/unaligned-mem/unamem.c
blob: cadfba1e91ebba928b6ba578ebe91769d6e131d1 (plain)
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
#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
#include <error.h>
#include <assert.h>

#include <unistd.h>
#include <wait.h>

#define ARGV0 "unamem"
#define DONT_FORK 1


static void report_wait (const int status) {
	if (WIFEXITED(status)) {
		printf("exit %d\n", WEXITSTATUS(status));
	}
	else if (WIFSIGNALED(status)) {
		printf("signal %d\n", WTERMSIG(status));
	}
	else {
		printf("?\n");
	}
}

int main (void) {
	static char m[9]; // bss address is nicer than stack
	char *c;
	uintptr_t *p;
	pid_t pid;
	int status;

	printf(
		"CHAR_BIT:  %d\n"
		"word:      %zd\n"
		"uintptr_t: %zd\n"
		"size_t:    %zd\n"
		"short:     %zd\n"
		"int:       %zd\n"
		"long:      %zd\n"
		"long long: %zd\n"
		,
		CHAR_BIT,
		CHAR_BIT * sizeof(uintptr_t),
		sizeof(uintptr_t),
		sizeof(size_t),
		sizeof(short),
		sizeof(int),
		sizeof(long),
		sizeof(long long));

	c = m;
	p = (void*)(m + 1);

	printf(
		"malloc:    %zx", (uintptr_t)m);
	for (size_t i = sizeof(uintptr_t); i > 1; i /= 2) {
		if ((uintptr_t)m % i == 0) {
			printf(" {%zu}", i);
		}
	}
	printf("\n");

	printf(
		"c:         %zx\n"
		"p:         %zx\n"
		,
		(uintptr_t)c,
		(uintptr_t)p);

	pid = DONT_FORK ? 0 : fork();
	if (pid > 0) {
		printf(
		"access:    "
		);
		wait(&status);
		report_wait(status);
	}
	else if (pid == 0) {
		*p = UINTPTR_MAX;
		*c = 0;
		assert(*p == UINTPTR_MAX);
		assert(*c == 0);

		*c = 0;
		*p = UINTPTR_MAX;
		assert(*p == UINTPTR_MAX);
		assert(*c == 0);
	}
	else {
		perror(ARGV0": fork()");
		return 1;
	}

	pid = DONT_FORK ? 0 : fork();
	if (pid > 0) {
		printf(
		"float:     "
		);
		wait(&status);
		report_wait(status);
	}
	else if (pid == 0) {
		volatile float a, b, c;

		a = 0.1;
		b = 1.0;
		c = b / a;
		assert(c > 1.0);
	}
	else {
		perror(ARGV0": fork()");
		return 1;
	}

	return 0;
}