Printk

Last updated

printk is a C function from the Linux kernel interface that prints messages to the kernel log. [1] It accepts a string parameter called the format string, which specifies a method for rendering an arbitrary number of varied data type parameter(s) into a string. [1] The string is then printed to the kernel log. [1]

Contents

It provides a printf-like abstraction and its parsing of the format string and arguments behave similarly to printf. [1] It acts as a debugging tool for kernel programmers who need this function for logging messages from the kernel. [1]

The printk function prototype is:

intprintk(constchar*fmt,...);

C standard library and its printf function are unavailable in kernel mode, hence the need for printk. [2]

Differences from printf

The function printk is based on printf, but cannot always be used in the same way that printf is used. [1]

Log levels

printk allows a caller to specify the type and importance of the message being sent. [1] This specifier is called the log level. [1]

The log level specifies the type of message being sent to the kernel message log. [1] The log level is specified by prepending (using C's string literal concatenation) a string describing the log level to the start of the message to be produced. [1] For example, a message could be produced at the KERN_INFO using the following: [1]

printk(KERN_INFO"Message: %s\n",arg);

The string specifying the log level consists of the ASCII start of the header character followed by a digit describing the log level or the character 'c' to indicate the message is a continuation of the previous message. [1] [3] The following log levels, along with their interpretations, are given below. [4]

0KERN_EMERGAn emergency condition; the system is probably dead
1KERN_ALERTA problem that requires immediate attention
2KERN_CRITA critical condition
3KERN_ERRAn error
4KERN_WARNINGA warning
5KERN_NOTICEA normal, but perhaps noteworthy, condition
6KERN_INFOAn informational message
7KERN_DEBUGA debug message, typically superfluous

When a log level is not specified, the default log level is KERN_WARNING, [1] unless a different default has been set in the kernel itself, such as with the loglevel= boot argument. [5]

Log levels are defined in <linux/kern_levels.h>. [3] Which log levels are printed is configured using the sysctl file /proc/sys/kernel/printk. [1]

Pointer formats

The %p format specifier (used for printing pointers in printf) is extended to add additional formatting modes, for example, requesting to print a struct sockaddr * using %pISpc would print an IPv4/v6 address and port in a human-friendly format (e.g. "1.2.3.4:12345" or "[1:2:3:4:5:6:7:8]:12345"). [6]

No floating point support

While printf supports output of floating point numbers, printk does not, [6] since the Linux kernel does not use floating point numbers within the kernel. [7]

Description

The function tries to lock the semaphore controlling access to the system console. [1] [8] If it succeeds, the output is logged and the console drivers are called. [1] If it is not possible to acquire the semaphore the output is placed into the log buffer, and the current holder of the console semaphore will notice the new output when they release the console semaphore and will send the buffered output to the console before releasing the semaphore. [1]

One effect of this deferred printing is that code which calls printk and then changes the log levels to be printed may break. This is because the log level to be printed is inspected when the actual printing occurs. [1]

The function printk can be called from anywhere in the kernel except during the very early stages of the kernel boot process; when the system console is not initialised. [4] The alternative function early_printk is implemented on some architectures and is used identically to printk during the early stages of the boot process. [4]

Related Research Articles

<span class="mw-page-title-main">GNU Debugger</span> Source-level debugger

The GNU Debugger (GDB) is a portable debugger that runs on many Unix-like systems and works for many programming languages, including Ada, Assembly, C, C++, D, Fortran, Haskell, Go, Objective-C, OpenCL C, Modula-2, Pascal, Rust, and partially others.

A "Hello, World!" program is generally a simple computer program which outputs to the screen a message similar to "Hello, World!" while ignoring any user input. A small piece of code in most general-purpose programming languages, this program is used to illustrate a language's basic syntax. A "Hello, World!" program is often the first written by a student of a new programming language, but such a program can also be used as a sanity check to ensure that the computer software intended to compile or run source code is correctly installed, and that its operator understands how to use it.

x86 assembly language is the name for the family of assembly languages which provide some level of backward compatibility with CPUs back to the Intel 8008 microprocessor, which was launched in April 1972. It is used to produce object code for the x86 class of processors.

In computer programming, standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr). Originally I/O happened via a physically connected system console, but standard streams abstract this. When a command is executed via an interactive shell, the streams are typically connected to the text terminal on which the shell is running, but can be changed with redirection or a pipeline. More generally, a child process inherits the standard streams of its parent process.

<span class="mw-page-title-main">Kernel panic</span> Fatal error condition associated with Unix-like computer operating systems

A kernel panic is a safety measure taken by an operating system's kernel upon detecting an internal fatal error in which either it is unable to safely recover or continuing to run the system would have a higher risk of major data loss. The term is largely specific to Unix and Unix-like systems. The equivalent on Microsoft Windows operating systems is a stop error, often called a "blue screen of death".

The C standard library or libc is the standard library for the C programming language, as specified in the ISO C standard. Starting from the original ANSI C standard, it was developed at the same time as the C library POSIX specification, which is a superset of it. Since ANSI C was adopted by the International Organization for Standardization, the C standard library is also called the ISO C library.

The printf family of functions in the C programming language are a set of functions that take a format string as input among a variable sized list of other values and produce as output a string that corresponds to the format specifier and given input values. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data to characters. The design has been copied to expose similar functionality in other programming languages.

Uncontrolled format string is a type of code injection vulnerability discovered around 1989 that can be used in security exploits. Originally thought harmless, format string exploits can be used to crash a program or to execute harmful code. The problem stems from the use of unchecked user input as the format string parameter in certain C functions that perform formatting, such as printf . A malicious user may use the %s and %x format tokens, among others, to print data from the call stack or possibly other locations in memory. One may also write arbitrary data to arbitrary locations using the %n format token, which commands printf and similar functions to write the number of bytes formatted to an address stored on the stack.

In computing, gettext is an internationalization and localization system commonly used for writing multilingual programs on Unix-like computer operating systems. One of the main benefits of gettext is that it separates programming from translating. The most commonly used implementation of gettext is GNU gettext, released by the GNU Project in 1995. The runtime library is libintl. gettext provides an option to use different strings for any number of plural forms of nouns, but this feature has no support for grammatical gender. The main filename extensions used by this system are .POT, .PO and .MO.

Address space layout randomization (ASLR) is a computer security technique involved in preventing exploitation of memory corruption vulnerabilities. In order to prevent an attacker from reliably redirecting code execution to, for example, a particular exploited function in memory, ASLR randomly arranges the address space positions of key data areas of a process, including the base of the executable and the positions of the stack, heap and libraries.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

Format is a function in Common Lisp that can produce formatted text using a format string similar to the printf format string. It provides more functionality than printf, allowing the user to output numbers in various formats, apply certain format specifiers only under certain conditions, iterate over data structures, output data tabularly, and even recurse, calling format internally to handle data structures that include their own preferred formatting strings. This functionally originates in MIT's Lisp Machine Lisp, where it was based on Multics ioa_.

The magic SysRq key is a key combination understood by the Linux kernel, which allows the user to perform various low-level commands regardless of the system's state. It is often used to recover from freezes, or to reboot a computer without corrupting the filesystem. Its effect is similar to the computer's hardware reset button but with many more options and much more control.

dmesg is a command on most Unix-like operating systems that prints the message buffer of the kernel. The output includes messages produced by the device drivers.

A scanf format string is a control parameter used in various functions to specify the layout of an input string. The functions can then divide the string and translate into values of appropriate data types. String scanning functions are often supplied in standard libraries. Scanf is a function that reads formatted data from the standard input string, which is usually the keyboard and writes the results whenever called in the specified arguments.

stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. It provides facilities for stepping through a list of function arguments of unknown number and type. C++ provides this functionality in the header cstdarg.

The Linux booting process involves multiple stages and is in many ways similar to the BSD and other Unix-style boot processes, from which it derives. Although the Linux booting process depends very much on the computer architecture, those architectures share similar stages and software components, including system startup, bootloader execution, loading and startup of a Linux kernel image, and execution of various startup scripts and daemons. Those are grouped into 4 steps: system startup, bootloader stage, kernel stage, and init process. When a Linux system is powered up or reset, its processor will execute a specific firmware/program for system initialization, such as Power-on self-test, invoking the reset vector to start a program at a known address in flash/ROM, then load the bootloader into RAM for later execution. In personal computer (PC), not only limited to Linux-distro PC, this firmware/program is called BIOS, which is stored in the mainboard. In embedded Linux system, this firmware/program is called boot ROM. After being loaded into RAM, bootloader will execute to load the second-stage bootloader. The second-stage bootloader will load the kernel image into memory, decompress and initialize it then pass control to this kernel image. Second-stage bootloader also performs several operation on the system such as system hardware check, mounting the root device, loading the necessary kernel modules, etc. Finally, the very first user-space process starts, and other high-level system initializations are performed.

printf (Unix) Standard UNIX utility

In Unix and Unix-like operating systems, printf is a shell builtin that formats and prints data.

<span class="mw-page-title-main">Linux console</span> Console of the Linux kernel

The Linux console is a system console internal to the Linux kernel. A system console is the device which receives all kernel messages and warnings and which allows logins in single user mode. The Linux console provides a way for the kernel and other processes to send text output to the user, and to receive text input from the user. The user typically enters text with a computer keyboard and reads the output text on a computer monitor. The Linux kernel supports virtual consoles – consoles that are logically separate, but which access the same physical keyboard and display. The Linux console are implemented by the VT subsystem of the Linux kernel, and do not rely on any user space software. This is in contrast to a terminal emulator, which is a user space process that emulates a terminal, and is typically used in a graphical display environment.

In computer programming, string interpolation is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing or, in formal terms, a form of quasi-quotation. The placeholder may be a variable name, or in some languages an arbitrary expression, in either case evaluated in the current context.

References

  1. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 "Message logging with printk — The Linux Kernel documentation". www.kernel.org. Retrieved 2020-09-09.
  2. ISO/IEC 9899:2018. International Standards Organization. 2018.
  3. 1 2 "kern_levels.h". GitHub. Retrieved 2020-09-27.
  4. 1 2 3 "printk()". archive.is. 2007-08-30. Archived from the original on 2007-08-30. Retrieved 2020-09-09.
  5. "The kernel's command-line parameters". kernel.org. Retrieved 2023-09-27.
  6. 1 2 "How to get printk format specifiers right — The Linux Kernel documentation". www.kernel.org. Retrieved 2020-09-09.
  7. "Re: Linux kernel and floating point". www.redhat.com. Retrieved 2020-09-09.
  8. "Driver Basics — The Linux Kernel documentation". www.kernel.org. Retrieved 2020-09-09.