xref: /linux/Documentation/process/deprecated.rst (revision fec61ff40b9e2a2439332eaca498aebe4eb5e056)
1.. SPDX-License-Identifier: GPL-2.0
2
3.. _deprecated:
4
5=====================================================================
6Deprecated Interfaces, Language Features, Attributes, and Conventions
7=====================================================================
8
9In a perfect world, it would be possible to convert all instances of
10some deprecated API into the new API and entirely remove the old API in
11a single development cycle. However, due to the size of the kernel, the
12maintainership hierarchy, and timing, it's not always feasible to do these
13kinds of conversions at once. This means that new instances may sneak into
14the kernel while old ones are being removed, only making the amount of
15work to remove the API grow. In order to educate developers about what
16has been deprecated and why, this list has been created as a place to
17point when uses of deprecated things are proposed for inclusion in the
18kernel.
19
20__deprecated
21------------
22While this attribute does visually mark an interface as deprecated,
23it `does not produce warnings during builds any more
24<https://git.kernel.org/linus/771c035372a036f83353eef46dbb829780330234>`_
25because one of the standing goals of the kernel is to build without
26warnings and no one was actually doing anything to remove these deprecated
27interfaces. While using `__deprecated` is nice to note an old API in
28a header file, it isn't the full solution. Such interfaces must either
29be fully removed from the kernel, or added to this file to discourage
30others from using them in the future.
31
32BUG() and BUG_ON()
33------------------
34Use WARN() and WARN_ON() instead, and handle the "impossible"
35error condition as gracefully as possible. While the BUG()-family
36of APIs were originally designed to act as an "impossible situation"
37assert and to kill a kernel thread "safely", they turn out to just be
38too risky. (e.g. "In what order do locks need to be released? Have
39various states been restored?") Very commonly, using BUG() will
40destabilize a system or entirely break it, which makes it impossible
41to debug or even get viable crash reports. Linus has `very strong
42<https://lore.kernel.org/lkml/CA+55aFy6jNLsywVYdGp83AMrXBo_P-pkjkphPGrO=82SPKCpLQ@mail.gmail.com/>`_
43feelings `about this
44<https://lore.kernel.org/lkml/CAHk-=whDHsbK3HTOpTF=ue_o04onRwTEaK_ZoJp_fjbqq4+=Jw@mail.gmail.com/>`_.
45
46Note that the WARN()-family should only be used for "expected to
47be unreachable" situations. If you want to warn about "reachable
48but undesirable" situations, please use the pr_warn()-family of
49functions. System owners may have set the *panic_on_warn* sysctl,
50to make sure their systems do not continue running in the face of
51"unreachable" conditions. (For example, see commits like `this one
52<https://git.kernel.org/linus/d4689846881d160a4d12a514e991a740bcb5d65a>`_.)
53
54uninitialized_var()
55-------------------
56For any compiler warnings about uninitialized variables, just add
57an initializer. Using the uninitialized_var() macro (or similar
58warning-silencing tricks) is dangerous as it papers over `real bugs
59<https://lore.kernel.org/lkml/20200603174714.192027-1-glider@google.com/>`_
60(or can in the future), and suppresses unrelated compiler warnings
61(e.g. "unused variable"). If the compiler thinks it is uninitialized,
62either simply initialize the variable or make compiler changes. Keep in
63mind that in most cases, if an initialization is obviously redundant,
64the compiler's dead-store elimination pass will make sure there are no
65needless variable writes.
66
67As Linus has said, this macro
68`must <https://lore.kernel.org/lkml/CA+55aFw+Vbj0i=1TGqCR5vQkCzWJ0QxK6CernOU6eedsudAixw@mail.gmail.com/>`_
69`be <https://lore.kernel.org/lkml/CA+55aFwgbgqhbp1fkxvRKEpzyR5J8n1vKT1VZdz9knmPuXhOeg@mail.gmail.com/>`_
70`removed <https://lore.kernel.org/lkml/CA+55aFz2500WfbKXAx8s67wrm9=yVJu65TpLgN_ybYNv0VEOKA@mail.gmail.com/>`_.
71
72open-coded arithmetic in allocator arguments
73--------------------------------------------
74Dynamic size calculations (especially multiplication) should not be
75performed in memory allocator (or similar) function arguments due to the
76risk of them overflowing. This could lead to values wrapping around and a
77smaller allocation being made than the caller was expecting. Using those
78allocations could lead to linear overflows of heap memory and other
79misbehaviors. (One exception to this is literal values where the compiler
80can warn if they might overflow. Though using literals for arguments as
81suggested below is also harmless.)
82
83For example, do not use ``count * size`` as an argument, as in::
84
85	foo = kmalloc(count * size, GFP_KERNEL);
86
87Instead, the 2-factor form of the allocator should be used::
88
89	foo = kmalloc_array(count, size, GFP_KERNEL);
90
91If no 2-factor form is available, the saturate-on-overflow helpers should
92be used::
93
94	bar = vmalloc(array_size(count, size));
95
96Another common case to avoid is calculating the size of a structure with
97a trailing array of others structures, as in::
98
99	header = kzalloc(sizeof(*header) + count * sizeof(*header->item),
100			 GFP_KERNEL);
101
102Instead, use the helper::
103
104	header = kzalloc(struct_size(header, item, count), GFP_KERNEL);
105
106See array_size(), array3_size(), and struct_size(),
107for more details as well as the related check_add_overflow() and
108check_mul_overflow() family of functions.
109
110simple_strtol(), simple_strtoll(), simple_strtoul(), simple_strtoull()
111----------------------------------------------------------------------
112The simple_strtol(), simple_strtoll(),
113simple_strtoul(), and simple_strtoull() functions
114explicitly ignore overflows, which may lead to unexpected results
115in callers. The respective kstrtol(), kstrtoll(),
116kstrtoul(), and kstrtoull() functions tend to be the
117correct replacements, though note that those require the string to be
118NUL or newline terminated.
119
120strcpy()
121--------
122strcpy() performs no bounds checking on the destination
123buffer. This could result in linear overflows beyond the
124end of the buffer, leading to all kinds of misbehaviors. While
125`CONFIG_FORTIFY_SOURCE=y` and various compiler flags help reduce the
126risk of using this function, there is no good reason to add new uses of
127this function. The safe replacement is strscpy().
128
129strncpy() on NUL-terminated strings
130-----------------------------------
131Use of strncpy() does not guarantee that the destination buffer
132will be NUL terminated. This can lead to various linear read overflows
133and other misbehavior due to the missing termination. It also NUL-pads the
134destination buffer if the source contents are shorter than the destination
135buffer size, which may be a needless performance penalty for callers using
136only NUL-terminated strings. The safe replacement is strscpy().
137(Users of strscpy() still needing NUL-padding should instead
138use strscpy_pad().)
139
140If a caller is using non-NUL-terminated strings, strncpy()() can
141still be used, but destinations should be marked with the `__nonstring
142<https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html>`_
143attribute to avoid future compiler warnings.
144
145strlcpy()
146---------
147strlcpy() reads the entire source buffer first, possibly exceeding
148the given limit of bytes to copy. This is inefficient and can lead to
149linear read overflows if a source string is not NUL-terminated. The
150safe replacement is strscpy().
151
152%p format specifier
153-------------------
154Traditionally, using "%p" in format strings would lead to regular address
155exposure flaws in dmesg, proc, sysfs, etc. Instead of leaving these to
156be exploitable, all "%p" uses in the kernel are being printed as a hashed
157value, rendering them unusable for addressing. New uses of "%p" should not
158be added to the kernel. For text addresses, using "%pS" is likely better,
159as it produces the more useful symbol name instead. For nearly everything
160else, just do not add "%p" at all.
161
162Paraphrasing Linus's current `guidance <https://lore.kernel.org/lkml/CA+55aFwQEd_d40g4mUCSsVRZzrFPUJt74vc6PPpb675hYNXcKw@mail.gmail.com/>`_:
163
164- If the hashed "%p" value is pointless, ask yourself whether the pointer
165  itself is important. Maybe it should be removed entirely?
166- If you really think the true pointer value is important, why is some
167  system state or user privilege level considered "special"? If you think
168  you can justify it (in comments and commit log) well enough to stand
169  up to Linus's scrutiny, maybe you can use "%px", along with making sure
170  you have sensible permissions.
171
172And finally, know that a toggle for "%p" hashing will `not be accepted <https://lore.kernel.org/lkml/CA+55aFwieC1-nAs+NFq9RTwaR8ef9hWa4MjNBWL41F-8wM49eA@mail.gmail.com/>`_.
173
174Variable Length Arrays (VLAs)
175-----------------------------
176Using stack VLAs produces much worse machine code than statically
177sized stack arrays. While these non-trivial `performance issues
178<https://git.kernel.org/linus/02361bc77888>`_ are reason enough to
179eliminate VLAs, they are also a security risk. Dynamic growth of a stack
180array may exceed the remaining memory in the stack segment. This could
181lead to a crash, possible overwriting sensitive contents at the end of the
182stack (when built without `CONFIG_THREAD_INFO_IN_TASK=y`), or overwriting
183memory adjacent to the stack (when built without `CONFIG_VMAP_STACK=y`)
184
185Implicit switch case fall-through
186---------------------------------
187The C language allows switch cases to fall through to the next case
188when a "break" statement is missing at the end of a case. This, however,
189introduces ambiguity in the code, as it's not always clear if the missing
190break is intentional or a bug. For example, it's not obvious just from
191looking at the code if `STATE_ONE` is intentionally designed to fall
192through into `STATE_TWO`::
193
194	switch (value) {
195	case STATE_ONE:
196		do_something();
197	case STATE_TWO:
198		do_other();
199		break;
200	default:
201		WARN("unknown state");
202	}
203
204As there have been a long list of flaws `due to missing "break" statements
205<https://cwe.mitre.org/data/definitions/484.html>`_, we no longer allow
206implicit fall-through. In order to identify intentional fall-through
207cases, we have adopted a pseudo-keyword macro "fallthrough" which
208expands to gcc's extension `__attribute__((__fallthrough__))
209<https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html>`_.
210(When the C17/C18  `[[fallthrough]]` syntax is more commonly supported by
211C compilers, static analyzers, and IDEs, we can switch to using that syntax
212for the macro pseudo-keyword.)
213
214All switch/case blocks must end in one of:
215
216* break;
217* fallthrough;
218* continue;
219* goto <label>;
220* return [expression];
221