0001 .. SPDX-License-Identifier: GPL-2.0
0002
0003 .. _deprecated:
0004
0005 =====================================================================
0006 Deprecated Interfaces, Language Features, Attributes, and Conventions
0007 =====================================================================
0008
0009 In a perfect world, it would be possible to convert all instances of
0010 some deprecated API into the new API and entirely remove the old API in
0011 a single development cycle. However, due to the size of the kernel, the
0012 maintainership hierarchy, and timing, it's not always feasible to do these
0013 kinds of conversions at once. This means that new instances may sneak into
0014 the kernel while old ones are being removed, only making the amount of
0015 work to remove the API grow. In order to educate developers about what
0016 has been deprecated and why, this list has been created as a place to
0017 point when uses of deprecated things are proposed for inclusion in the
0018 kernel.
0019
0020 __deprecated
0021 ------------
0022 While this attribute does visually mark an interface as deprecated,
0023 it `does not produce warnings during builds any more
0024 <https://git.kernel.org/linus/771c035372a036f83353eef46dbb829780330234>`_
0025 because one of the standing goals of the kernel is to build without
0026 warnings and no one was actually doing anything to remove these deprecated
0027 interfaces. While using `__deprecated` is nice to note an old API in
0028 a header file, it isn't the full solution. Such interfaces must either
0029 be fully removed from the kernel, or added to this file to discourage
0030 others from using them in the future.
0031
0032 BUG() and BUG_ON()
0033 ------------------
0034 Use WARN() and WARN_ON() instead, and handle the "impossible"
0035 error condition as gracefully as possible. While the BUG()-family
0036 of APIs were originally designed to act as an "impossible situation"
0037 assert and to kill a kernel thread "safely", they turn out to just be
0038 too risky. (e.g. "In what order do locks need to be released? Have
0039 various states been restored?") Very commonly, using BUG() will
0040 destabilize a system or entirely break it, which makes it impossible
0041 to debug or even get viable crash reports. Linus has `very strong
0042 <https://lore.kernel.org/lkml/CA+55aFy6jNLsywVYdGp83AMrXBo_P-pkjkphPGrO=82SPKCpLQ@mail.gmail.com/>`_
0043 feelings `about this
0044 <https://lore.kernel.org/lkml/CAHk-=whDHsbK3HTOpTF=ue_o04onRwTEaK_ZoJp_fjbqq4+=Jw@mail.gmail.com/>`_.
0045
0046 Note that the WARN()-family should only be used for "expected to
0047 be unreachable" situations. If you want to warn about "reachable
0048 but undesirable" situations, please use the pr_warn()-family of
0049 functions. System owners may have set the *panic_on_warn* sysctl,
0050 to make sure their systems do not continue running in the face of
0051 "unreachable" conditions. (For example, see commits like `this one
0052 <https://git.kernel.org/linus/d4689846881d160a4d12a514e991a740bcb5d65a>`_.)
0053
0054 open-coded arithmetic in allocator arguments
0055 --------------------------------------------
0056 Dynamic size calculations (especially multiplication) should not be
0057 performed in memory allocator (or similar) function arguments due to the
0058 risk of them overflowing. This could lead to values wrapping around and a
0059 smaller allocation being made than the caller was expecting. Using those
0060 allocations could lead to linear overflows of heap memory and other
0061 misbehaviors. (One exception to this is literal values where the compiler
0062 can warn if they might overflow. However, the preferred way in these
0063 cases is to refactor the code as suggested below to avoid the open-coded
0064 arithmetic.)
0065
0066 For example, do not use ``count * size`` as an argument, as in::
0067
0068 foo = kmalloc(count * size, GFP_KERNEL);
0069
0070 Instead, the 2-factor form of the allocator should be used::
0071
0072 foo = kmalloc_array(count, size, GFP_KERNEL);
0073
0074 Specifically, kmalloc() can be replaced with kmalloc_array(), and
0075 kzalloc() can be replaced with kcalloc().
0076
0077 If no 2-factor form is available, the saturate-on-overflow helpers should
0078 be used::
0079
0080 bar = vmalloc(array_size(count, size));
0081
0082 Another common case to avoid is calculating the size of a structure with
0083 a trailing array of others structures, as in::
0084
0085 header = kzalloc(sizeof(*header) + count * sizeof(*header->item),
0086 GFP_KERNEL);
0087
0088 Instead, use the helper::
0089
0090 header = kzalloc(struct_size(header, item, count), GFP_KERNEL);
0091
0092 .. note:: If you are using struct_size() on a structure containing a zero-length
0093 or a one-element array as a trailing array member, please refactor such
0094 array usage and switch to a `flexible array member
0095 <#zero-length-and-one-element-arrays>`_ instead.
0096
0097 For other calculations, please compose the use of the size_mul(),
0098 size_add(), and size_sub() helpers. For example, in the case of::
0099
0100 foo = krealloc(current_size + chunk_size * (count - 3), GFP_KERNEL);
0101
0102 Instead, use the helpers::
0103
0104 foo = krealloc(size_add(current_size,
0105 size_mul(chunk_size,
0106 size_sub(count, 3))), GFP_KERNEL);
0107
0108 For more details, also see array3_size() and flex_array_size(),
0109 as well as the related check_mul_overflow(), check_add_overflow(),
0110 check_sub_overflow(), and check_shl_overflow() family of functions.
0111
0112 simple_strtol(), simple_strtoll(), simple_strtoul(), simple_strtoull()
0113 ----------------------------------------------------------------------
0114 The simple_strtol(), simple_strtoll(),
0115 simple_strtoul(), and simple_strtoull() functions
0116 explicitly ignore overflows, which may lead to unexpected results
0117 in callers. The respective kstrtol(), kstrtoll(),
0118 kstrtoul(), and kstrtoull() functions tend to be the
0119 correct replacements, though note that those require the string to be
0120 NUL or newline terminated.
0121
0122 strcpy()
0123 --------
0124 strcpy() performs no bounds checking on the destination buffer. This
0125 could result in linear overflows beyond the end of the buffer, leading to
0126 all kinds of misbehaviors. While `CONFIG_FORTIFY_SOURCE=y` and various
0127 compiler flags help reduce the risk of using this function, there is
0128 no good reason to add new uses of this function. The safe replacement
0129 is strscpy(), though care must be given to any cases where the return
0130 value of strcpy() was used, since strscpy() does not return a pointer to
0131 the destination, but rather a count of non-NUL bytes copied (or negative
0132 errno when it truncates).
0133
0134 strncpy() on NUL-terminated strings
0135 -----------------------------------
0136 Use of strncpy() does not guarantee that the destination buffer will
0137 be NUL terminated. This can lead to various linear read overflows and
0138 other misbehavior due to the missing termination. It also NUL-pads
0139 the destination buffer if the source contents are shorter than the
0140 destination buffer size, which may be a needless performance penalty
0141 for callers using only NUL-terminated strings. The safe replacement is
0142 strscpy(), though care must be given to any cases where the return value
0143 of strncpy() was used, since strscpy() does not return a pointer to the
0144 destination, but rather a count of non-NUL bytes copied (or negative
0145 errno when it truncates). Any cases still needing NUL-padding should
0146 instead use strscpy_pad().
0147
0148 If a caller is using non-NUL-terminated strings, strncpy() can
0149 still be used, but destinations should be marked with the `__nonstring
0150 <https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html>`_
0151 attribute to avoid future compiler warnings.
0152
0153 strlcpy()
0154 ---------
0155 strlcpy() reads the entire source buffer first (since the return value
0156 is meant to match that of strlen()). This read may exceed the destination
0157 size limit. This is both inefficient and can lead to linear read overflows
0158 if a source string is not NUL-terminated. The safe replacement is strscpy(),
0159 though care must be given to any cases where the return value of strlcpy()
0160 is used, since strscpy() will return negative errno values when it truncates.
0161
0162 %p format specifier
0163 -------------------
0164 Traditionally, using "%p" in format strings would lead to regular address
0165 exposure flaws in dmesg, proc, sysfs, etc. Instead of leaving these to
0166 be exploitable, all "%p" uses in the kernel are being printed as a hashed
0167 value, rendering them unusable for addressing. New uses of "%p" should not
0168 be added to the kernel. For text addresses, using "%pS" is likely better,
0169 as it produces the more useful symbol name instead. For nearly everything
0170 else, just do not add "%p" at all.
0171
0172 Paraphrasing Linus's current `guidance <https://lore.kernel.org/lkml/CA+55aFwQEd_d40g4mUCSsVRZzrFPUJt74vc6PPpb675hYNXcKw@mail.gmail.com/>`_:
0173
0174 - If the hashed "%p" value is pointless, ask yourself whether the pointer
0175 itself is important. Maybe it should be removed entirely?
0176 - If you really think the true pointer value is important, why is some
0177 system state or user privilege level considered "special"? If you think
0178 you can justify it (in comments and commit log) well enough to stand
0179 up to Linus's scrutiny, maybe you can use "%px", along with making sure
0180 you have sensible permissions.
0181
0182 If you are debugging something where "%p" hashing is causing problems,
0183 you can temporarily boot with the debug flag "`no_hash_pointers
0184 <https://git.kernel.org/linus/5ead723a20e0447bc7db33dc3070b420e5f80aa6>`_".
0185
0186 Variable Length Arrays (VLAs)
0187 -----------------------------
0188 Using stack VLAs produces much worse machine code than statically
0189 sized stack arrays. While these non-trivial `performance issues
0190 <https://git.kernel.org/linus/02361bc77888>`_ are reason enough to
0191 eliminate VLAs, they are also a security risk. Dynamic growth of a stack
0192 array may exceed the remaining memory in the stack segment. This could
0193 lead to a crash, possible overwriting sensitive contents at the end of the
0194 stack (when built without `CONFIG_THREAD_INFO_IN_TASK=y`), or overwriting
0195 memory adjacent to the stack (when built without `CONFIG_VMAP_STACK=y`)
0196
0197 Implicit switch case fall-through
0198 ---------------------------------
0199 The C language allows switch cases to fall through to the next case
0200 when a "break" statement is missing at the end of a case. This, however,
0201 introduces ambiguity in the code, as it's not always clear if the missing
0202 break is intentional or a bug. For example, it's not obvious just from
0203 looking at the code if `STATE_ONE` is intentionally designed to fall
0204 through into `STATE_TWO`::
0205
0206 switch (value) {
0207 case STATE_ONE:
0208 do_something();
0209 case STATE_TWO:
0210 do_other();
0211 break;
0212 default:
0213 WARN("unknown state");
0214 }
0215
0216 As there have been a long list of flaws `due to missing "break" statements
0217 <https://cwe.mitre.org/data/definitions/484.html>`_, we no longer allow
0218 implicit fall-through. In order to identify intentional fall-through
0219 cases, we have adopted a pseudo-keyword macro "fallthrough" which
0220 expands to gcc's extension `__attribute__((__fallthrough__))
0221 <https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html>`_.
0222 (When the C17/C18 `[[fallthrough]]` syntax is more commonly supported by
0223 C compilers, static analyzers, and IDEs, we can switch to using that syntax
0224 for the macro pseudo-keyword.)
0225
0226 All switch/case blocks must end in one of:
0227
0228 * break;
0229 * fallthrough;
0230 * continue;
0231 * goto <label>;
0232 * return [expression];
0233
0234 Zero-length and one-element arrays
0235 ----------------------------------
0236 There is a regular need in the kernel to provide a way to declare having
0237 a dynamically sized set of trailing elements in a structure. Kernel code
0238 should always use `"flexible array members" <https://en.wikipedia.org/wiki/Flexible_array_member>`_
0239 for these cases. The older style of one-element or zero-length arrays should
0240 no longer be used.
0241
0242 In older C code, dynamically sized trailing elements were done by specifying
0243 a one-element array at the end of a structure::
0244
0245 struct something {
0246 size_t count;
0247 struct foo items[1];
0248 };
0249
0250 This led to fragile size calculations via sizeof() (which would need to
0251 remove the size of the single trailing element to get a correct size of
0252 the "header"). A `GNU C extension <https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_
0253 was introduced to allow for zero-length arrays, to avoid these kinds of
0254 size problems::
0255
0256 struct something {
0257 size_t count;
0258 struct foo items[0];
0259 };
0260
0261 But this led to other problems, and didn't solve some problems shared by
0262 both styles, like not being able to detect when such an array is accidentally
0263 being used _not_ at the end of a structure (which could happen directly, or
0264 when such a struct was in unions, structs of structs, etc).
0265
0266 C99 introduced "flexible array members", which lacks a numeric size for
0267 the array declaration entirely::
0268
0269 struct something {
0270 size_t count;
0271 struct foo items[];
0272 };
0273
0274 This is the way the kernel expects dynamically sized trailing elements
0275 to be declared. It allows the compiler to generate errors when the
0276 flexible array does not occur last in the structure, which helps to prevent
0277 some kind of `undefined behavior
0278 <https://git.kernel.org/linus/76497732932f15e7323dc805e8ea8dc11bb587cf>`_
0279 bugs from being inadvertently introduced to the codebase. It also allows
0280 the compiler to correctly analyze array sizes (via sizeof(),
0281 `CONFIG_FORTIFY_SOURCE`, and `CONFIG_UBSAN_BOUNDS`). For instance,
0282 there is no mechanism that warns us that the following application of the
0283 sizeof() operator to a zero-length array always results in zero::
0284
0285 struct something {
0286 size_t count;
0287 struct foo items[0];
0288 };
0289
0290 struct something *instance;
0291
0292 instance = kmalloc(struct_size(instance, items, count), GFP_KERNEL);
0293 instance->count = count;
0294
0295 size = sizeof(instance->items) * instance->count;
0296 memcpy(instance->items, source, size);
0297
0298 At the last line of code above, ``size`` turns out to be ``zero``, when one might
0299 have thought it represents the total size in bytes of the dynamic memory recently
0300 allocated for the trailing array ``items``. Here are a couple examples of this
0301 issue: `link 1
0302 <https://git.kernel.org/linus/f2cd32a443da694ac4e28fbf4ac6f9d5cc63a539>`_,
0303 `link 2
0304 <https://git.kernel.org/linus/ab91c2a89f86be2898cee208d492816ec238b2cf>`_.
0305 Instead, `flexible array members have incomplete type, and so the sizeof()
0306 operator may not be applied <https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_,
0307 so any misuse of such operators will be immediately noticed at build time.
0308
0309 With respect to one-element arrays, one has to be acutely aware that `such arrays
0310 occupy at least as much space as a single object of the type
0311 <https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_,
0312 hence they contribute to the size of the enclosing structure. This is prone
0313 to error every time people want to calculate the total size of dynamic memory
0314 to allocate for a structure containing an array of this kind as a member::
0315
0316 struct something {
0317 size_t count;
0318 struct foo items[1];
0319 };
0320
0321 struct something *instance;
0322
0323 instance = kmalloc(struct_size(instance, items, count - 1), GFP_KERNEL);
0324 instance->count = count;
0325
0326 size = sizeof(instance->items) * instance->count;
0327 memcpy(instance->items, source, size);
0328
0329 In the example above, we had to remember to calculate ``count - 1`` when using
0330 the struct_size() helper, otherwise we would have --unintentionally-- allocated
0331 memory for one too many ``items`` objects. The cleanest and least error-prone way
0332 to implement this is through the use of a `flexible array member`, together with
0333 struct_size() and flex_array_size() helpers::
0334
0335 struct something {
0336 size_t count;
0337 struct foo items[];
0338 };
0339
0340 struct something *instance;
0341
0342 instance = kmalloc(struct_size(instance, items, count), GFP_KERNEL);
0343 instance->count = count;
0344
0345 memcpy(instance->items, source, flex_array_size(instance, items, instance->count));