xref: /xnu-11215.81.4/doc/primitives/string-handling.md (revision d4514f0bc1d3f944c22d92e68b646ac3fb40d452)
1*d4514f0bSApple OSS Distributions# String handling in xnu
2*d4514f0bSApple OSS Distributions
3*d4514f0bSApple OSS Distributionsxnu implements most POSIX C string functions, including the inherited subset of
4*d4514f0bSApple OSS Distributionsstandard C string functions. Unfortunately, poor design choices have made many
5*d4514f0bSApple OSS Distributionsof these functions, including the more modern `strl` functions, confusing or
6*d4514f0bSApple OSS Distributionsunsafe. In addition, the advent of -fbounds-safety support in xnu is forcing
7*d4514f0bSApple OSS Distributionssome string handling practices to be revisited. This document explains the
8*d4514f0bSApple OSS Distributionsfailings of POSIX C string functions, xnu's `strbuf` functions, and their
9*d4514f0bSApple OSS Distributionsintersection with the -fbounds-safety C extension.
10*d4514f0bSApple OSS Distributions
11*d4514f0bSApple OSS Distributions## The short-form guidance
12*d4514f0bSApple OSS Distributions
13*d4514f0bSApple OSS Distributions* Use `strbuf*` when you have the length for all the strings;
14*d4514f0bSApple OSS Distributions* use `strl*` when you have the length of _one_ string, and the other is
15*d4514f0bSApple OSS Distributions  guaranteed to be NUL-terminated;
16*d4514f0bSApple OSS Distributions* use `str*` when you don't have the length for any of the strings, and they
17*d4514f0bSApple OSS Distributions  are all guaranteed to be NUL-terminated;
18*d4514f0bSApple OSS Distributions* stop using `strn*` functions.
19*d4514f0bSApple OSS Distributions
20*d4514f0bSApple OSS Distributions## Replacing `strncmp`
21*d4514f0bSApple OSS Distributions
22*d4514f0bSApple OSS Distributions`strncmp` is always wrong with -fbounds-safety, and it's unavailable as a
23*d4514f0bSApple OSS Distributionsresult. Given `strcmp(first, secnd, n)`, you need to know the types of `first`
24*d4514f0bSApple OSS Distributionsand `secnd` to pick a replacement. Choose according to this table:
25*d4514f0bSApple OSS Distributions
26*d4514f0bSApple OSS Distributions| strncmp(first, secnd, n) | __null_terminated first   | __indexable first               |
27*d4514f0bSApple OSS Distributions| ------------------------ | ------------------------- | ------------------------------- |
28*d4514f0bSApple OSS Distributions| __null_terminated secnd  | n/a                       | strlcmp(first, secnd, n1)       |
29*d4514f0bSApple OSS Distributions| __indexable secnd        | strlcmp(secnd, first, n2) | strbufcmp(first, n1, secnd, n2) |
30*d4514f0bSApple OSS Distributions
31*d4514f0bSApple OSS DistributionsUsing `strncmp` with two NUL-terminated strings is uncommon and it has no
32*d4514f0bSApple OSS Distributionsdirect replacement. The first person who needs to use -fbounds-safety in a file
33*d4514f0bSApple OSS Distributionsthat does this might need to write the string function.
34*d4514f0bSApple OSS Distributions
35*d4514f0bSApple OSS DistributionsIf you try to use `strlcmp` and you get a diagnostic like this:
36*d4514f0bSApple OSS Distributions
37*d4514f0bSApple OSS Distributions> passing 'const char *__indexable' to parameter of incompatible type
38*d4514f0bSApple OSS Distributions> 'const char *__null_terminated' is an unsafe operation ...
39*d4514f0bSApple OSS Distributions
40*d4514f0bSApple OSS Distributionsthen you might need to swap the two string arguments. `strlcmp` is sensitive to
41*d4514f0bSApple OSS Distributionsthe argument order: just like for `strlcpy`, the indexable string goes first.
42*d4514f0bSApple OSS Distributions
43*d4514f0bSApple OSS Distributions# The problems with string functions
44*d4514f0bSApple OSS Distributions
45*d4514f0bSApple OSS DistributionsPOSIX/BSD string handling functions come in many variants:
46*d4514f0bSApple OSS Distributions
47*d4514f0bSApple OSS Distributions* `str` functions (strlen, strcat, etc), unsafe for writing;
48*d4514f0bSApple OSS Distributions* `strn` functions (strnlen, strncat, etc), unsafe for writing;
49*d4514f0bSApple OSS Distributions* `strl` functions (strlcpy, strlcat, etc), safe but easily misunderstood.
50*d4514f0bSApple OSS Distributions
51*d4514f0bSApple OSS Distributions`str` functions for writing (`strcpy`, `strcat`, etc) are **all** unsafe
52*d4514f0bSApple OSS Distributionsbecause they don't care about the bounds of the output buffer. Most or all of
53*d4514f0bSApple OSS Distributionsthese functions have been deprecated or outright removed from xnu. You should
54*d4514f0bSApple OSS Distributionsnever use `str` functions to write to strings. Functions that simply read
55*d4514f0bSApple OSS Distributionsstrings (`strlen`, `strcmp`, `strchr`, etc) are generally found to be safe
56*d4514f0bSApple OSS Distributionsbecause there is no confusion that their input must be NUL-terminated and there
57*d4514f0bSApple OSS Distributionsis no danger of writing out of bounds (out of not writing at all).
58*d4514f0bSApple OSS Distributions
59*d4514f0bSApple OSS Distributions`strn` functions for writing (`strncpy`, `strncat`, etc) are **all** unsafe.
60*d4514f0bSApple OSS Distributions`strncpy` doesn't NUL-terminate the output buffer, and `strncat` doesn't accept
61*d4514f0bSApple OSS Distributionsa length for the output buffer. **All** new string buffers should include space
62*d4514f0bSApple OSS Distributionsfor a NUL terminator. `strn` functions for reading (`strncmp`, `strnlen`) are
63*d4514f0bSApple OSS Distributions_generally_ safe, but `strncmp` can cause confusion over which string is bound
64*d4514f0bSApple OSS Distributionsby the given size. In extreme cases, this can create information disclosure
65*d4514f0bSApple OSS Distributionsbugs or stability issues.
66*d4514f0bSApple OSS Distributions
67*d4514f0bSApple OSS Distributions`strl` functions, from OpenBSD, only come in writing variants, and they always
68*d4514f0bSApple OSS DistributionsNUL-terminate their output. This makes the writing part safe. (xnu adds `strl`
69*d4514f0bSApple OSS Distributionscomparison functions, which do no writing and are also safe.) However, these
70*d4514f0bSApple OSS Distributionsfunctions assume the output pointer is a buffer and the input is a NUL-
71*d4514f0bSApple OSS Distributionsterminated string. Because of coexistence with `strn` functions that make no
72*d4514f0bSApple OSS Distributionssuch assumption, this mental model isn't entirely adopted by many users. For
73*d4514f0bSApple OSS Distributionsinstance, the following code is buggy:
74*d4514f0bSApple OSS Distributions
75*d4514f0bSApple OSS Distributions```c
76*d4514f0bSApple OSS Distributionschar output[4];
77*d4514f0bSApple OSS Distributionschar input[8] = "abcdefgh"; /* not NUL-terminated */
78*d4514f0bSApple OSS Distributionsstrlcpy(output, input, sizeof(output));
79*d4514f0bSApple OSS Distributions```
80*d4514f0bSApple OSS Distributions
81*d4514f0bSApple OSS Distributions`strlcpy` returns the length of the input string; in xnu's implementation,
82*d4514f0bSApple OSS Distributionsliterally by calling `strlen(input)`. Even though only 3 characters are written
83*d4514f0bSApple OSS Distributionsto `output` (plus a NUL), `input` is read until reaching a NUL character. This
84*d4514f0bSApple OSS Distributionsis always a problem from the perspective of memory disclosures, and in some
85*d4514f0bSApple OSS Distributionscases, it can also lead to stability issues.
86*d4514f0bSApple OSS Distributions
87*d4514f0bSApple OSS Distributions# Changes with -fbounds-safety
88*d4514f0bSApple OSS Distributions
89*d4514f0bSApple OSS DistributionsWhen enabling -fbounds-safety, character buffers and NUL-terminated strings are
90*d4514f0bSApple OSS Distributionstwo distinct types, and they do not implicitly convert to each other. This
91*d4514f0bSApple OSS Distributionsprevents confusing the two in the way that is problematic with `strlcpy`, for
92*d4514f0bSApple OSS Distributionsinstance. However, it creates new problems:
93*d4514f0bSApple OSS Distributions
94*d4514f0bSApple OSS Distributions* What is the correct way to transform a character buffer into a NUL-terminated
95*d4514f0bSApple OSS Distributions  string?
96*d4514f0bSApple OSS Distributions* When -fbounds-safety flags that the use of a string function was improper,
97*d4514f0bSApple OSS Distributions  what is the solution?
98*d4514f0bSApple OSS Distributions
99*d4514f0bSApple OSS DistributionsThe most common use of character buffers is to build a string, and then this
100*d4514f0bSApple OSS Distributionsstring is passed without bounds as a NUL-terminated string to downstream users.
101*d4514f0bSApple OSS Distributions-fbounds-safety and XNU enshrine this practice with the following additions:
102*d4514f0bSApple OSS Distributions
103*d4514f0bSApple OSS Distributions* `tsnprintf`: like `snprintf`, but it returns a NUL-terminated string;
104*d4514f0bSApple OSS Distributions* `strbuf` functions, explicitly accepting character buffers and a distinct
105*d4514f0bSApple OSS Distributions  count for each:
106*d4514f0bSApple OSS Distributions  * `strbuflen(buffer, length)`: like `strnlen`;
107*d4514f0bSApple OSS Distributions  * `strbufcmp(a, alen, b, len)`: like `strcmp`;
108*d4514f0bSApple OSS Distributions  * `strbufcasecmp(a, alen, b, blen)`: like `strcasecmp`;
109*d4514f0bSApple OSS Distributions  * `strbufcpy(a, alen, b, blen)`: like `strlcpy` but returns `a` as a NUL-
110*d4514f0bSApple OSS Distributions    terminated string;
111*d4514f0bSApple OSS Distributions  * `strbufcat(a, alen, b, blen)`: like `strlcat` but returns `a` as a NUL-
112*d4514f0bSApple OSS Distributions    terminated string;
113*d4514f0bSApple OSS Distributions* `strl` (new) functions, accepting _one_ character buffer of a known size and
114*d4514f0bSApple OSS Distributions  _one_ NUL-terminated string:
115*d4514f0bSApple OSS Distributions  * `strlcmp(a, b, alen)`: like `strcmp`;
116*d4514f0bSApple OSS Distributions  * `strlcasecmp(a, b, alen)`: like `strcasecmp`.
117*d4514f0bSApple OSS Distributions
118*d4514f0bSApple OSS Distributions`strbuf` functions additionally all have overloads accepting character arrays
119*d4514f0bSApple OSS Distributionsin lieu of a pointer+length pair: `strbuflen(array)`, `strbufcmp(a, b)`,
120*d4514f0bSApple OSS Distributions`strbufcasecmp(a, b)`, `strbufcpy(a, b)`, `strbufcat(a, b)`.
121*d4514f0bSApple OSS Distributions
122*d4514f0bSApple OSS DistributionsIf the destination array of `strbufcpy` or `strbufcat` has a size of 0, they
123*d4514f0bSApple OSS Distributionsreturn NULL without doing anything else. Otherwise, the destination is always
124*d4514f0bSApple OSS DistributionsNUL-terminated and returned as a NUL-terminated string pointer.
125*d4514f0bSApple OSS Distributions
126*d4514f0bSApple OSS DistributionsWhile you are modifying a string, you should reference its data as some flavor
127*d4514f0bSApple OSS Distributionsof indexable pointer, and only once you're done should you convert it to a
128*d4514f0bSApple OSS DistributionsNUL-terminated string. NUL-terminated character pointers are generally not
129*d4514f0bSApple OSS Distributionssuitable for modifications as bounds are determined by contents. Overwriting
130*d4514f0bSApple OSS Distributionsany NUL character found through a `__null_terminated` pointer access will result
131*d4514f0bSApple OSS Distributionsin a trap. For instance:
132*d4514f0bSApple OSS Distributions
133*d4514f0bSApple OSS Distributions```c
134*d4514f0bSApple OSS Distributionsvoid my_string_consuming_func(const char *);
135*d4514f0bSApple OSS Distributions
136*d4514f0bSApple OSS Distributions// lots of __unsafe!
137*d4514f0bSApple OSS Distributionschar *__null_terminated my_string = __unsafe_forge_null_terminated(
138*d4514f0bSApple OSS Distributions  kalloc_data(my_string_size, Z_WAITOK));
139*d4514f0bSApple OSS Distributionsmemcpy(
140*d4514f0bSApple OSS Distributions  __unsafe_forge_bidi_indexable(void *, my_string, my_string_size),
141*d4514f0bSApple OSS Distributions  my_data,
142*d4514f0bSApple OSS Distributions  my_string_size);
143*d4514f0bSApple OSS Distributionsmy_string_consuming_func(my_string);
144*d4514f0bSApple OSS Distributions```
145*d4514f0bSApple OSS Distributions
146*d4514f0bSApple OSS DistributionsThis code converts the string pointer to a NUL-terminated string too early,
147*d4514f0bSApple OSS Distributionswhile it's still being modified. Keeping my_string a `__null_terminated` pointer
148*d4514f0bSApple OSS Distributionswhile it's being modified leads to more forging, which has more chances of
149*d4514f0bSApple OSS Distributionsintroducing errors, and is less ergonomic. Consider this instead:
150*d4514f0bSApple OSS Distributions
151*d4514f0bSApple OSS Distributions```c
152*d4514f0bSApple OSS Distributionsvoid my_string_consuming_func(const char *);
153*d4514f0bSApple OSS Distributions
154*d4514f0bSApple OSS Distributionschar *my_buffer = kalloc_data(my_string_size, Z_WAITOK);
155*d4514f0bSApple OSS Distributionsconst char *__null_terminated finished_string =
156*d4514f0bSApple OSS Distributions  strbufcpy(my_buffer, my_string_size, my_data, my_string_size);
157*d4514f0bSApple OSS Distributionsmy_string_consuming_func(finished);
158*d4514f0bSApple OSS Distributions```
159*d4514f0bSApple OSS Distributions
160*d4514f0bSApple OSS DistributionsThis example has two views of the same data: `my_buffer` (through which the
161*d4514f0bSApple OSS Distributionsstring is being modified) and `finished_string` (which is `const` and
162*d4514f0bSApple OSS DistributionsNUL-terminated). Using `my_buffer` as an indexable pointer allows you to modify
163*d4514f0bSApple OSS Distributionsit ergonomically, and importantly, without forging. You turn it into a
164*d4514f0bSApple OSS DistributionsNUL-terminated string at the same time you turn it into a `const` reference,
165*d4514f0bSApple OSS Distributionssignalling that you're done making changes.
166*d4514f0bSApple OSS Distributions
167*d4514f0bSApple OSS DistributionsWith -fbounds-safety enabled, you should structure the final operation modifying
168*d4514f0bSApple OSS Distributionsa character array such that you get a NUL-terminated view of it. For instance,
169*d4514f0bSApple OSS Distributionsthis plain C code:
170*d4514f0bSApple OSS Distributions
171*d4514f0bSApple OSS Distributions```c
172*d4514f0bSApple OSS Distributionschar thread_name[MAXTHREADNAMESIZE];
173*d4514f0bSApple OSS Distributions(void) snprintf(thread_name, sizeof(thread_name),
174*d4514f0bSApple OSS Distributions        "dlil_input_%s", ifp->if_xname);
175*d4514f0bSApple OSS Distributionsthread_set_thread_name(inp->dlth_thread, thread_name);
176*d4514f0bSApple OSS Distributions```
177*d4514f0bSApple OSS Distributions
178*d4514f0bSApple OSS Distributionsbecomes:
179*d4514f0bSApple OSS Distributions
180*d4514f0bSApple OSS Distributions```c
181*d4514f0bSApple OSS Distributionschar thread_name_buf[MAXTHREADNAMESIZE];
182*d4514f0bSApple OSS Distributionsconst char *__null_terminated thread_name;
183*d4514f0bSApple OSS Distributionsthread_name = tsnprintf(thread_name_buf, sizeof(thread_name_buf),
184*d4514f0bSApple OSS Distributions        "dlil_input_%s", ifp->if_xname);
185*d4514f0bSApple OSS Distributionsthread_set_thread_name(inp->dlth_thread, thread_name);
186*d4514f0bSApple OSS Distributions```
187*d4514f0bSApple OSS Distributions
188*d4514f0bSApple OSS DistributionsAlthough `tsnprintf` and `strbuf` functions return a `__null_terminated`
189*d4514f0bSApple OSS Distributionspointer to you for convenience, not all use cases are resolved by calling
190*d4514f0bSApple OSS Distributions`tsnprintf` or `strbufcpy` once. As a quick reference, with -fbounds-safety
191*d4514f0bSApple OSS Distributionsenabled, you can use `__unsafe_null_terminated_from_indexable(p_start, p_nul)`
192*d4514f0bSApple OSS Distributionsto convert a character array to a `__null_terminated` string if you need to
193*d4514f0bSApple OSS Distributionsperform more manipulations. (`p_start` is a pointer to the first character, and
194*d4514f0bSApple OSS Distributions`p_nul` is a pointer to the NUL character in that string.) For instance, if you
195*d4514f0bSApple OSS Distributionsbuild a string with successive calls to `scnprintf`, you would use
196*d4514f0bSApple OSS Distributions`__unsafe_null_terminated_from_indexable` at the end of the sequence to get your
197*d4514f0bSApple OSS DistributionsNUL-terminated string pointer.
198*d4514f0bSApple OSS Distributions
199*d4514f0bSApple OSS DistributionsOccasionally, you need to turn a NUL-terminated string back into "char buffer"
200*d4514f0bSApple OSS Distributions(usually to interoperate with copy APIs that need a pointer and a byte count).
201*d4514f0bSApple OSS DistributionsWhen possible, it's advised to use APIs that copy NUL-terminated pointers (like
202*d4514f0bSApple OSS Distributions`strlcpy`). Otherwise, convert the NUL-terminated string to an indexable buffer
203*d4514f0bSApple OSS Distributionsusing `__null_terminated_to_indexable` (if you don't need the NUL terminator to
204*d4514f0bSApple OSS Distributionsbe in bounds of the result pointer) or `__unsafe_null_terminated_to_indexable`
205*d4514f0bSApple OSS Distributions(if you need it). Also keep in mind that in code which pervasively deals with
206*d4514f0bSApple OSS Distributionsbuffers that have lengths and some of them happen to also be NUL-terminated
207*d4514f0bSApple OSS Distributionsstrings, it could be simply more convenient to keep string buffers in some
208*d4514f0bSApple OSS Distributionsflavor of indexable pointers instead of having conversions from and to
209*d4514f0bSApple OSS DistributionsNUL-terminated strings.
210*d4514f0bSApple OSS Distributions
211*d4514f0bSApple OSS Distributions# I have a choice between `strn*`, `strl*`, `strbuf*`. Which one do I use?
212*d4514f0bSApple OSS Distributions
213*d4514f0bSApple OSS DistributionsYou might come across cases where the same function in different families would
214*d4514f0bSApple OSS Distributionsseem like they all do the trick. For instance:
215*d4514f0bSApple OSS Distributions
216*d4514f0bSApple OSS Distributions```c
217*d4514f0bSApple OSS Distributionsstruct foo {
218*d4514f0bSApple OSS Distributions    char buf1[10];
219*d4514f0bSApple OSS Distributions    char buf2[16];
220*d4514f0bSApple OSS Distributions};
221*d4514f0bSApple OSS Distributions
222*d4514f0bSApple OSS Distributionsvoid bar(struct foo *f) {
223*d4514f0bSApple OSS Distributions    /* how do I test whether buf1 and buf2 contain the same string? */
224*d4514f0bSApple OSS Distributions    if (strcmp(f->buf1, f->buf2) == 0) { /* ... */ }
225*d4514f0bSApple OSS Distributions    if (strncmp(f->buf1, f->buf2, sizeof(f->buf1)) == 0) { /* ... */ }
226*d4514f0bSApple OSS Distributions    if (strlcmp(f->buf1, f->buf2, sizeof(f->buf1)) == 0) { /* ... */ }
227*d4514f0bSApple OSS Distributions    if (strbufcmp(f->buf1, f->buf2) == 0) { /* ... */ }
228*d4514f0bSApple OSS Distributions}
229*d4514f0bSApple OSS Distributions```
230*d4514f0bSApple OSS Distributions
231*d4514f0bSApple OSS DistributionsWithout -fbounds-safety, these all work the same, but when you enable it,
232*d4514f0bSApple OSS Distributions`strbufcmp` could be the only one that builds. If you do not have the privilege
233*d4514f0bSApple OSS Distributionsof -fbounds-safety to guide you to the best choice, as a rule of thumb, you
234*d4514f0bSApple OSS Distributionsshould prefer APIs in the following order:
235*d4514f0bSApple OSS Distributions
236*d4514f0bSApple OSS Distributions1. `strbuf*` APIs;
237*d4514f0bSApple OSS Distributions2. `strl*` APIs;
238*d4514f0bSApple OSS Distributions3. `str*` APIs.
239*d4514f0bSApple OSS Distributions
240*d4514f0bSApple OSS DistributionsThat is, to implement `bar`, you have a choice of `strcmp`, `strncmp` and
241*d4514f0bSApple OSS Distributions`strbufcmp`, and you should prefer `strbufcmp`.
242*d4514f0bSApple OSS Distributions
243*d4514f0bSApple OSS Distributions`strn` functions are **never** recommended. You should use `strbuflen` over
244*d4514f0bSApple OSS Distributions`strnlen` (they do the same thing, but having a separate `strbuflen` function
245*d4514f0bSApple OSS Distributionsmakes the guidance to avoid `strn` functions easier), and you should use
246*d4514f0bSApple OSS Distributions`strbufcmp`, `strlcmp` or even `strcmp` over `strncmp` (depending on whether
247*d4514f0bSApple OSS Distributionsyou know the length of each string, of just one, or of neither).
248