Re:Why Is SQLite Coded in C? (2017)
by Thiez on Thursday March 15, 2018 @05:29AM
(#16591389)
I find it a bit silly that `ptr.offset` is unsafe, but casting an arbitrary integer to a pointer isn't. E.g.:
Using casting one can even implement a "safe" pointer offset function, like so:
Obviously this "safe_offset" function can easily be used to trigger UB by computing invalid pointers, and not a single line of unsafe code was required (although we do need `unsafe` to dereference the bad pointer and actually trigger segfaults).
[ Parent
| on HN ]
Re:Why Is SQLite Coded in C? (2017)
by steveklabnik on Thursday March 15, 2018 @06:27AM
(#16591609)
I believe this is because offset uses an llvm intrinsic with the extra requirements, as it uses that info for optimization. Your version doesn't.
Interesting. However, isn't casting a random (potentially invalid) integer into pointer triggering the same potential UB? I ask because for GCC it is apparently:
>When casting from pointer to integer and back again, the resulting pointer must reference the same object as the original pointer, otherwise the behavior is undefined. That is, one may not use integer arithmetic to avoid the undefined behavior of pointer arithmetic as proscribed in C99 and C11 6.5.6/8.
https://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-imple...
That's pretty explicitly what Thiez was doing in their rust code, although obviously Rust/LLVM might have different semantics here.
The docs list no undefined behaviour for inttoptr, so it's (probably) not problematic at the LLVM level: http://llvm.org/docs/LangRef.html#inttoptr-to-instruction .
Re:Why Is SQLite Coded in C? (2017)
by steveklabnik on Thursday March 15, 2018 @06:47AM
(#16591702)
The exact rules of unsafe code are still up in the air. It’s not explicitly defined as UB yet, IIRC, and when we set the rules, we have a goal of not invalidating large swaths of code.