Fix #20901: can escape stack pointer through indexed array literal (#21063)

This commit is contained in:
Dennis 2025-03-23 01:35:43 +01:00 committed by GitHub
parent 53024b9fc5
commit 0ae065db22
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 18 additions and 8 deletions

View file

@ -27,7 +27,6 @@ import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.expressionsem;
import dmd.func;
@ -2728,13 +2727,6 @@ Expression castTo(Expression e, Scope* sc, Type t, Type att = null)
ArrayLiteralExp ae = e;
Type tb = t.toBasetype();
if (tb.ty == Tarray)
{
if (checkArrayLiteralEscape(*sc, ae, false))
{
return ErrorExp.get();
}
}
if (e.type == t)
{

View file

@ -24,6 +24,7 @@ import dmd.dscope;
import dmd.dtemplate : isDsymbol;
import dmd.dsymbol : PASS;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.func;
import dmd.globals;
@ -127,6 +128,13 @@ public:
return;
if (setGC(e, "this array literal"))
return;
if (checkArrayLiteralEscape(*sc, e, false))
{
err = true;
return;
}
f.printGCUsage(e.loc, "array literal may cause a GC allocation");
}

View file

@ -55,7 +55,9 @@ TEST_OUTPUT:
---
fail_compilation/retscope3.d(4003): Error: escaping a reference to parameter `u` by copying `u[]` into allocated memory is not allowed in a `@safe` function
fail_compilation/retscope3.d(4016): Error: storing reference to outer local variable `i` into allocated memory causes it to escape
fail_compilation/retscope3.d(4025): Deprecation: slice of static array temporary returned by `makeSA()` assigned to longer lived variable `a`
fail_compilation/retscope3.d(4025): Error: escaping reference to stack allocated value returned by `makeSA()` into allocated memory
fail_compilation/retscope3.d(4032): Error: escaping a reference to local variable `i` by copying `& i` into allocated memory is not allowed in a `@safe` function
---
*/
@ -87,3 +89,11 @@ void bar4003() @safe
{
int[][] a = [makeSA()[]];
}
// https://github.com/dlang/dmd/issues/20901
int* f20901() @safe
{
int i = 3;
auto x = &[&i][0]; // Should error, i is escaped into allocated memory
return *x;
}