Fri, 16 Jan 2015 18:13:44 +0100
Integrate suggestion from review to improve consistency with existing code.
1 /* BranchX86.c */
3 #include "BranchX86.h"
5 /*
6 static int inline Test86MSByte(Byte b)
7 {
8 return (b == 0 || b == 0xFF);
9 }
10 */
11 #define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)
13 const int kMaskToAllowedStatus[8] = {1, 1, 1, 0, 1, 0, 0, 0};
14 const Byte kMaskToBitNumber[8] = {0, 1, 2, 2, 3, 3, 3, 3};
16 /*
17 void x86_Convert_Init(UInt32 *prevMask, UInt32 *prevPos)
18 {
19 *prevMask = 0;
20 *prevPos = (UInt32)(-5);
21 }
22 */
24 UInt32 x86_Convert(Byte *buffer, UInt32 endPos, UInt32 nowPos,
25 UInt32 *prevMask, UInt32 *prevPos, int encoding)
26 {
27 UInt32 bufferPos = 0;
28 UInt32 limit;
30 if (endPos < 5)
31 return 0;
33 if (nowPos - *prevPos > 5)
34 *prevPos = nowPos - 5;
36 limit = endPos - 5;
37 while(bufferPos <= limit)
38 {
39 Byte b = buffer[bufferPos];
40 UInt32 offset;
41 if (b != 0xE8 && b != 0xE9)
42 {
43 bufferPos++;
44 continue;
45 }
46 offset = (nowPos + bufferPos - *prevPos);
47 *prevPos = (nowPos + bufferPos);
48 if (offset > 5)
49 *prevMask = 0;
50 else
51 {
52 UInt32 i;
53 for (i = 0; i < offset; i++)
54 {
55 *prevMask &= 0x77;
56 *prevMask <<= 1;
57 }
58 }
59 b = buffer[bufferPos + 4];
60 if (Test86MSByte(b) && kMaskToAllowedStatus[(*prevMask >> 1) & 0x7] &&
61 (*prevMask >> 1) < 0x10)
62 {
63 UInt32 src =
64 ((UInt32)(b) << 24) |
65 ((UInt32)(buffer[bufferPos + 3]) << 16) |
66 ((UInt32)(buffer[bufferPos + 2]) << 8) |
67 (buffer[bufferPos + 1]);
69 UInt32 dest;
70 while(1)
71 {
72 UInt32 index;
73 if (encoding)
74 dest = (nowPos + bufferPos + 5) + src;
75 else
76 dest = src - (nowPos + bufferPos + 5);
77 if (*prevMask == 0)
78 break;
79 index = kMaskToBitNumber[*prevMask >> 1];
80 b = (Byte)(dest >> (24 - index * 8));
81 if (!Test86MSByte(b))
82 break;
83 src = dest ^ ((1 << (32 - index * 8)) - 1);
84 }
85 buffer[bufferPos + 4] = (Byte)(~(((dest >> 24) & 1) - 1));
86 buffer[bufferPos + 3] = (Byte)(dest >> 16);
87 buffer[bufferPos + 2] = (Byte)(dest >> 8);
88 buffer[bufferPos + 1] = (Byte)dest;
89 bufferPos += 5;
90 *prevMask = 0;
91 }
92 else
93 {
94 bufferPos++;
95 *prevMask |= 1;
96 if (Test86MSByte(b))
97 *prevMask |= 0x10;
98 }
99 }
100 return bufferPos;
101 }