2

I have some code that runs x64 programs under ptrace and manipulates their code. For testing this sort of thing, I have a placeholder function in one of my test programs:

uint32_t __attribute__((noinline)) func(void) {
    return 0xCCCCCCCC;
}

The 0xCCCCCCCC is then replaced at runtime with some other constant.

When I compile with clang and optimisation, though, clang replaces calls to the function with the constant 0xCCCCCCCC (since the function is so simple). For example, here's part of the code generated for the call to check that the call to modified TestFunc() returns 0xCDCDCDCD, which it should after having been modified:

movl    $3435973836, %edi       ## imm = 0xCCCCCCCC
movl    $3435973836, %eax       ## imm = 0xCCCCCCCC
leaq    16843009(%rax), %rdx    ## [16843009 = 0x01010101]

As you might imagine, this test then fails, because these two mismatching constant values won't match!

Can I force clang (and, hopefully in the same way, gcc...) to generate the function call?

(I don't want to disable optimisations globally - I already have a build that does that (and with that build, all tests pass). I'd just like to do a spot fix, if that's possible.)

Tom Seddon
  • 2,648
  • 1
  • 19
  • 28
  • Perhaps you could put the function body somewhere that is not visible to the code which might optimize it – M.M Dec 21 '15 at 00:46
  • 1
    That does work, but I'm a bit suspicious whole-program optimisation will see right through it! I'd feel safer with something that's more akin to a function call analogue of `volatile`. – Tom Seddon Dec 21 '15 at 00:59
  • Could you call it through a `volatile` function pointer? – user253751 Dec 21 '15 at 01:06
  • 2
    Please report this to clang as a bug, they do mention the noinline attribute in http://clang.llvm.org/docs/AttributeReference.html . And if they didn't support it, they should print a warning. – Marc Glisse Dec 21 '15 at 08:50

1 Answers1

3

Use attribute optnone or optimize to set the optimization level for func to -O0.

Only optnone is defined on my machine. So the code for me is the following, but yours might use the header __attribute__ ((optimize("0"))).

#include <stdlib.h>

uint32_t __attribute__ ((optnone)) func(void) {
    return 0xCCCCCCCC;
}

int main()
{
    return func();
}

See In clang, how do you use per-function optimization attributes?.

Community
  • 1
  • 1
Dylan Kirkby
  • 1,427
  • 11
  • 19