Comments on the MISRA C coding guidelines (2011)
knosof.co.uk
knosof.co.uk
1. Avoid complex flow constructs, such as goto and recursion.
2. All loops must have fixed bounds. This prevents runaway code.
3. Avoid heap memory allocation.
4. Restrict functions to a single printed page.
5. Use a minimum of two runtime assertions per function.
6. Restrict the scope of data to the smallest possible.
7. Check the return value of all non-void functions, or cast to void to indicate the return value is useless.
8. Use the preprocessor sparingly.
9. Limit pointer use to a single dereference, and do not use function pointers.
10. Compile with all possible warnings active; all warnings should then be addressed before release of the software.
[1] https://yurichev.com/mirrors/C/JPL_Coding_Standard_C.pdf
[2] https://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Dev...
Fancy language constructs and complex algorithms are generally not helping. Keeping the program simple helps verification using automatic tooling and manual code reviews because the risk of hidden side effects or undiscovered defective code paths is minimized.
More precisely, however, heap allocation is usually accepted during the initialization phase (the moment when you can still abort the process with no consequence if needed, i.e in the case of a rocket, before it takes off).
These guidelines aren't meant to be applied for "general-purpose" code, which may be used by a human operator in a million possible ways. It's usually very special-purpose code that does only a handful of things (and if it doesn't, that's meant to be treated more like a design problem than anything else). Consequently, it's not that hard to figure out how much memory you need from the very beginning, and not allocate any of it on the fly.
Allocating memory on the heap complicates analysis a lot. It introduces potential timing issues. You have to make sure that no matter how your program runs, it'll always be able to allocate the memory it needs -- or to design it so that it runs correctly (i.e. predictably and in the right manner) even when an attempt to allocate memory fails. You have to bring in pretty complicated third-party code, or spend a lot of time and money writing your own (writing a memory allocator is trivial, but writing a good, safe one isn't exactly a walk in the park).
As for function pointers... that's more or less the same story. You don't need them that often for this sort of code, and when you do, the trade-off is usually worth it.
(In very rare situations it's not, but IMHO coding standards do the right thing here. Judgement calls about these things are very much subject to ego and organization politics. It's always better to err on the side of having to do extra work under some circumstances).
These guidelines don't produce the most good-looking code but they do make it harder to shoot yourself in the foot.
Obviously, there is an argument to be made about alternative solutions, such as code that you cannot physically point at your foot, but that's a discussion for another time (and also way more complicated than that...)
In the PLC / industrial automation world there's the added consideration that your code will probably need to be maintained (or at least navigated and understood) by people with limited software skills. And given that systems tend to be "wide, not deep" (as in, hundreds or thousands of mostly-independent inputs that only interact via very simple logic), usually ladder logic or function block diagrams are the preferred way to implement these sorts of systems. Even Structured Text is considered a bit too technical by most people.
Which is why the writing of this blog post is so bizarre, telling you that Rule 9 is pointless but not saying what Rule 9 is.
Admittedly the document is fairly priced at £10 per user - but good luck getting a rule added into an open source project like clang analyzer when you can't tell them what the rule is supposed to do
cppcheck has been making an effort in this direction - giving you the unique opportunity to back a kickstarter [2] that can't say what it's doing.
[1] https://www.misra.org.uk/forum/viewtopic.php?t=1189 [2] https://www.kickstarter.com/projects/3300446/add-all-missing...
That being said, this isn't a spec for good software. It's more of a spec for auditing software that has to work in a predictable way. The main consumers for this are, yes, software engineers and managers, but it's especially useful for framing quality assurance efforts.
It's entirely possible to check all the boxes while still cranking out swill. For instance, I'd be surprised if the Volkswagen software that famously assisted in cheating on emissions tests was properly MISRA reviewed since a lot of the guidelines have to do with making sure the code does exactly what is intended, no more or no less. A full review with someone who could read code would either require the reviewer to ask "this is the code that cheats on the test, right?" or to be oblivious as to the full purpose for the code.
Ideally, these un-safe methods would be removed from the C language, but then that would be removing the low level ability from C that it is very suited for. So these guidelines exist to note the most dangerous parts of C, but it is still up to the developer to determine how to use it safely.
However, modern engine control units have such complex requirements that complete verification against all of them is very unlikely in practice, especially in a third party audit.
I'm not sure that's true. Compilers (let's say, MSVC++) tend to support a mismash of standards and de-facto standards. If you are forbidden from using a construct not supported by the C standard (under which you are building) you are in fact specifying strict compliance with a particular standard, which is meaningful.
The best end result was largely unreadable code. Why? Because the junior developers tasked with the MISRA compliance efforts were measured by reducing the number of warnings instead of improving code quality.
The bonus was actual breakage in the field, as the test coverage of the legacy code being converted was particularly abysmal. But not to worry, another junior dev was tasked with creating unit tests for every function! With a codebase unsuitable to unit testing through fuzzy interfaces, that effort was about as effective as one would expect, too. </rant>
- goto is useful for error handling and when you have to double break
- function pointers are useful and easy to read state machines and also for functional programming, which is sometimes easier to comprehend and produces better patterns
- "Restrict functions to a single printed page." in my experience does not work. I would rather partition functions by topic or by level of "zoom"/abstraction
- "Use a minimum of two runtime assertions per function." that doesn't really say anything useful imho. Use as much as experience tells you too.
I agree with the rest
a la
bool noNaNs(float[] test); bool isSorted(inout float[]); float[] sort(float[] input) in(input.noNaNs) out(o; o.isSorted) { return input; }
Not sure about goto, I'm not sure what I prefer between goto or a while loop and a very big switch statement (let's say) to implement a lexer.
Personally I can't see how function pointers are worse than languages pushing return addresses onto the same fucking stack they push data.
Restrict functions to a single page sounds like a home work assignment rule that's been cargo culted into a standard. Functions should do one logical thing and nothing more or LESS.
The two runtime assertions might make sense for a space craft where cosmic rays are randomly flipping bits. Don't make much sense otherwise. My theory is functions that modify state should barf hard when told to do something stupid. Functions that don't should return an error.
MISRA C doesn't get me there - it helps, but isn't enough to guarantee the absence of undefined behaviour, despite its 'rule' to avoid UB [0] (which is not mechanically verifiable). It would presumably be possible to use a Turing-complete subset of C, defined such that compliance to it could be verified automatically. I imagine such a subset might be awfully claustrophobic, but my intuition is that this should be possible.
Another approach would be to write code in a different language entirely - either one defined to be free of undefined-behaviour, or one where the absence of it can practically be established statically/automatically. We could then transpile to C code. The transpiler could then guarantee never to generate C code with undefined behaviour.
It seems to be possible to do this today by writing Ada SPARK code and using the (proprietary, terribly pricey) CCG transpiler. [1] (SPARK is a fine choice here. When programming in the SPARK subset, it's impossible to invoke Ada's equivalent of undefined behaviour [0].)
Is there a 'tidier' answer to this problem, or perhaps something obvious that I'm missing?
A related question: is there a 'tidy' way that I can be certain my C code is insensitive to platform-specific behaviours (what C calls unspecified), such as the evaluation-order of argument expressions?
[0] https://learn.adacore.com/courses/SPARK_for_the_MISRA_C_Deve...
[1] https://www.electronicdesign.com/industrial-automation/artic...
A does not imply B. There's often broken generated code that is read by humans. Readability of generated code can be helpful and often essential, in finding bugs.
I just pulled it up and here's what he said in the interview ad verbatim:
"All of this code is Open Source, readable, and I believe now it's all MISRA C-compliant, too."
Interviewer cuts in: "What's that mean?"
"Um, MISRA is like the automotive coding standard. At first I—you know, I've come to respect—I've been reading, like, the standards lately, and I've come to respect them, they're actually written by very smart people!"
[The interviewer says something irrelevant to the point here that I don't feel like typing up and that Hotz didn't seem to agree with and that I don't really agree with.]
"MISRA's written by, like, computer scientists. And you can tell by the language they use—you can tell by the language they use, they talk about like whether certain, uh, conditions in MISRA are decidable or undecidable, and I and I and I...you mean like the halting problem? And, yes! Alright, you've earned my respect, I will read carefully what you have to say, and we want to make our code compliant with that."
He obviously worded his praise a bit strangely, but a standard written well enough to tame someone like George Hotz is fairly alluring. I was probably as surprised as he was when I found out how good they were. They set the bar so high that very little matches it as far as technical writing goes.
I feel like I'm reading "The Pact" from the Silo series of sci-fi (Wool, Switch, Dust). Hopefully you get the reference.
This goes far beyond coding guidelines. It reads more like THINKING guidelines, fallacies to decision making to resource allocation.
Who is the target audience for this?
Systems programmers in the automotive industry, and their direct superiors.
Although not an official regulatory requirement it is often used as a guideline in low-resource targets for Medical embedded systems.
In aerospace for example the JPL guidelines are also influenced by the initial MISRA consortium effort. And at least in style and motivation the JSF for C++ ia also influenced by MISRA.
Well, yes. That's the "safety culture" influence, the idea that there is not really such a thing as an "accident". With careful thought all the possible outcomes should be forseeable, and mitigation should be in place for all risks. This includes what might be called affordances for the programmer - tools that are prone to misuse and mistakes should be avoided. Guardrails around thought.
This chafes if you got into programming for the freedom, but is a lot more reassuring for people driving the car.
(edit: my own personal benchmark for technical writing is the dully-named "App Note 47: High Speed Amplifier Techniques" by the legendary Jim Williams. From its own preface:
"This publication represents the largest LTC commitment to an application note to date. No other application note absorbed as much effort, took so long or cost so much. ... We intend to supply useful high speed products and the level of support necessary for their successful application(such high minded community spirit is, of course, capitalism’s deputy)."
It is 132 pages including photographs, illustrations, screenshots of osciliscopes, equations, and a few jokes.)