by matheusmoreira · 4y ago · 0 comments
struct bytes { size_t size; unsigned char *pointer; };
Seems simple enough... A little structure like that has always been useful in my projects.I find myself agreeing with the glibc maintainer in the extended discussion linked from the article:
https://lwn.net/Articles/612244/
> Correct string handling means that you always know how long your strings are and therefore you can you memcpy (instead of strcpy).
I think he's absolutely right. The str* functions are just worse versions of the mem* functions.
For example, calls to printf can be transformed into calls to puts under certain conditions. The compiler can check + find those, even after optimizations. There are many of these tricks for the str* functions that assume NUL terminated C strings.
Though perhaps if the mem* functions were used to implement a fat strings implementation, many of those might still apply.
Point being; the compiler can help when your strings representation is first class by the language spec.
The compiler can also help with FORTIFY; it can insert compile time length checks in certain cases that can make code safer. This avoids treewide rewrites which are relatively painful to do for the Linux kernel due to its development model, but not impossible. That's another barrier to a new string representation and a library of routines for these.
That said, strscpy is not part of the language spec, so I'm guessing unless it's implemented in terms of language defined functions, it gets neither libcall optimizations nor fortified.
(Also the structure can be passed by value (without a pointer to the structure), which also allow to easily use in other function, e.g. to convert a null-terminated string or Pascal string into this structure, without allocating additional memory.)
No, just calling a conversion function before (that would need heap allocation) would never be accepted by C programmers (for the overhead).
Then there is inertia - how many really would want to port their application to a different string type? Not to mention, all the libraries you're using would also have to been converted.
Of course that also generates a giant foot gun because you might manage to get the old and new strlen to disagree on the size, because one reads the length field and the other searches the \0.
As it is, it will never happen.
Surely they could add better designed structures and functions for dealing with memory.
I'm not saying don't use length fields, I'm saying use nul terminators where possible and use length fields where needed. And, they are not mutually exclusive.
And C doesn't need a standardized length delineated string structure in my opinion. Nul terminators serve the job fine for most Standard APIs (which take only short strings), and can receive length fields as separate function parameters where required.
• On the most widely used architectures, reading a string is much easier if the string is a known length. x86 has its string instructions, ARM has its Load Multiple instructions.
• Even with length-prefixed strings, many uses of short strings are with string literals and so the length does not need to be stored anywhere.
It's inherent to the language. Writing "string" gives you a NUL-terminated string; converting that to another format takes effort.
Interestingly, some Mac OS compilers would let you write "\pABC" to get a structure containing the bytes {3, 'A', 'B', 'C'}. (The "p" stands for Pascal.)
Couldn't we just leave the NUL byte in there and pretend it doesn't exist?
const char *literal = "string literal with NUL byte";
struct bytes text;
text.size = strlen(literal); // strlen doesn't count the NUL terminator
text.pointer = literal;
// I know I discarded the const qualifier up there, but it's just to illustrate
Then a copy(text, other) function would conveniently ignore the entire NUL issue. The copy would not even have the terminating NUL.> Interestingly, some Mac OS compilers would let you write "\pABC" to get a structure containing the bytes {3, 'A', 'B', 'C'}. (The "p" stands for Pascal.)
Pascal strings are nice but their sizes are too limited. Same idea as my structure above but with a uint8_t for length instead of uint64_t = size_t.
Say two highest bits of the counter set the size of the counter field. 00 = 6 remaining bits, 01 = 14 bits (2 bytes), 10 = 30 bits, 11 = 62 bits (8 bytes).
A simple `counter* & 0x3f` would remove the width-setting bits, without any shifts, additions, etc.
This allows small strings to use only 1 byte for the counter, while allowing huge strings that span the entire RAM.
The kernel has perfectly reasonable I/O interfaces.
ssize_t bytes_read = read(file_descriptor, buffer, size);
ssize_t bytes_written = write(file_descriptor, buffer, size);
You always know the length.Well... At least you would always know the length if the standard C library didn't abstract that perfectly good interface away behind stdio just so it could do buffering and return NUL-terminated strings.
It's just like errno. The kernel simply returns a negated error constant on failure. The C standard library takes that sane interface and turns it into a thread local global variable.
This isn't unique to my example though. Traditional C strings have the exact same problem and they do get copied all the time.
Stock GCC doesn't have such option though. I guess it's implemented with a macOS-specific patch?
Of course this was before the days when everyone knows only C can be used to write OSes. /s
At least for string literals, no real effort required :)
I think they aren't "worse versions of the mem* functions"; they are different functions. The "str" functions deal with null-terminated data, "mem" functions deal with data of a specified length, and "strn" deals with whichever is shorter.
Some "str" functions do not have "mem" variants (and vice-versa). For example, there is no "memdup" function.
Well, yes. I say they're worse because the only reason they exist is to deal with this NUL terminator nonsense. The str* functions all reduce to the mem* functions after the string length is computed. To me it's like this:
str_function = mem_function(string, strlen(string) + 1)
There is no need for these functions to exist if we get rid of this NUL terminator business.> Some "str" functions do not have "mem" variants (and vice-versa). For example, there is no "memdup" function.
There could easily be. For example, strdup is essentially strcpy(malloc(strlen(string) + 1), string). A memdup function would be even more efficient because the length is already known: memcpy(malloc(length), source, length).
In the early 1990s, there was a popular shareware string library for C in circulation that added a whole raft of extra strXXX() functions, such as strrtrim() and strend(), to a C runtime library. All of these were useful. Indeed, they were fundamental in some other languages, e.g. some dialects of BASIC with their various string functions like MID$ and RIGHT$. But the standard C library never gained them.
The strXXX() set in the C standard library is, rather, in large part an ad hoc set of useful wrappers around stuff that could be done with assembly language idioms, like REPNE SCASB on x86 instruction sets, that had grown up by 1987. The functions weren't intended to be reducible to memXXX(). They were intended to be reducible to assembly language, or even to compiler intrinsics.
The sad part is that the context here is kernel code, in particular Linux kernel code, where human-readable text interfaces (as opposed to machine-parseable interfaces) are the norm. Whitespace-terminated or LF-terminated strings are the norm, in things like procfs for example, and it is a double irony that the C standard library addresses NUL termination more readily than it does those, and even then provides only an ad hoc collection of NUL-terminated string functions with long-since well-known glaring holes unsuitable for kernel code.
Getting rid of the problem in the way that you suggest would necessitate redesigning a lot of kernel APIs to not be human-readable text that operates in terms of variable length strings terminated by special character values with no explicit length counters. No more redirecting the output of the "echo" command to /proc/something . This is exceedingly unlikely to happen.
struct bytes { size_t size; unsigned char *data; };
now you've got two allocations (or at least two separate memory regions, or at least a pointer wasted assuming it's constant) per dynamically-allocated thing.On the other hand, if you take a more direct mirror of a Pascal string:
struct bytes { size_t size; unsigned char data[]; };
You're back to one memory span but can't reslice it.And of course the worst codebase is when someone uses the first one because they want to keep slicing and someone else uses the second one because they need to save memory / indirections. To support both you end up writing functions that take a separate size and data pointer, and... well, then what's the point?
size_t length = strlen("some string");
It's so common. Might as well memoize it so it's always available with no need to constantly loop through strings which is an O(N) algorithm. So many string algorithms call strlen, often multiple times on the same string. I remember GTA V took 6 minutes to parse a goddamn JSON file because of stuff like this and part of the fix was to store the string lengths.https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times...
So is a length variable really such a big deal? It even fits in a register.
I understand and agree with your one memory span point. Ideally they should be located as close as possible in memory.
struct bytes { size_t size; unsigned char data[]; };
const char *literal = "some text";
size_t length = strlen(literal);
struct bytes *text = malloc(sizeof(*text) + length);
text->size = length;
memcpy(text->data, literal, length); struct bytes { size_t size; unsigned char *data; };
struct bytes { size_t size; unsigned char data[]; };
you want depends heavily on what you're doing with the string(s) - plus other common variations like len+cap instead of just size, SSO, etc.So if you can't standardize the data structure, what's the common interface? A function that takes a pointer and a length - which is what we already have. So everyone in this thread appealing to the C standardization process or stdlib to do something wants instead - what, exactly?
> then what's the point?
There's no point. Moreover, passing the length separately is annoying and error-prone.You can have both your models in a single type. That's what my buffer lib achieves : SSO + slicing.
Also some major impl are 24 or even 32 bytes. With a generous SSO you catch a lot of strings w/o overhead.
In order to allow for the pointer to live on stack and minimize copying, the data is also reference counted and the compiler takes care of inserting the necessary reference counting calls where needed.
Overall it's pretty flexible, but the reference counting means it's not ideal to use shared strings in heavily threaded code. Of course the second a thread modifies a string, a new string is allocated and that thread can happily work on its "own" string.
Anyway, just yet another way of implementing strings.
Having a size_t on the stack is hardly an issue, it's what every low-level modern language does. It's fast, convenient, and pretty efficient. It also doesn't require deref'ing to get the length, which is a pretty common use case (e.g. checking if a string is empty, or too big, or something along those lines).
I would be also worried about any difficulties separating the length and data causes for prefetching/cache lines though.
The second form is also more amenable to SSO; I'm not sure how often that would come up in the kernel but it's saved me a decent chunk of memory in at least one past project. (Still today I'm sometimes frustated by Go `string` porting from Java `String`, like great now I don't have to pay a boxing overhead but if it's often absent/empty my base size is now 2x what it would otherwise be...)
Per Todd C. Miller (creator of strlcpy and maintainer of sudo) and Theo de Raadt (OpenBSD) in these 1999 (PostScript) slides, the simplest implementation of strlcpy() uses (can use) memcpy():
size_t strlcpy(char *dst, const char *src, size_t siz)
{
size_t n;
size_t slen = strlen(src);
if (siz) {
if ((n = MIN(slen, siz - 1)))
memcpy(dst, src, n);
dst[n] = ’\0’;
}
return(slen);
}
* https://www.openbsd.org/papers/strlcpy-slides.psThe current OpenBSD is currently different:
* https://github.com/openbsd/src/blob/master/lib/libc/string/s...
* https://cvsweb.openbsd.org/src/lib/libc/string/strlcpy.c
One problem with memcpy() is that it returns (void *), so there is no way to know if you've truncated things. From the USENIX paper on strlcpy():
> The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that is simply the length of the source; for strlcat() that means the length of the destination (before concatenation) plus the length of the source. To check for truncation, the programmer need only verify that the return value is less than the size parameter. Thus, if truncation has occurred, the number of bytes needed to store the entire string is now known and the programmer may allocate more space and re-copy the strings if he or she wishes.
* https://www.usenix.org/legacy/events/usenix99/full_papers/mi...
I understand the topic is strXxx() funcs which are ascii only, but it does need to be said that size!=len for wide and multi char sets.
Honestly "string" is a very harmful word that we've all grown used to. As an abstraction it sits somewhere between raw bytes and properly encoded text with proper unicode functions such as those provided by ICU. Python 3 finally forced people to start thinking about this stuff and nobody liked it.
Bytes are relevant when I have to allocate memory otherwise some definition of "character" is often more relevant. Even if I trim text to fit in a buffer I don't want to trim inside a "character" but get the most number of fitting "characters" Now "characters" are of course complicated as grapheme clusters are what is useful the most for human interaction ... but those are quite out of scope for a "simple" string library ...
The Linux kernel has data structure libraries for things like linked lists and maps. Does it really not have a higher-level string abstraction?
https://stackoverflow.com/questions/20935769/sse42-sttni-pcm...
Sometimes you just need to do the boring work so it's done. The Linux kernel is one of the most important pieces of software on the planet - limiting it's performance and safety due to C's string handling legacy is madness.