How to save unreachable code?

I would like to write a function that will have some optional code that will be executed or not depend on user settings. This function is intense cpu, and ifs in it will be slow, as the branch predictor is not so good.

My idea is to create a copy in memory of this function and replace the NOPs with a jump when I don't want to execute any code. My working example is as follows:

int Test()
{
    int x = 2;
    for (int i=0 ; i<10 ; i++)
    {
        x *= 2;

        __asm {NOP}; // to skip it replace this
        __asm {NOP}; // by JMP 2 (after the goto)
            x *= 2; // Op to skip or not

        x *= 2;
    }
    return x;
}

In my main test copy, I copy this function to the newly allocated executable memory and replace the NOP with JMP 2 so that the next x * = 2 is not executed. JMP 2 really "skips the next 2 bytes."

, JMP , , , .

, , :

__asm {NOP}; // to skip it replace this
__asm {NOP}; // by JMP 2 (after the goto)
goto dont_do_it;
    x *= 2; // Op to skip or not
dont_do_it:
x *= 2;

goto, . , , goto x * = 2 , .

, .

VStudio 2008.

+3
7

10, :

int Test()
{
    int x = 2;
    if (should_skip) {
        for (int i=0 ; i<10 ; i++)
        {
            x *= 2;
            x *= 2;
        }
    } else {
        for (int i=0 ; i<10 ; i++)
        {
            x *= 2;
            x *= 2;
            x *= 2;
        }
    }

    return x;
}

, , , , , .

, , x :

    int x = 2;
    if (should_skip) {
        doLoop<true>(x);
    } else {
        doLoop<false>(x);
    }

, .

, , . , , , .

+6

, ++ .

+4

, , . , , NOP JMP.

, . , . , , if-, .

, , - , . , ? , ? .

+4

!

volatile int y = 0;

int Test() 
{
    int x = 2; 
    for (int i=0 ; i<10 ; i++) 
    { 
        x *= 2; 

        __asm {NOP}; // to skip it replace this 
        __asm {NOP}; // by JMP 2 (after the goto) 
        goto dont_do_it;
    keep_my_code:
        x *= 2; // Op to skip or not 
    dont_do_it: 
        x *= 2; 
    }
    if (y) goto keep_my_code;
    return x; 
} 
+1

x64? , , . ; , . - ASM.

0

:

pragma Visual Studio.

, ASM, VS .

- , , , .

0

, , , . , , , , , . CPU , , .

0
source

Source: https://habr.com/ru/post/1739522/


All Articles