This is the mail archive of the
gcc-patches@gcc.gnu.org
mailing list for the GCC project.
[PATCH 2/6] New warnings -Wstring-plus-{char, int} (PR c++/62181)
- From: Xi Ruoyao <ryxi at stu dot xidian dot edu dot cn>
- To: gcc-patches at gcc dot gnu dot org
- Cc: ryxi at stu dot xidian dot edu dot cn
- Date: Mon, 12 Jun 2017 09:32:54 +0800
- Subject: [PATCH 2/6] New warnings -Wstring-plus-{char, int} (PR c++/62181)
- Authentication-results: sourceware.org; auth=none
- References: <1497230800.27153.4.camel@stu.xidian.edu.cn>
This patch adds warning option -Wstring-plus-int for C/C++.
gcc/ChangeLog:
2017-06-12 Xi Ruoyao <ryxi@stu.xidian.edu.cn>
* c-family/c.opt: New option -Wstring-plus-int.
* c-family/c-common.c (pointer_int_sum): Checking for
-Wstring-plus-int.
---
gcc/c-family/c-common.c | 25 +++++++++++++++++++++++++
gcc/c-family/c.opt | 5 +++++
2 files changed, 30 insertions(+)
--
Xi Ruoyao <ryxi@stu.xidian.edu.cn>
School of Aerospace Science and Technology, Xidian University
diff --git a/gcc/c-family/c-common.c b/gcc/c-family/c-common.c
index 4395e51..1eee48f 100644
--- a/gcc/c-family/c-common.c
+++ b/gcc/c-family/c-common.c
@@ -3100,6 +3100,31 @@ pointer_int_sum (location_t loc, enum tree_code resultcode,
else
size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
+ /* Handle -Wstring-plus-int, warn for adding string literals
+ and an integer which may result in a wild pointer. */
+ if (warn_string_plus_int
+ && resultcode == PLUS_EXPR
+ && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (result_type))))
+ {
+ tree orig_ptrop = tree_strip_nop_conversions(ptrop);
+ if (TREE_CODE (orig_ptrop) == ADDR_EXPR)
+ {
+ tree obj = TREE_OPERAND (orig_ptrop, 0);
+ if (TREE_CODE (obj) == STRING_CST)
+ {
+ tree t = TYPE_DOMAIN (TREE_TYPE (obj));
+ if (TREE_CODE (intop) != INTEGER_CST
+ || tree_int_cst_lt (intop, TYPE_MIN_VALUE (t))
+ || int_cst_value (intop)
+ > int_cst_value (TYPE_MAX_VALUE (t)) + 1)
+ warning_at (loc, OPT_Wstring_plus_int,
+ "add %qT to string does not append to "
+ "the string",
+ TREE_TYPE (intop));
+ }
+ }
+ }
+
/* We are manipulating pointer values, so we don't need to warn
about relying on undefined signed overflow. We disable the
warning here because we use integer types so fold won't know that
diff --git a/gcc/c-family/c.opt b/gcc/c-family/c.opt
index 37bb236..94ba3eb 100644
--- a/gcc/c-family/c.opt
+++ b/gcc/c-family/c.opt
@@ -732,6 +732,11 @@ C ObjC C++ ObjC++ Joined RejectNegative UInteger Var(warn_stringop_overflow) Ini
Under the control of Object Size type, warn about buffer overflow in string
manipulation functions like memcpy and strcpy.
+Wstring-plus-int
+C ObjC C++ ObjC++ Var(warn_string_plus_int) Warning
+Warn about adding strings and integers, which is likely an ill-formed
+attempt to append the string.
+
Wsuggest-attribute=format
C ObjC C++ ObjC++ Var(warn_suggest_attribute_format) Warning
Warn about functions which might be candidates for format attributes.
--
2.7.1