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