Page 1 of 1

Should I preserve the general regs(eax,etc) in multitasking.

Posted: Tue Mar 09, 2021 6:33 pm
by clementttttttttt
Google doesn't seem to help this time.

Re: Should I preserve the general regs(eax,etc) in multitask

Posted: Tue Mar 09, 2021 7:03 pm
by kzinti
Assuming you are using ia32 + system V, you need to preserve ebp, edi, esi and ebx explicitely (and eip, esp implicitely).

Example:

Code: Select all

task_switch:

    movl    4(%esp), %eax   # eax = old context
    movl    8(%esp), %edx   # edx = new context

    # Save old context
    pushl   %ebp
    pushl   %edi
    pushl   %esi
    pushl   %ebx

    # Switch stacks
    movl    %esp, (%eax)    # *old context = esp
    movl    %edx, %esp      # esp = new context

    # Restore new context
    popl    %ebx
    popl    %esi
    popl    %edi
    popl    %ebp

    ret

Re: Should I preserve the general regs(eax,etc) in multitask

Posted: Tue Mar 09, 2021 7:40 pm
by bzt
clementttttttttt wrote:Google doesn't seem to help this time.
Depends if you have cooperative multitasking or pre-emptive multitasking.

With cooperative, your code actively yields. There you can save the registers with push/pop on the caller side, or you could just tell the compiler that registers might change (using yield();asm(:::"rax, rbx, rcx, etc.");).

With pre-emptive multitasking, your code could be interrupted at any arbitrary point, so there you must save all registers on task switch (GPRs at a minimum, plus XMM if the task uses floating point arithmetic too).

Cheers,
bzt