Re: va_list and unanticipated format specifiers
Re: va_list and unanticipated format specifiers
- Subject: Re: va_list and unanticipated format specifiers
- From: Ken Thomases <email@hidden>
- Date: Thu, 3 Jun 2010 08:20:24 -0500
On Jun 3, 2010, at 6:47 AM, email@hidden wrote:
> One of my logging methods uses a variable argument list and is accessed via a macro
>
> #define MLog(level,s,...) [[MLog sharedController] withLevel:level sourceFile:__FILE__ lineNumber:__LINE__ format:(s),## __VA_ARGS__]
>
> The method implementation retrieves the va_list and instantiates an NSString
>
> // read variable argument list
> va_list ap;
> va_start(ap,format);
> NSString *logEntry = [[NSString alloc] initWithFormat:format arguments:ap];
> va_end(ap);
>
> The input into this is highly variable.
Right, that's to be expected.
> So a log/error message raised at a higher level may contain additional unanticipated format specifiers such as "%@".
I don't understand in what way that's unanticipated. Or, perhaps from the other point of view, what constitutes "anticipated"? How were you arriving at your expectation?
> This causes runtime woe as we run off the end of the va_list.
If the argument list and the format string don't match, that's a code bug. In general, it can't be detected because, as you note, the argument list is opaque.
In other words, the format string is what establishes the expected content of the argument list. It's where "anticipated" comes from.
> With the va_list we don't know the number of items.
> With the format spec we don't know which of the format specifiers are unanticipated.
Again, what constitutes "unanticipated" for a format specifier? If there's something like "%@" in the string and it's _not_ intended by the caller to be a format specifier, then the caller should have escaped the percent sign by doubling it.
Is the problem that the caller is only aware of the C library format specifiers and isn't aware of the Cocoa print specifiers?
> So is it just a question of sanitising the input format?
If you have a string which is not intended as a format string, then the proper way of formatting it is to pass it as a value, not the format string. Like so:
printf("%s\n", arbitrary_string);
NSLog(@"%@\n", arbitrary_nsstring);
Regards,
Ken
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden