Hi all,

I came across a piece of code.
I didnt understand the last 2 lines of the code. Can anyone explain it, pls?

In msdn it says "If the function succeeds, the return value is nonzero. If the function fails, the return value is zero."

       push parameters
call SetFileAttributes
dec eax
jne somewhere


Posted on 2011-01-11 16:03:17 by hakand
Those 2 lines of code assume that the function returns either 0 or 1 (very bad practice). A much better approach is:

      or eax, eax
     jz it_is_zero

or something similar.
Posted on 2011-01-11 18:04:03 by ti_mo_n
By standard practice, the return value of a function is placed on eax register.
So to test an error, you have to test eax, against with zero which can be done by any of the follows:
test eax, eax
and eax, eax
or eax, eax
cmp eax, 0

AND and TEST are both AND-Gate operations. The only difference is that TEST doesn't have a write cycle nor overwrite the result on the destination register.

They set a zero flag so you can do:
jz label ;go to somewhere if equals to zero
jnz label ;go to somewhere if not equals to zero

In your code:
dec	eax
jne somewhere

-First, jne (jump not equal) is the same as jnz (jump not zero). The way the processor knows if two numbers are equal is by subtracting. If the result equals zero then the two numbers are equal and sets a zero flag.

In your code, it assumes that eax is 0 or 1.
-If eax is 1, after dec eax; eax will become 0 and sets a zero flag. It will not jump since the new value is 0. But the original value was not 0 but 1, so it is doing the opposite of what the statement says (jne).
-If eax is 0, after dec eax; eax will become -1 and NOT set a zero flag. It will jump since the new value is not 0 but -1. The original value was not -1 but 0, so again is doing the opposite of the statement (jne).

Doing what is in your code is a bad practice because:
-It is confusing when you want to read your code fast and it could lead to a misinterpretation since it using a statement for an opposite purpose
-Not all the return values are 0 or 1. eax could literally be any number and 0 have the special meaning that there was an error.

For example, you have a function that the return value can be:
0 = error occurred
100 = happy
200 = sad
And it returns not an error, the original value of eax will be changed and you will have manually to change it back in order to use it.
Posted on 2011-01-12 06:35:57 by banzemanga
Thank you all.
banzemanga you know very well how to give the explanation in a detailed way :)
Posted on 2011-01-13 23:11:51 by hakand