[google] Check if the nonnull attribute is applied to 'this' (issue4446070)

Diego Novillo dnovillo@google.com
Fri Apr 29 15:39:00 GMT 2011


This patch from Le-Chun Wu adds support to check whether a nonnull
attribute is applied to 'this' pointer for non-static methods.

OK for trunk?  Applied to google/main

2011-04-27  Le-Chun Wu  <lcwu@google.com>

	Google ref 45339.

	* c-common.c (handle_nonnull_attribute): Check whether the nonnull
	attribute is applied to the 'this' pointer for non-static methods.

testsuite/ChangeLog.google-main
2011-04-27  Le-Chun Wu  <lcwu@google.com>

	* g++.dg/warn/nonnull2.C: New.

diff --git a/gcc/c-family/c-common.c b/gcc/c-family/c-common.c
index c6dc649..a1702f8 100644
--- a/gcc/c-family/c-common.c
+++ b/gcc/c-family/c-common.c
@@ -7434,7 +7434,7 @@ handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
 
   /* Argument list specified.  Verify that each argument number references
      a pointer argument.  */
-  for (attr_arg_num = 1; args; args = TREE_CHAIN (args))
+  for (attr_arg_num = 1; args; args = TREE_CHAIN (args), attr_arg_num++)
     {
       tree argument;
       unsigned HOST_WIDE_INT arg_num = 0, ck_num;
@@ -7466,6 +7466,7 @@ handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
 	      return NULL_TREE;
 	    }
 
+
 	  if (TREE_CODE (TREE_VALUE (argument)) != POINTER_TYPE)
 	    {
 	      error ("nonnull argument references non-pointer operand (argument %lu, operand %lu)",
@@ -7473,6 +7474,11 @@ handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
 	      *no_add_attrs = true;
 	      return NULL_TREE;
 	    }
+
+          if (TREE_CODE (type) == METHOD_TYPE && arg_num == 1)
+            warning (OPT_Wattributes,
+                     "nonnull argument references 'this' pointer (argument %lu, operand %lu)",
+                     (unsigned long) attr_arg_num, (unsigned long) arg_num);
 	}
     }
 
diff --git a/gcc/testsuite/g++.dg/warn/nonnull2.C b/gcc/testsuite/g++.dg/warn/nonnull2.C
new file mode 100644
index 0000000..03006b1
--- /dev/null
+++ b/gcc/testsuite/g++.dg/warn/nonnull2.C
@@ -0,0 +1,14 @@
+// Test that "nonnull" attribute should not be applied to 'this' pointer.
+// { dg-do compile }
+
+#define NULL 0
+
+class Foo {
+ public:
+  void method1(const int *ptr) __attribute__((nonnull(1, 2))); // { dg-warning "nonnull argument references 'this' pointer" }
+  void method2(int *ptr1, int a, int *ptr2) __attribute__((nonnull(2, 3, 4))); // { dg-error "nonnull argument references non-pointer operand" }
+  static void func3(int *ptr) __attribute__((nonnull(1))); // should not warn
+  Foo(char *str) __attribute__((nonnull())) {}
+};
+
+int func4(int *ptr1, int a) __attribute__((nonnull(1))); // should not warn
-- 
1.7.3.1


--
This patch is available for review at http://codereview.appspot.com/4446070



More information about the Gcc-patches mailing list