brk.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. //! BRK abstractions.
  2. //!
  3. //! This module provides safe abstractions over BRK.
  4. use prelude::*;
  5. use core::ptr;
  6. use core::convert::TryInto;
  7. use shim::{syscalls, config};
  8. use {sync, fail};
  9. /// The BRK mutex.
  10. ///
  11. /// This is used for avoiding data races in multiple allocator.
  12. static BRK_MUTEX: Mutex<BrkState> = Mutex::new(BrkState {
  13. current_brk: None,
  14. });
  15. /// A cache of the BRK state.
  16. ///
  17. /// To avoid keeping asking the OS for information whenever needed, we cache it.
  18. struct BrkState {
  19. /// The program break's end
  20. current_brk: Option<Pointer<u8>>,
  21. }
  22. /// A BRK lock.
  23. pub struct BrkLock {
  24. /// The inner lock.
  25. state: sync::MutexGuard<'static, BrkState>,
  26. }
  27. impl BrkLock {
  28. /// Extend the program break.
  29. ///
  30. /// # Safety
  31. ///
  32. /// Due to being able shrink the program break, this method is unsafe.
  33. unsafe fn sbrk(&mut self, size: isize) -> Result<Pointer<u8>, ()> {
  34. log!(NOTE, "BRKing new space.");
  35. // Calculate the new program break. To avoid making multiple syscalls, we make use of the
  36. // state cache.
  37. let expected_brk = self.current_brk().offset(size);
  38. // Break it to me, babe!
  39. let old_brk = Pointer::new(syscalls::brk(*expected_brk as *const u8) as *mut u8);
  40. if expected_brk == old_brk && size != 0 {
  41. // BRK failed. This syscall is rather weird, but whenever it fails (e.g. OOM) it
  42. // returns the old (unchanged) break.
  43. Err(())
  44. } else {
  45. // Update the program break cache.
  46. self.state.current_brk = Some(expected_brk.clone());
  47. // Return the old break.
  48. Ok(old_brk)
  49. }
  50. }
  51. /// Safely release memory to the OS.
  52. ///
  53. /// If failed, we return the memory.
  54. #[allow(cast_possible_wrap)]
  55. pub fn release(&mut self, block: Block) -> Result<(), Block> {
  56. // Check if we are actually next to the program break.
  57. if self.current_brk() == Pointer::from(block.empty_right()) {
  58. log!(DEBUG, "Releasing {:?} to the OS.", block);
  59. // We are. Now, sbrk the memory back. Do to the condition above, this is safe.
  60. let res = unsafe { self.sbrk(-(block.size() as isize)) };
  61. // In debug mode, we want to check for WTF-worthy scenarios.
  62. debug_assert!(res.is_ok(), "Failed to set the program break back.");
  63. Ok(())
  64. } else {
  65. // Return the block back.
  66. Err(block)
  67. }
  68. }
  69. /// Get the current program break.
  70. ///
  71. /// If not available in the cache, requested it from the OS.
  72. fn current_brk(&mut self) -> Pointer<u8> {
  73. if let Some(ref cur) = self.state.current_brk {
  74. return cur.clone();
  75. }
  76. // TODO: Damn it, borrowck.
  77. // Get the current break.
  78. let cur = current_brk();
  79. self.state.current_brk = Some(cur.clone());
  80. cur
  81. }
  82. /// BRK new space.
  83. ///
  84. /// The first block represents the aligner segment (that is the precursor aligning the middle
  85. /// block to `align`), the second one is the result and is of exactly size `size`. The last
  86. /// block is the excessive space.
  87. ///
  88. /// # Failure
  89. ///
  90. /// This method calls the OOM handler if it is unable to acquire the needed space.
  91. // TODO: This method is possibly unsafe.
  92. pub fn canonical_brk(&mut self, size: usize, align: usize) -> (Block, Block, Block) {
  93. // Calculate the canonical size (extra space is allocated to limit the number of system calls).
  94. let brk_size = size + config::extra_brk(size) + align;
  95. // Use SBRK to allocate extra data segment. The alignment is used as precursor for our
  96. // allocated block. This ensures that it is properly memory aligned to the requested value.
  97. // TODO: Audit the casts.
  98. let (alignment_block, rest) = unsafe {
  99. Block::from_raw_parts(
  100. self.sbrk(brk_size.try_into().unwrap()).unwrap_or_else(|()| fail::oom()),
  101. brk_size,
  102. )
  103. }.align(align).unwrap();
  104. // Split the block to leave the excessive space.
  105. let (res, excessive) = rest.split(size);
  106. // Make some assertions.
  107. debug_assert!(res.aligned_to(align), "Alignment failed.");
  108. debug_assert!(res.size() + alignment_block.size() + excessive.size() == brk_size, "BRK memory leak.");
  109. (alignment_block, res, excessive)
  110. }
  111. }
  112. /// Lock the BRK lock to allow manipulating the program break.
  113. pub fn lock() -> BrkLock {
  114. BrkLock {
  115. state: BRK_MUTEX.lock(),
  116. }
  117. }
  118. /// `SBRK` symbol which can coexist with the allocator.
  119. ///
  120. /// `SBRK`-ing directly (from the `BRK` syscall or libc) might make the state inconsistent. This
  121. /// function makes sure that's not happening.
  122. ///
  123. /// With the exception of being able to coexist, it follows the same rules. Refer to the relevant
  124. /// documentation.
  125. ///
  126. /// # Failure
  127. ///
  128. /// On failure the maximum pointer (`!0 as *mut u8`) is returned.
  129. pub unsafe extern fn sbrk(size: isize) -> *mut u8 {
  130. *lock().sbrk(size).unwrap_or_else(|()| Pointer::new(!0 as *mut u8))
  131. }
  132. /// Get the current program break.
  133. fn current_brk() -> Pointer<u8> {
  134. unsafe { Pointer::new(syscalls::brk(ptr::null()) as *mut u8) }
  135. }
  136. #[cfg(test)]
  137. mod test {
  138. use super::*;
  139. #[test]
  140. fn test_ordered() {
  141. let brk = lock().canonical_brk(20, 1);
  142. assert!(brk.0 <= brk.1);
  143. assert!(brk.1 <= brk.2);
  144. }
  145. #[test]
  146. fn test_brk_grow_up() {
  147. unsafe {
  148. let brk1 = lock().sbrk(5).unwrap();
  149. let brk2 = lock().sbrk(100).unwrap();
  150. assert!(*brk1 < *brk2);
  151. }
  152. }
  153. }