我试图用直接系统调用来调用mmap。
#include <sys/mman.h>
int main() {
__asm__("mov $0x0, %r9;"
"mov $0xffffffffffffffff, %r8;"
"mov $0x32, %rcx;"
"mov $0x7, %rdx;"
"mov $0x1000, %rsi;"
"mov $0x303000, %rdi;"
"mov $0x9, %rax;"
"syscall;");
return 0;
}
我静态地编译了程序:
$ gcc -static -o foo foo.c
但系统调用失败,如strace所示:
$ strace ./foo
mmap(0x303000, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, -1, 0) = -1 EBADF (Bad file descriptor)
我们可以看到错误地设置了mmap标志。 0x32应该是MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS。问题是,如果我使用libc中的mmap调用另一个mmap:
int main() {
mmap(0x202000, 4096, 0x7, 0x32, -1, 0);
__asm__("mov $0x0, %r9;"
"mov $0xffffffffffffffff, %r8;"
"mov $0x32, %rcx;"
"mov $0x7, %rdx;"
"mov $0x1000, %rsi;"
"mov $0x303000, %rdi;"
"mov $0x9, %rax;"
"syscall;");
return 0;
}
然后两个mmap工作:
$ strace ./foo
mmap(0x202000, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x202000
mmap(0x303000, 4096, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x303000
所以似乎使用libc,mmap标志是“解决”的东西。但我真的不明白发生了什么。
为什么mmap系统调用示例只有在我之前调用libc mmap时才有效?