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

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
clementttttttttt
Member
Member
Posts: 70
Joined: Tue Jul 14, 2020 4:01 am
Libera.chat IRC: clementttttttttt

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

Post by clementttttttttt »

Google doesn't seem to help this time.
kzinti
Member
Member
Posts: 898
Joined: Mon Feb 02, 2015 7:11 pm

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

Post 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
User avatar
bzt
Member
Member
Posts: 1584
Joined: Thu Oct 13, 2016 4:55 pm
Contact:

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

Post 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
Post Reply