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.
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.
11 #![feature(rustc_private)]
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;
23 use std::ffi::{CStr, CString};
24 use std::mem::transmute;
25 use std::path::PathBuf;
27 use std::thread::Builder;
29 use rustc::front::map as ast_map;
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;
41 use syntax::diagnostics::registry::Registry;
42 use syntax::parse::token;
47 pub static TEST_STATIC: i32 = 42;
52 pub fn test_add(a: i32, b: i32) -> i32 { a + b }
55 let mut path = match std::env::args().nth(2) {
56 Some(path) => PathBuf::from(&path),
57 None => panic!("missing rustc path")
60 // Remove two segments from rustc path to get sysroot.
64 let mut ee = ExecutionEngine::new(program, path);
66 let test_static = match ee.get_global("TEST_STATIC") {
67 Some(g) => g as *const i32,
68 None => panic!("failed to get global")
71 assert_eq!(unsafe { *test_static }, 42);
73 ee.add_module(program2);
75 let test_add: fn(i32, i32) -> i32;
77 test_add = match ee.get_function("test_add") {
78 Some(f) => unsafe { transmute(f) },
79 None => panic!("failed to get function")
82 assert_eq!(test_add(1, 2), 3);
85 struct ExecutionEngine {
86 ee: llvm::ExecutionEngineRef,
87 modules: Vec<llvm::ModuleRef>,
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");
96 let ee = unsafe { llvm::LLVMBuildExecutionEngine(llmod) };
99 panic!("Failed to create ExecutionEngine: {}", llvm_error());
102 let ee = ExecutionEngine{
104 modules: vec![llmod],
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");
116 unsafe { llvm::LLVMExecutionEngineAddModule(self.ee, llmod); }
118 self.modules.push(llmod);
119 self.load_deps(&deps);
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();
126 for &m in &self.modules {
127 let fv = unsafe { llvm::LLVMGetNamedFunction(m, s.as_ptr()) };
130 let fp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, fv) };
132 assert!(!fp.is_null());
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();
143 for &m in &self.modules {
144 let gv = unsafe { llvm::LLVMGetNamedGlobal(m, s.as_ptr()) };
147 let gp = unsafe { llvm::LLVMGetPointerToGlobal(self.ee, gv) };
149 assert!(!gp.is_null());
156 /// Loads all dependencies of compiled code.
157 /// Expects a series of paths to dynamic library files.
158 fn load_deps(&self, deps: &[PathBuf]) {
160 let s = match path.as_os_str().to_str() {
163 "Could not convert crate path to UTF-8 string: {:?}", path)
165 let cs = CString::new(s).unwrap();
167 let res = unsafe { llvm::LLVMRustLoadDynamicLibrary(cs.as_ptr()) };
170 panic!("Failed to load crate {:?}: {}",
171 path.display(), llvm_error());
177 impl Drop for ExecutionEngine {
179 unsafe { llvm::LLVMDisposeExecutionEngine(self.ee) };
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() })
190 fn build_exec_options(sysroot: PathBuf) -> Options {
191 let mut opts = basic_options();
193 // librustc derives sysroot from the executable name.
194 // Since we are not rustc, we must specify it.
195 opts.maybe_sysroot = Some(sysroot);
197 // Prefer faster build time
198 opts.optimize = config::OptLevel::No;
200 // Don't require a `main` function
201 opts.crate_types = vec![config::CrateTypeDylib];
206 /// Compiles input up to phase 4, translation to LLVM.
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());
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),
220 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
222 let cfg = build_configuration(&sess);
224 let id = "input".to_string();
226 let krate = driver::phase_1_parse_input(&sess, cfg, &input);
228 let krate = driver::phase_2_configure_and_expand(&sess, &cstore, krate, &id, None)
229 .expect("phase_2 returned `None`");
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);
237 abort_on_err(driver::phase_3_run_analysis_passes(
238 &sess, &cstore, ast_map, &arenas, &id,
239 MakeGlobMap::No, |tcx, mir_map, analysis| {
241 let trans = driver::phase_4_translate_to_llvm(tcx, mir_map, analysis);
243 let crates = tcx.sess.cstore.used_crates(LinkagePreference::RequireDynamic);
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();
250 assert_eq!(trans.modules.len(), 1);
251 let llmod = trans.modules[0].llmod;
253 // Workaround because raw pointers do not impl Send
254 let modp = llmod as usize;
260 match handle.join() {
261 Ok((llmod, deps)) => Some((llmod as llvm::ModuleRef, deps)),