xref: /llvm-project/clang/test/Analysis/suppression-attr-doc.cpp (revision 017675fff116c26bef7f0a389c983c909a3141fd)
1 // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix \
2 // RUN:                    -analyzer-disable-checker=core.uninitialized \
3 // RUN:                    -verify %s
4 
5 // NOTE: These tests correspond to examples provided in documentation
6 // of [[clang::suppress]]. If you break them intentionally, it's likely that
7 // you need to update the documentation!
8 
9 typedef __typeof(sizeof(int)) size_t;
10 void *malloc(size_t);
11 
foo_initial()12 int foo_initial() {
13   int *x = nullptr;
14   return *x; // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
15 }
16 
foo1()17 int foo1() {
18   int *x = nullptr;
19   [[clang::suppress]]
20   return *x;  // null pointer dereference warning suppressed here
21 }
22 
foo2()23 int foo2() {
24   [[clang::suppress]] {
25     int *x = nullptr;
26     return *x;  // null pointer dereference warning suppressed here
27   }
28 }
29 
bar_initial(bool coin_flip)30 int bar_initial(bool coin_flip) {
31   int *result = (int *)malloc(sizeof(int));
32   if (coin_flip)
33     return 1; // There's no warning here YET, but it will show up if the other one is suppressed.
34 
35   return *result;  // expected-warning{{Potential leak of memory pointed to by 'result'}}
36 }
37 
bar1(bool coin_flip)38 int bar1(bool coin_flip) {
39   __attribute__((suppress))
40   int *result = (int *)malloc(sizeof(int));
41   if (coin_flip)
42     return 1;  // warning about this leak path is suppressed
43 
44   return *result;  // warning about this leak path also suppressed
45 }
46 
bar2(bool coin_flip)47 int bar2(bool coin_flip) {
48   int *result = (int *)malloc(sizeof(int));
49   if (coin_flip)
50     return 1;  // expected-warning{{Potential leak of memory pointed to by 'result'}}
51 
52   __attribute__((suppress))
53   return *result;  // leak warning is suppressed only on this path
54 }
55 
56 class [[clang::suppress]] C {
foo()57   int foo() {
58     int *x = nullptr;
59     return *x;  // warnings suppressed in the entire class
60   }
61 
62   int bar();
63 };
64 
bar()65 int C::bar() {
66   int *x = nullptr;
67   return *x;  // expected-warning{{Dereference of null pointer (loaded from variable 'x')}}
68 }
69