178 points · by synergy20 · 3y ago · 243 comments
"This is horribly inefficient BSD crap. Using these function only leads to other errors. Correct string handling means that you always know how long your strings are and therefore you can you memcpy (instead of strcpy).
Beside, those who are using strcat or variants deserved to be punished."
- Ulrich Drepper, around 23 years ago: https://sourceware.org/legacy-ml/libc-alpha/2000-08/msg00053...
I still support this addition. If you are doing methamphetamine with needle sharing you should stop methamphetamine, but distributing clean needles is still an improvement.
One benefit of defining strlcpy yourself is that you can define it as a macro that expands to an open-coded call to snprintf, and then that is diagnosed by GCC; you may get static warnings about possible truncation. (I suspect GCC might not yet be analyzing strlcpy/strlcat calls, but that could change.)
The functions silently discard data in order to achieve memory safety. Historically, that has been viewed as acceptable in C coding culture. There are situations in which that is okay, like truncating some unimportant log message to "only" 1024 characters.
Truncating can cause an exploitable security hole; like some syntax is truncated so that its closing brace is missing, and the attacker is able to somehow complete it maliciously.
Even when arbitrary limits are acceptable, silently enforcing them in a low-level copying function may not be the best place in the program. If the truncation is caused by some excessively long input, maybe that input should be validated close to where it comes into the program, and rejected. E.g. don't let the user input some 500 character field, pretend you're saving it and then have them find out the next day that only 255 of it got saved.
Even if in my program I find it useful to have a truncating copying function, I don't necessarily want it to be silent when truncation occurs. Maybe in that particular program, I want to abort the program with a diagnostic message. I can then pass large texts in the unit and integration tests, to find the places in the program that have inflexible text handling, but are being reached by unchecked large inputs.
#include <stdio.h>
#include <string.h>
#define strlcpy(dst, src, size) ((size_t) snprintf(dst, size, "%s", src))
size_t (strlcpy)(char *dst, const char *src, size_t size)
{
return strlcpy(dst, src, size);
}
int main(void)
{
char littlebuf[8];
strlcpy(littlebuf, "Supercalifragilisticexpealidocious", sizeof littlebuf);
return 0;
}
strlcpy.c: In function ‘main’:
strlcpy.c:4:63: warning: ‘%s’ directive output truncated writing 34 bytes into a region of size 8 [-Wformat-truncation=]
#define strlcpy(dst, src, size) ((size_t) snprintf(dst, size, "%s", src))
^
strlcpy.c:14:22:
strlcpy(littlebuf, "Supercalifragilisticexpealidocious", sizeof littlebuf);
~
strlcpy.c:14:3: note: in expansion of macro ‘strlcpy’
strlcpy(littlebuf, "Supercalifragilisticexpealidocious", sizeof littlebuf);
^~~~~~~
strlcpy.c:4:34: note: ‘snprintf’ output 35 bytes into a destination of size 8
#define strlcpy(dst, src, size) ((size_t) snprintf(dst, size, "%s", src))
~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
strlcpy.c:14:3: note: in expansion of macro ‘strlcpy’
strlcpy(littlebuf, "Supercalifragilisticexpealidocious", sizeof littlebuf);
^~~~~~~
If glibc doesn't do something in the header file such that we get similar diagnostics for its strlcpy, we can make the argument that this is detrimental to the program.I guess the answer is "some people's C is good enough, but not yours"
https://www.humprog.org/~stephen/research/papers/kell17some-...
I still fail to label C as evil.
P.S.: Don't start with all memory management and related stuff. We have solutions for these everywhere, incl., but not limited to GCs, Rust, etc. Their existence do not invalidate C, and we don't need to abandon it. Horses for courses.
[0] and not just in C itself, unexpected truncation through FFI is an issue which regularly pops up
They seemed useful enough to get added to the other BSDs, Solaris, Mac OS X, Irix(!), QNX, and Cygwin as well as used in the Linux kernel.
strncpy() can make a string into a non-string (depending on size), which is clearly bad.
That, as it turns out, is the case of most (but not all) strn* functions.
Of course strncpy adds the injury that it’s specified to alllow nul-terminated inputs (it stops at the first nul byte, before filling the target buffer with nuls).
To be pedantic, they're pointers to char. Nothing more. Calling them array confuses non-C coders. The length is just an unenforced contract and has to be passed.
I think (or hope) the concepts are pretty clear if you understand what a pointer is.
https://archive.kernel.org/oldlinux/htmldocs/kernel-api/API-...
Well, I couldn't think of a stronger argument against NULL terminated strings than this. After all, NULL terminated strings make no guarantee about having a finite length. Nothing prevents you from building a memory mapped string that is being generated on demand that never ends.
The only NUL that C requires is the NUL following C string literals, and you can even easily define char-arrays without NUL.
char buf[5] = "Hello";
or even #define DEFINE_NONZ_STRING(name, lit) char name[sizeof lit - 1] = lit "";
Can also easily build pointer + length representations, without even a runtime strlen() cost. struct String { const char *buf, int len; };
#define STRING(lit) ((String) { (lit ""), sizeof lit - 1 })Call it safe_strncpy and be done with it. Otherwise asprintf and snprintf exist. strlcpy is a more garbage version of snprintf.
On the other hand, his recommendation to always know string lengths and use memcpy didn't really become common practice over the last 20+ years either, so I'm not sure it was worth all the arguing.
At this point, I'm kind of joining the camp of "C has proven to be too bug-prone for most organizations to use safely and therefore we should all go to Rust".
It hasn't become common practice in C. But other languages (like JavaScript or Python) have become hugely popular, and don't use null-terminated strings.
There is never, ever, under any circumstances, a reason to be abusive.
This is very different from e.g. Torvalds who sometimes rants a bit after someone who he feels ought to know better screwed up. I'm not saying that's brilliant either, but I can be a lot more understanding when people are abrasive out of passion for their project after something went wrong.
"Doctor, it hurts when I strcpy — so don't do that".
He's being a jerk about it, but I would not say that he doesn't have a point.
strlcpy may not be the best API, but it's sane enough and by now ubiquitous enough to deserve inclusion. Had glibc and others engaged we may have had a better API. Regardless, glibc should never have had such a long veto here.
Truncation can lead to big issues, especially if the string being composed refers to paths, device names, other resources, etc. For example you may truncate a path from /foo/bar/baz to /foo/bar and inadvertently operate on other files. An API that makes this confusing is dangerous.
See the confused deputy problem description [4].
[1] https://mafford.com/text/the-many-ways-to-copy-a-string-in-c...
[2] https://lwn.net/Articles/659214/
[3] https://docs.kernel.org/core-api/kernel-api.html#c.strscpy
https://www.austingroupbugs.net/view.php?id=986 (scroll to 0002897)
> strlcpy() fits within the existing set of functions like a glove. strlcpy(a, b, n) behaves identically to snprintf(a, n, "%s", b). The return value always corresponds to the number of non-null bytes that would have been written. If we truly think that this is bad design, should we come up with a new version of snprintf() that also doesn't do this? I don't think so.
People typically do not consider snprintf and strlcpy to be a similar family of functions. There's no need to transpose the weird behavior to a new string copying routine.
Fixing this now is hard: Writing to 0-ended strings require manually tracking lengths. Expanding a string without allowing malloc is misery.
The only way out I see is basically starting from zero: ISO C should define an API with a (pointer,current length, max length) struct at its core, pointer pointing to a 0-terminated C string. You can read it, but changing it requires using functions that can error out and/or malloc more memory. There are already multiple libs like this, but C has none. If the struct would be ABI, non-C programming languages can pass strings between them.
And zero-terminated strings are not strictly worse than other length-prefixed string forms. They save some space -- sure, less relevant today -- as well as provide an in-band termination signal -- which is hacky, again sure, but it is convenient when looking at a hex dump for example.
Float/double literals do
This reminds me. From a spec/design perspective Ceylon was the cleanest language I know. Almost everything, including a lot of the keywords were actually defined in the standard library. The fact that Integer was actually a Java int behind the scenes was just a compiler implementation detail. There was very little "magic". If you wanted to know how something in the language worked you could just look at the standard library.
When I read arguments they are full of people thinking that their one size fits all and that somehow having too many variations would be bad.
This seems illogical to me since I've had to write my own string copying routines enough times because the one that fitted my need wasn't commonly available. Purism with C is just stu.... well anyhow.
A "good" fat pointer library for C would help a lot - something that could pop a NUL onto the end when you needed to put the string into an OS function but I would also have to groan at the idea that NUL termination should be outlawed in some way. At the C level you want options not limitations.
And this is true for strings too. If you use only static strings in your whole project, the standard is enough, but I won't write an IRC server or a posix Shell without my own strings (not anymore :p).
It says that they might be added to POSIX.
edit apparently Ulrich Drepper (major glibc contributer & former glibc leader is back at Red Hat [0]
https://research.redhat.com/blog/project_member/ulrich-drepp...
(https://www.reddit.com/r/linux/comments/zzhd9/comment/c69cam...)
snprintf(buf, sizeof(buf), "%s%s", a, b);
This as safe as strlcpy and strlcat, but more efficient, and has been standard for 24 years.2. This is inefficient in a similar way that strlcpy is: it does more work than the size of the buffer.
2. You have the option to provide the length, snprintf(buf, sizeof buf, "%.*s%.*s", len1, str1, len2, str2);
If you're bottlenecked by snprintf (hint: you aren't) then snprintf isn't your API anyway. Write some more custom code, probably some memcpy's etc.
C has void*, that allows you to implement easily modifiable data structures. There is a bit of 'NIH' syndrome in what I'm saying, I'll admit, but in the end it's better imho.
My intuition would be to give some importance to not looping on the source string radically beyond the length of the destination buffer.
https://sourceware.org/git/?p=glibc.git;a=blob;f=string/strl...
First, you make two structs: str_buf { capacity, len, data[] } and str_view { len, data* }.
Then write your string handling functions to write into a str_buf* and read from str_views. You have the length and capacity available so memcpy is easy and safe to use.
The str_buf treats capacity as 1 less than it really is such that it can ensure there's always a stupid 0 at the end for compatibility with APIs that expect 0 terminated strings.
There you go, no more security bugs, no more nonsense.
Off-by-one errors are a thing.
> Just make your own string functions from scratch when using C, you'll thank me later.
No, if you're going to use C and you need a string type use a well supported string library so that you don't end up reinventing the wheel (probably in a buggy way) and benefit from the battle testing that that code has gone through.
If we're looking at actual strings (as in text) then I'd use 'libunistring'.
It seems it was once an explicit design choice in Glibc. Here (https://sourceware.org/bugzilla/show_bug.cgi?id=10891) a Glibc ticket refers to documentation "Thread-aware Local Model, A Proposal" of the plans for the _l() functions (https://akkadia.org/drepper/tllocale.ps.gz) long ago, which are nowadays implemented in Glibc.
It looks like snprintf_l() and other <stdio.h> functions were not part of that plan.
That plan or something like it also made its way into POSIX.1-2008, so it seems likely that the committee gave some thought to including strftime_l() and not snprintf_l().
The paper linked above includes a rationale that tiny, potentially performance-critical functions like isalpha() need a fast version that takes a local parameter, thus isalpha_l(), because of the overhead of fetching a thread-local value inside the function.
Perhaps the intent is that only those tiny functions, or even macros, whose performance would be greatly affected by the cost of fetching the thread-local locale, need a _l() version. That mostly makes sense for the functions which have _l() versions in Glibc. But with that rationale, I don't see why there is strftime_l() but not snprintf_l().
It’s rather that POSIX decided to add the strl functions, so adding them (and verifying their semantics) is a necessity.
That is very much Drepper’s position:
> Correct string handling means that you always know how long your strings are and therefore you can you memcpy (instead of strcpy).
> Beside, those who are using strcat or variants deserved to be punished.
1. glibc has been handling things with a lot more civility post-Drepper, and while it's had as hard a time as any OS infrastructure project, that's helped a lot when it came to managing more polarizing issues.
2. The greatest enemy to wider Rust adoption is not that C-educated programmers are reluctant to learn and apply more solid principles. The greatest enemy to wider Rust adoption is that, despite having ample material about the past mistakes of their forerunners, the Rust community is only learning from those that relate to language design and ignoring all the other ones.
What? How is that your takeaway from the thread?
There's only a few mentions of Rust and none of them are abrasive.
This is particularly important at a point in a language's lifetime when community support is not just the best, but usually the only kind of support you can get. I like Rust and I'm very productive with it, but if anyone thinks I'm going to ask junior devs on my team to put up with the kind of stuff I see upstream, they're wrong. Just because we developed a thick skin for it on FOSS mailing lists back in the nineties doesn't mean everyone needs to.
[1]: https://man.openbsd.org/strlcpy.3I look forwards to forgetting about this and/or discovering a new foot gun.
I've learned C on Windows and the Windows API is friendly in comparison to the C API. When Windows beats you in API design, you should really reconsider some of your policies.
Is mem_copy really that much worse than memcpy? Why not memcopy? What do we gain by leaving out that single o? Why is settimeofday not sttmod if munmap is how you write memoryunmap?
It feels to me like POSIX is still being optimized for people manually poking holes into punchcards. We've had autocomplete for decades now, a few extra characters won't hurt, I promise.
What you grow up with is what you consider to be normal and I totally get it why you'd balk at strstr or other cryptic names (or LDA or ls, for that matter) but to me they look perfectly normal and are part of my muscle memory. See also: QWERTY and the piano keyboard for mechanical analogues.
And in modern times, I suspect it'd just be thematically weird to have strcpy, strcat, and safeCopyString in string.h, so old conventions still stick around.
One thing I think is the problem with making safer string functions is it's hard to do that while staying at the same very low level of abstraction. And I think a lot of code out there sets up string functions to work off incomplete information. (here is a pointer to a string buffer, trust me it's big enough to hold what you'll stuff in it)