This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: __builtin_string_constant_p
* Joseph S. Myers:
>> For some routines that should only accept string literals, it would be
>> nice to have a __builtin_string_constant_p built-in. For example,
>
> Meaning what exactly, for such cases as
>
> foo(complicated_expression ? "bar" : non_string)
>
> where complicated_expression might or might not be optimised to 1?
Well, that's not a string literal, so it's okay to return 0 in my
case.
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 '").
In the meantime, I've come up with the idiom below (which is used to
guard string creation from a plain pointer, I'm not yet at the stage
of writing SQL database interfaces 8-). It's not ideal, but it's
better than no check at all.
inline String* create(const char* src)
{
size_t length = strlen(src);
// This checks that we can determine the length of SRC at compile
// time. With current GCC versions (as of 2004-0811), passing
// something that isn't a string constant results in an undefined
// to argumentToStringCreateMustBeStringConstant. However, this
// reference might still be optimized away because the compiler
// could deduce that an object cannot have a size that large.
if (length > 65536) {
extern void argumentToStringCreateMustBeStringConstant();
argumentToStringCreateMustBeStringConstant();
}
return UNCHECKED_create(src, length);
}