For example, in libopus we have platform-specific SIMD optimizations that are chosen at runtime.
The common solution is just to have a function pointer that points to the accelerated routine. But there are only a limited number of choices for each routine. So we put pointers to them in a static const array, which gets stored on a read-only page. Then instead of storing a pointer, we just store an index into this array. This index is chosen based on the available instruction sets detected at runtime. This lets us use the same index for every accelerated function.
Then, we pad the array size out to a power of two. To call an accelerated function, we mask off the upper bits of the index. Even if the index gets corrupted, we still call one of the functions in the array. So there's only so much damage it can do.
Obviously this doesn't apply if the set of functions you need to call is open-ended (e.g., a callback, like nginx was using). But it seems like a good pattern to follow when it applies.
Also, that just sounds like how switch/case is sometimes implemented. Have you considered just using a switch/case statement instead of manually managing function pointers and the like?
It also means that you don't need to pass around (a pointer to) a big table of function pointers throughout all of your functions that need to use accelerated routines. Instead you just pass a single integer index. But that is pretty minor.
It can be pretty similar to a switch in practice, but I think there are a few differences. One is function argument handling. Each version of an accelerated routine has to be an independent function, compiled in a separate compilation unit, because you have to limit the instruction sets available. So you will duplicate all of the function call setup overhead in each branch of the switch. This probably gets optimized away by a decent compiler. Even if it does, you still wind up essentially duplicating the function table at every call site. That does not seem likely to get optimized away. You could dispatch to a common thunk which selects the accelerated routine to call, but now you have two function calls instead of one. I am also not sure that switch statements handle the default case as cheaply as doing a single bitwise AND with a small, compile-time constant.
But if you have a use of function pointers that can be replaced by a simple switch statement, that is probably the better approach.
[1]: https://www.comp.nus.edu.sg/~gregory/papers/ndss17stack.pdf
But it does, doesn't it?
You're suggesting we replace C, which isn't necessarily a bad idea, but there are considerable hurdles, as it's a lingua franca. C has an excellent suite of compilers for every platform you can name, excellent development tools, every serious programmer already knows the language, and it easily hooks in to platform-specific functionality.
If we want to replace C, we have a few languages to choose from: BetterC, Zig, Rust.
If BetterC were a strict subset of C, things would be quite different, but it's not, so it has the just another language problem.
If we want to go the subset route, we already have MISRA C, which blocks various categories of bugs and undefined behaviour. Crucially, it's possible to mechanically verify that a program is MISRA-compliant.
Solaris has it thanks to SPARC tagged memory.
Problem is when would we ever get it as mainstream, always enabled, in other platforms.
But even if all userspace developers move to safer languages, we still have the UNIX derived kernels, PIC and other microcontrollers, routers and plenty of other embedded stuff to worry about.
Even Microsoft with their Azure Sphere project, which is supposed to be all about secure IoT, still bundles a Linux kernel with it.
Hence why we really need to fix C somehow.
I feel like Elrond at the council of Rivendell: "you have only one choice." Except throwing a ring into a hole is a comparatively well-defined task relative to rewriting an unknown number of crappy pieces of software. Ed: also there's no conveniently situated group of people to whom to assign the project.
Most of the infrastructural projects you're referring to predated modern languages. There is no reason, for example, for an MTA to be written in C today. We use MTAs written in C because MTAs are old.
The same applies to system languages, just that the army is the OS that bundles them as THE official language.
Pascal based OSes unfortunately lost their place on the market.
To pick a more modern example, how many people would have bothered with JavaScript if it wasn't THE language on the Web OS?
Far as embedded, there were some done in Ada and a Java subset. There's even real-time GC's for that kind of stuff. One or two companies sell Java processors that run it natively. CompSci stays doing CPU extensions that could work with MCU's.
With a properly designed programming environment, you don't need many bounds checks to begin with. Almost every embedded system can easily afford the cost of the few you can't eliminate.
While they aren't Rust level safe, they eliminate like 80% of the common C safety errors.
Thanks to explicit conversions, proper enums, reference parameters, actual string and vector types, memory allocation based on types instead of arbitrary numbers, type safe linkage thanks modules.
So while use after free or double frees would are still an issue, many other classes of typical C errors would be gone.
Yes Rust is great and all, sometimes getting people half-way is better than not at all.
Including the commercial failure of Inferno.
How things are going even Microsoft could eventually have again their own version.
So from the business perspective it seems the only way to win is to fix the language UNIX is written on.
Pure userspace software is the easiest to fix; there has already been a huge shift to {safer,easier} languages for most new(-ish) software. C/C++ is mostly used for existing software where other options we not {possible,practical}. Porting to another language will probably happen now that we have options like Rust, but it will take a massive amount of work.
However, one place where we need more (and better) alternatives to C is the library ABI. If you want to make a library that can be used by as widely as possible you either use C or something that can generate libraries with a standard C-style ABI. That's the FFI tools of most other languages expect. (C++ ABI is also used, but name-mangling complicates interfacing with other languages) Rust's #[no_mangle] helps, but what we really need is standardized ABI with a safer calling conventions and memory handling semantics that is still very generic, without any language specific baggage or other complications. Until that exists, key parts of the infrastructure will stay with C out of necessity.
> kernels
That's one of the infrastructure pieces I was referring to. Other parts that depend critically on a generic C-like ABI interoperability might include driver-based stuff like libGL.so.
> microcontrollers
While I needed the low-level properties of C (w/ assembly) when I was implementing {802.3,IP,TCP,HTTP,SNMP} on a Z80-clone with 16kB of RAM, modern "microcontrollers" often aren't very "micro" and basically a lightweight linux host. They will move to other languages following after regular userspace software.
However, this is assuming there is even a need for safer languages on the micro, which is true when it's accepting data from a hostile source like a network. A much better idea is to simply not connect your embedded device to a network. A safer language isn't necessary if you aren't controlling anything dangerous, your input is limited to reading buttons states with GPIO, and any bugs can be fixed with a reset from a hardware watchdog timer.
> other embedded stuff to worry about.
There is defiantly a lot of embedded crap that need to be junked and replaced asap, but that's not really a C problem. Buffer overrun safety is great but it doesn't do much when the device has a backdoor password clearly visible in the firmware, ships with the admin password "admin", or grants remote admin access when the password is "" (empty string).
We do need to fix C, but there are, unfortunately, far worse problems with embedded devices.
On the microcontrollers side, there are a couple of vendors that I usually advocate, which do sell Basic, Pascal, Oberon, Java implementations, however if it surprising and refreshing as well, that they still manage to keep in business, given how hard is to move most embedded devs away from C89 + extensions/Assembly duo.
Talks about how to advocate C++ to such devs are a now a recurring theme at C++ conferences.
Even Microsoft which uses a mix of C# and Rust for IoT Edge, they went with Linux and C on Azure Sphere, which is supposed to be their mark on secure IoT, while I was expecting that at very least they would use the opportunity to push their Checked C project, given that Azure Sphere is being pushed by the same MSR group from Singularity and friends.
(Disclaimer - I work there.)
shameless plug: https://www.c2rust.com
The other thing to do is to enforce checks on array indices.
Canaries are usually checked on heap deallocation (resp. stack canaries are checked on stack frame deallocation, i.e. function return). Checking them at any other time is expensive and incurs high overhead. They also don't catch all overflows - an overflow with an attacker-controlled index could easily skip the canary and overwrite whatever lies past it.
The problem of memory bounds checking is solvable if you decide to forego memory, processing time, and/or compatibility with existing code. Trying to achieve memory safety while maintaining those three properties is very hard.
What I described is what higher-level languages do if they provide this sort of protection and it's what must do done if such protection is required.
Turn on ASAN in production. HWASAN may make that more palatable.
typedef struct {
const void* fptr;
char buf[124];
} mystruct; struct ngx_http_request_s {
uint32_t signature;
ngx_connection_t connection;
...
ngx_http_log_handler_pt log_handler;
...
u_char lowcase_header[NGX_HTTP_LC_HEADER_LEN];
...
unsigned http_minor:16;
unsigned http_major:16;
};
They underflow lowcase_header (or rather, assume the existence of an underflow bug) to overwrite log_handler, a function pointer that is called when an error occurs.I do find the authors' presentation a little disingenuous, because the purported underflow bug does not actually exist - the authors assume it does, then proceed as if they have full control over the function pointer (including the ASLR leak necessary to obtain proper gadget addresses).
We've got to get more code out of C and into something with subscript checking. None of the kludges for fixing C work.