RE4B Challenge 6

Challenge

What does this code do? This is one of the simplest exercises I made, but still this code can be served as useful library function and is certainly used in many modern real-world applications.

Non-optimizing GCC 4.8.2:

<f>:
   0:             push   rbp
   1:             mov    rbp,rsp
   4:             mov    QWORD PTR [rbp-0x8],rdi
   8:             mov    QWORD PTR [rbp-0x10],rsi
   c:             mov    rax,QWORD PTR [rbp-0x8]
  10:             movzx  eax,BYTE PTR [rax]
  13:             movsx  dx,al
  17:             mov    rax,QWORD PTR [rbp-0x10]
  1b:             mov    WORD PTR [rax],dx
  1e:             mov    rax,QWORD PTR [rbp-0x10]
  22:             movzx  eax,WORD PTR [rax]
  25:             test   ax,ax
  28:             jne    2c 
  2a:             jmp    38 
  2c:             add    QWORD PTR [rbp-0x8],0x1
  31:             add    QWORD PTR [rbp-0x10],0x2
  36:             jmp    c 
  38:             pop    rbp
  39:             ret

Optimizing GCC 4.8.2:

<f>:
   0:          jmp    10 
   2:          nop    WORD PTR [rax+rax*1+0x0]
   8:          add    rdi,0x1
   c:          add    rsi,0x2
  10:          movsx  ax,BYTE PTR [rdi]
  14:          test   ax,ax
  17:          mov    WORD PTR [rsi],ax
  1a:          jne    8 
  1c:          repz ret
  1e:          xchg   ax,ax

Reslove

将单字节扩展为双字节,带符号

void f(char *a1, char *a2){
    char tmp;
    i = 0;
    k = 0;
    
    do{
        tmp = a1[i];
        
        if(tmp >= 0){
            a2[i] = 0;
        }else{
            a2[i] = -1;
        }
    
        a2[i+1] = tmp;

        i += 1;
        k += 2;
    }while(tmp != '\0');
}

PS1: 汇编代码的优化很好,使用C编写后反而很不优雅。 PS2: 不要在意参数的类型。这里的代码仅仅是体现了一下逻辑,和汇编不完全等价。

Table of Contents