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