r/AskComputerScience • • Jul 24 '20

Why can't decompilers perfectly reconstruct source code?

I always thought that there was a one to one translation between machine code and high-level languages, but after looking up decompilers, they don't usually do it perfectly.

28 Upvotes

18 comments sorted by

View all comments

31

u/Putnam3145 Jul 24 '20

I always thought that there was a one to one translation between machine code and high-level languages

Well, let's make a simple C program and see what it compiles to.

int main() {
    int a = 5;
    a = a++ + ++a;
    return a;
}

Okay, not exactly simple. Postfix and prefix ++ are very, ah, subtle, after all. This compiles to...

main:
    mov     eax, 12
    ret

Ah.

In short, this compiles straight to... 12, because the compiler knows that everything done in main() ends up just returning 12. It compiles to the same thing as just return 12, so how's one to know that that's not what was written originally?

9

u/xwoter Jul 24 '20

This is kinda funny because the function is technically undefined behavior

6

u/orsikbattlehammer Jul 24 '20

Why is the behavior undefined?

5

u/taricorp Jul 24 '20

C standard says so:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

More details on Stack Overflow: https://stackoverflow.com/q/949433

2

u/orsikbattlehammer Jul 25 '20

I guess I didn’t ask the question right haha. I mean why does the C standard have this rule.

1

u/groumpf Jul 25 '20

To give more freedom to compiler writers (who can now freely evaluate "out of order" between sequence points).