1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use byteorder::{ByteOrder, LittleEndian};
use std::convert::TryFrom;
#[derive(Debug)]
pub struct ImpossibleRelocation { }
pub trait Relocation {
type Encoding;
fn from_encoding(encoding: Self::Encoding) -> Self;
fn from_size(size: RelocationSize) -> Self;
fn size(&self) -> usize;
fn write_value(&self, buf: &mut [u8], value: isize) -> Result<(), ImpossibleRelocation>;
fn read_value(&self, buf: &[u8]) -> isize;
fn kind(&self) -> RelocationKind;
fn page_size() -> usize;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelocationKind {
Relative = 0,
AbsToRel = 1,
RelToAbs = 2,
}
impl RelocationKind {
pub fn from_encoding(encoding: u8) -> Self {
match encoding {
0 => Self::Relative,
1 => Self::AbsToRel,
2 => Self::RelToAbs,
x => panic!("Unsupported relocation kind {}", x)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelocationSize {
Byte = 1,
Word = 2,
DWord = 4,
QWord = 8,
}
impl Relocation for RelocationSize {
type Encoding = u8;
fn from_encoding(encoding: Self::Encoding) -> Self {
match encoding {
1 => RelocationSize::Byte,
2 => RelocationSize::Word,
4 => RelocationSize::DWord,
8 => RelocationSize::QWord,
x => panic!("Unsupported relocation size {}", x)
}
}
fn from_size(size: RelocationSize) -> Self {
size
}
fn size(&self) -> usize {
*self as usize
}
fn write_value(&self, buf: &mut [u8], value: isize) -> Result<(), ImpossibleRelocation> {
match self {
RelocationSize::Byte => buf[0] =
i8::try_from(value).map_err(|_| ImpossibleRelocation { } )?
as u8,
RelocationSize::Word => LittleEndian::write_i16(buf,
i16::try_from(value).map_err(|_| ImpossibleRelocation { } )?
),
RelocationSize::DWord => LittleEndian::write_i32(buf,
i32::try_from(value).map_err(|_| ImpossibleRelocation { } )?
),
RelocationSize::QWord => LittleEndian::write_i64(buf,
i64::try_from(value).map_err(|_| ImpossibleRelocation { } )?
),
}
Ok(())
}
fn read_value(&self, buf: &[u8]) -> isize {
match self {
RelocationSize::Byte => buf[0] as i8 as isize,
RelocationSize::Word => LittleEndian::read_i16(buf) as isize,
RelocationSize::DWord => LittleEndian::read_i32(buf) as isize,
RelocationSize::QWord => LittleEndian::read_i64(buf) as isize,
}
}
fn kind(&self) -> RelocationKind {
RelocationKind::Relative
}
fn page_size() -> usize {
4096
}
}
pub(crate) fn fits_signed_bitfield(value: i64, bits: u8) -> bool {
if bits >= 64 {
return true;
}
let half = 1i64 << (bits - 1);
value < half && value >= -half
}