今天不拐彎抹角蚌卤,直接驗證一下淺嘗輒止23-Linux系統(tǒng)調(diào)用1里面的說法。
繞過glibc
我們平時用的系統(tǒng)調(diào)用是glibc封裝的(如果是Android平臺奥秆,就是bionic)逊彭,下面就來驗證一下glibc里面看到的調(diào)用system call的方法。
可以看下面代碼中#if defined(__arm__) && !defined(__thumb__)
和#endif
包住的部分构订,這個測試只適合用ARM32并且使用ARM指令(非thumb)的平臺侮叮。
代碼演示
以下代碼未經(jīng)測試,只能保證用-marm
編譯選項可以編譯通過悼瘾。因為現(xiàn)在手上的設(shè)備是跑thumb指令的囊榜,相對于我在跑arm指令的平臺上驗證的代碼(驗證過),有些修改亥宿。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#if defined(__arm__) && !defined(__thumb__)
#include <linux/unistd.h>
int three_paramter_syscall_wrapper(int nr, int p0, int p1, int p2){
register int _p0 asm("r0") = p0;
register int _p1 asm("r1") = p1;
register int _p2 asm("r2") = p2;
register int _nr asm("r7") = nr;
asm volatile(
"swi 0x0"
:"=r" (_p0)
:"r" (_nr), "r" (_p0), "r" (_p1), "r" (_p2)
:"memory"
);
return _p1;
}
int my_write(int fd, void *buf, size_t count){
return three_paramter_syscall_wrapper(__NR_write, fd, (int)buf, (int)count);
}
int my_read(int fd, void *buf, size_t count){
return three_paramter_syscall_wrapper(__NR_read, fd, (int)buf, (int)count);
}
int my_lseek(int fd, off_t offset, int whence){
return three_paramter_syscall_wrapper(__NR_lseek, fd, (int)offset, whence);
}
#endif
int main(int argc, char **argv){
int tmp;
int syscall = 1234;
int my_syscall = 5678;
int ret = -1;
int fd = open("./tmp", O_CREAT | O_RDWR);
printf("\n[Standard] system call:\n");
ret = write(fd, &syscall, sizeof(syscall));
printf("write %dB\n", ret);
ret = lseek(fd, 0, SEEK_SET);
printf("lseek %d\n", ret);
ret = read(fd, &tmp, sizeof(tmp));
printf("read %dB [%d]\n", ret, tmp);
ret = lseek(fd, 0, SEEK_SET);
printf("lseek %d\n", ret);
#if defined(__arm__) && !defined(__thumb__)
printf("\n[My] system call:\n");
ret = my_write(fd, &syscall, sizeof(syscall));
printf("write %dB\n", ret);
ret = my_lseek(fd, 0, SEEK_SET);
printf("lseek %d\n", ret);
ret = my_read(fd, &tmp, sizeof(tmp));
printf("read %dB [%d]\n", ret, tmp);
ret = my_lseek(fd, 0, SEEK_SET);
printf("lseek %d\n", ret);
#else
printf("Please use arm32 platform to test!\n", ret);
#endif
unlink("./tmp");
return 0;
}
輸出
后一半輸出是預(yù)計在跑arm指令的平臺上運行的結(jié)果卸勺。
[Standard] system call:
write 4B
lseek 0
read 4B [1234]
lseek 0
[My] system call:
write 4B
lseek 0
read 4B [5678]
lseek 0