]> granicus.if.org Git - clang/commitdiff
[analyzer] do not warn about returning stack-allocated memory when it comes from...
authorTed Kremenek <kremenek@apple.com>
Sat, 3 Mar 2012 01:22:03 +0000 (01:22 +0000)
committerTed Kremenek <kremenek@apple.com>
Sat, 3 Mar 2012 01:22:03 +0000 (01:22 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@151964 91177308-0d34-0410-b5e6-96231b3b80d8

lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
test/Analysis/inline.c

index d071ef8c1f748ecb7d0f716154fd33761f265c8a..8c76cc523d6333e4687496478eb14ef5647b7ed2 100644 (file)
@@ -113,7 +113,7 @@ void StackAddrEscapeChecker::EmitStackError(CheckerContext &C, const MemRegion *
 }
 
 void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
-                                        CheckerContext &C) const {
+                                          CheckerContext &C) const {
   
   const Expr *RetE = RS->getRetValue();
   if (!RetE)
@@ -122,18 +122,26 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt *RS,
   SVal V = C.getState()->getSVal(RetE, C.getLocationContext());
   const MemRegion *R = V.getAsRegion();
 
-  if (!R || !R->hasStackStorage())
-    return;  
+  if (!R)
+    return;
   
-  if (R->hasStackStorage()) {
-    // Automatic reference counting automatically copies blocks.
-    if (C.getASTContext().getLangOptions().ObjCAutoRefCount &&
-        isa<BlockDataRegion>(R))
-      return;
+  const StackSpaceRegion *SS =
+    dyn_cast_or_null<StackSpaceRegion>(R->getMemorySpace());
+    
+  if (!SS)
+    return;
 
-    EmitStackError(C, R, RetE);
+  // Return stack memory in an ancestor stack frame is fine.
+  const StackFrameContext *SFC = SS->getStackFrame();
+  if (SFC != C.getLocationContext()->getCurrentStackFrame())
     return;
-  }
+
+  // Automatic reference counting automatically copies blocks.
+  if (C.getASTContext().getLangOptions().ObjCAutoRefCount &&
+      isa<BlockDataRegion>(R))
+    return;
+
+  EmitStackError(C, R, RetE);
 }
 
 void StackAddrEscapeChecker::checkEndPath(CheckerContext &Ctx) const {
index de807fb3aad90d13854f2d684b0bd1833fbfa679..9e64d33690d17daac1d1fa5994d7f09a16d9bf0f 100644 (file)
@@ -58,3 +58,22 @@ void test_factorial_2() {
     *p = 0xDEADBEEF; // no-warning
   }
 }
+
+// Test that returning stack memory from a parent stack frame does
+// not trigger a warning.
+static char *return_buf(char *buf) {
+  return buf + 10;
+}
+
+void test_return_stack_memory_ok() {
+  char stack_buf[100];
+  char *pos = return_buf(stack_buf);
+  (void) pos;
+}
+
+char *test_return_stack_memory_bad() {
+  char stack_buf[100];
+  char *x = stack_buf;
+  return x; // expected-warning {{stack memory associated}}
+}
+