-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_thread_jump.c
84 lines (66 loc) · 1.43 KB
/
test_thread_jump.c
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
#define _GNU_SOURCE
#include<stdio.h>
#include<fcntl.h>
#include<time.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
#include<stdint.h>
#include<signal.h>
#include<setjmp.h>
#include<stdbool.h>
#include<pthread.h>
#include<sys/mman.h>
#include<sys/time.h>
#define PAGE_SIZE 4096
int num_threads = 4;
char *buf;
char *buf1;
static sigjmp_buf jumper;
void signal_handler(int sig)
{
siglongjmp(jumper, 1);
}
void setup_signal_handler(void)
{
struct sigaction act, oact;
act.sa_handler = signal_handler;
act.sa_flags = SA_NODEFER;
sigaction(SIGSEGV, &act, &oact);
}
void *pthread_transfer(void *arg)
{
int pid = *(int *)arg;
int segfault;
printf("Thread %d starts\n", pid);
segfault = sigsetjmp(jumper, 0);
if (segfault == 0) {
memcpy(buf + pid * PAGE_SIZE, buf1, PAGE_SIZE);
} else {
printf("Thread %d triggers seg fault\n", pid);
}
pthread_exit(0);
}
int main(void)
{
pthread_t *pthreads;
int pids[16];
int i;
buf1 = malloc(PAGE_SIZE);
memset(buf1, 'c', PAGE_SIZE);
buf = malloc(PAGE_SIZE * 3);
setup_signal_handler();
// Allocate threads
pthreads = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
for (i = 0; i < num_threads; i++) {
pids[i] = i;
pthread_create(pthreads + i, NULL, pthread_transfer, (void *)(pids + i));
}
for (i = 0; i < num_threads; i++) {
pthread_join(pthreads[i], NULL);
}
free(buf);
free(buf1);
free(pthreads);
return 0;
}