Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC NOPs being compiled away

Venturing out of my usual VC++ realm into the world of GCC (via MINGW32). Trying to create a Windows PE that consists largely of NOPs, ala:

for(i = 0; i < 1000; i++)
{
    asm("nop");
}

But either I'm using the wrong syntax or the compiler is optimising through them because those NOPs don't survive the compilation process.

I'm using the -O0 flag, otherwise defaults. Any ideas on how I can coax the compiler into leaving the NOPs intact?

like image 837
Rushyo Avatar asked Dec 10 '22 11:12

Rushyo


2 Answers

A convenient way to get 1000 inline nops is to use the .rept directive of the GNU assembler:

void thousand_nops(void) {
    asm(".rept 1000 ; nop ; .endr");
}

Try on godbolt.

like image 173
Nate Eldredge Avatar answered Jan 07 '23 19:01

Nate Eldredge


Are you expecting it to unroll the loop in to 1000 nops? I did a quick test with gcc and I don't see the (one) nop disappear:

        xorl    %eax, %eax
        .p2align 4,,7
.L2:
#APP
        nop
#NO_APP
        addl    $1, %eax
        cmpl    $1000, %eax
        jne     .L2

With gcc -S -O3 -funroll-all-loops I see it unroll the loop 8 times (thus 8 nop) but I think if you want 1000 it's going to be easiest to do:

#define NOP10() asm("nop;nop;nop;nop;nop;nop;nop;nop;nop;nop")

And then use NOP10(); ...

like image 27
Ben Jackson Avatar answered Jan 07 '23 20:01

Ben Jackson