xref: /llvm-project/clang/test/Analysis/invalid-ptr-checker.c (revision b98a594977f25e555822e5ceef457f69c73cce45)
1 // RUN: %clang_analyze_cc1                                                      \
2 // RUN:  -analyzer-checker=security.cert.env.InvalidPtr                         \
3 // RUN:  -analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=false \
4 // RUN:  -analyzer-output=text -verify -Wno-unused %s
5 //
6 // RUN: %clang_analyze_cc1                                                      \
7 // RUN:  -analyzer-checker=security.cert.env.InvalidPtr                         \
8 // RUN:  -analyzer-config                                                       \
9 // RUN: security.cert.env.InvalidPtr:InvalidatingGetEnv=true                    \
10 // RUN: -analyzer-output=text -verify=expected,pedantic -Wno-unused %s
11 
12 #include "Inputs/system-header-simulator.h"
13 
14 char *getenv(const char *name);
15 int setenv(const char *name, const char *value, int overwrite);
16 int strcmp(const char *, const char *);
17 
18 int custom_env_handler(const char **envp);
19 
getenv_after_getenv(void)20 void getenv_after_getenv(void) {
21   char *v1 = getenv("V1");
22   // pedantic-note@-1{{previous function call was here}}
23 
24   char *v2 = getenv("V2");
25   // pedantic-note@-1{{'getenv' call may invalidate the result of the previous 'getenv'}}
26 
27   strcmp(v1, v2);
28   // pedantic-warning@-1{{use of invalidated pointer 'v1' in a function call}}
29   // pedantic-note@-2{{use of invalidated pointer 'v1' in a function call}}
30 }
31 
setenv_after_getenv(void)32 void setenv_after_getenv(void) {
33   char *v1 = getenv("VAR1");
34 
35   setenv("VAR2", "...", 1);
36   // expected-note@-1{{'setenv' call may invalidate the environment returned by 'getenv'}}
37 
38   strcmp(v1, "");
39   // expected-warning@-1{{use of invalidated pointer 'v1' in a function call}}
40   // expected-note@-2{{use of invalidated pointer 'v1' in a function call}}
41 }
42 
main(int argc,const char * argv[],const char * envp[])43 int main(int argc, const char *argv[], const char *envp[]) {
44   setenv("VAR", "...", 0);
45   // expected-note@-1 2 {{'setenv' call may invalidate the environment parameter of 'main'}}
46 
47   *envp;
48   // expected-warning@-1 2 {{dereferencing an invalid pointer}}
49   // expected-note@-2 2 {{dereferencing an invalid pointer}}
50 }
51 
multiple_invalidation_no_duplicate_notes(void)52 void multiple_invalidation_no_duplicate_notes(void) {
53   char *v1 = getenv("VAR1");
54 
55   setenv("VAR2", "...", 1); // no note here
56 
57   setenv("VAR3", "...", 1);
58   // expected-note@-1{{'setenv' call may invalidate the environment returned by 'getenv'}}
59 
60   strcmp(v1, "");
61   // expected-warning@-1{{use of invalidated pointer 'v1' in a function call}}
62   // expected-note@-2{{use of invalidated pointer 'v1' in a function call}}
63 }
64