How safe is this replacement without register input?

I am very new to assembly, and the code below should exchange two integers for two different functions: first use swap_c and then using swap_asm .

However, I doubt whether I need to push (I mean saving) each value of the registers before the assembly code and pop them later (just before returning to main ). In other words, will I be angry with me if I return to other registered content (not as key as ebp or esp , but just eax , ebx , ecx and edx )) after running the swap_asm function? Is it better to uncomment the lines in the assembly?

This code works fine for me, and I managed to reduce 27 lines of assembled C code to 7 assembly lines.

ps: The system is Windows 10, VS-2013 Express.

main.c part

 #include <stdio.h> extern void swap_asm(int *x, int *y); void swap_c(int *a, int *b) { int t = *a; *a = *b; *b = t; } int main(int argc, char *argv[]) { int x = 3, y = 5; printf("before swap => x = %dy = %d\n\n", x, y); swap_c(&x, &y); printf("after swap_c => x = %dy = %d\n\n", x, y); swap_asm(&x, &y); printf("after swap_asm => x = %dy = %d\n\n", x, y); getchar(); return (0); } 

assembly.asm part

  .686 .model flat, c .stack 100h .data .code swap_asm proc ; push eax ; push ebx ; push ecx ; push edx mov eax, [esp] + 4 ; get address of "x" stored in stack into eax mov ebx, [esp] + 8 ; get address of "y" stored in stack into ebx mov ecx, [eax] ; get value of "x" from address stored in [eax] into ecx mov edx, [ebx] ; get value of "y" from address stored in [ebx] into edx mov [eax], edx ; store value in edx into address stored in [eax] mov [ebx], ecx ; store value in ecx into address stored in [ebx] ; pop edx ; pop ecx ; pop ebx ; pop eax ret swap_asm endp end 
+5
source share
1 answer

This usually depends on the system calling convention you are working on. The calling convention indicates how to call the functions. As a rule, it says where to put the arguments and which registers should be saved by the called function.

On i386 Windows with a cdecl conditional call (which you are probably using), you can freely overwrite the eax , ecx and edx . The ebx register must be kept. While your code is running, it mysteriously fails when the function starts to depend on saving ebx , so it's better to save and restore it.

+8
source

Source: https://habr.com/ru/post/1243000/


All Articles