Last active
January 17, 2021 21:13
-
-
Save xfgusta/ab23e40eb5569edf6624721b71c7f1f8 to your computer and use it in GitHub Desktop.
Variadic function in C without stdarg header (gcc, linux x86_64)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int sum(int n, ...); | |
int main(void) { | |
printf("sum(5, 5) = %d\n", sum(2, 5, 5)); | |
printf("sum(10, 20, 30, 40, 50) = %d\n", sum(5, 10, 20, 30, 40, 50)); | |
printf("sum(9, 8, 7, 6, 5, 4, 3, 2, 1) = %d\n", sum(9, 9, 8, 7, 6, 5, 4, 3, 2, 1)); | |
return 0; | |
} | |
int sum(int n, ...) { | |
int result = 0; | |
register int esi asm("esi"); | |
register int edx asm("edx"); | |
register int ecx asm("ecx"); | |
register long r8 asm("r8"); | |
register long r9 asm("r9"); | |
register long rbp asm("rbp"); | |
int esiv = esi, edxv = edx, ecxv = ecx, r8v = r8, r9v = r9; | |
void *stack = (void *) rbp + 16; | |
while(n--) { | |
switch(n) { | |
case 0: | |
result += esiv; | |
break; | |
case 1: | |
result += edxv; | |
break; | |
case 2: | |
result += ecxv; | |
break; | |
case 3: | |
result += r8v; | |
break; | |
case 4: | |
result += r9v; | |
break; | |
default: | |
result += *(int *) stack; | |
stack += 8; | |
break; | |
} | |
} | |
return result; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment