0
  mov    %rdi,%r9
  mov    $0x0,%eax
  mov    $0xffffffffffffffff,%rcx
  repnz scas %es:(%rdi),%al
  not    %rcx
  sub    $0x1,%rcx

So I am aware of what the repnz instruction does, but what is the purpose of not %rcx and %sub %rcx?

  • 1
    Since `rcx` is counting down from -1 the `not` and the `sub` adjust it so you get the string length. – Jester Apr 18 '20 at 00:39
  • See [How to prove that the C statement -x, ~x+1, and ~(x-1) yield the same results?](https://stackoverflow.com/q/2278518) for why not/sub turn `-1 - strlen` into `strlen`. – Peter Cordes Apr 18 '20 at 00:42
  • I capitalized the instructions in the title so it wouldn't read as a "why not?" question. I should have left an edit message for that. – Peter Cordes Apr 18 '20 at 01:07
  • @PeterCordes It does not answer my question as in the websites you pointed out it talks about ~(x-1) whereas in this piece of code it is ~x-1. They are different. –  Apr 18 '20 at 12:21
  • @Jester Check my comment above. –  Apr 18 '20 at 12:21
  • Which part is unclear? `-x = ~x + 1` so `~x = -1 - x` so that gives you how many iterations there were since `rcx` counts down from -1. The final -1 is because you do not want count the terminating zero in the string length. – Jester Apr 18 '20 at 13:02
  • I am sorry, if rcx is just counting down from 1, shouldn't we just be doing ~x+1? Since we just want to find out the positive value of the corresponding integer stored in rcx? –  Apr 18 '20 at 13:34
  • @Oishika: Did you read the other duplicates? Specifically [REPNZ SCAS Assembly Instruction Specifics](https://stackoverflow.com/q/26783797) goes into a lot of detail about fixing up the count. I didn't close this until I found other duplicates that did answer your question exactly. And no, RCX is counting down from `-1` (all-ones), not from `1`. If it was counting down from `1`, `rep` would have stopped on RCX=0. – Peter Cordes Apr 18 '20 at 16:55

0 Answers0