基于给定x86汇编逆向编写C语言函数的技术求助
mystery Function Let's break down this x86-64 assembly to figure out exactly what the mystery function does, using the struct definition and function prototype you provided.
First, remember that in x86-64 System V calling convention (used on Linux/macOS), the first function argument is passed in the rdi register—here, that's our struct my_struct *s pointer.
Let's go through each instruction step by step:
400596: 8b 07 mov (%rdi),%eax
This dereferences the pointer inrdito grab the value ofs->a(the first member of the struct) and stores it ineax. Right now,eaxholds the original value ofs->a.400598: 8d 04 40 lea (%rax,%rax,2),%eax
Theleainstruction here computesrax + (rax * 2)(sinceraxis the 64-bit counterpart ofeax). That's equivalent to multiplying the originals->aby 3, so noweax = 3 * original_s_a.40059b: 89 07 mov %eax,(%rdi)
We write this multiplied value back tos->a, updating the struct'samember to be three times its original value. Theeaxregister still holds this 3x value.40059d: 83 47 04 07 addl $0x7,0x4(%rdi)0x4(%rdi)is the address ofs->b—sinceint atakes up 4 bytes, we offset the struct pointer by 4 to reach the second member. This instruction adds 7 directly tos->b, sos->b += 7. Crucially, this doesn't change the value ineax.4005a1: c3 retq
In integer-returning functions, x86-64 useseaxto hold the return value. Sinceeaxstill has3 * original_s_a, that's what the function sends back to the caller.
Equivalent C Code
Here's the C code that matches the assembly's behavior exactly:
#include "mystery.h" int mystery(struct my_struct *s) { int original_a = s->a; s->a = 3 * original_a; s->b += 7; return original_a * 3; }
You could also write it more concisely (since after updating s->a, its value is exactly the return value):
int mystery(struct my_struct *s) { s->a *= 3; s->b += 7; return s->a; }
内容的提问来源于stack exchange,提问作者minturtle

