9 ms·
Checked C
- galkk 6y agoI want to like the idea, but to me the examples looks like the abomination that was (is?) managed C++. As per wiki, they state that they have automatic conversion tools, but I highly doubt that this will be used in production, even in Microsoft. Example from their wiki (https://github.com/microsoft/checkedc/blob/master/samples/string-helpers.c#L140 https://github.com/microsoft/checkedc/blob/master/samples/st...): // Delete all c from p (adapted from p. 47, K&R 2nd Edition) // p implicitly has count(0). checked void squeeze(nt_array_ptr<char> p, char c) { int i = 0, j = 0; // Create a temporary whose count of elements can // change. nt_array_ptr<char> s : count(i) = p; for ( ; s[i] != '\0'; i++) { // We need to widen the bounds of s so that we // can assign to s[j] when j == i. // (In the long run, this will be taken care of by the // flow-sensitive bounds widening). nt_array_ptr<char> tmp : count(i + 1) = s; if (tmp[i] != c) tmp[j++] = tmp[i]; } // if i==j, this writes a 0 at the upper bound. Writing a 0 at the upper bound // is allowed for pointers to null-terminated arrays. It is not allowed for // regular arrays. s[j] = 0; }
- The_rationalist 6y agoRelated but for c++ https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-posted/ https://herbsutter.com/2018/09/20/lifetime-profile-v1-0-post... There is also cyclone. Finally, if you missed it there is a new probabilistic variant of asan: https://llvm.org/docs/GwpAsan.html https://llvm.org/docs/GwpAsan.html (and also a hardware accelerates one but only for ARM)
- moonchild 6y agoCyclone has been dead for decades, and only works on 32-bit anyway. (I did some work to try to port it, but it's not very practical to.)
- moonchild 6y agoRecent discussion: https://news.ycombinator.com/item?id=25989115 https://news.ycombinator.com/item?id=25989115
- trestenhortz 6y agoThe real problem with C and C++ is you have to be an expert to not make disastrous errors. And you have to always get it right.
- gypsyharlot 6y agoAnd the industry's experts who are famous for writing "idiomatic C" keep making mistakes constantly that result in new CVEs.
- Cthulhu_ 6y agoC/C++ is a potential footgun, but it has its place for applications where they need precise control.
- the-smug-one 6y agoYou're not precise though. Precise ought not mean "It is possible to express precise thought regarding memory, yada yada, in this language", it ought mean "A person is capable of expressing precise thought regarding [...] in this language, without making mistakes".
- tene 6y agoCould you offer some insight or examples of where or how C permits or enabled more-precise control than is permitted or enabled by Rust?
- wvenable 6y agoYou need unsafe in Rust just to do a doubly-linked list.
- tene 6y agoYes, I agree, you can implement a doubly-linked list in Rust exactly as you can in C, with the same precise control. You can even implement intrusive collections: https://docs.rs/intrusive-collections/ https://docs.rs/intrusive-collections/ Unsafe is a normal part of the language, and how you manually implement precise control behind a safe reusable abstraction whose correct use can be verified by the compiler. Do you have any examples of precise control you can express in C, but can't express in Rust?
- Animats 6y agoThis is similar to an approach I proposed in 2012.[1] Microsoft: "Rather than changing the run-time representation of a pointer in order to support bounds checking, in Checked C the programmer associates abounds expression with each_Array_ptr<T>-typed variable and member to indicate where the bounds are stored. The compiler inserts a run-time check that ensures that deferencing an_Array_ptr<T>is safe (the compiler may optimize away the runtime check if it can prove it always passes). Bounds expressions consist of non-modifying C expressions and can involve variables, parameters, and struct field members. For bounds on members, the bounds can refer only to other members declared in the same structure." Me: No array descriptors are generated by the compiler. The programmer tells the compiler the size of the array as an expression, and that expression is evaluated at the point in the program where the relevant declaration appears. The Microsoft syntax is very Microsoft. It involves many leading underscores and long keywords. What I proposed involved adding C++ "&" references, and making lengths explicit in the places in C where you can write "[]". This is more concise. The basic idea is the same, though. Arrays have a length, which is defined by some expression on nearby variables, such as other fields of the same struct or other parameters in the same function call. C programs that work usually have a length around somewhere, but the compiler doesn't know where it is. Make that explicit, and you can check. If you add ranges and references to C syntax, and provide length information, you can deal with one of C's three big questions - "How big is it?" (The other two big questions are "who owns it?" and "what locks it?") This area is 10% technology and 90% politics, so you need sizable organizational support to make much happen. [1] http://www.animats.com/papers/languages/safearraysforc43.pdf http://www.animats.com/papers/languages/safearraysforc43.pdf
- unwind 6y agoCool, thanks for working in this area of course. I had a quick look at your paper out of general interest (I'm probably a very conservative C programmer, I would rather move to Rust than modify C to make it safer). I didn't understand this part: int arr100[100]; // an array of 100 ints arr100& arr100r; // ref to array of 100 ints > This is valid C++ today. Is it really? That doesn't look valid to me, but I'm well and truly much more of a C programmer than a C++ one. I did try it on Godbolt, and got an error: <source>:2:1: error: 'arr100' does not name a type 2 | arr100& arr100r; // ref to array of 100 ints | ^~~~~~ Compiler returned: 1 Apologies if this is already mentioned somewhere in errata or something, or if I'm simply being too dense.
- amir734jj 6y agoYet another solution to make C type check. If people want to use type checked C, the they can use C++/Rust/Golang as the overhead would be minimal. C gives programmer tons of freedom and that's the beauty of the C. Taking away that freedom eliminates the whole purpose of using C in the first place.
- Cthulhu_ 6y agoYou can't just rewrite an existing application to another language. What you can do is add tooling to an existing codebase to improve it. Facebook did this some time ago with Flow for Javascript.
- pjmlp 6y agoAgreed, but that also requires throwing away UNIX clones and I don't see that happening on my lifetime.
- quelsolaar 6y agoIf anyone from Microsoft is listening: I'm a very experienced C programmer and what I would like, much more then a new language version, are some basic OS functions where I can query the status of a pointer. Is it readable? Is it writable? Where does the memory allocation start and end? Is the memory in the heap or stack, or a memory mapped file? All the information is available inside the OS, but I cant get at it. If it was available it would be possible to write all kinds of instrumentation. If it was possible (in debug mode) to get the layout of the stack, that would also be super useful. Buffer overruns are really mostly a problem when they are on the stack. By warping malloc and free, you can easily find buffer over runs, memory leaks and double frees. They become a none issue. But with stack memory you have very little control. I avoid using the stack for operations where this might be an issue, just because its so much harder to debug. I would love to be able to write APIs that have built in tests (in debug mode) where all pointers are checked, and if anything is broken the API can fail gracefully and give out precise errors.
- murderfs 6y agohttps://devblogs.microsoft.com/cppblog/addresssanitizer-asan-for-windows-with-msvc/ https://devblogs.microsoft.com/cppblog/addresssanitizer-asan...
- quelsolaar 6y agoI would like to be able to query it. Windows used to support IsBadReadPtr and IsBadWritePtr but they have been deprecated. I'm not aware of something similar on Linux.
- tinus_hn 6y agoIt’s not very useful, if a pointer is bad and you access it you’ll crash anyway. The problem is when the pointer is manipulated to be good, but not pointing at what you expect.
- quelsolaar 6y ago
- roca 6y agoThere is nothing lifetime-related here, right? I.e. nothing to help prevent use-after-free errors.
- dep_b 6y agoIt would be nice if you can move your existing C codebase piecemeal towards a more safe standard using linters and compiler checks. Because projects with a lot of legacy (mostly C) code (which means all popular operating systems) cannot be rewritten towards safer languages without having an additional motivation like features that have a meaning to the business. So most likely a lot of it will stick around for a very long time but still needs to become 2021 level secure.
- guerrilla 6y agoOne way to do that could be with frama-c [1]. It allows you to put the checks in comments that are interpreted prior to C compilation. See the example here [2]. 1. https://frama-c.com/ https://frama-c.com/ 2. https://frama-c.com/html/acsl.html https://frama-c.com/html/acsl.html
- astrange 6y agoiOS is doing this. No more information is available though. https://support.apple.com/guide/security/memory-safe-iboot-implementation-sec30d8d9ec1/web https://support.apple.com/guide/security/memory-safe-iboot-i...
- tinus_hn 6y agoWhat a lot of people don’t realize though is that only a company with the force of Apple can get the kind of access to the hardware you need to write this level of firmware. Apple writes every instruction executed by the processor from the moment it powers on until it’s booted. Unlike for instance devices running on the Intel platform, where the processor is running an entire OS behind your back, and you can’t turn it off.
- userbinator 6y agoThat's not surprising. It's Apple, after all. I get downvoted a lot for saying this, but I'll say it anyway: I'm getting increasingly convinced that the purpose of this whole "safe languages" push is ultimately to the benefit of companies who want to deepen and their control over users. If you look at who the biggest proponents are, it's pretty obvious what their motivations are. They don't want you jailbreaking or rooting, they want to force you into their walled garden and keep you there. https://news.ycombinator.com/item?id=7883026 https://news.ycombinator.com/item?id=7883026
- WalterBright 6y agoAnother way to do it: https://www.digitalmars.com/articles/C-biggest-mistake.html https://www.digitalmars.com/articles/C-biggest-mistake.html i.e. just change: void foo(char* a) to: void foo(char[] a) and that passes a phat pointer (pointer and length) instead of just a pointer, enabling array bounds checking.
- yokljo 6y agoThis comment could mislead people: The linked article explicitly says that * and [] are identical when used in function arguments. It then goes on to suggest a possible syntactical change for the C language where the [] syntax would be a fat pointer.
- mhandley 6y agoThe article you reference actually proposes new syntax: void foo(char a[..]) for passing an array pointer and length, and to eventually deprecate: void foo(char a[]) Personally I like this suggestion, but as the article is 12 years old, I'm obviously in a minority.
- jodrellblank 6y agoPsst, he didn’t just reference the article, he wrote it.
- mhandley 6y agoThanks for pointing that out! Still, his comment here doesn't quite match the article and certainly confused me. Is he now suggesting: void foo(char[] a) instead of what he originally proposed, which is: void foo(char a[..]) If so, that does seem cleaner. I still like the overall suggestion.
- pron 6y agoIn the future, new low-level projects will probably use languages that make it easier to write safe programs, like Rust, Zig, perhaps new languages -- each according to the programmers' tastes and preferences -- but what many people might not know is that there are tools (like https://trust-in-soft.com/ https://trust-in-soft.com/) that can guarantee no memory errors in C code. They do require a significant effort to use, but it is significantly less effort than a rewrite in another language, and significantly less risky to boot (not to mention that there are quite a few platforms that use custom hardware and don't have compilers for new languages [1]). These tools are actually more battle-tested, and more heavily used in safety- and security-critical systems software than any new language. Given the amount of C (and C++) code in existence and heavy use, those tools and extensions like Checked C (assuming they can compile to C) are extremely important for the quality of software we use. [1]: https://youtu.be/uqan23518Yc?t=610 https://youtu.be/uqan23518Yc?t=610
- sai_c 6y agoThe problem is most developers and/or management don't care about security. They only care about being done as fast and/or as cheaply as possible. I'm still not convinced the new languages (Rust & Zig) will change the overall situation. Why? Simple example in Rust: "LOL! I need to get stuff done." unsafe { Really nasty hacks here to circumvent any obstacles. } Example in Zig: "LOL! I need to get stuff done. Tests? What tests???" zig build-exe example.zig -O ReleaseFast Trying to solve those security bugs with the help of the language is of course the low hanging fruit. But systems languages will always need an escape hatch for certain problems to be solved. And those mechanisms WILL be abused in the name of "get it done already". So we really need other means to erase those bug classes. Which ones I don't know.
- rmrfrmrf 6y agoIn an iterative development process, it's not the end of the world to get potentially unsafe code out the door and then make it safe later, and there's a huge benefit in having unsafe code labeled and framed in source when security bugs are found.
- 6y ago
- pornel 6y agoI don't expect it to get traction. • C is valued for being super portable and compatible with every platform, including legacy ones, but this applies to specifically C89 or C90, and nothing else. As soon as you embrace new features, it's not your universal C any more. You're going to need newer compilers, new tooling, and that's almost like starting with a new language. • C users have mostly self-selected themselves to like C the way it is: a small, flexible, zero-overhead language that isn't C++. Addition of checked containers, generics, and restrictions on pointer arithmetic, etc. make checked C not feel like C any more. • Checked C still needs refactoring of the code. For large established codebases this is still a lot of work, and still a risk of introducing new bugs. It's very tempting to settle on just running one more analyzer, sanitizer or fuzzer instead. And in the end with all this effort, back-compat break, whole-codebase refactoring you're still left with the old C, with headers and include paths, sloppy macros, ancient stdlib, painful dependency management, etc. If you're going to rewrite C incrementally to a more complex dialect, and require a newer non-standard compiler for it, you may as well run c2rust on it first.
- Blikkentrekker 6y ago> [...] a small, flexible [...] I do not see what would make C more flexible than any other language. The other points are correct and C's niche is indeed that it is small, ubiquitous, simple, and yet low level.
- cwfowler 6y agoNon-standard is one of the biggest drawbacks of Rust. If there were a standard and independent Rust equivalents of gcc, clang, icc and Visual C, then the decision to try out Rust would be easier. One reference implementation is a lock-in, not only technologically, but also socially in terms of a community that is too monolithic for its own good.
- bitexploder 6y agoWhat an interesting take. Go, Python, Ruby and countless other languages only have one implementation and real community. I don’t think this is a real concern for most developers. As long as the language solves their problems and is well maintained with a community that trusts the language maintainers.
- benatkin 6y ago;) https://twitter.com/nixcraft/status/1361428043126996994?s=19 https://twitter.com/nixcraft/status/1361428043126996994?s=19
- squid_demon 6y agoI think using SAL annotations along with the /analyze flag in MSVC is much less obtrusive then this solution and allows programmers to annotate portions of their code without having to learn / rewrite in an entirely new dialect of C.
- xvilka 6y agoIt's better to convert existing C code to Rust semi-automatically with C2Rust[1] framework rather than wasting time converting to this instead. [1] https://github.com/immunant/c2rust/ https://github.com/immunant/c2rust/
- ape4 6y agoSince nobody else has posted it yet: #include <stdio_checked.h> #include <stdchecked.h> #pragma CHECKED_SCOPE ON int main(int argc, nt_array_ptr<char> argv checked[] : count(argc)) { puts("hello, world"); return 0; }
- petergrant 6y agoI wonder if projects like this are the first step towards rewriting projects in Rust?
- godshatter 6y agoC gets a lot of flak, especially here, but I like the fact that you have more choices in how to do things. Yes, it's absurdly easy to shoot yourself in the foot, but you can also make use of design patterns that help. For a simple example, if you have a struct that has a pointer to an array that is allocated previously and that also has a length and maybe an allocated amount (and you're careful with making sure they are correct), then you can pass a pointer to the struct to a function that verifies that the length is sufficient for what is to be done and then the function doesn't have to check the length every time it accesses something in the array if it can be assured that the allocated memory or the length didn't change. This could save a lot of generic behind-the-scenes code that verifies the length every time an array element is accessed. It's up to the developer to make sure all the pieces are in place and everything is prepared before calling this function. If that code is in a tight loop, it could make a big difference in performance. It's a sharp knife, but sometimes you need a sharp knife. You just have to be more careful. Dulling the blade makes it more safe, but it doesn't let you make use of it's sharpness. Is it often overused? Probably. Does it have a steep learning curve to be able to write code that doesn't exhibit certain classes of errors? Sure. Should other options be used where performance isn't as critical? Probably. But it has it's place.