[关闭]
@gain 2016-03-23T08:41:20.000000Z 字数 980 阅读 1683

week4-使用库函数API和C代码中嵌入汇编代码两种方式使用同一个系统调用

Linux内核 Linux 操作系统


@干宇航
原创作品转载请注明出处 《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000

实验环境:
Ubuntu 32bit 15.10

选择用系统调用exit,系统调用号0x1

c代码,来自cppprefernce.com

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(void)
  4. {
  5. FILE *fp = fopen("data.txt","r");
  6. if (fp == NULL) {
  7. fprintf(stderr, "error opening file data.txt in function main()\n");
  8. exit(1);
  9. }
  10. fclose(fp);
  11. printf("Normal Return\n");
  12. }

输出结果
error opening file data.txt in function main()

修改后的C内联汇编代码

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main(void)
  4. {
  5. FILE *fp = fopen("data.txt","r");
  6. if (fp == NULL) {
  7. fprintf(stderr, "error opening file data.txt in function main()\n");
  8. //exit(1);
  9. asm volatile(
  10. "mov $0x1,%ebx\n\t" ebx作为exit(1)中的参数1
  11. "mov $0x1,%eax\n\t" eax中储存的系统调用号1
  12. "int $0x80\n\t" 调用中断,进入内核态
  13. );
  14. }
  15. fclose(fp);
  16. printf("Normal Return\n");
  17. }

输出结果
error opening file data.txt in function main()

  1. asm volatile(
  2. "mov $0x1,%ebx\n\t" ebx作为exit(1)中的参数1
  3. "mov $0x1,%eax\n\t" eax中储存的系统调用号1
  4. "int $0x80\n\t" 调用中断,进入内核态
  5. );

总结:汇编代码调用系统调用时,ebx作为参数传入,然后eax是系统调用号。然后调用中断进入系统内核态。进入sys_exit,立即把eax的值压入内核栈。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注