Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 78 additions & 10 deletions src/MIDebugEngine/Engine.Impl/Variables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ internal VariableInformation(string displayName, string expr, ThreadContext ctx,
: this(ctx, engine, thread)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
_strippedName = ProcessFormatSpecifiers(expr, out _format);
Name = displayName;
IsParameter = isParameter;
_parent = null;
Expand All @@ -225,7 +225,7 @@ internal VariableInformation(string expr, IVariableInformation parent, AD7Engine
: this(parent.ThreadContext, engine, parent.Client)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
_strippedName = ProcessFormatSpecifiers(expr, out _format);
Name = displayName ?? expr;
_parent = parent;
VariableNodeType = NodeType.Synthetic;
Expand All @@ -236,7 +236,7 @@ internal VariableInformation(string expr, VariableInformation parent)
: this(parent._ctx, parent._engine, parent.Client)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
_strippedName = ProcessFormatSpecifiers(expr, out _format);
Name = expr;
VariableNodeType = NodeType.Root;
}
Expand Down Expand Up @@ -337,9 +337,19 @@ public VariableInformation FindChildByName(string name)
private ThreadContext _ctx;
private bool _attribsFetched;
private bool _isReadonly;
/// <summary>
/// This callback is used when we need to call into the engine for additional information for
/// the format specifier.
///
/// <param name="threadId">The threadId to use when calling the engine.</param>
/// <param name="frameLevel">The frameLevel to use when calling the engine.</param>
/// <returns>The expression to send to the engine</returns>
/// </summary>
private delegate Task<string> DeferedFormatExpression(int threadId, uint frameLevel);
private DeferedFormatExpression _deferedFormatExpression;
private IVariableInformation _parent;
private string _format;
private string _strippedName; // "Name" stripped of format specifiers
private IVariableInformation _parent;
private string _fullname;

public enum NodeType
Expand All @@ -365,7 +375,7 @@ public enum NodeType

private static Regex s_isFunction = new Regex(@".+\(.*\).*");

private string StripFormatSpecifier(string exp, out string formatSpecifier)
private string ProcessFormatSpecifiers(string exp, out string formatSpecifier)
{
formatSpecifier = null; // will be used with -var-set-format

Expand Down Expand Up @@ -428,16 +438,35 @@ private string StripFormatSpecifier(string exp, out string formatSpecifier)
}

// array with static size
// TODO: could return '(T(*)[n])(exp)' but requires T
var m = Regex.Match(trimmed, @"^\[?(\d+)\]?$");
if (m.Success)
{
string count = m.Groups[1].Value; // (\d+) capture group
string expr = exp.Substring(0, lastComma);

if (_engine.DebuggedProcess.MICommandFactory.Mode == MIMode.Gdb)
return "*" + exp.Substring(0, lastComma) + "@" + trimmed; // this does not work for lldb
{
// return *<expression>@<count> which is only supported in GDB
return FormattableString.Invariant($"*{expr}@{count}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this work with more complex expressions?
Parens around expr might be needed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also I think this syntax works for dynamic sizes too, see L472.

}
else
{
_deferedFormatExpression = async (int threadId, uint frameLevel) =>
{
string derefType = await GetDereferencedTypeStringAsync(expr, threadId, frameLevel);

return exp.Substring(0, lastComma);
}
if (!string.IsNullOrEmpty(derefType))
{
// Cast 'exp' to a pointer of an array of type 'T' with size 'n' with '*(T(*)[n])(exp)'
return FormattableString.Invariant($"*({derefType}(*)[{count}])({expr})");
}

return string.Empty;
};

return expr;
}
}

// array with dynamic size
if (Regex.Match(trimmed, @"^\[([a-zA-Z_][a-zA-Z_\d]*)\]$").Success)
Expand All @@ -446,6 +475,27 @@ private string StripFormatSpecifier(string exp, out string formatSpecifier)
return exp;
}

private async Task<string> GetDereferencedTypeStringAsync(string expr, int threadId, uint frameLevel)
{
// TODO: Should we error if the current type is not a pointer type?

// Evaluates: *expr
Results results = await _engine.DebuggedProcess.MICommandFactory.VarCreate($"*({expr})", threadId, frameLevel, 0, ResultClass.None);

if (results.ResultClass == ResultClass.done)
{
Comment thread
WardenGnaw marked this conversation as resolved.
Resolved
string varName = results.TryFindString("name");
if (!String.IsNullOrWhiteSpace(varName))
{
// Remove the variable we created as we don't track it.
await _engine.DebuggedProcess.MICommandFactory.VarDelete(varName);
}

return results.TryFindString("type");
}
return null;
}

public void AsyncEval(IDebugEventCallback2 pExprCallback)
{
EngineCallback engineCallback;
Expand Down Expand Up @@ -547,7 +597,25 @@ internal async Task Eval(uint radix, enum_EVALFLAGS dwFlags = 0, DAPEvalFlags dw

int threadId = Client.GetDebuggedThread().Id;
uint frameLevel = _ctx.Level;
Results results = await _engine.DebuggedProcess.MICommandFactory.VarCreate(_strippedName, threadId, frameLevel, dwFlags, ResultClass.None);

string expression = _strippedName;

// If we have a deferred format expression, resolve it.
if (_deferedFormatExpression != null)
{
string deferedExpression = await _deferedFormatExpression(threadId, frameLevel);

if (!string.IsNullOrEmpty(deferedExpression))
{
expression = deferedExpression;
}
else
{
Debug.Fail(FormattableString.Invariant($"Failed to resolve deferred expression. Falling back to original: '{expression}'."));
}
}

Results results = await _engine.DebuggedProcess.MICommandFactory.VarCreate(expression, threadId, frameLevel, dwFlags, ResultClass.None);

if (results.ResultClass == ResultClass.done)
{
Expand Down
41 changes: 38 additions & 3 deletions test/CppTests/Tests/NatvisTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,9 +402,7 @@ public void TestThisConditional(ITestSettings settings)
[Theory]
[DependsOnTest(nameof(CompileNatvisDebuggee))]
[RequiresTestSettings]
// Disable on macOS
[UnsupportedDebugger(SupportedDebugger.Lldb, SupportedArchitecture.x64 | SupportedArchitecture.x86)]
public void TestArrayPointer(ITestSettings settings)
public void TestCommaFormatSpecifier(ITestSettings settings)
{
this.TestPurpose("This test checks if the comma format specifier is visualized.");
this.WriteSettings(settings);
Expand Down Expand Up @@ -438,6 +436,43 @@ public void TestArrayPointer(ITestSettings settings)
}
}

[Theory]
[DependsOnTest(nameof(CompileNatvisDebuggee))]
[RequiresTestSettings]
public void TestCommaFormatWithSquareBrackets(ITestSettings settings)
{
this.TestPurpose("This test checks if the comma format specifier with square brackets is visualized.");
this.WriteSettings(settings);

IDebuggee debuggee = Debuggee.Open(this, settings.CompilerSettings, NatvisName, DebuggeeMonikers.Natvis.Default);

this.Comment("Run the debuggee, check argument count");
using (IDebuggerRunner runner = CreateDebugAdapterRunner(settings))
{
this.Comment("Configure launch");
LaunchCommand launch = new LaunchCommand(settings.DebuggerSettings, debuggee.OutputPath);
runner.RunCommand(launch);

this.Comment("Set Breakpoint");
SourceBreakpoints writerBreakpoints = debuggee.Breakpoints(NatvisSourceName, ReturnSourceLine);
runner.SetBreakpoints(writerBreakpoints);

runner.Expects.StoppedEvent(StoppedReason.Breakpoint).AfterConfigurationDone();

using (IThreadInspector threadInspector = runner.GetThreadInspector())
{
IFrameInspector currentFrame = threadInspector.Stack.First();

this.Comment("Verifying comma format specifier");
int[] expected = { 0, 1, 4, 9 };
currentFrame.AssertEvaluateAsIntArray("arr._array,[4]", EvaluateContext.Watch, expected);
}

runner.Expects.ExitedEvent(exitCode: 0).TerminatedEvent().AfterContinue();
runner.DisconnectAndVerify();
}
}

#endregion
}
}