[8] 어셈블리 반복문 연습

2017. 10. 24. 21:28SystemHacking/Assembly

 

 

C언어 반복문을 어셈블리로 직접 작성해보자


[ C언어 ]

- 문자열의 끝을 파악해서 문자개수를 세고, 문자열의 뒤에서부터 출력한다


 str buffer[1024] ;
 int index ;
 int i=0 ;
 int main(){

  scanf("%s",string);

  while( string[i] != null ){
   i++;
  }


  index--;

  for( i=index; i >= 0 ; i-- ){
   printf("%c",string[i]);
  }


  printf("\n");
  return 0;

}


 

[ 어셈블리 ]


 str string[1024];
 int index;
 int i=0;
 scanf("%s",string);

 while( string[i] != null ){
   i++;
 }
 

index = i;

 while( i < 0 ){
  printf("%c",string[i]);
  i--;
}


extern gets

section .data
prompt_str db '%s',00
print_chr db '%c',00
print_new db 10,00

section .bss
buffer: resb    1024
len:    resd    1
i:      resd    1

section .text
global  main
main:
        push    buffer
        push    prompt_str
        call    scanf                                           ; scanf("%s", buffer )

while:
        mov    edx,    dword [len]                        ; edx 레지스터에 문자 개수를 입력
        cmp    byte [buffer + edx],    0                 ; 문자열의 문자가 NULL 인지 확인( 문자열의 끝을 확인 )

        jz       while_end                                      ; Jump Zero, 두 비교값이 같으면 Jump !

        inc     dword [len]                                   ; jz가 실행되지 않아 코드가 순서대로 진행 ( +1 )
        jmp    while                                          ; while 레이블로 이동 ( 반복 )

while_end:
        dec     dword [len]                        
        mov    edx,    dword [len]                       ; 문자열의 끝을 찾았고, len 주소에는 문자 개수가 들어있다
        mov    eax,    [buffer + edx]                    ; edx에 문자개수를 입력했고, buffer 주소에서 해당 문자의 위치로 이동

                                                                 ; eax 레지스터에 문자의 뒤에서부터 한글자씩 입력되어진다

        push    eax                          
        push    print_chr
        call      printf
        push    print_new
        call      printf

        cmp     dword [len],    0                         ; 인덱스와 0 을 비교, 문자의 처음으로 도착했다면
        jz        end                                          ;  Jump Zero -> 반복문 종료
        jmp     while_end                                  ; JZ 미실행, while_end레이블로 이동 ( 반복 )

end:


 


[ 코드 실행 결과 ]