Last active
January 28, 2019 21:24
-
-
Save akoskovacs/3c1912cf5fb2c388e4114516c8955948 to your computer and use it in GitHub Desktop.
Leaf function example
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
// Compile with: gcc -O2 leaf.c -o leaf | |
// Proof: https://godbolt.org/z/vg1FSS | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
// Not actually tweaking the stack (except for ret) | |
int leaf_me_alone(int a, int b) | |
{ | |
return a*a + b*b / 2; | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
const char *as, *bs; | |
as = bs = NULL; | |
if ((as = argv[1])) { | |
bs = argv[2]; | |
} | |
if (!as || !bs) { | |
return 1; | |
} | |
int a = atoi(as); | |
int b = atoi(bs); | |
printf("%d\n", leaf_me_alone(a, b)); | |
printf("%d\n", leaf_me_alone(b, a)); | |
return 0; | |
} |
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
leaf_me_alone(int, int): | |
imul esi, esi | |
imul edi, edi | |
sar esi | |
lea eax, [rsi+rdi] | |
ret | |
.LC0: | |
.string "%d\n" | |
main: | |
mov rdi, QWORD PTR [rsi+8] | |
mov eax, 1 | |
test rdi, rdi | |
je .L10 | |
push rbp | |
push rbx | |
sub rsp, 8 | |
mov rbp, QWORD PTR [rsi+16] | |
test rbp, rbp | |
je .L3 | |
mov edx, 10 | |
xor esi, esi | |
call strtol | |
mov edx, 10 | |
mov rdi, rbp | |
xor esi, esi | |
mov rbx, rax | |
call strtol | |
imul ebx, ebx | |
mov edi, OFFSET FLAT:.LC0 | |
mov rbp, rax | |
imul ebp, eax | |
xor eax, eax | |
mov esi, ebp | |
sar esi | |
add esi, ebx | |
sar ebx | |
call printf | |
lea esi, [rbx+rbp] | |
mov edi, OFFSET FLAT:.LC0 | |
xor eax, eax | |
call printf | |
xor eax, eax | |
.L3: | |
add rsp, 8 | |
pop rbx | |
pop rbp | |
ret | |
.L10: | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment