But lets assume this is solved. Then a API can be checked for certain properties. You can specify what it means that something is read-only in an environment etc. And ensure that it is enforced by the operating system.
As example: the verification of seL4 not only guarantees avoidance of classical security holes (buffer overflows etc.) but also certain non-interference properties.
Here's a summary of security kernel approach:
http://www.cse.psu.edu/~trj1/cse443-s12/docs/ch6.pdf
Unfortunately, the secure UNIX papers are paywalled. Here's another high-assurance project with sections illustrating issues with UNIX API and changes they had to make. That's back when it had dozens of sys calls.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.93....
After a while, the formal verification people got the tools working well enough to prove absence of certain types of problems in code itself rather than an abstract model of it. So, now you see them showing absence of buffer overflows, etc. There's also tools to do similar stuff for assembly and hardware languages. I saw one proof that went down to the gates. Capabilities gradually expanded from system-level properties to lowest-level properties.
It is a really big problem and it needs to be solved. Did you miss this recent news?
http://www.theregister.co.uk/2016/10/21/linux_privilege_esca...
But I think that is not really the big problem we have. I think it is operating system interfaces. By default a process is in its own address space and cannot do anything dangerous. It is only with the operating system API (which is the syscalls or an C API that uses syscalls) that it can do dangerous things like writing in the filesystem. Posix defines such an API which allows every program to do the same as the user running it. Windows does the same. This would be fine in a world where we can trust each program we run to not be malicious and to not be exploitable. Now we are trying to make those inherently unsafe APIs safe via sandboxing, but I guess that it is much easier to create a new API that is safe from the beginning.