Skip to content
systemcoding.dev
Security

Write Safe printf-Style Wrappers With the format Attribute

Declare a logging function with __attribute__((format(printf, ...))) so GCC and Clang check each call's format and arguments, and pair it with vsnprintf.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the GNU, C and C++ logos.

Most C projects end up with a log_msg or die function that takes a format string and a variable number of arguments, then hands them to vsnprintf or vfprintf. The wrapper works, and it quietly disables the best bug detector in the compiler. GCC and Clang check printf calls against their format strings because the library functions are declared with a special attribute, and your wrapper is not, so a wrong argument type or an attacker-controlled format passes without a word. The fix is one line on the declaration. This post shows the attribute, the warnings it turns on, the two shapes of wrapper (... and va_list) and the checks it enables for the format-string bugs described earlier in this series. Examples target GCC 15 and Clang 20 on Linux 6.12 with glibc 2.41.

A wrapper the compiler cannot see through

Start with an ordinary logging function:

log.hc
#ifndef LOG_H
#define LOG_H

void log_msg(int level, const char *fmt, ...);

#endif
log.cc
#include "log.h"
#include <stdarg.h>
#include <stdio.h>

void log_msg(int level, const char *fmt, ...)
{
    char line[256];
    va_list ap;

    va_start(ap, fmt);
    vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    fprintf(stderr, "[%d] %s\n", level, line);
}

The body is fine. The problem is at the call sites, which the compiler cannot verify:

main.cc
#include "log.h"

int main(int argc, char **argv)
{
    log_msg(1, "id=%d name=%s", "alex", 7);   /* arguments swapped */
    log_msg(1, argv[1]);                       /* user text as format */
    return argc;
}

Compile with gcc -std=c17 -Wall -Wextra -Wformat=2 -o demo main.c log.c. There are no warnings, because as far as the compiler knows log_msg takes an arbitrary string and arbitrary extra arguments. At run time the first call passes a pointer where %d reads an int, which prints a meaningless number, and the second hands attacker-controlled text to a format parser.

Add the attribute

The GCC attribute is format(archetype, string-index, first-to-check). It says the function behaves like a standard function of the given family. For printf the archetype is printf, string-index is the position of the format parameter counting from 1, and first-to-check is the position of the first variadic argument. Here the format is the second parameter and the variadic part starts at the third:

log.hc
#ifndef LOG_H
#define LOG_H

#if defined(__GNUC__) || defined(__clang__)
#define LOG_PRINTF(fmt, args) __attribute__((format(printf, fmt, args)))
#else
#define LOG_PRINTF(fmt, args)
#endif

void log_msg(int level, const char *fmt, ...) LOG_PRINTF(2, 3);

#endif

A macro keeps the header portable to compilers without the attribute, and puts the numbers in one place. Put the attribute on the declaration in the header, where every caller sees it, and keep the definition free of it. The same text can use the C23 attribute [[gnu::format(printf, 2, 3)]] in GCC 10 and later when compiling with -std=c23.

Recompile the same main.c, and the compiler now reads every call:

Text
main.c: In function 'main':
main.c:5:28: warning: format '%d' expects argument of type 'int', but argument 3 has type 'char *' [-Wformat=]
    5 |     log_msg(1, "id=%d name=%s", "alex", 7);   /* arguments swapped */
      |                         ~^      ~~~~~~
      |                          |      |
      |                          int    char *
      |                         %s
main.c:5:36: warning: format '%s' expects argument of type 'char *', but argument 4 has type 'int' [-Wformat=]
    5 |     log_msg(1, "id=%d name=%s", "alex", 7);   /* arguments swapped */
      |                                  ~^            ~
      |                                   |            |
      |                                   char *       int
      |                                  %d
main.c:6:5: warning: format not a string literal and no format arguments [-Wformat-security]
    6 |     log_msg(1, argv[1]);                       /* user text as format */
      |     ^~~~~~~

The caret art and column numbers depend on the compiler version, but the three diagnostics are what you should expect: two mismatches from -Wformat (part of -Wall) and the security warning from -Wformat-security. Add -Werror=format-security to refuse to build the third. The GCC manual documents the attribute in Common Function Attributes.

Wrappers that take a va_list

Many projects have a second function that takes a va_list, so that other variadic functions can forward to it:

log.hc
void vlog_msg(int level, const char *fmt, va_list ap) LOG_PRINTF(2, 0);

The 0 for first-to-check tells the compiler that there are no variadic arguments to inspect, because they are in the va_list. It still checks that fmt is a valid format string and, with -Wformat-nonliteral, warns when it is not a literal, which is the right behavior for a function whose callers are other wrappers. A good arrangement is that the ... function carries (2, 3), the va_list function carries (2, 0), and the first calls the second:

log.cc
void vlog_msg(int level, const char *fmt, va_list ap)
{
    char line[256];
    vsnprintf(line, sizeof line, fmt, ap);
    fprintf(stderr, "[%d] %s\n", level, line);
}

void log_msg(int level, const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vlog_msg(level, fmt, ap);
    va_end(ap);
}

Inside log_msg, the call vlog_msg(level, fmt, ap) passes a non-literal format, and -Wformat-nonliteral would warn about it, except that GCC recognizes that log_msg itself carries the format attribute for the same parameter and suppresses the warning for pass-through. This is the whole reason to annotate both layers: the check moves out to the real call sites, and the pass-through stays quiet. If you see a -Wformat-nonliteral warning inside your wrapper, the attribute is missing on the function that contains it.

Which archetypes exist

ArchetypeUse for
printffunctions that format like printf
scanffunctions that parse like scanf
strftimefunctions that take a strftime format and a struct tm
strfmonmonetary formatting like strfmon
gnu_printf and ms_printfpin the dialect when cross-compiling or on MinGW, where printf may mean the Microsoft one

On MinGW, printf follows the platform's C runtime and gnu_printf follows ISO C, and picking the wrong one makes %zu and %lld warn or pass incorrectly. A project that targets both uses __MINGW_PRINTF_FORMAT where defined and printf elsewhere.

There is a related attribute, format_arg(n), for functions that take a format string and return a translated version of it, such as gettext. It tells the compiler the returned string has the same conversions as argument n, so that printf(gettext("%d files"), n) is still checked.

Which warnings to enable

Three flags work with the attribute:

FlagEffect
-Wformatchecks argument types and counts against the format, on in -Wall
-Wformat-securitywarns about non-literal formats with no arguments
-Wformat-nonliteralwarns about any non-literal format that is not forwarded by an annotated wrapper

-Wformat=2 enables the three plus -Wformat-y2k. It is a good default for new code and noisy for old code, where the first run finds wrappers that need the attribute. Treat each such warning as a to-do: find the function, annotate it and let the compiler find the callers.

Verifying the attribute took effect

A quick test: write a deliberate mistake in a scratch file and confirm the compiler complains. If it does not, the attribute is on the definition and not on the declaration the caller includes, the parameter numbers are off by one (they count from 1, and member functions in C++ count this as the first parameter) or the flag is missing. Clang accepts the same attribute and the same numbering. In C++ on GCC and Clang, a non-static member function's implicit this takes index 1, so the format parameter of void Logger::log(int, const char *, ...) is 3 and the arguments start at 4.

Where the attribute pays off most

The wrappers that matter most are the ones that sit closest to untrusted data: the logging function that records a request header, the error reporter that echoes a file name and the protocol layer that formats a reply. Those are the places where a user-controlled string ends up in the format position through a careless call such as log_msg(1, name). The attribute turns that single mistake into a build failure when -Werror=format-security is on, and the cost to the project is one line per declaration. Search the codebase for functions that call vsnprintf, vfprintf, vsyslog or vasprintf. Every one of them is a wrapper that needs the annotation, and the list is usually short.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.