6xxx strlen and 9xxx conclusions.
[libguestfs-talks.git] / 2020-frama-c / 6200-strlen-2.html
1 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
2 <link rel="stylesheet" href="style.css" type="text/css"/>
3 <script src="code.js" type="text/javascript"></script>
4
5 <h1>glibc strlen (part 2)</h1>
6
7 <pre class="code">
8   const unsigned long int *longword_ptr;
9   unsigned long int longword, himagic, lomagic;
10
11   longword_ptr = (unsigned long int *) char_ptr;
12
13   himagic = 0x80808080L;
14   lomagic = 0x01010101L;
15   himagic = ((himagic << 16) << 16) | himagic;
16   lomagic = ((lomagic << 16) << 16) | lomagic;
17
18   for (;;)
19     {
20       longword = *longword_ptr++;
21
22       if (((longword - lomagic) & ~longword & himagic) != 0)
23         {
24           <span class="comment">/* Which of the bytes was the zero?  If none of them were, it was
25              a misfire; continue the search.  */</span>
26
27           const char *cp = (const char *) (longword_ptr - 1);
28
29           if (cp[0] == 0)
30             return cp - str;
31           if (cp[1] == 0)
32             return cp - str + 1;
33           if (cp[2] == 0)
34             return cp - str + 2;
35           if (cp[3] == 0)
36             return cp - str + 3;
37           if (sizeof (longword) > 4)
38             {
39               if (cp[4] == 0)
40                 return cp - str + 4;
41               if (cp[5] == 0)
42                 return cp - str + 5;
43               if (cp[6] == 0)
44                 return cp - str + 6;
45               if (cp[7] == 0)
46                 return cp - str + 7;
47             }
48         }
49     }
50 }
51 </pre>