在使用Linux内核提供的打印函数时,使用“%p”可以实现很多额外的效果,对于我们调试内核代码也有一定帮助。
比如当我们看到函数指针变量,想获取这个函数指针对应的是哪个函数,可以使用“%pF”,示例:
1 #include <linux/init.h> 2 #include <linux/module.h> 3 4 static int test_function(void) 5 { 6 printk("%s enter.\n", __func__); 7 8 return 0; 9 } 10 11 static int __init printk_demo_init(void) 12 { 13 int (*func)(void); 14 15 func = test_function; 16 17 printk("%s: %pF\n", __func__, func); 18 19 return 0; 20 } 21 22 static void __exit printk_demo_exit(void) 23 { 24 25 } 26 27 module_init(printk_demo_init); 28 module_exit(printk_demo_exit); 29 30 MODULE_LICENSE("GPL");
运行效果:
[root@vexpress-a9 ~]# insmod /mnt/printk_demo.ko
[ 76.901583] printk_demo_init: test_function+0x0/0x20 [printk_demo]
关于更多“%p”的特殊用法,可以参考:linux\lib\vsprintf.c中pointer函数的实现。
/* * Show a '%p' thing. A kernel extension is that the '%p' is followed * by an extra set of alphanumeric characters that are extended format * specifiers. * * Please update scripts/checkpatch.pl when adding/removing conversion * characters. (Search for "check for vsprintf extension"). * * Right now we handle: * * - 'F' For symbolic function descriptor pointers with offset * - 'f' For simple symbolic function names without offset * - 'S' For symbolic direct pointers with offset * - 's' For symbolic direct pointers without offset * - '[FfSs]R' as above with __builtin_extract_return_addr() translation * - 'B' For backtraced symbolic direct pointers with offset * - 'R' For decoded struct resource, e.g., [mem 0x0-0x1f 64bit pref] * - 'r' For raw struct resource, e.g., [mem 0x0-0x1f flags 0x201] * - 'b[l]' For a bitmap, the number of bits is determined by the field * width which must be explicitly specified either as part of the * format string '%32b[l]' or through '%*b[l]', [l] selects * range-list format instead of hex format * - 'M' For a 6-byte MAC address, it prints the address in the * usual colon-separated hex notation * - 'm' For a 6-byte MAC address, it prints the hex address without colons * - 'MF' For a 6-byte MAC FDDI address, it prints the address * with a dash-separated hex notation * - '[mM]R' For a 6-byte MAC address, Reverse order (Bluetooth) * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way * IPv4 uses dot-separated decimal without leading 0's (1.2.3.4) * IPv6 uses colon separated network-order 16 bit hex with leading 0's * [S][pfs] * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to * [4] or [6] and is able to print port [p], flowinfo [f], scope [s] * - 'i' [46] for 'raw' IPv4/IPv6 addresses * IPv6 omits the colons (01020304...0f) * IPv4 uses dot-separated decimal with leading 0's (010.123.045.006) * [S][pfs] * Generic IPv4/IPv6 address (struct sockaddr *) that falls back to * [4] or [6] and is able to print port [p], flowinfo [f], scope [s] * - '[Ii][4S][hnbl]' IPv4 addresses in host, network, big or little endian order * - 'I[6S]c' for IPv6 addresses printed as specified by * http://tools.ietf.org/html/rfc5952 * - 'E[achnops]' For an escaped buffer, where rules are defined by combination * of the following flags (see string_escape_mem() for the * details): * a - ESCAPE_ANY * c - ESCAPE_SPECIAL * h - ESCAPE_HEX * n - ESCAPE_NULL * o - ESCAPE_OCTAL * p - ESCAPE_NP * s - ESCAPE_SPACE * By default ESCAPE_ANY_NP is used. * - 'U' For a 16 byte UUID/GUID, it prints the UUID/GUID in the form * "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" * Options for %pU are: * b big endian lower case hex (default) * B big endian UPPER case hex * l little endian lower case hex * L little endian UPPER case hex * big endian output byte order is: * [0][1][2][3]-[4][5]-[6][7]-[8][9]-[10][11][12][13][14][15] * little endian output byte order is: * [3][2][1][0]-[5][4]-[7][6]-[8][9]-[10][11][12][13][14][15] * - 'V' For a struct va_format which contains a format string * and va_list *, * call vsnprintf(->format, *->va_list). * Implements a "recursive vsnprintf". * Do not use this feature without some mechanism to verify the * correctness of the format string and va_list arguments. * - 'K' For a kernel pointer that should be hidden from unprivileged users * - 'NF' For a netdev_features_t * - 'h[CDN]' For a variable-length buffer, it prints it as a hex string with * a certain separator (' ' by default): * C colon * D dash * N no separator * The maximum supported length is 64 bytes of the input. Consider * to use print_hex_dump() for the larger input. * - 'a[pd]' For address types [p] phys_addr_t, [d] dma_addr_t and derivatives * (default assumed to be phys_addr_t, passed by reference) * - 'd[234]' For a dentry name (optionally 2-4 last components) * - 'D[234]' Same as 'd' but for a struct file * - 'g' For block_device name (gendisk + partition number) * - 'C' For a clock, it prints the name (Common Clock Framework) or address * (legacy clock framework) of the clock * - 'Cn' For a clock, it prints the name (Common Clock Framework) or address * (legacy clock framework) of the clock * - 'Cr' For a clock, it prints the current rate of the clock * - 'G' For flags to be printed as a collection of symbolic strings that would * construct the specific value. Supported flags given by option: * p page flags (see struct page) given as pointer to unsigned long * g gfp flags (GFP_* and __GFP_*) given as pointer to gfp_t * v vma flags (VM_*) given as pointer to unsigned long * - 'O' For a kobject based struct. Must be one of the following: * - 'OF[fnpPcCF]' For a device tree object * Without any optional arguments prints the full_name * f device node full_name * n device node name * p device node phandle * P device node path spec (name + @unit) * F device node flags * c major compatible string * C full compatible string * * - 'x' For printing the address. Equivalent to "%lx". * * ** Please update also Documentation/printk-formats.txt when making changes ** * * Note: The difference between 'S' and 'F' is that on ia64 and ppc64 * function pointers are really function descriptors, which contain a * pointer to the real address. * * Note: The default behaviour (unadorned %p) is to hash the address, * rendering it useful as a unique identifier. */ static noinline_for_stack char *pointer(const char *fmt, char *buf, char *end, void *ptr, struct printf_spec spec) { const int default_width = 2 * sizeof(void *); if (!ptr && *fmt != 'K') { /* * Print (null) with the same width as a pointer so it makes * tabular output look nice. */ if (spec.field_width == -1) spec.field_width = default_width; return string(buf, end, "(null)", spec); } switch (*fmt) { case 'F': case 'f': ptr = dereference_function_descriptor(ptr); /* Fallthrough */ case 'S': case 's': case 'B': return symbol_string(buf, end, ptr, spec, fmt); case 'R': case 'r': return resource_string(buf, end, ptr, spec, fmt); case 'h': return hex_string(buf, end, ptr, spec, fmt); case 'b': switch (fmt[1]) { case 'l': return bitmap_list_string(buf, end, ptr, spec, fmt); default: return bitmap_string(buf, end, ptr, spec, fmt); } case 'M': /* Colon separated: 00:01:02:03:04:05 */ case 'm': /* Contiguous: 000102030405 */ /* [mM]F (FDDI) */ /* [mM]R (Reverse order; Bluetooth) */ return mac_address_string(buf, end, ptr, spec, fmt); case 'I': /* Formatted IP supported * 4: 1.2.3.4 * 6: 0001:0203:...:0708 * 6c: 1::708 or 1::1.2.3.4 */ case 'i': /* Contiguous: * 4: 001.002.003.004 * 6: 000102...0f */ switch (fmt[1]) { case '6': return ip6_addr_string(buf, end, ptr, spec, fmt); case '4': return ip4_addr_string(buf, end, ptr, spec, fmt); case 'S': { const union { struct sockaddr raw; struct sockaddr_in v4; struct sockaddr_in6 v6; } *sa = ptr; switch (sa->raw.sa_family) { case AF_INET: return ip4_addr_string_sa(buf, end, &sa->v4, spec, fmt); case AF_INET6: return ip6_addr_string_sa(buf, end, &sa->v6, spec, fmt); default: return string(buf, end, "(invalid address)", spec); }} } break; case 'E': return escaped_string(buf, end, ptr, spec, fmt); case 'U': return uuid_string(buf, end, ptr, spec, fmt); case 'V': { va_list va; va_copy(va, *((struct va_format *)ptr)->va); buf += vsnprintf(buf, end > buf ? end - buf : 0, ((struct va_format *)ptr)->fmt, va); va_end(va); return buf; } case 'K': return restricted_pointer(buf, end, ptr, spec); case 'N': return netdev_bits(buf, end, ptr, fmt); case 'a': return address_val(buf, end, ptr, fmt); case 'd': return dentry_name(buf, end, ptr, spec, fmt); case 'C': return clock(buf, end, ptr, spec, fmt); case 'D': return dentry_name(buf, end, ((const struct file *)ptr)->f_path.dentry, spec, fmt); #ifdef CONFIG_BLOCK case 'g': return bdev_name(buf, end, ptr, spec, fmt); #endif case 'G': return flags_string(buf, end, ptr, fmt); case 'O': switch (fmt[1]) { case 'F': return device_node_string(buf, end, ptr, spec, fmt + 1); } case 'x': return pointer_string(buf, end, ptr, spec); } /* default is to _not_ leak addresses, hash before printing */ return ptr_to_id(buf, end, ptr, spec); }
此外,内核文档linux\Documentation\printk-formats.txt对其用法也做了说明。
========================================= How to get printk format specifiers right ========================================= :Author: Randy Dunlap <rdunlap@infradead.org> :Author: Andrew Murray <amurray@mpc-data.co.uk> Integer types ============= :: If variable is of Type, use printk format specifier: ------------------------------------------------------------ int %d or %x unsigned int %u or %x long %ld or %lx unsigned long %lu or %lx long long %lld or %llx unsigned long long %llu or %llx size_t %zu or %zx ssize_t %zd or %zx s32 %d or %x u32 %u or %x s64 %lld or %llx u64 %llu or %llx If <type> is dependent on a config option for its size (e.g., ``sector_t``, ``blkcnt_t``) or is architecture-dependent for its size (e.g., ``tcflag_t``), use a format specifier of its largest possible type and explicitly cast to it. Example:: printk("test: sector number/total blocks: %llu/%llu\n", (unsigned long long)sector, (unsigned long long)blockcount); Reminder: ``sizeof()`` result is of type ``size_t``. The kernel's printf does not support ``%n``. For obvious reasons, floating point formats (``%e, %f, %g, %a``) are also not recognized. Use of any unsupported specifier or length qualifier results in a WARN and early return from vsnprintf. Raw pointer value SHOULD be printed with %p. The kernel supports the following extended format specifiers for pointer types: Pointer Types ============= Pointers printed without a specifier extension (i.e unadorned %p) are hashed to give a unique identifier without leaking kernel addresses to user space. On 64 bit machines the first 32 bits are zeroed. If you _really_ want the address see %px below. :: %p abcdef12 or 00000000abcdef12 Symbols/Function Pointers ========================= :: %pF versatile_init+0x0/0x110 %pf versatile_init %pS versatile_init+0x0/0x110 %pSR versatile_init+0x9/0x110 (with __builtin_extract_return_addr() translation) %ps versatile_init %pB prev_fn_of_versatile_init+0x88/0x88 The ``F`` and ``f`` specifiers are for printing function pointers, for example, f->func, &gettimeofday. They have the same result as ``S`` and ``s`` specifiers. But they do an extra conversion on ia64, ppc64 and parisc64 architectures where the function pointers are actually function descriptors. The ``S`` and ``s`` specifiers can be used for printing symbols from direct addresses, for example, __builtin_return_address(0), (void *)regs->ip. They result in the symbol name with (``S``) or without (``s``) offsets. If KALLSYMS are disabled then the symbol address is printed instead. The ``B`` specifier results in the symbol name with offsets and should be used when printing stack backtraces. The specifier takes into consideration the effect of compiler optimisations which may occur when tail-call``s are used and marked with the noreturn GCC attribute. Examples:: printk("Going to call: %pF\n", gettimeofday); printk("Going to call: %pF\n", p->func); printk("%s: called from %pS\n", __func__, (void *)_RET_IP_); printk("%s: called from %pS\n", __func__, (void *)__builtin_return_address(0)); printk("Faulted at %pS\n", (void *)regs->ip); printk(" %s%pB\n", (reliable ? "" : "? "), (void *)*stack); Kernel Pointers =============== :: %pK 01234567 or 0123456789abcdef For printing kernel pointers which should be hidden from unprivileged users. The behaviour of ``%pK`` depends on the ``kptr_restrict sysctl`` - see Documentation/sysctl/kernel.txt for more details. Unmodified Addresses ==================== :: %px 01234567 or 0123456789abcdef For printing pointers when you _really_ want to print the address. Please consider whether or not you are leaking sensitive information about the Kernel layout in memory before printing pointers with %px. %px is functionally equivalent to %lx. %px is preferred to %lx because it is more uniquely grep'able. If, in the future, we need to modify the way the Kernel handles printing pointers it will be nice to be able to find the call sites. Struct Resources ================ :: %pr [mem 0x60000000-0x6fffffff flags 0x2200] or [mem 0x0000000060000000-0x000000006fffffff flags 0x2200] %pR [mem 0x60000000-0x6fffffff pref] or [mem 0x0000000060000000-0x000000006fffffff pref] For printing struct resources. The ``R`` and ``r`` specifiers result in a printed resource with (``R``) or without (``r``) a decoded flags member. Passed by reference. Physical addresses types ``phys_addr_t`` ======================================== :: %pa[p] 0x01234567 or 0x0123456789abcdef For printing a ``phys_addr_t`` type (and its derivatives, such as ``resource_size_t``) which can vary based on build options, regardless of the width of the CPU data path. Passed by reference. DMA addresses types ``dma_addr_t`` ================================== :: %pad 0x01234567 or 0x0123456789abcdef For printing a ``dma_addr_t`` type which can vary based on build options, regardless of the width of the CPU data path. Passed by reference. Raw buffer as an escaped string =============================== :: %*pE[achnops] For printing raw buffer as an escaped string. For the following buffer:: 1b 62 20 5c 43 07 22 90 0d 5d few examples show how the conversion would be done (the result string without surrounding quotes):: %*pE "\eb \C\a"\220\r]" %*pEhp "\x1bb \C\x07"\x90\x0d]" %*pEa "\e\142\040\\\103\a\042\220\r\135" The conversion rules are applied according to an optional combination of flags (see :c:func:`string_escape_mem` kernel documentation for the details): - ``a`` - ESCAPE_ANY - ``c`` - ESCAPE_SPECIAL - ``h`` - ESCAPE_HEX - ``n`` - ESCAPE_NULL - ``o`` - ESCAPE_OCTAL - ``p`` - ESCAPE_NP - ``s`` - ESCAPE_SPACE By default ESCAPE_ANY_NP is used. ESCAPE_ANY_NP is the sane choice for many cases, in particularly for printing SSIDs. If field width is omitted the 1 byte only will be escaped. Raw buffer as a hex string ========================== :: %*ph 00 01 02 ... 3f %*phC 00:01:02: ... :3f %*phD 00-01-02- ... -3f %*phN 000102 ... 3f For printing a small buffers (up to 64 bytes long) as a hex string with certain separator. For the larger buffers consider to use :c:func:`print_hex_dump`. MAC/FDDI addresses ================== :: %pM 00:01:02:03:04:05 %pMR 05:04:03:02:01:00 %pMF 00-01-02-03-04-05 %pm 000102030405 %pmR 050403020100 For printing 6-byte MAC/FDDI addresses in hex notation. The ``M`` and ``m`` specifiers result in a printed address with (``M``) or without (``m``) byte separators. The default byte separator is the colon (``:``). Where FDDI addresses are concerned the ``F`` specifier can be used after the ``M`` specifier to use dash (``-``) separators instead of the default separator. For Bluetooth addresses the ``R`` specifier shall be used after the ``M`` specifier to use reversed byte order suitable for visual interpretation of Bluetooth addresses which are in the little endian order. Passed by reference. IPv4 addresses ============== :: %pI4 1.2.3.4 %pi4 001.002.003.004 %p[Ii]4[hnbl] For printing IPv4 dot-separated decimal addresses. The ``I4`` and ``i4`` specifiers result in a printed address with (``i4``) or without (``I4``) leading zeros. The additional ``h``, ``n``, ``b``, and ``l`` specifiers are used to specify host, network, big or little endian order addresses respectively. Where no specifier is provided the default network/big endian order is used. Passed by reference. IPv6 addresses ============== :: %pI6 0001:0002:0003:0004:0005:0006:0007:0008 %pi6 00010002000300040005000600070008 %pI6c 1:2:3:4:5:6:7:8 For printing IPv6 network-order 16-bit hex addresses. The ``I6`` and ``i6`` specifiers result in a printed address with (``I6``) or without (``i6``) colon-separators. Leading zeros are always used. The additional ``c`` specifier can be used with the ``I`` specifier to print a compressed IPv6 address as described by http://tools.ietf.org/html/rfc5952 Passed by reference. IPv4/IPv6 addresses (generic, with port, flowinfo, scope) ========================================================= :: %pIS 1.2.3.4 or 0001:0002:0003:0004:0005:0006:0007:0008 %piS 001.002.003.004 or 00010002000300040005000600070008 %pISc 1.2.3.4 or 1:2:3:4:5:6:7:8 %pISpc 1.2.3.4:12345 or [1:2:3:4:5:6:7:8]:12345 %p[Ii]S[pfschnbl] For printing an IP address without the need to distinguish whether it``s of type AF_INET or AF_INET6, a pointer to a valid ``struct sockaddr``, specified through ``IS`` or ``iS``, can be passed to this format specifier. The additional ``p``, ``f``, and ``s`` specifiers are used to specify port (IPv4, IPv6), flowinfo (IPv6) and scope (IPv6). Ports have a ``:`` prefix, flowinfo a ``/`` and scope a ``%``, each followed by the actual value. In case of an IPv6 address the compressed IPv6 address as described by http://tools.ietf.org/html/rfc5952 is being used if the additional specifier ``c`` is given. The IPv6 address is surrounded by ``[``, ``]`` in case of additional specifiers ``p``, ``f`` or ``s`` as suggested by https://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-07 In case of IPv4 addresses, the additional ``h``, ``n``, ``b``, and ``l`` specifiers can be used as well and are ignored in case of an IPv6 address. Passed by reference. Further examples:: %pISfc 1.2.3.4 or [1:2:3:4:5:6:7:8]/123456789 %pISsc 1.2.3.4 or [1:2:3:4:5:6:7:8]%1234567890 %pISpfc 1.2.3.4:12345 or [1:2:3:4:5:6:7:8]:12345/123456789 UUID/GUID addresses =================== :: %pUb 00010203-0405-0607-0809-0a0b0c0d0e0f %pUB 00010203-0405-0607-0809-0A0B0C0D0E0F %pUl 03020100-0504-0706-0809-0a0b0c0e0e0f %pUL 03020100-0504-0706-0809-0A0B0C0E0E0F For printing 16-byte UUID/GUIDs addresses. The additional 'l', 'L', 'b' and 'B' specifiers are used to specify a little endian order in lower ('l') or upper case ('L') hex characters - and big endian order in lower ('b') or upper case ('B') hex characters. Where no additional specifiers are used the default big endian order with lower case hex characters will be printed. Passed by reference. dentry names ============ :: %pd{,2,3,4} %pD{,2,3,4} For printing dentry name; if we race with :c:func:`d_move`, the name might be a mix of old and new ones, but it won't oops. ``%pd`` dentry is a safer equivalent of ``%s`` ``dentry->d_name.name`` we used to use, ``%pd<n>`` prints ``n`` last components. ``%pD`` does the same thing for struct file. Passed by reference. block_device names ================== :: %pg sda, sda1 or loop0p1 For printing name of block_device pointers. struct va_format ================ :: %pV For printing struct va_format structures. These contain a format string and va_list as follows:: struct va_format { const char *fmt; va_list *va; }; Implements a "recursive vsnprintf". Do not use this feature without some mechanism to verify the correctness of the format string and va_list arguments. Passed by reference. kobjects ======== :: %pO Base specifier for kobject based structs. Must be followed with character for specific type of kobject as listed below: Device tree nodes: %pOF[fnpPcCF] For printing device tree nodes. The optional arguments are: f device node full_name n device node name p device node phandle P device node path spec (name + @unit) F device node flags c major compatible string C full compatible string Without any arguments prints full_name (same as %pOFf) The separator when using multiple arguments is ':' Examples: %pOF /foo/bar@0 - Node full name %pOFf /foo/bar@0 - Same as above %pOFfp /foo/bar@0:10 - Node full name + phandle %pOFfcF /foo/bar@0:foo,device:--P- - Node full name + major compatible string + node flags D - dynamic d - detached P - Populated B - Populated bus Passed by reference. struct clk ========== :: %pC pll1 %pCn pll1 For printing struct clk structures. ``%pC`` and ``%pCn`` print the name (Common Clock Framework) or address (legacy clock framework) of the structure. Passed by reference. bitmap and its derivatives such as cpumask and nodemask ======================================================= :: %*pb 0779 %*pbl 0,3-6,8-10 For printing bitmap and its derivatives such as cpumask and nodemask, ``%*pb`` output the bitmap with field width as the number of bits and ``%*pbl`` output the bitmap as range list with field width as the number of bits. Passed by reference. Flags bitfields such as page flags, gfp_flags ============================================= :: %pGp referenced|uptodate|lru|active|private %pGg GFP_USER|GFP_DMA32|GFP_NOWARN %pGv read|exec|mayread|maywrite|mayexec|denywrite For printing flags bitfields as a collection of symbolic constants that would construct the value. The type of flags is given by the third character. Currently supported are [p]age flags, [v]ma_flags (both expect ``unsigned long *``) and [g]fp_flags (expects ``gfp_t *``). The flag names and print order depends on the particular type. Note that this format should not be used directly in :c:func:`TP_printk()` part of a tracepoint. Instead, use the ``show_*_flags()`` functions from <trace/events/mmflags.h>. Passed by reference. Network device features ======================= :: %pNF 0x000000000000c000 For printing netdev_features_t. Passed by reference. If you add other ``%p`` extensions, please extend lib/test_printf.c with one or more test cases, if at all feasible. Thank you for your cooperation and attention.