Skip to content

Commit 54246c1

Browse files
committed
[spec/function] Specify null dereference behavior for @safe code
Forbid optimizations which assume a null dereference will not occur. `ldc2` does use those optimizations with `-O2` - see: https://forum.dlang.org/post/vv6o31$ac9$1@digitalmars.com. Specify that codegen must detect null dereferences if the system (by default) does not. Specify that codegen must detect when any expression causes a null pointer to be indexed outside the protected first page. Include warning that dmd does not implement this yet - see dlang/dmd#17776.
1 parent b8dddee commit 54246c1

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

spec/function.dd

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4069,15 +4069,15 @@ $(H3 $(LNAME2 safe-values, Safe Values))
40694069

40704070
$(P A pointer is a safe value when it is one of:)
40714071
$(OL
4072-
$(LI `null`)
4072+
$(LI `null` - $(RELATIVE_LINK2 null-dereferences, see below))
40734073
$(LI it points to a memory object that is live and
40744074
the pointed to value in that memory object is safe.)
40754075
)
40764076
$(P Examples:)
40774077
$(SPEC_RUNNABLE_EXAMPLE_RUN
40784078
---
4079-
int* n = null; /* n is safe because dereferencing null is a well-defined
4080-
crash. */
4079+
int* n = null; /* n is safe because dereferencing null must either crash
4080+
or abort. */
40814081
int* x = cast(int*) 0xDEADBEEF; /* x is (most likely) unsafe because it
40824082
is not a valid pointer and cannot be dereferenced. */
40834083

@@ -4169,6 +4169,23 @@ $(H3 $(LNAME2 safe-values, Safe Values))
41694169
expected by the function.)
41704170
)
41714171

4172+
$(H3 $(LNAME2 null-dereferences, Null Dereferences))
4173+
4174+
$(P When generating `@safe` code, a compliant implementation:)
4175+
4176+
- Must not assume that a null dereference will not occur. Optimizations
4177+
that require that assumption cannot be used for `@safe` functions.
4178+
- Must generate code that will detect and abort execution if a
4179+
null dereference occurs:
4180+
- On systems that do not protect access to the first page of memory addresses
4181+
by default. (Note that e.g. calling
4182+
[`mprotect`](https://pubs.opengroup.org/onlinepubs/007904875/functions/mprotect.html)
4183+
is `@system`).
4184+
- On all systems when an expression causes a null pointer to be indexed,
4185+
causing a memory access that may be outside the protected first page
4186+
of memory addresses. $(RED Warning:) $(TT dmd)
4187+
[has not implemented](https://github.com/dlang/dmd/issues/17776) this yet.
4188+
41724189
$(H3 $(LNAME2 safe-aliasing, Safe Aliasing))
41734190

41744191
$(P When one memory location is accessible with two different types, that

0 commit comments

Comments
 (0)