This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
| Index Nav: | [Date Index] [Subject Index] [Author Index] [Thread Index] | |
|---|---|---|
| Message Nav: | [Date Prev] [Date Next] | [Thread Prev] [Thread Next] |
| Other format: | [Raw text] | |
My apologies if this is a frequently contributed patch, but I recently
came across a bug in a colleague's code that had been diagnosed by IBM's
xlc compiler, but I was surprised/shocked to discover that it is
uncommented upon by GCC. Given some blatently incorrect code such as:
void foo()
{
int x[4];
...
x[12] = 0;
...
}
I discovered that the known compile-time array bounds violation isn't
picked up by gcc, even with "-W -Wall -Wextra -pedantic". I can't cite
the exact section from the ISO standards from memory, but I do recall from
bug-fixes on the PA, that it's
undefined/implementation-defined/not-well-defined to contruct a pointer
outside the bounds of a declared object. The one minor quirk is that it's
valid to refer to the byte beyond the end of an object, i.e. &x[4] above,
but &x[-1] and &x[5] have "issues".
The patch below adds minimal compile-time array bounds checking to the C
front-end, via c-typeck.c's build_array_ref. This patch doesn't attempt
to do anything clever with pointers or indices other than integer
constants, by checking whether the array being referred to is a "raw"
declaration. I'm sure that it may be possible to extend this code to
other obvious cases, but the ones caught below should be
non-controversial.
In the proposed implementation, the new -Wbounds-check is enabled by
default, but may be turned off via -Wno-bounds-check. Other alternatives
include not enabling it by default, turning it on with -Wall, making it a
pedwarn controlled by -pedantic. I'm open to suggestions.
The following patch has been tested on i686-pc-linux-gnu with a full
"make bootstrap", all default languages including Ada, and regression
tested with a top-level "make -k check" with no new failures.
Thoughts? Ok for mainline?
2007-01-12 Roger Sayle <roger@eyesopen.com>
* c.opt (Wbounds-check): New command line option.
* c-typeck.c (build_array_ref): When the index is an integer
constant and they array is a naked VAR_DECL, test whether the
index is within the declared bounds of the array.
* doc/invoke.texi: Document the new -Wno-bounds-check option.
* gcc.dg/Wbounds-check-1.c: New test case.
* gcc.dg/Wbounds-check-2.c: Likewise.
* gcc.dg/Wbounds-check-3.c: Likewise.
* gcc.dg/Wbounds-check-4.c: Likewise.
Roger
--Attachment:
patchc2.txt
Description: Text document
Attachment:
Wbounds-check-1.c
Description: Text document
Attachment:
Wbounds-check-2.c
Description: Text document
Attachment:
Wbounds-check-3.c
Description: Text document
Attachment:
Wbounds-check-4.c
Description: Text document
| Index Nav: | [Date Index] [Subject Index] [Author Index] [Thread Index] | |
|---|---|---|
| Message Nav: | [Date Prev] [Date Next] | [Thread Prev] [Thread Next] |