summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: b9a7b0787ab728694e7373668e41d05bb6ada641 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::cell::RefCell;
use libc::malloc;
use std::fmt::{self, Display, Formatter};

mod parse;

#[derive(Clone, Debug)]
pub enum LeakError {
    Unexpected(char),
    InvalidSuffix(String),
    InvalidNumber(String),
    NumberNotPositive
}

impl Display for LeakError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unexpected(c) => write!(f, "Unexpected character: '{c}'"),
            Self::InvalidSuffix(s) => write!(f, "Invalid file size suffix: '{s}'"),
            Self::InvalidNumber(s) => write!(f, "Invalid number: '{s}'"),
            Self::NumberNotPositive => write!(f, "Cannot leak negative memory")
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct LeakAmount {
    to_leak: u128
}

#[derive(Copy, Clone, Debug)]
pub enum LeakMethod {
    Rust,
    Lazy,
    Unsafe
}

fn leak_rust(amount: usize) {
    Vec::<u8>::with_capacity(amount).leak();
}

thread_local!(static TOLIET: RefCell<Vec<Vec<u8>>> = RefCell::new(Vec::new()));

fn leak_lazy(amount: usize) {
    TOLIET.with(|t| {
        t.borrow_mut().push(Vec::<u8>::with_capacity(amount));
    });
}

fn leak_unsafe(amount: usize) {
    unsafe {
        malloc(amount);
    }
}

fn leak_match(amount: usize, method: LeakMethod) {
    match method {
        LeakMethod::Rust => leak_rust(amount),
        LeakMethod::Lazy => leak_lazy(amount),
        LeakMethod::Unsafe => leak_unsafe(amount),
    }
}

pub fn leak<T: Into<LeakAmount>>(amount: T, method: LeakMethod) -> Result<(), LeakError> {
    let num: u128 = amount.into().to_leak;
    
    if num <= 0 {
        return Err(LeakError::NumberNotPositive)
    } 

    let count = num / usize::MAX as u128;
    
    for _ in 0..count {
        leak_match(usize::MAX, method);    
    }

    leak_match((num % usize::MAX as u128) as usize, method);

    Ok(())
}

pub async fn leak_async<T: Into<LeakAmount> + Send>(amount: T, method: LeakMethod) -> Result<(), LeakError> {
    leak(amount, method)
}