Skip to content

Commit 24f50c1

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 24f50c1

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

spec/function.dd

Lines changed: 19 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,22 @@ $(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:
4179+
- When a null dereference occurs on systems that by default do not protect
4180+
access to the first page of memory addresses. (Note that e.g. calling
4181+
[`mprotect`](https://pubs.opengroup.org/onlinepubs/007904875/functions/mprotect.html)
4182+
is `@system`).
4183+
- On all systems when an expression causes a null pointer to be indexed,
4184+
causing a memory access that may be outside the protected first page
4185+
of memory addresses. $(RED Warning:) $(TT dmd)
4186+
[has not implemented](https://github.com/dlang/dmd/issues/17776) this yet.
4187+
41724188
$(H3 $(LNAME2 safe-aliasing, Safe Aliasing))
41734189

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

0 commit comments

Comments
 (0)