1

I'm learning reverse engineering, and I have the following snippet which I am trying to make sense of:

var = strcmp("C:\\Windows\\System32\\svchost.exe", pe.szExeFile);
if (var)
  var = -(var < 0) | 1;
if (var)
{
  // additional code here
}

I think I understand most of what is going on here, but I'm confused about the purpose of the var = -(var < 0) | 1; line. I'm only very vaguely familiar with C/C++, so I'm having a hard time wrapping my head around what this line does.

I understand that it's a bitwise OR, but I'm unsure how the -(var < 0) works. Is the expression inside the parentheses evaluated to a 1 or 0 and then the negative is applied and the OR? Is it evaluated as a boolean? If so, how does the | work on a boolean?

Or am I totally missing the point here?

  • 3
    in C the result of `<` is an `int` (either 0 or 1) – M.M Mar 22 '21 at 05:52
  • 1
    If you work out the bits (and assuming two's complement representation), that's just another way to write `var = (var < 0) ? -1 : 1`. It could be a legitimate compiler optimization (to avoid branching), but it's not the code one would normally write for that. – dxiv Mar 22 '21 at 06:02
  • @M.M - thanks, I can at least logic through it with that information – spakejaniel Mar 22 '21 at 06:05
  • @dxiv - when I initially read it I thought maybe C ternary syntax used | instead of ?, since that was the only way I could parse it in a way that made sense to me, so that is good to know, thanks! – spakejaniel Mar 22 '21 at 06:07
  • 1
    It doesn't make much sense. You could remove it and the following `if` test. – user207421 Mar 22 '21 at 07:24

1 Answers1

0

strcmp() returns one of three possible results:

  • < 0
  • 0
  • > 0

Assumed common two's complement, after the first if the variable var will be

  • -1 for the former "< 0"
  • 0 for the former "= 0"
  • +1 for the former "> 0"

However, the second if will be taken only if var is non-zero.

The "mysterious" first if has no effect, as far as the source is concerned that you show.

the busybee
  • 10,755
  • 3
  • 13
  • 30
  • 1
    Perhaps the actual value of `var` is used in the code that isn't shown. – Nate Eldredge Mar 22 '21 at 21:07
  • 1
    @NateEldredge That's why I wrote "_the source […] that you show_". – the busybee Mar 22 '21 at 21:12
  • After dealing with this for a few days, my guess is it is decompiled and the second if is the implementation of strcmp to force an answer of -1/0/+1 rather than the more general 'negative/zero/positive' in the strcmp spec – spakejaniel Mar 23 '21 at 15:12
  • @spakejaniel That sounds sensible. However, some implementations of `strcmp()` I saw don't care. – the busybee Mar 23 '21 at 18:02