This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: __builtin_string_constant_p
- From: Michael Veksler <VEKSLER at il dot ibm dot com>
- To: Florian Weimer <fw at deneb dot enyo dot de>
- Cc: gcc at gcc dot gnu dot org
- Date: Wed, 11 Aug 2004 10:39:10 +0300
- Subject: Re: __builtin_string_constant_p
Florian Weime wrote on 11/08/2004 09:36:42:
> >> For some routines that should only accept string literals, it would
be
> >> nice to have a __builtin_string_constant_p built-in. For example,
> >
[...]
> Maybe a few words on why I want to do this are in order. Suppose
> you've got function executeSQL(const char*) which executes an SQL
> statement. You want to allow users to call
>
> executeSQL("SELECT * FROM users");
>
> but not
>
> char buf[200];
> snprintf(buf, sizeof(buf), "SELECT * FROM users WHERE name = '%s'",
name);
> executeSQL(buf);
>
> because that might open SQL injection attacks (name could be a string
> similar to "'; DELETE FROM users; SELECT '").
There is a portable 99% solution for that:
#define string_constant_p(text) (*(&(text)+1) ==
text+strlen(text)+1)
Limitations:
1. It may fail to compile when 'text' is an expression like:
string_constant_p(str+1)
2. It will return false positive if the size of the buffer is exactly
string length + '\0'.
It does not seem likely that user's snprintf will generate a string
with
exactly the right size. Thinking of it again, if SQL injection is
involved, you may never know (If the injection is big enough snprinf
will return max string for the buffer).
Another idea:
#define assert_string_constant(text) (void)(#text "")
It will fail compilation unless text is a string literal - and
can be concatenated with the second "" string.
This is a 100% solution - with an ugly error message.