by avar · 3y ago · 0 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.This means cdecl, stdcall or whatever modern ABIs OSes use, not C. Many languages and runtimes can call APIs and DLLs, though you may rightfully argue that their FFI or wrappers were likely compiled from C using the same ABI flags. But ABI is no magic, just a well-defined set of conventions.
And then, no one prohibits to use length-aware strings and either have safety null at the end or only copy to null-terminated before a call. Most OS calls are usually io-bound and incomparably heavy anyway.
Whether null-terminated or not, dynamic strings that solve the problem of being able to add two strings together without worrying whether the destination buffer is large enough (trading that problem for DoS concerns when a malicious agent may feed a huge input 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.
That would be a poor argument back in the 80s; and is increasingly wrong for modern processors. Compiler intrinsics can paper-over some of the conceptual gap, but dropping down to inline assembly can't be entirely eliminated (even if it's relegated to core libraries). Lots of C code relies on certain patterns compiling down to specific instructions, e.g. for vectorising; since C itself has no concept of such things. C is based around a 1D memory model which has no concept of cache hierarchies. C has no representation of branch prediction, out-of-order instructions, or pipelines; let alone hyperthreading or multi-core programming.
After all, if processors were "C VMs", then GCC/LLVM/etc. wouldn't be such herculean feats of engineering!
But seriously it’s sometimes hard to slice out what level of similarity is implied. Obvious things are somewhat less obvious to others sometimes
[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 })In case you're more interested in theory than practice, I have a different answer: I use a different API.
However, I'm aware not even that could stop you, because you could still ask "what do you do when the strings might have more than SIZE_MAX characters?", which is entirely possible (as a combination of 2 or more strings).
And to answer that, we're coming back to my original answer: It doesn't happen. I'm not calling the API with such huge strings. (And no, I usually don't keep formal proofs that it couldn't happen -- there are also an infinite number of other properties that I don't verify).
struct String { const char *buf, const char *buf_end; };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".
Source is for humans to read, it shouldn't look like alphabet soup for the idiomatic cases.
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.
It was the way plenty of languages from the 70s stored their strings, including such popular ones as BASIC.
Modern C uses things like glib's GString, which (in addition to keeping the NUL terminator) track the length and can resize the underlying memory. And people also use a lot more asprintf instead of strcpy and strcat.
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.