aboutsummaryrefslogtreecommitdiff
path: root/lib/Analysis/CallAndMessageChecker.cpp
blob: ebc3a4fd5605245dfe57d1973662cf0954694169 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//===--- CallAndMessageChecker.cpp ------------------------------*- C++ -*--==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This defines CallAndMessageChecker, a builtin checker that checks for various
// errors of call and objc message expressions.
//
//===----------------------------------------------------------------------===//

#include "clang/Analysis/PathSensitive/CheckerVisitor.h"
#include "clang/Analysis/PathSensitive/BugReporter.h"
#include "clang/AST/ParentMap.h"
#include "GRExprEngineInternalChecks.h"

using namespace clang;

namespace {
class VISIBILITY_HIDDEN CallAndMessageChecker
  : public CheckerVisitor<CallAndMessageChecker> {
  BugType *BT_call_null;
  BugType *BT_call_undef;  
  BugType *BT_call_arg;
  BugType *BT_msg_undef;
  BugType *BT_msg_arg;
  BugType *BT_struct_ret;
  BugType *BT_void_ptr;
public:
  CallAndMessageChecker() :
    BT_call_null(0), BT_call_undef(0), BT_call_arg(0),
    BT_msg_undef(0), BT_msg_arg(0), BT_struct_ret(0), BT_void_ptr(0) {}

  static void *getTag() {
    static int x = 0;
    return &x;
  }
  void PreVisitCallExpr(CheckerContext &C, const CallExpr *CE);
  void PreVisitObjCMessageExpr(CheckerContext &C, const ObjCMessageExpr *ME);
private:
  void EmitBadCall(BugType *BT, CheckerContext &C, const CallExpr *CE);
};
} // end anonymous namespace

void clang::RegisterCallAndMessageChecker(GRExprEngine &Eng) {
  Eng.registerCheck(new CallAndMessageChecker());
}

void CallAndMessageChecker::EmitBadCall(BugType *BT, CheckerContext &C,
                                        const CallExpr *CE) {
  ExplodedNode *N = C.GenerateSink();
  if (!N)
    return;
    
  EnhancedBugReport *R = new EnhancedBugReport(*BT, BT->getName(), N);
  R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
                       bugreporter::GetCalleeExpr(N));
  C.EmitReport(R);
}

void CallAndMessageChecker::PreVisitCallExpr(CheckerContext &C, 
                                             const CallExpr *CE){
  
  const Expr *Callee = CE->getCallee()->IgnoreParens();
  SVal L = C.getState()->getSVal(Callee);
  
  if (L.isUndef()) {
    if (!BT_call_undef)
      BT_call_undef =
        new BuiltinBug("Called function pointer is an undefined pointer value");
    EmitBadCall(BT_call_undef, C, CE);
    return;
  }
  
  if (isa<loc::ConcreteInt>(L)) {
    if (!BT_call_null)
      BT_call_null =
        new BuiltinBug("Called function pointer is null (null dereference)");
    EmitBadCall(BT_call_null, C, CE);
  }  
  
  for (CallExpr::const_arg_iterator I = CE->arg_begin(), E = CE->arg_end();
       I != E; ++I) {
    if (C.getState()->getSVal(*I).isUndef()) {
      if (ExplodedNode *N = C.GenerateSink()) {
        if (!BT_call_arg)
          BT_call_arg = new BuiltinBug("Pass-by-value argument in function call"
                                       " is undefined");
        // Generate a report for this bug.
        EnhancedBugReport *R = new EnhancedBugReport(*BT_call_arg,
                                                     BT_call_arg->getName(), N);
        R->addRange((*I)->getSourceRange());
        R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, *I);
        C.EmitReport(R);
        return;
      }
    }
  }
}

void CallAndMessageChecker::PreVisitObjCMessageExpr(CheckerContext &C,
                                                    const ObjCMessageExpr *ME) {

  const GRState *state = C.getState();

  if (const Expr *receiver = ME->getReceiver())
    if (state->getSVal(receiver).isUndef()) {
      if (ExplodedNode *N = C.GenerateSink()) {
        if (!BT_msg_undef)
          BT_msg_undef =
            new BuiltinBug("Receiver in message expression is a garbage value");
        EnhancedBugReport *R =
          new EnhancedBugReport(*BT_msg_undef, BT_msg_undef->getName(), N);
        R->addRange(receiver->getSourceRange());
        R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue,
                             receiver);
        C.EmitReport(R);
      }
      return;
    }

  // Check for any arguments that are uninitialized/undefined.
  for (ObjCMessageExpr::const_arg_iterator I = ME->arg_begin(),
         E = ME->arg_end(); I != E; ++I) {
    if (state->getSVal(*I).isUndef()) {
      if (ExplodedNode *N = C.GenerateSink()) {
        if (!BT_msg_arg)
          BT_msg_arg =
            new BuiltinBug("Pass-by-value argument in message expression"
                           " is undefined");      
        // Generate a report for this bug.
        EnhancedBugReport *R = new EnhancedBugReport(*BT_msg_arg,
                                                     BT_msg_arg->getName(), N);
        R->addRange((*I)->getSourceRange());
        R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, *I);
        C.EmitReport(R);
        return;
      }
    }
  }

  // Check if the receiver was nil and then return value a struct.
  if (const Expr *Receiver = ME->getReceiver()) {
    SVal L_untested = state->getSVal(Receiver);
    // Assume that the receiver is not NULL.
    DefinedOrUnknownSVal L = cast<DefinedOrUnknownSVal>(L_untested);
    const GRState *StNotNull = state->Assume(L, true);

    // Assume that the receiver is NULL.
    const GRState *StNull = state->Assume(L, false);

    if (StNull) {
      QualType RetTy = ME->getType();
      if (RetTy->isRecordType()) {
        if (C.getPredecessor()->getParentMap().isConsumedExpr(ME)) {
          // The [0 ...] expressions will return garbage.  Flag either an
          // explicit or implicit error.  Because of the structure of this
          // function we currently do not bifurfacte the state graph at
          // this point.
          // FIXME: We should bifurcate and fill the returned struct with
          //  garbage.
          if (ExplodedNode* N = C.GenerateSink(StNull)) {
            if (!StNotNull) {
              if (!BT_struct_ret) {
                std::string sbuf;
                llvm::raw_string_ostream os(sbuf);
                os << "The receiver in the message expression is 'nil' and "
                  "results in the returned value (of type '"
                   << ME->getType().getAsString()
                   << "') to be garbage or otherwise undefined";
                BT_struct_ret = new BuiltinBug(os.str().c_str());
              }
              
              EnhancedBugReport *R = new EnhancedBugReport(*BT_struct_ret, 
                                                   BT_struct_ret->getName(), N);
              R->addRange(Receiver->getSourceRange());
              R->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, 
                                   Receiver);
              C.EmitReport(R);
              return;
            }
            else
              // Do not report implicit bug.
              return;
          }
        }
      } else {
        ASTContext &Ctx = C.getASTContext();
        if (RetTy != Ctx.VoidTy) {
          if (C.getPredecessor()->getParentMap().isConsumedExpr(ME)) {
            // sizeof(void *)
            const uint64_t voidPtrSize = Ctx.getTypeSize(Ctx.VoidPtrTy);
            // sizeof(return type)
            const uint64_t returnTypeSize = Ctx.getTypeSize(ME->getType());
            
            if (voidPtrSize < returnTypeSize) {
              if (ExplodedNode* N = C.GenerateSink(StNull)) {
                if (!StNotNull) {
                  if (!BT_struct_ret) {
                    std::string sbuf;
                    llvm::raw_string_ostream os(sbuf);
                    os << "The receiver in the message expression is 'nil' and "
                      "results in the returned value (of type '"
                       << ME->getType().getAsString()
                       << "' and of size "
                       << returnTypeSize / 8
                       << " bytes) to be garbage or otherwise undefined";
                    BT_void_ptr = new BuiltinBug(os.str().c_str());
                  }
              
                  EnhancedBugReport *R = new EnhancedBugReport(*BT_void_ptr, 
                                                     BT_void_ptr->getName(), N);
                  R->addRange(Receiver->getSourceRange());
                  R->addVisitorCreator(
                          bugreporter::registerTrackNullOrUndefValue, Receiver);
                  C.EmitReport(R);
                  return;
                } else
                  // Do not report implicit bug.
                  return;
              }
            }
            else if (!StNotNull) {
              // Handle the safe cases where the return value is 0 if the
              // receiver is nil.
              //
              // FIXME: For now take the conservative approach that we only
              // return null values if we *know* that the receiver is nil.
              // This is because we can have surprises like:
              //
              //   ... = [[NSScreens screens] objectAtIndex:0];
              //
              // What can happen is that [... screens] could return nil, but
              // it most likely isn't nil.  We should assume the semantics
              // of this case unless we have *a lot* more knowledge.
              //
              SVal V = C.getValueManager().makeZeroVal(ME->getType());
              C.GenerateNode(StNull->BindExpr(ME, V));
              return;
            }
          }
        }
      }
    }
    // Do not propagate null state.
    if (StNotNull)
      C.GenerateNode(StNotNull);
  }
}