vm.rs 62.1 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.

qinsoon's avatar
qinsoon committed
15 16
use std::collections::HashMap;

qinsoon's avatar
qinsoon committed
17
use ast::ptr::*;
qinsoon's avatar
qinsoon committed
18
use ast::ir::*;
19
use ast::inst::*;
qinsoon's avatar
qinsoon committed
20
use ast::types;
qinsoon's avatar
qinsoon committed
21
use ast::types::*;
qinsoon's avatar
qinsoon committed
22
use compiler::{Compiler, CompilerPolicy};
qinsoon's avatar
qinsoon committed
23 24
use compiler::backend;
use compiler::backend::BackendTypeInfo;
qinsoon's avatar
qinsoon committed
25
use compiler::machine_code::CompiledFunction;
26

27
use runtime::thread::*;
28
use runtime::*;
qinsoon's avatar
qinsoon committed
29
use utils::ByteSize;
30
use utils::BitSize;
31
use utils::Address;
32
use runtime::mm as gc;
33
use vm::handle::*;
qinsoon's avatar
qinsoon committed
34 35
use vm::vm_options::VMOptions;
use vm::vm_options::MuLogLevel;
36

qinsoon's avatar
qinsoon committed
37 38
use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
use log::LogLevel;
39
use std::sync::Arc;
qinsoon's avatar
qinsoon committed
40
use std::sync::RwLock;
41
use std::sync::RwLockWriteGuard;
42
use std::sync::atomic::{AtomicUsize, AtomicBool, ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT, Ordering};
43

qinsoon's avatar
qinsoon committed
44 45 46 47 48
// FIXME:
// besides fields in VM, there are some 'globals' we need to persist
// such as STRUCT_TAG_MAP
// possibly INTERNAL_ID in ir.rs, internal types, etc

qinsoon's avatar
qinsoon committed
49
pub struct VM {
50
    // ---serialize---
qinsoon's avatar
qinsoon committed
51
    // 0
52
    next_id: AtomicUsize,
qinsoon's avatar
qinsoon committed
53
    // 1
qinsoon's avatar
qinsoon committed
54
    id_name_map: RwLock<HashMap<MuID, MuName>>,
qinsoon's avatar
qinsoon committed
55
    // 2
qinsoon's avatar
qinsoon committed
56
    name_id_map: RwLock<HashMap<MuName, MuID>>,
qinsoon's avatar
qinsoon committed
57
    // 3
qinsoon's avatar
qinsoon committed
58
    types: RwLock<HashMap<MuID, P<MuType>>>,
qinsoon's avatar
qinsoon committed
59 60
    // 4
    backend_type_info: RwLock<HashMap<MuID, Box<BackendTypeInfo>>>,
61
    // 5
qinsoon's avatar
qinsoon committed
62
    constants: RwLock<HashMap<MuID, P<Value>>>,
qinsoon's avatar
qinsoon committed
63
    // 6
qinsoon's avatar
qinsoon committed
64
    globals: RwLock<HashMap<MuID, P<Value>>>,
65
    pub global_locations: RwLock<HashMap<MuID, ValueLocation>>,
qinsoon's avatar
qinsoon committed
66
    // 7
qinsoon's avatar
qinsoon committed
67
    func_sigs: RwLock<HashMap<MuID, P<MuFuncSig>>>,
qinsoon's avatar
qinsoon committed
68
    // 8
qinsoon's avatar
qinsoon committed
69
    funcs: RwLock<HashMap<MuID, RwLock<MuFunction>>>,
qinsoon's avatar
qinsoon committed
70 71
    // 9
    func_vers: RwLock<HashMap<MuID, RwLock<MuFunctionVersion>>>,
72 73
    // 10
    pub primordial: RwLock<Option<MuPrimordialThread>>,
qinsoon's avatar
qinsoon committed
74 75
    // 11
    is_running: AtomicBool,
qinsoon's avatar
qinsoon committed
76 77
    // 12
    pub vm_options: VMOptions,
qinsoon's avatar
qinsoon committed
78
    
79
    // ---partially serialize---
qinsoon's avatar
qinsoon committed
80
    // 13
81
    compiled_funcs: RwLock<HashMap<MuID, RwLock<CompiledFunction>>>,
82

83 84 85
    // Maps each callsite to a tuple of the corresponding catch blocks label (or ""_
    // and the id of the containing function-version
    // 14
86
    exception_table: RwLock<HashMap<MuID, HashMap<MuName, MuName>>>,
87

88 89 90 91
    // ---do not serialize---

    // client may try to store funcref to the heap, so that they can load it later, and call it
    // however the store may happen before we have an actual address to the func (in AOT scenario)
92 93 94 95 96 97 98 99 100 101 102
    aot_pending_funcref_store: RwLock<HashMap<Address, ValueLocation>>,

    // Table for excetions
    // TODO: Have a table of these tables (one per bundle?)

    // The exception table (before it has been written to disk)


    // Same as above but once the everything have been resolved to addreses

    // TODO: What should the function version refer to? (It has to refer to something that has callee saved registers...)
103 104 105
    // TODO: probably we should remove the pointer (its unsafe), thats why we need Sync/Send for VM
    //       we can make a copy of callee_saved_register location
    pub compiled_exception_table: RwLock<HashMap<Address, (Address, *const CompiledFunction)>>
106
}
107 108
unsafe impl Sync for VM {}
unsafe impl Send for VM {}
109

110 111 112
use std::u64;
const PENDING_FUNCREF : u64 = u64::MAX;

113
const VM_SERIALIZE_FIELDS : usize = 14;
qinsoon's avatar
qinsoon committed
114

115 116
impl Encodable for VM {
    fn encode<S: Encoder> (&self, s: &mut S) -> Result<(), S::Error> {
117 118
        let mut field_i = 0;

qinsoon's avatar
qinsoon committed
119 120
        // serialize VM_SERIALIZE_FIELDS fields
        // PLUS ONE extra global STRUCT_TAG_MAP
121
        s.emit_struct("VM", VM_SERIALIZE_FIELDS + 2, |s| {
122
            // next_id
qinsoon's avatar
qinsoon committed
123
            trace!("...serializing next_id");
124
            try!(s.emit_struct_field("next_id", field_i, |s| {
125 126
                s.emit_usize(self.next_id.load(Ordering::SeqCst))
            }));
127
            field_i += 1;
128 129
                
            // id_name_map
qinsoon's avatar
qinsoon committed
130
            trace!("...serializing id_name_map");
131 132
            {
                let map : &HashMap<MuID, MuName> = &self.id_name_map.read().unwrap();            
133
                try!(s.emit_struct_field("id_name_map", field_i, |s| map.encode(s)));
134
            }
135
            field_i += 1;
136 137
            
            // name_id_map
qinsoon's avatar
qinsoon committed
138
            trace!("...serializing name_id_map");
139 140
            {
                let map : &HashMap<MuName, MuID> = &self.name_id_map.read().unwrap(); 
141
                try!(s.emit_struct_field("name_id_map", field_i, |s| map.encode(s)));
142
            }
143
            field_i += 1;
144 145
            
            // types
qinsoon's avatar
qinsoon committed
146
            trace!("...serializing types");
147 148
            {
                let types = &self.types.read().unwrap();
149
                try!(s.emit_struct_field("types", field_i, |s| types.encode(s)));
qinsoon's avatar
qinsoon committed
150
            }
151 152
            field_i += 1;

qinsoon's avatar
qinsoon committed
153
            // STRUCT_TAG_MAP
qinsoon's avatar
qinsoon committed
154
            trace!("...serializing struct_tag_map");
qinsoon's avatar
qinsoon committed
155 156
            {
                let struct_tag_map = types::STRUCT_TAG_MAP.read().unwrap();
157 158 159 160 161 162 163 164 165
                try!(s.emit_struct_field("struct_tag_map", field_i, |s| struct_tag_map.encode(s)));
            }
            field_i += 1;

            // HYBRID_TAG_MAP
            trace!("...serializing hybrid_tag_map");
            {
                let hybrid_tag_map = types::HYBRID_TAG_MAP.read().unwrap();
                try!(s.emit_struct_field("hybrid_tag_map", field_i, |s| hybrid_tag_map.encode(s)));
qinsoon's avatar
qinsoon committed
166
            }
167
            field_i += 1;
qinsoon's avatar
qinsoon committed
168 169
            
            // backend_type_info
qinsoon's avatar
qinsoon committed
170
            trace!("...serializing backend_type_info");
qinsoon's avatar
qinsoon committed
171 172
            {
                let backend_type_info : &HashMap<_, _> = &self.backend_type_info.read().unwrap();
173
                try!(s.emit_struct_field("backend_type_info", field_i, |s| backend_type_info.encode(s)));
qinsoon's avatar
qinsoon committed
174
            }
175
            field_i += 1;
qinsoon's avatar
qinsoon committed
176 177
            
            // constants
qinsoon's avatar
qinsoon committed
178
            trace!("...serializing constants");
qinsoon's avatar
qinsoon committed
179 180
            {
                let constants : &HashMap<_, _> = &self.constants.read().unwrap();
181
                try!(s.emit_struct_field("constants", field_i, |s| constants.encode(s)));
qinsoon's avatar
qinsoon committed
182
            }
183
            field_i += 1;
qinsoon's avatar
qinsoon committed
184 185
            
            // globals
qinsoon's avatar
qinsoon committed
186
            trace!("...serializing globals");
qinsoon's avatar
qinsoon committed
187 188
            {
                let globals: &HashMap<_, _> = &self.globals.read().unwrap();
189
                try!(s.emit_struct_field("globals", field_i, |s| globals.encode(s)));
qinsoon's avatar
qinsoon committed
190
            }
191
            field_i += 1;
qinsoon's avatar
qinsoon committed
192 193
            
            // func sigs
qinsoon's avatar
qinsoon committed
194
            trace!("...serializing func_sigs");
qinsoon's avatar
qinsoon committed
195 196
            {
                let func_sigs: &HashMap<_, _> = &self.func_sigs.read().unwrap();
197
                try!(s.emit_struct_field("func_sigs", field_i, |s| func_sigs.encode(s)));
qinsoon's avatar
qinsoon committed
198
            }
199
            field_i += 1;
qinsoon's avatar
qinsoon committed
200 201
            
            // funcs
qinsoon's avatar
qinsoon committed
202
            trace!("...serializing funcs");
qinsoon's avatar
qinsoon committed
203 204
            {
                let funcs : &HashMap<_, _> = &self.funcs.read().unwrap();
205
                try!(s.emit_struct_field("funcs", field_i, |s| {
qinsoon's avatar
qinsoon committed
206 207 208 209 210 211 212 213 214 215 216 217
                    s.emit_map(funcs.len(), |s| {
                        let mut i = 0;
                        for (k,v) in funcs.iter() {
                            s.emit_map_elt_key(i, |s| k.encode(s)).ok();
                            let func : &MuFunction = &v.read().unwrap();
                            s.emit_map_elt_val(i, |s| func.encode(s)).ok();
                            i += 1;
                        }
                        Ok(())
                    })
                }));
            }
218 219
            field_i += 1;

qinsoon's avatar
qinsoon committed
220
            // primordial
qinsoon's avatar
qinsoon committed
221
            trace!("...serializing primordial");
qinsoon's avatar
qinsoon committed
222 223
            {
                let primordial = &self.primordial.read().unwrap();
224
                try!(s.emit_struct_field("primordial", field_i, |s| primordial.encode(s)));
qinsoon's avatar
qinsoon committed
225
            }
226
            field_i += 1;
qinsoon's avatar
qinsoon committed
227 228
            
            // is_running
qinsoon's avatar
qinsoon committed
229
            trace!("...serializing is_running");
qinsoon's avatar
qinsoon committed
230
            {
231
                try!(s.emit_struct_field("is_running", field_i, |s| self.is_running.load(Ordering::SeqCst).encode(s)));
232
            }
233
            field_i += 1;
qinsoon's avatar
qinsoon committed
234 235 236 237 238 239 240

            // options
            trace!("...serializing vm_options");
            {
                try!(s.emit_struct_field("vm_options", field_i, |s| self.vm_options.encode(s)));
            }
            field_i += 1;
241
            
qinsoon's avatar
qinsoon committed
242
            // compiled_funcs
qinsoon's avatar
qinsoon committed
243
            trace!("...serializing compiled_funcs");
qinsoon's avatar
qinsoon committed
244 245
            {
                let compiled_funcs : &HashMap<_, _> = &self.compiled_funcs.read().unwrap();
246
                try!(s.emit_struct_field("compiled_funcs", field_i, |s| {
qinsoon's avatar
qinsoon committed
247 248 249 250 251 252 253 254 255 256 257 258
                    s.emit_map(compiled_funcs.len(), |s| {
                        let mut i = 0;
                        for (k, v) in compiled_funcs.iter() {
                            try!(s.emit_map_elt_key(i, |s| k.encode(s)));
                            let compiled_func : &CompiledFunction = &v.read().unwrap();
                            try!(s.emit_map_elt_val(i, |s| compiled_func.encode(s)));
                            i += 1;
                        }
                        Ok(())
                    })
                }));
            }
259
            field_i += 1;
260 261
            trace!("...serializing exception_table");
            {
262
                let map : &HashMap<MuID, HashMap<MuName, MuName>> = &self.exception_table.read().unwrap();
263 264 265 266
                try!(s.emit_struct_field("exception_table", field_i, |s| map.encode(s)));
            }
            field_i += 1;

qinsoon's avatar
qinsoon committed
267
            trace!("serializing finished");
268 269 270
            Ok(())
        })
    }
qinsoon's avatar
qinsoon committed
271 272
}

qinsoon's avatar
qinsoon committed
273 274
impl Decodable for VM {
    fn decode<D: Decoder>(d: &mut D) -> Result<VM, D::Error> {
275 276 277
        let mut field_i = 0;

        d.read_struct("VM", VM_SERIALIZE_FIELDS + 2, |d| {
qinsoon's avatar
qinsoon committed
278
            // next_id
279
            let next_id = try!(d.read_struct_field("next_id", field_i, |d| {
qinsoon's avatar
qinsoon committed
280 281
                d.read_usize()
            }));
282
            field_i += 1;
qinsoon's avatar
qinsoon committed
283 284
            
            // id_name_map
285 286 287
            let id_name_map = try!(d.read_struct_field("id_name_map", field_i, |d| Decodable::decode(d)));
            field_i += 1;

qinsoon's avatar
qinsoon committed
288
            // name_id_map
289 290
            let name_id_map = try!(d.read_struct_field("name_id_map", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
291 292
            
            // types
293 294 295 296
            let types = try!(d.read_struct_field("types", field_i, |d| Decodable::decode(d)));
            field_i += 1;

            // struct tag map
qinsoon's avatar
qinsoon committed
297
            {
298
                let mut struct_tag_map : HashMap<MuName, StructType_> = try!(d.read_struct_field("struct_tag_map", field_i, |d| Decodable::decode(d)));
qinsoon's avatar
qinsoon committed
299 300 301 302 303 304
                
                let mut map_guard = types::STRUCT_TAG_MAP.write().unwrap();
                map_guard.clear();
                for (k, v) in struct_tag_map.drain() {
                    map_guard.insert(k, v);
                }
305 306 307 308 309 310 311 312 313 314 315 316 317
                field_i += 1;
            }

            // hybrid tag map
            {
                let mut hybrid_tag_map : HashMap<MuName, HybridType_> = try!(d.read_struct_field("hybrid_tag_map", field_i, |d| Decodable::decode(d)));

                let mut map_guard = types::HYBRID_TAG_MAP.write().unwrap();
                map_guard.clear();
                for (k, v) in hybrid_tag_map.drain() {
                    map_guard.insert(k, v);
                }
                field_i += 1;
qinsoon's avatar
qinsoon committed
318
            }
qinsoon's avatar
qinsoon committed
319 320
            
            // backend_type_info
321 322
            let backend_type_info = try!(d.read_struct_field("backend_type_info", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
323 324
            
            // constants
325 326
            let constants = try!(d.read_struct_field("constants", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
327 328
            
            // globals
329 330
            let globals = try!(d.read_struct_field("globals", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
331 332
            
            // func sigs
333 334
            let func_sigs = try!(d.read_struct_field("func_sigs", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
335 336
            
            // funcs
337
            let funcs = try!(d.read_struct_field("funcs", field_i, |d| {
qinsoon's avatar
qinsoon committed
338 339 340 341 342 343 344 345 346 347
                d.read_map(|d, len| {
                    let mut map = HashMap::new();
                    for i in 0..len {
                        let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
                        let val = RwLock::new(try!(d.read_map_elt_val(i, |d| Decodable::decode(d))));
                        map.insert(key, val);
                    }
                    Ok(map)
                })
            }));
348
            field_i += 1;
qinsoon's avatar
qinsoon committed
349 350
            
            // primordial
351 352
            let primordial = try!(d.read_struct_field("primordial", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
353 354

            // is_running
355 356
            let is_running = try!(d.read_struct_field("is_running", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
357 358 359 360

            // vm_options
            let vm_options = try!(d.read_struct_field("vm_options", field_i, |d| Decodable::decode(d)));
            field_i += 1;
qinsoon's avatar
qinsoon committed
361
            
qinsoon's avatar
qinsoon committed
362
            // compiled funcs
363
            let compiled_funcs = try!(d.read_struct_field("compiled_funcs", field_i, |d| {
qinsoon's avatar
qinsoon committed
364 365 366 367 368 369 370 371 372 373
                d.read_map(|d, len| {
                    let mut map = HashMap::new();
                    for i in 0..len {
                        let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d)));
                        let val = RwLock::new(try!(d.read_map_elt_val(i, |d| Decodable::decode(d))));
                        map.insert(key, val);
                    }
                    Ok(map)
                })
            }));
374
            field_i += 1;
375 376 377 378 379 380 381

            trace!("Deserialising exception table");
            let exception_table = try!(d.read_struct_field("exception_table", field_i, |d| Decodable::decode(d)));
            field_i += 1;


            let vm = VM {
qinsoon's avatar
qinsoon committed
382 383 384 385 386 387 388
                next_id: ATOMIC_USIZE_INIT,
                id_name_map: RwLock::new(id_name_map),
                name_id_map: RwLock::new(name_id_map),
                types: RwLock::new(types),
                backend_type_info: RwLock::new(backend_type_info),
                constants: RwLock::new(constants),
                globals: RwLock::new(globals),
389
                global_locations: RwLock::new(hashmap!{}),
qinsoon's avatar
qinsoon committed
390 391
                func_sigs: RwLock::new(func_sigs),
                funcs: RwLock::new(funcs),
392
                func_vers: RwLock::new(hashmap!{}),
qinsoon's avatar
qinsoon committed
393 394
                primordial: RwLock::new(primordial),
                is_running: ATOMIC_BOOL_INIT,
qinsoon's avatar
qinsoon committed
395
                vm_options: vm_options,
396
                compiled_funcs: RwLock::new(compiled_funcs),
397 398
                exception_table: RwLock::new(exception_table),
                aot_pending_funcref_store: RwLock::new(HashMap::new()),
399
                compiled_exception_table: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
400 401 402 403 404 405 406 407 408 409
            };
            
            vm.next_id.store(next_id, Ordering::SeqCst);
            vm.is_running.store(is_running, Ordering::SeqCst);
            
            Ok(vm)
        })
    }
}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
macro_rules! gen_handle_int {
    ($fn_from: ident, $fn_to: ident, $int_ty: ty) => {
        pub fn $fn_from (&self, num: $int_ty, len: BitSize) -> APIHandleResult {
            let handle_id = self.next_id();
            self.new_handle (APIHandle {
                id: handle_id,
                v: APIHandleValue::Int(num as u64, len)
            })
        }

        pub fn $fn_to (&self, handle: APIHandleArg) -> $int_ty {
            handle.v.as_int() as $int_ty
        }
    }
}

qinsoon's avatar
qinsoon committed
426 427
impl <'a> VM {
    pub fn new() -> VM {
qinsoon's avatar
qinsoon committed
428 429 430 431 432 433 434 435 436
        VM::new_internal(VMOptions::default())
    }

    pub fn new_with_opts(str: &str) -> VM {
        VM::new_internal(VMOptions::init(str))
    }

    fn new_internal(options: VMOptions) -> VM {
        VM::start_logging(options.flag_log_level);
qinsoon's avatar
qinsoon committed
437

qinsoon's avatar
qinsoon committed
438
        let ret = VM {
439
            next_id: ATOMIC_USIZE_INIT,
440
            is_running: ATOMIC_BOOL_INIT,
qinsoon's avatar
qinsoon committed
441 442
            vm_options: options,

qinsoon's avatar
qinsoon committed
443 444
            id_name_map: RwLock::new(HashMap::new()),
            name_id_map: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
445

qinsoon's avatar
qinsoon committed
446
            constants: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
447

qinsoon's avatar
qinsoon committed
448
            types: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
449
            backend_type_info: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
450

qinsoon's avatar
qinsoon committed
451
            globals: RwLock::new(HashMap::new()),
452
            global_locations: RwLock::new(hashmap!{}),
qinsoon's avatar
qinsoon committed
453

qinsoon's avatar
qinsoon committed
454
            func_sigs: RwLock::new(HashMap::new()),
455
            func_vers: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
456
            funcs: RwLock::new(HashMap::new()),
qinsoon's avatar
qinsoon committed
457
            compiled_funcs: RwLock::new(HashMap::new()),
458
            exception_table: RwLock::new(HashMap::new()),
459 460
            primordial: RwLock::new(None),

461
            aot_pending_funcref_store: RwLock::new(HashMap::new()),
462
            compiled_exception_table: RwLock::new(HashMap::new()),
463
        };
qinsoon's avatar
qinsoon committed
464

465
        // insert all internal types
qinsoon's avatar
qinsoon committed
466 467 468 469 470 471
        {
            let mut types = ret.types.write().unwrap();
            for ty in INTERNAL_TYPES.iter() {
                types.insert(ty.id(), ty.clone());
            }
        }
qinsoon's avatar
qinsoon committed
472

473
        ret.is_running.store(false, Ordering::SeqCst);
474 475 476 477 478 479 480 481 482

        // Does not need SeqCst.
        //
        // If VM creates Mu threads and Mu threads calls traps, the trap handler still "happens
        // after" the creation of the VM itself. Rust does not have a proper memory model, but this
        // is how C++ works.
        //
        // If the client needs to create client-level threads, however, the client should properly
        // synchronise at the time of inter-thread communication, rather than creation of the VM.
483
        ret.next_id.store(USER_ID_START, Ordering::Relaxed);
qinsoon's avatar
qinsoon committed
484

485 486 487 488
        // init types
        types::init_types();

        ret.init_runtime();
qinsoon's avatar
qinsoon committed
489

490 491
        ret
    }
qinsoon's avatar
qinsoon committed
492

493
    fn init_runtime(&self) {
qinsoon's avatar
qinsoon committed
494 495 496 497 498 499
        // init log
        VM::start_logging(self.vm_options.flag_log_level);

        // init gc
        {
            let ref options = self.vm_options;
500
            gc::gc_init(options.flag_gc_immixspace_size, options.flag_gc_lospace_size, options.flag_gc_nthreads, !options.flag_gc_disable_collection);
qinsoon's avatar
qinsoon committed
501 502 503 504 505 506 507 508 509 510 511 512
        }
    }

    fn start_logging(level: MuLogLevel) {
        match level {
            MuLogLevel::None  => {},
            MuLogLevel::Error => VM::start_logging_internal(LogLevel::Error),
            MuLogLevel::Warn  => VM::start_logging_internal(LogLevel::Warn),
            MuLogLevel::Info  => VM::start_logging_internal(LogLevel::Info),
            MuLogLevel::Debug => VM::start_logging_internal(LogLevel::Debug),
            MuLogLevel::Trace => VM::start_logging_internal(LogLevel::Trace),
        }
qinsoon's avatar
qinsoon committed
513 514 515
    }

    pub fn start_logging_trace() {
qinsoon's avatar
qinsoon committed
516 517 518 519
        VM::start_logging_internal(LogLevel::Trace)
    }

    fn start_logging_internal(level: LogLevel) {
520 521 522 523 524 525 526 527 528
        use stderrlog;

        let verbose = match level {
            LogLevel::Error => 0,
            LogLevel::Warn  => 1,
            LogLevel::Info  => 2,
            LogLevel::Debug => 3,
            LogLevel::Trace => 4,
        };
qinsoon's avatar
qinsoon committed
529

530 531 532
        match stderrlog::new().verbosity(verbose).init() {
            Ok(()) => info!("logger initialized"),
            Err(e) => error!("failed to init logger, probably already initialized: {:?}", e)
qinsoon's avatar
qinsoon committed
533 534
        }
    }
535 536

    pub fn add_exception_callsite(&self, callsite: MuName, catch: MuName, fv: MuID) {
537 538 539 540 541 542 543 544 545 546
        let mut table = self.exception_table.write().unwrap();

        if table.contains_key(&fv) {
            let mut map = table.get_mut(&fv).unwrap();
            map.insert(callsite, catch);
        } else {
            let mut new_map = HashMap::new();
            new_map.insert(callsite, catch);
            table.insert(fv, new_map);
        };
547 548
    }

549 550 551
    pub fn resume_vm(serialized_vm: &str) -> VM {
        use rustc_serialize::json;
        
552
        let vm : VM = json::decode(serialized_vm).unwrap();
553
        
554
        vm.init_runtime();
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

        // restore gc types
        {
            let type_info_guard = vm.backend_type_info.read().unwrap();
            let mut type_info_vec: Vec<Box<BackendTypeInfo>> = type_info_guard.values().map(|x| x.clone()).collect();
            type_info_vec.sort_by(|a, b| a.gc_type.id.cmp(&b.gc_type.id));

            let mut expect_id = 0;
            for ty_info in type_info_vec.iter() {
                use runtime::mm;

                let ref gc_type = ty_info.gc_type;

                if gc_type.id != expect_id {
                    debug_assert!(expect_id < gc_type.id);

                    while expect_id < gc_type.id {
                        use runtime::mm::common::gctype::GCType;

qinsoon's avatar
qinsoon committed
574
                        mm::add_gc_type(GCType::new_noreftype(0, 8));
575 576 577 578 579 580 581 582 583 584 585
                        expect_id += 1;
                    }
                }

                // now expect_id == gc_type.id
                debug_assert!(expect_id == gc_type.id);

                mm::add_gc_type(gc_type.as_ref().clone());
                expect_id += 1;
            }
        }
586

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
        // construct exception table
        vm.build_exception_table();

        vm
    }

    pub fn build_exception_table(&self) {
        let exception_table = self.exception_table.read().unwrap();
        let compiled_funcs = self.compiled_funcs.read().unwrap();
        let mut compiled_exception_table = self.compiled_exception_table.write().unwrap();

        for (fv, map) in exception_table.iter() {
            let ref compiled_func = *compiled_funcs.get(fv).unwrap().read().unwrap();

            for (callsite, catch_block) in map.iter() {
                let catch_addr = if catch_block.is_empty() {
                    unsafe {Address::zero()}
604
                } else {
605
                    resolve_symbol(catch_block.clone())
606 607
                };

608
                compiled_exception_table.insert(resolve_symbol(callsite.clone()), (catch_addr, &*compiled_func));
609 610
            }
        }
611 612
    }
    
613
    pub fn next_id(&self) -> MuID {
614 615 616
        // This only needs to be atomic, and does not need to be a synchronisation operation. The
        // only requirement for IDs is that all IDs obtained from `next_id()` are different. So
        // `Ordering::Relaxed` is sufficient.
617
        self.next_id.fetch_add(1, Ordering::Relaxed)
618 619
    }
    
620 621 622 623 624 625
    pub fn run_vm(&self) {
        self.is_running.store(true, Ordering::SeqCst);
    }
    
    pub fn is_running(&self) -> bool {
        self.is_running.load(Ordering::Relaxed)
qinsoon's avatar
qinsoon committed
626 627
    }
    
628
    pub fn set_name(&self, entity: &MuEntity) {
qinsoon's avatar
qinsoon committed
629
        let id = entity.id();
630
        let name = entity.name().unwrap();
qinsoon's avatar
qinsoon committed
631 632
        
        let mut map = self.id_name_map.write().unwrap();
633
        map.insert(id, name.clone());
qinsoon's avatar
qinsoon committed
634 635 636 637 638
        
        let mut map2 = self.name_id_map.write().unwrap();
        map2.insert(name, id);
    }
    
639
    pub fn id_of_by_refstring(&self, name: &String) -> MuID {
qinsoon's avatar
qinsoon committed
640
        let map = self.name_id_map.read().unwrap();
641 642 643 644
        match map.get(name) {
            Some(id) => *id,
            None => panic!("cannot find id for name: {}", name)
        }
645
    }
646 647 648

    /// should only used by client
    /// 'name' used internally may be slightly different to remove some special symbols
649 650
    pub fn id_of(&self, name: &str) -> MuID {
        self.id_of_by_refstring(&name.to_string())
qinsoon's avatar
qinsoon committed
651
    }
652 653 654

    /// should only used by client
    /// 'name' used internally may be slightly different to remove some special symbols
qinsoon's avatar
qinsoon committed
655 656
    pub fn name_of(&self, id: MuID) -> MuName {
        let map = self.id_name_map.read().unwrap();
657
        map.get(&id).unwrap().clone()
qinsoon's avatar
qinsoon committed
658 659
    }
    
660
    pub fn declare_const(&self, entity: MuEntityHeader, ty: P<MuType>, val: Constant) -> P<Value> {
qinsoon's avatar
qinsoon committed
661
        let mut constants = self.constants.write().unwrap();
662
        let ret = P(Value{hdr: entity, ty: ty, v: Value_::Constant(val)});
663

664
        self.declare_const_internal(&mut constants, ret.id(), ret.clone());
qinsoon's avatar
qinsoon committed
665 666 667
        
        ret
    }
668 669 670 671

    fn declare_const_internal(&self, map: &mut RwLockWriteGuard<HashMap<MuID, P<Value>>>, id: MuID, val: P<Value>) {
        debug_assert!(!map.contains_key(&id));

672
        trace!("declare const #{} = {}", id, val);
673 674
        map.insert(id, val);
    }
qinsoon's avatar
qinsoon committed
675
    
676 677 678 679 680 681 682
    pub fn get_const(&self, id: MuID) -> P<Value> {
        let const_lock = self.constants.read().unwrap();
        match const_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find const #{}", id)
        }
    }
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

    pub fn get_const_nocheck(&self, id: MuID) -> Option<P<Value>> {
        let const_lock = self.constants.read().unwrap();
        match const_lock.get(&id) {
            Some(ret) => Some(ret.clone()),
            None => None
        }
    }

    #[cfg(feature = "aot")]
    pub fn allocate_const(&self, val: P<Value>) -> ValueLocation {
        let id = val.id();
        let name = match val.name() {
            Some(name) => format!("CONST_{}_{}", id, name),
            None => format!("CONST_{}", id)
        };

        ValueLocation::Relocatable(backend::RegGroup::GPR, name)
    }
702
    
703
    pub fn declare_global(&self, entity: MuEntityHeader, ty: P<MuType>) -> P<Value> {
qinsoon's avatar
qinsoon committed
704
        let global = P(Value{
705 706
            hdr: entity,
            ty: self.declare_type(MuEntityHeader::unnamed(self.next_id()), MuType_::iref(ty.clone())),
707
            v: Value_::Global(ty)
qinsoon's avatar
qinsoon committed
708
        });
qinsoon's avatar
qinsoon committed
709 710
        
        let mut globals = self.globals.write().unwrap();
711
        let mut global_locs = self.global_locations.write().unwrap();
712

713
        self.declare_global_internal(&mut globals, &mut global_locs, global.id(), global.clone());
qinsoon's avatar
qinsoon committed
714
        
qinsoon's avatar
qinsoon committed
715
        global
qinsoon's avatar
qinsoon committed
716
    }
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

    fn declare_global_internal(
        &self,
        globals: &mut RwLockWriteGuard<HashMap<MuID, P<Value>>>,
        global_locs: &mut RwLockWriteGuard<HashMap<MuID, ValueLocation>>,
        id: MuID, val: P<Value>
    ) {
        self.declare_global_internal_no_alloc(globals, id, val.clone());
        self.alloc_global(global_locs, id, val);
    }

    // when bulk declaring, we hold locks for everything, we cannot resolve backend type, and do alloc
    fn declare_global_internal_no_alloc(
        &self,
        globals: &mut RwLockWriteGuard<HashMap<MuID, P<Value>>>,
        id: MuID, val: P<Value>
    ) {
        debug_assert!(!globals.contains_key(&id));

        info!("declare global #{} = {}", id, val);
        globals.insert(id, val.clone());
    }

    fn alloc_global(
        &self,
        global_locs: &mut RwLockWriteGuard<HashMap<MuID, ValueLocation>>,
        id: MuID, val: P<Value>
    ) {
        let backend_ty = self.get_backend_type_info(val.ty.get_referenced_ty().unwrap().id());
        let loc = gc::allocate_global(val, backend_ty);
        info!("allocate global #{} as {}", id, loc);
        global_locs.insert(id, loc);
    }
qinsoon's avatar
qinsoon committed
750
    
751 752
    pub fn declare_type(&self, entity: MuEntityHeader, ty: MuType_) -> P<MuType> {
        let ty = P(MuType{hdr: entity, v: ty});
qinsoon's avatar
qinsoon committed
753
        
qinsoon's avatar
qinsoon committed
754
        let mut types = self.types.write().unwrap();
755

756
        self.declare_type_internal(&mut types, ty.id(), ty.clone());
qinsoon's avatar
qinsoon committed
757 758 759
        
        ty
    }
760 761 762 763 764

    fn declare_type_internal(&self, types: &mut RwLockWriteGuard<HashMap<MuID, P<MuType>>>, id: MuID, ty: P<MuType>) {
        debug_assert!(!types.contains_key(&id));

        types.insert(id, ty.clone());
qinsoon's avatar
qinsoon committed
765

766
        trace!("declare type #{} = {}", id, ty);
qinsoon's avatar
qinsoon committed
767 768 769 770
        if ty.is_struct() {
            let tag = ty.get_struct_hybrid_tag().unwrap();
            let struct_map_guard = STRUCT_TAG_MAP.read().unwrap();
            let struct_inner = struct_map_guard.get(&tag).unwrap();
771
            trace!("  {}", struct_inner);
qinsoon's avatar
qinsoon committed
772 773 774 775
        } else if ty.is_hybrid() {
            let tag = ty.get_struct_hybrid_tag().unwrap();
            let hybrid_map_guard = HYBRID_TAG_MAP.read().unwrap();
            let hybrid_inner = hybrid_map_guard.get(&tag).unwrap();
776
            trace!("  {}", hybrid_inner);
qinsoon's avatar
qinsoon committed
777
        }
778
    }
qinsoon's avatar
qinsoon committed
779
    
780 781 782 783 784 785 786 787
    pub fn get_type(&self, id: MuID) -> P<MuType> {
        let type_lock = self.types.read().unwrap();
        match type_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find type #{}", id)
        }
    }    
    
788 789
    pub fn declare_func_sig(&self, entity: MuEntityHeader, ret_tys: Vec<P<MuType>>, arg_tys: Vec<P<MuType>>) -> P<MuFuncSig> {
        let ret = P(MuFuncSig{hdr: entity, ret_tys: ret_tys, arg_tys: arg_tys});
790 791

        let mut func_sigs = self.func_sigs.write().unwrap();
792
        self.declare_func_sig_internal(&mut func_sigs, ret.id(), ret.clone());
qinsoon's avatar
qinsoon committed
793 794 795
        
        ret
    }
796 797 798 799 800 801 802

    fn declare_func_sig_internal(&self, sigs: &mut RwLockWriteGuard<HashMap<MuID, P<MuFuncSig>>>, id: MuID, sig: P<MuFuncSig>) {
        debug_assert!(!sigs.contains_key(&id));

        info!("declare func sig #{} = {}", id, sig);
        sigs.insert(id, sig);
    }
qinsoon's avatar
qinsoon committed
803
    
804 805 806 807 808 809 810 811
    pub fn get_func_sig(&self, id: MuID) -> P<MuFuncSig> {
        let func_sig_lock = self.func_sigs.read().unwrap();
        match func_sig_lock.get(&id) {
            Some(ret) => ret.clone(),
            None => panic!("cannot find func sig #{}", id)
        }
    }
    
812
    pub fn declare_func (&self, func: MuFunction) {
qinsoon's avatar
qinsoon committed
813
        let mut funcs = self.funcs.write().unwrap();
814 815 816 817 818 819 820 821 822

        self.declare_func_internal(&mut funcs, func.id(), func);
    }

    fn declare_func_internal(&self, funcs: &mut RwLockWriteGuard<HashMap<MuID, RwLock<MuFunction>>>, id: MuID, func: MuFunction) {
        debug_assert!(!funcs.contains_key(&id));

        info!("declare func #{} = {}", id, func);
        funcs.insert(id, RwLock::new(func));
823
    }
824 825 826 827 828 829 830 831 832

    /// this is different than vm.name_of()
    pub fn get_func_name(&self, id: MuID) -> MuName {
        let funcs_lock = self.funcs.read().unwrap();
        match funcs_lock.get(&id) {
            Some(func) => func.read().unwrap().name().unwrap(),
            None => panic!("cannot find name for Mu function #{}")
        }
    }
833
    
834 835 836 837 838 839 840 841 842
    /// The IR builder needs to look-up the function signature from the existing function ID.
    pub fn get_func_sig_for_func(&self, id: MuID) -> P<MuFuncSig> {
        let funcs_lock = self.funcs.read().unwrap();
        match funcs_lock.get(&id) {
            Some(func) => func.read().unwrap().sig.clone(),
            None => panic!("cannot find Mu function #{}", id)
        }
    }    
    
843
    pub fn define_func_version (&self, func_ver: MuFunctionVersion) {
qinsoon's avatar
qinsoon committed
844
        info!("define function version {}", func_ver);
845
        // record this version
qinsoon's avatar
qinsoon committed
846
        let func_ver_id = func_ver.id();
847 848
        {
            let mut func_vers = self.func_vers.write().unwrap();
qinsoon's avatar
qinsoon committed
849
            func_vers.insert(func_ver_id, RwLock::new(func_ver));
850 851 852 853
        }
        
        // acquire a reference to the func_ver
        let func_vers = self.func_vers.read().unwrap();
qinsoon's avatar
qinsoon committed
854
        let func_ver = func_vers.get(&func_ver_id).unwrap().write().unwrap();
855 856 857
        
        // change current version to this (obsolete old versions)
        let funcs = self.funcs.read().unwrap();
qinsoon's avatar
qinsoon committed
858
        debug_assert!(funcs.contains_key(&func_ver.func_id)); // it should be declared before defining
qinsoon's avatar
qinsoon committed
859
        let mut func = funcs.get(&func_ver.func_id).unwrap().write().unwrap();
860
        
861 862 863 864
        func.new_version(func_ver.id());
        
        // redefinition happens here
        // do stuff        
865
    }
866 867 868 869 870 871 872 873 874 875 876 877 878 879

    /// Add a new bundle into VM.
    ///
    /// This function will drain the contents of all arguments.
    ///
    /// Ideally, this function should happen atomically. e.g. The client should not see a new type
    /// added without also seeing a new function added.
    pub fn declare_many(&self,
                        new_id_name_map: &mut HashMap<MuID, MuName>,
                        new_types: &mut HashMap<MuID, P<MuType>>,
                        new_func_sigs: &mut HashMap<MuID, P<MuFuncSig>>,
                        new_constants: &mut HashMap<MuID, P<Value>>,
                        new_globals: &mut HashMap<MuID, P<Value>>,
                        new_funcs: &mut HashMap<MuID, Box<MuFunction>>,
880 881
                        new_func_vers: &mut HashMap<MuID, Box<MuFunctionVersion>>,
                        arc_vm: Arc<VM>
882 883 884
                        ) {
        // Make sure other components, if ever acquiring multiple locks at the same time, acquire
        // them in this order, to prevent deadlock.
885 886 887 888 889 890 891 892 893
        {
            let mut id_name_map = self.id_name_map.write().unwrap();
            let mut name_id_map = self.name_id_map.write().unwrap();
            let mut types = self.types.write().unwrap();
            let mut constants = self.constants.write().unwrap();
            let mut globals = self.globals.write().unwrap();
            let mut func_sigs = self.func_sigs.write().unwrap();
            let mut funcs = self.funcs.write().unwrap();
            let mut func_vers = self.func_vers.write().unwrap();
894

895 896 897 898
            for (id, name) in new_id_name_map.drain() {
                id_name_map.insert(id, name.clone());
                name_id_map.insert(name, id);
            }
899

900 901 902
            for (id, obj) in new_types.drain() {
                self.declare_type_internal(&mut types, id, obj);
            }
903

904 905 906
            for (id, obj) in new_constants.drain() {
                self.declare_const_internal(&mut constants, id, obj);
            }
907

908 909 910 911
            for (id, obj) in new_globals.drain() {
                // we bulk allocate later (since we are holding all the locks, we cannot find ty info)
                self.declare_global_internal_no_alloc(&mut globals, id, obj);
            }
912

913 914 915
            for (id, obj) in new_func_sigs.drain() {
                self.declare_func_sig_internal(&mut func_sigs, id, obj);
            }
916

917 918 919
            for (id, obj) in new_funcs.drain() {
                self.declare_func_internal(&mut funcs, id, *obj);
            }
920

921 922 923
            for (id, obj) in new_func_vers.drain() {
                let func_id = obj.func_id;
                func_vers.insert(id, RwLock::new(*obj));
924

925 926 927 928 929 930
                {
                    trace!("Adding funcver {} as a version of {}...", id, func_id);
                    let func = funcs.get_mut(&func_id).unwrap();
                    func.write().unwrap().new_version(id);
                    trace!("Added funcver {} as a version of {} {:?}.", id, func_id, func);
                }
931 932 933
            }
        }
        // Locks released here
934 935 936 937 938 939 940

        // allocate all the globals defined
        {
            let globals = self.globals.read().unwrap();
            let mut global_locs = self.global_locations.write().unwrap();

            // make sure current thread has allocator
941
            let created = unsafe {MuThread::current_thread_as_mu_thread(Address::zero(), arc_vm.clone())};
942 943 944 945

            for (id, global) in globals.iter() {
                self.alloc_global(&mut global_locs, *id, global.clone());
            }
946 947 948 949

            if created {
                unsafe {MuThread::cleanup_current_mu_thread()};
            }
950
        }
951
    }
952
    
953
    pub fn add_compiled_func (&self, func: CompiledFunction) {
qinsoon's avatar
qinsoon committed
954
        debug_assert!(self.funcs.read().unwrap().contains_key(&func.func_id));
qinsoon's avatar
qinsoon committed
955
        debug_assert!(self.func_vers.read().unwrap().contains_key(&func.func_ver_id));
qinsoon's avatar
qinsoon committed
956

qinsoon's avatar
qinsoon committed
957
        self.compiled_funcs.write().unwrap().insert(func.func_ver_id, RwLock::new(func));
qinsoon's avatar
qinsoon committed
958 959
    }
    
qinsoon's avatar
qinsoon committed
960
    pub fn get_backend_type_info(&self, tyid: MuID) -> Box<BackendTypeInfo> {        
qinsoon's avatar
qinsoon committed
961 962 963
        {
            let read_lock = self.backend_type_info.read().unwrap();
        
964
            match read_lock.get(&tyid) {
qinsoon's avatar
qinsoon committed
965 966 967 968
                Some(info) => {return info.clone();},
                None => {}
            }
        }
969 970

        let types = self.types.read().unwrap();
qinsoon's avatar
qinsoon committed
971 972 973 974
        let ty = match types.get(&tyid) {
            Some(ty) => ty,
            None => panic!("invalid type id during get_backend_type_info(): {}", tyid)
        };
qinsoon's avatar
qinsoon committed
975
        let resolved = Box::new(backend::resolve_backend_type_info(ty, self));
qinsoon's avatar
qinsoon committed
976 977
        
        let mut write_lock = self.backend_type_info.write().unwrap();
978
        write_lock.insert(tyid, resolved.clone());
qinsoon's avatar
qinsoon committed
979 980 981 982
        
        resolved        
    }
    
qinsoon's avatar
qinsoon committed
983 984 985 986
    pub fn get_type_size(&self, tyid: MuID) -> ByteSize {
        self.get_backend_type_info(tyid).size
    }
    
qinsoon's avatar
qinsoon committed
987
    pub fn globals(&self) -> &RwLock<HashMap<MuID, P<Value>>> {
qinsoon's avatar
qinsoon committed
988 989 990
        &self.globals
    }
    
qinsoon's avatar
qinsoon committed
991
    pub fn funcs(&self) -> &RwLock<HashMap<MuID, RwLock<MuFunction>>> {
qinsoon's avatar
qinsoon committed
992
        &self.funcs
993
    }
994
    
qinsoon's avatar
qinsoon committed
995
    pub fn func_vers(&self) -> &RwLock<HashMap<MuID, RwLock<MuFunctionVersion>>> {
996 997
        &self.func_vers
    }
qinsoon's avatar
qinsoon committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

    pub fn get_cur_version_of(&self, fid: MuID) -> Option<MuID> {
        let funcs_guard = self.funcs.read().unwrap();
        match funcs_guard.get(&fid) {
            Some(rwlock_func) => {
                let func_guard = rwlock_func.read().unwrap();
                func_guard.cur_ver
            },
            None => None
        }
    }
1009
    
qinsoon's avatar
qinsoon committed
1010
    pub fn compiled_funcs(&self) -> &RwLock<HashMap<MuID, RwLock<CompiledFunction>>> {
1011 1012
        &self.compiled_funcs
    }
1013 1014 1015 1016 1017 1018 1019 1020
    
    pub fn types(&self) -> &RwLock<HashMap<MuID, P<MuType>>> {
        &self.types
    }
    
    pub fn func_sigs(&self) -> &RwLock<HashMap<MuID, P<MuFuncSig>>> {
        &self.func_sigs
    }
qinsoon's avatar
qinsoon committed
1021
    
1022 1023 1024 1025 1026 1027 1028
    pub fn resolve_function_address(&self, func_id: MuID) -> ValueLocation {
        let funcs = self.funcs.read().unwrap();
        let func : &MuFunction = &funcs.get(&func_id).unwrap().read().unwrap();
                
        if self.is_running() {
            unimplemented!()
        } else {
1029
            ValueLocation::Relocatable(backend::RegGroup::GPR, func.name().unwrap())
1030 1031 1032
        }
    }
    
qinsoon's avatar
qinsoon committed
1033
    pub fn new_stack(&self, func_id: MuID) -> Box<MuStack> {
qinsoon's avatar
qinsoon committed
1034 1035 1036
        let funcs = self.funcs.read().unwrap();
        let func : &MuFunction = &funcs.get(&func_id).unwrap().read().unwrap();
        
1037 1038 1039
        Box::new(MuStack::new(self.next_id(), self.resolve_function_address(func_id), func))
    }
    
qinsoon's avatar
qinsoon committed
1040
    pub fn make_primordial_thread(&self, func_id: MuID, has_const_args: bool, args: Vec<Constant>) {
1041
        let mut guard = self.primordial.write().unwrap();
qinsoon's avatar
qinsoon committed
1042
        *guard = Some(MuPrimordialThread{func_id: func_id, has_const_args: has_const_args, args: args});
qinsoon's avatar
qinsoon committed
1043
    }
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

    pub fn make_boot_image(&self,
                            whitelist: Vec<MuID>,
                            primordial_func: Option<&APIHandle>, primordial_stack: Option<&APIHandle>,
                            primordial_threadlocal: Option<&APIHandle>,
                            sym_fields: Vec<&APIHandle>, sym_strings: Vec<String>,
                            reloc_fields: Vec<&APIHandle>, reloc_strings: Vec<String>,
                            output_file: String) {
        self.make_boot_image_internal(
            whitelist,
            primordial_func, primordial_stack,
            primordial_threadlocal,
            sym_fields, sym_strings,
            reloc_fields, reloc_strings,
            vec![],
            output_file
        )
    }
qinsoon's avatar
qinsoon committed
1062
    
qinsoon's avatar
qinsoon committed
1063
    #[allow(unused_variables)]
1064 1065 1066 1067 1068 1069 1070 1071
    pub fn make_boot_image_internal(&self,
                                   whitelist: Vec<MuID>,
                                   primordial_func: Option<&APIHandle>, primordial_stack: Option<&APIHandle>,
                                   primordial_threadlocal: Option<&APIHandle>,
                                   sym_fields: Vec<&APIHandle>, sym_strings: Vec<String>,
                                   reloc_fields: Vec<&APIHandle>, reloc_strings: Vec<String>,
                                   extra_sources_to_link: Vec<String>,
                                   output_file: String) {