Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions SqlScriptDom/LexerPostProcessing.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,10 @@ $content = $content.Replace("catch (CharStreamException cse) {","finally {")
$content = $content.Replace("if ( cse is CharStreamIOException ) {","if (false) {")
$content = $content.Replace("throw new TokenStreamIOException(((CharStreamIOException)cse).io);","")
$content = $content.Replace("throw new TokenStreamException(cse.Message);","")
# Every rule method checks the stack first, so that deep nesting throws InsufficientExecutionStackException
# instead of overflowing the stack. A rule signature ends with the "//throws" comment and its body opens on the next line.
$rules = [regex]::Matches($content, '//throws RecognitionException').Count
$content = [regex]::Replace($content, '(?m)^([^\r\n]*\) *//throws RecognitionException[^\r\n]*\r?\n\{)(\r?\n)', '${1}${2}' + "`t`t" + 'global::System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack();${2}')
$checks = [regex]::Matches($content, 'RuntimeHelpers\.EnsureSufficientExecutionStack\(\);').Count
if ($rules -eq 0 -or $checks -ne $rules) { throw "Stack check inserted into $checks of $rules rule methods in $($args[0])" }
[System.IO.File]::WriteAllText($args[1], $content)
6 changes: 6 additions & 0 deletions SqlScriptDom/ParserPostProcessing.ps1
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# We don't want wrapper exceptions - IOException is totally fine!
$content = [System.IO.File]::ReadAllText($args[0]).Replace("using TokenStreamIOException = antlr.TokenStreamIOException;","")
# Every rule method checks the stack first, so that deep nesting throws InsufficientExecutionStackException
# instead of overflowing the stack. A rule signature ends with the "//throws" comment and its body opens on the next line.
$rules = [regex]::Matches($content, '//throws RecognitionException').Count
$content = [regex]::Replace($content, '(?m)^([^\r\n]*\) *//throws RecognitionException[^\r\n]*\r?\n\{)(\r?\n)', '${1}${2}' + "`t`t" + 'global::System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack();${2}')
$checks = [regex]::Matches($content, 'RuntimeHelpers\.EnsureSufficientExecutionStack\(\);').Count
if ($rules -eq 0 -or $checks -ne $rules) { throw "Stack check inserted into $checks of $rules rule methods in $($args[0])" }
[System.IO.File]::WriteAllText($args[1], $content)
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// </copyright>
//------------------------------------------------------------------------------
using Microsoft.SqlServer.TransactSql.ScriptDom;
using System.Runtime.CompilerServices;

namespace Microsoft.SqlServer.TransactSql.ScriptDom.ScriptGenerator
{
Expand Down Expand Up @@ -41,6 +42,8 @@ public override void ExplicitVisit(SelectStatement node)

void GenerateQueryExpression(QueryExpression queryExpression, AlignmentPoint clauseBody, SchemaObjectName intoClause, Identifier filegroupClause = null)
{
// A UNION chain and nested query parentheses recurse through here without passing an Accept method.
RuntimeHelpers.EnsureSufficientExecutionStack();
QuerySpecification querySpecification = queryExpression as QuerySpecification;
if (querySpecification != null)
{
Expand Down
206 changes: 206 additions & 0 deletions Test/SqlDom/DeepNestingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
//------------------------------------------------------------------------------
// <copyright file="DeepNestingTests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Microsoft.SqlServer.TransactSql.ScriptDom;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SqlStudio.Tests.AssemblyTools.TestCategory;

namespace SqlStudio.Tests.UTSqlScriptDom
{
/// <summary>
/// A deeply nested statement must stop the parser, the script generator and the fragment visitors
/// with InsufficientExecutionStackException. Without the stack checks it overflows the stack, and a
/// stack overflow ends the process. Every case runs on a thread with a fixed 1 MB stack, and every
/// deep case below overflows that stack when the checks are missing.
/// </summary>
public partial class SqlDomTests
{
private const int SmallStackSize = 1024 * 1024;

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void DeeplyNestedParenthesesThrowInsufficientExecutionStack()
{
string script = "SELECT " + NestedText("(", "1", ")", 10000);

ParserTestUtils.ExecuteTestForAllParsers(parser =>
{
AssertThrowsInsufficientExecutionStack(() => ParseWithoutErrors(parser, script));
}, true);
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void DeeplyNestedScalarSubqueriesThrowInsufficientExecutionStack()
{
string script = "SELECT " + NestedText("(SELECT ", "1", ")", 5000);

AssertThrowsInsufficientExecutionStack(() => ParseWithoutErrors(new TSql170Parser(true), script));
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void DeeplyNestedFunctionCallsThrowInsufficientExecutionStack()
{
string script = "SELECT " + NestedText("ABS(", "1", ")", 10000);

AssertThrowsInsufficientExecutionStack(() => ParseWithoutErrors(new TSql170Parser(true), script));
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void LongBinaryExpressionChainThrowsInsufficientExecutionStack()
{
string script = "SELECT 1" + RepeatedText(" + 1", 100000);

AssertThrowsInsufficientExecutionStack(() => ParseWithoutErrors(new TSql170Parser(true), script));
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void LongUnionAllChainThrowsInsufficientExecutionStackInScriptGenerator()
{
SelectStatement statement = BuildUnionAllChain(100000);

AssertThrowsInsufficientExecutionStack(() =>
{
string script;
new Sql170ScriptGenerator().GenerateScript(statement, out script);
});
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void LongUnionAllChainThrowsInsufficientExecutionStackInVisitor()
{
SelectStatement statement = BuildUnionAllChain(100000);

AssertThrowsInsufficientExecutionStack(() => statement.Accept(new GenericFragmentVisitor<QuerySpecification>(query => true)));
}

[TestMethod]
[Priority(0)]
[SqlStudioTestCategory(Category.UnitTest)]
public void OrdinaryAndModeratelyNestedStatementsParseOnSmallStack()
{
string[] scripts =
{
"SELECT a.id, b.name FROM dbo.a AS a INNER JOIN dbo.b AS b ON a.id = b.id WHERE a.x > 1 ORDER BY b.name;",
"WITH c AS (SELECT id FROM dbo.t) SELECT id FROM c WHERE id IN (SELECT id FROM dbo.u) GROUP BY id HAVING COUNT(*) > 1;",
"CREATE PROCEDURE dbo.p @x INT AS BEGIN IF @x > 0 BEGIN UPDATE dbo.t SET y = y + 1 WHERE id = @x; END ELSE SELECT 0; END",
"SELECT " + NestedText("(", "1", ")", 64),
// SQL Server documents 32 as the nesting limit for subqueries.
"SELECT " + NestedText("(SELECT ", "1", ")", 32),
"SELECT " + NestedText("ABS(", "1", ")", 40),
"SELECT 1" + RepeatedText(" + 1", 500),
"SELECT 1" + RepeatedText(" UNION ALL SELECT 1", 400),
};

foreach (string script in scripts)
{
Exception exception = RunOnThreadWithStack(SmallStackSize, () =>
{
TSqlFragment fragment = ParseWithoutErrors(new TSql170Parser(true), script);

string generated;
new Sql170ScriptGenerator().GenerateScript(fragment, out generated);
ParseWithoutErrors(new TSql170Parser(true), generated);

fragment.Accept(new GenericFragmentVisitor<TSqlFragment>(node => true));
});

Assert.IsNull(exception, "Failed on a statement of " + script.Length + " characters: " + exception);
}
}

private static string NestedText(string open, string inner, string close, int depth)
{
return RepeatedText(open, depth) + inner + RepeatedText(close, depth);
}

private static string RepeatedText(string text, int count)
{
StringBuilder builder = new StringBuilder(text.Length * count);
for (int i = 0; i < count; i++)
{
builder.Append(text);
}
return builder.ToString();
}

private static TSqlFragment ParseWithoutErrors(TSqlParser parser, string script)
{
IList<ParseError> errors;
TSqlFragment fragment = parser.Parse(new StringReader(script), out errors);
Assert.AreEqual(0, errors.Count, errors.Count == 0 ? string.Empty : errors[0].Message);
return fragment;
}

// A left-deep chain of UNION ALL query expressions, the shape the parser builds for
// "SELECT 1 UNION ALL SELECT 1 ...". Building it directly keeps the parse out of these cases.
private static SelectStatement BuildUnionAllChain(int count)
{
QueryExpression query = BuildSelectOne();
for (int i = 0; i < count; i++)
{
query = new BinaryQueryExpression
{
BinaryQueryExpressionType = BinaryQueryExpressionType.Union,
All = true,
FirstQueryExpression = query,
SecondQueryExpression = BuildSelectOne()
};
}
return new SelectStatement { QueryExpression = query };
}

private static QuerySpecification BuildSelectOne()
{
QuerySpecification query = new QuerySpecification();
query.SelectElements.Add(new SelectScalarExpression { Expression = new IntegerLiteral { Value = "1" } });
return query;
}

// Runs the action on a new thread with the given stack size and returns what it threw, so that
// the assertion runs on the test thread.
private static Exception RunOnThreadWithStack(int maxStackSize, Action action)
{
Exception caught = null;
Thread thread = new Thread(() =>
{
try
{
action();
}
catch (Exception exception)
{
caught = exception;
}
}, maxStackSize);
thread.Start();
thread.Join();
return caught;
}

private static void AssertThrowsInsufficientExecutionStack(Action action)
{
Exception exception = RunOnThreadWithStack(SmallStackSize, action);
Assert.IsNotNull(exception, "Expected InsufficientExecutionStackException, but the call completed.");
Assert.IsInstanceOfType(exception, typeof(InsufficientExecutionStackException), exception.GetType().FullName + ": " + exception.Message);
}
}
}
2 changes: 2 additions & 0 deletions tools/AstGen/ClassDescription.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,8 @@ public void GenerateAcceptMethod(StringBuilder sb)
GenerateSummary(sb, "Accepts visitor", "\t\t");
sb.AppendLine("\t\tpublic override void Accept(" + FragmentVisitorTypeName + " visitor)");
sb.AppendLine("\t\t{");
// Visitors and the script generator recurse through Accept, so a deep tree throws instead of overflowing the stack.
sb.AppendLine("\t\t\tglobal::System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack();");
sb.AppendLine("\t\t\tif (visitor != null)");
sb.AppendLine("\t\t\t{");
sb.AppendLine("\t\t\t\tvisitor.ExplicitVisit(this);");
Expand Down