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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//! The relocation package provide two structures: RelocSink, TrapSink.
//! This structures are used by Cranelift when compiling functions to mark
//! any other calls that this function is doing, so we can "patch" the
//! function addrs in runtime with the functions we need.
use cranelift_codegen::binemit;
use cranelift_codegen::ir::{self, ExternalName, SourceLoc};
use wasmer_runtime_core::{
    structures::TypedIndex,
    types::{FuncIndex, SigIndex},
};

pub mod call_names {
    pub const LOCAL_NAMESPACE: u32 = 1;
    pub const IMPORT_NAMESPACE: u32 = 2;
    pub const SIG_NAMESPACE: u32 = 3;

    pub const STATIC_MEM_GROW: u32 = 0;
    pub const STATIC_MEM_SIZE: u32 = 1;
    pub const SHARED_STATIC_MEM_GROW: u32 = 2;
    pub const SHARED_STATIC_MEM_SIZE: u32 = 3;
    pub const DYNAMIC_MEM_GROW: u32 = 4;
    pub const DYNAMIC_MEM_SIZE: u32 = 5;
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Eq)]
pub enum Reloc {
    Abs8,
    X86PCRel4,
    X86CallPCRel4,
}

#[derive(Serialize, Deserialize, Debug, Copy, Clone)]
pub enum LibCall {
    Probestack,
    CeilF32,
    CeilF64,
    FloorF32,
    FloorF64,
    TruncF32,
    TruncF64,
    NearestF32,
    NearestF64,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ExternalRelocation {
    /// The relocation code.
    pub reloc: Reloc,
    /// The offset where to apply the relocation.
    pub offset: binemit::CodeOffset,
    /// The addend to add to the relocation value.
    pub addend: binemit::Addend,
    /// Relocation type.
    pub target: RelocationType,
}

pub struct LocalRelocation {
    /// The offset where to apply the relocation.
    pub offset: binemit::CodeOffset,
    /// The addend to add to the relocation value.
    pub addend: binemit::Addend,
    /// Relocation type.
    pub target: FuncIndex,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum VmCallKind {
    StaticMemoryGrow,
    StaticMemorySize,

    SharedStaticMemoryGrow,
    SharedStaticMemorySize,

    DynamicMemoryGrow,
    DynamicMemorySize,
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum VmCall {
    Local(VmCallKind),
    Import(VmCallKind),
}

/// Specify the type of relocation
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum RelocationType {
    Intrinsic(String),
    LibCall(LibCall),
    VmCall(VmCall),
    Signature(SigIndex),
}

/// Implementation of a relocation sink that just saves all the information for later
pub struct RelocSink {
    /// Relocations recorded for the function.
    pub external_relocs: Vec<ExternalRelocation>,
    pub local_relocs: Vec<LocalRelocation>,
}

impl binemit::RelocSink for RelocSink {
    fn reloc_ebb(
        &mut self,
        _offset: binemit::CodeOffset,
        _reloc: binemit::Reloc,
        _ebb_offset: binemit::CodeOffset,
    ) {
        // This should use the `offsets` field of `ir::Function`.
        unimplemented!("RelocSink::reloc_ebb");
    }
    fn reloc_external(
        &mut self,
        offset: binemit::CodeOffset,
        reloc: binemit::Reloc,
        name: &ExternalName,
        addend: binemit::Addend,
    ) {
        let reloc = match reloc {
            binemit::Reloc::Abs8 => Reloc::Abs8,
            binemit::Reloc::X86PCRel4 => Reloc::X86PCRel4,
            binemit::Reloc::X86CallPCRel4 => Reloc::X86CallPCRel4,
            _ => unimplemented!("unimplented reloc type: {}", reloc),
        };

        match *name {
            ExternalName::User {
                namespace: 0,
                index,
            } => {
                assert_eq!(reloc, Reloc::X86CallPCRel4);
                self.local_relocs.push(LocalRelocation {
                    offset,
                    addend,
                    target: FuncIndex::new(index as usize),
                });
            }
            ExternalName::User { namespace, index } => {
                use self::call_names::*;

                let target = match namespace {
                    LOCAL_NAMESPACE => RelocationType::VmCall(VmCall::Local(match index {
                        STATIC_MEM_GROW => VmCallKind::StaticMemoryGrow,
                        STATIC_MEM_SIZE => VmCallKind::StaticMemorySize,

                        SHARED_STATIC_MEM_GROW => VmCallKind::SharedStaticMemoryGrow,
                        SHARED_STATIC_MEM_SIZE => VmCallKind::SharedStaticMemorySize,

                        DYNAMIC_MEM_GROW => VmCallKind::DynamicMemoryGrow,
                        DYNAMIC_MEM_SIZE => VmCallKind::DynamicMemorySize,
                        _ => unimplemented!("reloc_external VmCall::Local {}", index),
                    })),
                    IMPORT_NAMESPACE => RelocationType::VmCall(VmCall::Import(match index {
                        STATIC_MEM_GROW => VmCallKind::StaticMemoryGrow,
                        STATIC_MEM_SIZE => VmCallKind::StaticMemorySize,

                        SHARED_STATIC_MEM_GROW => VmCallKind::SharedStaticMemoryGrow,
                        SHARED_STATIC_MEM_SIZE => VmCallKind::SharedStaticMemorySize,

                        DYNAMIC_MEM_GROW => VmCallKind::DynamicMemoryGrow,
                        DYNAMIC_MEM_SIZE => VmCallKind::DynamicMemorySize,
                        _ => unimplemented!("reloc_external VmCall::Import {}", index),
                    })),
                    SIG_NAMESPACE => RelocationType::Signature(SigIndex::new(index as usize)),
                    _ => unimplemented!("reloc_external SigIndex {}", index),
                };
                self.external_relocs.push(ExternalRelocation {
                    reloc,
                    offset,
                    addend,
                    target,
                });
            }
            ExternalName::TestCase { length, ascii } => {
                let (slice, _) = ascii.split_at(length as usize);
                let name = String::from_utf8(slice.to_vec()).unwrap();
                self.external_relocs.push(ExternalRelocation {
                    reloc,
                    offset,
                    addend,
                    target: RelocationType::Intrinsic(name),
                });
            }
            ExternalName::LibCall(libcall) => {
                let libcall = match libcall {
                    ir::LibCall::CeilF32 => LibCall::CeilF32,
                    ir::LibCall::FloorF32 => LibCall::FloorF32,
                    ir::LibCall::TruncF32 => LibCall::TruncF32,
                    ir::LibCall::NearestF32 => LibCall::NearestF32,
                    ir::LibCall::CeilF64 => LibCall::CeilF64,
                    ir::LibCall::FloorF64 => LibCall::FloorF64,
                    ir::LibCall::TruncF64 => LibCall::TruncF64,
                    ir::LibCall::NearestF64 => LibCall::NearestF64,
                    ir::LibCall::Probestack => LibCall::Probestack,
                    _ => unimplemented!("unimplemented libcall: {}", libcall),
                };
                let relocation_type = RelocationType::LibCall(libcall);
                self.external_relocs.push(ExternalRelocation {
                    reloc,
                    offset,
                    addend,
                    target: relocation_type,
                });
            }
        }
    }

    fn reloc_constant(&mut self, _: u32, _: cranelift_codegen::binemit::Reloc, _: u32) {
        unimplemented!("RelocSink::reloc_constant")
    }

    fn reloc_jt(
        &mut self,
        _offset: binemit::CodeOffset,
        _reloc: binemit::Reloc,
        _jt: ir::JumpTable,
    ) {
        unimplemented!("RelocSink::reloc_jt");
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum TrapCode {
    StackOverflow,
    HeapOutOfBounds,
    TableOutOfBounds,
    OutOfBounds,
    IndirectCallToNull,
    BadSignature,
    IntegerOverflow,
    IntegerDivisionByZero,
    BadConversionToInteger,
    Interrupt,
    UnreachableCodeReached,
    User(u16),
}

/// Implementation of a relocation sink that just saves all the information for later
impl RelocSink {
    pub fn new() -> Self {
        Self {
            external_relocs: Vec::new(),
            local_relocs: Vec::new(),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct TrapData {
    pub trapcode: TrapCode,
    pub srcloc: u32,
}

/// Simple implementation of a TrapSink
/// that saves the info for later.
#[derive(Serialize, Deserialize)]
pub struct TrapSink {
    trap_datas: Vec<(usize, TrapData)>,
}

impl TrapSink {
    pub fn new() -> TrapSink {
        TrapSink {
            trap_datas: Vec::new(),
        }
    }

    pub fn lookup(&self, offset: usize) -> Option<TrapData> {
        self.trap_datas
            .iter()
            .find(|(trap_offset, _)| *trap_offset == offset)
            .map(|(_, trap_data)| *trap_data)
    }

    pub fn drain_local(&mut self, current_func_offset: usize, local: &mut LocalTrapSink) {
        self.trap_datas.extend(
            local
                .trap_datas
                .drain(..)
                .map(|(offset, trap_data)| (current_func_offset + offset, trap_data)),
        );
    }
}

pub struct LocalTrapSink {
    trap_datas: Vec<(usize, TrapData)>,
}

impl LocalTrapSink {
    pub fn new() -> Self {
        LocalTrapSink { trap_datas: vec![] }
    }
}

impl binemit::TrapSink for LocalTrapSink {
    fn trap(&mut self, offset: u32, srcloc: SourceLoc, trapcode: ir::TrapCode) {
        let trapcode = match trapcode {
            ir::TrapCode::StackOverflow => TrapCode::StackOverflow,
            ir::TrapCode::HeapOutOfBounds => TrapCode::HeapOutOfBounds,
            ir::TrapCode::TableOutOfBounds => TrapCode::TableOutOfBounds,
            ir::TrapCode::OutOfBounds => TrapCode::OutOfBounds,
            ir::TrapCode::IndirectCallToNull => TrapCode::IndirectCallToNull,
            ir::TrapCode::BadSignature => TrapCode::BadSignature,
            ir::TrapCode::IntegerOverflow => TrapCode::IntegerOverflow,
            ir::TrapCode::IntegerDivisionByZero => TrapCode::IntegerDivisionByZero,
            ir::TrapCode::BadConversionToInteger => TrapCode::BadConversionToInteger,
            ir::TrapCode::Interrupt => TrapCode::Interrupt,
            ir::TrapCode::UnreachableCodeReached => TrapCode::UnreachableCodeReached,
            ir::TrapCode::User(x) => TrapCode::User(x),
        };

        self.trap_datas.push((
            offset as usize,
            TrapData {
                trapcode,
                srcloc: srcloc.bits(),
            },
        ));
    }
}