1 /* BraIA64.c -- Converter for IA-64 code
2 2008-10-04 : Igor Pavlov : Public domain */
3 
4 #include "Bra.h"
5 
6 static const Byte kBranchTable[32] =
7 {
8   0, 0, 0, 0, 0, 0, 0, 0,
9   0, 0, 0, 0, 0, 0, 0, 0,
10   4, 4, 6, 6, 0, 0, 7, 7,
11   4, 4, 0, 0, 4, 4, 0, 0
12 };
13 
IA64_Convert(Byte * data,SizeT size,UInt32 ip,int encoding)14 SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding)
15 {
16   SizeT i;
17   if (size < 16)
18     return 0;
19   size -= 16;
20   for (i = 0; i <= size; i += 16)
21   {
22     UInt32 instrTemplate = data[i] & 0x1F;
23     UInt32 mask = kBranchTable[instrTemplate];
24     UInt32 bitPos = 5;
25     int slot;
26     for (slot = 0; slot < 3; slot++, bitPos += 41)
27     {
28       UInt32 bytePos, bitRes;
29       UInt64 instruction, instNorm;
30       int j;
31       if (((mask >> slot) & 1) == 0)
32         continue;
33       bytePos = (bitPos >> 3);
34       bitRes = bitPos & 0x7;
35       instruction = 0;
36       for (j = 0; j < 6; j++)
37         instruction += (UInt64)data[i + j + bytePos] << (8 * j);
38 
39       instNorm = instruction >> bitRes;
40       if (((instNorm >> 37) & 0xF) == 0x5 && ((instNorm >> 9) & 0x7) == 0)
41       {
42         UInt32 src = (UInt32)((instNorm >> 13) & 0xFFFFF);
43         UInt32 dest;
44         src |= ((UInt32)(instNorm >> 36) & 1) << 20;
45 
46         src <<= 4;
47 
48         if (encoding)
49           dest = ip + (UInt32)i + src;
50         else
51           dest = src - (ip + (UInt32)i);
52 
53         dest >>= 4;
54 
55         instNorm &= ~((UInt64)(0x8FFFFF) << 13);
56         instNorm |= ((UInt64)(dest & 0xFFFFF) << 13);
57         instNorm |= ((UInt64)(dest & 0x100000) << (36 - 20));
58 
59         instruction &= (1 << bitRes) - 1;
60         instruction |= (instNorm << bitRes);
61         for (j = 0; j < 6; j++)
62           data[i + j + bytePos] = (Byte)(instruction >> (8 * j));
63       }
64     }
65   }
66   return i;
67 }
68