您的位置:首页 > 运维架构 > Linux

Linux系统调用程序分析

2015-03-25 20:40 459 查看
当用户态进程调用一个系统调用时,CPU切换为内核态,并开始执行一个内核函数;

在Linux中是通过执行int $0x80来执行系统调用,这条汇编指令产生向量为128的编程异常。

内核实现了很多不同的系统调用,进程需要指明系统调用号作为参数进行调用,使用eax寄存器。

寄存器传参数有如下限制:

1> 每个参数的长度不能超过寄存器的长度,即32位;

2> 在系统调用号(eax)之外,参数的个数不能超过6个(ebx,ecx,edx,esi,edi,ebp)。

下面通过对getpid系统调用函数从调用API和汇编方式进行分析:

<span style="font-size:18px;">#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
pid_t pid;

pid = getpid();
printf("The pid of this program is %d\n", pid);

return 0;
}</span>
<span style="font-size:18px;">#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
pid_t pid;

//the first arg use %ebx,here not have input arg.
asm volatile
(
<span style="white-space:pre">	</span>"mov $0x14,%%eax\n\t"
"int $0x80\n\t"
"movl %%eax,%0\n\t"
: "+r" (pid)
);
printf("The pid of this program is %d\n", pid);

return 0;
}</span>


getpid的系统调用号为20,参考http://codelab.shiyanlou.com/xref/linux-3.18.6/arch/x86/syscalls/syscall_32.tbl,或者linux中的/usr/include/x86_64-linux-gnu/asm/unistd_32.h。

author: 于凯

参考课程:《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: