1

I'm working on instrumenting a piece of assembly code and I noted the following interesting phenomena:

The original assembly:

  64     .loc 1 22 0 is_stmt 0 discriminator 1
  65     cmpl    $31, -4(%rbp)   #, i
  66     jg  .L2 #,

Instrumented assembly:

  64     .loc 1 22 0 is_stmt 0 discriminator 1
  65     cmpl    $31, -4(%rbp)   #, i
  66     addq    $15, %r15
  67     jg  .L2 #,

First, r15 is not used by any other part of the assembly (ensured by gcc --fixed-r15). After adding a single addq, the program hangs (like there is a dead loop). I didn't understand what's the significance with that add so I tried to put it at other places. Interestingly, I found that whenever it's added after a section with discriminator 1, then some errors would occur. Any idea? I couldn't fully understand the discriminator after a reading of this. Will keep reading.

Any idea?

qweruiop
  • 3,156
  • 6
  • 31
  • 55

1 Answers1

3

In general you cannot simply add instructions into an existing assembly listing and hope everything will work out as before. For example, the added instruction may modify some architectural state that changes the behavior of the following instructions.

In your particular example, the addq instruction will overwrite the flags previously set by the prior cmpl instruction, so the conditional jg will do the wrong thing (looping forever in your case).

BeeOnRope
  • 60,350
  • 16
  • 207
  • 386
  • You're exactly right. So I'm in the process of figuring out how to add instructions I need properly. Where can I find information regarding which flags are modified by which? I guess Intel's manual is one... – qweruiop Oct 05 '16 at 03:47
  • The Intel software developers guide is certainly one place, but the [x86 tag wiki](http://stackoverflow.com/tags/x86/info) here on SO has a ton of other good links, including references that are a lot more compact than the 1,000+ page intel guides. – BeeOnRope Oct 05 '16 at 04:09
  • BTW, the `lea` instruction allows you to add two registers (and more) without modifying the flags. – BeeOnRope Oct 05 '16 at 04:09
  • will check out. I actually only need to add an immediate value to a register. Is there a good candidate for that? – qweruiop Oct 05 '16 at 04:12
  • 1
    `lea` can add immediates also. – BeeOnRope Oct 05 '16 at 04:19