Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

scope: check for escape by throw #6675

Merged
merged 1 commit into from Apr 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/ddmd/escape.d
Expand Up @@ -400,6 +400,59 @@ bool checkAssignEscape(Scope* sc, Expression e, bool gag)
return result;
}

/************************************
* Detect cases where pointers to the stack can 'escape' the
* lifetime of the stack frame when throwing `e`.
* Print error messages when these are detected.
* Params:
* sc = used to determine current function and module
* e = expression to check for any pointers to the stack
* gag = do not print error messages
* Returns:
* true if pointers to the stack can escape
*/
bool checkThrowEscape(Scope* sc, Expression e, bool gag)
{
//printf("[%s] checkThrowEscape, e = %s\n", e.loc.toChars(), e.toChars());
EscapeByResults er;

escapeByValue(e, &er);

if (!er.byref.dim && !er.byvalue.dim && !er.byexp.dim)
return false;

bool result = false;
foreach (VarDeclaration v; er.byvalue)
{
//printf("byvalue %s\n", v.toChars());
if (v.isDataseg())
continue;

Dsymbol p = v.toParent2();

if (v.isScope())
{
if (sc._module && sc._module.isRoot())
{
// Only look for errors if in module listed on command line
if (global.params.vsafe) // https://issues.dlang.org/show_bug.cgi?id=17029
{
if (!gag)
error(e.loc, "scope variable %s may not be thrown", v.toChars());
result = true;
}
continue;
}
}
else
{
//printf("no infer for %s\n", v.toChars());
v.doNotInferScope = true;
}
}
return result;
}

/************************************
* Detect cases where pointers to the stack can 'escape' the
* lifetime of the stack frame by returning 'e' by value.
Expand Down
2 changes: 2 additions & 0 deletions src/ddmd/statementsem.d
Expand Up @@ -3308,6 +3308,8 @@ else
if (ts.exp.op == TOKerror)
return setError();

checkThrowEscape(sc, ts.exp, false);

ClassDeclaration cd = ts.exp.type.toBasetype().isClassHandle();
if (!cd || ((cd != ClassDeclaration.throwable) && !ClassDeclaration.throwable.isBaseOf(cd, null)))
{
Expand Down
16 changes: 16 additions & 0 deletions test/fail_compilation/retscope2.d
Expand Up @@ -146,3 +146,19 @@ S700* escape700(int i) @safe
return s.get1(); // 721
}

/*************************************************/

/*
TEST_OUTPUT:
---
fail_compilation/retscope2.d(804): Error: scope variable e may not be thrown
---
*/

#line 800

void foo800()
{
scope Exception e;
throw e;
}