mod.rs 12.5 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Australian National University
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
use utils;
16 17
use utils::Word;
use utils::Address;
18
use ast::ir::*;
19
use vm::VM;
20 21
use compiler::backend::RegGroup;

22
use std::fmt;
qinsoon's avatar
qinsoon committed
23
use std::os::raw::c_int;
24 25 26
use std::os::raw::c_char;
use std::os::raw::c_void;
use std::ffi::CString;
27 28
use std::ffi::CStr;
use std::sync::Arc;
29

qinsoon's avatar
qinsoon committed
30 31
/// memory management: allocation, reclamation
/// (the actual code is in src/gc, which gets re-exported in mm module)
32
pub mod mm;
qinsoon's avatar
qinsoon committed
33
/// thread management: stack, thread
qinsoon's avatar
qinsoon committed
34
pub mod thread;
qinsoon's avatar
qinsoon committed
35
/// mathematics functions
qinsoon's avatar
qinsoon committed
36
pub mod math;
qinsoon's avatar
qinsoon committed
37 38
/// a list of all entrypoints used by compiler to generate calls into runtime
/// (where generated code entries the runtime)
qinsoon's avatar
qinsoon committed
39
pub mod entrypoints;
qinsoon's avatar
qinsoon committed
40
/// exception handling
41 42
pub mod exception;

qinsoon's avatar
qinsoon committed
43
/// Dl_info used by dynamic loading functions
44 45 46
// consider using libloading crate instead of the raw c functions for dynalic libraries
// however i am not sure if libloading can load symbols from current process (not from an actual dylib)
// so here i use dlopen/dlsym from C
47 48 49 50 51 52 53 54
#[repr(C)]
struct Dl_info {
    dli_fname: *const c_char,
    dli_fbase: *mut c_void,
    dli_sname: *const c_char,
    dli_saddr: *mut c_void,
}

55 56 57 58
#[link(name="dl")]
extern "C" {
    fn dlopen(filename: *const c_char, flags: isize) -> *const c_void;
    fn dlsym(handle: *const c_void, symbol: *const c_char) -> *const c_void;
59
    fn dladdr(addr: *mut c_void, info: *mut Dl_info) -> i32;
60
    fn dlerror() -> *const c_char;
61 62
}

qinsoon's avatar
qinsoon committed
63 64 65
/// returns name for a function address
// FIXME: this actually returns the name and address of the nearest symbol (of any type)
//        that starts before function_addr (instead we want the nearest function symbol)
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
pub fn get_function_info(function_addr: Address) -> (CName, Address) {
    use std::ptr;

    // Rust requires this to be initialised
    let mut info = Dl_info {
        dli_fname: ptr::null::<c_char>(),
        dli_fbase: ptr::null_mut::<c_void>(),
        dli_sname: ptr::null::<c_char>(),
        dli_saddr: ptr::null_mut::<c_void>(),
    };

    unsafe {dladdr(function_addr.to_ptr_mut::<c_void>(), &mut info)};

    let error = unsafe {dlerror()};
    if !error.is_null() {
        let cstr = unsafe {CStr::from_ptr(error)};
        error!("cannot find function address: {}", function_addr);
        error!("{}", cstr.to_str().unwrap());

        panic!("failed to resolve function address");
    }
    if !info.dli_sname.is_null() {
        (unsafe {CStr::from_ptr(info.dli_sname)}.to_str().unwrap().to_string(), Address::from_ptr(info.dli_saddr))
    } else {
        ("UNKOWN".to_string(), Address::from_ptr(info.dli_saddr))
    }

}

qinsoon's avatar
qinsoon committed
95 96
/// returns address for a given symbol, e.g. function name
pub fn resolve_symbol(symbol: MuName) -> Address {
97
    use std::ptr;
98

99
    let symbol = name_check(symbol);
100 101 102
    
    let rtld_default = unsafe {dlopen(ptr::null(), 0)};
    let ret = unsafe {dlsym(rtld_default, CString::new(symbol.clone()).unwrap().as_ptr())};
103 104 105 106

    let error = unsafe {dlerror()};
    if !error.is_null() {
        let cstr = unsafe {CStr::from_ptr(error)};
107 108
        error!("cannot find symbol: {}", symbol);
        error!("{}", cstr.to_str().unwrap());
109 110

        panic!("failed to resolve symbol");
111 112 113 114 115
    }
    
    Address::from_ptr(ret)
}

qinsoon's avatar
qinsoon committed
116 117
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};

qinsoon's avatar
qinsoon committed
118 119 120 121 122 123 124 125 126
/// ValueLocation represents the runtime location for a value.
/// The purpose of this data structure is to refer to a location in a unified way
/// for both compile time (usually talking about symbols) and run time (talking about addresses)
/// A ValueLocation could be:
/// * a register (the register holds the value)
/// * a Constant (the value itself)
/// * a relocatable symbol (a relocatable symbol emitted by AOT compiler, which resides the value)
/// * a direct memory address (the address contains the value)
/// * a indirect memory address (the address contains a pointer to the value)
qinsoon's avatar
qinsoon committed
127
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
128
pub enum ValueLocation {
qinsoon's avatar
qinsoon committed
129 130 131 132 133
    Register    (RegGroup, MuID),     // 0
    Constant    (RegGroup, Word),     // 1
    Relocatable (RegGroup, MuName),   // 2
    Direct      (RegGroup, Address),  // 3
    Indirect    (RegGroup, Address),  // 4
qinsoon's avatar
qinsoon committed
134 135
}

136 137 138 139 140 141 142 143 144 145 146 147
impl fmt::Display for ValueLocation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &ValueLocation::Register(_, id) => write!(f, "VL_Reg: {}", id),
            &ValueLocation::Constant(_, val) => write!(f, "VL_Const: {}", val),
            &ValueLocation::Relocatable(_, ref name) => write!(f, "VL_Reloc: {}", name),
            &ValueLocation::Direct(_, addr) => write!(f, "VL_Direct: 0x{:x}", addr),
            &ValueLocation::Indirect(_, addr) => write!(f, "VL_Indirect: 0x{:x}", addr)
        }
    }
}

qinsoon's avatar
qinsoon committed
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
impl Encodable for ValueLocation {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
        s.emit_enum("ValueLocation", |s| {
            match self {
                &ValueLocation::Register(grp, id) => {
                    s.emit_enum_variant("Register", 0, 2, |s| {
                        try!(s.emit_enum_variant_arg(0, |s| grp.encode(s)));
                        try!(s.emit_enum_variant_arg(1, |s| id.encode(s)));
                        Ok(())
                    })
                }
                &ValueLocation::Constant(grp, val) => {
                    s.emit_enum_variant("Constant", 1, 2, |s| {
                        try!(s.emit_enum_variant_arg(0, |s| grp.encode(s)));
                        try!(s.emit_enum_variant_arg(1, |s| val.encode(s)));
                        Ok(())
                    })    
                }                
                &ValueLocation::Relocatable(grp, ref name) => {
                    s.emit_enum_variant("Relocatable", 2, 2, |s| {
                        try!(s.emit_enum_variant_arg(0, |s| grp.encode(s)));
                        try!(s.emit_enum_variant_arg(1, |s| name.encode(s)));
                        Ok(())
                    })
                }
                &ValueLocation::Direct(_, _)
                | &ValueLocation::Indirect(_, _) => {
                    panic!("trying to encode an address location (not persistent)")
                }
            }
        })
    }
}

impl Decodable for ValueLocation {
    fn decode<D: Decoder>(d: &mut D) -> Result<ValueLocation, D::Error> {
        d.read_enum("ValueLocation", |d| {
            d.read_enum_variant(
                &vec!["Register", "Constant", "Relocatable"],
                |d, idx| {
                    match idx {
                        0 => {
                            // Register variant
                            let grp = try!(d.read_enum_variant_arg(0, |d| Decodable::decode(d)));
                            let id = try!(d.read_enum_variant_arg(1, |d| Decodable::decode(d)));
                            
                            Ok(ValueLocation::Register(grp, id))
                        }
                        1 => {
                            // Constant
                            let grp = try!(d.read_enum_variant_arg(0, |d| Decodable::decode(d)));
                            let val = try!(d.read_enum_variant_arg(1, |d| Decodable::decode(d)));
                            Ok(ValueLocation::Constant(grp, val))
                        }
                        2 => {
                            // Relocatable
                            let grp = try!(d.read_enum_variant_arg(0, |d| Decodable::decode(d)));
                            let name = try!(d.read_enum_variant_arg(1, |d| Decodable::decode(d)));
                            Ok(ValueLocation::Relocatable(grp, name))
                        }
                        _ => panic!("unexpected enum variant for ValueLocation: {}", idx)
                    }
                }
             ) 
        })
    }
214 215 216
}

impl ValueLocation {
qinsoon's avatar
qinsoon committed
217
    /// loads value from a ValueLocation
218 219
    pub fn load_value(&self) -> (RegGroup, Word) {
        match self {
qinsoon's avatar
qinsoon committed
220 221 222 223 224 225 226 227 228 229
            &ValueLocation::Register(_, _)        => unimplemented!(),
            &ValueLocation::Direct(group, addr)   => {
                (group, unsafe {addr.load::<Word>()})
            }
            &ValueLocation::Indirect(group, addr) => {
                unsafe {
                    let ptr = addr.load::<Address>();
                    (group, ptr.load::<Word>())
                }
            }
230 231 232
            &ValueLocation::Constant(group, word) => {
                (group, word)
            }
qinsoon's avatar
qinsoon committed
233 234 235 236
            &ValueLocation::Relocatable(group, ref symbol) => {
                let addr = resolve_symbol(symbol.clone());
                (group, unsafe {addr.load::<Word>()})
            }
237 238
        }
    }
qinsoon's avatar
qinsoon committed
239 240

    /// creates a ValueLocation from a constant, panics if impossible
qinsoon's avatar
qinsoon committed
241
    pub fn from_constant(c: Constant) -> ValueLocation {
242
        match c {
qinsoon's avatar
qinsoon committed
243 244
            Constant::Int(int_val)    => ValueLocation::Constant(RegGroup::GPR, utils::mem::u64_to_raw(int_val)),
            Constant::Float(f32_val)  => ValueLocation::Constant(RegGroup::FPR, utils::mem::f32_to_raw(f32_val)),
245 246 247
            Constant::Double(f64_val) => ValueLocation::Constant(RegGroup::FPR, utils::mem::f64_to_raw(f64_val)),
            _ => unimplemented!()
        }
qinsoon's avatar
qinsoon committed
248
    }
qinsoon's avatar
qinsoon committed
249 250

    /// returns the address that contains the value
qinsoon's avatar
qinsoon committed
251 252
    pub fn to_address(&self) -> Address {
        match self {
qinsoon's avatar
qinsoon committed
253
            &ValueLocation::Direct(_, addr)   => addr,
qinsoon's avatar
qinsoon committed
254
            &ValueLocation::Indirect(_, addr) => unsafe {addr.load::<Address>()},
qinsoon's avatar
qinsoon committed
255 256 257
            &ValueLocation::Relocatable(_, ref symbol) => resolve_symbol(symbol.clone()),
            &ValueLocation::Register(_, _)
            | &ValueLocation::Constant(_, _)  => panic!("a register/constant cannot be turned into address")
qinsoon's avatar
qinsoon committed
258 259
        }
    }
260

qinsoon's avatar
qinsoon committed
261
    /// returns a relocatable symbol that contains the value, panics if impossible
262 263 264 265 266 267
    pub fn to_relocatable(&self) -> MuName {
        match self {
            &ValueLocation::Relocatable(_, ref name) => name.clone(),
            _ => panic!("expecting Relocatable location, found {}", self)
        }
    }
268 269
}

qinsoon's avatar
qinsoon committed
270 271 272 273 274
/// a C wrapper as main function for executable boot images"
/// The C wrapper does:
/// 1. loads the persisted VM
/// 2. invokes mu_main() to hand the control to Rust code
/// 3. returns the return value set by SetRetval
275 276
pub const PRIMORDIAL_ENTRY : &'static str = "src/runtime/main.c";

qinsoon's avatar
qinsoon committed
277
/// starts trace level logging, this function will be called from C
278 279
#[no_mangle]
pub extern fn mu_trace_level_log() {
qinsoon's avatar
qinsoon committed
280
    VM::start_logging_trace();
281 282
}

qinsoon's avatar
qinsoon committed
283
/// the main function for executable boot image, this function will be called from C
284
#[no_mangle]
qinsoon's avatar
qinsoon committed
285
pub extern fn mu_main(serialized_vm : *const c_char, argc: c_int, argv: *const *const c_char) {
286
    debug!("mu_main() started...");
qinsoon's avatar
qinsoon committed
287 288

    // load and resume the VM
289 290
    let str_vm = unsafe{CStr::from_ptr(serialized_vm)}.to_str().unwrap();
    let vm : Arc<VM> = Arc::new(VM::resume_vm(str_vm));
qinsoon's avatar
qinsoon committed
291 292

    // find the primordial function as an entry
293 294 295 296 297 298 299 300
    let primordial = vm.primordial.read().unwrap();
    if primordial.is_none() {
        panic!("no primordial thread/stack/function. Client should provide an entry point");
    } else {
        let primordial = primordial.as_ref().unwrap();
        
        // create mu stack
        let stack = vm.new_stack(primordial.func_id);
qinsoon's avatar
qinsoon committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

        // if the primordial named some const arguments, we use the const args
        // otherwise we push 'argc' and 'argv' to new stack
        let args : Vec<ValueLocation> = if primordial.has_const_args {
            primordial.args.iter().map(|arg| ValueLocation::from_constant(arg.clone())).collect()
        } else {
            let mut args = vec![];

            // 1st arg: argc
            args.push(ValueLocation::from_constant(Constant::Int(argc as u64)));

            // 2nd arg: argv
            args.push(ValueLocation::from_constant(Constant::Int(argv as u64)));

            args
        };
317
        
qinsoon's avatar
qinsoon committed
318
        // FIXME: currently assumes no user defined thread local - See Issue #48
319
        let thread = thread::MuThread::new_thread_normal(stack, unsafe{Address::zero()}, args, vm.clone());
320 321 322
        
        thread.join().unwrap();
    }
323
}
324

qinsoon's avatar
qinsoon committed
325
/// runtime function to print a hex value (for PRINTHEX instruction for debugging use)
326 327
#[no_mangle]
pub extern fn muentry_print_hex(x: u64) {
328
    println!("PRINTHEX: 0x{:x}", x);
329
}