├── src ├── UseAfterFreeChecker.cpp ├── Registry.cpp ├── Diagnostics.h ├── TypeConfusionChecker.h ├── StrCpyOverflowChecker.h ├── CMakeLists.txt ├── TypeCastingVulnChecker.h ├── StrCpyOverflowChecker.cpp ├── Diagnostics.cpp ├── UseDefChecker.h ├── TypeConfusionChecker.cpp ├── PHPTaintChecker.h ├── TypeCastingVulnChecker.cpp ├── PHPTaintChecker.cpp └── UseDefChecker.cpp ├── tests ├── strcpy-overflow │ ├── strcpy-stack-overflow.c │ ├── expects │ │ └── strcpy-stack-overflow.c.exp │ └── test_harness.py ├── uninitialized-var │ ├── include │ │ ├── cxx-obj-declaration.h │ │ ├── cxx-function-arg-by-reference.h │ │ ├── cxx-two-constructors.h │ │ ├── cxx-exercise-buggy-paths.h │ │ ├── cxx-calls-across-object-definitions.h │ │ └── cxx-struct-field-uninitialized.h │ ├── fail-cxx-instantiated-object-var-passed-by-ref.cpp │ ├── fail-cxx-uninstantiated-object-function-call.cpp │ ├── fail-cxx-unary-lnot-operator.cpp │ ├── fail-cxx-constructor-not-defined.cpp │ ├── fail-cxx-uninitialized-var-passed-by-ref.cpp │ ├── pass-cxx-exercise-buggy-paths.cpp │ ├── pass-cxx-instantiated-object-uninitialized-field-pass-by-value.cpp │ ├── pass-cxx-functionbody-available-var-passed-by-ref.cpp │ ├── fail-cxx-two-constructors.cpp │ ├── fail-cxx-calls-across-object-definitions.cpp │ ├── fail-cxx-struct-field-uninitialized.cpp │ └── fail-cxx-uninstantiated-object-uninitialized-field.cpp ├── typeconfusion │ ├── char-to-int-declstmt.c │ ├── char-to-int.c │ ├── char-void-int-declstmt.c │ ├── expects │ │ ├── char-to-int.c.exp │ │ ├── char-void-int.c.exp │ │ ├── char-to-int-declstmt.c.exp │ │ └── char-void-int-declstmt.c.exp │ ├── char-void-int.c │ └── test_harness.py ├── typecast-bugs │ ├── expects │ │ ├── reallocarray-int-unsigned.c.exp │ │ ├── memset-implicit.c.exp │ │ ├── realloc-implicit.c.exp │ │ ├── memcpy-implicit.c.exp │ │ ├── calloc-implicit.c.exp │ │ ├── memmove-implicit.c.exp │ │ ├── strncpy-implicit.c.exp │ │ ├── malloc-implicit.c.exp │ │ ├── memset-int-unsigned.c.exp │ │ ├── realloc-int-unsigned.c.exp │ │ ├── memcpy-int-unsigned.c.exp │ │ ├── calloc-int-unsigned.c.exp │ │ ├── memmove-int-unsigned.c.exp │ │ ├── strncpy-int-unsigned.c.exp │ │ ├── malloc-int-unsigned.c.exp │ │ └── rangetest.c.exp │ ├── reallocarray-int-unsigned.c │ ├── memset-implicit.c │ ├── malloc-implicit.c │ ├── memset-int-unsigned.c │ ├── malloc-int-unsigned.c │ ├── memcpy-implicit.c │ ├── memmove-implicit.c │ ├── strncpy-implicit.c │ ├── calloc-implicit.c │ ├── memcpy-int-unsigned.c │ ├── memmove-int-unsigned.c │ ├── strncpy-int-unsigned.c │ ├── calloc-int-unsigned.c │ ├── realloc-implicit.c │ ├── realloc-int-unsigned.c │ ├── rangetest.c │ └── test_harness.py ├── phpchecker-tests │ ├── test-unsanstr.c │ ├── test-sancall.c │ ├── testmacro.h │ ├── expects │ │ ├── test-sancall.c.exp │ │ └── test-unsanstr.c.exp │ └── test_harness.py └── README.md ├── README.md ├── FindLLVM.cmake └── LICENSE /src/UseAfterFreeChecker.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/strcpy-overflow/strcpy-stack-overflow.c: -------------------------------------------------------------------------------- 1 | void f(char *src) { 2 | char dst[2]; 3 | strcpy(dst, src); 4 | } 5 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-obj-declaration.h: -------------------------------------------------------------------------------- 1 | class foo { 2 | public: 3 | foo(); 4 | int x; 5 | }; 6 | 7 | -------------------------------------------------------------------------------- /tests/typeconfusion/char-to-int-declstmt.c: -------------------------------------------------------------------------------- 1 | void f() { 2 | char a; 3 | int b; 4 | void *data = &a; 5 | b = *(int *)(data); 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-function-arg-by-reference.h: -------------------------------------------------------------------------------- 1 | class foo { 2 | public: 3 | foo() {} 4 | void bar(int &a); 5 | }; 6 | -------------------------------------------------------------------------------- /tests/typeconfusion/char-to-int.c: -------------------------------------------------------------------------------- 1 | void f() { 2 | void *data; 3 | char a; 4 | int b; 5 | data = &a; 6 | b = *(int *)(data); 7 | } 8 | 9 | 10 | -------------------------------------------------------------------------------- /tests/typeconfusion/char-void-int-declstmt.c: -------------------------------------------------------------------------------- 1 | void f() { 2 | char a; 3 | int b; 4 | void *data1 = &a; 5 | void *data2 = data1; 6 | b = *(int *)(data2); 7 | } 8 | 9 | 10 | -------------------------------------------------------------------------------- /tests/typeconfusion/expects/char-to-int.c.exp: -------------------------------------------------------------------------------- 1 | char-to-int.c:6:9: warning: data is unsafely cast from char * to int * 2 | b = *(int *)(data); 3 | ^~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/typeconfusion/char-void-int.c: -------------------------------------------------------------------------------- 1 | void f() { 2 | void *data1, *data2; 3 | char a; 4 | int b; 5 | data1 = &a; 6 | data2 = data1; 7 | b = *(int *)(data2); 8 | } 9 | 10 | 11 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-two-constructors.h: -------------------------------------------------------------------------------- 1 | class foo { 2 | public: 3 | foo() {} //default constructor missing initializer 4 | foo(int a) { m_x = a; } 5 | int m_x; 6 | }; 7 | -------------------------------------------------------------------------------- /tests/typeconfusion/expects/char-void-int.c.exp: -------------------------------------------------------------------------------- 1 | char-void-int.c:7:9: warning: data2 is unsafely cast from char * to int * 2 | b = *(int *)(data2); 3 | ^~~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/typeconfusion/expects/char-to-int-declstmt.c.exp: -------------------------------------------------------------------------------- 1 | char-to-int-declstmt.c:5:9: warning: data is unsafely cast from char * to int * 2 | b = *(int *)(data); 3 | ^~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-exercise-buggy-paths.h: -------------------------------------------------------------------------------- 1 | class foo { 2 | public: 3 | foo() : m_y(0) {} 4 | int m_x; 5 | int m_y; 6 | 7 | void do_something(); 8 | void do_something_else(); 9 | }; 10 | -------------------------------------------------------------------------------- /tests/typeconfusion/expects/char-void-int-declstmt.c.exp: -------------------------------------------------------------------------------- 1 | char-void-int-declstmt.c:6:9: warning: data2 is unsafely cast from char * to int * 2 | b = *(int *)(data2); 3 | ^~~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/strcpy-overflow/expects/strcpy-stack-overflow.c.exp: -------------------------------------------------------------------------------- 1 | strcpy-stack-overflow.c:3:4: warning: Destination of str* call is a fixed size buffer that can potentially overflow 2 | strcpy(dst, src); 3 | ^~~~~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/reallocarray-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | reallocarray-int-unsigned.c:15:10: warning: i is explicitly cast from int to unsigned int. This may be unsafe 2 | ptr = reallocarray(ptr, j, (unsigned)i); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | 1 warning generated. 5 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-calls-across-object-definitions.h: -------------------------------------------------------------------------------- 1 | class foo { 2 | public: 3 | foo() {} 4 | void updateX(); 5 | int x; 6 | bool isTrue; 7 | }; 8 | 9 | class bar { 10 | public: 11 | foo fooInstance; 12 | void call(bool cond); 13 | bar() {} 14 | }; 15 | 16 | void foo::updateX() { 17 | if(isTrue) 18 | x = 10; 19 | return; 20 | } 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | #### Directory structure 2 | 3 | - src: Source dir for Melange plugins 4 | 5 | #### Credits 6 | 7 | - A template created out of [awruef's find-heartbleed plugin][1] 8 | - CXX_FLAGS borrowed and adjusted from [AlexDenisov's ToyClang plugin][2] 9 | 10 | [1]: https://github.com/awruef/find-heartbleed 11 | [2]: https://github.com/AlexDenisov/ToyClangPlugin 12 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memset-implicit.c.exp: -------------------------------------------------------------------------------- 1 | memset-implicit.c:11:4: warning: size is implicitly cast from int to unsigned long. This may be unsafe 2 | memset(src, 0, size); 3 | ^~~~~~~~~~~~~~~~~~~~ 4 | memset-implicit.c:17:6: warning: size is implicitly cast from int to unsigned long. This may be unsafe 5 | memset(src, 0, size); 6 | ^~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/realloc-implicit.c.exp: -------------------------------------------------------------------------------- 1 | realloc-implicit.c:15:10: warning: i is implicitly cast from int to unsigned long. This may be unsafe 2 | ptr = realloc(ptr, i); 3 | ^~~~~~~~~~~~~~~ 4 | realloc-implicit.c:23:12: warning: i is implicitly cast from int to unsigned long. This may be unsafe 5 | ptr = realloc(ptr, i); 6 | ^~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memcpy-implicit.c.exp: -------------------------------------------------------------------------------- 1 | memcpy-implicit.c:13:4: warning: size is implicitly cast from int to unsigned long. This may be unsafe 2 | memcpy(dest, src, size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~ 4 | memcpy-implicit.c:20:6: warning: size is implicitly cast from int to unsigned long. This may be unsafe 5 | memcpy(dest, src, size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/calloc-implicit.c.exp: -------------------------------------------------------------------------------- 1 | calloc-implicit.c:14:16: warning: i is implicitly cast from int to unsigned long. This may be unsafe 2 | void *ptr = calloc(j, i); 3 | ^~~~~~~~~~~~ 4 | calloc-implicit.c:22:21: warning: i is implicitly cast from int to unsigned long. This may be unsafe 5 | void *ptr = calloc(j, i); 6 | ^~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memmove-implicit.c.exp: -------------------------------------------------------------------------------- 1 | memmove-implicit.c:13:4: warning: size is implicitly cast from int to unsigned long. This may be unsafe 2 | memmove(dest, src, size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~ 4 | memmove-implicit.c:20:6: warning: size is implicitly cast from int to unsigned long. This may be unsafe 5 | memmove(dest, src, size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/strncpy-implicit.c.exp: -------------------------------------------------------------------------------- 1 | strncpy-implicit.c:13:4: warning: size is implicitly cast from int to unsigned long. This may be unsafe 2 | strncpy(dest, src, size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~ 4 | strncpy-implicit.c:20:6: warning: size is implicitly cast from int to unsigned long. This may be unsafe 5 | strncpy(dest, src, size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/malloc-implicit.c.exp: -------------------------------------------------------------------------------- 1 | malloc-implicit.c:10:16: warning: size is implicitly cast from int to unsigned long. This may be unsafe 2 | void *ptr = malloc(size); 3 | ^~~~~~~~~~~~ 4 | malloc-implicit.c:16:21: warning: size is implicitly cast from int to unsigned long. This may be unsafe 5 | void *ptr = malloc(size); 6 | ^~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/reallocarray-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = malloc(j); 8 | ptr = reallocarray(ptr, (unsigned)i, j); 9 | free(ptr); 10 | } 11 | 12 | void g(int i) { 13 | unsigned long j = 10; 14 | void *ptr = malloc(j); 15 | ptr = reallocarray(ptr, j, (unsigned)i); 16 | free(ptr); 17 | } 18 | 19 | -------------------------------------------------------------------------------- /tests/uninitialized-var/include/cxx-struct-field-uninitialized.h: -------------------------------------------------------------------------------- 1 | struct foostruct { 2 | bool isTrue; 3 | int x; 4 | }; 5 | 6 | class foo { 7 | public: 8 | foo() {} 9 | void addFooStructInstance(foostruct fs); 10 | }; 11 | 12 | class bar { 13 | public: 14 | foo fooInstance; 15 | void call(bool cond); 16 | }; 17 | 18 | void foo::addFooStructInstance(foostruct fs) { 19 | if(fs.isTrue) 20 | fs.x = 10; 21 | return; 22 | } 23 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memset-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | memset-int-unsigned.c:11:4: warning: size is explicitly cast from int to unsigned int. This may be unsafe 2 | memset(src, 0, (unsigned)size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | memset-int-unsigned.c:17:6: warning: size is explicitly cast from int to unsigned int. This may be unsafe 5 | memset(src, 0, (unsigned)size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/realloc-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | realloc-int-unsigned.c:15:10: warning: i is explicitly cast from int to unsigned int. This may be unsafe 2 | ptr = realloc(ptr, (unsigned)i); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~ 4 | realloc-int-unsigned.c:23:12: warning: i is explicitly cast from int to unsigned int. This may be unsafe 5 | ptr = realloc(ptr, (unsigned)i); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memcpy-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | memcpy-int-unsigned.c:13:4: warning: size is explicitly cast from int to unsigned int. This may be unsafe 2 | memcpy(dest, src, (unsigned)size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | memcpy-int-unsigned.c:20:6: warning: size is explicitly cast from int to unsigned int. This may be unsafe 5 | memcpy(dest, src, (unsigned)size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/calloc-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | calloc-int-unsigned.c:13:16: warning: i is explicitly cast from int to unsigned int. This may be unsafe 2 | void *ptr = calloc(j, (unsigned)i); 3 | ^~~~~~~~~~~~~~~~~~~~~~ 4 | calloc-int-unsigned.c:21:21: warning: i is explicitly cast from int to unsigned int. This may be unsafe 5 | void *ptr = calloc(j, (unsigned)i); 6 | ^~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/memmove-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | memmove-int-unsigned.c:13:4: warning: size is explicitly cast from int to unsigned int. This may be unsafe 2 | memmove(dest, src, (unsigned)size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | memmove-int-unsigned.c:20:6: warning: size is explicitly cast from int to unsigned int. This may be unsafe 5 | memmove(dest, src, (unsigned)size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/strncpy-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | strncpy-int-unsigned.c:13:4: warning: size is explicitly cast from int to unsigned int. This may be unsafe 2 | strncpy(dest, src, (unsigned)size); 3 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4 | strncpy-int-unsigned.c:20:6: warning: size is explicitly cast from int to unsigned int. This may be unsafe 5 | strncpy(dest, src, (unsigned)size); 6 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/malloc-int-unsigned.c.exp: -------------------------------------------------------------------------------- 1 | malloc-int-unsigned.c:10:16: warning: size is explicitly cast from int to unsigned int. This may be unsafe 2 | void *ptr = malloc((unsigned)size); 3 | ^~~~~~~~~~~~~~~~~~~~~~ 4 | malloc-int-unsigned.c:16:21: warning: size is explicitly cast from int to unsigned int. This may be unsafe 5 | void *ptr = malloc((unsigned)size); 6 | ^~~~~~~~~~~~~~~~~~~~~~ 7 | 2 warnings generated. 8 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memset-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 10; 5 | char src[10]; 6 | memset(src, 0, size); 7 | } 8 | 9 | void f2(int size) { 10 | char src[10]; 11 | memset(src, 0, size); 12 | } 13 | 14 | void f3(int size) { 15 | char src[10]; 16 | if (size < 0) 17 | memset(src, 0, size); 18 | } 19 | 20 | void f4(int size) { 21 | char src[10]; 22 | if (size > 0) 23 | memset(src, 0, size); 24 | } 25 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-instantiated-object-var-passed-by-ref.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags the following scenario 2 | * a) instantiated cxx object 3 | * b) member function of object takes in passed argument by reference 4 | * c) uninitialized var is passed to the member function 5 | * Result: Fail 6 | */ 7 | #include "include/cxx-function-arg-by-reference.h" 8 | 9 | void func() { 10 | foo fooobj; 11 | int b; 12 | fooobj.bar(b); 13 | } 14 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-uninstantiated-object-function-call.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags 2 | * a) uninitialized use of member fields of cxx objects in function calls when 3 | * the object has not been instantiated 4 | * Result: Fail 5 | */ 6 | 7 | class foo { 8 | public: 9 | foo(); 10 | void bar(); 11 | int x; 12 | }; 13 | 14 | foo::foo() {} 15 | 16 | void call(int a) {} 17 | 18 | void foo::bar() { 19 | call(x); // No warning! 20 | } 21 | 22 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-unary-lnot-operator.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags 2 | * a) uninitialized use of member fields of cxx objects used in unary LNot operation 3 | * the object has not been instantiated 4 | * Result: Fail 5 | */ 6 | class foo { 7 | public: 8 | int x; 9 | bool m_b; 10 | foo(); 11 | void bar(); 12 | }; 13 | 14 | foo::foo(): x(0) { } 15 | 16 | void foo::bar() { 17 | // Our checker flags this 18 | // Clang SA doesn't 19 | if(!m_b) 20 | x = 1; 21 | } 22 | -------------------------------------------------------------------------------- /tests/typecast-bugs/malloc-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 10; 5 | void *ptr = malloc(size); 6 | free(ptr); 7 | } 8 | 9 | void f2(int size) { 10 | void *ptr = malloc(size); 11 | free(ptr); 12 | } 13 | 14 | void f3(int size) { 15 | if (size < 0) { 16 | void *ptr = malloc(size); 17 | free(ptr); 18 | } 19 | } 20 | 21 | void f4(int size) { 22 | if (size > 0) { 23 | void *ptr = malloc(size); 24 | free(ptr); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memset-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 10; 5 | char src[10]; 6 | memset(src, 0, (unsigned)size); 7 | } 8 | 9 | void f2(int size) { 10 | char src[10]; 11 | memset(src, 0, (unsigned)size); 12 | } 13 | 14 | void f3(int size) { 15 | char src[10]; 16 | if (size < 0) 17 | memset(src, 0, (unsigned)size); 18 | } 19 | 20 | void f4(int size) { 21 | char src[10]; 22 | if (size > 0) 23 | memset(src, 0, (unsigned)size); 24 | } 25 | -------------------------------------------------------------------------------- /tests/typecast-bugs/malloc-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 10; 5 | void *ptr = malloc((unsigned)size); 6 | free(ptr); 7 | } 8 | 9 | void f2(int size) { 10 | void *ptr = malloc((unsigned)size); 11 | free(ptr); 12 | } 13 | 14 | void f3(int size) { 15 | if (size < 0) { 16 | void *ptr = malloc((unsigned)size); 17 | free(ptr); 18 | } 19 | } 20 | 21 | void f4(int size) { 22 | if (size > 0) { 23 | void *ptr = malloc((unsigned)size); 24 | free(ptr); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-constructor-not-defined.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags 2 | * uninitialized use of member fields of cxx objects in function calls when the 3 | * constructor of the object is declared but not defined. 4 | * Note: It is possible that the definition of constructor is in a different source 5 | * file and this file simply makes use of class foo. 6 | * Result: Fail 7 | */ 8 | #include "include/cxx-obj-declaration.h" 9 | 10 | void call(int a) {} 11 | 12 | void func() { 13 | foo a; 14 | call(a.x); // No warning 15 | } 16 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-uninitialized-var-passed-by-ref.cpp: -------------------------------------------------------------------------------- 1 | /* crbug.com/411163 2 | * This file tests if clang analyzer flags 3 | * a) when an uninitialized variable passed by reference to a class' member function AND 4 | * b) a pointer to the class instance is passed as an argument 5 | * Implementation of member function is in a different source file 6 | * Class declaration is in the included header 7 | * 8 | * Result: Fail 9 | */ 10 | 11 | #include "./include/cxx-function-arg-by-reference.h" 12 | 13 | void func(foo *fooptr) { 14 | int x; 15 | fooptr->bar(x); 16 | } 17 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memcpy-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | memcpy(dest, src, size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | memcpy(dest, src, size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | memcpy(dest, src, size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | memcpy(dest, src, size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/uninitialized-var/pass-cxx-exercise-buggy-paths.cpp: -------------------------------------------------------------------------------- 1 | /* This file runs clang against a hypothetical scenario 2 | * where we have an executable that captures conditional 3 | * initialization bugs at the core of most crbugs scavenged so far 4 | */ 5 | 6 | #include "include/cxx-exercise-buggy-paths.h" 7 | 8 | void foo::do_something() { 9 | foo::m_x = 1; 10 | } 11 | 12 | void foo::do_something_else() { 13 | foo::m_y = foo::m_x; 14 | } 15 | 16 | int main(int argc, char **argv) { 17 | foo fooobj; 18 | if(argc > 1) 19 | fooobj.do_something(); 20 | fooobj.do_something_else(); 21 | return fooobj.m_x; 22 | } 23 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memmove-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | memmove(dest, src, size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | memmove(dest, src, size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | memmove(dest, src, size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | memmove(dest, src, size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/typecast-bugs/strncpy-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | strncpy(dest, src, size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | strncpy(dest, src, size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | strncpy(dest, src, size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | strncpy(dest, src, size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/test-unsanstr.c: -------------------------------------------------------------------------------- 1 | #include "testmacro.h" 2 | 3 | extern int zend_hash_find(HashTable *ht, const char *ch, unsigned i, void **data); 4 | 5 | void sanitized() { 6 | zval **z; 7 | char *tmp; 8 | HashTable *ht; 9 | const char *ch = "c"; 10 | unsigned i = 0; 11 | zend_hash_find(ht, ch, i, (void **) &z); 12 | if (Z_TYPE_PP(z) == 1) 13 | tmp = Z_STRVAL_PP(z); 14 | } 15 | 16 | void unsanitized() { 17 | zval **z; 18 | char *tmp; 19 | HashTable *ht; 20 | const char *ch = "c"; 21 | unsigned i = 0; 22 | zend_hash_find(ht, ch, i, (void **) &z); 23 | tmp = Z_STRVAL_PP(z); 24 | } 25 | 26 | -------------------------------------------------------------------------------- /tests/typecast-bugs/calloc-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = calloc(i, j); 8 | free(ptr); 9 | } 10 | 11 | void f2() { 12 | int i; 13 | unsigned long j; 14 | void *ptr = calloc(j, i); 15 | free(ptr); 16 | } 17 | 18 | void f3(int i) { 19 | unsigned long j; 20 | j = 10; 21 | if (i < 0) { 22 | void *ptr = calloc(j, i); 23 | free(ptr); 24 | } 25 | } 26 | 27 | void f4(int i) { 28 | unsigned long j; 29 | j = 10; 30 | if (i > 0) { 31 | void *ptr = calloc(j, i); 32 | free(ptr); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/uninitialized-var/pass-cxx-instantiated-object-uninitialized-field-pass-by-value.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags 2 | * uninitialized use of member fields of cxx objects in function calls when 3 | * the object has been instantiated and is passed by value 4 | * Result: Pass 5 | */ 6 | 7 | 8 | class foo { 9 | public: 10 | int y; 11 | void bar(foo a); 12 | foo(); 13 | }; 14 | 15 | foo::foo() {} 16 | 17 | void foo::bar(foo a) { if(a.y == 5) a.y = 0;} 18 | 19 | void func() { 20 | // Object instantiation 21 | foo a; 22 | a.bar(a); // warning: Function call argument is an uninitialized value 23 | } 24 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memcpy-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | memcpy(dest, src, (unsigned)size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | memcpy(dest, src, (unsigned)size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | memcpy(dest, src, (unsigned)size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | memcpy(dest, src, (unsigned)size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/uninitialized-var/pass-cxx-functionbody-available-var-passed-by-ref.cpp: -------------------------------------------------------------------------------- 1 | /* This file tests if clang analyzer flags the following scenario 2 | * a) instantiated cxx object 3 | * b) member function of object takes in passed argument by reference 4 | * c) uninitialized var is passed to the member function 5 | * d) implementation of member function in same translation unit 6 | * Result: Pass 7 | */ 8 | #include "include/cxx-function-arg-by-reference.h" 9 | 10 | void foo::bar(int &a) { 11 | if(a > 10) // warning: The left operand of '>' is a garbage value 12 | a = 0; 13 | } 14 | 15 | 16 | void func() { 17 | foo fooobj; 18 | int b; 19 | fooobj.bar(b); 20 | } 21 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/test-sancall.c: -------------------------------------------------------------------------------- 1 | #include "testmacro.h" 2 | 3 | extern int zend_hash_find(HashTable *ht, const char *ch, unsigned i, void **data); 4 | extern void convert_to_string(zval *op); 5 | 6 | void sanitized() { 7 | zval **z; 8 | char *tmp; 9 | HashTable *ht; 10 | const char *ch = "c"; 11 | unsigned i = 0; 12 | zend_hash_find(ht, ch, i, (void **) &z); 13 | convert_to_string(*z); 14 | tmp = Z_STRVAL_PP(z); 15 | } 16 | 17 | void unsanitized() { 18 | zval **z; 19 | char *tmp; 20 | HashTable *ht; 21 | const char *ch = "c"; 22 | unsigned i = 0; 23 | zend_hash_find(ht, ch, i, (void **) &z); 24 | tmp = Z_STRVAL_PP(z); 25 | } 26 | -------------------------------------------------------------------------------- /tests/typecast-bugs/memmove-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | memmove(dest, src, (unsigned)size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | memmove(dest, src, (unsigned)size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | memmove(dest, src, (unsigned)size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | memmove(dest, src, (unsigned)size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/typecast-bugs/strncpy-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int size = 12; 5 | char src[12] = "helloworld"; 6 | char dest[12]; 7 | strncpy(dest, src, (unsigned)size); 8 | } 9 | 10 | void f2(int size) { 11 | char src[12] = "helloworld"; 12 | char dest[12]; 13 | strncpy(dest, src, (unsigned)size); 14 | } 15 | 16 | void f3(int size) { 17 | char src[12] = "helloworld"; 18 | char dest[12]; 19 | if (size < 0) 20 | strncpy(dest, src, (unsigned)size); 21 | } 22 | 23 | void f4(int size) { 24 | char src[12] = "helloworld"; 25 | char dest[12]; 26 | if (size > 0) 27 | strncpy(dest, src, (unsigned)size); 28 | } 29 | -------------------------------------------------------------------------------- /tests/typecast-bugs/calloc-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = calloc((unsigned)i, j); 8 | free(ptr); 9 | } 10 | 11 | void f2(int i) { 12 | unsigned long j = 10; 13 | void *ptr = calloc(j, (unsigned)i); 14 | free(ptr); 15 | } 16 | 17 | void f3(int i) { 18 | unsigned long j; 19 | j = 10; 20 | if (i < 0) { 21 | void *ptr = calloc(j, (unsigned)i); 22 | free(ptr); 23 | } 24 | } 25 | 26 | void f4(int i) { 27 | unsigned long j; 28 | j = 10; 29 | if (i > 0) { 30 | void *ptr = calloc(j, (unsigned)i); 31 | free(ptr); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /tests/typecast-bugs/realloc-implicit.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = malloc(j); 8 | ptr = realloc(ptr, i); 9 | free(ptr); 10 | } 11 | 12 | void f2(int i) { 13 | unsigned long j = 10; 14 | void *ptr = malloc(j); 15 | ptr = realloc(ptr, i); 16 | free(ptr); 17 | } 18 | 19 | void f3(int i) { 20 | unsigned long j = 10; 21 | void *ptr = malloc(j); 22 | if (i < 0) 23 | ptr = realloc(ptr, i); 24 | free(ptr); 25 | } 26 | 27 | void f4(int i) { 28 | unsigned long j = 10; 29 | void *ptr = malloc(j); 30 | if (i > 0) 31 | ptr = realloc(ptr, i); 32 | free(ptr); 33 | } 34 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | #### Tests 2 | 3 | Directory for tests that clang analyzer fails; might optionally contain tests that pass but are interesting nonetheless: 4 | 5 | - `uninitialized-var` contains test cases for use of uninitialized variable 6 | 7 | #### Naming convention for test files 8 | 9 | (pass/fail)-cxx-(description-of-test).cpp 10 | 11 | pass == Test passes i.e., clang analyzer flags warning as expected 12 | fail == Test fails => Stuff that is interesting! 13 | cxx == Pertaining to cxx feature e.g., objects 14 | 15 | #### Command line 16 | 17 | Clang analyzer exercises all the default checkers e.g., use of uninitialized var, use-after-free etc. So just do this: 18 | 19 | ```bash 20 | clang --analyze $TEST.cpp 21 | ``` 22 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-two-constructors.cpp: -------------------------------------------------------------------------------- 1 | /* crbug.com/393981 and 411161 2 | * This file tests if clang analyzer flags a warning in the following scenario: 3 | * a) there are two constructors for an object 4 | * b) the default constructor does not initialize member field 5 | * c) defaut constructor is used to instantiate a class object 6 | * d) the class object is passed by reference/pointer to a function call 7 | * e) function call reads uninitialized variable 8 | * Result: Fail 9 | */ 10 | 11 | #include "include/cxx-two-constructors.h" 12 | 13 | void call(foo *fooptr) { 14 | fooptr->m_x; // No warning! 15 | } 16 | 17 | void func() { 18 | foo fooobj; // Calls default constructor 19 | call(&fooobj); 20 | } 21 | -------------------------------------------------------------------------------- /tests/typecast-bugs/expects/rangetest.c.exp: -------------------------------------------------------------------------------- 1 | rangetest.c:13:16: warning: i is implicitly cast from int to unsigned long. This may be unsafe 2 | void *ptr = calloc(j, i); 3 | ^~~~~~~~~~~~ 4 | rangetest.c:22:14: warning: i is implicitly cast from int to unsigned long. This may be unsafe 5 | void *ptr = calloc(j, i); 6 | ^~~~~~~~~~~~ 7 | rangetest.c:31:14: warning: i is implicitly cast from int to unsigned long. This may be unsafe 8 | void *ptr = calloc(j, i); 9 | ^~~~~~~~~~~~ 10 | rangetest.c:49:16: warning: i is implicitly cast from int to unsigned long. This may be unsafe 11 | void *ptr = calloc(j, i); 12 | ^~~~~~~~~~~~ 13 | 4 warnings generated. 14 | -------------------------------------------------------------------------------- /tests/typecast-bugs/realloc-int-unsigned.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = malloc(j); 8 | ptr = realloc(ptr, (unsigned)i); 9 | free(ptr); 10 | } 11 | 12 | void f2(int i) { 13 | unsigned long j = 10; 14 | void *ptr = malloc(j); 15 | ptr = realloc(ptr, (unsigned)i); 16 | free(ptr); 17 | } 18 | 19 | void f3(int i) { 20 | unsigned long j = 10; 21 | void *ptr = malloc(j); 22 | if (i < 0) 23 | ptr = realloc(ptr, (unsigned)i); 24 | free(ptr); 25 | } 26 | 27 | void f4(int i) { 28 | unsigned long j = 10; 29 | void *ptr = malloc(j); 30 | if (i > 0) 31 | ptr = realloc(ptr, (unsigned)i); 32 | free(ptr); 33 | } 34 | -------------------------------------------------------------------------------- /tests/typecast-bugs/rangetest.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f1() { 4 | int i; 5 | unsigned long j; 6 | i = j = 10; 7 | void *ptr = calloc(i, j); 8 | free(ptr); 9 | } 10 | 11 | void f2(int i) { 12 | unsigned long j; 13 | void *ptr = calloc(j, i); 14 | free(ptr); 15 | } 16 | 17 | void f3(int i) { 18 | unsigned long j; 19 | j = 10; 20 | i = -1; 21 | if (i < 0) { 22 | void *ptr = calloc(j, i); 23 | free(ptr); 24 | } 25 | } 26 | 27 | void f4(int i) { 28 | unsigned long j; 29 | j = 10; 30 | if (i < 0) { 31 | void *ptr = calloc(j, i); 32 | free(ptr); 33 | } 34 | } 35 | 36 | void f5(int i) { 37 | unsigned long j; 38 | j = 10; 39 | if (i > 0) { 40 | void *ptr = calloc(j, i); 41 | free(ptr); 42 | } 43 | } 44 | 45 | void f6(int i) { 46 | unsigned long j; 47 | j = 10; 48 | i = -1; 49 | void *ptr = calloc(j, i); 50 | free(ptr); 51 | } 52 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/testmacro.h: -------------------------------------------------------------------------------- 1 | typedef struct _hashtable { 2 | unsigned nTableSize; 3 | unsigned nTableMask; 4 | unsigned nNumOfElements; 5 | unsigned long nNextFreeElement; 6 | unsigned char nApplyCount; 7 | } HashTable; 8 | 9 | typedef union _zvalue_value { 10 | long lval; /* long value */ 11 | double dval; /* double value */ 12 | struct { 13 | char *val; 14 | int len; 15 | } str; 16 | HashTable *ht; /* hash table value */ 17 | } zvalue_value; 18 | 19 | struct _zval_struct { 20 | /* Variable information */ 21 | zvalue_value value; /* value */ 22 | int type; 23 | }; 24 | 25 | typedef struct _zval_struct zval; 26 | 27 | #define Z_STRVAL(zval) (zval).value.str.val 28 | #define Z_STRVAL_P(zvalp) Z_STRVAL(*zvalp) 29 | #define Z_STRVAL_PP(zvalpp) Z_STRVAL_P(*zvalpp) 30 | 31 | #define Z_TYPE(zval) (zval).type 32 | #define Z_TYPE_P(zvalp) Z_TYPE(*zvalp) 33 | #define Z_TYPE_PP(zvalpp) Z_TYPE_P(*zvalpp) 34 | -------------------------------------------------------------------------------- /src/Registry.cpp: -------------------------------------------------------------------------------- 1 | #include "clang/StaticAnalyzer/Core/CheckerRegistry.h" 2 | #include "UseDefChecker.h" 3 | #include "TypeCastingVulnChecker.h" 4 | #include "StrCpyOverflowChecker.h" 5 | #include "TypeConfusionChecker.h" 6 | #include "PHPTaintChecker.h" 7 | 8 | using namespace clang; 9 | using namespace ento; 10 | 11 | // Register plugin! 12 | extern "C" 13 | void clang_registerCheckers(CheckerRegistry ®istry) { 14 | registry.addChecker("alpha.security.UseDefChecker", "CXX UseDef Checker"); 15 | registry.addChecker("alpha.security.CastChecker", "Unsafe cast checker"); 16 | registry.addChecker("alpha.security.StrOverflowChecker", "Str Overflow Checker"); 17 | registry.addChecker("alpha.security.TypeConfusionChecker", "Type confusion Checker"); 18 | registry.addChecker("alpha.security.PHPChecker", "PHP Checker"); 19 | } 20 | 21 | extern "C" 22 | const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING; 23 | 24 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-calls-across-object-definitions.cpp: -------------------------------------------------------------------------------- 1 | /* crbug.com/419428 2 | * This test is a simplified version of crbug 419428 3 | * Essentially, it tests if calls across class definitions 4 | * is sufficient to confuse clang. tl;dr: yes, it is! 5 | * Result: Fail 6 | */ 7 | 8 | #include "include/cxx-calls-across-object-definitions.h" 9 | 10 | void bar::call(bool cond) { 11 | /* isTrue is initialized if cond is true */ 12 | if(cond) 13 | fooInstance.isTrue = true; 14 | 15 | /* Member field isTrue is read in function updateX() */ 16 | fooInstance.updateX(); // No warning! 17 | return; 18 | } 19 | 20 | /* This is what is missing for clang analyzer to flag a warning. 21 | * Without this function that actually instantiates object of 22 | * type `bar`, the analyzer doesn't do anything interesting 23 | * Uncomment to see clang flag a warning 24 | */ 25 | /* 26 | void func(bool cond) { 27 | bar b; 28 | // warning: Branch condition evaluates to a garbage value in 29 | // include/cxx-calls-across-object-definitions.h:17:5 30 | b.call(cond); 31 | } 32 | */ 33 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/expects/test-sancall.c.exp: -------------------------------------------------------------------------------- 1 | test-sancall.c:24:10: warning: Untrusted data in Zend macro 2 | tmp = Z_STRVAL_PP(z); 3 | ^ 4 | ./testmacro.h:29:41: note: expanded from macro 'Z_STRVAL_PP' 5 | #define Z_STRVAL_PP(zvalpp) Z_STRVAL_P(*zvalpp) 6 | ^ 7 | ./testmacro.h:28:38: note: expanded from macro 'Z_STRVAL_P' 8 | #define Z_STRVAL_P(zvalp) Z_STRVAL(*zvalp) 9 | ^ 10 | ./testmacro.h:27:27: note: expanded from macro 'Z_STRVAL' 11 | #define Z_STRVAL(zval) (zval).value.str.val 12 | ^ 13 | test-sancall.c:24:10: warning: Untrusted data in Zend macro 14 | tmp = Z_STRVAL_PP(z); 15 | ^~~~~~~~~~~~~~ 16 | ./testmacro.h:29:30: note: expanded from macro 'Z_STRVAL_PP' 17 | #define Z_STRVAL_PP(zvalpp) Z_STRVAL_P(*zvalpp) 18 | ^~~~~~~~~~~~~~~~~~~ 19 | ./testmacro.h:28:28: note: expanded from macro 'Z_STRVAL_P' 20 | #define Z_STRVAL_P(zvalp) Z_STRVAL(*zvalp) 21 | ^~~~~~~~~~~~~~~~ 22 | ./testmacro.h:27:43: note: expanded from macro 'Z_STRVAL' 23 | #define Z_STRVAL(zval) (zval).value.str.val 24 | ~~~~~~~~~~~~~~~~~^~~ 25 | 2 warnings generated. 26 | -------------------------------------------------------------------------------- /src/Diagnostics.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_DIAGNOSTICS_H 2 | #define MELANGE_DIAGNOSTICS_H 3 | 4 | #include "clang/AST/ASTContext.h" 5 | #include "clang/Analysis/AnalysisContext.h" 6 | #include "clang/Basic/SourceLocation.h" 7 | #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 8 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 9 | 10 | namespace Melange { 11 | 12 | class Diagnostics { 13 | 14 | typedef clang::ento::BugReport::ExtraTextList ETLTy; 15 | typedef ETLTy::const_iterator EBIIteratorTy; 16 | typedef std::pair DiagPairTy; 17 | typedef llvm::DenseMap DiagnosticsInfoTy; 18 | 19 | 20 | ETLTy EncodedBugInfo; 21 | DiagnosticsInfoTy DiagnosticsInfo; 22 | 23 | public: 24 | void encodeBugInfo(std::string Node, clang::ento::CheckerContext &C); 25 | void storeDiagnostics(const clang::Decl *D, clang::SourceLocation SL); 26 | void dumpCallsOnStack(clang::ento::CheckerContext &C); 27 | ETLTy &getBugInfoDiag(); 28 | 29 | // utility 30 | static std::string getADCQualifiedNameAsStringRef(const clang::LocationContext *LC); 31 | static std::string getMangledNameAsString(const clang::NamedDecl *ND, clang::ASTContext &ASTC); 32 | }; 33 | 34 | } // end of Melange namespace 35 | #endif 36 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/expects/test-unsanstr.c.exp: -------------------------------------------------------------------------------- 1 | test-unsanstr.c:23:10: warning: Untrusted data in Zend macro 2 | tmp = Z_STRVAL_PP(z); 3 | ^ 4 | ./testmacro.h:29:41: note: expanded from macro 'Z_STRVAL_PP' 5 | #define Z_STRVAL_PP(zvalpp) Z_STRVAL_P(*zvalpp) 6 | ^ 7 | ./testmacro.h:28:38: note: expanded from macro 'Z_STRVAL_P' 8 | #define Z_STRVAL_P(zvalp) Z_STRVAL(*zvalp) 9 | ^ 10 | ./testmacro.h:27:27: note: expanded from macro 'Z_STRVAL' 11 | #define Z_STRVAL(zval) (zval).value.str.val 12 | ^ 13 | test-unsanstr.c:23:10: warning: Untrusted data in Zend macro 14 | tmp = Z_STRVAL_PP(z); 15 | ^~~~~~~~~~~~~~ 16 | ./testmacro.h:29:30: note: expanded from macro 'Z_STRVAL_PP' 17 | #define Z_STRVAL_PP(zvalpp) Z_STRVAL_P(*zvalpp) 18 | ^~~~~~~~~~~~~~~~~~~ 19 | ./testmacro.h:28:28: note: expanded from macro 'Z_STRVAL_P' 20 | #define Z_STRVAL_P(zvalp) Z_STRVAL(*zvalp) 21 | ^~~~~~~~~~~~~~~~ 22 | ./testmacro.h:27:43: note: expanded from macro 'Z_STRVAL' 23 | #define Z_STRVAL(zval) (zval).value.str.val 24 | ~~~~~~~~~~~~~~~~~^~~ 25 | 2 warnings generated. 26 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-struct-field-uninitialized.cpp: -------------------------------------------------------------------------------- 1 | /* crbug.com/419428 2 | This file tests if clang flags a warning in the following scenario: 3 | * a) There are two distinct cxx object definitions available 4 | * b) One object (bar) has an object of the other type (foo) 5 | * c) Object bar has a member function that calls a member function of foo 6 | * through its own instance of foo (fooInstance) 7 | * d) Member field of foo is uninitialized when a condition (cond) is false 8 | * Result: Fail 9 | */ 10 | 11 | #include "include/cxx-struct-field-uninitialized.h" 12 | 13 | /* crbug 419428: bar is equivalent to class MediaQueryData. 14 | * bar::call is equivalent to MediaQueryData::addParserValue() 15 | */ 16 | void bar::call(bool cond) { 17 | 18 | /* crbug 419428: foostruct is equivalent to struct CSSParserValue */ 19 | foostruct fs; 20 | if(cond) 21 | fs.isTrue = true; 22 | 23 | /* If cond == false, the branch is not taken 24 | * and fs.isTrue is not initialized. 25 | * Clang is expected to flag a warning here. 26 | */ 27 | /* crbug 419428: foo is equivalent to class CSSParserValueList. 28 | * fooInstance is equivalent to field m_valueList in MediaQueryData. 29 | * addFooStructInstance() is equivalent to CSSParserValueList::addValue(). 30 | */ 31 | fooInstance.addFooStructInstance(fs); // No warning! 32 | return; 33 | } 34 | -------------------------------------------------------------------------------- /tests/uninitialized-var/fail-cxx-uninstantiated-object-uninitialized-field.cpp: -------------------------------------------------------------------------------- 1 | /* crbug.com/411177 and 411167 2 | * This file tests if clang analyzer flags a warning in the following scenario 3 | * a) Constructor fails to initialize member field 4 | * b) member field is defined in one member function 5 | * c) same member field is used in another member function 6 | * Developers might assume a certain call order between member functions of a 7 | * class and overlook lack of initialization. This is not concocted but a real 8 | * bug from Chromium source code. Read the bug report and patches. 9 | * Result: Fail 10 | * ---------------------------- 11 | * Update: 12.02.15 12 | * Checker-v2.0 flags a sub-set of undefined use of cxx object fields 13 | * a) Definition in ctor initializer, in-class, or in method definition is 14 | * recorded 15 | * TODO: Record definition in ctor body as well 16 | * b) Use is checked for binary operator ``=" i.e., being on the rhs 17 | * of assignment qualifies as use 18 | */ 19 | 20 | class foo { 21 | public: 22 | foo() {} 23 | void init_member(); 24 | void read_member(); 25 | int m_x; 26 | int m_y; 27 | }; 28 | 29 | void foo::init_member() { 30 | /* Clang SA: No warning here 31 | * Our checker flags this 32 | */ 33 | m_x = m_y; 34 | } 35 | 36 | void foo::read_member() { 37 | if(!m_x) // Clang SA: No warning! 38 | m_x = 10; 39 | } 40 | -------------------------------------------------------------------------------- /src/TypeConfusionChecker.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_TYPECONFUSION_CHECKER_H 2 | #define MELANGE_TYPECONFUSION_CHECKER_H 3 | 4 | #include "clang/StaticAnalyzer/Core/Checker.h" 5 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 6 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 7 | #include "Diagnostics.h" 8 | 9 | #ifdef _DEBUG 10 | #define DEBUG_PRINT(x) llvm::errs() << x << "\n" 11 | #else 12 | #define DEBUG_PRINT(x) 13 | #endif 14 | 15 | namespace Melange { 16 | 17 | class Diagnostics; 18 | 19 | class TypeConfusionChecker : public clang::ento::Checker, 20 | clang::ento::check::PreStmt, 21 | clang::ento::check::PreStmt, 22 | clang::ento::check::PreStmt> { 23 | 24 | mutable Diagnostics Diag; 25 | 26 | public: 27 | void checkPreStmt(const clang::CastExpr *CE, clang::ento::CheckerContext &C) const; 28 | void checkPreStmt(const clang::CallExpr *CaE, clang::ento::CheckerContext &C) const; 29 | void checkPreStmt(const clang::BinaryOperator *BO, clang::ento::CheckerContext &C) const; 30 | void checkPreStmt(const clang::DeclStmt *DS, clang::ento::CheckerContext &C) const; 31 | void reportBug(clang::ento::CheckerContext &C, clang::SourceRange SR, 32 | llvm::StringRef Message, llvm::StringRef declName) const; 33 | 34 | private: 35 | mutable std::unique_ptr BT; 36 | }; 37 | } // end of Melange namespace 38 | 39 | 40 | #endif 41 | -------------------------------------------------------------------------------- /src/StrCpyOverflowChecker.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_STRCPYOVERFLOW_CHECKER_H 2 | #define MELANGE_STRCPYOVERFLOW_CHECKER_H 3 | 4 | #include "clang/StaticAnalyzer/Core/Checker.h" 5 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 6 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 7 | #include "Diagnostics.h" 8 | 9 | #ifdef _DEBUG 10 | #define DEBUG_PRINT(x) llvm::errs() << x << "\n" 11 | #else 12 | #define DEBUG_PRINT(x) 13 | #endif 14 | 15 | namespace Melange { 16 | 17 | class Diagnostics; 18 | 19 | class StrCpyOverflowChecker : public clang::ento::Checker> { 20 | 21 | mutable Diagnostics Diag; 22 | 23 | public: 24 | void checkPreStmt(const clang::CallExpr *CE, clang::ento::CheckerContext &C) const; 25 | private: 26 | mutable std::unique_ptr BT; 27 | void reportBug(clang::ento::CheckerContext &C, clang::SourceRange SR, 28 | llvm::StringRef Message, llvm::StringRef declName) const; 29 | void handleStrArgs(const clang::Expr *E1, const clang::Expr *E2, 30 | clang::ento::CheckerContext &C) const; 31 | 32 | const std::vector callNames = 33 | {"strcpy", "strcat"}; 34 | // enum ALLOC_API : unsigned { 35 | // MALLOC_START = 0, 36 | // MALLOC_END = 4, 37 | // CALLOC_START = 5, 38 | // CALLOC_END = 7, 39 | // REALLOC_START = 8, 40 | // REALLOC_END = 10, 41 | // REALLOCARRAY_START = 11, 42 | // REALLOCARRAY_END = 12, 43 | // MEMCPY_START = 13, 44 | // MEMCPY_END = 14 45 | // }; 46 | }; 47 | } // end of Melange namespace 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /tests/strcpy-overflow/test_harness.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'bhargava' 4 | 5 | import os, sys, subprocess 6 | import collections 7 | import filecmp 8 | import unittest 9 | import glob 10 | 11 | statout = collections.namedtuple('StatusOutPair', ['ret', 'out']) 12 | 13 | 14 | def execwrapper(args, errMsg): 15 | p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable="/bin/bash") 16 | out, err = p.communicate() 17 | if err: 18 | return statout(False, out) 19 | return statout(True, out) 20 | 21 | 22 | def diffExp(filename, out): 23 | basename = os.path.basename(filename) 24 | with open("expects/%s.exp" % basename, "r") as expectation: 25 | expects = expectation.read() 26 | if out != expects: 27 | return False 28 | expectation.close() 29 | return True 30 | 31 | 32 | def invokecj(filename): 33 | args = "clang --analyze -Xclang -load -Xclang /home/bhargava/work/gitlab/checkers/build-live/libusedef-checker.so -Xclang -analyzer-checker=alpha.security.StrOverflowChecker %s" % filename 34 | retpair = execwrapper(args, "Test on %s" % filename + " failed") 35 | if retpair.ret: 36 | return diffExp(filename, retpair.out) 37 | return False 38 | 39 | 40 | # Schema: filename, filename.nodes.exp, filename.edges.exp 41 | def testinput(filename): 42 | return invokecj(filename) 43 | 44 | 45 | class SimpleTester(unittest.TestCase): 46 | def tearDown(self): 47 | plist_files = glob.glob("*.plist") 48 | for f in plist_files: 49 | os.remove(f) 50 | 51 | 52 | class TestBasic(SimpleTester): 53 | def test_malloc(self): 54 | self.assertEqual(testinput('strcpy-stack-overflow.c'), True, 55 | 'Test on strcpy-stack-overflow.c failed') 56 | 57 | if __name__ == '__main__': 58 | unittest.main() 59 | -------------------------------------------------------------------------------- /tests/phpchecker-tests/test_harness.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'bhargava' 4 | 5 | import os, sys, subprocess 6 | import collections 7 | import filecmp 8 | import unittest 9 | import glob 10 | 11 | statout = collections.namedtuple('StatusOutPair', ['ret', 'out']) 12 | 13 | 14 | def execwrapper(args, errMsg): 15 | p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable="/bin/bash") 16 | out, err = p.communicate() 17 | if err: 18 | return statout(False, out) 19 | return statout(True, out) 20 | 21 | 22 | def diffExp(filename, out): 23 | basename = os.path.basename(filename) 24 | with open("expects/%s.exp" % basename, "r") as expectation: 25 | expects = expectation.read() 26 | if out != expects: 27 | return False 28 | expectation.close() 29 | return True 30 | 31 | 32 | def invokecj(filename): 33 | args = "clang --analyze -Xclang -load -Xclang /home/bhargava/work/gitlab/checkers/build-live/libusedef-checker.so -Xclang -analyzer-checker=alpha.security.PHPChecker -Xanalyzer -analyzer-disable-checker=core,unix,deadcode,cplusplus,security %s" % filename 34 | retpair = execwrapper(args, "Test on %s" % filename + " failed") 35 | if retpair.ret: 36 | return diffExp(filename, retpair.out) 37 | return False 38 | 39 | 40 | # Schema: filename, filename.nodes.exp, filename.edges.exp 41 | def testinput(filename): 42 | return invokecj(filename) 43 | 44 | 45 | class SimpleTester(unittest.TestCase): 46 | def tearDown(self): 47 | plist_files = glob.glob("*.plist") 48 | for f in plist_files: 49 | os.remove(f) 50 | 51 | 52 | class TestBasic(SimpleTester): 53 | def test_unsanstr(self): 54 | self.assertEqual(testinput('test-unsanstr.c'), True, 55 | 'Test on test-unsanstr.c failed') 56 | def test_sancall(self): 57 | self.assertEqual(testinput('test-sancall.c'), True, 58 | 'Test on test-sancall.c failed') 59 | 60 | if __name__ == '__main__': 61 | unittest.main() 62 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 2.8) 2 | 3 | project (usedef-checker) 4 | #set(CMAKE_BUILD_TYPE Release) 5 | 6 | # Set up relavant paths 7 | 8 | # Paths to LLVM source and build trees 9 | set(LLVM_HOME /home/bhargava/work/clang-analyzer/git-mirror-test) 10 | set(LLVM_SRC_DIR ${LLVM_HOME}/llvm) 11 | set(CLANG_SRC_DIR ${LLVM_SRC_DIR}/tools/clang) 12 | set(LLVM_BUILD_DIR /home/bhargava/workspace/llvm) 13 | set(CLANG_BUILD_DIR ${LLVM_BUILD_DIR}/tools/clang) 14 | 15 | # Flags to compile checker code 16 | set (CMAKE_CXX_FLAGS "-std=c++11 -fPIC -pedantic -fno-common -Wcast-qual -fno-strict-aliasing -Wno-long-long -Wall -Wno-unused-parameter -Wwrite-strings -fno-rtti") 17 | 18 | # Add paths to include and libs here 19 | add_definitions(${LLVM_DEFINITIONS}) 20 | include_directories( "${LLVM_SRC_DIR}/include" 21 | "${CLANG_SRC_DIR}/include" 22 | "${CLANG_SRC_DIR}/lib/StaticAnalyzer/Checkers" 23 | "${LLVM_BUILD_DIR}/include" 24 | "${CLANG_BUILD_DIR}/include" 25 | "${CLANG_BUILD_DIR}/lib/StaticAnalyzer/Checkers") 26 | link_directories(${LLVM_LIBRARY_DIRS}) 27 | 28 | # Make a shared library out of the checker. Can be loaded by scan-build -load-plugin 29 | add_library( usedef-checker SHARED 30 | UseDefChecker.cpp 31 | UseAfterFreeChecker.cpp 32 | TypeCastingVulnChecker.cpp 33 | PHPTaintChecker.cpp 34 | TypeConfusionChecker.cpp 35 | StrCpyOverflowChecker.cpp 36 | Diagnostics.cpp 37 | Registry.cpp 38 | ) 39 | 40 | #### Not necessary 41 | 42 | # Locate llvm 43 | #find_package(LLVM) 44 | 45 | # Necessary for out of source builds; Hooks plugin on to LLVM source tree 46 | #set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} /home/bhargava/work/clang-analyzer/git-mirror-test/llvm/cmake/modules ) 47 | 48 | # Path to llvm-config binary is required for some reason 49 | #set(LLVM_CONFIG /home/bhargava/work/clang-analyzer/git-mirror-test/llvm/bin/llvm-config) 50 | 51 | #add_definitions (-D__STDC_LIMIT_MACROS -D__STDC_CONSTANT_MACROS) 52 | #add_definitions (-DHAVE_CLANG_CONFIG_H ) 53 | 54 | #set (CMAKE_MODULE_LINKER_FLAGS "-Wl,-flat_namespace -Wl,-undefined -Wl,suppress") 55 | 56 | #if (SYMBOL_FILE) 57 | # set_target_properties( ${name} PROPERTIES LINK_FlAGS 58 | # "-exported_symbols_list ${SYMBOL_FILE}") 59 | #endif() 60 | 61 | #### Not necessary 62 | -------------------------------------------------------------------------------- /src/TypeCastingVulnChecker.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_TYPECASTINGVULN_CHECKER_H 2 | #define MELANGE_TYPECASTINGVULN_CHECKER_H 3 | 4 | #include "clang/StaticAnalyzer/Core/Checker.h" 5 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 6 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 7 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 8 | #include "Diagnostics.h" 9 | 10 | #ifdef _DEBUG 11 | #define DEBUG_PRINT(x) llvm::errs() << x << "\n" 12 | #else 13 | #define DEBUG_PRINT(x) 14 | #endif 15 | 16 | namespace Melange { 17 | 18 | class Diagnostics; 19 | 20 | class TypeCastingVulnChecker : public clang::ento::Checker { 21 | 22 | mutable Diagnostics Diag; 23 | 24 | public: 25 | void checkPreCall(const clang::ento::CallEvent &Call, clang::ento::CheckerContext &C) const; 26 | private: 27 | mutable std::unique_ptr BT; 28 | void reportBug(clang::ento::CheckerContext &C, clang::SourceRange SR, 29 | llvm::StringRef Message, llvm::StringRef declName) const; 30 | void handleAllocArg(const clang::Expr *E, clang::ento::SVal sval, 31 | clang::ento::CheckerContext &C) const; 32 | void reportUnsafeExpCasts(const clang::Expr *ECE, clang::ento::SVal sval, 33 | clang::ento::CheckerContext &C) const; 34 | void reportUnsafeImpCasts(const clang::ImplicitCastExpr *ICE, 35 | clang::ento::SVal sval, 36 | clang::ento::CheckerContext &C) const; 37 | 38 | const std::vector callNames = 39 | {"malloc", "xmalloc", "av_malloc", "av_mallocz", "srslte_vec_malloc", 40 | "calloc", "xcalloc", "av_calloc", 41 | "realloc", "xrealloc", "av_realloc", 42 | "reallocarray", "xreallocarray", 43 | "memcpy", "memset", "memmove", 44 | "strncpy" 45 | }; 46 | enum ALLOC_API : unsigned { 47 | MALLOC_START = 0, 48 | MALLOC_END = MALLOC_START + 4, 49 | CALLOC_START = 5, 50 | CALLOC_END = CALLOC_START + 2, 51 | REALLOC_START = 8, 52 | REALLOC_END = REALLOC_START + 2, 53 | REALLOCARRAY_START = 11, 54 | REALLOCARRAY_END = REALLOCARRAY_START + 1, 55 | MEMCPY_START = 13, 56 | MEMCPY_END = MEMCPY_START + 2, 57 | STRCPY_START = 16, 58 | STRCPY_END = STRCPY_START 59 | }; 60 | }; 61 | } // end of Melange namespace 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /tests/typeconfusion/test_harness.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'bhargava' 4 | 5 | import os, sys, subprocess 6 | import collections 7 | import filecmp 8 | import unittest 9 | import glob 10 | 11 | statout = collections.namedtuple('StatusOutPair', ['ret', 'out']) 12 | 13 | 14 | def execwrapper(args, errMsg): 15 | p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable="/bin/bash") 16 | out, err = p.communicate() 17 | if err: 18 | return statout(False, out) 19 | return statout(True, out) 20 | 21 | 22 | def diffExp(filename, out): 23 | basename = os.path.basename(filename) 24 | with open("expects/%s.exp" % basename, "r") as expectation: 25 | expects = expectation.read() 26 | if out != expects: 27 | return False 28 | expectation.close() 29 | return True 30 | 31 | 32 | def invokecj(filename): 33 | args = "clang --analyze -Xclang -load -Xclang /home/bhargava/work/gitlab/checkers/build-live/libusedef-checker.so -Xclang -analyzer-disable-checker=core,unix,deadcode,cplusplus,security -Xclang -analyzer-checker=alpha.security.TypeConfusionChecker %s" % filename 34 | retpair = execwrapper(args, "Test on %s" % filename + " failed") 35 | if retpair.ret: 36 | return diffExp(filename, retpair.out) 37 | return False 38 | 39 | 40 | # Schema: filename, filename.nodes.exp, filename.edges.exp 41 | def testinput(filename): 42 | return invokecj(filename) 43 | 44 | 45 | class SimpleTester(unittest.TestCase): 46 | def tearDown(self): 47 | plist_files = glob.glob("*.plist") 48 | for f in plist_files: 49 | os.remove(f) 50 | 51 | 52 | class TestBasic(SimpleTester): 53 | def test_charint(self): 54 | self.assertEqual(testinput('char-to-int.c'), True, 55 | 'Test on char-to-int.c failed') 56 | def test_charvoidint(self): 57 | self.assertEqual(testinput('char-void-int.c'), True, 58 | 'Test on char-void-int.c failed') 59 | def test_charintds(self): 60 | self.assertEqual(testinput('char-to-int-declstmt.c'), True, 61 | 'Test on char-to-int-declstmt.c failed') 62 | def test_charvoidintds(self): 63 | self.assertEqual(testinput('char-void-int-declstmt.c'), True, 64 | 'Test on char-void-int-declstmt.c failed') 65 | 66 | 67 | if __name__ == '__main__': 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /src/StrCpyOverflowChecker.cpp: -------------------------------------------------------------------------------- 1 | #include "StrCpyOverflowChecker.h" 2 | 3 | using namespace clang; 4 | using namespace ento; 5 | using Melange::StrCpyOverflowChecker; 6 | 7 | void StrCpyOverflowChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { 8 | 9 | const FunctionDecl *FD = C.getCalleeDecl(CE); 10 | if (!FD) 11 | return; 12 | 13 | std::vector IIvec; 14 | for (auto &i : callNames) 15 | IIvec.push_back(&C.getASTContext().Idents.get(i)); 16 | 17 | const auto *funI = FD->getIdentifier(); 18 | auto iter = std::find(IIvec.begin(), IIvec.end(), funI); 19 | 20 | if (iter == IIvec.end()) 21 | return; 22 | 23 | // auto index = std::distance(IIvec.begin(), iter); 24 | // 25 | // DEBUG_PRINT("Index is: " + std::to_string(index)); 26 | 27 | handleStrArgs(CE->getArg(0), CE->getArg(1), C); 28 | } 29 | 30 | void StrCpyOverflowChecker::handleStrArgs(const clang::Expr *E1, 31 | const clang::Expr *E2, 32 | clang::ento::CheckerContext &C) const { 33 | 34 | // Strip arguments of imp casts and parentheses 35 | const auto dest = E1->IgnoreParenImpCasts(); 36 | const auto src = E2->IgnoreParenImpCasts(); 37 | 38 | // Keep it simple and look for declrefexpr's only 39 | if (!isa(dest)) 40 | return; 41 | 42 | const DeclRefExpr *DREDest = cast(dest); 43 | 44 | if (!isa(src)) 45 | return; 46 | 47 | const DeclRefExpr *DRESrc = cast(src); 48 | 49 | // Destination must be fixed size buffer 50 | if (!isa(DREDest->getDecl()->getType())) 51 | return; 52 | 53 | // Source must be a pointer type 54 | if (!DRESrc->getDecl()->getType().getTypePtr()->isPointerType()) 55 | return; 56 | 57 | // Source must be an input parameter to function 58 | if (!isa(DRESrc->getDecl())) 59 | return; 60 | 61 | std::string Message = "Destination of str* call is a fixed size buffer that can potentially overflow"; 62 | 63 | // Report bug 64 | reportBug(C, DREDest->getSourceRange(), Message, DREDest->getDecl()->getQualifiedNameAsString()); 65 | } 66 | 67 | void StrCpyOverflowChecker::reportBug(CheckerContext &C, SourceRange SR, 68 | StringRef Message, StringRef declName) const { 69 | const char *name = "Strcpy overflow checker"; 70 | const char *desc = "Flags potential overflows due to strcpy"; 71 | 72 | ExplodedNode *EN = C.generateSink(); 73 | if (!EN) 74 | return; 75 | 76 | if (!BT) 77 | BT.reset(new BuiltinBug(this, name, desc)); 78 | 79 | BugReport *R = new BugReport(*BT, Message, EN); 80 | R->addRange(SR); 81 | 82 | Diag.encodeBugInfo(declName, C); 83 | for (auto &i : Diag.getBugInfoDiag()) { 84 | R->addExtraText(i); 85 | } 86 | 87 | C.emitReport(R); 88 | } 89 | -------------------------------------------------------------------------------- /src/Diagnostics.cpp: -------------------------------------------------------------------------------- 1 | #include "Diagnostics.h" 2 | #include "clang/AST/Mangle.h" 3 | #include "clang/AST/DeclCXX.h" 4 | 5 | using Melange::Diagnostics; 6 | using namespace clang; 7 | using namespace clang::ento; 8 | 9 | void Diagnostics::storeDiagnostics(const Decl *D, SourceLocation SL) { 10 | DiagnosticsInfoTy::iterator I = DiagnosticsInfo.find(D); 11 | if (I != DiagnosticsInfo.end()) 12 | return; 13 | 14 | typedef std::pair KVPair; 15 | I = DiagnosticsInfo.insert(KVPair(D, DiagPairTy(EncodedBugInfo, SL))).first; 16 | assert(I != DiagnosticsInfo.end()); 17 | return; 18 | } 19 | 20 | void Diagnostics::encodeBugInfo(std::string Node, CheckerContext &C) { 21 | EncodedBugInfo.clear(); 22 | 23 | EncodedBugInfo.push_back(Node); 24 | // Call stack is written to EncodedBugInfo 25 | dumpCallsOnStack(C); 26 | } 27 | 28 | Diagnostics::ETLTy &Diagnostics::getBugInfoDiag() { 29 | return EncodedBugInfo; 30 | } 31 | 32 | void Diagnostics::dumpCallsOnStack(CheckerContext &C) { 33 | const LocationContext *LC = C.getLocationContext(); 34 | 35 | if(C.inTopFrame()){ 36 | EncodedBugInfo.push_back(getADCQualifiedNameAsStringRef(LC)); 37 | return; 38 | } 39 | 40 | for (const LocationContext *LCtx = C.getLocationContext(); 41 | LCtx; LCtx = LCtx->getParent()) { 42 | if(LCtx->getKind() == LocationContext::ContextKind::StackFrame) 43 | EncodedBugInfo.push_back(getADCQualifiedNameAsStringRef(LCtx)); 44 | /* It doesn't make sense to continue if parent is 45 | * not a stack frame. I imagine stack frames stacked 46 | * together and not interspersed between other frame types 47 | * like Scope or Block. 48 | */ 49 | else 50 | llvm_unreachable("dumpCallsOnStack says this is not a stack frame!"); 51 | } 52 | 53 | return; 54 | } 55 | 56 | std::string Diagnostics::getADCQualifiedNameAsStringRef(const LocationContext *LC) { 57 | 58 | if(LC->getKind() != LocationContext::ContextKind::StackFrame) 59 | llvm_unreachable("getADC says we are not in a stack frame!"); 60 | 61 | const AnalysisDeclContext *ADC = LC->getAnalysisDeclContext(); 62 | assert(ADC && "getAnalysisDecl returned null while dumping" 63 | " calls on stack"); 64 | 65 | // This gives us the function declaration being visited 66 | const Decl *D = ADC->getDecl(); 67 | assert(D && "ADC getDecl returned null while dumping" 68 | " calls on stack"); 69 | 70 | const NamedDecl *ND = dyn_cast(D); 71 | assert(ND && "Named declaration null while dumping" 72 | " calls on stack"); 73 | 74 | return getMangledNameAsString(ND, ADC->getASTContext()); 75 | } 76 | 77 | std::string Diagnostics::getMangledNameAsString(const NamedDecl *ND, 78 | ASTContext &ASTC) { 79 | // Create Mangle context 80 | MangleContext *MC = ASTC.createMangleContext(); 81 | 82 | // We need raw string stream so we can return std::string 83 | std::string MangledName; 84 | llvm::raw_string_ostream raw_stream(MangledName); 85 | 86 | if(!MC->shouldMangleDeclName(ND)) 87 | return ND->getQualifiedNameAsString(); 88 | 89 | /* Assertion deep within mangleName */ 90 | if(!isa(ND) && !isa(ND)){ 91 | MC->mangleName(ND, raw_stream); 92 | return raw_stream.str(); 93 | } 94 | 95 | return ND->getQualifiedNameAsString(); 96 | } 97 | -------------------------------------------------------------------------------- /src/UseDefChecker.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_USEDEFCHECKER_H 2 | #define MELANGE_USEDEFCHECKER_H 3 | 4 | #include "clang/StaticAnalyzer/Core/Checker.h" 5 | #include "llvm/ADT/DenseSet.h" 6 | #include "llvm/ADT/DenseMap.h" 7 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 8 | #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 9 | #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h" 10 | 11 | namespace Melange { 12 | 13 | class UseDefChecker : public clang::ento::Checker< clang::ento::check::EndFunction, 14 | clang::ento::check::BranchCondition, 15 | clang::ento::check::PreStmt, 16 | clang::ento::check::PreCall, 17 | clang::ento::check::EndOfTranslationUnit> { 18 | 19 | typedef llvm::DenseSet CtorsVisitedTy; 20 | typedef llvm::DenseSet CtorsDeclSetTy; 21 | typedef clang::ento::BugReport::ExtraTextList ETLTy; 22 | typedef ETLTy::const_iterator EBIIteratorTy; 23 | typedef std::pair DiagPairTy; 24 | typedef llvm::DenseMap DiagnosticsInfoTy; 25 | typedef const clang::ento::FunctionSummariesTy::MapTy FSMapTy; 26 | typedef const clang::ento::FunctionSummariesTy::FunctionSummary::TLDTaintMapTy TLDTMTy; 27 | typedef const clang::ento::FunctionSummariesTy::FunctionSummary::DTPair DTPairTy; 28 | 29 | mutable std::unique_ptr BT; 30 | enum SetKind { Ctor, Context }; 31 | 32 | mutable CtorsVisitedTy ctorsVisited; 33 | mutable ETLTy EncodedBugInfo; 34 | mutable DiagnosticsInfoTy DiagnosticsInfo; 35 | 36 | public: 37 | void checkPreStmt(const clang::BinaryOperator *BO, clang::ento::CheckerContext &C) const; 38 | void checkEndFunction(clang::ento::CheckerContext &C) const; 39 | void checkBranchCondition(const clang::Stmt *Condition, clang::ento::CheckerContext &Ctx) const; 40 | void checkPreCall(const clang::ento::CallEvent &Call, clang::ento::CheckerContext &C) const; 41 | void checkEndOfTranslationUnit(const clang::TranslationUnitDecl *TU, clang::ento::AnalysisManager &Mgr, 42 | clang::ento::BugReporter &BR) const; 43 | 44 | private: 45 | void addNDToTaintSet(const clang::NamedDecl *ND, clang::ento::CheckerContext &C) const; 46 | bool isTaintedInContext(const clang::NamedDecl *ND, clang::ento::CheckerContext &C) const; 47 | void reportBug(clang::ento::AnalysisManager &Mgr, clang::ento::BugReporter &BR, const clang::Decl *D) const; 48 | void checkUnaryOp(const clang::UnaryOperator *UO, clang::ento::CheckerContext &C) const; 49 | void checkBinaryOp(const clang::BinaryOperator *BO, clang::ento::CheckerContext &C) const; 50 | void checkUseIfMemberExpr(const clang::Expr *E, clang::ento::CheckerContext &C) const; 51 | void trackMembersInAssign(const clang::BinaryOperator *BO, clang::ento::CheckerContext &C) const; 52 | void branchStmtChecker(const clang::Stmt *Condition, clang::ento::CheckerContext &C) const; 53 | void encodeBugInfo(const clang::MemberExpr *ME, clang::ento::CheckerContext &C) const; 54 | void dumpCallsOnStack(clang::ento::CheckerContext &C) const; 55 | void storeDiagnostics(const clang::Decl *D, clang::SourceLocation SL) const; 56 | void taintCtorInits(const clang::CXXConstructorDecl *CCD, clang::ento::CheckerContext &C) const; 57 | 58 | // Static utility functions 59 | static bool isCXXFieldDecl(const clang::Expr *E); 60 | static std::string getADCQualifiedNameAsStringRef(const clang::LocationContext *LC); 61 | static std::string getMangledNameAsString(const clang::NamedDecl *ND, clang::ASTContext &ASTC); 62 | }; 63 | } // end of Melange namespace 64 | 65 | #endif // MELANGE_USEDEFCHECKER_H 66 | -------------------------------------------------------------------------------- /tests/typecast-bugs/test_harness.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | __author__ = 'bhargava' 4 | 5 | import os, sys, subprocess 6 | import collections 7 | import filecmp 8 | import unittest 9 | import glob 10 | 11 | statout = collections.namedtuple('StatusOutPair', ['ret', 'out']) 12 | 13 | 14 | def execwrapper(args, errMsg): 15 | p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, executable="/bin/bash") 16 | out, err = p.communicate() 17 | if err: 18 | return statout(False, out) 19 | return statout(True, out) 20 | 21 | 22 | def diffExp(filename, out): 23 | basename = os.path.basename(filename) 24 | with open("expects/%s.exp" % basename, "r") as expectation: 25 | expects = expectation.read() 26 | if out != expects: 27 | return False 28 | expectation.close() 29 | return True 30 | 31 | 32 | def invokecj(filename): 33 | args = "clang --analyze -Xclang -load -Xclang /home/bhargava/work/gitlab/checkers/build-live/libusedef-checker.so -Xclang -analyzer-checker=alpha.security.CastChecker -Xanalyzer -analyzer-disable-checker=core,unix,deadcode,cplusplus,security %s" % filename 34 | retpair = execwrapper(args, "Test on %s" % filename + " failed") 35 | if retpair.ret: 36 | return diffExp(filename, retpair.out) 37 | return False 38 | 39 | 40 | # Schema: filename, filename.nodes.exp, filename.edges.exp 41 | def testinput(filename): 42 | return invokecj(filename) 43 | 44 | 45 | class SimpleTester(unittest.TestCase): 46 | def tearDown(self): 47 | plist_files = glob.glob("*.plist") 48 | for f in plist_files: 49 | os.remove(f) 50 | 51 | 52 | class TestBasic(SimpleTester): 53 | def test_malloc(self): 54 | self.assertEqual(testinput('malloc-int-unsigned.c'), True, 55 | 'Test on malloc-int-unsigned.c failed') 56 | def test_calloc(self): 57 | self.assertEqual(testinput('calloc-int-unsigned.c'), True, 58 | 'Test on calloc-int-unsigned.c failed') 59 | def test_realloc(self): 60 | self.assertEqual(testinput('realloc-int-unsigned.c'), True, 61 | 'Test on realloc-int-unsigned.c failed') 62 | def test_reallocarray(self): 63 | self.assertEqual(testinput('reallocarray-int-unsigned.c'), True, 64 | 'Test on reallocarray-int-unsigned.c failed') 65 | def test_memcpy(self): 66 | self.assertEqual(testinput('memcpy-int-unsigned.c'), True, 67 | 'Test on memcpy-int-unsigned.c failed') 68 | def test_memset(self): 69 | self.assertEqual(testinput('memset-int-unsigned.c'), True, 70 | 'Test on memset-int-unsigned.c failed') 71 | def test_memmove(self): 72 | self.assertEqual(testinput('memmove-int-unsigned.c'), True, 73 | 'Test on memmove-int-unsigned.c failed') 74 | def test_strncpy(self): 75 | self.assertEqual(testinput('strncpy-int-unsigned.c'), True, 76 | 'Test on strncpy-int-unsigned.c failed') 77 | def test_mallocimplicit(self): 78 | self.assertEqual(testinput('malloc-implicit.c'), True, 79 | 'Test on malloc-implicit.c failed') 80 | def test_callocimplicit(self): 81 | self.assertEqual(testinput('calloc-implicit.c'), True, 82 | 'Test on calloc-implicit.c failed') 83 | def test_reallocimplicit(self): 84 | self.assertEqual(testinput('realloc-implicit.c'), True, 85 | 'Test on realloc-implicit.c failed') 86 | def test_memcpyimplicit(self): 87 | self.assertEqual(testinput('memcpy-implicit.c'), True, 88 | 'Test on memcpy-implicit.c failed') 89 | def test_memsetimplicit(self): 90 | self.assertEqual(testinput('memset-implicit.c'), True, 91 | 'Test on memset-implicit.c failed') 92 | def test_memmoveimplicit(self): 93 | self.assertEqual(testinput('memmove-implicit.c'), True, 94 | 'Test on memmove-implicit.c failed') 95 | def test_strncpyimplicit(self): 96 | self.assertEqual(testinput('strncpy-implicit.c'), True, 97 | 'Test on strncpy-implicit.c failed') 98 | def test_range(self): 99 | self.assertEqual(testinput('rangetest.c'), True, 100 | 'Test on rangetest.c failed') 101 | 102 | 103 | if __name__ == '__main__': 104 | unittest.main() 105 | -------------------------------------------------------------------------------- /src/TypeConfusionChecker.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeConfusionChecker.h" 2 | 3 | 4 | using namespace clang; 5 | using namespace ento; 6 | using Melange::TypeConfusionChecker; 7 | 8 | REGISTER_MAP_WITH_PROGRAMSTATE(TypeMap, const ValueDecl*, QualType) 9 | 10 | const QualType *isVoidPtr(CheckerContext &C, const Expr* E) { 11 | if (!isa(E)) 12 | return nullptr; 13 | 14 | const auto *VD = cast(E)->getDecl(); 15 | 16 | ProgramStateRef State = C.getState(); 17 | const QualType *T = State->get(VD); 18 | return T; 19 | } 20 | 21 | void handleInternal(const Decl *D, const Expr *E, CheckerContext &C) { 22 | ProgramStateRef State = C.getState(); 23 | const ValueDecl *VD = cast(D); 24 | 25 | if (cast(E)->getCastKind() != CK_BitCast) { 26 | const QualType *RT = isVoidPtr(C, E->IgnoreImpCasts()); 27 | if (!RT) 28 | return; 29 | 30 | DEBUG_PRINT("RHS is void ptr that has been cast to " + RT->getAsString()); 31 | 32 | State = State->set(VD, *(const_cast(RT))); 33 | if(State != C.getState()) { 34 | DEBUG_PRINT("Value is " + State->get(VD)->getAsString()); 35 | C.addTransition(State); 36 | } 37 | return; 38 | } 39 | 40 | DEBUG_PRINT("RHS is being bitcast"); 41 | 42 | State = State->set(VD, E->IgnoreImpCasts()->getType()); 43 | if(State != C.getState()) { 44 | DEBUG_PRINT("Value is " + State->get(VD)->getAsString()); 45 | C.addTransition(State); 46 | } 47 | } 48 | 49 | void handleBO(const BinaryOperator *BO, CheckerContext &C) { 50 | const auto *LHS = BO->getLHS()->IgnoreParenImpCasts(); 51 | 52 | if (!isa(LHS)) 53 | return; 54 | 55 | DEBUG_PRINT("DeclRefExpr"); 56 | 57 | const auto *LDecl = cast(LHS)->getDecl(); 58 | 59 | if (!(LDecl->getType().getTypePtr()->isVoidPointerType())) 60 | return; 61 | 62 | DEBUG_PRINT("LHS is void ptr"); 63 | 64 | const auto *RHS = BO->getRHS()->IgnoreParens(); 65 | 66 | if (!isa(RHS)) 67 | return; 68 | 69 | handleInternal(cast(LDecl), RHS, C); 70 | } 71 | 72 | void handleDeclStmt(const DeclStmt *DS, CheckerContext &C) { 73 | const Decl *D = DS->getSingleDecl(); 74 | 75 | if (!isa(D)) 76 | return; 77 | 78 | const VarDecl *VD = cast(D); 79 | DEBUG_PRINT("Var Decl"); 80 | 81 | if (!(cast(VD)->getType().getTypePtr()->isVoidPointerType())) 82 | return; 83 | 84 | DEBUG_PRINT("Var Decl is void ptr"); 85 | 86 | if (!VD->hasInit()) 87 | return; 88 | 89 | const Expr *E = VD->getInit()->IgnoreParens(); 90 | 91 | if (!isa(E)) 92 | return; 93 | 94 | handleInternal(D, E, C); 95 | } 96 | 97 | void handleAssignment(const Stmt *S, CheckerContext &C) { 98 | 99 | assert((isa(S) || isa(S)) && 100 | "Expression neither BO nor DeclStmt"); 101 | 102 | if (isa(S)) 103 | handleBO(cast(S), C); 104 | else if (isa(S)) 105 | handleDeclStmt(cast(S), C); 106 | } 107 | 108 | void TypeConfusionChecker::checkPreStmt(const clang::CastExpr *CE, 109 | clang::ento::CheckerContext &C) const { 110 | if (isa(CE)) 111 | return; 112 | 113 | DEBUG_PRINT("Explicit cast expression"); 114 | // CE->dump(); 115 | 116 | const auto *E = CE->getSubExpr()->IgnoreParenImpCasts(); 117 | if (!isa(E)) 118 | return; 119 | 120 | DEBUG_PRINT("Found declref expr"); 121 | 122 | ProgramStateRef State = C.getState(); 123 | const ValueDecl *VD = cast(E)->getDecl(); 124 | const QualType *QT = State->get(VD); 125 | 126 | if (!QT) 127 | return; 128 | 129 | DEBUG_PRINT("Obtained value from key"); 130 | 131 | // Compare Cast To type to T 132 | if (!isa(CE)) 133 | return; 134 | 135 | const Type *castTo = cast(CE)->getTypeAsWritten().getTypePtr(); 136 | 137 | std::string declName, Message, castFromTyString, castToTyString; 138 | castToTyString = castTo->getCanonicalTypeInternal().getAsString(); 139 | castFromTyString = QT->getAsString(); 140 | 141 | if (castToTyString.compare(castFromTyString) == 0) 142 | return; 143 | 144 | DEBUG_PRINT("Type comparison failed"); 145 | 146 | if (isa(VD)) 147 | declName = cast(VD)->getQualifiedNameAsString(); 148 | 149 | Message = declName + " is unsafely cast from " + castFromTyString + " to " + 150 | castToTyString; 151 | 152 | reportBug(C, CE->getSourceRange(), Message, declName); 153 | } 154 | 155 | void TypeConfusionChecker::checkPreStmt(const clang::CallExpr *CaE, 156 | clang::ento::CheckerContext &C) const { 157 | return; 158 | } 159 | 160 | void TypeConfusionChecker::checkPreStmt(const clang::BinaryOperator *BO, 161 | clang::ento::CheckerContext &C) const { 162 | 163 | if (BO->getOpcode() != BO_Assign) 164 | return; 165 | 166 | DEBUG_PRINT("Assignment"); 167 | 168 | handleAssignment(cast(BO), C); 169 | } 170 | 171 | void TypeConfusionChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const { 172 | if (!DS->isSingleDecl()) 173 | return; 174 | 175 | DEBUG_PRINT("Single DeclStmt"); 176 | 177 | handleAssignment(cast(DS), C); 178 | } 179 | 180 | void TypeConfusionChecker::reportBug(CheckerContext &C, SourceRange SR, 181 | StringRef Message, StringRef declName) const { 182 | const char *name = "Type confusion checker"; 183 | const char *desc = "Flags unsafe casts"; 184 | 185 | ExplodedNode *EN = C.generateSink(); 186 | if (!EN) 187 | return; 188 | 189 | if (!BT) 190 | BT.reset(new BuiltinBug(this, name, desc)); 191 | 192 | BugReport *R = new BugReport(*BT, Message, EN); 193 | R->addRange(SR); 194 | 195 | Diag.encodeBugInfo(declName, C); 196 | for (auto &i : Diag.getBugInfoDiag()) { 197 | R->addExtraText(i); 198 | } 199 | 200 | C.emitReport(R); 201 | } 202 | -------------------------------------------------------------------------------- /src/PHPTaintChecker.h: -------------------------------------------------------------------------------- 1 | #ifndef MELANGE_PHPTAINT_CHECKER_H 2 | #define MELANGE_PHPTAINT_CHECKER_H 3 | 4 | #include "clang/Basic/Builtins.h" 5 | #include "clang/StaticAnalyzer/Core/Checker.h" 6 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 7 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 8 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 9 | #include "Diagnostics.h" 10 | 11 | #ifdef _DEBUG 12 | #define DEBUG_PRINT(x) llvm::errs() << x << "\n" 13 | #else 14 | #define DEBUG_PRINT(x) 15 | #endif 16 | 17 | static const unsigned InvalidArgIndex = UINT_MAX; 18 | static const unsigned ReturnValueIndex = UINT_MAX-1; 19 | 20 | namespace Melange { 21 | 22 | class Diagnostics; 23 | 24 | class PHPTaintChecker : public clang::ento::Checker, 25 | clang::ento::check::PostStmt, 26 | clang::ento::check::Location> { 27 | 28 | mutable Diagnostics Diag; 29 | 30 | public: 31 | void checkPreStmt(const clang::CallExpr *Call, clang::ento::CheckerContext &C) const; 32 | void checkPostStmt(const clang::CallExpr *Call, clang::ento::CheckerContext &C) const; 33 | void checkLocation(clang::ento::SVal Loc, bool IsLoad, const clang::Stmt *S, 34 | clang::ento::CheckerContext &) const; 35 | 36 | static void *getTag() { static int Tag; return &Tag; } 37 | 38 | private: 39 | mutable std::unique_ptr BT; 40 | 41 | inline void initBugType() const { 42 | if (!BT) 43 | BT.reset(new clang::ento::BugType(this, "Use of Tainted Data", "Tainted Data")); 44 | } 45 | 46 | /// \brief Catch taint related bugs. Check if tainted data is passed to a 47 | /// system call etc. 48 | bool checkPre(const clang::CallExpr *CE, clang::ento::CheckerContext &C) const; 49 | 50 | /// \brief Add taint sources on a pre-visit. 51 | void addSourcesPre(const clang::CallExpr *CE, clang::ento::CheckerContext &C) const; 52 | 53 | /// \brief Propagate taint generated at pre-visit. 54 | bool propagateFromPre(const clang::CallExpr *CE, clang::ento::CheckerContext &C) const; 55 | 56 | /// \brief Add taint sources on a post visit. 57 | void addSourcesPost(const clang::CallExpr *CE, clang::ento::CheckerContext &C) const; 58 | 59 | /// \brief Given a pointer argument, get the symbol of the value it contains 60 | /// (points to). 61 | static clang::ento::SymbolRef getPointedToSymbol(clang::ento::CheckerContext &C, 62 | const clang::Expr *Arg); 63 | 64 | /// Functions defining the attack surface. 65 | typedef clang::ento::ProgramStateRef (PHPTaintChecker::*FnCheck)(const clang::CallExpr *, 66 | clang::ento::CheckerContext &C) const; 67 | 68 | /// Functions handling macro madness in PHP 69 | typedef clang::ento::ProgramStateRef (PHPTaintChecker::*SanHandler)(clang::ento::SVal sym, 70 | clang::ento::CheckerContext &C) const; 71 | clang::ento::ProgramStateRef postRetTaint(const clang::CallExpr *CE, 72 | clang::ento::CheckerContext &C) const; 73 | 74 | clang::ento::ProgramStateRef prePHPTaintSources(const clang::CallExpr *CE, 75 | clang::ento::CheckerContext &C) const; 76 | 77 | bool checkPHPSinks(const clang::CallExpr *CE, llvm::StringRef Name, 78 | clang::ento::CheckerContext &C) const; 79 | 80 | clang::ento::ProgramStateRef postSanTaint(clang::ento::SVal sym, 81 | clang::ento::CheckerContext &C) const; 82 | 83 | /// Generate a report if the expression is tainted or points to tainted data. 84 | bool generateReportIfTainted(const clang::Expr *E, const char Msg[], 85 | clang::ento::CheckerContext &C) const; 86 | 87 | void generateReport(const clang::Expr *E, const char Msg[], 88 | clang::ento::CheckerContext &C) const; 89 | 90 | 91 | typedef llvm::SmallVector ArgVector; 92 | 93 | /// \brief A struct used to specify taint propagation rules for a function. 94 | /// 95 | /// If any of the possible taint source arguments is tainted, all of the 96 | /// destination arguments should also be tainted. Use InvalidArgIndex in the 97 | /// src list to specify that all of the arguments can introduce taint. Use 98 | /// InvalidArgIndex in the dst arguments to signify that all the non-const 99 | /// pointer and reference arguments might be tainted on return. If 100 | /// ReturnValueIndex is added to the dst list, the return value will be 101 | /// tainted. 102 | struct TaintPropagationRule { 103 | /// List of arguments which can be taint sources and should be checked. 104 | ArgVector SrcArgs; 105 | /// List of arguments which should be tainted on function return. 106 | ArgVector DstArgs; 107 | // TODO: Check if using other data structures would be more optimal. 108 | bool Sanitize; 109 | 110 | TaintPropagationRule(): Sanitize(false) {} 111 | 112 | TaintPropagationRule(unsigned SArg, 113 | unsigned DArg, bool TaintRet = false, 114 | bool San = false) { 115 | SrcArgs.push_back(SArg); 116 | DstArgs.push_back(DArg); 117 | if (TaintRet) 118 | DstArgs.push_back(ReturnValueIndex); 119 | Sanitize = San; 120 | } 121 | 122 | TaintPropagationRule(unsigned SArg1, unsigned SArg2, 123 | unsigned DArg, bool TaintRet = false, 124 | bool San = false) { 125 | SrcArgs.push_back(SArg1); 126 | SrcArgs.push_back(SArg2); 127 | DstArgs.push_back(DArg); 128 | if (TaintRet) 129 | DstArgs.push_back(ReturnValueIndex); 130 | Sanitize = San; 131 | } 132 | 133 | /// Get the propagation rule for a given function. 134 | static TaintPropagationRule 135 | getTaintPropagationRule(llvm::StringRef Name, 136 | clang::ento::CheckerContext &C); 137 | 138 | inline void addSrcArg(unsigned A) { SrcArgs.push_back(A); } 139 | inline void addDstArg(unsigned A) { DstArgs.push_back(A); } 140 | 141 | inline bool isNull() const { return SrcArgs.empty(); } 142 | 143 | inline bool isDestinationArgument(unsigned ArgNum) const { 144 | return (std::find(DstArgs.begin(), 145 | DstArgs.end(), ArgNum) != DstArgs.end()); 146 | } 147 | 148 | static inline bool isTaintedOrPointsToTainted(const clang::Expr *E, 149 | clang::ento::ProgramStateRef State, 150 | clang::ento::CheckerContext &C) { 151 | return (State->isTainted(E, C.getLocationContext()) || 152 | (E->getType().getTypePtr()->isPointerType() && 153 | State->isTainted(getPointedToSymbol(C, E)))); 154 | } 155 | 156 | inline bool isSanRule() const { return Sanitize; } 157 | 158 | /// \brief Pre-process a function which propagates taint according to the 159 | /// taint rule. 160 | clang::ento::ProgramStateRef process(const clang::CallExpr *CE, 161 | clang::ento::CheckerContext &C) const; 162 | 163 | }; 164 | 165 | static inline TaintPropagationRule getRule(llvm::StringRef Name, 166 | clang::ento::CheckerContext &C) { 167 | return TaintPropagationRule::getTaintPropagationRule(Name, C); 168 | } 169 | }; 170 | 171 | } // end of Melange namespace 172 | 173 | #endif 174 | -------------------------------------------------------------------------------- /FindLLVM.cmake: -------------------------------------------------------------------------------- 1 | # - Find LLVM headers and libraries. 2 | # This module locates LLVM and adapts the llvm-config output for use with 3 | # CMake. 4 | # 5 | # A given list of COMPONENTS is passed to llvm-config. 6 | # 7 | # The following variables are defined: 8 | # LLVM_FOUND - true if LLVM was found 9 | # LLVM_CXXFLAGS - C++ compiler flags for files that include LLVM headers. 10 | # LLVM_HOST_TARGET - Target triple used to configure LLVM. 11 | # LLVM_INCLUDE_DIRS - Directory containing LLVM include files. 12 | # LLVM_LDFLAGS - Linker flags to add when linking against LLVM 13 | # (includes -LLLVM_LIBRARY_DIRS). 14 | # LLVM_LIBRARIES - Full paths to the library files to link against. 15 | # LLVM_LIBRARY_DIRS - Directory containing LLVM libraries. 16 | # LLVM_ROOT_DIR - The root directory of the LLVM installation. 17 | # llvm-config is searched for in ${LLVM_ROOT_DIR}/bin. 18 | # LLVM_VERSION_MAJOR - Major version of LLVM. 19 | # LLVM_VERSION_MINOR - Minor version of LLVM. 20 | # LLVM_VERSION_STRING - Full LLVM version string (e.g. 2.9). 21 | # 22 | # Note: The variable names were chosen in conformance with the offical CMake 23 | # guidelines, see ${CMAKE_ROOT}/Modules/readme.txt. 24 | 25 | # Try suffixed versions to pick up the newest LLVM install available on Debian 26 | # derivatives. 27 | # We also want an user-specified LLVM_ROOT_DIR to take precedence over the 28 | # system default locations such as /usr/local/bin. Executing find_program() 29 | # multiples times is the approach recommended in the docs. 30 | set(llvm_config_names llvm-config-3.6 llvm-config36 31 | llvm-config-3.5 llvm-config35 32 | llvm-config-3.4 llvm-config34 33 | llvm-config-3.3 llvm-config33 34 | llvm-config-3.2 llvm-config32 35 | llvm-config-3.1 llvm-config31 llvm-config) 36 | find_program(LLVM_CONFIG 37 | NAMES ${llvm_config_names} 38 | PATHS ${LLVM_ROOT_DIR}/bin NO_DEFAULT_PATH 39 | DOC "Path to llvm-config tool.") 40 | find_program(LLVM_CONFIG NAMES ${llvm_config_names}) 41 | 42 | if ((WIN32 AND NOT(MINGW OR CYGWIN)) OR NOT LLVM_CONFIG) 43 | if (WIN32) 44 | # A bit of a sanity check: 45 | if( NOT EXISTS ${LLVM_ROOT_DIR}/include/llvm ) 46 | message(FATAL_ERROR "LLVM_ROOT_DIR (${LLVM_ROOT_DIR}) is not a valid LLVM install") 47 | endif() 48 | # We incorporate the CMake features provided by LLVM: 49 | set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${LLVM_ROOT_DIR}/share/llvm/cmake") 50 | include(LLVMConfig) 51 | # Set properties 52 | set(LLVM_HOST_TARGET ${TARGET_TRIPLE}) 53 | set(LLVM_VERSION_STRING ${LLVM_PACKAGE_VERSION}) 54 | set(LLVM_CXXFLAGS ${LLVM_DEFINITIONS}) 55 | set(LLVM_LDFLAGS "") 56 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "all-targets" index) 57 | list(APPEND LLVM_FIND_COMPONENTS ${LLVM_TARGETS_TO_BUILD}) 58 | # Work around LLVM bug 21016 59 | list(FIND LLVM_TARGETS_TO_BUILD "X86" TARGET_X86) 60 | if(TARGET_X86 GREATER -1) 61 | list(APPEND LLVM_FIND_COMPONENTS x86utils) 62 | endif() 63 | # Similar to the work around above, but for AArch64 64 | list(FIND LLVM_TARGETS_TO_BUILD "AArch64" TARGET_AArch64) 65 | if(TARGET_AArch64 GREATER -1) 66 | list(APPEND LLVM_FIND_COMPONENTS AArch64Utils) 67 | endif() 68 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "backend" index) 69 | if(${LLVM_VERSION_STRING} MATCHES "^3\\.[0-2][\\.0-9A-Za-z]*") 70 | # Versions below 3.3 do not support components objcarcopts, option 71 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "objcarcopts" index) 72 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "option" index) 73 | endif() 74 | if(${LLVM_VERSION_STRING} MATCHES "^3\\.[0-4][\\.0-9A-Za-z]*") 75 | # Versions below 3.5 do not support components lto, profiledata 76 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "lto" index) 77 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "profiledata" index) 78 | endif() 79 | 80 | if(${LLVM_VERSION_STRING} MATCHES "^3\\.[0-4][\\.0-9A-Za-z]*") 81 | llvm_map_components_to_libraries(tmplibs ${LLVM_FIND_COMPONENTS}) 82 | else() 83 | llvm_map_components_to_libnames(tmplibs ${LLVM_FIND_COMPONENTS}) 84 | endif() 85 | if(MSVC) 86 | foreach(lib ${tmplibs}) 87 | list(APPEND LLVM_LIBRARIES "${LLVM_LIBRARY_DIRS}/${CMAKE_STATIC_LIBRARY_PREFIX}${lib}${CMAKE_STATIC_LIBRARY_SUFFIX}") 88 | endforeach() 89 | else() 90 | # Rely on the library search path being set correctly via -L on 91 | # MinGW and others, as the library list returned by 92 | # llvm_map_components_to_libraries also includes imagehlp and psapi. 93 | set(LLVM_LDFLAGS "-L${LLVM_LIBRARY_DIRS}") 94 | set(LLVM_LIBRARIES ${tmplibs}) 95 | endif() 96 | 97 | # When using the CMake LLVM module, LLVM_DEFINITIONS is a list 98 | # instead of a string. Later, the list seperators would entirely 99 | # disappear, replace them by spaces instead. A better fix would be 100 | # to switch to add_definitions() instead of throwing strings around. 101 | string(REPLACE ";" " " LLVM_CXXFLAGS "${LLVM_CXXFLAGS}") 102 | else() 103 | if (NOT FIND_LLVM_QUIETLY) 104 | message(WARNING "Could not find llvm-config. Try manually setting LLVM_CONFIG to the llvm-config executable of the installation to use.") 105 | endif() 106 | endif() 107 | else() 108 | macro(llvm_set var flag) 109 | if(LLVM_FIND_QUIETLY) 110 | set(_quiet_arg ERROR_QUIET) 111 | endif() 112 | execute_process( 113 | COMMAND ${LLVM_CONFIG} --${flag} 114 | OUTPUT_VARIABLE LLVM_${var} 115 | OUTPUT_STRIP_TRAILING_WHITESPACE 116 | ${_quiet_arg} 117 | ) 118 | if(${ARGV2}) 119 | file(TO_CMAKE_PATH "${LLVM_${var}}" LLVM_${var}) 120 | endif() 121 | endmacro() 122 | macro(llvm_set_libs var flag prefix) 123 | if(LLVM_FIND_QUIETLY) 124 | set(_quiet_arg ERROR_QUIET) 125 | endif() 126 | execute_process( 127 | COMMAND ${LLVM_CONFIG} --${flag} ${LLVM_FIND_COMPONENTS} 128 | OUTPUT_VARIABLE tmplibs 129 | OUTPUT_STRIP_TRAILING_WHITESPACE 130 | ${_quiet_arg} 131 | ) 132 | file(TO_CMAKE_PATH "${tmplibs}" tmplibs) 133 | string(REGEX REPLACE "([$^.[|*+?()]|])" "\\\\\\1" pattern "${prefix}/") 134 | string(REGEX MATCHALL "${pattern}[^ ]+" LLVM_${var} ${tmplibs}) 135 | endmacro() 136 | 137 | llvm_set(VERSION_STRING version) 138 | llvm_set(CXXFLAGS cxxflags) 139 | llvm_set(HOST_TARGET host-target) 140 | llvm_set(INCLUDE_DIRS includedir true) 141 | llvm_set(ROOT_DIR prefix true) 142 | 143 | if(${LLVM_VERSION_STRING} MATCHES "^3\\.[0-2][\\.0-9A-Za-z]*") 144 | # Versions below 3.3 do not support components objcarcopts, option 145 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "objcarcopts" index) 146 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "option" index) 147 | endif() 148 | if(${LLVM_VERSION_STRING} MATCHES "^3\\.[0-4][\\.0-9A-Za-z]*") 149 | # Versions below 3.5 do not support components lto, profiledata 150 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "lto" index) 151 | list(REMOVE_ITEM LLVM_FIND_COMPONENTS "profiledata" index) 152 | endif() 153 | 154 | llvm_set(LDFLAGS ldflags) 155 | if(NOT ${LLVM_VERSION_STRING} MATCHES "^3\\.[0-4][\\.0-9A-Za-z]*") 156 | # In LLVM 3.5+, the system library dependencies (e.g. "-lz") are accessed 157 | # using the separate "--system-libs" flag. 158 | llvm_set(SYSTEM_LIBS system-libs) 159 | string(REPLACE "\n" " " LLVM_LDFLAGS "${LLVM_LDFLAGS} ${LLVM_SYSTEM_LIBS}") 160 | endif() 161 | llvm_set(LIBRARY_DIRS libdir true) 162 | llvm_set_libs(LIBRARIES libfiles "${LLVM_LIBRARY_DIRS}") 163 | endif() 164 | 165 | # On CMake builds of LLVM, the output of llvm-config --cxxflags does not 166 | # include -fno-rtti, leading to linker errors. Be sure to add it. 167 | if(CMAKE_COMPILER_IS_GNUCXX OR (${CMAKE_CXX_COMPILER_ID} STREQUAL "Clang")) 168 | if(NOT ${LLVM_CXXFLAGS} MATCHES "-fno-rtti") 169 | set(LLVM_CXXFLAGS "${LLVM_CXXFLAGS} -fno-rtti") 170 | endif() 171 | endif() 172 | 173 | string(REGEX REPLACE "([0-9]+).*" "\\1" LLVM_VERSION_MAJOR "${LLVM_VERSION_STRING}" ) 174 | string(REGEX REPLACE "[0-9]+\\.([0-9]+).*[A-Za-z]*" "\\1" LLVM_VERSION_MINOR "${LLVM_VERSION_STRING}" ) 175 | 176 | # Use the default CMake facilities for handling QUIET/REQUIRED. 177 | include(FindPackageHandleStandardArgs) 178 | 179 | if(${CMAKE_VERSION} VERSION_LESS "2.8.4") 180 | # The VERSION_VAR argument is not supported on pre-2.8.4, work around this. 181 | set(VERSION_VAR dummy) 182 | endif() 183 | 184 | find_package_handle_standard_args(LLVM 185 | REQUIRED_VARS LLVM_ROOT_DIR LLVM_HOST_TARGET 186 | VERSION_VAR LLVM_VERSION_STRING) 187 | -------------------------------------------------------------------------------- /src/TypeCastingVulnChecker.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeCastingVulnChecker.h" 2 | 3 | using namespace clang; 4 | using namespace ento; 5 | using Melange::TypeCastingVulnChecker; 6 | 7 | bool isStrictlyPositive(SVal symVal) { 8 | if (symVal.isConstant() && 9 | ((symVal.getBaseKind() == SVal::NonLocKind) && 10 | (symVal.getSubKind() == nonloc::ConcreteIntKind))) { 11 | 12 | const nonloc::ConcreteInt& C = symVal.castAs(); 13 | const llvm::APInt &value = C.getValue(); 14 | 15 | if (value.isStrictlyPositive()) 16 | return true; 17 | 18 | return false; 19 | } 20 | 21 | // Symval is not a concrete int => may not be strictly positive 22 | return false; 23 | } 24 | 25 | bool isAssumedStrictlyPositive(Optional symVal, CheckerContext &C) { 26 | 27 | if (!symVal) 28 | return false; 29 | 30 | ProgramStateRef State = C.getState(); 31 | SValBuilder &SB = C.getSValBuilder(); 32 | 33 | llvm::APInt IntMax(32, 2147483647); 34 | NonLoc IntMaxVal = SB.makeIntVal(IntMax, false); 35 | llvm::APInt Zero(32, 0); 36 | NonLoc ZeroVal = SB.makeIntVal(Zero, false); 37 | 38 | SVal condUpper = SB.evalBinOpNN(State, BO_LT, *symVal, IntMaxVal, 39 | SB.getConditionType()); 40 | 41 | Optional NLCondUpper = condUpper.getAs(); 42 | 43 | if(!NLCondUpper) 44 | return false; 45 | 46 | ProgramStateRef stateUT, stateUF; 47 | std::tie(stateUT, stateUF) = State->assume(*NLCondUpper); 48 | 49 | SVal condLower = SB.evalBinOpNN(State, BO_GT, *symVal, ZeroVal, 50 | SB.getConditionType()); 51 | 52 | Optional NLCondLower = condLower.getAs(); 53 | 54 | if(!NLCondLower) 55 | return false; 56 | 57 | ProgramStateRef stateLT, stateLF; 58 | std::tie(stateLT, stateLF) = State->assume(*NLCondLower); 59 | 60 | // (0, INT_MAX) 61 | if ((stateUT && stateLT) && (!stateUF && !stateLF)) { 62 | DEBUG_PRINT("0 < size < INT_MAX"); 63 | return true; 64 | } 65 | // (INT_MAX, UINT64_MAX) 66 | if (!stateUT && stateUF) { 67 | DEBUG_PRINT("size > INT_MAX"); 68 | return false; 69 | } 70 | // (0, 71 | if (stateLT && !stateLF) { 72 | DEBUG_PRINT("size > 0"); 73 | return true; 74 | } 75 | // , 0) 76 | if (!stateLT && stateLF) { 77 | DEBUG_PRINT("size < 0"); 78 | return false; 79 | } 80 | // , INT_MAX) 81 | DEBUG_PRINT("size is unconstrained"); 82 | return false; 83 | } 84 | 85 | bool isUnsafeExpCast(CheckerContext &C, const Expr *E, SVal sym, 86 | std::string &Message, std::string &declName) { 87 | 88 | assert(isa(E->IgnoreParenImpCasts()) && "Expr is not explicit cast"); 89 | 90 | const ExplicitCastExpr *ECE = cast(E->IgnoreParenImpCasts()); 91 | 92 | const auto *ICE = dyn_cast(ECE->getSubExpr()); 93 | 94 | if (!ICE) 95 | return false; 96 | 97 | DEBUG_PRINT("Is implicit cast"); 98 | 99 | // Implicitcastexpr 100 | 101 | if (ICE->getCastKind() != CK_LValueToRValue) 102 | return false; 103 | 104 | DEBUG_PRINT("Involves lvaltorval conv"); 105 | 106 | // lvaltorval 107 | const auto *castDRE = dyn_cast(ECE->getSubExpr()->IgnoreParenImpCasts()); 108 | 109 | if (!castDRE) 110 | return false; 111 | 112 | if (isStrictlyPositive(sym)) 113 | return false; 114 | 115 | Optional NL = sym.getAs(); 116 | if (isAssumedStrictlyPositive(NL, C)) 117 | return false; 118 | 119 | DEBUG_PRINT("castee is declrefexpr and may evaluate to neg int"); 120 | // declrefexpr 121 | const auto *VD = castDRE->getDecl(); 122 | auto castFromType = VD->getType(); 123 | auto castToType = ECE->getTypeAsWritten(); 124 | 125 | if (castFromType == castToType) 126 | return false; 127 | 128 | if (isa(VD)) 129 | declName = cast(VD)->getQualifiedNameAsString(); 130 | 131 | DEBUG_PRINT("declName: " + declName); 132 | DEBUG_PRINT("castfrom type: " + castFromType.getAsString()); 133 | DEBUG_PRINT("castto type: " + castToType.getAsString()); 134 | 135 | Message = declName + " is explicitly cast from " + castFromType.getAsString() + " to " + 136 | castToType.getAsString() + ". This may be unsafe."; 137 | 138 | return true; 139 | } 140 | 141 | bool isUnsafeImpCast(CheckerContext &C, const ImplicitCastExpr *ICE, SVal sym, 142 | std::string &Message, std::string &declName) { 143 | if (ICE->getCastKind() != CK_IntegralCast) 144 | return false; 145 | 146 | DEBUG_PRINT("Is integral cast"); 147 | 148 | const auto *lvalRvalCast = dyn_cast(ICE->getSubExpr()); 149 | 150 | if (!lvalRvalCast) 151 | return false; 152 | 153 | DEBUG_PRINT("Involves lvaltorval conv"); 154 | 155 | const auto *castDRE = dyn_cast(ICE->IgnoreParenImpCasts()); 156 | 157 | if (!castDRE) 158 | return false; 159 | 160 | if (isStrictlyPositive(sym)) 161 | return false; 162 | 163 | Optional NL = sym.getAs(); 164 | if (isAssumedStrictlyPositive(NL, C)) 165 | return false; 166 | 167 | DEBUG_PRINT("castee is declrefexpr and may evaluate to neg int"); 168 | // declrefexpr 169 | const auto *VD = castDRE->getDecl(); 170 | auto castFromType = VD->getType(); 171 | auto castToType = cast(ICE)->getType(); 172 | 173 | if (castFromType == castToType) 174 | return false; 175 | 176 | if (isa(VD)) 177 | declName = cast(VD)->getQualifiedNameAsString(); 178 | 179 | DEBUG_PRINT("declName: " + declName); 180 | DEBUG_PRINT("castfrom type: " + castFromType.getAsString()); 181 | DEBUG_PRINT("castto type: " + castToType.getAsString()); 182 | 183 | Message = declName + " is implicitly cast from " + castFromType.getAsString() + " to " + 184 | castToType.getAsString() + ". This may be unsafe."; 185 | 186 | return true; 187 | } 188 | 189 | void TypeCastingVulnChecker::reportUnsafeExpCasts(const Expr *ECE, SVal sym, 190 | CheckerContext &C) const { 191 | std::string Message = ""; 192 | std::string declName = ""; 193 | if (isUnsafeExpCast(C, ECE, sym, Message, declName)) 194 | reportBug(C, ECE->getSourceRange(), Message, declName); 195 | } 196 | 197 | void TypeCastingVulnChecker::reportUnsafeImpCasts(const ImplicitCastExpr *ICE, 198 | SVal sym, 199 | CheckerContext &C) const { 200 | std::string Message = ""; 201 | std::string declName = ""; 202 | if (isUnsafeImpCast(C, ICE, sym, Message, declName)) 203 | reportBug(C, ICE->getSourceRange(), Message, declName); 204 | } 205 | 206 | void TypeCastingVulnChecker::handleAllocArg(const Expr *E, SVal sym, 207 | CheckerContext &C) const { 208 | 209 | const auto *ECE = dyn_cast(E->IgnoreParenImpCasts()); 210 | const auto *ICE = dyn_cast(E); 211 | 212 | if (ECE) 213 | reportUnsafeExpCasts(E, sym, C); 214 | else if (ICE) 215 | reportUnsafeImpCasts(ICE, sym, C); 216 | } 217 | 218 | void TypeCastingVulnChecker::checkPreCall(const CallEvent &CE, 219 | CheckerContext &C) const { 220 | 221 | std::vector IIvec; 222 | for (auto &i : callNames) 223 | IIvec.push_back(&C.getASTContext().Idents.get(i)); 224 | 225 | const auto *funI = CE.getCalleeIdentifier(); 226 | auto iter = std::find(IIvec.begin(), IIvec.end(), funI); 227 | 228 | if (iter == IIvec.end()) 229 | return; 230 | 231 | auto index = std::distance(IIvec.begin(), iter); 232 | 233 | DEBUG_PRINT("Index is: " + std::to_string(index)); 234 | 235 | if ((index >= MALLOC_START) && (index <= MALLOC_END)) 236 | handleAllocArg(CE.getArgExpr(0), CE.getArgSVal(0), C); 237 | else if ((index >= CALLOC_START) && (index <= CALLOC_END)) { 238 | handleAllocArg(CE.getArgExpr(0), CE.getArgSVal(0), C); 239 | handleAllocArg(CE.getArgExpr(1), CE.getArgSVal(1), C); 240 | } 241 | else if ((index >= REALLOC_START) && (index <= REALLOC_END)) 242 | handleAllocArg(CE.getArgExpr(1), CE.getArgSVal(1), C); 243 | else if ((index >= REALLOCARRAY_START) && (index <= REALLOCARRAY_END)) { 244 | handleAllocArg(CE.getArgExpr(1), CE.getArgSVal(1), C); 245 | handleAllocArg(CE.getArgExpr(2), CE.getArgSVal(2), C); 246 | } 247 | else if ((index >= MEMCPY_START) && (index <= STRCPY_END)) 248 | handleAllocArg(CE.getArgExpr(2), CE.getArgSVal(2), C); 249 | } 250 | 251 | //ProgramStateRef TypeCastingVulnChecker::evalAssume(ProgramStateRef S, SVal cond, 252 | // bool assumption) const { 253 | // SymbolRef sym = cond.getAsSymbol(); 254 | // ConstraintManager &CM = S->getConstraintManager(); 255 | // if (sym) { 256 | // SymExpr::Kind K = sym->getKind(); 257 | // if ((K >= SymExpr::Kind::BEGIN_BINARYSYMEXPRS) && (K <= SymExpr::Kind::END_BINARYSYMEXPRS)) { 258 | //// sym->dump(); 259 | // ProgramStateRef stateT, stateF; 260 | // Optional loc = cond.getAs(); 261 | // Optional nonloc = cond.getAs(); 262 | // if (loc) 263 | // std::tie(stateT, stateF) = CM.assumeDual(S, *loc); 264 | // else if (nonloc) 265 | // std::tie(stateT, stateF) = CM.assumeDual(S, *nonloc); 266 | // 267 | // if (stateT && !stateF) 268 | // llvm::errs() << "Assertion of condition\n"; 269 | // } 270 | // } 271 | // return S; 272 | //} 273 | 274 | void TypeCastingVulnChecker::reportBug(CheckerContext &C, SourceRange SR, 275 | StringRef Message, StringRef declName) const { 276 | const char *name = "Type casting vulnerability checker"; 277 | const char *desc = "Flags potential unsafe casts"; 278 | 279 | ExplodedNode *EN = C.generateSink(); 280 | if (!EN) 281 | return; 282 | 283 | if (!BT) 284 | BT.reset(new BuiltinBug(this, name, desc)); 285 | 286 | BugReport *R = new BugReport(*BT, Message, EN); 287 | R->addRange(SR); 288 | 289 | Diag.encodeBugInfo(declName, C); 290 | for (auto &i : Diag.getBugInfoDiag()) { 291 | R->addExtraText(i); 292 | } 293 | 294 | C.emitReport(R); 295 | } 296 | -------------------------------------------------------------------------------- /src/PHPTaintChecker.cpp: -------------------------------------------------------------------------------- 1 | #include "PHPTaintChecker.h" 2 | #include "llvm/ADT/StringSwitch.h" 3 | 4 | using namespace clang; 5 | using namespace ento; 6 | using namespace Melange; 7 | 8 | /// A set which is used to pass information from call pre-visit instruction 9 | /// to the call post-visit. The values are unsigned integers, which are either 10 | /// ReturnValueIndex, or indexes of the pointer/reference argument, which 11 | /// points to data, which should be tainted on return. 12 | REGISTER_SET_WITH_PROGRAMSTATE(TaintArgsOnPostVisit, unsigned) 13 | 14 | static const char MsgZendTaint[] = 15 | "Untrusted data in Zend macro "; 16 | 17 | StringRef getCallName(const CallExpr *CE, CheckerContext &C) { 18 | const FunctionDecl *FDecl = C.getCalleeDecl(CE); 19 | if (!FDecl || FDecl->getKind() != Decl::Function) 20 | return StringRef(); 21 | 22 | StringRef Name = C.getCalleeName(FDecl); 23 | if (Name.empty()) 24 | return StringRef(); 25 | 26 | return Name; 27 | } 28 | 29 | StringRef getCallNameFromArgExpr(const Stmt *S, CheckerContext &C) { 30 | const auto &parents = C.getASTContext().getParents(*S); 31 | 32 | if (parents.empty()) 33 | return StringRef(); 34 | 35 | const Stmt *parent = parents.front().get(); 36 | if (!parent) 37 | return StringRef(); 38 | 39 | const CallExpr *CE = dyn_cast(parent); 40 | if (!CE) 41 | return StringRef(); 42 | 43 | return getCallName(CE, C); 44 | } 45 | 46 | PHPTaintChecker::TaintPropagationRule 47 | PHPTaintChecker::TaintPropagationRule::getTaintPropagationRule(StringRef Name, 48 | CheckerContext &C) { 49 | // TODO: Currently, we might loose precision here: we always mark a return 50 | // value as tainted even if it's just a pointer, pointing to tainted data. 51 | 52 | // Check for exact name match for functions without builtin substitutes. 53 | TaintPropagationRule Rule = llvm::StringSwitch(Name) 54 | .Case("convert_to_string", TaintPropagationRule(0, 0, false, true)) 55 | .Case("convert_to_array", TaintPropagationRule(0, 0, false, true)) 56 | .Case("convert_to_long", TaintPropagationRule(0, 0, false, true)) 57 | .Default(TaintPropagationRule()); 58 | 59 | if (!Rule.isNull()) 60 | return Rule; 61 | 62 | return TaintPropagationRule(); 63 | } 64 | 65 | void PHPTaintChecker::checkPreStmt(const CallExpr *CE, 66 | CheckerContext &C) const { 67 | DEBUG_PRINT("In PreStmt"); 68 | // Check for errors first. 69 | if (checkPre(CE, C)) 70 | return; 71 | 72 | // Add taint second. 73 | addSourcesPre(CE, C); 74 | } 75 | 76 | void PHPTaintChecker::checkPostStmt(const CallExpr *CE, 77 | CheckerContext &C) const { 78 | if (propagateFromPre(CE, C)) 79 | return; 80 | addSourcesPost(CE, C); 81 | } 82 | 83 | void PHPTaintChecker::checkLocation(SVal Loc, bool isLoad, const Stmt *S, 84 | CheckerContext &C) const { 85 | ProgramStateRef State = C.getState(); 86 | 87 | /// Bail if we are not loading/storing a tainted value 88 | if (!State->isTainted(Loc)) 89 | return; 90 | 91 | /// Taint is flowing either into a sanitizer or a sink macro 92 | /// First, check for former, then latter 93 | StringRef SanName; 94 | SourceLocation MacroLoc = cast(S)->getExprLoc(); 95 | 96 | if (MacroLoc.isMacroID()) 97 | SanName = C.getMacroNameOrSpelling(MacroLoc); 98 | else 99 | SanName = getCallNameFromArgExpr(S, C); 100 | 101 | if (SanName.empty()) 102 | return; 103 | 104 | SanHandler evalSanitized = llvm::StringSwitch(SanName) 105 | .Case("Z_TYPE", &PHPTaintChecker::postSanTaint) 106 | .Case("convert_to_string", &PHPTaintChecker::postSanTaint) 107 | .Case("convert_to_long", &PHPTaintChecker::postSanTaint) 108 | .Case("convert_to_array", &PHPTaintChecker::postSanTaint) 109 | .Default(nullptr); 110 | 111 | if (evalSanitized) { 112 | DEBUG_PRINT("In san"); 113 | assert(isa(S) && "A non-expr statement seen in sanitizer macro"); 114 | State = (this->*evalSanitized)(Loc, C); 115 | if (State != C.getState()) 116 | C.addTransition(State); 117 | return; 118 | } 119 | 120 | /// Check if we are in a sink 121 | bool isSink = llvm::StringSwitch(SanName) 122 | .Case("Z_STRVAL", true) 123 | .Case("Z_ARRVAL", true) 124 | .Default(false); 125 | 126 | if (isSink) { 127 | DEBUG_PRINT("In sink"); 128 | assert(isa(S) && "A non-expr statement seen in sink macro"); 129 | generateReport(cast(S), MsgZendTaint, C); 130 | } 131 | } 132 | 133 | ProgramStateRef PHPTaintChecker::postSanTaint(SVal sval, CheckerContext &C) const { 134 | ProgramStateRef State = C.getState(); 135 | 136 | SymbolRef Sym = sval.getAsSymbol(); 137 | if (!Sym) 138 | return State; 139 | 140 | DEBUG_PRINT("Removing taint"); 141 | 142 | State = State->removeTaint(Sym); 143 | assert(State && "State corruption post taint removal"); 144 | return State; 145 | } 146 | 147 | void PHPTaintChecker::addSourcesPre(const CallExpr *CE, 148 | CheckerContext &C) const { 149 | ProgramStateRef State = nullptr; 150 | 151 | StringRef Name = getCallName(CE, C); 152 | if (Name.empty()) 153 | return; 154 | 155 | // First, try generating a propagation rule for this function. 156 | TaintPropagationRule Rule = 157 | TaintPropagationRule::getTaintPropagationRule(Name, C); 158 | if (!Rule.isNull()) { 159 | State = Rule.process(CE, C); 160 | if (!State) 161 | return; 162 | C.addTransition(State); 163 | return; 164 | } 165 | 166 | DEBUG_PRINT("Generating taint on vulnerable source APIs"); 167 | 168 | // Otherwise, check if we have custom pre-processing implemented. 169 | FnCheck evalFunction = llvm::StringSwitch(Name) 170 | .Case("zend_hash_find", &PHPTaintChecker::prePHPTaintSources) 171 | .Case("zend_hash_quick_find", &PHPTaintChecker::prePHPTaintSources) 172 | .Case("zend_hash_index_find", &PHPTaintChecker::prePHPTaintSources) 173 | .Case("_ldap_hash_fetch", &PHPTaintChecker::prePHPTaintSources) 174 | .Case("php_stream_context_get_option", &PHPTaintChecker::prePHPTaintSources) 175 | .Default(nullptr); 176 | // Check and evaluate the call. 177 | if (evalFunction) 178 | State = (this->*evalFunction)(CE, C); 179 | if (!State) 180 | return; 181 | C.addTransition(State); 182 | } 183 | 184 | bool PHPTaintChecker::propagateFromPre(const CallExpr *CE, 185 | CheckerContext &C) const { 186 | ProgramStateRef State = C.getState(); 187 | StringRef Name = getCallName(CE, C); 188 | 189 | // Depending on what was tainted at pre-visit, we determined a set of 190 | // arguments which should be tainted after the function returns. These are 191 | // stored in the state as TaintArgsOnPostVisit set. 192 | TaintArgsOnPostVisitTy TaintArgs = State->get(); 193 | if (TaintArgs.isEmpty()) 194 | return false; 195 | 196 | for (llvm::ImmutableSet::iterator 197 | I = TaintArgs.begin(), E = TaintArgs.end(); I != E; ++I) { 198 | unsigned ArgNum = *I; 199 | 200 | // Special handling for the tainted return value. 201 | if (ArgNum == ReturnValueIndex) { 202 | DEBUG_PRINT("Adding taint on return value"); 203 | State = State->addTaint(CE, C.getLocationContext()); 204 | continue; 205 | } 206 | 207 | // The arguments are pointer arguments. The data they are pointing at is 208 | // tainted after the call. 209 | if (CE->getNumArgs() < (ArgNum + 1)) 210 | return false; 211 | const Expr* Arg = CE->getArg(ArgNum); 212 | DEBUG_PRINT("Getting pointed to symbol"); 213 | SymbolRef Sym = getPointedToSymbol(C, Arg); 214 | 215 | PHPTaintChecker::TaintPropagationRule Rule = getRule(Name, C); 216 | DEBUG_PRINT(Name); 217 | if (Sym) { 218 | std::string info; 219 | (Rule.isSanRule() ? (info = "Removing taint in post call") : 220 | (info = "Adding taint in post call")); 221 | DEBUG_PRINT(info); 222 | if (Rule.isSanRule()) 223 | State = State->removeTaint(Sym); 224 | else 225 | State = State->addTaint(Sym); 226 | } 227 | else 228 | DEBUG_PRINT("Sym null"); 229 | } 230 | 231 | // Clear up the taint info from the state. 232 | State = State->remove(); 233 | 234 | if (State != C.getState()) { 235 | C.addTransition(State); 236 | return true; 237 | } 238 | return false; 239 | } 240 | 241 | void PHPTaintChecker::addSourcesPost(const CallExpr *CE, 242 | CheckerContext &C) const { 243 | // Define the attack surface. 244 | // Set the evaluation function by switching on the callee name. 245 | const FunctionDecl *FDecl = C.getCalleeDecl(CE); 246 | if (!FDecl || FDecl->getKind() != Decl::Function) 247 | return; 248 | 249 | StringRef Name = C.getCalleeName(FDecl); 250 | if (Name.empty()) 251 | return; 252 | FnCheck evalFunction = llvm::StringSwitch(Name) 253 | .Case("zend_read_property", &PHPTaintChecker::postRetTaint) 254 | .Case("zend_read_static_property", &PHPTaintChecker::postRetTaint) 255 | .Default(nullptr); 256 | 257 | // If the callee isn't defined, it is not of security concern. 258 | // Check and evaluate the call. 259 | ProgramStateRef State = nullptr; 260 | if (evalFunction) 261 | State = (this->*evalFunction)(CE, C); 262 | if (!State) 263 | return; 264 | 265 | C.addTransition(State); 266 | } 267 | 268 | /// Check taint before processing function call 269 | bool PHPTaintChecker::checkPre(const CallExpr *CE, CheckerContext &C) const{ 270 | 271 | DEBUG_PRINT("Checking taint pre call"); 272 | StringRef Name = getCallName(CE, C); 273 | if (Name.empty()) 274 | return false; 275 | 276 | if (checkPHPSinks(CE, Name, C)) 277 | return true; 278 | 279 | return false; 280 | } 281 | 282 | SymbolRef PHPTaintChecker::getPointedToSymbol(CheckerContext &C, 283 | const Expr* Arg) { 284 | 285 | DEBUG_PRINT("Unknown or undefined address"); 286 | ProgramStateRef State = C.getState(); 287 | SVal AddrVal = State->getSVal(Arg->IgnoreParens(), C.getLocationContext()); 288 | if (AddrVal.isUnknownOrUndef()) 289 | return nullptr; 290 | 291 | DEBUG_PRINT("Address not an lvalue"); 292 | Optional AddrLoc = AddrVal.getAs(); 293 | if (!AddrLoc) 294 | return nullptr; 295 | 296 | DEBUG_PRINT("Obtaining symbolref of address"); 297 | const PointerType *ArgTy = 298 | dyn_cast(Arg->getType().getCanonicalType().getTypePtr()); 299 | SVal Val = State->getSVal(*AddrLoc, 300 | ArgTy ? ArgTy->getPointeeType(): QualType()); 301 | return Val.getAsSymbol(); 302 | } 303 | 304 | ProgramStateRef 305 | PHPTaintChecker::TaintPropagationRule::process(const CallExpr *CE, 306 | CheckerContext &C) const { 307 | ProgramStateRef State = C.getState(); 308 | 309 | // Check for taint in arguments. 310 | bool IsTainted = false; 311 | for (ArgVector::const_iterator I = SrcArgs.begin(), 312 | E = SrcArgs.end(); I != E; ++I) { 313 | unsigned ArgNum = *I; 314 | 315 | if (ArgNum == InvalidArgIndex) { 316 | // Check if any of the arguments is tainted, but skip the 317 | // destination arguments. 318 | for (unsigned int i = 0; i < CE->getNumArgs(); ++i) { 319 | if (isDestinationArgument(i)) 320 | continue; 321 | if ((IsTainted = isTaintedOrPointsToTainted(CE->getArg(i), State, C))) 322 | break; 323 | } 324 | break; 325 | } 326 | 327 | if (CE->getNumArgs() < (ArgNum + 1)) 328 | return State; 329 | if ((IsTainted = isTaintedOrPointsToTainted(CE->getArg(ArgNum), State, C))) 330 | break; 331 | } 332 | if (!IsTainted) 333 | return State; 334 | 335 | // Mark the arguments which should be tainted after the function returns. 336 | for (ArgVector::const_iterator I = DstArgs.begin(), 337 | E = DstArgs.end(); I != E; ++I) { 338 | unsigned ArgNum = *I; 339 | 340 | // Should we mark all arguments as tainted? 341 | if (ArgNum == InvalidArgIndex) { 342 | // For all pointer and references that were passed in: 343 | // If they are not pointing to const data, mark data as tainted. 344 | // TODO: So far we are just going one level down; ideally we'd need to 345 | // recurse here. 346 | for (unsigned int i = 0; i < CE->getNumArgs(); ++i) { 347 | const Expr *Arg = CE->getArg(i); 348 | // Process pointer argument. 349 | const Type *ArgTy = Arg->getType().getTypePtr(); 350 | QualType PType = ArgTy->getPointeeType(); 351 | if ((!PType.isNull() && !PType.isConstQualified()) 352 | || (ArgTy->isReferenceType() && !Arg->getType().isConstQualified())) 353 | State = State->add(i); 354 | } 355 | continue; 356 | } 357 | 358 | // Should mark the return value? 359 | if (ArgNum == ReturnValueIndex) { 360 | State = State->add(ReturnValueIndex); 361 | continue; 362 | } 363 | 364 | // Mark the given argument. 365 | assert(ArgNum < CE->getNumArgs()); 366 | State = State->add(ArgNum); 367 | } 368 | 369 | return State; 370 | } 371 | 372 | ProgramStateRef PHPTaintChecker::prePHPTaintSources(const CallExpr *CE, 373 | CheckerContext &C) const { 374 | ProgramStateRef State = C.getState(); 375 | 376 | StringRef Name = getCallName(CE, C); 377 | if (Name.empty()) 378 | return State; 379 | 380 | unsigned taintArgNum = llvm::StringSwitch(Name) 381 | .Case("zend_hash_find", 3) 382 | .Case("zend_hash_quick_find", 4) 383 | .Case("zend_hash_index_find", 2) 384 | .Case("_ldap_hash_fetch", 2) 385 | .Case("php_stream_context_get_option", 3) 386 | .Default(InvalidArgIndex); 387 | 388 | if (taintArgNum == InvalidArgIndex) 389 | return State; 390 | 391 | /// Sanity check 392 | assert((taintArgNum < CE->getNumArgs() || taintArgNum == ReturnValueIndex) && 393 | "Taint generation rule invalid"); 394 | 395 | DEBUG_PRINT("Add taint arg info to checker state"); 396 | 397 | return State->add(taintArgNum); 398 | } 399 | 400 | ProgramStateRef PHPTaintChecker::postRetTaint(const CallExpr *CE, 401 | CheckerContext &C) const { 402 | DEBUG_PRINT("Adding taint on return value post call"); 403 | return C.getState()->addTaint(CE, C.getLocationContext()); 404 | } 405 | 406 | bool PHPTaintChecker::generateReportIfTainted(const Expr *E, 407 | const char Msg[], 408 | CheckerContext &C) const { 409 | assert(E); 410 | 411 | // Check for taint. 412 | ProgramStateRef State = C.getState(); 413 | if (!State->isTainted(getPointedToSymbol(C, E)) && 414 | !State->isTainted(E, C.getLocationContext())) 415 | return false; 416 | 417 | // Generate diagnostic. 418 | if (ExplodedNode *N = C.addTransition()) { 419 | initBugType(); 420 | BugReport *report = new BugReport(*BT, Msg, N); 421 | report->addRange(E->getSourceRange()); 422 | 423 | { 424 | Diag.encodeBugInfo("", C); 425 | for (auto &i : Diag.getBugInfoDiag()) 426 | report->addExtraText(i); 427 | } 428 | 429 | C.emitReport(report); 430 | return true; 431 | } 432 | return false; 433 | } 434 | 435 | void PHPTaintChecker::generateReport(const Expr *E, const char Msg[], 436 | CheckerContext &C) const { 437 | assert(E); 438 | 439 | // Generate diagnostic. 440 | if (ExplodedNode *N = C.addTransition()) { 441 | initBugType(); 442 | BugReport *report = new BugReport(*BT, Msg, N); 443 | report->addRange(E->getSourceRange()); 444 | 445 | { 446 | Diag.encodeBugInfo("", C); 447 | for (auto &i : Diag.getBugInfoDiag()) 448 | report->addExtraText(i); 449 | } 450 | 451 | C.emitReport(report); 452 | } 453 | } 454 | 455 | bool PHPTaintChecker::checkPHPSinks(const CallExpr *CE, StringRef Name, 456 | CheckerContext &C) const { 457 | // TODO: Populate this with PHP sink functions if any 458 | 459 | // unsigned ArgNum = llvm::StringSwitch(Name) 460 | // .Case("ZF_STRVAL", 0) 461 | // .Case("ZF_STRVAL_P", 0) 462 | // .Case("ZF_STRVAL_PP", 0) 463 | // .Case("ZF_ARRVAL", 0) 464 | // .Case("ZF_ARRVAL_P", 0) 465 | // .Case("ZF_ARRVAL_PP", 0) 466 | // .Default(UINT_MAX); 467 | // 468 | // if (ArgNum == UINT_MAX || CE->getNumArgs() < (ArgNum + 1)) 469 | // return false; 470 | // 471 | // if (generateReportIfTainted(CE->getArg(ArgNum), 472 | // MsgZendTaint, C)) 473 | // return true; 474 | 475 | return false; 476 | } 477 | -------------------------------------------------------------------------------- /src/UseDefChecker.cpp: -------------------------------------------------------------------------------- 1 | #include "UseDefChecker.h" 2 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 3 | #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 4 | #include "clang/StaticAnalyzer/Core/PathSensitive/FunctionSummary.h" 5 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 6 | #include "clang/AST/Decl.h" 7 | #include "clang/AST/DeclTemplate.h" 8 | #include "clang/AST/ExprCXX.h" 9 | #include "clang/AST/Mangle.h" 10 | #include "llvm/Support/raw_ostream.h" 11 | 12 | using namespace clang; 13 | using namespace clang::ento; 14 | using Melange::UseDefChecker; 15 | 16 | REGISTER_SET_WITH_PROGRAMSTATE(TaintDeclsInContext, const Decl*) 17 | 18 | void UseDefChecker::taintCtorInits(const CXXConstructorDecl *CCD, 19 | CheckerContext &C) const { 20 | 21 | for(auto *I : CCD->inits()){ 22 | CXXCtorInitializer *CtorInitializer = I; 23 | /* FIXME: Choose the right variant(s) of 24 | * is*MemberInitializer call 25 | */ 26 | if(!CtorInitializer->isMemberInitializer()) 27 | continue; 28 | 29 | /* Turns out isMemberInitializer() also returns 30 | * member fields initialized in class decl 31 | */ 32 | 33 | // Update state map 34 | const FieldDecl *FD = CtorInitializer->getMember(); 35 | 36 | const NamedDecl *ND = dyn_cast(FD); 37 | assert(ND && "UDC: ND can't be null here"); 38 | 39 | addNDToTaintSet(ND, C); 40 | 41 | // Add init expressions to taint set if necessary 42 | const Expr *E = CtorInitializer->getInit()->IgnoreImpCasts(); 43 | if(isCXXFieldDecl(E)){ 44 | const MemberExpr *MEI = dyn_cast(E); 45 | const NamedDecl *NDI = dyn_cast(MEI->getMemberDecl()); 46 | addNDToTaintSet(NDI, C); 47 | } 48 | } 49 | } 50 | 51 | /* We visit endfunction to make sure we update CtorVisited if necessary. 52 | * Note that even an empty ctor body, like so: 53 | * foo() {} 54 | * is going to end up here and update CtorVisited to true. 55 | */ 56 | void UseDefChecker::checkEndFunction(CheckerContext &C) const { 57 | 58 | const AnalysisDeclContext *ADC = C.getLocationContext()->getAnalysisDeclContext(); 59 | const CXXMethodDecl *CMD = dyn_cast(ADC->getDecl()); 60 | 61 | if (!CMD || CMD->isStatic()) 62 | return; 63 | 64 | if (!isa(CMD)) 65 | return; 66 | 67 | /* Absent AST visitor, we postpone tainting of Ctor inits 68 | * to the fag end of Ctor analysis. This will increase 69 | * false negatives in theory but not likely in practice because 70 | * use of uninitialized class members during object creation is 71 | * rare and pretty fucked up to be honest. 72 | */ 73 | taintCtorInits(dyn_cast(CMD), C); 74 | 75 | const Decl *TLD = C.getTopLevelDecl(); 76 | 77 | if (isa(TLD)) { 78 | const CXXMethodDecl *TLDCMD = cast(TLD); 79 | const CXXRecordDecl *CRD = TLDCMD->getParent(); 80 | assert(CRD && "UDC: CXXRecordDecl can't be null"); 81 | 82 | if (ctorsVisited.find(CRD) == ctorsVisited.end()) { 83 | taintCtorInits(dyn_cast(TLD), C); 84 | ctorsVisited.insert(CRD); 85 | } 86 | } 87 | 88 | } 89 | 90 | void UseDefChecker::checkEndOfTranslationUnit(const TranslationUnitDecl *TU, 91 | AnalysisManager &Mgr, 92 | BugReporter &BR) const { 93 | 94 | const FunctionSummariesTy::MapTy &Map = Mgr.FunctionSummary->getMap(); 95 | CtorsDeclSetTy TaintedClassMembers; 96 | 97 | /// 0. Find Ctor taints 98 | for(FSMapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I){ 99 | if(!isa(I->first)) 100 | continue; 101 | 102 | const TLDTMTy &CtorTaintMap = I->second.getTaintMap(); 103 | for(TLDTMTy::const_iterator II = CtorTaintMap.begin(), EE = CtorTaintMap.end(); 104 | II != EE; ++II) 105 | TaintedClassMembers.insert(II->first); 106 | } // end of ctor taint for loop 107 | 108 | /// 1. Iterate through FS Map 109 | for(FSMapTy::const_iterator I = Map.begin(), E = Map.end(); I != E ; ++I){ 110 | 111 | if(isa(I->first)) 112 | continue; 113 | 114 | /// 2. Get taint map of FS 115 | const TLDTMTy &TaintMap = I->second.getTaintMap(); 116 | 117 | /// 3. Iterate through Taint map 118 | for(TLDTMTy::const_iterator II = TaintMap.begin(), EE = TaintMap.end(); 119 | II != EE; ++II) { 120 | 121 | /// 4. For each tainted decl, check if it is tainted in Ctor 122 | if(TaintedClassMembers.find(II->first) != TaintedClassMembers.end()) 123 | continue; 124 | 125 | const Decl *BuggyDecl = cast(II->first); 126 | 127 | const FieldDecl *FD = cast(BuggyDecl); 128 | assert(FD && "UDC: BuggyDecl is not a FieldDecl"); 129 | const RecordDecl *RD = FD->getParent(); 130 | assert(RD && "UDC: BuggyDecl has no RecordDecl"); 131 | const CXXRecordDecl *CRD = cast(RD); 132 | assert(CRD && "UDC: BuggyDecl has no CXXRecordDecl"); 133 | 134 | // There is a user declared Ctor that we haven't visited. 135 | // So don't flag warning. 136 | if(CRD->hasUserDeclaredConstructor() && (ctorsVisited.find(CRD) == ctorsVisited.end())) 137 | continue; 138 | 139 | DiagnosticsInfoTy::iterator I = DiagnosticsInfo.find(BuggyDecl); 140 | SourceLocation SL = std::get<1>(I->second); 141 | SourceManager &SM = Mgr.getSourceManager(); 142 | 143 | // FIXME: Warnings in header files are potential false positives 144 | // Genesis is Crbug 411177. 145 | if(!SM.isWrittenInMainFile(SL)) 146 | continue; 147 | 148 | /// Report bug! 149 | reportBug(Mgr, BR, BuggyDecl); 150 | } // end of taint map for loop 151 | } // end of function summary for loop 152 | } 153 | 154 | void UseDefChecker::branchStmtChecker(const Stmt *Condition, 155 | CheckerContext &C) const { 156 | 157 | const Expr *E = dyn_cast(Condition); 158 | switch (Condition->getStmtClass()) { 159 | default: 160 | break; 161 | case Stmt::ImplicitCastExprClass: { 162 | branchStmtChecker(E->IgnoreImpCasts(), C); 163 | break; 164 | } 165 | case Stmt::MemberExprClass: { 166 | checkUseIfMemberExpr(E, C); 167 | break; 168 | } 169 | case Stmt::CompoundStmtClass: { 170 | const CompoundStmt *CompStmt = cast(Condition); 171 | CompoundStmt::const_body_iterator Iter = CompStmt->body_begin(); 172 | while (Iter != CompStmt->body_end()) { 173 | branchStmtChecker(*Iter, C); 174 | ++Iter; 175 | } 176 | break; 177 | } 178 | case Stmt::CompoundAssignOperatorClass: 179 | case Stmt::BinaryOperatorClass: { 180 | const BinaryOperator *BO = cast(Condition); 181 | checkBinaryOp(BO, C); 182 | break; 183 | } 184 | case Stmt::UnaryOperatorClass: { 185 | const UnaryOperator *UO = cast(Condition); 186 | checkUnaryOp(UO, C); 187 | break; 188 | } 189 | } 190 | return; 191 | } 192 | 193 | void UseDefChecker::checkBranchCondition(const Stmt *Condition, 194 | CheckerContext &C) const { 195 | 196 | if (isa(C.getTopLevelDecl())) 197 | return; 198 | 199 | branchStmtChecker(Condition, C); 200 | } 201 | 202 | void UseDefChecker::checkPreStmt(const BinaryOperator *BO, 203 | CheckerContext &C) const { 204 | 205 | if (BO->getOpcode() != BO_Assign) 206 | return; 207 | 208 | const Expr *RHS = BO->getRHS()->IgnoreImpCasts(); 209 | const Expr *LHS = BO->getLHS()->IgnoreImpCasts(); 210 | 211 | if(!isCXXFieldDecl(RHS) && !isCXXFieldDecl(LHS)) 212 | return; 213 | 214 | trackMembersInAssign(BO, C); 215 | } 216 | 217 | void UseDefChecker::checkPreCall(const CallEvent &Call, 218 | CheckerContext &C) const { 219 | 220 | if (isa(C.getTopLevelDecl())) 221 | return; 222 | 223 | const Decl *D = Call.getDecl(); 224 | const FunctionDecl *FD = dyn_cast_or_null(D); 225 | 226 | for (unsigned i = 0, e = Call.getNumArgs(); i != e; ++i) { 227 | 228 | if (!isCXXFieldDecl(Call.getArgExpr(i)->IgnoreImpCasts())) 229 | continue; 230 | 231 | const ParmVarDecl *ParamDecl = nullptr; 232 | const MemberExpr *CAE = dyn_cast(Call.getArgExpr(i)->IgnoreImpCasts()); 233 | 234 | if (FD && i < FD->getNumParams()) 235 | ParamDecl = FD->getParamDecl(i); 236 | 237 | // Skip args passed by ref/ptr 238 | if (ParamDecl->getType()->isReferenceType() || 239 | ParamDecl->getType()->isPointerType()) 240 | continue; 241 | 242 | if (ParamDecl && CAE) { 243 | const FieldDecl *FiD = dyn_cast(CAE->getMemberDecl()); 244 | 245 | if (FiD && isa(FiD->getParent())) { 246 | const NamedDecl *ND = dyn_cast(CAE->getMemberDecl()); 247 | if (ND && !isTaintedInContext(ND, C)) 248 | encodeBugInfo(CAE, C); 249 | } 250 | } 251 | } 252 | 253 | return; 254 | } 255 | 256 | void UseDefChecker::encodeBugInfo(const MemberExpr *ME, 257 | CheckerContext &C) const { 258 | /* Get the FQ field name */ 259 | const NamedDecl *ND = dyn_cast(ME->getMemberDecl()); 260 | const std::string FieldName = ND->getQualifiedNameAsString(); 261 | 262 | /* This is used by reportBug to sneak in name of the undefined field 263 | * Note: We don't mangle Fieldname because it's not a VarDecl and non 264 | * VarDecls cannot be mangled. 265 | */ 266 | 267 | /* Clear DS before populating to avoid rewrites in case of multiple 268 | * undefs being detected. 269 | */ 270 | EncodedBugInfo.clear(); 271 | 272 | EncodedBugInfo.push_back(FieldName); 273 | // Call stack is written to EncodedBugInfo 274 | dumpCallsOnStack(C); 275 | 276 | const Decl *FD = C.getTopLevelDecl(); 277 | 278 | if (!isa(FD)){ 279 | storeDiagnostics(cast(ND), ME->getMemberLoc()); 280 | /// This taint means we found a potentially undefined class member 281 | C.addCSTaint(cast(ND)); 282 | } 283 | 284 | return; 285 | } 286 | 287 | void UseDefChecker::storeDiagnostics(const Decl *D, SourceLocation SL) const { 288 | DiagnosticsInfoTy::iterator I = DiagnosticsInfo.find(D); 289 | if (I != DiagnosticsInfo.end()) 290 | return; 291 | 292 | typedef std::pair KVPair; 293 | I = DiagnosticsInfo.insert(KVPair(D, DiagPairTy(EncodedBugInfo, SL))).first; 294 | assert(I != DiagnosticsInfo.end()); 295 | return; 296 | } 297 | 298 | bool UseDefChecker::isCXXFieldDecl(const Expr *E) { 299 | const MemberExpr *ME = dyn_cast(E->IgnoreImpCasts()); 300 | 301 | if (!ME) 302 | return false; 303 | 304 | const FieldDecl *FD = dyn_cast(ME->getMemberDecl()); 305 | 306 | if (!FD) 307 | return false; 308 | 309 | if (!isa(FD->getParent())) 310 | return false; 311 | 312 | const CXXRecordDecl *CRD = dyn_cast(FD->getParent()); 313 | 314 | // We don't want to be dealing with struct/union fields 315 | if (CRD->isCLike()) 316 | return false; 317 | 318 | return true; 319 | } 320 | 321 | void UseDefChecker::reportBug(AnalysisManager &Mgr, BugReporter &BR, 322 | const Decl *D) const { 323 | 324 | const char *name = "Undefined CXX object checker"; 325 | const char *desc = "Flags potential uses of undefined CXX object fields"; 326 | 327 | StringRef Message = "Potentially uninitialized object field"; 328 | 329 | DiagnosticsInfoTy::iterator I = DiagnosticsInfo.find(D); 330 | 331 | ETLTy EBI = std::get<0>(I->second); 332 | SourceLocation SL = std::get<1>(I->second); 333 | 334 | PathDiagnosticLocation l(SL, Mgr.getSourceManager()); 335 | 336 | if (!BT) 337 | BT.reset(new BuiltinBug(this, name, desc)); 338 | 339 | BugReport *R = new BugReport(*BT, Message, l); 340 | 341 | for (EBIIteratorTy i = EBI.begin(), 342 | e = EBI.end(); i != e; ++i) { 343 | R->addExtraText(*i); 344 | } 345 | 346 | BR.emitReport(R); 347 | } 348 | 349 | void UseDefChecker::checkUseIfMemberExpr(const Expr *E, 350 | CheckerContext &C) const { 351 | bool hasLvalToRvalCast = false; 352 | while (isa(E)) { 353 | const ImplicitCastExpr *ICE = dyn_cast(E); 354 | if (!hasLvalToRvalCast && (ICE->getCastKind() == CK_LValueToRValue)) 355 | hasLvalToRvalCast = true; 356 | 357 | E = ICE->getSubExpr(); 358 | } 359 | 360 | if (!isCXXFieldDecl(E) || !hasLvalToRvalCast) 361 | return; 362 | 363 | const MemberExpr *ME = dyn_cast(E); 364 | assert(ME && "UDC: ME can't be null here"); 365 | 366 | const NamedDecl *ND = dyn_cast(ME->getMemberDecl()); 367 | assert(ND && "UDC: ND can't be null here"); 368 | 369 | if (!isTaintedInContext(ND, C)) 370 | encodeBugInfo(ME, C); 371 | } 372 | 373 | void UseDefChecker::checkBinaryOp(const BinaryOperator *BO, 374 | CheckerContext &C) const { 375 | 376 | /* In taintclient-checkerv1.7, we permitted warnings in the Ctor 377 | * analysis context with the added logic that we only flag 378 | * undefined use if we know for sure that all initializations 379 | * in Ctor context have been tainted. 380 | * It turns out this decision is prone to Toctou flaw. Suppose that 381 | * at the time of check, Ctor is not visited but it gets visited 382 | * during the course of emitting bug report. 383 | * To counter this, we disable checking for undefined use 384 | * in Ctor analysis decl contexts altogether. 385 | */ 386 | if (isa(C.getTopLevelDecl())) 387 | return; 388 | 389 | const Expr *RHS = BO->getRHS()->IgnoreImpCasts(); 390 | const Expr *LHS = BO->getLHS()->IgnoreImpCasts(); 391 | 392 | if (const UnaryOperator *UOR = dyn_cast(RHS)) 393 | checkBranchCondition(UOR, C); 394 | 395 | if (const UnaryOperator *UOL = dyn_cast(LHS)) 396 | checkBranchCondition(UOL, C); 397 | 398 | if(!isCXXFieldDecl(RHS) && !isCXXFieldDecl(LHS)) 399 | return; 400 | 401 | switch (BO->getOpcode()) { 402 | default: 403 | break; 404 | 405 | case BO_Mul: 406 | case BO_Div: 407 | case BO_Rem: 408 | case BO_Add: 409 | case BO_Sub: 410 | case BO_Shl: 411 | case BO_Shr: 412 | case BO_LT: 413 | case BO_GT: 414 | case BO_LE: 415 | case BO_GE: 416 | case BO_EQ: 417 | case BO_NE: 418 | case BO_And: 419 | case BO_Xor: 420 | case BO_Or: 421 | case BO_LAnd: 422 | case BO_LOr: { 423 | if (isCXXFieldDecl(LHS)) 424 | checkUseIfMemberExpr(BO->getLHS(), C); 425 | 426 | if (isCXXFieldDecl(RHS)) 427 | checkUseIfMemberExpr(BO->getRHS(), C); 428 | 429 | break; 430 | } 431 | } 432 | } 433 | 434 | void UseDefChecker::checkUnaryOp(const UnaryOperator *UO, 435 | CheckerContext &C) const { 436 | 437 | if (isa(C.getTopLevelDecl())) 438 | return; 439 | 440 | /* Ignore implicit casts */ 441 | Expr *E = UO->getSubExpr()->IgnoreImpCasts(); 442 | 443 | if (const BinaryOperator *BO = dyn_cast(E)) { 444 | checkBranchCondition(BO, C); 445 | return; 446 | } 447 | 448 | if (!isCXXFieldDecl(E)) 449 | return; 450 | 451 | switch (UO->getOpcode()) { 452 | case UO_PostInc: 453 | case UO_PostDec: 454 | case UO_PreInc: 455 | case UO_PreDec: 456 | case UO_Minus: // Additive inverse 457 | case UO_Not: 458 | case UO_Deref: 459 | case UO_LNot: { 460 | checkUseIfMemberExpr(UO->getSubExpr(), C); 461 | break; 462 | } 463 | case UO_Plus: 464 | case UO_AddrOf: 465 | case UO_Real: 466 | case UO_Imag: 467 | case UO_Extension: 468 | default: 469 | break; 470 | } 471 | } 472 | 473 | /* Utility function to track uses and defs in assignment 474 | * statements. Returns false if RHS is not in defs set. When this 475 | * happens, onus is on caller to report bug. 476 | */ 477 | void UseDefChecker::trackMembersInAssign(const BinaryOperator *BO, 478 | CheckerContext &C) const { 479 | 480 | /* Check if LHS/RHS is a member expression */ 481 | const Expr *lhs = BO->getLHS()->IgnoreImpCasts(); 482 | const Expr *rhs = BO->getRHS()->IgnoreImpCasts(); 483 | 484 | const MemberExpr *MeLHS = dyn_cast(lhs); 485 | const MemberExpr *MeRHS = dyn_cast(rhs); 486 | 487 | /* Assert because wrapper takes care of ensuring we get here only if 488 | * one of Binop expressions is a member expression. 489 | */ 490 | assert((MeLHS || MeRHS) && "Neither LHS nor RHS is a member expression"); 491 | 492 | /* If we are here, we can be sure that the member field 493 | * being defined/used belongs to this* object 494 | */ 495 | 496 | /* Check use first because this->rhs may be uninitialized 497 | * and we would want to report the bug and exit before 498 | * anything else. Exception being this->rhs in ctor being undefined. 499 | * See comment in checkPreStmt. 500 | */ 501 | if(MeRHS && isCXXFieldDecl(rhs)){ 502 | const NamedDecl *NDR = dyn_cast(MeRHS->getMemberDecl()); 503 | 504 | if(!isTaintedInContext(NDR, C) && !isa(C.getTopLevelDecl())) { 505 | const Expr *TE = BO->getRHS(); 506 | 507 | while (isa(TE)) { 508 | const ImplicitCastExpr *ICE = dyn_cast(TE); 509 | if (ICE->getCastKind() == CK_LValueToRValue) { 510 | encodeBugInfo(MeRHS, C); 511 | return; 512 | } 513 | TE = ICE->getSubExpr(); 514 | } 515 | } 516 | } 517 | 518 | /* Add lhs to set if it is a this* member. We silently add LHS exprs 519 | * while exploring Ctor path even if we find that RHS is undefined. The 520 | * expectation is that it is abnormal to have uninitialized RHS in the 521 | * process of object creation. 522 | */ 523 | if(MeLHS && isCXXFieldDecl(lhs)){ 524 | const NamedDecl *NDL = dyn_cast(MeLHS->getMemberDecl()); 525 | addNDToTaintSet(NDL, C); 526 | } 527 | } 528 | 529 | /* Utility function for inserting fields into a given set */ 530 | void UseDefChecker::addNDToTaintSet(const NamedDecl *ND, 531 | CheckerContext &C) const { 532 | ProgramStateRef State = C.getState(); 533 | 534 | const Decl *TLD = C.getTopLevelDecl(); 535 | 536 | if (isa(TLD)) { 537 | /* This taints definitions in top level ctor function summary */ 538 | C.addCSTaint(cast(ND)); 539 | } 540 | 541 | /* This taints definitions in analysis decl context */ 542 | State = State->add(cast(ND)); 543 | if(State != C.getState()) 544 | C.addTransition(State); 545 | } 546 | 547 | bool UseDefChecker::isTaintedInContext(const NamedDecl *ND, 548 | CheckerContext &C) const { 549 | ProgramStateRef State = C.getState(); 550 | const Decl *D = cast(ND); 551 | return State->contains(D); 552 | } 553 | 554 | /* This utility function must be called from reportBug before 555 | * populating the ExtraData portion of the bug report. 556 | * dumpCallsOnStack pushes the call stack as a list of strings 557 | * to EncodedBugInfo. EncodedBugInfo is copied on to the bug 558 | * report's ExtraText field. 559 | * 560 | * Finally, the HTML Diagnostics client picks up ExtraText and 561 | * populates the HTML report with the call stack. 562 | */ 563 | 564 | void UseDefChecker::dumpCallsOnStack(CheckerContext &C) const { 565 | 566 | const LocationContext *LC = C.getLocationContext(); 567 | 568 | if(C.inTopFrame()){ 569 | EncodedBugInfo.push_back(getADCQualifiedNameAsStringRef(LC)); 570 | return; 571 | } 572 | 573 | for (const LocationContext *LCtx = C.getLocationContext(); 574 | LCtx; LCtx = LCtx->getParent()) { 575 | if(LCtx->getKind() == LocationContext::ContextKind::StackFrame) 576 | EncodedBugInfo.push_back(getADCQualifiedNameAsStringRef(LCtx)); 577 | /* It doesn't make sense to continue if parent is 578 | * not a stack frame. I imagine stack frames stacked 579 | * together and not interspersed between other frame types 580 | * like Scope or Block. 581 | */ 582 | else 583 | llvm_unreachable("dumpCallsOnStack says this is not a stack frame!"); 584 | } 585 | 586 | return; 587 | } 588 | 589 | std::string UseDefChecker::getADCQualifiedNameAsStringRef(const LocationContext *LC) { 590 | 591 | if(LC->getKind() != LocationContext::ContextKind::StackFrame) 592 | llvm_unreachable("getADC says we are not in a stack frame!"); 593 | 594 | const AnalysisDeclContext *ADC = LC->getAnalysisDeclContext(); 595 | assert(ADC && "getAnalysisDecl returned null while dumping" 596 | " calls on stack"); 597 | 598 | // This gives us the function declaration being visited 599 | const Decl *D = ADC->getDecl(); 600 | assert(D && "ADC getDecl returned null while dumping" 601 | " calls on stack"); 602 | 603 | const NamedDecl *ND = dyn_cast(D); 604 | assert(ND && "Named declaration null while dumping" 605 | " calls on stack"); 606 | 607 | return getMangledNameAsString(ND, ADC->getASTContext()); 608 | } 609 | 610 | std::string UseDefChecker::getMangledNameAsString(const NamedDecl *ND, 611 | ASTContext &ASTC) { 612 | // Create Mangle context 613 | MangleContext *MC = ASTC.createMangleContext(); 614 | 615 | // We need raw string stream so we can return std::string 616 | std::string MangledName; 617 | llvm::raw_string_ostream raw_stream(MangledName); 618 | 619 | if(!MC->shouldMangleDeclName(ND)) 620 | return ND->getQualifiedNameAsString(); 621 | 622 | /* Assertion deep within mangleName */ 623 | if(!isa(ND) && !isa(ND)){ 624 | MC->mangleName(ND, raw_stream); 625 | return raw_stream.str(); 626 | } 627 | 628 | return ND->getQualifiedNameAsString(); 629 | } 630 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------