File: stale_stack_leak.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (57 lines) | stat: -rw-r--r-- 2,229 bytes parent folder | download | duplicates (18)
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
// Test that out-of-scope local variables are ignored by LSan.

// LSan-in-ASan fails at -O0 on aarch64, because the stack use-after-return
// instrumentation stashes the argument to `PutPointerOnStaleStack` on the stack
// in order to conditionally call __asan_stack_malloc. This subverts our
// expectations for this test, where we assume the pointer is never stashed
// except at the bottom of the dead frame. Building at -O1 or greater solves
// this problem, because the compiler is smart enough to stash the argument in a
// callee-saved register for rematerialization instead.
// RUN: %clangxx_lsan -O1 %s -o %t

// RUN: %env_lsan_opts="report_objects=1:use_registers=0:use_stacks=1" not %run %t 2>&1 | FileCheck %s
// RUN: %env_lsan_opts="report_objects=1:use_registers=0:use_stacks=1:exitcode=0" %run %t 2>&1 | FileCheck --check-prefix=CHECK-sanity %s
//
// x86 passes parameters through stack that may lead to false negatives
// The same applies to s390x register save areas.
// UNSUPPORTED: i686,target={{(x86|powerpc64|arm|s390x).*}}

#include <stdio.h>
#include <stdlib.h>
#include "sanitizer_common/print_address.h"

void **pp;

// Put pointer far enough on the stack that LSan has space to run in without
// overwriting it.
// Hopefully the argument p will be passed on a register, saving us from false
// negatives.
__attribute__((noinline))
void *PutPointerOnStaleStack(void *p) {
  void *locals[2048];
  locals[0] = p;
  pp = &locals[0];
  print_address("Test alloc: ", 1, locals[0]);
  return 0;
}

int main() {
  PutPointerOnStaleStack(malloc(1337));
  return 0;
}

// This must run after LSan, to ensure LSan didn't overwrite the pointer before
// it had a chance to see it. If LSan is invoked with atexit(), this works.
// Otherwise, we need a different method.
__attribute__((destructor))
__attribute__((no_sanitize_address))
__attribute__((no_sanitize("hwaddress")))
void ConfirmPointerHasSurvived() {
  print_address("Value after LSan: ", 1, *pp);
}
// CHECK: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK-sanity: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK: LeakSanitizer: detected memory leaks
// CHECK: [[ADDR]] (1337 bytes)
// CHECK: SUMMARY: {{.*}}Sanitizer:
// CHECK-sanity: Value after LSan: [[ADDR]]