├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE.txt ├── Makefile ├── README.md ├── examples └── math.rs └── src ├── jit ├── mod.rs └── x86_64.rs ├── lib.rs ├── macros.rs └── region.rs /.gitignore: -------------------------------------------------------------------------------- 1 | *.dylib 2 | *.rlib 3 | *.so 4 | /rust-jit 5 | /rust-jit-macros 6 | /Cargo.lock 7 | /target 8 | /asm 9 | *~ 10 | .*.swp 11 | .*.swo 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - curl -O http://static.rust-lang.org/dist/rust-nightly-x86_64-unknown-linux-gnu.tar.gz 3 | - tar -zxf rust-nightly-x86_64-unknown-linux-gnu.tar.gz 4 | - (cd rust-nightly-x86_64-unknown-linux-gnu/ && sudo ./install.sh) 5 | script: 6 | - make 7 | - make example 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "lejit" 3 | version = "0.0.1" 4 | authors = ["Arcterus "] 5 | 6 | [lib] 7 | name = "lejit" 8 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: rust-jit 2 | 3 | rust-jit: src/lib.rs src/*.rs src/jit/*.rs rust-jit-macros 4 | rustc --opt-level 3 $< 5 | touch $@ 6 | 7 | rust-jit-macros: src/macros.rs 8 | rustc --opt-level 3 $< 9 | touch $@ 10 | 11 | clean: 12 | rm rust-jit rust-jit-macros liblejit* 13 | 14 | example: examples/math.rs rust-jit 15 | rustc -L . -o example-math $< 16 | ./example-math 17 | rm example-math 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeJIT [![Build Status](https://travis-ci.org/Arcterus/lejit.png?branch=master)](https://travis-ci.org/Arcterus/lejit) # 2 | 3 | A simple JIT library written in Rust. Any help is much appreciated. 4 | 5 | ## Dependencies ## 6 | 7 | * Rust (from Git) 8 | 9 | ## Build Instructions ## 10 | 11 | ```bash 12 | make 13 | ``` 14 | 15 | ## License ## 16 | 17 | Copyright (C) 2014 by Arcterus. All rights reserved. 18 | Licensed under the MPL v2.0. See LICENSE.txt for more information. 19 | 20 | -------------------------------------------------------------------------------- /examples/math.rs: -------------------------------------------------------------------------------- 1 | #![crate_type = "bin"] 2 | 3 | #![feature(macro_rules, globs, phase)] 4 | 5 | #[phase(plugin, link)] 6 | extern crate lejit; 7 | extern crate libc; 8 | 9 | use lejit::*; 10 | use lejit::JitOp::*; 11 | use lejit::JitReg::*; 12 | 13 | fn main() { 14 | let mut jit = Jit::new(); 15 | 16 | jit.build_function("add_four".to_string(), |func| { 17 | func.op(Movrr(R1, R2)) 18 | .op(Addri(R1, 4)) 19 | .op(Call("sub_four")) 20 | .end(); 21 | }); 22 | 23 | jit.build_function("sub_four".to_string(), |func| { 24 | func.op(Movrr(R1, R2)) 25 | .op(Subri(R1, 4)) 26 | .op(Call("random_stuff")) 27 | .end(); 28 | }); 29 | 30 | jit.build_function("random_stuff".to_string(), |func| { 31 | let op = func.op(Subri(R1, 7)) 32 | .op(Addri(R1, 1000000000)); 33 | let op2 = op.op(Subri(R1, 500000000)) 34 | .op(Movri(R1, 1)) 35 | .op(Movri(R1, 10000)); 36 | op2.op(Movri(R1, 1000000000000)) 37 | .end(); 38 | }); 39 | 40 | let add = jit_compilefn!(jit, (int) -> int); 41 | println!("add(4): {}", add(4)); 42 | } 43 | -------------------------------------------------------------------------------- /src/jit/mod.rs: -------------------------------------------------------------------------------- 1 | #![experimental] 2 | 3 | use std::collections::BTreeMap; 4 | use std::os; 5 | use region::MemoryRegion; 6 | 7 | #[cfg(target_arch = "x86_64")] 8 | #[path = "x86_64.rs"] 9 | mod backend; 10 | 11 | #[experimental] 12 | pub trait Compilable<'a, 'b> { 13 | fn compile(&self, jit: &'a Jit<'a, 'b>, pos: uint) -> Vec; 14 | } 15 | 16 | #[experimental] 17 | pub trait Opcode { 18 | fn len(&self) -> uint; 19 | } 20 | 21 | #[experimental] 22 | pub trait Register { 23 | fn to_real_reg(&self) -> u8; 24 | fn extended(&self) -> bool; 25 | } 26 | 27 | #[experimental] 28 | pub enum JitOp<'a> { 29 | Addri(JitReg, u64), 30 | Subri(JitReg, u64), 31 | Mulri(JitReg, u64), 32 | Mulrr(JitReg, JitReg), 33 | Divri(JitReg, u64), 34 | Divrr(JitReg, JitReg), 35 | Movrr(JitReg, JitReg), 36 | Movri(JitReg, u64), 37 | Pushr(JitReg), 38 | Popr(JitReg), 39 | Call(&'a str), 40 | Ret 41 | } 42 | 43 | #[deriving(PartialEq)] 44 | #[experimental] 45 | pub enum JitReg { 46 | R1, 47 | R2, 48 | R3, 49 | R4, 50 | R5, 51 | R6, 52 | R7, 53 | R8, 54 | R9, 55 | R10, 56 | R11, 57 | R12, 58 | R13, 59 | R14, 60 | SP, 61 | BP 62 | } 63 | 64 | #[experimental] 65 | pub struct Jit<'a:'b, 'b> { 66 | funcs: BTreeMap>, 67 | last_func: Option<&'b JitFunction<'a, 'b>>, 68 | region: Option 69 | } 70 | 71 | #[experimental] 72 | pub struct JitFunction<'a:'b, 'b> { 73 | pub label: JitLabel, 74 | pub sublabels: Vec, 75 | pub ops: Vec>, 76 | jit: Option<&'b mut Jit<'a, 'b>>, 77 | len: uint 78 | } 79 | 80 | #[experimental] 81 | pub struct JitLabel { 82 | name: String, 83 | pos: uint 84 | } 85 | 86 | #[experimental] 87 | pub struct JitOpcode<'a:'b, 'b> { 88 | func: JitFunction<'a, 'b>, 89 | op: JitOp<'a> 90 | } 91 | 92 | #[experimental] 93 | impl<'a, 'b> Jit<'a, 'b> { 94 | pub fn new() -> Jit<'a, 'b> { 95 | Jit { 96 | funcs: BTreeMap::new(), 97 | last_func: None, 98 | region: None 99 | } 100 | } 101 | 102 | /// Creates a function with the given name and returns a JitFunction for the 103 | /// new function. 104 | fn function(&'b mut self, name: String) -> JitFunction<'a, 'b> { 105 | let pos = match self.last_func { 106 | Some(func) => func.label.pos + func.len(), 107 | None => 0 108 | }; 109 | JitFunction::new(name, Some(self), pos) 110 | } 111 | 112 | /// Builds a function with the given name and using the given closure to add 113 | /// operations to the function. 114 | /// 115 | /// # Example 116 | /// 117 | /// ``` 118 | /// let mut jit = Jit::new(); 119 | /// jit.build_function("example".to_string(), |func| { 120 | /// func.op(Movri(R1, 3)).end() 121 | /// }); 122 | /// ``` 123 | pub fn build_function(&'b mut self, name: String, cb: |func: JitFunction<'a, 'b>|) { 124 | let func = self.function(name); 125 | cb(func) 126 | } 127 | 128 | /// Tries to find and return the function with the given name. If there is 129 | /// no function with the given name, None will be returned. 130 | pub fn find_function(&'a self, name: &str) -> Option<&'b JitFunction<'a, 'b>> { 131 | self.funcs.get(name) 132 | } 133 | 134 | /// Compiles the code that has been given to the JIT so far and returns the 135 | /// executable instructions. 136 | pub fn compile(&'a self) -> Vec { 137 | let mut vec = vec!(); 138 | let mut pos = 0; 139 | for func in self.funcs.values() { 140 | let comp = func.compile(self, pos); 141 | pos += comp.len(); 142 | vec.extend(comp.into_iter()); 143 | } 144 | vec 145 | } 146 | 147 | /// Generates a memory mapped region for the executable code to be placed. 148 | /// The returned region will be invalidated if this function is called again. 149 | pub fn region(&'a mut self) -> &mut os::MemoryMap { 150 | let code = self.compile(); 151 | let mut region = match os::MemoryMap::new(code.len(), &[os::MapReadable, os::MapWritable]) { 152 | Ok(m) => m, 153 | Err(f) => panic!(f) 154 | }; 155 | region.copy(code.as_slice()); 156 | region.protect(); 157 | self.region = Some(region); 158 | self.region.as_mut().unwrap() 159 | } 160 | } 161 | 162 | #[experimental] 163 | impl<'a:'b, 'b> JitFunction<'a, 'b> { 164 | pub fn new(name: String, jit: Option<&'b mut Jit<'a, 'b>>, pos: uint) -> JitFunction<'a, 'b> { 165 | JitFunction { 166 | label: JitLabel::new(name, pos), 167 | sublabels: vec!(), 168 | ops: vec!(), 169 | jit: jit, 170 | len: 0 171 | } 172 | } 173 | 174 | pub fn op(mut self, op: JitOp<'a>) -> JitOpcode<'a, 'b> { 175 | self.len += op.len(); 176 | self.ops.push(op); 177 | JitOpcode::new(self, op) 178 | } 179 | 180 | pub fn label(&mut self, name: String) { 181 | self.sublabels.push(JitLabel::new(name, self.ops.len())); 182 | } 183 | 184 | pub fn end(mut self) { 185 | self.len += (JitOp::Ret).len(); 186 | self.ops.push(JitOp::Ret); 187 | let jit = self.jit.unwrap(); 188 | self.jit = None; 189 | let name = self.label.name.clone(); 190 | let name_clone = name.clone(); 191 | jit.funcs.insert(name, self); 192 | jit.last_func = jit.funcs.get(&name_clone); 193 | } 194 | 195 | pub fn len(&self) -> uint { self.len } 196 | } 197 | 198 | #[experimental] 199 | impl JitLabel { 200 | pub fn new(name: String, pos: uint) -> JitLabel { 201 | JitLabel { 202 | name: name, 203 | pos: pos 204 | } 205 | } 206 | } 207 | 208 | #[experimental] 209 | impl<'a:'b, 'b> JitOpcode<'a, 'b> { 210 | pub fn new(func: JitFunction<'a, 'b>, op: JitOp<'a>) -> JitOpcode<'a, 'b> { 211 | JitOpcode { 212 | func: func, 213 | op: op 214 | } 215 | } 216 | 217 | pub fn op(self, op: JitOp<'a>) -> JitOpcode<'a, 'b> { 218 | self.func.op(op) 219 | } 220 | 221 | pub fn end(self) { 222 | self.func.end() 223 | } 224 | } 225 | 226 | #[experimental] 227 | impl<'a, 'b> Opcode for JitOpcode<'a, 'b> { 228 | fn len(&self) -> uint { self.op.len() } 229 | } 230 | -------------------------------------------------------------------------------- /src/jit/x86_64.rs: -------------------------------------------------------------------------------- 1 | use std::{u8, u16, u32, u64}; 2 | use super::{Compilable, Opcode, Register, Jit, JitFunction, JitOp, JitReg}; 3 | 4 | //static REXW: u8 = 0x48; 5 | static RET: u8 = 0xc3; 6 | 7 | #[experimental] 8 | impl<'a, 'b> Compilable<'a, 'b> for JitFunction<'a, 'b> { 9 | fn compile(&self, jit: &'a Jit<'a, 'b>, pos: uint) -> Vec { 10 | let mut vec = vec!(); 11 | let mut pos = pos; 12 | for op in self.ops.iter() { 13 | let comp = op.compile(jit, pos); 14 | println!("{}", comp); 15 | pos += comp.len(); 16 | vec.extend(comp.into_iter()); 17 | } 18 | vec 19 | } 20 | } 21 | 22 | #[experimental] 23 | impl<'a> Opcode for JitOp<'a> { 24 | fn len(&self) -> uint { 25 | match *self { 26 | JitOp::Addri(_, imm) | JitOp::Subri(_, imm) => 27 | if needed_bytes(imm) == 1 { 28 | 4 29 | } else { 30 | 7 // TODO: account for 4 31 | }, 32 | JitOp::Mulri(reg, imm) => encode_mulri(reg, imm).len(), /* mul needs to be variable-length here, so... */ 33 | JitOp::Mulrr(reg1, reg2) => encode_mulrr(reg1, reg2).len(), 34 | JitOp::Divri(reg, imm) => encode_divri(reg, imm).len(), 35 | JitOp::Divrr(reg1, reg2) => encode_divrr(reg1, reg2).len(), 36 | JitOp::Movrr(reg1, reg2) => { 37 | let rex = if encode_rex(reg1, Some(reg2), false) == 0b01000000 { 0 } else { 1 }; 38 | 3 + rex 39 | } 40 | JitOp::Movri(reg, imm) => { 41 | let rex = if encode_rex(reg, None, false) == 0b01000000 { 0 } else { 1 }; 42 | rex + match imm { 43 | 1 | 2 | 3 => 5, 44 | _ => 9 45 | } 46 | }, 47 | JitOp::Pushr(reg) => 1 + if encode_rex(reg, None, false) == 0b01000000 { 0 } else { 1 }, 48 | JitOp::Popr(reg) => 1 + if encode_rex(reg, None, false) == 0b01000000 { 0 } else { 1 }, 49 | JitOp::Call(_) => 5, 50 | JitOp::Ret => 1 51 | } 52 | } 53 | } 54 | 55 | #[experimental] 56 | impl<'a, 'b> Compilable<'a, 'b> for JitOp<'a> { 57 | fn compile(&self, jit: &'a Jit<'a, 'b>, pos: uint) -> Vec { 58 | match *self { 59 | JitOp::Addri(reg, imm) => encode_addri(reg, imm), 60 | JitOp::Subri(reg, imm) => encode_subri(reg, imm), 61 | JitOp::Mulri(reg, imm) => encode_mulri(reg, imm), 62 | JitOp::Mulrr(reg1, reg2) => encode_mulrr(reg1, reg2), 63 | JitOp::Divri(reg, imm) => encode_divri(reg, imm), 64 | JitOp::Divrr(reg1, reg2) => encode_divrr(reg1, reg2), 65 | JitOp::Movrr(reg1, reg2) => encode_movrr(reg1, reg2), 66 | JitOp::Movri(reg, imm) => encode_movri(reg, imm), 67 | JitOp::Pushr(reg) => encode_pushr(reg), 68 | JitOp::Popr(reg) => encode_popr(reg), 69 | JitOp::Call(name) => encode_call(jit.find_function(name), pos), 70 | JitOp::Ret => vec!(RET), 71 | //_ => unimplemented!() // TODO: implement all ops 72 | } 73 | } 74 | } 75 | 76 | #[inline] 77 | fn encode_rex(reg: JitReg, reg2: Option, w_field: bool) -> u8 { 78 | // TODO: handle SIB if needed 79 | let mut res = if w_field { 80 | 0b01001000 81 | } else { 82 | 0b01000000 83 | }; 84 | if reg.extended() { 85 | res += if reg2.is_some() { 86 | 1 << 2 87 | } else { 88 | 1 89 | }; 90 | } 91 | if reg2.is_some() { 92 | if reg2.unwrap().extended() { 93 | res += 1; 94 | } 95 | } 96 | res 97 | } 98 | 99 | #[inline] 100 | fn encode_addri(reg: JitReg, imm: u64) -> Vec { 101 | let rex = encode_rex(reg, None, true); 102 | match needed_bytes(imm) { 103 | 1 => vec!(rex, 0x83, (0b11 << 6) + reg.to_real_reg(), imm as u8), 104 | 2 | 3 => vec!(rex, 0x81, (0b11 << 6) + reg.to_real_reg(), imm as u8, (imm >> 8) as u8, (imm >> 16) as u8, (imm >> 24) as u8), 105 | 4 => panic!(), // TODO: should mov and then add 106 | _ => unreachable!() 107 | } 108 | } 109 | 110 | #[inline] 111 | fn encode_subri(reg: JitReg, imm: u64) -> Vec { 112 | let rex = encode_rex(reg, None, true); 113 | match needed_bytes(imm) { 114 | 1 => vec!(rex, 0x83, (0b11 << 6) + (0b101 << 3) + reg.to_real_reg(), imm as u8), 115 | 2 | 3 => vec!(rex, 0x81, (0b11 << 6) + (0b101 << 3) + reg.to_real_reg(), imm as u8, (imm >> 8) as u8, (imm >> 16) as u8, (imm >> 24) as u8), 116 | 4 => panic!(), // TODO: should mov and then add 117 | _ => unreachable!() 118 | } 119 | } 120 | 121 | #[inline] 122 | fn encode_mul_div_rr(reg: JitReg, reg2: JitReg, special: u8) -> Vec { 123 | let mut res = vec!(); 124 | if reg != JitReg::R1 { /* rax */ 125 | res.extend(encode_pushr(JitReg::R1).into_iter()); 126 | res.extend(encode_movrr(JitReg::R1, reg).into_iter()); 127 | } 128 | if reg2 != JitReg::R3 { /* rsi */ 129 | res.extend(encode_pushr(JitReg::R3).into_iter()); 130 | res.extend(encode_movrr(JitReg::R3, reg2).into_iter()); 131 | } 132 | res.push_all(&[encode_rex(JitReg::R3, None, true), 0xf7, 133 | (0b11 << 6) + (special << 3) + JitReg::R3.to_real_reg()]); 134 | if reg2 != JitReg::R3 { /* rsi */ 135 | res.extend(encode_popr(JitReg::R3).into_iter()); 136 | } 137 | if reg != JitReg::R1 { /* rax */ 138 | res.extend(encode_movrr(reg, JitReg::R1).into_iter()); 139 | res.extend(encode_popr(JitReg::R1).into_iter()); 140 | } 141 | res 142 | } 143 | 144 | #[inline] 145 | fn encode_mulrr(reg: JitReg, reg2: JitReg) -> Vec { 146 | encode_mul_div_rr(reg, reg2, 0b100) 147 | } 148 | 149 | #[inline] 150 | fn encode_mulri(reg: JitReg, imm: u64) -> Vec { 151 | let mut res = vec!(); 152 | let immreg = 153 | if reg == JitReg::R3 { /* rsi */ 154 | JitReg::R5 /* rcx */ 155 | } else { 156 | JitReg::R3 157 | }; 158 | res.extend(encode_pushr(immreg).into_iter()); 159 | res.extend(encode_movri(immreg, imm).into_iter()); 160 | res.extend(encode_mulrr(reg, immreg).into_iter()); 161 | res.extend(encode_popr(immreg).into_iter()); 162 | res 163 | } 164 | 165 | #[inline] 166 | fn encode_divrr(reg1: JitReg, reg2: JitReg) -> Vec { 167 | encode_mul_div_rr(reg1, reg2, 0b110) 168 | } 169 | 170 | #[inline] 171 | fn encode_divri(reg: JitReg, imm: u64) -> Vec { 172 | let mut res = vec!(); 173 | let immreg = 174 | if reg == JitReg::R3 { /* rsi */ 175 | JitReg::R5 /* rcx */ 176 | } else { 177 | JitReg::R3 178 | }; 179 | res.extend(encode_pushr(immreg).into_iter()); 180 | res.extend(encode_movri(immreg, imm).into_iter()); 181 | res.extend(encode_divrr(reg, immreg).into_iter()); 182 | res.extend(encode_popr(immreg).into_iter()); 183 | res 184 | } 185 | 186 | #[inline] 187 | fn encode_pushr(reg: JitReg) -> Vec { 188 | let rex = encode_rex(reg, None, true); 189 | if rex == 0b01001000 { 190 | vec!(0x50 + reg.to_real_reg()) 191 | } else { 192 | vec!(rex, 0x50 + reg.to_real_reg()) 193 | } 194 | } 195 | 196 | #[inline] 197 | fn encode_popr(reg: JitReg) -> Vec { 198 | let rex = encode_rex(reg, None, true); 199 | if rex == 0b01001000 { 200 | vec!(0x58 + reg.to_real_reg()) 201 | } else { 202 | vec!(rex, 0x58 + reg.to_real_reg()) 203 | } 204 | } 205 | 206 | #[inline] 207 | fn encode_movrr(reg1: JitReg, reg2: JitReg) -> Vec { 208 | vec!(encode_rex(reg1, Some(reg2), true), 0x89, 209 | (0b11 << 6) + (reg2.to_real_reg() << 3) + reg1.to_real_reg() as u8) 210 | } 211 | 212 | #[inline] 213 | fn encode_movri(reg: JitReg, imm: u64) -> Vec { 214 | let rex = encode_rex(reg, None, false); 215 | match needed_bytes(imm) { 216 | 1 | 2 | 3 => { 217 | if rex == 0b01000000 { 218 | vec!(0xb8 + reg.to_real_reg(), imm as u8, (imm >> 8) as u8, 219 | (imm >> 16) as u8, (imm >> 24) as u8) 220 | } else { 221 | vec!(rex, 0xb8 + reg.to_real_reg(), imm as u8, (imm >> 8) as u8, 222 | (imm >> 16) as u8, (imm >> 24) as u8) 223 | } 224 | } 225 | 4 => vec!(rex + (1 << 3), 0xb8 + reg.to_real_reg(), imm as u8, 226 | (imm >> 8) as u8, (imm >> 16) as u8, (imm >> 24) as u8, 227 | (imm >> 32) as u8, (imm >> 40) as u8, (imm >> 48) as u8, 228 | (imm >> 56) as u8), 229 | _ => unreachable!() 230 | } 231 | } 232 | 233 | #[inline] 234 | fn encode_call<'a, 'b>(func: Option<&'b JitFunction<'a, 'b>>, pos: uint) -> Vec { 235 | match func { 236 | Some(func) => { 237 | let mut pos = func.label.pos as i32 - pos as i32; 238 | if pos > 0 { 239 | pos -= 5; 240 | } 241 | vec!(0xe8, pos as u8, (pos >> 8) as u8, (pos >> 16) as u8, (pos >> 24) as u8) 242 | } 243 | None => panic!() // XXX: fix 244 | } 245 | } 246 | 247 | #[inline] 248 | fn needed_bytes(num: u64) -> uint { 249 | if num <= u8::MAX as u64 { 250 | 1 251 | } else if num <= u16::MAX as u64 { 252 | 2 253 | } else if num <= u32::MAX as u64 { 254 | 3 255 | } else if num <= u64::MAX { 256 | 4 257 | } else { 258 | unreachable!() 259 | } 260 | } 261 | 262 | #[experimental] 263 | impl Register for JitReg { 264 | fn to_real_reg(&self) -> u8 { 265 | match *self { 266 | JitReg::R1 => 0b000, /* rax */ 267 | JitReg::R2 => 0b111, /* rdi */ 268 | JitReg::R3 => 0b110, /* rsi */ 269 | JitReg::R4 => 0b010, /* rdx */ 270 | JitReg::R5 => 0b001, /* rcx */ 271 | JitReg::R6 => 0b000, /* r8 */ 272 | JitReg::R7 => 0b001, /* r9 */ 273 | JitReg::R8 => 0b011, /* rbx */ 274 | JitReg::R9 => 0b010, /* r10 */ 275 | JitReg::R10 => 0b011, /* r11 */ 276 | JitReg::R11 => 0b100, /* r12 */ 277 | JitReg::R12 => 0b101, /* r13 */ 278 | JitReg::R13 => 0b110, /* r14 */ 279 | JitReg::R14 => 0b111, /* r15 */ 280 | JitReg::SP => 0b100, /* rsp */ 281 | JitReg::BP => 0b101 /* rbp */ 282 | } 283 | } 284 | 285 | fn extended(&self) -> bool { 286 | match *self { 287 | JitReg::R6 | JitReg::R7 | JitReg::R9 | JitReg::R10 | JitReg::R11 | 288 | JitReg::R12 | JitReg::R13 | JitReg::R14 => true, 289 | _ => false 290 | } 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2014 Arcterus 3 | * 4 | * This Source Code Form is subject to the terms of the Mozilla Public 5 | * License, v. 2.0. If a copy of the MPL was not distributed with this 6 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. 7 | */ 8 | 9 | #![crate_name = "lejit"] 10 | 11 | #![crate_type = "dylib"] 12 | #![crate_type = "rlib"] 13 | 14 | #![feature(globs, macro_rules)] 15 | 16 | #![experimental] 17 | 18 | //! A (hopefully) simple JIT library. 19 | //! 20 | //! # Example 21 | //! 22 | //! ``` 23 | //! #![feature(macro_rules, globs, phase)] 24 | //! 25 | //! #[phase(plugin, link)] 26 | //! extern crate lejit; 27 | //! extern crate libc; 28 | //! 29 | //! use lejit::*; 30 | //! use lejit::JitOp::*; 31 | //! use lejit::JitReg::*; 32 | //! 33 | //! fn main() { 34 | //! let mut jit = Jit::new(); 35 | //! 36 | //! jit.build_function("add_four".to_string(), |func| { 37 | //! func.op(Movrr(R1, R2)) 38 | //! .op(Addri(R1, 4)) 39 | //! .op(Call("sub_four")) 40 | //! .end(); 41 | //! }); 42 | //! 43 | //! jit.build_function("sub_four".to_string(), |func| { 44 | //! func.op(Movrr(R1, R2)) 45 | //! .op(Subri(R1, 4)) 46 | //! .op(Call("random_stuff")) 47 | //! .end(); 48 | //! }); 49 | //! 50 | //! jit.build_function("random_stuff".to_string(), |func| { 51 | //! let op = func.op(Subri(R1, 7)) 52 | //! .op(Addri(R1, 1000000000)); 53 | //! let op2 = op.op(Subri(R1, 500000000)) 54 | //! .op(Movri(R1, 1)) 55 | //! .op(Movri(R1, 10000)); 56 | //! op2.op(Movri(R1, 1000000000000)) 57 | //! .end(); 58 | //! }); 59 | //! 60 | //! let add = jit_compilefn!(jit, (int) -> int); 61 | //! println!("add(4): {}", add(4)); 62 | //! } 63 | //! ``` 64 | 65 | extern crate libc; 66 | 67 | pub use jit::*; 68 | 69 | pub mod region; 70 | pub mod jit; 71 | 72 | #[macro_export] 73 | macro_rules! jit_compilefn ( 74 | ($jit:ident, ($($types:ty),+) -> $rettype:ty) => ({ 75 | type JitFnType = extern "C" fn($($types),+) -> $rettype; 76 | let region = $jit.region(); 77 | let addr = region.data(); 78 | unsafe { ::std::mem::transmute::<*mut u8, JitFnType>(addr) } 79 | }) 80 | ) 81 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | #![crate_name = "lejit_macros"] 2 | #![crate_type = "rlib"] 3 | 4 | #![feature(macro_rules)] 5 | 6 | // TODO: probably just rewrite as a syntax extension 7 | #[macro_export] 8 | macro_rules! jit_asm ( 9 | ($jit:ident, $(fn $flabel:ident : $($(. $sublabel:ident :)* $op:path $($operands:expr),*);*)+) => ({ 10 | $({ 11 | let func = $jit.function(stringify!($flabel).to_string()); 12 | $( 13 | $( 14 | func.label(stringify!($sublabel).to_string()); 15 | )* 16 | let func = func.op(op_asm!($op $(,$operands)*)); 17 | )* 18 | func.end(); 19 | })+ 20 | }) 21 | ) 22 | 23 | #[macro_export] 24 | macro_rules! op_asm ( 25 | ($op:path, $($operands:expr),+) => ( 26 | $op($($operands),+) 27 | ); 28 | ($op:path) => ( 29 | $op 30 | ) 31 | ) 32 | -------------------------------------------------------------------------------- /src/region.rs: -------------------------------------------------------------------------------- 1 | #![experimental] 2 | 3 | use libc; 4 | use std::ptr; 5 | use std::os; 6 | 7 | #[experimental] 8 | pub trait MemoryRegion { 9 | fn protect(&mut self) -> bool; 10 | fn copy(&mut self, data: &[u8]) -> bool; 11 | } 12 | 13 | #[experimental] 14 | impl MemoryRegion for os::MemoryMap { 15 | fn protect(&mut self) -> bool { 16 | unsafe { 17 | libc::mprotect(self.data() as *mut libc::c_void, 18 | self.len() as libc::size_t, 19 | libc::PROT_READ | libc::PROT_EXEC) == -1 20 | } 21 | } 22 | 23 | fn copy(&mut self, data: &[u8]) -> bool { 24 | if data.len() > self.len() { 25 | false 26 | } else { 27 | unsafe { 28 | ptr::copy_memory(self.data(), data.as_ptr(), data.len()); 29 | } 30 | true 31 | } 32 | } 33 | } 34 | --------------------------------------------------------------------------------