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
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use backtrace::Backtrace;
use libc;
use log::{info, warn};
use rand::Rng;
use std::alloc::{GlobalAlloc, Layout};
use std::cell::RefCell;
use std::cmp::{max, min};
use std::fs::OpenOptions;
use std::io::Write;
use std::mem;
use std::os::raw::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};

const MEBIBYTE: usize = 1024 * 1024;
const MIN_BLOCK_SIZE: usize = 1000;
const SMALL_BLOCK_TRACE_PROBABILITY: usize = 1;
const REPORT_USAGE_INTERVAL: usize = 512 * MEBIBYTE;
const SKIP_ADDR: u64 = 0x700000000000;
const PRINT_STACK_TRACE_ON_MEMORY_SPIKE: bool = true;

#[cfg(target_os = "linux")]
const ENABLE_STACK_TRACE: bool = true;

// Currently there is no point in getting stack traces on non-linux platform, because other tools don't support linux.
#[cfg(not(target_os = "linux"))]
const ENABLE_STACK_TRACE: bool = false;

const COUNTERS_SIZE: usize = 16384;
static TOTAL_MEMORY_USAGE: AtomicUsize = AtomicUsize::new(0);
static MEM_SIZE: [AtomicUsize; COUNTERS_SIZE] = unsafe {
    // SAFETY: Rust [guarantees](https://doc.rust-lang.org/stable/std/sync/atomic/struct.AtomicUsize.html)
    // that `usize` and `AtomicUsize` have the same representation.
    std::mem::transmute::<[usize; COUNTERS_SIZE], [AtomicUsize; COUNTERS_SIZE]>([0usize; 16384])
};
static MEM_CNT: [AtomicUsize; COUNTERS_SIZE] = unsafe {
    std::mem::transmute::<[usize; COUNTERS_SIZE], [AtomicUsize; COUNTERS_SIZE]>([0usize; 16384])
};

static mut SKIP_PTR: [u8; 1 << 20] = [0; 1 << 20];
static mut CHECKED_PTR: [u8; 1 << 20] = [0; 1 << 20];

const STACK_SIZE: usize = 1;
const MAX_STACK: usize = 15;
const SAVE_STACK_TRACES_TO_FILE: bool = false;

const SKIPPED_TRACE: *mut c_void = 1 as *mut c_void;
const MISSING_TRACE: *mut c_void = 2 as *mut c_void;

#[repr(C)]
struct AllocHeader {
    magic: u64,
    size: u64,
    tid: u64,
    stack: [*mut c_void; STACK_SIZE],
}

const HEADER_SIZE: usize = mem::size_of::<AllocHeader>();
const MAGIC_RUST: usize = 0x12345678991100;

thread_local! {
    pub static TID: RefCell<usize> = RefCell::new(0);
    pub static IN_TRACE: RefCell<usize> = RefCell::new(0);
    pub static MEMORY_USAGE_MAX: RefCell<usize> = RefCell::new(0);
    pub static MEMORY_USAGE_LAST_REPORT: RefCell<usize> = RefCell::new(0);
}

#[cfg(not(target_os = "linux"))]
pub static NTHREADS: AtomicUsize = AtomicUsize::new(0);

#[cfg(target_os = "linux")]
pub fn get_tid() -> usize {
    let res = TID.with(|t| {
        if *t.borrow() == 0 {
            *t.borrow_mut() = nix::unistd::gettid().as_raw() as usize;
        }
        *t.borrow()
    });
    res
}

#[cfg(not(target_os = "linux"))]
pub fn get_tid() -> usize {
    let res = TID.with(|t| {
        if *t.borrow() == 0 {
            *t.borrow_mut() = NTHREADS.fetch_add(1, Ordering::SeqCst) as usize;
        }
        *t.borrow()
    });
    res
}

pub fn murmur64(mut h: u64) -> u64 {
    h ^= h >> 33;
    h = h.overflowing_mul(0xff51afd7ed558ccd).0;
    h ^= h >> 33;
    h = h.overflowing_mul(0xc4ceb9fe1a85ec53).0;
    h ^= h >> 33;
    return h;
}

const IGNORE_START: &'static [&'static str] = &[
    "__rg_",
    "_ZN5actix",
    "_ZN5alloc",
    "_ZN6base64",
    "_ZN6cached",
    "_ZN4core",
    "_ZN9hashbrown",
    "_ZN20reed_solomon_erasure",
    "_ZN5tokio",
    "_ZN10tokio_util",
    "_ZN3std",
    "_ZN8smallvec",
];

const IGNORE_INSIDE: &'static [&'static str] = &[
    "$LT$actix..",
    "$LT$alloc..",
    "$LT$base64..",
    "$LT$cached..",
    "$LT$core..",
    "$LT$hashbrown..",
    "$LT$reed_solomon_erasure..",
    "$LT$tokio..",
    "$LT$tokio_util..",
    "$LT$serde_json..",
    "$LT$std..",
    "$LT$tracing_subscriber..",
];

fn skip_ptr(addr: *mut c_void) -> bool {
    if addr as u64 >= SKIP_ADDR {
        return true;
    }
    let mut found = false;
    backtrace::resolve(addr, |symbol| {
        if let Some(name) = symbol.name() {
            let name = name.as_str().unwrap_or("");
            for &s in IGNORE_START {
                if name.starts_with(s) {
                    found = true;
                    break;
                }
            }
            for &s in IGNORE_INSIDE {
                if name.contains(s) {
                    found = true;
                    break;
                }
            }
        }
    });

    return found;
}

pub fn total_memory_usage() -> usize {
    TOTAL_MEMORY_USAGE.load(Ordering::SeqCst)
}

pub fn current_thread_memory_usage() -> usize {
    let tid = get_tid();
    let memory_usage = MEM_SIZE[tid % COUNTERS_SIZE].load(Ordering::SeqCst);
    memory_usage
}

pub fn thread_memory_usage(tid: usize) -> usize {
    let memory_usage = MEM_SIZE[tid % COUNTERS_SIZE].load(Ordering::SeqCst);
    memory_usage
}

pub fn thread_memory_count(tid: usize) -> usize {
    let memory_cnt = MEM_CNT[tid % COUNTERS_SIZE].load(Ordering::SeqCst);
    memory_cnt
}

pub fn current_thread_peak_memory_usage() -> usize {
    MEMORY_USAGE_MAX.with(|x| *x.borrow())
}

pub fn reset_memory_usage_max() {
    let tid = get_tid();
    let memory_usage = MEM_SIZE[tid % COUNTERS_SIZE].load(Ordering::SeqCst);
    MEMORY_USAGE_MAX.with(|x| *x.borrow_mut() = memory_usage);
}

pub struct MyAllocator<A> {
    inner: A,
}

impl<A> MyAllocator<A> {
    pub const fn new(inner: A) -> MyAllocator<A> {
        MyAllocator { inner }
    }
}

unsafe impl<A: GlobalAlloc> GlobalAlloc for MyAllocator<A> {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let new_layout =
            Layout::from_size_align(layout.size() + HEADER_SIZE, layout.align()).unwrap();

        let res = self.inner.alloc(new_layout);

        let tid = get_tid();
        let memory_usage = layout.size()
            + MEM_SIZE[tid % COUNTERS_SIZE].fetch_add(layout.size(), Ordering::SeqCst);
        TOTAL_MEMORY_USAGE.fetch_add(layout.size(), Ordering::SeqCst);
        MEM_CNT[tid % COUNTERS_SIZE].fetch_add(1, Ordering::SeqCst);

        if PRINT_STACK_TRACE_ON_MEMORY_SPIKE
            && memory_usage > REPORT_USAGE_INTERVAL + MEMORY_USAGE_LAST_REPORT.with(|x| *x.borrow())
        {
            if IN_TRACE.with(|in_trace| *in_trace.borrow()) == 0 {
                IN_TRACE.with(|in_trace| *in_trace.borrow_mut() = 1);
                MEMORY_USAGE_LAST_REPORT.with(|x| *x.borrow_mut() = memory_usage);

                let bt = Backtrace::new();

                warn!(
                    "Thread {} reached new record of memory usage {}MiB\n{:?} added: {:?}",
                    tid,
                    memory_usage / MEBIBYTE,
                    bt,
                    layout.size() / MEBIBYTE,
                );
                IN_TRACE.with(|in_trace| *in_trace.borrow_mut() = 0);
            }
        }
        if memory_usage > MEMORY_USAGE_MAX.with(|x| *x.borrow()) {
            MEMORY_USAGE_MAX.with(|x| *x.borrow_mut() = memory_usage);
        }

        let mut addr: Option<*mut c_void> = Some(MISSING_TRACE);
        let mut ary: [*mut c_void; MAX_STACK + 1] = [0 as *mut c_void; MAX_STACK + 1];
        let mut chosen_i = 0;

        if ENABLE_STACK_TRACE && IN_TRACE.with(|in_trace| *in_trace.borrow()) == 0 {
            IN_TRACE.with(|in_trace| *in_trace.borrow_mut() = 1);
            if layout.size() >= MIN_BLOCK_SIZE
                || rand::thread_rng().gen_range(0, 100) < SMALL_BLOCK_TRACE_PROBABILITY
            {
                let size = libc::backtrace(ary.as_ptr() as *mut *mut c_void, MAX_STACK as i32);
                ary[0] = 0 as *mut c_void;
                for i in 1..min(size as usize, MAX_STACK) {
                    addr = Some(ary[i] as *mut c_void);
                    chosen_i = i;
                    if ary[i] < SKIP_ADDR as *mut c_void {
                        let hash = murmur64(ary[i] as u64) % (1 << 23);
                        if (SKIP_PTR[(hash / 8) as usize] >> hash % 8) & 1 == 1 {
                            continue;
                        }
                        if (CHECKED_PTR[(hash / 8) as usize] >> hash % 8) & 1 == 1 {
                            break;
                        }
                        if SAVE_STACK_TRACES_TO_FILE {
                            backtrace::resolve(ary[i], |symbol| {
                                let fname = format!("/tmp/logs/{}", tid);
                                if let Ok(mut f) = OpenOptions::new()
                                    .create(true)
                                    .write(true)
                                    .append(true)
                                    .open(fname)
                                {
                                    if let Some(path) = symbol.filename() {
                                        f.write(
                                            format!(
                                                "PATH {:?} {} {}\n",
                                                ary[i],
                                                symbol.lineno().unwrap_or(0),
                                                path.to_str().unwrap_or("<UNKNOWN>")
                                            )
                                            .as_bytes(),
                                        )
                                        .unwrap();
                                    }
                                    if let Some(name) = symbol.name() {
                                        f.write(
                                            format!("SYMBOL {:?} {}\n", ary[i], name.to_string())
                                                .as_bytes(),
                                        )
                                        .unwrap();
                                    }
                                }
                            });
                        }

                        let should_skip = skip_ptr(ary[i]);
                        if should_skip {
                            SKIP_PTR[(hash / 8) as usize] |= 1 << hash % 8;
                            continue;
                        }
                        CHECKED_PTR[(hash / 8) as usize] |= 1 << hash % 8;

                        if SAVE_STACK_TRACES_TO_FILE {
                            let fname = format!("/tmp/logs/{}", tid);

                            if let Ok(mut f) = OpenOptions::new()
                                .create(true)
                                .write(true)
                                .append(true)
                                .open(fname)
                            {
                                f.write(format!("STACK_FOR {:?}\n", addr).as_bytes())
                                    .unwrap();
                                let ary2: [*mut c_void; 256] = [0 as *mut c_void; 256];
                                let size2 = libc::backtrace(ary2.as_ptr() as *mut *mut c_void, 256)
                                    as usize;
                                for i in 0..size2 {
                                    let addr2 = ary2[i];

                                    backtrace::resolve(addr2, |symbol| {
                                        if let Some(name) = symbol.name() {
                                            let name = name.as_str().unwrap_or("");

                                            f.write(
                                                format!("STACK {:?} {:?} {:?}\n", i, addr2, name)
                                                    .as_bytes(),
                                            )
                                            .unwrap();
                                        }
                                    });
                                }
                            }
                        }
                        break;
                    }
                }
            } else {
                addr = Some(SKIPPED_TRACE);
            }
            IN_TRACE.with(|in_trace| *in_trace.borrow_mut() = 0);
        }

        let mut stack = [0 as *mut c_void; STACK_SIZE];
        stack[0] = addr.unwrap_or(0 as *mut c_void);
        for i in 1..STACK_SIZE {
            stack[i] =
                ary[min(MAX_STACK as isize, max(0, chosen_i as isize + i as isize)) as usize];
        }

        let header = AllocHeader {
            magic: (MAGIC_RUST + STACK_SIZE) as u64,
            size: layout.size() as u64,
            tid: tid as u64,
            stack,
        };

        *(res as *mut AllocHeader) = header;

        res.offset(HEADER_SIZE as isize)
    }

    unsafe fn dealloc(&self, mut ptr: *mut u8, layout: Layout) {
        let new_layout =
            Layout::from_size_align(layout.size() + HEADER_SIZE, layout.align()).unwrap();

        ptr = ptr.offset(-(HEADER_SIZE as isize));

        (*(ptr as *mut AllocHeader)).magic = (MAGIC_RUST + STACK_SIZE + 0x100) as u64;
        let tid: usize = (*(ptr as *mut AllocHeader)).tid as usize;

        MEM_SIZE[tid % COUNTERS_SIZE].fetch_sub(layout.size(), Ordering::SeqCst);
        TOTAL_MEMORY_USAGE.fetch_sub(layout.size(), Ordering::SeqCst);
        MEM_CNT[tid % COUNTERS_SIZE].fetch_sub(1, Ordering::SeqCst);

        self.inner.dealloc(ptr, new_layout);
    }
}

pub fn print_counters_ary() {
    info!("tid {}", get_tid());
    let mut total_cnt: usize = 0;
    let mut total_size: usize = 0;
    for idx in 0..COUNTERS_SIZE {
        let val: usize = MEM_SIZE.get(idx).unwrap().load(Ordering::SeqCst);
        if val != 0 {
            let cnt = MEM_CNT.get(idx).unwrap().load(Ordering::SeqCst);
            total_cnt += cnt;
            info!("COUNTERS {}: {} {}", idx, cnt, val);
            total_size += val;
        }
    }
    info!("COUNTERS TOTAL {} {}", total_cnt, total_size);
}