I'm trying to implement custom setjmp/longjmp for x64 windows. I have following code:
contextSave:
xorq %rdx,%rdx
movq %rdx,(%rcx)
movq %rbx,0x8(%rcx)
leaq 0x8(%rsp),%rax
movq %rax,0x10(%rcx)
movq %rbp,0x18(%rcx)
movq %rsi,0x20(%rcx)
movq %rdi,0x28(%rcx)
movq %r12,0x30(%rcx)
movq %r13,0x38(%rcx)
movq %r14,0x40(%rcx)
movq %r15,0x48(%rcx)
movq (%rsp),%rax
movq %rax,0x50(%rcx)
movdqa %xmm6,0x60(%rcx)
movdqa %xmm7,0x70(%rcx)
movdqa %xmm8,0x80(%rcx)
movdqa %xmm9,0x90(%rcx)
movdqa %xmm10,0xa0(%rcx)
movdqa %xmm11,0xb0(%rcx)
movdqa %xmm12,0xc0(%rcx)
movdqa %xmm13,0xd0(%rcx)
movdqa %xmm14,0xe0(%rcx)
movdqa %xmm15,0xf0(%rcx)
xorq %rax,%rax
retq
contextRestore:
movq $1,%rax
movq 0x8(%rcx),%rbx
movq 0x18(%rcx),%rbp
movq 0x20(%rcx),%rsi
movq 0x28(%rcx),%rdi
movq 0x30(%rcx),%r12
movq 0x38(%rcx),%r13
movq 0x40(%rcx),%r14
movq 0x48(%rcx),%r15
movdqa 0x60(%rcx),%xmm6
movdqa 0x70(%rcx),%xmm7
movdqa 0x80(%rcx),%xmm8
movdqa 0x90(%rcx),%xmm9
movdqa 0xa0(%rcx),%xmm10
movdqa 0xb0(%rcx),%xmm11
movdqa 0xc0(%rcx),%xmm12
movdqa 0xd0(%rcx),%xmm13
movdqa 0xe0(%rcx),%xmm14
movdqa 0xf0(%rcx),%xmm15
movq 0x50(%rcx),%rdx
movq 0x10(%rcx),%rsp
jmp *%rdx
Execution context is saved in following structs:
typedef struct Float128{
unsigned long part[2];
}Float128 __attribute__((aligned(16)));
typedef struct ContextData{
long frame;
long rbx;
long rsp;
long rbp;
long rsi;
long rdi;
long r12;
long r13;
long r14;
long r15;
long rip;
long spare;
Float128 Xmm6;
Float128 Xmm7;
Float128 Xmm8;
Float128 Xmm9;
Float128 Xmm10;
Float128 Xmm11;
Float128 Xmm12;
Float128 Xmm13;
Float128 Xmm14;
Float128 Xmm15;
}ContextData;
Code is modified version of this,this and this
gdb shows the following error message:
#0 0x000000000040231e in contextRestore () Backtrace stopped: Cannot access memory at address 0xbaadf00dbaadf00d
Info registers shows that 0xbaadf00dbaadf00d is stored in many registers. contextSave is not working as expected.
Update:
It seems that the problem is outside of showed code. I created a simple code with the functions to isolate the problem. It is causing a following error.
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
Registers seem to be ok thought.
ContextData context;
if(contextSave(context)==1){
puts("context restored");
exit(0);
}
contextRestore(context);
Update 2
Debugging shows that rsp,rpb and rip are zero in ContextData struct.
So they are not save properly by contextSave.
Ok it seem that the structs were the problem. I don´t whatever the functions are correctly implemnted. I have decided to only use the structs and use standart library for now.
Correct types:
typedef struct Float128{
unsigned long long data[2]
}Float128 __attribute__((aligned(16)));
typedef Float128 Context[16];