Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. extern crate libc;
  2.  
  3. use std::mem;
  4. use std::ops::{Index, IndexMut};
  5.  
  6. extern "C" {
  7. fn memset(s: *mut libc::c_void, c: libc::uint32_t, n: libc::size_t) -> *mut libc::c_void;
  8. }
  9.  
  10. const PAGE_SIZE: usize = 4096;
  11.  
  12. struct JitMemory {
  13. contents: *mut u8,
  14. }
  15.  
  16. impl JitMemory {
  17. fn new(num_pages: usize) -> JitMemory {
  18. let contents: *mut u8;
  19. unsafe {
  20. let size = num_pages * PAGE_SIZE;
  21. let mut _contents: *mut libc::c_void = mem::uninitialized();
  22. libc::posix_memalign(&mut _contents, PAGE_SIZE, size);
  23. libc::mprotect(
  24. _contents,
  25. size,
  26. libc::PROT_EXEC | libc::PROT_READ | libc::PROT_WRITE,
  27. );
  28.  
  29. memset(_contents, 0xc3, size); // for now, prepopulate with 'RET'
  30.  
  31. contents = mem::transmute(_contents);
  32. }
  33.  
  34. JitMemory { contents: contents }
  35. }
  36. }
  37.  
  38. struct JitMemoryIndex {
  39. value: JitMemory,
  40. index: usize,
  41. }
  42.  
  43. impl JitMemoryIndex {
  44. fn new(num_pages: usize) -> JitMemoryIndex {
  45. JitMemoryIndex {
  46. value: JitMemory::new(num_pages),
  47. index: 0,
  48. }
  49. }
  50.  
  51. fn insert(&mut self, value: u8) {
  52. self.value[self.index] = value;
  53. self.index += 1;
  54. }
  55. }
  56.  
  57. impl Index<usize> for JitMemory {
  58. type Output = u8;
  59.  
  60. fn index(&self, _index: usize) -> &u8 {
  61. unsafe { &*self.contents.offset(_index as isize) }
  62. }
  63. }
  64.  
  65. impl IndexMut<usize> for JitMemory {
  66. fn index_mut(&mut self, _index: usize) -> &mut u8 {
  67. unsafe { &mut *self.contents.offset(_index as isize) }
  68. }
  69. }
  70.  
  71. fn main() {
  72. let mut jit: JitMemoryIndex = JitMemoryIndex::new(1);
  73.  
  74. jit.insert(0x48);
  75. jit.insert(0xc7);
  76. jit.insert(0xc0);
  77. jit.insert(0x64);
  78. jit.insert(0);
  79. jit.insert(0);
  80. jit.insert(0);
  81.  
  82. let run_jit: (fn() -> i64) = unsafe { mem::transmute(jit.value.contents) };
  83. println!("{}", run_jit());
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement