Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A strcpy gcc inline assembly code

Can anybody tell me what work these two variables int rsrc, rdst; do? OR explain the following code to me statement by statement?

static inline char * asm_strcpy(char *dst, char *src) {
    int rsrc, rdst;
    __asm__ __volatile__(
        "1: \tlodsb\n\t;"
        "stosb\n\t;"
        "testb %%al,%%al\n\t;"
        "jne 1b;"
        : "=&S" (rsrc), "=&D" (rdst)
        : "0" (src),"1" (dst) 
        );
    return dst;
}
like image 522
Jianchen Avatar asked Oct 02 '22 15:10

Jianchen


1 Answers

rsrc and rdst are used as placeholder variables and later the compiler is instructed to optimize them in registers, using exactly SI and DI. The same is happening with src and dst but they are used as input for the assembly code, while rsrc and rdst are its discarded output.

the assembly code is quite trivial:

1:
  lodsb ; loads byte at *SI to register AL, increments SI
  stosb ; stores byte at *DI from register AL, increments DI
  testb AL,AL ; sets flags based on value in AL
  jne 1: ; repeat if AL is non zero 

for all this to operate correctly the direction flag should be clear; there is no rule of thumb because it may depend on calling convention or may be freely modified throughout the program

if the above code should be made DF agnostic, the following should wrap it:

PUSHF
CLD
...
POPF
like image 200
bbonev Avatar answered Oct 13 '22 11:10

bbonev