]> git.lizzy.rs Git - rust.git/blob - src/test/run-make/execution-engine/test.rs
fe6a5faf9324a3a46e4b0bdd8634c9e14c9d0f40
[rust.git] / src / test / run-make / execution-engine / test.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(rustc_private)]
12 #![feature(libc)]
13
14 extern crate libc;
15 extern crate rustc;
16 extern crate rustc_driver;
17 extern crate rustc_front;
18 extern crate rustc_lint;
19 extern crate rustc_metadata;
20 extern crate rustc_resolve;
21 extern crate syntax;
22
23 use std::ffi::{CStr, CString};
24 use std::mem::transmute;
25 use std::path::PathBuf;
26 use std::rc::Rc;
27 use std::thread::Builder;
28
29 use rustc::front::map as ast_map;
30 use rustc::llvm;
31 use rustc::middle::cstore::{CrateStore, LinkagePreference};
32 use rustc::middle::ty;
33 use rustc::session::config::{self, basic_options, build_configuration, Input, Options};
34 use rustc::session::build_session;
35 use rustc_driver::{driver, abort_on_err};
36 use rustc_front::lowering::{lower_crate, LoweringContext};
37 use rustc_resolve::MakeGlobMap;
38 use rustc_metadata::cstore::CStore;
39 use libc::c_void;
40
41 use syntax::diagnostics::registry::Registry;
42 use syntax::parse::token;
43
44 fn main() {
45     let program = r#"
46     #[no_mangle]
47     pub static TEST_STATIC: i32 = 42;
48     "#;
49
50     let program2 = r#"
51     #[no_mangle]
52     pub fn test_add(a: i32, b: i32) -> i32 { a + b }
53     "#;
54
55     let mut path = match std::env::args().nth(2) {
56         Some(path) => PathBuf::from(&path),
57         None => panic!("missing rustc path")
58     };
59
60     // Remove two segments from rustc path to get sysroot.
61     path.pop();
62     path.pop();
63
64     let mut ee = ExecutionEngine::new(program, path);
65
66     let test_static = match ee.get_global("TEST_STATIC") {
67         Some(g) => g as *const i32,
68         None => panic!("failed to get global")
69     };
70
71     assert_eq!(unsafe { *test_static }, 42);
72
73     ee.add_module(program2);
74
75     let test_add: fn(i32, i32) -> i32;
76
77     test_add = match ee.get_function("test_add") {
78         Some(f) => unsafe { transmute(f) },
79         None => panic!("failed to get function")
80     };
81
82     assert_eq!(test_add(1, 2), 3);
83 }
84
85 struct ExecutionEngine {
86     ee: llvm::ExecutionEngineRef,
87     modules: Vec<llvm::ModuleRef>,
88     sysroot: PathBuf,
89 }
90
91 impl ExecutionEngine {
92     pub fn new(program: &str, sysroot: PathBuf) -> ExecutionEngine {
93         let (llmod, deps) = compile_program(program, sysroot.clone())
94             .expect("failed to compile program");
95
96         let ee = unsafe { llvm::LLVMBuildExecutionEngine(llmod) };
97
98         if ee.is_null() {
99             panic!("Failed to create ExecutionEngine: {}", llvm_error());
100         }
101
102         let ee = ExecutionEngine{
103             ee: ee,
104             modules: vec![llmod],
105             sysroot: sysroot,
106         };
107
108         ee.load_deps(&deps);
109         ee
110     }
111
112     pub fn add_module(&mut self, program: &str) {
113         let (llmod, deps) = compile_program(program, self.sysroot.clone())
114             .expect("failed to compile program in add_module");
115
116         unsafe { llvm::LLVMExecutionEngineAddModule(self.ee, llmod); }
117
118         self.modules.push(llmod);
119         self.load_deps(&deps);
120     }
121
122     /// Returns a raw pointer to the named function.
123     pub fn get_function(&mut self, name: &str) -> Option<*const c_void> {
124         let s = CString::new(name.as_bytes()).unwrap();
125
126         for &m in &self.modules {
127             let fv = unsafe { llvm::LLVMGetNamedFunction(m, s.as_ptr()) };
128
129             if !fv.is_null() {
130                 let fp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, fv) };
131
132                 assert!(!fp.is_null());
133                 return Some(fp);
134             }
135         }
136         None
137     }
138
139     /// Returns a raw pointer to the named global item.
140     pub fn get_global(&mut self, name: &str) -> Option<*const c_void> {
141         let s = CString::new(name.as_bytes()).unwrap();
142
143         for &m in &self.modules {
144             let gv = unsafe { llvm::LLVMGetNamedGlobal(m, s.as_ptr()) };
145
146             if !gv.is_null() {
147                 let gp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, gv) };
148
149                 assert!(!gp.is_null());
150                 return Some(gp);
151             }
152         }
153         None
154     }
155
156     /// Loads all dependencies of compiled code.
157     /// Expects a series of paths to dynamic library files.
158     fn load_deps(&self, deps: &[PathBuf]) {
159         for path in deps {
160             let s = match path.as_os_str().to_str() {
161                 Some(s) => s,
162                 None => panic!(
163                     "Could not convert crate path to UTF-8 string: {:?}", path)
164             };
165             let cs = CString::new(s).unwrap();
166
167             let res = unsafe { llvm::LLVMRustLoadDynamicLibrary(cs.as_ptr()) };
168
169             if res == 0 {
170                 panic!("Failed to load crate {:?}: {}",
171                     path.display(), llvm_error());
172             }
173         }
174     }
175 }
176
177 impl Drop for ExecutionEngine {
178     fn drop(&mut self) {
179         unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) };
180     }
181 }
182
183 /// Returns last error from LLVM wrapper code.
184 fn llvm_error() -> String {
185     String::from_utf8_lossy(
186         unsafe { CStr::from_ptr(llvm::LLVMRustGetLastError()).to_bytes() })
187         .into_owned()
188 }
189
190 fn build_exec_options(sysroot: PathBuf) -> Options {
191     let mut opts = basic_options();
192
193     // librustc derives sysroot from the executable name.
194     // Since we are not rustc, we must specify it.
195     opts.maybe_sysroot = Some(sysroot);
196
197     // Prefer faster build time
198     opts.optimize = config::OptLevel::No;
199
200     // Don't require a `main` function
201     opts.crate_types = vec![config::CrateTypeDylib];
202
203     opts
204 }
205
206 /// Compiles input up to phase 4, translation to LLVM.
207 ///
208 /// Returns the LLVM `ModuleRef` and a series of paths to dynamic libraries
209 /// for crates used in the given input.
210 fn compile_program(input: &str, sysroot: PathBuf)
211                    -> Option<(llvm::ModuleRef, Vec<PathBuf>)> {
212     let input = Input::Str(input.to_string());
213     let thread = Builder::new().name("compile_program".to_string());
214
215     let handle = thread.spawn(move || {
216         let opts = build_exec_options(sysroot);
217         let cstore = Rc::new(CStore::new(token::get_ident_interner()));
218         let sess = build_session(opts, None, Registry::new(&rustc::DIAGNOSTICS),
219                                  cstore.clone());
220         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
221
222         let cfg = build_configuration(&sess);
223
224         let id = "input".to_string();
225
226         let krate = driver::phase_1_parse_input(&sess, cfg, &input);
227
228         let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, &id, None)
229             .expect("phase_2 returned `None`");
230
231         let krate = driver::assign_node_ids(&sess, krate);
232         let lcx = LoweringContext::new(&sess, Some(&krate));
233         let mut hir_forest = ast_map::Forest::new(lower_crate(&lcx, &krate));
234         let arenas = ty::CtxtArenas::new();
235         let ast_map = driver::make_map(&sess, &mut hir_forest);
236
237         abort_on_err(driver::phase_3_run_analysis_passes(
238             &sess, &cstore, ast_map, &arenas, &id,
239             MakeGlobMap::No, |tcx, mir_map, analysis| {
240
241             let trans = driver::phase_4_translate_to_llvm(tcx, mir_map, analysis);
242
243             let crates = tcx.sess.cstore.used_crates(LinkagePreference::RequireDynamic);
244
245             // Collect crates used in the session.
246             // Reverse order finds dependencies first.
247             let deps = crates.into_iter().rev()
248                 .filter_map(|(_, p)| p).collect();
249
250             assert_eq!(trans.modules.len(), 1);
251             let llmod = trans.modules[0].llmod;
252
253             // Workaround because raw pointers do not impl Send
254             let modp = llmod as usize;
255
256             (modp, deps)
257         }), &sess)
258     }).unwrap();
259
260     match handle.join() {
261         Ok((llmod, deps)) => Some((llmod as llvm::ModuleRef, deps)),
262         Err(_) => None
263     }
264 }