396 points · by dmalcolm · 2y ago · 143 comments
I would say the #1 reason I stop learning a technology is because of frustrating or unclear errors.
EDIT: Getting a bit of topic, but I meant more because I love C and would love it more with rust level error messages.
This is a veering off topic, but I do agree that Nix-the-language has a lot of issues.
(You might suggest Guix, but I don't want to faff about with non-supported repositories for table stakes like firmware and such. Maybe Nickel will eventually provide a more pleasant and principled way to define Nix configurations?)
People getting used to good errors and demanding more, is part of the virtuous circle that keeps them high quality.
Making good looking diagnostics requires UX work, but making good diagnostics requires a flexible compiler architecture and a lot of effort, nothing more, nothing less.
Overly verbose error messages that obscure more than illuminate are chief complaint against C++.
Honestly, they can just sap all the energy out of a project.
It's why the Constraint system was important for C++.
Why would anyone use the resulting language over C? What you're describing is C with a slightly friendlier compiler.
(Signed overflow being a prime example where you really either just need to define what happens or accept that your compiler is basically never going to warn you about a possible signed overflow -- which is UB. The compromise here by Rust is to allow one to pick between some implementation defined behaviors. That seems pretty sensible.)
Another is reproducibility and accuracy: LLMs have a tendency to confidently state things that are wrong, and to say different things to different people, the compiler has the advantage of being deterministic and generally have better understanding of what's going on to produce correct suggestions (although we still have cases of incorrect assumptions producing invalid suggestions, I believe we have a good track record there).
If those tools help you, more power to you, but I fear their use by inexperienced rustaceans being misled (an expert can identify when the bot is wrong, a novice might just end up questioning their sanity).
Side note: the more I write the more I realize that the same concerns I have with LLMs also apply to the compiler in some way and am trying to bridge that cognitive dissonance. I'm guessing that the reproducibility argument, ensuring the same good error triggers for everyone that makes the same mistake and the lack of human curation, are the thing that makes me uneasy about LLMs for teaching languages.
> "Missing semicolon on line 32"
I looked at it, looked at them, and said "You're missing a semicolon on line 32". They looked at line 32 and, hey! look at that! Forgot a semicolon at the end. Added it and their program worked fine.
Even the best error messages can't help some people.
I tried to use GCC's analyser several times, but I couldn't find any good front ends to it that make the output readable. Clang has multiple (reasonably good HTML output, CodeChecker, Xcode integration, etc.). How do you read the output?
Furthermore, I find that GCC produces many more false positives than Clang.
I do find some false positives, but I haven't had many of them to be a deal breaker for me. Aside from what I mentioned about the errors being descriptive, I do like the defaults and that it's part of the compilation process.
for example, possible malloc null warning is on by default (which i don't think is on clang).
https://news.ycombinator.com/item?id=39918278 ("GCC 14 Boasts Nice ASCII Art for Visualizing Buffer Overflows (phoronix.com)", 2 hours ago)
It was a drop in replacement shim for an arbitrary executable that would pretend to be the original when invoked, fork off the original and hook up to its stdout and stderr.
The error output was then fed to a custom GPT assistant that knew what program the errors came from. That assistant was tasked with turning the original errors into friendly human readable form. The output from the assistant was then sent out of the shim stderr.
It worked very well, but then I got really sick and wasn't able to work on it anymore.
I was using it for GCC / Clang errors because I had become tired of staring at heavily nested compiler dumps for concept/template issues, but you could use it for anything of course.
It would be a nice project for someone to build again, do it properly and generalize it since it doesn't look like I am going to be bouncing around again for a while.
You can see an example of the output here: https://godbolt.org/z/aan6Kfxds (that's the first example from the article, with -fdiagnostics-format=sarif-stderr added to the command-line options)
I experimented with SVG output for the diagrams, but didn't get this in good enough shape for GCC 14.
I did attempt to use the SARIF output just after your previous blog post a year ago, with a CMake based project, but after an hour I still wasn't able get the warnings to show within the context of the source code.
The -fdiagnostics-format option isn't even in the GCC documentation, your blog post is the only place where I saw it mentioned.
In short: I'd love to use GCC's analyser, and tried it several times, but my bottleneck is usability, ease of setup, and a proper interface to help sort out the many false positives from the true issues.
if (nbytes < sizeof(*hwrpb))
return -1;
if (copy_to_user(buffer, hwrpb, nbytes) != 0)
return -2;
The fix that was done was: if (nbytes > sizeof(*hwrpb))
But I think the correct fix is: if (copy_to_user(buffer, hwrpb, sizeof(*hwrpb)) != 0)
It never makes sense to copy out of the hwrpb pointer any size other than sizeof(*hwrpb).and sizeof(hwrpb) is now 16 bytes, then you will be copying 12 bytes of data too many from the caller, potentially reading into memory it doesn't own. I would say that should be avoided.
The better solution I believe would be to only copy the minimum amount of bytes supported by caller & callee. So:
nbytes = MIN(nbytes, sizeof(
hwrpb));Which should ensure backwards and forwards compatibility, assuming the version info of hwrpb->size is respected then the fact that part of the hwrpb struct isn't initialized shouldn't matter.
if (nbytes < sizeof(*hwrpb))
If the buffer isn't large enough to hold *hwrpb, then it already fails. The original check was good, only needed to change the amount of bytes copied to sizeof(*hwrpb).Recall that the API is intended to be used like this:
struct hwrbp buf;
getsysinfo(GSI_GET_HWRPB, &buf, sizeof(buf), /* .. */);
At first glance, it might seem unnecessary to pass the buffer size at all, because in theory the user and kernel should agree on what the sizeof(struct hwrbp) is. But the reason it is passed is because there are various reasons why the separately compiled kernel and user binaries might disagree (e.g., incorrect compiler flags, wrong header file being used, struct has changed between different versions, etc.), and it's useful to detect that. So you can make an argument that the most conservative check is: if (nbytes != sizeof(\*hwrpb)) return -1;
After all, if the user and kernel disagree on the correct size of the struct, then something is wrong! But allowing nbytes < sizeof(*hwrpb) has the benefit that the kernel developers can add fields at the end of the struct without breaking backward compatibility with older applications.I would agree with you if the kernel had some other mechanism to pass the size of the buffer that was actually filled to the client (like e.g. the read() syscall does) but the getsysinfo() API doesn't return that data, so the kernel must either fill the buffer entirely or return failure.*
I doubt the analyze variant would fare any better.
At $JOB we disable it on a line by line basis, but I'm not sure it is worth the effort.
I haven't done much C development lately, so I'm curious how often `strcpy` and `strcat` are used. Last I checked they're almost as big no-nos as using goto. (Yes, I know goto is often preferred in kernel dev...) Can anyone share on how helpful the c-string analyses are to them?
While use of functions like `strcpy` are less advisable, there are contexts in which they are guaranteed to be correct unless other strong (e.g. language-level) invariants are broken, in which case you have much bigger problems. In these somewhat infrequent cases, there is a valid argument that notionally safer alternatives may be slightly less efficient for no benefit.
Writing a strbuffer type and associated functions isn't particularly hard and the resulting interface is nicer to use, safer, and more efficient.
For C, absolutely. For C++, it's likely a footgun.
(I'm not however fond at all of longjmp)
I don't think there is any justifiable reason to use setjmp/longjmp in modern C code. At best it's a crude imitation of throw/catch semantics; if you really want that, C++ has a real implementation.
The strxcpy family on the other hand is complete garbage and should never be used for any reason. I'm horrified that they're used in the kernel at all. All of those functions (and every failed attempt at "fixing" them) should have been nuked from orbit.
Indeed a like a few gotos here and there for doing cleanup toward the end of the function.
Goto + Switch (or the GCC computed goto extension) is also a wonderful way to implement state machines.
strlcpy() is better and what most people think strncpy() is, but still results in truncated strings if not used carefully which can also lead to big problems.
char buf[1000];
strncpy(buf, "foo", sizeof(buf));
This writes 3 characters and 9997 zeros. It's probably not what you want 99% of the time. strncpy (dst, src, (sizeof dst) - 1);
dst[(sizeof dst) - 1] = 0;
int truncated = strlen (dst) - strlen (src);
Without the extra two lines after every strncpy, you're probably going to have a a hard to discover transient bug.I've seen a lot of code where people changed from `strcpy` to `strncpy` because they thought that was safety and security best practice. Even sometimes creating a new security vulnerability which wasn't there with `strcpy`.
`strncpy` does two unexpected things which lead to safety, security and performance issues, especially in large codebases where the destination buffers are passed to other code:
• `strncpy` does NOT zero-terminate the copied string if it limits the length.
Whatever is given the copied string in future is vulnerable to a buffer-read-overrun and junk characters appended to the string, unless the reader has specific knowledge of the buffer length and is strict about NOT treating it as a null-terminated string. That's unusual C, so it's rarely done correctly. It also doesn't show up in testing or normal use, if `strnlen` is "for safety" and nobody enters data that large.
• `strncpy` writes the entire destination buffer with zeros after the copied string.
Usually this isn't a safety and security problem, but it can be terrible for performace if large buffers are being used to ensure there's room for all likely input data.
I've seen these issues in large, commercial C code, with unfortunate effects:
The code had a security fault because under some circumstances, a password check would read characters after the end of a buffer due to lack of a zero-terminator, that authors over the years assumed would always be there.
A password change function could set the new password to something different than the user entered, so they couldn't login after.
The code was assumed to be "fast" because it was C, and avoided "slow" memory allocation and a string API when processing strings. It used preallocated char arrays all over the place to hold temporary strings and `strncpy` to "safely" copy. They were wrong: It would have run faster with a clean string API that did allocations (for multiple reasons, not just `strncpy`).
Those char arrays had the slight inconvenience of causing oddly mismatched string length limits in text fields all over the place. But it was worth it for performance, they thought. To avoid that being a real problem, buffers tended to be sized to be "larger" than any likely value, so buffer sizes like 256 or 1000, 10000 or other arbitrary lengths plucked at random depending on developer mood at the time, and mismatched between countless different places in the large codebase. `strncpy` was used to write to them.
Using `malloc`, or better a proper string object API, would have run much faster in real use, at the same time as being safer and cleaner code.
Even worse, sometimes strings would be appended in pieces, each time using `strncpy` with the remaining length of the destination buffer. That filled the destination with zeros repeatedly, for every few characters appended. Sometimes causing user-interactions that would take milliseconds if coded properly, to take minutes.
Ironically, even a slow scripting language like Python using ordinary string type would have probably run faster than the C application. (Also Python dictionaries would have been faster than the buggy C hash tables in that application which took O(n) lookup time, and SQLite database tables would have been faster, smaller and simpler than the slow and large C "optimised" data structures they used to store data).
I don't think so. Gotos are fine, strcat and strcpy without a malloc with the correct size in the same scope is a code smell.
Huh? Why is goto a no-no? It is there for good reason. I think we all agree with Dijkstra that, in his words, unbridled gotos are harmful, but C's goto is most definitely bridled. I doubt any language created in the last 50+ years has unbridled gotos. That's an ancient programming technique that went out of fashion long ago (in large part because of Dijkstra).
But when unbridled gotos were the only tool in the toolbox, bad code was an inevitability in a codebase of any meaningful size. Not even the best programmer was immune. This is what the "Go to statement considered harmful" paper was about.
It was written in 1968. We listened. We created languages that addressed the concerns raised and moved forward. It is no longer relevant. Why does it keep getting repeated in a misappropriated way?
The idiom `if (error) goto cleanup` is about the only thing I see goto used for. What flow control replaces that other than exceptions?
The problem there is the 30K line function, not the goto!
When clang was new users switched to it just for the error messages and promises not to fuck them over too hard e.g. start exploiting that signed integer overflows are "ackchyually undefined". Which is of course correct, but not what users complained about. They complained that what they considered a bugfix release broke code because the defaults changed and -fwrapv didn't even catch all the cases that used to compile to what the user needed/expected.
https://lists.gnu.org/archive/html/emacs-devel/2017-04/msg00...
So not surprising gcc devs weren't especially interested in on it, since Lord Stallman can come in and decree it unethical on a whim out of misguided fears.