184253c8bSKees Cook.. SPDX-License-Identifier: GPL-2.0
284253c8bSKees Cook
398348577SFederico Vaga.. _deprecated:
498348577SFederico Vaga
584253c8bSKees Cook=====================================================================
684253c8bSKees CookDeprecated Interfaces, Language Features, Attributes, and Conventions
784253c8bSKees Cook=====================================================================
884253c8bSKees Cook
984253c8bSKees CookIn a perfect world, it would be possible to convert all instances of
1084253c8bSKees Cooksome deprecated API into the new API and entirely remove the old API in
1184253c8bSKees Cooka single development cycle. However, due to the size of the kernel, the
1284253c8bSKees Cookmaintainership hierarchy, and timing, it's not always feasible to do these
1384253c8bSKees Cookkinds of conversions at once. This means that new instances may sneak into
1484253c8bSKees Cookthe kernel while old ones are being removed, only making the amount of
1584253c8bSKees Cookwork to remove the API grow. In order to educate developers about what
1684253c8bSKees Cookhas been deprecated and why, this list has been created as a place to
1784253c8bSKees Cookpoint when uses of deprecated things are proposed for inclusion in the
1884253c8bSKees Cookkernel.
1984253c8bSKees Cook
2084253c8bSKees Cook__deprecated
2184253c8bSKees Cook------------
2284253c8bSKees CookWhile this attribute does visually mark an interface as deprecated,
2384253c8bSKees Cookit `does not produce warnings during builds any more
2484253c8bSKees Cook<https://git.kernel.org/linus/771c035372a036f83353eef46dbb829780330234>`_
2584253c8bSKees Cookbecause one of the standing goals of the kernel is to build without
2684253c8bSKees Cookwarnings and no one was actually doing anything to remove these deprecated
2784253c8bSKees Cookinterfaces. While using `__deprecated` is nice to note an old API in
2884253c8bSKees Cooka header file, it isn't the full solution. Such interfaces must either
2984253c8bSKees Cookbe fully removed from the kernel, or added to this file to discourage
3084253c8bSKees Cookothers from using them in the future.
3184253c8bSKees Cook
327af51678SKees CookBUG() and BUG_ON()
337af51678SKees Cook------------------
347af51678SKees CookUse WARN() and WARN_ON() instead, and handle the "impossible"
357af51678SKees Cookerror condition as gracefully as possible. While the BUG()-family
367af51678SKees Cookof APIs were originally designed to act as an "impossible situation"
377af51678SKees Cookassert and to kill a kernel thread "safely", they turn out to just be
387af51678SKees Cooktoo risky. (e.g. "In what order do locks need to be released? Have
397af51678SKees Cookvarious states been restored?") Very commonly, using BUG() will
407af51678SKees Cookdestabilize a system or entirely break it, which makes it impossible
417af51678SKees Cookto debug or even get viable crash reports. Linus has `very strong
427af51678SKees Cook<https://lore.kernel.org/lkml/CA+55aFy6jNLsywVYdGp83AMrXBo_P-pkjkphPGrO=82SPKCpLQ@mail.gmail.com/>`_
437af51678SKees Cookfeelings `about this
447af51678SKees Cook<https://lore.kernel.org/lkml/CAHk-=whDHsbK3HTOpTF=ue_o04onRwTEaK_ZoJp_fjbqq4+=Jw@mail.gmail.com/>`_.
457af51678SKees Cook
467af51678SKees CookNote that the WARN()-family should only be used for "expected to
477af51678SKees Cookbe unreachable" situations. If you want to warn about "reachable
487af51678SKees Cookbut undesirable" situations, please use the pr_warn()-family of
497af51678SKees Cookfunctions. System owners may have set the *panic_on_warn* sysctl,
507af51678SKees Cookto make sure their systems do not continue running in the face of
517af51678SKees Cook"unreachable" conditions. (For example, see commits like `this one
527af51678SKees Cook<https://git.kernel.org/linus/d4689846881d160a4d12a514e991a740bcb5d65a>`_.)
537af51678SKees Cook
5484253c8bSKees Cookopen-coded arithmetic in allocator arguments
5584253c8bSKees Cook--------------------------------------------
5684253c8bSKees CookDynamic size calculations (especially multiplication) should not be
5784253c8bSKees Cookperformed in memory allocator (or similar) function arguments due to the
5884253c8bSKees Cookrisk of them overflowing. This could lead to values wrapping around and a
5984253c8bSKees Cooksmaller allocation being made than the caller was expecting. Using those
6084253c8bSKees Cookallocations could lead to linear overflows of heap memory and other
6184253c8bSKees Cookmisbehaviors. (One exception to this is literal values where the compiler
623577cdb2SLen Bakercan warn if they might overflow. However, the preferred way in these
633577cdb2SLen Bakercases is to refactor the code as suggested below to avoid the open-coded
643577cdb2SLen Bakerarithmetic.)
6584253c8bSKees Cook
6684253c8bSKees CookFor example, do not use ``count * size`` as an argument, as in::
6784253c8bSKees Cook
6884253c8bSKees Cook	foo = kmalloc(count * size, GFP_KERNEL);
6984253c8bSKees Cook
7084253c8bSKees CookInstead, the 2-factor form of the allocator should be used::
7184253c8bSKees Cook
7284253c8bSKees Cook	foo = kmalloc_array(count, size, GFP_KERNEL);
7384253c8bSKees Cook
74e1be43d9SKees CookSpecifically, kmalloc() can be replaced with kmalloc_array(), and
75e1be43d9SKees Cookkzalloc() can be replaced with kcalloc().
76e1be43d9SKees Cook
7784253c8bSKees CookIf no 2-factor form is available, the saturate-on-overflow helpers should
7884253c8bSKees Cookbe used::
7984253c8bSKees Cook
80*129027b7SChristophe JAILLET	bar = dma_alloc_coherent(dev, array_size(count, size), &dma, GFP_KERNEL);
8184253c8bSKees Cook
8284253c8bSKees CookAnother common case to avoid is calculating the size of a structure with
8384253c8bSKees Cooka trailing array of others structures, as in::
8484253c8bSKees Cook
8584253c8bSKees Cook	header = kzalloc(sizeof(*header) + count * sizeof(*header->item),
8684253c8bSKees Cook			 GFP_KERNEL);
8784253c8bSKees Cook
8884253c8bSKees CookInstead, use the helper::
8984253c8bSKees Cook
9084253c8bSKees Cook	header = kzalloc(struct_size(header, item, count), GFP_KERNEL);
9184253c8bSKees Cook
9268e4cd17SGustavo A. R. Silva.. note:: If you are using struct_size() on a structure containing a zero-length
9368e4cd17SGustavo A. R. Silva        or a one-element array as a trailing array member, please refactor such
9468e4cd17SGustavo A. R. Silva        array usage and switch to a `flexible array member
9568e4cd17SGustavo A. R. Silva        <#zero-length-and-one-element-arrays>`_ instead.
9668e4cd17SGustavo A. R. Silva
97e1be43d9SKees CookFor other calculations, please compose the use of the size_mul(),
98e1be43d9SKees Cooksize_add(), and size_sub() helpers. For example, in the case of::
99e1be43d9SKees Cook
100e1be43d9SKees Cook	foo = krealloc(current_size + chunk_size * (count - 3), GFP_KERNEL);
101e1be43d9SKees Cook
102e1be43d9SKees CookInstead, use the helpers::
103e1be43d9SKees Cook
104e1be43d9SKees Cook	foo = krealloc(size_add(current_size,
105e1be43d9SKees Cook				size_mul(chunk_size,
106e1be43d9SKees Cook					 size_sub(count, 3))), GFP_KERNEL);
107e1be43d9SKees Cook
108e1be43d9SKees CookFor more details, also see array3_size() and flex_array_size(),
109e1be43d9SKees Cookas well as the related check_mul_overflow(), check_add_overflow(),
110e1be43d9SKees Cookcheck_sub_overflow(), and check_shl_overflow() family of functions.
11184253c8bSKees Cook
11284253c8bSKees Cooksimple_strtol(), simple_strtoll(), simple_strtoul(), simple_strtoull()
11384253c8bSKees Cook----------------------------------------------------------------------
1147929b983SJonathan CorbetThe simple_strtol(), simple_strtoll(),
1157929b983SJonathan Corbetsimple_strtoul(), and simple_strtoull() functions
11684253c8bSKees Cookexplicitly ignore overflows, which may lead to unexpected results
1177929b983SJonathan Corbetin callers. The respective kstrtol(), kstrtoll(),
1187929b983SJonathan Corbetkstrtoul(), and kstrtoull() functions tend to be the
11984253c8bSKees Cookcorrect replacements, though note that those require the string to be
12084253c8bSKees CookNUL or newline terminated.
12184253c8bSKees Cook
12284253c8bSKees Cookstrcpy()
12384253c8bSKees Cook--------
12427def953SKees Cookstrcpy() performs no bounds checking on the destination buffer. This
12527def953SKees Cookcould result in linear overflows beyond the end of the buffer, leading to
12627def953SKees Cookall kinds of misbehaviors. While `CONFIG_FORTIFY_SOURCE=y` and various
12727def953SKees Cookcompiler flags help reduce the risk of using this function, there is
12827def953SKees Cookno good reason to add new uses of this function. The safe replacement
12927def953SKees Cookis strscpy(), though care must be given to any cases where the return
13027def953SKees Cookvalue of strcpy() was used, since strscpy() does not return a pointer to
13127def953SKees Cookthe destination, but rather a count of non-NUL bytes copied (or negative
13227def953SKees Cookerrno when it truncates).
13384253c8bSKees Cook
13484253c8bSKees Cookstrncpy() on NUL-terminated strings
13584253c8bSKees Cook-----------------------------------
13627def953SKees CookUse of strncpy() does not guarantee that the destination buffer will
13727def953SKees Cookbe NUL terminated. This can lead to various linear read overflows and
13827def953SKees Cookother misbehavior due to the missing termination. It also NUL-pads
13927def953SKees Cookthe destination buffer if the source contents are shorter than the
14027def953SKees Cookdestination buffer size, which may be a needless performance penalty
141dfbafa70SKees Cookfor callers using only NUL-terminated strings.
142dfbafa70SKees Cook
143dfbafa70SKees CookWhen the destination is required to be NUL-terminated, the replacement is
14427def953SKees Cookstrscpy(), though care must be given to any cases where the return value
14527def953SKees Cookof strncpy() was used, since strscpy() does not return a pointer to the
14627def953SKees Cookdestination, but rather a count of non-NUL bytes copied (or negative
14727def953SKees Cookerrno when it truncates). Any cases still needing NUL-padding should
14827def953SKees Cookinstead use strscpy_pad().
14984253c8bSKees Cook
150dfbafa70SKees CookIf a caller is using non-NUL-terminated strings, strtomem() should be
151dfbafa70SKees Cookused, and the destinations should be marked with the `__nonstring
15284253c8bSKees Cook<https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html>`_
153dfbafa70SKees Cookattribute to avoid future compiler warnings. For cases still needing
154dfbafa70SKees CookNUL-padding, strtomem_pad() can be used.
15584253c8bSKees Cook
15684253c8bSKees Cookstrlcpy()
15784253c8bSKees Cook---------
15827def953SKees Cookstrlcpy() reads the entire source buffer first (since the return value
15927def953SKees Cookis meant to match that of strlen()). This read may exceed the destination
16027def953SKees Cooksize limit. This is both inefficient and can lead to linear read overflows
16127def953SKees Cookif a source string is not NUL-terminated. The safe replacement is strscpy(),
16227def953SKees Cookthough care must be given to any cases where the return value of strlcpy()
16327def953SKees Cookis used, since strscpy() will return negative errno values when it truncates.
16484253c8bSKees Cook
165d8401f50SKees Cook%p format specifier
166d8401f50SKees Cook-------------------
167d8401f50SKees CookTraditionally, using "%p" in format strings would lead to regular address
168d8401f50SKees Cookexposure flaws in dmesg, proc, sysfs, etc. Instead of leaving these to
169d8401f50SKees Cookbe exploitable, all "%p" uses in the kernel are being printed as a hashed
170d8401f50SKees Cookvalue, rendering them unusable for addressing. New uses of "%p" should not
171d8401f50SKees Cookbe added to the kernel. For text addresses, using "%pS" is likely better,
172d8401f50SKees Cookas it produces the more useful symbol name instead. For nearly everything
173d8401f50SKees Cookelse, just do not add "%p" at all.
174d8401f50SKees Cook
175d8401f50SKees CookParaphrasing Linus's current `guidance <https://lore.kernel.org/lkml/CA+55aFwQEd_d40g4mUCSsVRZzrFPUJt74vc6PPpb675hYNXcKw@mail.gmail.com/>`_:
176d8401f50SKees Cook
177d8401f50SKees Cook- If the hashed "%p" value is pointless, ask yourself whether the pointer
178d8401f50SKees Cook  itself is important. Maybe it should be removed entirely?
179d8401f50SKees Cook- If you really think the true pointer value is important, why is some
180d8401f50SKees Cook  system state or user privilege level considered "special"? If you think
181d8401f50SKees Cook  you can justify it (in comments and commit log) well enough to stand
182d8401f50SKees Cook  up to Linus's scrutiny, maybe you can use "%px", along with making sure
183d8401f50SKees Cook  you have sensible permissions.
184d8401f50SKees Cook
1856ab0493dSKees CookIf you are debugging something where "%p" hashing is causing problems,
1866ab0493dSKees Cookyou can temporarily boot with the debug flag "`no_hash_pointers
1876ab0493dSKees Cook<https://git.kernel.org/linus/5ead723a20e0447bc7db33dc3070b420e5f80aa6>`_".
188d8401f50SKees Cook
18984253c8bSKees CookVariable Length Arrays (VLAs)
19084253c8bSKees Cook-----------------------------
19184253c8bSKees CookUsing stack VLAs produces much worse machine code than statically
19284253c8bSKees Cooksized stack arrays. While these non-trivial `performance issues
19384253c8bSKees Cook<https://git.kernel.org/linus/02361bc77888>`_ are reason enough to
19484253c8bSKees Cookeliminate VLAs, they are also a security risk. Dynamic growth of a stack
19584253c8bSKees Cookarray may exceed the remaining memory in the stack segment. This could
19684253c8bSKees Cooklead to a crash, possible overwriting sensitive contents at the end of the
19784253c8bSKees Cookstack (when built without `CONFIG_THREAD_INFO_IN_TASK=y`), or overwriting
19884253c8bSKees Cookmemory adjacent to the stack (when built without `CONFIG_VMAP_STACK=y`)
199a035d552SGustavo A. R. Silva
200a035d552SGustavo A. R. SilvaImplicit switch case fall-through
201a035d552SGustavo A. R. Silva---------------------------------
20276136e02SKees CookThe C language allows switch cases to fall through to the next case
20376136e02SKees Cookwhen a "break" statement is missing at the end of a case. This, however,
20476136e02SKees Cookintroduces ambiguity in the code, as it's not always clear if the missing
20576136e02SKees Cookbreak is intentional or a bug. For example, it's not obvious just from
20676136e02SKees Cooklooking at the code if `STATE_ONE` is intentionally designed to fall
20776136e02SKees Cookthrough into `STATE_TWO`::
20876136e02SKees Cook
20976136e02SKees Cook	switch (value) {
21076136e02SKees Cook	case STATE_ONE:
21176136e02SKees Cook		do_something();
21276136e02SKees Cook	case STATE_TWO:
21376136e02SKees Cook		do_other();
21476136e02SKees Cook		break;
21576136e02SKees Cook	default:
21676136e02SKees Cook		WARN("unknown state");
21776136e02SKees Cook	}
218b9918bdcSJoe Perches
219b9918bdcSJoe PerchesAs there have been a long list of flaws `due to missing "break" statements
220a035d552SGustavo A. R. Silva<https://cwe.mitre.org/data/definitions/484.html>`_, we no longer allow
22176136e02SKees Cookimplicit fall-through. In order to identify intentional fall-through
22276136e02SKees Cookcases, we have adopted a pseudo-keyword macro "fallthrough" which
22376136e02SKees Cookexpands to gcc's extension `__attribute__((__fallthrough__))
22476136e02SKees Cook<https://gcc.gnu.org/onlinedocs/gcc/Statement-Attributes.html>`_.
22576136e02SKees Cook(When the C17/C18  `[[fallthrough]]` syntax is more commonly supported by
226b9918bdcSJoe PerchesC compilers, static analyzers, and IDEs, we can switch to using that syntax
22776136e02SKees Cookfor the macro pseudo-keyword.)
228b9918bdcSJoe Perches
229b9918bdcSJoe PerchesAll switch/case blocks must end in one of:
230b9918bdcSJoe Perches
23176136e02SKees Cook* break;
23276136e02SKees Cook* fallthrough;
23376136e02SKees Cook* continue;
23476136e02SKees Cook* goto <label>;
23576136e02SKees Cook* return [expression];
23668e4cd17SGustavo A. R. Silva
23768e4cd17SGustavo A. R. SilvaZero-length and one-element arrays
23868e4cd17SGustavo A. R. Silva----------------------------------
23968e4cd17SGustavo A. R. SilvaThere is a regular need in the kernel to provide a way to declare having
24068e4cd17SGustavo A. R. Silvaa dynamically sized set of trailing elements in a structure. Kernel code
24168e4cd17SGustavo A. R. Silvashould always use `"flexible array members" <https://en.wikipedia.org/wiki/Flexible_array_member>`_
24268e4cd17SGustavo A. R. Silvafor these cases. The older style of one-element or zero-length arrays should
24368e4cd17SGustavo A. R. Silvano longer be used.
24468e4cd17SGustavo A. R. Silva
24568e4cd17SGustavo A. R. SilvaIn older C code, dynamically sized trailing elements were done by specifying
24668e4cd17SGustavo A. R. Silvaa one-element array at the end of a structure::
24768e4cd17SGustavo A. R. Silva
24868e4cd17SGustavo A. R. Silva        struct something {
24968e4cd17SGustavo A. R. Silva                size_t count;
25068e4cd17SGustavo A. R. Silva                struct foo items[1];
25168e4cd17SGustavo A. R. Silva        };
25268e4cd17SGustavo A. R. Silva
25368e4cd17SGustavo A. R. SilvaThis led to fragile size calculations via sizeof() (which would need to
25468e4cd17SGustavo A. R. Silvaremove the size of the single trailing element to get a correct size of
25568e4cd17SGustavo A. R. Silvathe "header"). A `GNU C extension <https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_
25668e4cd17SGustavo A. R. Silvawas introduced to allow for zero-length arrays, to avoid these kinds of
25768e4cd17SGustavo A. R. Silvasize problems::
25868e4cd17SGustavo A. R. Silva
25968e4cd17SGustavo A. R. Silva        struct something {
26068e4cd17SGustavo A. R. Silva                size_t count;
26168e4cd17SGustavo A. R. Silva                struct foo items[0];
26268e4cd17SGustavo A. R. Silva        };
26368e4cd17SGustavo A. R. Silva
26468e4cd17SGustavo A. R. SilvaBut this led to other problems, and didn't solve some problems shared by
26568e4cd17SGustavo A. R. Silvaboth styles, like not being able to detect when such an array is accidentally
26668e4cd17SGustavo A. R. Silvabeing used _not_ at the end of a structure (which could happen directly, or
26768e4cd17SGustavo A. R. Silvawhen such a struct was in unions, structs of structs, etc).
26868e4cd17SGustavo A. R. Silva
26968e4cd17SGustavo A. R. SilvaC99 introduced "flexible array members", which lacks a numeric size for
27068e4cd17SGustavo A. R. Silvathe array declaration entirely::
27168e4cd17SGustavo A. R. Silva
27268e4cd17SGustavo A. R. Silva        struct something {
27368e4cd17SGustavo A. R. Silva                size_t count;
27468e4cd17SGustavo A. R. Silva                struct foo items[];
27568e4cd17SGustavo A. R. Silva        };
27668e4cd17SGustavo A. R. Silva
27768e4cd17SGustavo A. R. SilvaThis is the way the kernel expects dynamically sized trailing elements
27868e4cd17SGustavo A. R. Silvato be declared. It allows the compiler to generate errors when the
27968e4cd17SGustavo A. R. Silvaflexible array does not occur last in the structure, which helps to prevent
28068e4cd17SGustavo A. R. Silvasome kind of `undefined behavior
28168e4cd17SGustavo A. R. Silva<https://git.kernel.org/linus/76497732932f15e7323dc805e8ea8dc11bb587cf>`_
28268e4cd17SGustavo A. R. Silvabugs from being inadvertently introduced to the codebase. It also allows
28368e4cd17SGustavo A. R. Silvathe compiler to correctly analyze array sizes (via sizeof(),
28468e4cd17SGustavo A. R. Silva`CONFIG_FORTIFY_SOURCE`, and `CONFIG_UBSAN_BOUNDS`). For instance,
28568e4cd17SGustavo A. R. Silvathere is no mechanism that warns us that the following application of the
28668e4cd17SGustavo A. R. Silvasizeof() operator to a zero-length array always results in zero::
28768e4cd17SGustavo A. R. Silva
28868e4cd17SGustavo A. R. Silva        struct something {
28968e4cd17SGustavo A. R. Silva                size_t count;
29068e4cd17SGustavo A. R. Silva                struct foo items[0];
29168e4cd17SGustavo A. R. Silva        };
29268e4cd17SGustavo A. R. Silva
29368e4cd17SGustavo A. R. Silva        struct something *instance;
29468e4cd17SGustavo A. R. Silva
29568e4cd17SGustavo A. R. Silva        instance = kmalloc(struct_size(instance, items, count), GFP_KERNEL);
29668e4cd17SGustavo A. R. Silva        instance->count = count;
29768e4cd17SGustavo A. R. Silva
29868e4cd17SGustavo A. R. Silva        size = sizeof(instance->items) * instance->count;
29968e4cd17SGustavo A. R. Silva        memcpy(instance->items, source, size);
30068e4cd17SGustavo A. R. Silva
30168e4cd17SGustavo A. R. SilvaAt the last line of code above, ``size`` turns out to be ``zero``, when one might
30268e4cd17SGustavo A. R. Silvahave thought it represents the total size in bytes of the dynamic memory recently
30368e4cd17SGustavo A. R. Silvaallocated for the trailing array ``items``. Here are a couple examples of this
30468e4cd17SGustavo A. R. Silvaissue: `link 1
30568e4cd17SGustavo A. R. Silva<https://git.kernel.org/linus/f2cd32a443da694ac4e28fbf4ac6f9d5cc63a539>`_,
30668e4cd17SGustavo A. R. Silva`link 2
30768e4cd17SGustavo A. R. Silva<https://git.kernel.org/linus/ab91c2a89f86be2898cee208d492816ec238b2cf>`_.
30868e4cd17SGustavo A. R. SilvaInstead, `flexible array members have incomplete type, and so the sizeof()
30968e4cd17SGustavo A. R. Silvaoperator may not be applied <https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_,
31068e4cd17SGustavo A. R. Silvaso any misuse of such operators will be immediately noticed at build time.
31168e4cd17SGustavo A. R. Silva
31268e4cd17SGustavo A. R. SilvaWith respect to one-element arrays, one has to be acutely aware that `such arrays
31368e4cd17SGustavo A. R. Silvaoccupy at least as much space as a single object of the type
31468e4cd17SGustavo A. R. Silva<https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html>`_,
31568e4cd17SGustavo A. R. Silvahence they contribute to the size of the enclosing structure. This is prone
31668e4cd17SGustavo A. R. Silvato error every time people want to calculate the total size of dynamic memory
31768e4cd17SGustavo A. R. Silvato allocate for a structure containing an array of this kind as a member::
31868e4cd17SGustavo A. R. Silva
31968e4cd17SGustavo A. R. Silva        struct something {
32068e4cd17SGustavo A. R. Silva                size_t count;
32168e4cd17SGustavo A. R. Silva                struct foo items[1];
32268e4cd17SGustavo A. R. Silva        };
32368e4cd17SGustavo A. R. Silva
32468e4cd17SGustavo A. R. Silva        struct something *instance;
32568e4cd17SGustavo A. R. Silva
32668e4cd17SGustavo A. R. Silva        instance = kmalloc(struct_size(instance, items, count - 1), GFP_KERNEL);
32768e4cd17SGustavo A. R. Silva        instance->count = count;
32868e4cd17SGustavo A. R. Silva
32968e4cd17SGustavo A. R. Silva        size = sizeof(instance->items) * instance->count;
33068e4cd17SGustavo A. R. Silva        memcpy(instance->items, source, size);
33168e4cd17SGustavo A. R. Silva
33268e4cd17SGustavo A. R. SilvaIn the example above, we had to remember to calculate ``count - 1`` when using
33368e4cd17SGustavo A. R. Silvathe struct_size() helper, otherwise we would have --unintentionally-- allocated
33468e4cd17SGustavo A. R. Silvamemory for one too many ``items`` objects. The cleanest and least error-prone way
33517dca050SGustavo A. R. Silvato implement this is through the use of a `flexible array member`, together with
33617dca050SGustavo A. R. Silvastruct_size() and flex_array_size() helpers::
33768e4cd17SGustavo A. R. Silva
33868e4cd17SGustavo A. R. Silva        struct something {
33968e4cd17SGustavo A. R. Silva                size_t count;
34068e4cd17SGustavo A. R. Silva                struct foo items[];
34168e4cd17SGustavo A. R. Silva        };
34268e4cd17SGustavo A. R. Silva
34368e4cd17SGustavo A. R. Silva        struct something *instance;
34468e4cd17SGustavo A. R. Silva
34568e4cd17SGustavo A. R. Silva        instance = kmalloc(struct_size(instance, items, count), GFP_KERNEL);
34668e4cd17SGustavo A. R. Silva        instance->count = count;
34768e4cd17SGustavo A. R. Silva
34817dca050SGustavo A. R. Silva        memcpy(instance->items, source, flex_array_size(instance, items, instance->count));
3498763a30bSKees Cook
3508763a30bSKees CookThere are two special cases of replacement where the DECLARE_FLEX_ARRAY()
3518763a30bSKees Cookhelper needs to be used. (Note that it is named __DECLARE_FLEX_ARRAY() for
3528763a30bSKees Cookuse in UAPI headers.) Those cases are when the flexible array is either
3538763a30bSKees Cookalone in a struct or is part of a union. These are disallowed by the C99
3548763a30bSKees Cookspecification, but for no technical reason (as can be seen by both the
3558763a30bSKees Cookexisting use of such arrays in those places and the work-around that
3568763a30bSKees CookDECLARE_FLEX_ARRAY() uses). For example, to convert this::
3578763a30bSKees Cook
3588763a30bSKees Cook	struct something {
3598763a30bSKees Cook		...
3608763a30bSKees Cook		union {
3618763a30bSKees Cook			struct type1 one[0];
3628763a30bSKees Cook			struct type2 two[0];
3638763a30bSKees Cook		};
3648763a30bSKees Cook	};
3658763a30bSKees Cook
3668763a30bSKees CookThe helper must be used::
3678763a30bSKees Cook
3688763a30bSKees Cook	struct something {
3698763a30bSKees Cook		...
3708763a30bSKees Cook		union {
3718763a30bSKees Cook			DECLARE_FLEX_ARRAY(struct type1, one);
3728763a30bSKees Cook			DECLARE_FLEX_ARRAY(struct type2, two);
3738763a30bSKees Cook		};
3748763a30bSKees Cook	};
375