samedi 29 août 2020

C function from assembler code as a char string

I was just wondering how random number is generated in assembler, I found question from russian stack overflow where a person asks rather not how to generate a random number in assembler, but how to implement that in c code using _asm{}. The answer posted to his question surprised me (translated to eng):

char r[]="!!!!!!!!!!!№№№№№№№№№№№;;;;;;;;;;;;;;;;;;;;;;;;;55555555555555666666666666666666666666666777777777777777777777777777777777777777777777777777777777777";  // String, which length should be calculated

main()
{
    static unsigned long  (__cdecl *lenstr)(char*); // Pointer to function declaration. The method for passing parameters must be defined explicitly - it is different in different compilers

    static int i=0;
        if(!i)
            {
                static char s[]={
                    0x5a,
                    //pop %%edx
                    0x5f,
                    //pop %%edi
                    0xfc,
                    //cld
                    0x31,0xc9,
                    //xor %%ecx,%%ecx
                    0x31,0xc0,
                    //xor %%eax,%%eax
                    0x49,
                    //dec %%ecx
                    0xf2,0xae,
                    //repne scasв
                    0xf7,0xd1,
                    //not %%ecx
                    0x49,
                    //dec %%ecx
                    0x91,
                    //xchg %%eax,%%ecx
                    0x52,
                    //push %%edx
                    0xc3
                    //ret
                    }; // Array with assembler code
                lenstr=(unsigned long ( __cdecl *)(char*))&s; // Linking function pointer to to that array
                i=1;
            }               

            printf("%s%c%d%c%s\n","String length",' ',lenstr(r),' ',"symbols");
}

Two questions:

  1. How long does the opportunity to put assembler code as a casted char array to function-pointer is existing and why it was developed?
  2. I didn’t understand: calculating string length is kinda smart method of random number generation or it was just an example of machine code to pointer casting?



Aucun commentaire:

Enregistrer un commentaire