@trusted considered harmful

Artur Skawina art.08.09 at gmail.com
Sun Jul 29 02:13:34 PDT 2012


On 07/29/12 07:14, David Piepgrass wrote:
>> On Saturday, July 28, 2012 22:08:42 David Nadlinger wrote:
>>> On Saturday, 28 July 2012 at 02:33:54 UTC, Jonathan M Davis But unfortunately wrong – you call S.save in the @trusted block… ;)
>>
>> Yeah. I screwed that up. I was obviously in too much of a hurry when I wrote
>> it. And actually, in this particular case, since the part that can't be
>> @trusted is in the middle of an expression doing @system stuff, simply using an
>> @trusted block wouldn't do the trick.
> 
> Have you guys thought about the possibility that the language could simply not trust any calls that were resolved using a template argument?
> 
> I'm a bit tired so I may be missing something, but it seems to me that (in a @trusted template) if the compiler uses an instantiated template parameter (e.g. actual type Foo standing in for template parameter T) to choose a function to call, the compiler should require that the function be @safe, based on the principle that a template cannot vouch for what it can't control. IOW, since a template can't predict what function actually gets called, the compiler should require whatever function gets called to be @safe.

This wouldn't be enough, and would just paper over the real issue.
While the problem is probably most obvious with templates, it is also
present when no generics are involved.

If you write a @trusted non-templated function like

   class C { int field; /*...*/ }

   auto f(C c) @trusted { do_something_potentially_unsafe_but_verified_with(c.field); }

it will be fine, as it is all obviously safe, right?

Well, until somebody else later changes 'C' to

   class C { @property field() { return unsafe_buggy_code(); } /*...*/ }

without realizing that 'C.field' is accessed in a @safe context.

The compiler will silently accept it and run the @system code just as
if it was marked as @safe or @trusted. The definition of 'C' and the
function 'f' could be in different modules or even libraries. Both will
still build, without even giving a hint that something may be wrong.

"You can't audit code that isn't available." -- that code may not have
been written yet. With the current '@trust' model even an "innocent"
access to non-local data can result in all @safe checks being bypassed.
Keeping all external accesses out of '@trusted' scopes is not really a
practical solution. Most accesses will be (perceived as) safe, so
programmers will choose to ignore the potential hazards in order to
keep the code readable.

artur 


More information about the Digitalmars-d mailing list