[swift-evolution] Asserts should not cause undefined behaviour
Arnold
aschwaighofer at apple.com
Sat Jan 2 04:57:31 CST 2016
'assert' evaluates the condition and aborts only in Odebug builds.
'precondition' evaluates the condition and aborts also in optimized -0 builds.
As far as I remember the decision was made to give it this semantics to mimic C's assert() function.
If an abort is desired in optimized builds one should use 'precondition'.
Sent from my iPhone
> On Jan 2, 2016, at 8:27 AM, Dave Abrahams <dabrahams at apple.com> wrote:
>
>
>>> On Jan 1, 2016, at 11:25 PM, Chris Lattner <clattner at apple.com> wrote:
>>>
>>> On Dec 31, 2015, at 1:56 PM, Dave Abrahams <dabrahams at apple.com> wrote:
>>>>> 2) Adding asserts to code should not make the code more dangerous whatever the build. Assuming the truth of the assert may lead to runtime safety checks being skipped and undefined behaviour when a no-op would be a safe behaviour.
>>>>
>>>> This only affects code built with -Ounchecked, which is definitely not a safe mode to build your code. The intention of this mode is that you can use it to get a performance boost, if you believe your code to be sufficiently tested. This mode, which isn’t the default in any way, intentionally takes the guard rails off to get better performance.
>>>>
>>>> If you don’t like that model, don’t use this mode.
>>>
>>> Let’s just consider -O; I think I understand Joseph’s objection here, and it seems valid.
>>
>> Ah, good point.
>>
>>> Normally in -O, we say that if you stay in the “safe subset” of Swift code, you never get undefined behavior, even if there’s a bug in your code. You might get *unpredictable* behavior of course, but presumably guaranteeing no undefined behavior rules out large classes of problems, including many security holes. Now suppose you decide to be responsible and add some asserts to help you catch bugs during development. Hopefully they help you catch all the bugs, but what if they don’t? All of a sudden, if you still have a bug when you ship, you now have undefined behavior. As much as I’m a fan of assertions having optimization benefits, It seems a little perverse that using them could make shipping code less secure.
>>
>> Yes, I agree. -O should not imply undefined behavior in the case of an assert() predicate being dynamically false.
>>
>> It sounds like we just need a documentation update here?
>
> I’m pretty sure the documentation reflects assumptions that the optimizer is already taking advantage of, but the performance team knows for sure.
>
> -Dave
>
More information about the swift-evolution
mailing list