27

Is there function like sprintf() in Linux Kernel (like printf()->printk())?

1
  • 1
    Note that for many use cases, the seq_file interface is much better suited. (If you use the seq_path() or seq_escape() facilities, do remember to include ` in the set of escape'd characters. I've tried to push related bugfixes (in e.g. /proc`) but getting such "corner cases" any kind of recognition is too much of a problem, so if you introduce such bugs, you are likely going to just have to live with them forever.) Mar 16, 2017 at 16:41

5 Answers 5

30

yes. https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/lib/vsprintf.c#n1828

int snprintf(char *buf, size_t size, const char *fmt, ...)
{
    va_list args;
    int i;

    va_start(args, fmt);
    i = vsnprintf(buf, size, fmt, args);
    va_end(args);

    return i;
}
EXPORT_SYMBOL(snprintf);

sprintf() by itself is prone to buffer overflows. CERT buffer overflows, Apple, etc

5
  • Which header should I include?
    – Alex
    Sep 4, 2012 at 13:24
  • 1
    this http://lxr.linux.no/linux+v3.5.3/include/linux/kernel.h#L323 located in linux/include/linux/kernel.h Sep 4, 2012 at 13:27
  • The implementation of this and of some other useful functions (scnptintf, snprintf, etc.) as well as their description is in lib/vsprintf.c. There are some useful features these functions have that their user-space counterparts do not (%pS, for example).
    – Eugene
    Sep 5, 2012 at 6:52
  • 4
    This answer is wrong. The code referred to above is not built into the kernel. The version of sprintf() available in the kernel is in lib/vsprintf.c I edited the answer but it was rejected by someone who doesn't know what they're talking about.
    – mpe
    Sep 10, 2012 at 6:15
  • 1
    Can you extend your answer to mention options like kasfprintf()?
    – 0andriy
    Mar 16, 2017 at 21:17
2

Yes, just include linux/kernel.h

0

yes there is check out here for example

you can use grep to see if it is in the kernel's source code

0

Running crash on a live 2.6 kernel confirms sprintf() is defined, and where it is defined.

crash> sym sprintf

ffffffff81267ba0 (T) sprintf ../debug/kernel-2.6.39/linux-2.6.39-400.210.2.el6uek/lib/vsprintf.c: 1442

0

sprintf() is unsafe because of buffer overflow. If you need to pass data from user space to kernel space, use instead copy_from_user(); it acts like copy_to_user() but in reverse direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.