[Reversing] Helloworld.c 분석

‍허진·2023년 3월 21일
0

hacking

목록 보기
3/7

리버싱을 시작하면서 간단한 코드를 분석해보겠다.

Hello World를 출력하는 c코드이다.

#include <stdio.h>

int main(){
    printf("Hello World\n");
}

위와 같이 컴파일하였다.

이제 gdb를 이용하여 분석해보자.

main 함수를 disassemble한 결과는 다음과 같았다.

이 코드는 prinf 함수를 실행하는 간단한 코드이기에 복잡한 것은 없었다.

main+8 줄에서 rdi에 문자열을 저장하게 되는 것을 확인할 수 있다.

rdi에 'Hello World'라는 문자열을 가리키는 주소가 저장되어 있다.

x/s 명령어로 문자열을 확인할 수 있었다.

그 다음에 call 명령어로 puts 함수를 호출하여 Hello World를 출력한다.

여기서 왜 printf 함수를 썼는데 puts를 호출하는지 궁금해서 chatgpt에게 물어보았더니 대답을 해주었다.

It's possible that the compiler or linker optimized your code and replaced the printf call with a call to puts. This can happen if the compiler or linker determines that your printf call does not actually require any format specifiers, or if it determines that the format string is a constant string.
This is because the format string passed to printf does not contain any format specifiers (such as %s or %d), so the compiler has determined that it can safely replace the printf call with a call to puts.
If you want to ensure that a printf call is not optimized to puts, you can add a format specifier to the format string. For example, if you change the code above to use %s in the format string, the printf call will not be optimized:

해석하자면, 내가 "Hello World"라는 문자열만 출력하고자 했기에 인자를 받지 않는 puts를 호출한 것이다. 즉, printf에 포맷 지정자를 전달하지 않으면 puts가 호출되는 구조인 것 같다.

profile
매일 공부하기 목표 👨‍💻 

0개의 댓글