int a[5] = { 0, 1, 2, 3, 4};
_Array_ptr<int> p : count(5) = a; // p points to 5 elements.
My proposal for C: int a[5] = { 0, 1, 2, 3, 4};
int p[..] = a; // p points to 5 elements.
https://www.digitalmars.com/articles/C-biggest-mistake.htmlhttps://github.com/Microsoft/checkedc/wiki/New-pointer-and-a...
At least there's BetterC ;)
https://www.absint.com/astree/index.htm
https://github.com/NASA-SW-VnV/ikos
https://github.com/static-analysis-engineering/CodeHawk-C
I have planned to try using them on OpenZFS for a while, but I am still busy reviewing and fixing reports made by conventional static analyzers. I plan to look into these next.
That said, at least one of them claims to be able to prove the absence of issues in C that checked C’s documentation explicitly says it cannot prevent. The obvious one is use-after-free.
This comment did not age well:
https://news.ycombinator.com/item?id=34086304
A quick test with `clang -std=c89 -pedantic` says it was in C99. Amazingly, it seems that almost nobody knew about it.
Unless they have changed course, it seems more likely that Microsoft will drop NT for a UNIX kernel than Microsoft would put this into their compiler. I assume that this is by Microsoft Research and work by Microsoft Research is almost never used by Microsoft. The only exception I know is Drawbridge, which they reportedly used in Azure.
• Microsoft source code annotation language (SAL)
• Cyclone (AT&T research language)
• SCC, the Safe C compiler.
• Ccured
• MemSafe
The breakthrough will come when someone can create an automated system to convert unsafe C into safe something. AI may be far enough along to do that now. Every array in a valid C program has a size, defined by some expression known to the programmer. All you have to do is find that expression and tell the language about it. Most of the time this is easy. Sometimes it's hard. Sometimes it's impossible, in which case the program is probably a buffer overflow waiting to happen.
[1] http://animats.com/papers/languages/safearraysforc43.pdf
[1] https://staff.aist.go.jp/y.oiwa/FailSafeC/index-en.html
[2] https://people.cs.rutgers.edu/~sn349/softbound/
The former apparently implements full ANSI C, and the latter apparently has a memory safety proof in Coq.
The group that did [1] also did an ANSI C to Java compiler.
It seems to me that we could really use a safe ABI (x86_64_safe, etc.) for C/C++, and that it should be supported by clang and gcc.
Maybe CHERI will catch on someday...
"We find that typ3c automatically converted 67.9% of pointers in our benchmark programs to checked types, which improves on the 48.4% inferred by unification-style algorithms used in prior work. boun3c was able to infer bounds for 77.3% of pointers that required them."
That's reasonably good. The real goal is to convert all pointers to either run-time checked pointers (slower) or compile-time checked pointers. It's already possible to convert everything to "fat pointers". GCC used to have that as an option. But the goal is to eliminate the need for that for code that's frequently executed. That is, inner loops. It's good to see activity in this area.
The output code is kind of clunky looking, but that could be fixed.
> This C code is guaranteed to be safe. We had an AI go through it and make it safe.
No, thanks. That sounds more like a problem than a solution.
Can't we just make macros to redefine types as some 'safe' type variant system, and #include "safetypes.h" or something? It's ugly, but searching your source code for 'int a[5]' and replacing it with 'INT(a,5)' might be dumb enough to work.
a := [5]int32{0, 1, 2, 3, 4} // Go
let mut array: [i32; 5] = [0, 1, 2, 3, 4]; // RustThe problem is that it doesn't use them much, and gets rid of them as soon as possible:
int a[5] = {1, 2, 3, 4, 5, 6};
printf("%d\n", a[8]);
in clang, this warns, by default, on both misuse sites "excess elements in array initializer" and "array index is past the end of the array". Which is good.However things go downhill as soon as you pass the arrays downstack:
#include <stdio.h>
static void foo(int *a) {
printf("%d\n", a[8]);
}
static void bar(int a[]){
printf("%d\n", a[8]);
}
static void qux(int a[6]){
printf("%d\n", a[8]);
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
foo(a);
bar(a);
qux(a);
}
no warning anywhere, even under "-Wall -Weverything". #include <stdio.h>
static void qux(int a[static 6]){
printf("%d\n", a[8]);
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
qux(a);
}
I get, test.c:9:5: warning: array argument is too small; contains 5 elements, callee requires at least 6 [-Warray-bounds]
I did not enable any warning flags at all, this is just default Clang on a Mac.If you want to catch the a[8] inside the function you need something else.
static void foo(int (*a)[6]) {
printf("%d\n", (*a)[8]); // warning: array index 8 is past the end of the array (which contains 6 elements)
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
foo(&a); // warning: incompatible pointer types passing 'int (*)[5]' to parameter of type 'int (*)[6]'
}
This is all vanilla C89, so it works even with very old compilers, so long as they're conformant.IMO, if GCC or clang implemented and ran with those proposed changes, they'd probably be accepted for the next C revision, and become popular long before then. This is mostly a matter of time and motivation; corporate funded developer time seems to be mostly focused on half measures; e.g. type attributes, rather than fundamentally improving pointer and array semantics. But if someone put in enough time and effort, including going through the rigmarole of integration into mainline, this could happen.
int main(int argc, char **argv) { return myMain(argv[0 .. argc]); }
Strings can be done like this: char [..] s = p[0 .. strlen(p)]; int main(char [..] args)
Maybe with some way to tell the compiler the correct parameter order if needed? Perhaps: int main(char [..argc] argv)
I'm curious if ELF and other formats have enough info to figure that mapping out? int main(int argc, char **argv : count(argc)) {}
If you're already creating an extension for C, then it's fine to "change" its signature in this way. Or am I misunderstanding your objection?Sure, the compiler can't verify that argv does indeed have argc elements, but hopefully we can rely on the kernel and C runtime to populate things properly. If not, I would say it doesn't matter that the compiler can't help you here; your system is screwed beyond repair already.
At the very least, the compiler can emit bounds checking to ensure that you don't try to access past argc elements in that array, which is still valuable.
Edit: it occurs to me that you were talking about WalterBright's version, not the version in Checked C. But I think my comment still applies: if you're changing how things work, then you just keep changing how things work to cover cases like this.
char *strncpy(char * restrict dest : count(n),
const char * restrict src : count(n),
size_t n) : bounds(dest, (_Array_ptr<char>)dest + n); static ubyte* [n*2] requires_ptr_twice_as_large_as_input(n : uint)
(
ubyte*[n] input,
ubyte*[n*2] output,
) {
output[0..n] = input[0..n];
output[n..2*n] = input[0..n];
return output;
}
void main()
{
ubyte[10] input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
ubyte[20] output = new ubyte[20];
requires_ptr_twice_as_large_as_input!(10)(&input, &output);
}ABEL = "Advanced Boolean Expression Language", a language for programming PLDs (Programmable Logic Devices) which was a core business for Data I/O.
#define ARR_LEN(a) (sizeof (a) / sizeof *(a))
int a[5] = { 0, 1, 2, 3, 4};
int (*p)[ARR_LEN(a)] = &a;
ARR_LEN(*p) // 5#define ARR_LEN(a) (sizeof (a) / sizeof (a))
int main(void) { int a[5] = {0, 1, 2, 3, 4};
int (*p)[ARR_LEN(a)] = &a;
(*p)[6] = 1;
return ARR_LEN(*p); // 5
}I had no idea this was possible in C. It is unfortunate that GCC seems to ignore this information. Clang on the other hand uses it.
Variable modified types, they were introduces with VLAs (variable length arrays) in c99. C11 made both optional, and C2x mandates only VMTs.
If you have a start and end pointer and you move either one, you don't know what the original size of the allocation was.
"Checked C" - https://news.ycombinator.com/item?id=26190403 - 133 comments - 2021
"Refactoring the FreeBSD Kernel with Checked C" - https://news.ycombinator.com/item?id=25989115 - 41 comments - 2021
"Achieving Safety Incrementally with Checked C" - https://news.ycombinator.com/item?id=19424106 - 21 comments - 2019
"Checked C: Making C Safer by Extension" - https://news.ycombinator.com/item?id=17939537 - 55 comments - 2018
"Checked C: extension to C that adds static and dynamic checking" - https://news.ycombinator.com/item?id=16588483 - 92 comments - 2018
"Checked C" - https://news.ycombinator.com/item?id=11899925 - 156 comments - 2016
C to Checked C by 3C - https://news.ycombinator.com/item?id=30857289 - March 2022 (1 comment)
A Formal Model of Checked C - https://news.ycombinator.com/item?id=30321535 - Feb 2022 (37 comments)
Why Checked C when there was Verona? - https://news.ycombinator.com/item?id=26499846 - March 2021 (2 comments)
Checked C - https://news.ycombinator.com/item?id=26190403 - Feb 2021 (133 comments)
Refactoring the FreeBSD Kernel with Checked C [pdf] - https://news.ycombinator.com/item?id=25989115 - Feb 2021 (41 comments)
Refactoring the FreeBSD Kernel with Checked C [pdf] - https://news.ycombinator.com/item?id=24019185 - Aug 2020 (13 comments)
Achieving Safety Incrementally with Checked C - https://news.ycombinator.com/item?id=19424106 - March 2019 (21 comments)
Checked C: Making C Safer by Extension - https://news.ycombinator.com/item?id=17939537 - Sept 2018 (55 comments)
Checked C: extension to C that adds static and dynamic checking - https://news.ycombinator.com/item?id=16588483 - March 2018 (92 comments)
Checked C - https://news.ycombinator.com/item?id=12049548 - July 2016 (3 comments)
Checked C – A Safer C/C++ from Microsoft - https://news.ycombinator.com/item?id=11936418 - June 2016 (3 comments)
Checked C - https://news.ycombinator.com/item?id=11899925 - June 2016 (156 comments)
As a useful counterexample, glib has GArray, GPtrArray, and GList, along with functions that you use to manipulate the lists. Those functions are presumably implemented correctly, and will prevent you from making out-of-bounds accesses.
But of course those things are not widely adopted, because they're not standardized, they're not in libc, and libc has not been reimagined such that all of its APIs take and return these safer list primitives instead of bare C arrays.
(And sure, GArray etc. are not necessarily suitable everywhere, as they require heap allocations. But I could imagine a safe abstraction that could allow for using stack or static allocations to back it.)
So I see something like Checked C as a band-aid, when the language and stdlib just needs a complete overhaul. Obviously that's incredibly unlikely to ever happen, so something like Checked C is a decent compromise, I guess.
Also, which part of GPtrArray prevents you from making out of bounds access? Last time I checked it doesn't.
Well, that's also C's fault for not having parametric polymorphism.
> But of course those things are not widely adopted, because they're not standardized, they're not in libc, and libc has not been reimagined such that all of its APIs take and return these safer list primitives instead of bare C arrays.
I'm really not sure why the second thing is regarded by C programmers as such an insuperable barrier to the first thing.
I absolutely understand that there are circumstances where extreme portability is a major requirement. That, and C's ability to operate in highly constrained environments are among its most laudable features.
But many of us (including me) write user-facing C applications that have neither requirement and where Glib is either already installed or easy to install. Why not just go ahead and use it? If you're trying to get it to run on a tiny embedded system or in some land without Glib . . . well, this isn't the program for you!
I feel like this is more of a weird cultural prejudice than a technical matter. People run programs in JavaScript (or Haskell, or Python) with hundreds of dependencies, and while some find that annoying, I don't hear people in these communities objecting to idea of dependencies the way people do with C.
Could the standard library be better? Of course. But there's something to be said for not including a lot of batteries in the standard and just using the third-party tools that are available.
And if people look deeper, there are some surprising elements of Pascal in newer languages, more than many realize. At some point, sanity and common sense will sneak through.
Truly bizarre that we ended up with C, still feature incomplete compared to what was available at the time.
ESPOL/NEWP from 1961, almost a decade before C came to be, even had unsafe code blocks!
I guess the hard part will be the fact that all your dependent libraries will (likely) still be unsafe.
https://learn.microsoft.com/en-us/cpp/code-quality/code-anal...
You would be better off comparing it to Astree, which is a static analyzer written by the group that wrote the Compcert C compiler.
https://www.absint.com/astree/index.htm
Astree claims to be able to prove the absence of use-after-free, which the checked C documentation says that checked C does not prevent.
You would need to check to see if Astree can prove the absence of all of the issues that checked C is intended to prevent, but at a glance that seems possible. In theory, Astree can be used to fix all of them by doing fixes until it stops complaining.
I was wrong to write this. They were written by different groups in France, but licenses for both of them are being sold by the same company, which made it easy to mistake the creators as the same group. I realized my misunderstanding several hours after making that comment and could not edit to correct the error.
Also why can we not get better syntax for C? Function pointer syntax is so bad that people actively avoid using them. #pragma once is a hack. Every string library function is actively dangerous in addition to puts/gets.
I know that nobody wants to be the one to mess with the core language and ruin it but this is awfully low-hanging fruit that hasn’t been fixed in 50 years.
For a different language syntax it makes a lot more sense to consider using a different language in the first place though, because everybody has a different opinion what such a 'better C' syntax should look like (e.g. it sounds like you'd actually want Zig).
Backwards compatability.
>Function pointer syntax is so bad that people actively avoid using them.
That is because C syntax mistakenly put the return value before the parameters. You use function pointers if you have to.
>#pragma once is a hack.
It is a hack to prevent the previous hack of #ifdef'ing the thing.
>but this is awfully low-hanging fruit that hasn’t been fixed in 50 years.
It is literally impossible to fix.
I recently submitted a PR for the `c2nim` import tool to handle double function pointers. I didn't actually understand the C code until I got the transpiler working despite cdecl.org:
// posix signal
void(*signal(int, void (*)(int)))(int);
in Nim becomes: var signal*: proc (a1: cint; a2: proc (a1: cint)): proc (a1: cint)
Well I'm 99.5% certain at least. Even now I'm uncertain of the C syntax. And I've not been bold enough to test 3rd order C function pointers. I figure that's probably C code you don't wanna touch if possible.https://github.com/nim-lang/c2nim/blob/11f2c5363dfe7e8c7c8ce...
The other annoying one is that "signed" and "unsigned" are basically adjectives, but "long" can be both a type and a modifier. So it's difficult to parse unless you're the target C compiler. Technically you can, but you have to use backtracking.
void(*signal(int, void (*)(int)))(int)
The result of the expression is void.Parentheses go first in order of operations, so we evaluate this first:
(*signal(int, void (*)(int)))
Function call binds before dereference, so this goes first: signal(int, void (*)(int))
"signal" becomes the actual declared name. At the bottom, we have a function that takes two parameters, an int, and a function pointer that takes an int and returns void. Now we work outwards.This function returns a pointer, that when dereferenced, can be called with an int, and returns void when doing so.
In layman's terms, we have a function "signal" that takes an int and a function pointer and returns a function pointer, and both function pointers are to a function that takes an int and returns void.
Is it easy? If you can read C expressions, it can be easy. But it is definitely tedious, and does not come out quickly--it violates the principle that you have <type> <variable name>; it is not what I would consider readable or good design. And it would be easier if types were consistently read in one direction (like Rust types).
As a generalization I completely disagree. But for function pointers specifically, yes, they are easily the worst part of the C syntax.
>void(signal(int, void ()(int)))(int);
That's just declaring signal as function (int, pointer to function (int) returning void) returning pointer to function (int) returning void, DUH. Thank you cdecl.org
But notice how absolutely ugly it is that the final return type comes first, that is due to the C function signatures.
Not really. Just create a bit mask.
https://github.com/dlang/dmd/blob/master/compiler/src/dmd/cp...
This is trivial to parse if you use spiral rule, humans or machine.
I simply can't tell if we're not fixing this stuff out of laziness, out of fear, or because no one wants to admit that no one knows who's holding us back.
I don't think you really understand what C actually is. C basically does not compete as a programming language. On a UNIX like it is the language of the kernel and as such its quirks inevitably represent the quirks of the kernel, you use C if you want to talk to the kernel.
>Would it truly be that difficult to introduce a "fn" keyword?
Yes, literally impossible. Just look at the controversy of C23 removing the almost entirely unused K&R function declaration syntax.
Nothing good has come to anyone who started an argument with those words.
It can be made to function more like C with #![no_std]. However that is an even less than batteries included experience than C.
That said, frama-c suffers from a documentation problem. It has so much documentation that it either lacks good documentation explaining how to navigate its documentation, or it has that documentation and it is not easy to find. :/