-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctx_switch.c
65 lines (55 loc) · 1.19 KB
/
ctx_switch.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
#include <stdio.h>
#include <stdlib.h>
typedef size_t uintptr_t;
#ifdef __x86_64__
#define NUM_REG 4
#elif __i386__
#define NUM_REG 3
#else
#define NUM_REG 0
#endif
struct stack_context {
uintptr_t sp_reg;
uintptr_t other_reg[NUM_REG];
}actx, bctx, pctx;
struct stack_context *cur_ctx;
#define STACK_SIZE 4096
unsigned int astack[STACK_SIZE];
unsigned int bstack[STACK_SIZE];
extern void my_yeild(struct stack_context *rctx);
extern void funa(void);
extern void funb(void);
void funa(void)
{
int i = 0;
my_yeild(&bctx);
while (i++ < 20) {
printf("a %d\n", i);
sleep(1);
my_yeild(&bctx);
}
exit(0);
}
void funb(void)
{
int i = 0;
my_yeild(&actx);
while (i++ < 20) {
printf("b %d\n", i);
sleep(1);
my_yeild(&actx);
}
exit(0);
}
int main()
{
cur_ctx = &pctx;
uintptr_t *sp = (uintptr_t *) ((((uintptr_t)&astack[STACK_SIZE]) & -16L) - sizeof(uintptr_t));
*sp = (uintptr_t)funa;
actx.sp_reg = (uintptr_t)sp;
sp = (uintptr_t *) ((((uintptr_t)&bstack[STACK_SIZE]) & -16L) - sizeof(uintptr_t));
*sp = (uintptr_t)funb;
bctx.sp_reg = (uintptr_t) sp;
my_yeild(&actx);
return 0;
}