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
|
#include <iostream>
using namespace std;
typedef void (*Ptr)(int);
int numThr=0;
long r0[10],r1[10],r2[10]; // struct with all registered named
long *stack0,*stack1,*stack2;
void save(long *rLocation) {
asm(//"pushq %rdi\n"
"mov %rax, (%rdi)\n"
"mov %rbx, 8(%rdi)\n"
"mov %rcx, 16(%rdi)\n"
"mov %rdx, 24(%rdi)\n"
"mov %rsi, 32(%rdi)\n"
"mov %r8, 40(%rdi)\n"
"mov %rbp, 48(%rdi)\n"); //...
}
void load(long *rLocation) { // similar to the book
asm(//"popq %rdi\n"
"mov (%rdi), %rax\n"
"mov 48(%rdi), %rbp\n"
"mov 40(%rdi), %r8\n"
"mov 32(%rdi), %rsi\n"
"mov 24(%rdi), %rdx\n"
"mov 16(%rdi), %rcx\n"
"mov 8(%rdi), %rbx\n"
/*"mov 16(%rdi),%rsp\n"*/); //....
}
int currentThr;
void setStack(long *s) {
asm("mov %rdi,%rsp\n");
}
void setStackAndRun(long *s,Ptr ptr) {
asm("mov %rdi,%rsp\n");
ptr(currentThr);
}
void getStack(long **s) {
asm("mov %rsp,(%rdi)");
}
void startThr(Ptr ptr) {
numThr++;
currentThr=numThr;
if (numThr==1) {
stack1=((long *)malloc(sizeof(long)*64000))+64000;
save(r0);
getStack(&stack0);
load(r1);
setStackAndRun(stack1,ptr);
}
else if (numThr==2) {
stack2=((long *)malloc(sizeof(long)*64000))+64000;
save(r0);
getStack(&stack0);
load(r2);
setStackAndRun(stack2,ptr);
}
//ptr(numThreads);
}
void shareCPU(int thread) {
if (numThr==1) {
save(r1); // Save out created thread registers
load(r0); // Load the main thread registers
setStack(stack0);
// do "opposite" of what we did on lines 36-39
}
// Switch stacks back and swap registers
}
void main1(int whoami) {
while(true) {
cout << "Main 1 says Hello" << endl;
shareCPU(whoami);
}
}
void main2(int whoami) {
while(true) {
cout << "Main 2 says Hello" << endl;
shareCPU(whoami);
}
}
int main() {
startThr(main1);
startThr(main2);
while(true) {
shareCPU(0);
};
return 0;
}
| |