请选择 进入手机版 | 继续访问电脑版

马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

一个关于内联优化和调用约定的Bug

[复制链接]
查看2135 | 回复0 | 2019-10-24 09:48:47 | 显示全部楼层 |阅读模式

很久没有更新博客了(博客园怎么还不更新后台),前几天在写一个Linux 0.11的实行 [1] 时遇到了一个奇葩的Bug,就在这简单记载一下调试过程吧。


现象

这个实行要求在Linux 0.11中实现简单的信号量 [2],但在改动内核代码后运行测试步调总是报错,比方:

  1. <code>/* pc_test.c */
  2. #define __LIBRARY__
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <semaphore.h>
  6. #include <unistd.h>
  7. _syscall2(long, sem_open, const char *, name, unsigned int, value);
  8. _syscall1(int, sem_unlink, const char *, name);
  9. int main(void)
  10. {
  11. sem_t *mutex;
  12. if ((mutex = (sem_t *) sem_open("mutex", 1)) == (sem_t *)-1)
  13. {
  14. perror("opening mutex semaphore");
  15. return EXIT_FAILURE;
  16. }
  17. sem_unlink("mutex");
  18. return EXIT_SUCCESS;
  19. }
  20. </code>
复制代码

提示为段错误:

094847wlxnc8gpnzcljxkj.png


定位

在内核实现信号量的核心代码 sem.c 中插桩调试,终极把发生段错误的位置定在探求已存在信号量的 find_sem 函数中:

  1. <code>/*
  2. 以下注释部分是semaphore.h中我定义的链表结构体
  3. #define MAXSEMNAME 128
  4. struct sem_t
  5. {
  6. char m_name[MAXSEMNAME+1];
  7. unsigned long m_value;
  8. struct sem_t * m_prev;
  9. struct sem_t * m_next;
  10. struct task_struct * m_wait;
  11. };
  12. typedef struct sem_t sem_t;
  13. #define SEM_FAILED ((sem_t *)-1)
  14. */
  15. // Data structure optimization is possible here
  16. sem_t _semHead={.m_name = "_semHead", .m_value = 0, .m_prev = NULL,\
  17. .m_next = NULL, .m_wait = NULL};
  18. sem_t *find_sem(const char* name)
  19. {
  20. sem_t *tmpSemP = &_semHead;
  21. while (tmpSemP->m_next != NULL)
  22. {
  23. if (strcmp((tmpSemP->m_name), name) == 0)
  24. {
  25. return tmpSemP;
  26. }
  27. tmpSemP = tmpSemP->m_next;
  28. }
  29. return tmpSemP;
  30. }</code>
复制代码


由于该函数中存在 P->member 这样的解引用操纵,很大概率就是P的值出了题目,以是就在P对应的操纵附近加上 printk ,判定是否进一步定位Bug:

  1. <code>sem_t *find_sem(const char* name)
  2. {
  3. printk("Now we are in find_sem\n"); // DEBUG
  4. sem_t *tmpSemP = &_semHead;
  5. while (tmpSemP->m_next != NULL)
  6. {
  7. printk("find_sem: tmpSemp before strcmp: %p\n", tmpSemP);
  8. if (strcmp((tmpSemP->m_name), name) == 0)
  9. {
  10. printk("find_sem: tmpSemp after strcmp: %p\n", tmpSemP); // DEBUG
  11. printk("find_sem: return...\n\n"); // DEBUG
  12. return tmpSemP;
  13. }
  14. printk("find_sem: tmpSemp after strcmp: %p\n\n", tmpSemP); // DEBUG
  15. tmpSemP = tmpSemP->m_next;
  16. }
  17. printk("find_sem: return...\n\n"); // DEBUG
  18. return tmpSemP;
  19. }</code>
复制代码


重新编译内核,再次运行上面的 pc_test.c ,希奇的事变发生了:

094848mtl644n48gdqv887.png

可以看到,第一次进入 find_sem 并没有发生段错误,这是由于第一次调用 sem_open 的时间内核中还没有信号量,以是 tmpSemP->m_next != NULL 不成立,但是第二次和第三次进入 find_semtemSemP 的值却在 strcmp(tmpSemP->m_name, name) 前后发生了改变。我们知道,C中的函数参数是“按值转达”的,如果编译器真的把strcmp 按照C函数的规则编译,那么转达 m_name 的值, tmpSemP 的值是不可能改变的。以是如今的结论是, string.h 中定义的 strcmp 很可能出了题目。


复现

为了更好的分析和调试,我将 string.h , semaphore.hsem.c 中的 find_sem 关键代码拿出来,精简后在用户态举行Bug复现:

  1. <code>/* test.c */
  2. #include <stdio.h>
  3. // string.h
  4. inline int strcmp(const char * cs,const char * ct)
  5. {
  6. register int __res ;
  7. __asm__("cld\n"
  8. "1:\tlodsb\n\t"
  9. "scasb\n\t"
  10. "jne 2f\n\t"
  11. "testb %%al,%%al\n\t"
  12. "jne 1b\n\t"
  13. "xorl %%eax,%%eax\n\t"
  14. "jmp 3f\n"
  15. "2:\tmovl $1,%%eax\n\t"
  16. "jl 3f\n\t"
  17. "negl %%eax\n"
  18. "3:"
  19. :"=a" (__res):"D" (cs),"S" (ct));
  20. return __res;
  21. }
  22. //semaphore.h
  23. typedef struct sem_t
  24. {
  25. char m_name[128];
  26. struct sem_t *m_next;
  27. } sem_t;
  28. //sem.c
  29. int main(void)
  30. {
  31. sem_t _semRear={.m_name = "_semRear", .m_next = (sem_t *)0};
  32. sem_t _semHead={.m_name = "_semHead", .m_next = &_semRear};
  33. sem_t *tmpSemP = &_semHead;
  34. char name[] = "test";
  35. while (tmpSemP->m_next != (sem_t *)0)
  36. {
  37. printf("1. tempSemP: %p\n", tmpSemP);
  38. if(!strcmp((tmpSemP->m_name), name))
  39. return 0;
  40. printf("2. tempSemP: %p\n", tmpSemP);
  41. tmpSemP = tmpSemP->m_next;
  42. }
  43. return 0;
  44. }</code>
复制代码


Bug复现:

094848q7u5sztqjadh7shd.png


分析

我们起首分析一下 strcmp 的实现:

  1. <code>extern inline int strcmp(const char * cs,const char * ct)
  2. {
  3. register int __res ; // 寄存器变量
  4. __asm__("cld\n" // 整理方向位
  5. "1:\tlodsb\n\t" // 将ds:[esi]存入al,esi++
  6. "scasb\n\t" // 比较al与es:[edi],edi++
  7. "jne 2f\n\t" // 若不等,向下跳转到2标记
  8. "testb %%al,%%al\n\t" // 测试al寄存器
  9. "jne 1b\n\t" // 若al不为0,则向上跳转到1标记
  10. "xorl %%eax,%%eax\n\t" // 若al为零,则清空eax(返回值)
  11. "jmp 3f\n" // 向下跳转到3标记返回
  12. "2:\tmovl $1,%%eax\n\t" // eax置为1
  13. "jl 3f\n\t" // 若上面的比较al更小,则这里返回正值(1)
  14. "negl %%eax\n\t" // 否则eax = -1 返回负值
  15. "3:"
  16. :"=a" (__res):"D" (cs),"S" (ct)); // 规定edi寄存器吸收cs参数的值,esi吸收ct参数的值,终极将eax的值输出到__res寄存器变量中
  17. return __res; // 返回__res
  18. }</code>
复制代码


如上,为了性能优化, strcmp 使用了内联优化(函数和汇编),是代码还是编译器的锅呢?拖入IDA,静态分析一下:

094849axulfuflvldfx1pp.png


编译器忠实的保存了内联汇编的语句。通过 __printf_chk 的参数,我们知道进入控制流进入 strcmp 之前和之后编译器都把 tempSemP 放在寄存器 edi 中,而且由于信号量结构体的第一个成员就是 m_name :

  1. <code>//semaphore.h
  2. typedef struct sem_t
  3. {
  4. char m_name[128];
  5. struct sem_t *m_next;
  6. } sem_t;</code>
复制代码

m_name 又是一个数组名,以是 tmpSemP->m_nametmpSemP 就值而言是雷同的。由于内联汇编规定使用 edi 作为第一个参数的输入寄存器,以是编译器为了优化,起首就将 tempSemP 放在寄存器 edi ,这样背面进入 strcmp 的时间就不必要再次改变 edi 了 。


但是,内联汇编的代码中明显有 scasb [3] ,其会在比较操纵后更改 edi 的值,岂非编译器不知道吗?通过查阅GCC文档关于内联汇编的说明 [4]:

  1. <code>asm asm-qualifiers ( AssemblerTemplate
  2. : OutputOperands
  3. [ : InputOperands
  4. [ : Clobbers ] ])</code>
复制代码

6.47.2.6 Clobbers and Scratch Registers

While the compiler is aware of changes to entries listed in the output operands, the inline asm code may modify more than just the outputs. For example, calculations may require additional registers, or the processor may overwrite a register as a side effect of a particular assembler instruction. In order to inform the compiler of these changes, list them in the clobber list. Clobber list items are either register names or the special clobbers (listed below). Each clobber list item is a string constant enclosed in double quotes and separated by commas.

Clobber descriptions may not in any way overlap with an input or output operand….


文档说明白对于汇编语句中被修改但是不在 InputOperands中的寄存器,应该在 Clobbers 中写出,不然编译器不知道哪些寄存器(Bug这里是 edi )被修改,也就可能在优化的过程中堕落了。


回到 strcmp 的代码,最后一行是:"=a" (__res):"D" (cs),"S" (ct)); ,而scasblodsb [5] 修改的又是 edi , esi 。根据上面文档的说明, clobbers 不能与输入输出位置的操纵数重复,以是如果这里在 clobbers 的位置放上 edi , esi 就会报错:

094849ya2aoalojnga2jqa.png

(这个步调员)为了编译通过,在 clobbers 的位置便没有放上 edi , esi ,大部分环境下都没有题目,但是如果编译器在优化的过程中依靠于 strcmp 不改变 edi , esi ,就可能出现Bug。


试验

如今我们从理论上发现了Bug的成因,下面我们做个试验验证一下。由于该Bug是由于tmpSemP->m_nametmpSemP 就值而言是雷同,才导致 tmpSemP 变量中心存储和 tmpSemP->m_name 传参使用了雷同的寄存器 edi ,我们可以改变结构体成员的排列,制止这种特定的优化方式,应该就会在测试步调中制止bug,比方:

  1. <code>typedef struct sem_t
  2. {
  3. struct sem_t * m_next;
  4. char m_name[128];
  5. } sem_t;</code>
复制代码

再次运行,报错消散:

094850ignlv9lcblevzlfn.png

再次在IDA中观察:

094850v9x2lkhtewlifh0r.png

可见,这里在调用第一个 __printf_chk 的时间 tempSemP 是放在 ecx 而非 edi 中,而第二个 __printf_chk 是使用之前放在 edx 中的 tempSemP 而非 edi ,确实制止了这种优化。


但是,一个新的题目出现了,根据x86调用约定(Calling Convention), ecxedx 是 Caller-saved (volatile) registers [6] ,即调用者不能依靠被调用函数包管它们的值不变,那 GCC 为什么就使用这两个寄存器作为 strcmp 调用前后 tempSemP 的值呢?


着实,在 GCC 文档中对于 inline function 提到了这么一句 [7]:

This combination of inline and extern has almost the effect of a macro. The way to use it is to put a function definition in a header file with these keywords, and put another copy of the definition (lacking inline and extern) in a library file. The definition in the header file will cause most calls to the function to be inlined. If any uses of the function remain, they will refer to the single copy in the library.

也就是说,在使用 inlineextern 修饰的函数时,GCC将其几乎(almost)和宏一样处理,可能也就不再根据调用约定优化了。


管理

管理思路有两种。


一是告知编译器哪些寄存器不能依靠(volatile),大概直接使用非汇编的写法,让编译器去安排。比方我们可以创建一个 string_fix.h ,在C上实实际现一个 strCmp

  1. <code>#ifndef _STRING_FIX_H_
  2. #define _STRING_FIX_H_
  3. /*
  4. * This header file is for fixing bugs caused by inline assembly
  5. * in string.h.
  6. */
  7. int strCmp(const char* s1, const char* s2)
  8. {
  9. while(*s1 && (*s1 == *s2))
  10. {
  11. s1++;
  12. s2++;
  13. }
  14. return *(const unsigned char*)s1 - *(const unsigned char*)s2;
  15. }
  16. #endif
  17. </code>
复制代码


二是手动在原来的内联汇编中生存被修改的寄存器,比方:

  1. <code>extern inline int strcmp(const char * cs,const char * ct)
  2. {
  3. register int __res ;
  4. __asm__("push %%edi\n\tpush %%esi\n\t"
  5. "cld\n\t"
  6. "1:\tlodsb\n\t"
  7. "scasb\n\t"
  8. "jne 2f\n\t"
  9. "testb %%al,%%al\n\t"
  10. "jne 1b\n\t"
  11. "xorl %%eax,%%eax\n\t"
  12. "jmp 3f\n"
  13. "2:\tmovl $1,%%eax\n\t"
  14. "jl 3f\n\t"
  15. "negl %%eax\n\t"
  16. "3:\n\t"
  17. "pop %%esi\n\tpop %%edi\n"
  18. :"=a" (__res):"D" (cs),"S" (ct));
  19. return __res;
  20. }</code>
复制代码


测试及后续不再展示。


后记

这真的是Linus Torvalds [8] 写的代码吗?我试着在网上找到了一份看似权势巨子的代码 [9],结果其中的 strcmp 如下:

  1. <code>
  2. extern inline int strcmp(const char * cs,const char * ct)
  3. {
  4. register int __res __asm__("ax");
  5. __asm__("cld\n"
  6. "1:\tlodsb\n\t"
  7. "scasb\n\t"
  8. "jne 2f\n\t"
  9. "testb %%al,%%al\n\t"
  10. "jne 1b\n\t"
  11. "xorl %%eax,%%eax\n\t"
  12. "jmp 3f\n"
  13. "2:\tmovl $1,%%eax\n\t"
  14. "jl 3f\n\t"
  15. "negl %%eax\n"
  16. "3:"
  17. :"=a" (__res):"D" (cs),"S" (ct):"si","di");
  18. return __res;
  19. }</code>
复制代码

Linus Torvalds明白了 Clobberssidi ,或许谁人时间的GCC没有 Clobbers 不能和 InOutputOperands 重叠这个限定吧。


比较大的可能性是如今的人在研究的过程中为了方便编译,将 Clobbers 直接做了删除,比方下面几篇文章都提到了这种方法:

Ubuntu15.10邂逅linux0.11

linux环境下编译linux0.11内核

linux0.12 编译过程


同时,在这篇文章中指出 [10] ,Linux 0.1x 中这种因 Clobbers 无法通过现代编译器文件还有:

  • include/linux/sched.h: set_base,set_limit
  • include/string.h :strcpy, strncpy,strcat,strncat,strcmp,strncmp,strchr, strrchr,strspn,strcspn,strpbrk,strstr,memcpy,memmove,memcmp,memchr,
  • mm/memory.c:copy_page,get_free_page
  • fs/buffer.c:COPY_BLK
  • fs/namei.c:match
  • fs/bitmap.c:clear_block,find_first_zero
  • kernel/blk_drv/floppy.c:copy_buffer
  • kernel/blk_drv/hd.c:port_read,port_write
  • kernel/chr_drv/console.c:scrup,scrdown,csi_J,csi_K,con_write


参考

[1] HIT-OSLAB-MANUAL

[2] Semaphore (programming)

[3] SCASB

[4] 6.47 How to Use Inline Assembly Language in C Code

[5] lodsb

[6] Register_preservation

[7] 5.34 An Inline Function is As Fast As a Macro

[8] Linus Torvalds

[9] Linux 0.11 source

[10] 64位Debian Sid下编译Linux 0.11内核







来源:https://www.cnblogs.com/liqiuhao/p/11728440.html
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则