2016年8月26日 星期五

[Linux] C語言 - Hello World

前言

剛好今天上完台大 sean 講的課

來用 c 寫一個 Hello World 玩一下


先寫一個 hello.asm

 jmp hello
se:
 push 0x4
 push 0xb
 pop edx
 pop eax
 pop ecx
 xor ebx,ebx
 int 0x80
 ret
hello:
 call se
 db 'Hello World',0

編譯 + 解釋一下

$ nasm -felf32 hello.asm -o hello.o
$ objcopy -O binary hello.o hello.bin
$ xxd -i hello.bin > hello.h

其實還可以再加 ld -melf_i386 hello.o -o hello
然後執行 hello 來看有沒有錯誤

然後 hello.asm 的目的是要 呼叫 linux 的 syscall 
write(0,"Hello World",11) ## 11 指字串長度
故我們要設定 register:
  eax = 4 (write 的 syscall )
  ebx = 0
  ecx = "Hello World"
  edx = 11
上面都 ok 就可以來個講單的 hello world in C 語言
// hello_world.c
#include "hello.h"

typedef int (*FUNC)();
int main(){
    ((FUNC)hello_bin)();
}

編譯:
$ gcc -fno-stack-protector -z execstack hello_world.c -o hello_world
$ ./hello_world
Hello World

附一下 hello.h

unsigned char hello_bin[] = {
  0xeb, 0x0c, 0x6a, 0x04, 0x6a, 0x0b, 0x5a, 0x58, 0x59, 0x31, 0xdb, 0xcd,
  0x80, 0xc3, 0xe8, 0xef, 0xff, 0xff, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
  0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x00
};
unsigned int hello_bin_len = 31;
用不同的方式還蠻有趣的

沒有留言:

張貼留言

Triton/Trisis

紀錄網路上蒐集整理的內容