ivoriik
ivoriik

Reputation: 165

How to find which function prints printk statement?

Is it a way to find in which function printk was executed? I know that I can add __function__ to my printk to get this information, but I'm working with big project and it's kinda impossible to add this to all printk manually.

Maybe I should add some macros to code or use some linux command?

Upvotes: 1

Views: 1007

Answers (2)

0andriy
0andriy

Reputation: 4709

Since we are talking about Linux kernel programming, there are several ways to achieve this. The worst one is to define custom macro where you add something additional to print. Now, let's consider better approaches.

Approach 1. If you are interesting to put function name to only subset of the messages, assuming for debug purposes, the best option is to enable Dynamic Debug option and use special macros instead of direct calls to printk, i.e. pr_debug(), dev_dbg(), netdev_dbg() and so on.

It will allow you to turn on and off any single message at run time along with enabling __func__ to be printed or not.

Approach 2. Another approach if you want to enable additional arguments to the families of macros, such as pr_*() and dev_*(), you may define special macros at the very beginning of each module or, if you want, include from the header, though it must be the very fist one in each C-file. See example from ipmi_msghandler.c:

#define pr_fmt(fmt) "%s" fmt, "IPMI message handler: "
#define dev_fmt pr_fmt

It can be easily transformed to

#define pr_fmt(fmt) "%s(): " fmt, __func__
#define dev_fmt pr_fmt

The benefit of this method is a possibility to set up different prefixes to different modules, like using their filenames, and it will be applied to all messages of the same family of macros.

Disadvantage is that only pr_*() and dev_*() families do have such facilities.

Upvotes: 2

Mathieu
Mathieu

Reputation: 9699

You can do this with some macro (at least with printf, but the principle is the same with printk):

#include <stdio.h>

/* redefine printf for the rest of file. */
#define printf(...) \ 
do { \
    printf("%s: %d:\t", __FILE__, __LINE__);\    
    printf(__VA_ARGS__);\
} while (0)

/* after this point, each call to printf will be replaced by two. */


int main(void)
{
    printf("Hello\n");
    return 0;
}

Will print (tested from https://tio.run/#c-gcc):

.code.tio.c: 12:    Hello 

Instead of just

Hello

Upvotes: 0

Related Questions