10 ms·
A perspective on friendly C
- twic 11y agoThis seems like a crazy conversation to be having in 2016. We're seriously considering what semantics to attach for illegal operations? How about doing what every other language of the last couple of decades does and just not allow them? > I doubt anyone is willing to pay 2x performance for their C code to be more friendly. If they were, why are they writing in C? Beats me why anyone is writing in C full stop.
- foxhill 11y agothey are not necessarily illegal operations; embedded systems and kernel development would be two such examples - an area where C is frequently used. i can list many reasons why i continue to use C, please, there's no need to suggest or imply that C has outlived its usefulness - it clearly hasn't.
- to3m 11y agoYes. The standard leaves a lot of things undefined precisely so that they can be legal, or do something meaningful - or, indeed, not - without causing the implementation to become non-standard because of it. This is what "undefined" means: what it say! It doesn't mean "illegal", and it doesn't mean "bad".
- scott_s 11y agoI think you are confused "implementation defined" and "undefined". If something is "implementation defined", it is legal for a C program to do it, even though the standard does not define what exactly must happen. Compiler writers are allowed to define a reasonable behavior for their situation. However, "undefined" does mean "illegal". Not only does the standard not say what will happen, the standard says that such behavior is not allowed in well-formed C programs. C compilers, then, tend to optimize based on the assumption that certain behaviors will not happen. This can causes weirdness when they encounter programs that exhibit this behavior - and yes, such programs have a bug. But often, the bug manifests in an even stranger way. Check out the work of John Regehr for more (academic publications: http://www.cs.utah.edu/~regehr/papers/; http://www.cs.utah.edu/~regehr/papers/; blog: http://blog.regehr.org/ http://blog.regehr.org/).
- to3m 11y agoWell-formedness doesn't appear to have a definition in C11. In the C++11 standard, the wording rather implies to me that it is a static property, suggesting that a well-formed program could therefore still induce undefined behaviour at runtime. The C11 standard is however quite clear on what undefined behaviour is: "behaviour...for which this International Standard imposes no requirements". That sounds like a far cry from illegality to me! It sounds more like it is merely... yes... undefined. This means that gcc (et al) are allowed to do what they do. It doesn't mean it's not crap.
- scott_s 11y agoI think you omitted the "erroneous" part of that definition. From http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf: 3.4.1 1 implementation-defined behavior unspecified behavior where each implementation documents how the choice is made 2 EXAMPLE An example of implementation-defined behavior is the propagation of the high-order bit when a signed integer is shifted right. 3.4.3 1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements 2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). 3 EXAMPLE An example of undefined behavior is the behavior on integer overflow. And later, 4. Conformance 2 If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe ‘‘behavior that is undefined’’. ... 5 A *strictly conforming* program shall use only those features of the language and library specified in this International Standard.3) It shall not produce output dependent on any unspecified, undefined, or implementation-defined behavior, and shall not exceed any minimum implementation limit. Substitute "strictly conforming" where I said (colloquially) "well-formed". Footnote 3 basically says that a program can still be strictly conforming if it uses of conditional features has conditional guards. All of that above tells me: "implementation-defined" and "undefined" are different concepts in the C standard, and programs with "undefined" behavior are erroneous - or, colloquially, illegal programs. Oddly, I still agree with your final conclusion: gcc and other compilers are definitely allowed to do what they do; they are following the standard.
- yarrel 11y agoIt's a fast, simple, low-level language that despite the best efforts of standards bodies is easy to reason about.
- nickpsecurity 11y agoIt's not easy to reason about. The static analysis and formal verification results that were straight-forward to obtain in languages like ML and Modula took many Master's and Ph.D.'s worth of work for C. Human review also proved to catch less than safer, systems languages in many case studies because it just has too many gotchas. In common cases, too, rather than obscure ones. So, no, C is not easy to reason about. Nor are the tools that can cheap if you want low, false positives.
- swiley 11y ago>Beats me why anyone is writing in C full stop. Deterministic execution, type checking at compile time, portability are all just three reasons.
- bdamm 11y agoThat's silly. C is legendary for non-deterministic execution. Macros make a mess of type checking. And portability is possible but only with a tremendous amount of work for any library or product large enough to matter, with many different compilers and platforms bringing their own flavor of library semantics - if they're even available. No, people write C because it's the only choice in many cases. Like where you need total control over memory management, or because you want to interact with a kernel or hardware directly, or because you want to write functions in the lingua franca of compiled code.
- Coding_Cat 11y agoI often write small bits in C because it's simply fun. And I tend to get bogged down over-abstracting when I'm working in something more modern. The simplicity of C is a boon, allowing me to focus on one small problem and easilly study the performance. (I have spend the last 2 days making a thread-pool and BLAS system in C for fun, initially results are quite good. My 4x4 matrix-matrix multiplication algorithm beats Intel's own example :D). I wouldn't be quick to use it for a large scale project which does not require 110% performance but for anything were performance is your nr. 1 goal I've found it quite refereshing.
- exDM69 11y ago> My 4x4 matrix-matrix multiplication algorithm beats Intel's own example You know you can't make such statements without putting your money where your mouth is. We want to see the code. Here's three different 4x4 matrix multiplication routines I've written (the mmmul functions). Depends on your cpu which is fastest. https://github.com/rikusalminen/threedee-simd/blob/master/include/threedee/matrix.h https://github.com/rikusalminen/threedee-simd/blob/master/in...
- pcwalton 11y ago> How about doing what every other language of the last couple of decades does and just not allow them? I fully agree. But this is not without tradeoffs: eliminating undefined behavior pretty much means (a) the performance and runtime overhead of a GC (most languages); (b) forbidding malloc (verified "mission-critical" variants of Ada, C, etc.); (c) requiring programmers to learn a lot of new concepts (Rust†). I do think that there is rapidly becoming little reason to use C except for throwaway programs, and as an industry we need to be more open to (c) if we are ever going to move beyond making the same memory management mistakes we've been continuously making since the 1960s. But I also understand the reasons why programmers continue to choose C and C++. † It's interesting to me that the biggest reason C++ programmers give for bouncing off Rust is fundamentally "I want my undefined behavior back", though very few actually word it like that.
- nickpsecurity 11y agoNo it doesn't: just means we know what it will do. It might still fail. It might still use a risky approach that allows high optimization. One can run old Pascal or Modula-2 with unsafe constructs to do anything C can do at high performance. Disallowing undefined behavior simply means the result is defined behavior. Might be safe, unsafe, any number of things. Just clearly that to developer and tools.
- pcwalton 11y agoThe point of the article is that precisely what you suggest will have extremely bad consequences for optimization. In your proposal, how do you propose to solve the load-load forwarding issue described in the article?
- jryan49 11y agoIt's a high performance, portable, systems programming, with a huge history. That's why people still use it. I'd argue most programmers today don't need to program in such a language.
- nickpsecurity 11y agoAlso known as the legacy effect. Like COBOL, the cost to rewrite, retrain, retool and so on for new language is too high to be worth it. There's also a certain mindset the new thing would have to be compatible with that's somewhat unique to C. Even C-like languages such as Cyclone couldn't break past that.
- RodgerTheGreat 11y agoI like the term "platform nepotism" to describe the fact that in Unix, C has special treatment from the perspective of APIs and ABIs. If you want to interact with the kernel or standard system libraries you must use a C-style calling convention against routines designed with the C type system in mind. Any other language must pay the cost of closing that gap, whether the cost is paid in extra tooling, clumsy rearrangement of activation records, typecasts, loss of type safety, using a restricted subset of normal language features, etc. A vast selection of libraries for most platforms impose similar bottlenecks. Unless you're willing to uproot an immense pre-existing platform, C will always have an upper hand. Reinventing all those wheels will take a long time, so it's good to see that there are a few efforts already underway.
- nickpsecurity 11y agoVery, very well-said. There is no out when one is locked into broken architecture. Any escape comes at a cost.
- jryan49 11y agoI wouldn't call it "broken". The tools we have today will be "broken" by tomorrow's standards as well.
- overgard 11y ago> This seems like a crazy conversation to be having in 2016. We're seriously considering what semantics to attach for illegal operations? How about doing what every other language of the last couple of decades does and just not allow them? If every important program on your computer (The ones written in C -- OS, web browser, text editor, language interpreters, etc.) suddenly became twice as slow for "safety", assuming you never modify those programs on your own, you'd probably be a little bit cross right? You wouldn't really care that the language is safer, you'd just notice your top of the line computer is suddenly feeling pretty slow.
- pcwalton 11y ago> If every important program on your computer (The ones written in C -- OS, web browser, text editor, language interpreters, etc.) suddenly became twice as slow for "safety", assuming you never modify those programs on your own, you'd probably be a little bit cross right? Exactly. Read the comments on literally any thread about browsers on HN to understand why sacrificing that degree of performance is unacceptable.
- jotux 11y ago>Beats me why anyone is writing in C full stop. Embedded software? All of the platforms I work on provide C/C++ compilers and driver libraries that are C only. I'm working on an ARM Cortex project right now and there isn't even C++11 support.
- foxhill 11y agoi believe the premise for a "friendly C" (wether attainable or not) is one such that, existing C programs can be compiled with a new compiler, which could, in principle, prevent certain classes of bugs. designing a new language somewhat hinders this - unless some sort of source to source translator tool could be produced, perhaps. in my opinion, C should roughly stay the way it is. we have higher level languages which provide a lot more safety, and we have the clock cycles available to absorb the reduced performance that they may incur. more importantly, compiler implementations for these languages can continue to reduce the gap between "high level" and "native C".
- pjmlp 11y agoThe thing is, such languages already existed outside AT&T before C had any value outside UNIX.
- scott_s 11y agoRegehr recently wrote a response to his own proposal, called "The Problem with Friendly C", http://blog.regehr.org/archives/1287 http://blog.regehr.org/archives/1287. HN discussion: https://news.ycombinator.com/item?id=10786512 https://news.ycombinator.com/item?id=10786512
- StefanKarpinski 11y agoThat post is linked to in the first sentence of this post.
- scott_s 11y agoSomehow I missed the reference to the follow-up, but I mostly wanted to link this HN discussion to the one from two weeks ago.
- pcwalton 11y agoFantastic article. This nails down in a very precise way what I've always said whenever the "compilers should just stop doing optimizations that rely on undefined behavior" meme comes up here. You depend on undefined behavior for performance; you don't realize you're depending on it because the optimizations "just work" most of the time; the reasons they work is due to undefined behavior, but it's easy to overlook that and blame compiler developers for being language lawyers when in fact GCC and LLVM are doing what you want them to do.
- Analemma_ 11y agoFair enough, but this isn't exactly an argument in C's favor. If you're saying "But we need this unsafe behavior for performance!", that only adds to the urgency to abandon C as soon as possible in favor of things like Rust, which should eventually have all of the speed and none of the UB insanity.
- pcwalton 11y agoI fully agree that we should be rapidly transitioning away from C and C++. :)
- valarauca1 11y ago>which should eventually have all the speed and none of the UB insanity Judging by the benchmark game [1] https://benchmarksgame.alioth.debian.org/u64q/rust.html https://benchmarksgame.alioth.debian.org/u64q/rust.html Rust has almost caught/eclipsed C. The biggest issue for the marks its behind on are stabilized SIMD support in Rust (nightly has it but its not finalized on an RFC level). [1] Look I'll save you the comment. Yes the benchmark game isn't always indicative of real world performance. Its a bunch of small micro benchmarks that demonstrate basically how quickly Regexs/Hashing/Math are in each language. While that's not everything you do when programming its a decent chunk.
- bluejekyll 11y agoWhile I completely agree with migrating towards Rust, these games are a little misleading. I can't find the source, but when I was reading some of the authors comments in the past, it sounded like there was unsafe code used. Does anyone have a link to the source used in these tests?
- kazinator 11y agoStart by removing gratuitous undefined behavior from the dialect: undefined behavior which has not reason to exist because it arises from of the lack of requirements with regard to some translation aspect of the language, and not anything related to a run-time difficulty. For instance, the unspecified order in which function arguments are evaluated, or the operands of most operators, or initializers in a declarator and such. In combination with certain uses of side effects, this creates undefined behavior (and even when not undefined, it can create surprises and bugs). This is purely a C semantics problem, not connected to the way the machine works, or the large scale way in which programs and their data fit together. And let us note that even if evaluation order is pinned down by the language semantics, the compiler can still re-arrange it anyway, when it can recognize opportunities in which re-ordering evaluation makes no difference (the result, including all effects, are still as if it had been left to right). Contrast that with, say, bounds checking arrays, where the neglect to do so is justified by the fact that pointers don't carry the size information, since they are mapped to machine addresses, which is a translation decision that has deep, non-localized semantic implications. Wider pointers don't fit into a register, which affects how they are passed between functions. They take up more space in every data structure which has pointers, and so on. There is a tangible, external difference, and performance impact. A reasonable dialect in C should sacrifice safety only when there is a tangible performance issue. Undefined behaviors at translation time (particularly in the preprocessor!) should be completely banished. Here is one: there is no reason why a preprocessor token pasting operation (A ## B) which results in an invalid token should be undefined behavior. The execution of the preprocessor is quasi cost-free. Whether or not two elements pasted together to form a valid token can be checked, and diagnosed. The few preprocessor cycles which that requires are worth it! The fact that it's not practical to banish or diagnose all undefined behaviors (nor desirable or reasonable to do so, since UB is an area for useful extensions) shouldn't be used as an excuse not to eliminate some of the silly ones.
- kevin_thibedeau 11y agoThe undefined behavior is there so that the language can be used across heterogeneous systems. 9-bit chars, 36-bit words, 1's complement arithmetic, decimal registers, NULL somewhere other than address 0? You can have all that with standard compliant C.
- stcredzero 11y agoLet's say someone developed a variant of Go with manual memory management. How far would this be from a "friendly C"? EDIT: " I doubt anyone is willing to pay 2x performance for their C code to be more friendly. If they were, why are they writing in C?" Because it's friendly? Because the cost/benefit in terms of avoided bugs and productivity is worth it to the company/shop.
- pcwalton 11y ago> Let's say someone developed a variant of Go with manual memory management. How far would this be from a "friendly C"? Depends on what the semantics of that hypothetical Go variant are. How would that Go variant solve the load-load forwarding problem described in the article? > Because it's friendly? Because the cost/benefit in terms of avoided bugs and productivity is worth it to the company/shop. I think the point the author was making is that if you are OK with that performance hit you're probably OK with Java, which banishes undefined behavior in the C sense entirely.
- stcredzero 11y agoI could see someone being ok with 100% overhead, but not with 400%. Last I checked (which was years ago) hitting 50% native speed in a JIT managed language was an admirable feat and not guaranteed.
- helmut_hed 11y agoI doubt anyone is willing to pay 2x performance for their C code to be more friendly. If they were, why are they writing in C? To me this is the fundamental issue with the friendly/boring C proposals. The whole reason to use C/C++ anymore is for performance, in return for which you are responsible for certain things - like using only defined behavior. If you are writing e.g. crypto code, why not use a higher level language that provides more checks and guarantees, and is generally easier to reason about? Or segregate the performance-critical "engine" type code into C++ and use something higher level for everything else?
- rixed 11y agoCrypto may be one of the fields where you need tight control over speed of execution to alleviate timing attacks. The mere presence of a GC can be exploited.
- nkurz 11y agoAs a simple example, let’s consider trying to establish semantics for stray (i.e. out of bounds) read and writes. We can start by trying to define what happens for a stray read. That’s fairly easy, we can simply return an undefined value. I don't disagree with this piece, but I think it's missing the thrust of the "friendly C" argument. The desire (at least I feel it) is simply for the compiler to "do what I mean", rather than making unexpected optimizations based on undefined behavior. There is no expectation that the resulting language will be "safe" as the word is normally used. If one wants safety (and can accept the performance compromise that this entails) then there are alternative languages to choose from. Instead, "friendly C" has much simpler ambitions: replace undefined behavior with compiler specified behavior. The spec could simply guarantee that if you read an out-of-bounds value, that the compiler will generate assembly that attempts to read the value at that address. Having the program segfault on the attempt is perfectly acceptable. The only thing that is not acceptable is for the compiler to reason that the read will be out of bounds, and thus decide to omit the error checking code that follows.
- pcwalton 11y ago> The spec could simply guarantee that if you read an out-of-bounds value, that the compiler will generate assembly that attempts to read the value at that address You didn't understand the example. Your proposal destroys load-load forwarding, as the article demonstrates.
- anon4 11y agoWhy not extend the language with an "rmem" keyword or function that you use like this: rmem(pointer) and you're guaranteed to produce a memory read, rather than reusing a value in register. Then say that the compiler is free to assume two pointers/arrays etc. never overlap. Then, introduce linters which can detect most cases of these-two-pointers-might-overlap. Maybe runtime ones like valgrind. I want to write C as high level assembly. If I put values in registers and reuse them, then I'm opening myself for the same kind of problems as if I'm writing C and not doing explicit memory reads.
- 11y ago
- dmitrygr 11y ago> In the example above, your normal C compiler could return “0” because it assumes the intervening write can’t change the value at p_int not unless you use the restrict keyword...
- munificent 11y agoint foo(int* p_int, float p_float) { int a = *p_int; *p_float = 0.0; return a - *p_int; } Should that be `float* p_float`?
- exDM69 11y agoThe "2x slower" is an extremely conservative estimate if all loads and stores were bounds checked. Given the indirect effects on program optimization, it might be closer to 10x for practical programs.