tor_allocate.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. use libc::{c_char, c_void};
  2. use std::{ptr, slice, mem};
  3. #[cfg(not(test))]
  4. extern "C" {
  5. fn tor_malloc_ ( size: usize) -> *mut c_void;
  6. }
  7. // Defined only for tests, used for testing purposes, so that we don't need
  8. // to link to tor C files. Uses the system allocator
  9. #[cfg(test)]
  10. extern "C" fn tor_malloc_ ( size: usize) -> *mut c_void {
  11. use libc::malloc;
  12. unsafe { malloc(size) }
  13. }
  14. /// Allocate memory using tor_malloc_ and copy an existing string into the
  15. /// allocated buffer, returning a pointer that can later be called in C.
  16. ///
  17. /// # Inputs
  18. ///
  19. /// * `src`, a reference to a String.
  20. ///
  21. /// # Returns
  22. ///
  23. /// A `*mut c_char` that should be freed by tor_free in C
  24. ///
  25. pub fn allocate_and_copy_string(src: &String) -> *mut c_char {
  26. let bytes: &[u8] = src.as_bytes();
  27. let size = mem::size_of_val::<[u8]>(bytes);
  28. let size_one_byte = mem::size_of::<u8>();
  29. // handle integer overflow when adding one to the calculated length
  30. let size_with_null_byte = match size.checked_add(size_one_byte) {
  31. Some(n) => n,
  32. None => return ptr::null_mut(),
  33. };
  34. let dest = unsafe { tor_malloc_(size_with_null_byte) as *mut u8 };
  35. if dest.is_null() {
  36. return ptr::null_mut();
  37. }
  38. unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), dest, size) };
  39. // set the last byte as null, using the ability to index into a slice
  40. // rather than doing pointer arithmatic
  41. let slice = unsafe { slice::from_raw_parts_mut(dest, size_with_null_byte)};
  42. slice[size] = 0; // add a null terminator
  43. dest as *mut c_char
  44. }
  45. #[cfg(test)]
  46. mod test {
  47. #[test]
  48. fn test_allocate_and_copy_string_with_empty() {
  49. use std::ffi::CStr;
  50. use libc::{free, c_void};
  51. use tor_allocate::allocate_and_copy_string;
  52. let empty = String::new();
  53. let allocated_empty = allocate_and_copy_string(&empty);
  54. let allocated_empty_rust = unsafe {
  55. CStr::from_ptr(allocated_empty).to_str().unwrap()
  56. };
  57. assert_eq!("", allocated_empty_rust);
  58. unsafe { free(allocated_empty as *mut c_void) };
  59. }
  60. #[test]
  61. fn test_allocate_and_copy_string_with_not_empty_string() {
  62. use std::ffi::CStr;
  63. use libc::{free, c_void};
  64. use tor_allocate::allocate_and_copy_string;
  65. let empty = String::from("foo bar biz");
  66. let allocated_empty = allocate_and_copy_string(&empty);
  67. let allocated_empty_rust = unsafe {
  68. CStr::from_ptr(allocated_empty).to_str().unwrap()
  69. };
  70. assert_eq!("foo bar biz", allocated_empty_rust);
  71. unsafe { free(allocated_empty as *mut c_void) };
  72. }
  73. }