这是一个现场面试问题,我很困惑。
我被要求为 linux 编写一个 Hello world 程序。这也是在不使用系统中的任何库的情况下。我想我必须使用系统调用或其他东西。代码应该使用 -nostdlib 和 -nostartfiles 选项运行。
如果有人能帮忙就好了。。
$ cat > hwa.S
write = 0x04
exit = 0xfc
.text
_start:
movl $1, %ebx
lea str, %ecx
movl $len, %edx
movl $write, %eax
int $0x80
xorl %ebx, %ebx
movl $exit, %eax
int $0x80
.data
str: .ascii "Hello, world!\n"
len = . -str
.globl _start
$ as -o hwa.o hwa.S
$ ld hwa.o
$ ./a.out
Hello, world!
看一下示例 4(不会因可移植性而获奖):
#include <syscall.h>
void syscall1(int num, int arg1)
{
asm("int\t$0x80\n\t":
/* output */ :
/* input */ "a"(num), "b"(arg1)
/* clobbered */ );
}
void syscall3(int num, int arg1, int arg2, int arg3)
{
asm("int\t$0x80\n\t" :
/* output */ :
/* input */ "a"(num), "b"(arg1), "c"(arg2), "d"(arg3)
/* clobbered */ );
}
char str[] = "Hello, world!\n";
int _start()
{
syscall3(SYS_write, 0, (int) str, sizeof(str)-1);
syscall1(SYS_exit, 0);
}
编辑:正如下面Zan Lynx所指出的, sys_write的第一个参数是文件描述符。因此,这段代码执行了写入 stdin (fd 0) 而不是 stdout (fd 1) 的"Hello, world!\n"
不常见的事情。
如以下链接中的示例所示,以纯汇编形式编写它怎么样?
http://blog.var.cc/blog/archive/2004/11/10/hello_world_in_x86_assembly__programming_workshop.html
.global _start
.text
_start:
mov $1, %rax
mov $1, %rdi
mov $yourText, %rsi
mov $13, %rdx
syscall
mov $60, %rax
xor %rdi, %rdi
syscall
yourText:
.ascii "Hello, World\n"
您可以使用以下命令组装和运行它gcc
:
$ vim hello.s
$ gcc -c hello.s && ld hello.o -o hello.out && ./hello.out
或使用as
:
$as hello.s -o hello.o && ld hello.o -o hello.out && ./hello.out
您必须直接与操作系统交谈。您可以write
通过执行以下操作来文件描述符 1 (stdout):
#include <unistd.h>
int main()
{
write(1, "Hello World\n", 12);
}
shell脚本呢?我在问题中没有看到任何编程语言要求。
echo "Hello World!"