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

feat: add stacktrace context to inline code #65

Merged
merged 8 commits into from
Oct 23, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Features

- Send events to Sentry fully synchronously ([#59](https://github.com/SummitHosting/sentry-powershell/pull/59), [#62](https://github.com/SummitHosting/sentry-powershell/pull/62))
- Add StackTrace context to frames coming from inline script/command ([#65](https://github.com/getsentry/sentry-powershell/pull/65))

### Fixes

Expand Down
165 changes: 125 additions & 40 deletions modules/Sentry/private/StackTraceProcessor.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -114,33 +114,11 @@ class StackTraceProcessor : SentryEventProcessor
hidden [Sentry.SentryStackTrace]GetStackTrace()
{
# We collect all frames and then reverse them to the order expected by Sentry (caller->callee).
# Do not try to make this code go backwards, because it relies on the InvocationInfo from the previous frame.
# Do not try to make this code go backwards because it relies on the InvocationInfo from the previous frame.
$sentryFrames = New-Object System.Collections.Generic.List[Sentry.SentryStackFrame]
if ($null -ne $this.StackTraceFrames)
{
$sentryFrames.Capacity = $this.StackTraceFrames.Count + 1
}
elseif ($null -ne $this.StackTraceString)
if ($null -ne $this.StackTraceString)
{
$sentryFrames.Capacity = $this.StackTraceString.Count + 1
}

if ($null -ne $this.StackTraceFrames)
{
# Note: if InvocationInfo is present, use it to fill the first frame. This is the case for ErrroRecord handling
# and has the information about the actual script file and line that have thrown the exception.
if ($null -ne $this.InvocationInfo)
{
$sentryFrames.Add($this.CreateFrame($this.InvocationInfo))
}

foreach ($frame in $this.StackTraceFrames)
{
$sentryFrames.Add($this.CreateFrame($frame))
}
}
elseif ($null -ne $this.StackTraceString)
{
# Note: if InvocationInfo is present, use it to update:
# - the first frame (in case of `$_ | Out-Sentry` in a catch clause).
# - the second frame (in case of `write-error` and `$_ | Out-Sentry` in a trap).
Expand All @@ -167,10 +145,21 @@ class StackTraceProcessor : SentryEventProcessor
}
$sentryFrames.Add($sentryFrame)
}

if ($null -ne $sentryFrameInitial)
{
$sentryFrames.Insert(0, $sentryFrameInitial)
}

$this.EnhanceTailFrames($sentryFrames)
}
elseif ($null -ne $this.StackTraceFrames)
{
$sentryFrames.Capacity = $this.StackTraceFrames.Count + 1
foreach ($frame in $this.StackTraceFrames)
{
$sentryFrames.Add($this.CreateFrame($frame))
}
}

foreach ($sentryFrame in $sentryFrames)
Expand Down Expand Up @@ -213,7 +202,10 @@ class StackTraceProcessor : SentryEventProcessor
$regex = 'at (?<Function>[^,]*), (?<AbsolutePath>.*): line (?<LineNumber>\d*)'
if ($frame -match $regex)
{
$sentryFrame.AbsolutePath = $Matches.AbsolutePath
if ($Matches.AbsolutePath -ne '<No file>')
{
$sentryFrame.AbsolutePath = $Matches.AbsolutePath
}
$sentryFrame.LineNumber = [int]$Matches.LineNumber
$sentryFrame.Function = $Matches.Function
}
Expand All @@ -224,6 +216,54 @@ class StackTraceProcessor : SentryEventProcessor
return $sentryFrame
}

hidden EnhanceTailFrames([Sentry.SentryStackFrame[]] $sentryFrames)
{
if ($null -eq $this.StackTraceFrames)
{
return
}

# The last frame is usually how the PowerShell was invoked. We need to get this info from $this.StackTraceFrames
# - for pwsh scriptname.ps1 it would be something like `. scriptname.ps1`
# - for pwsh -c `& {..}` it would be the `& {..}` code block. And in this case, the next frame would also be
# just a scriptblock without a filename so we need to get the source code from the StackTraceFrames too.
$i = 0;
for ($j = $sentryFrames.Count - 1; $j -ge 0; $j--)
{
$sentryFrame = $sentryFrames[$j]
$frame = $this.StackTraceFrames | Select-Object -Last 1 -Skip $i
$i++

if ($null -eq $frame)
{
break
}

if ($null -eq $sentryFrame.AbsolutePath -and $null -eq $frame.ScriptName)
{
if ($frame.ScriptLineNumber -gt 0 -and $frame.ScriptLineNumber -eq $sentryFrame.LineNumber)
{
$this.SetScriptInfo($sentryFrame, $frame)
$this.SetModule($sentryFrame)
$this.SetFunction($sentryFrame, $frame)
}
$this.SetContextLines($sentryFrame, $frame)

# Try to match following frames that are part of the same codeblock.
while ($j -gt 0)
{
$nextSentryFrame = $sentryFrames[$j - 1]
if ($nextSentryFrame.AbsolutePath -ne $sentryFrame.AbsolutePath)
{
break
}
$this.SetContextLines($nextSentryFrame, $frame)
$j--
}
}
}
}

hidden SetScriptInfo([Sentry.SentryStackFrame] $sentryFrame, [System.Management.Automation.CallStackFrame] $frame)
{
if (![string]::IsNullOrEmpty($frame.ScriptName))
Expand Down Expand Up @@ -268,13 +308,42 @@ class StackTraceProcessor : SentryEventProcessor
if ([string]::IsNullOrEmpty($sentryFrame.AbsolutePath) -and $frame.FunctionName -eq '<ScriptBlock>' -and ![string]::IsNullOrEmpty($frame.Position))
{
$sentryFrame.Function = $frame.Position.Text

# $frame.Position.Text may be a multiline command (e.g. when executed with `pwsh -c '& { ... \n ... \n ... }`)
# So we need to trim it to a single line.
if ($sentryFrame.Function.Contains("`n"))
{
$lines = $sentryFrame.Function -split "[`r`n]+"
$sentryFrame.Function = $lines[0] + ' '
if ($lines.Count -gt 2)
{
$sentryFrame.Function += ' ...<multiline script content omitted>... '
}
$sentryFrame.Function += $lines[$lines.Count - 1]
}
}
else
{
$sentryFrame.Function = $frame.FunctionName
}
}

hidden SetContextLines([Sentry.SentryStackFrame] $sentryFrame, [System.Management.Automation.CallStackFrame] $frame)
{
if ($sentryFrame.LineNumber -gt 0)
{
try
{
$lines = $frame.InvocationInfo.MyCommand.ScriptBlock.ToString() -split "`n"
$this.SetContextLines($sentryFrame, $lines)
}
catch
{
Write-Warning "Failed to read context lines for frame with function '$($sentryFrame.Function)': $_"
}
}
}

hidden SetContextLines([Sentry.SentryStackFrame] $sentryFrame)
{
if ([string]::IsNullOrEmpty($sentryFrame.AbsolutePath) -or $sentryFrame.LineNumber -lt 1)
Expand All @@ -287,26 +356,42 @@ class StackTraceProcessor : SentryEventProcessor
try
{
$lines = Get-Content $sentryFrame.AbsolutePath -TotalCount ($sentryFrame.LineNumber + 5)
if ($null -eq $sentryFrame.ContextLine)
{
$sentryFrame.ContextLine = $lines[$sentryFrame.LineNumber - 1]
}
$preContextCount = [math]::Min(5, $sentryFrame.LineNumber - 1)
$postContextCount = [math]::Min(5, $lines.Count - $sentryFrame.LineNumber)
if ($sentryFrame.LineNumber -gt 6)
{
$lines = $lines | Select-Object -Skip ($sentryFrame.LineNumber - 6)
}
# Note: these are read-only in sentry-dotnet so we just update the underlying lists instead of replacing.
$sentryFrame.PreContext.Clear()
$lines | Select-Object -First $preContextCount | ForEach-Object { $sentryFrame.PreContext.Add($_) }
$sentryFrame.PostContext.Clear()
$lines | Select-Object -Last $postContextCount | ForEach-Object { $sentryFrame.PostContext.Add($_) }
$this.SetContextLines($sentryFrame, $lines)
}
catch
{
Write-Warning "Failed to read context lines for $($sentryFrame.AbsolutePath): $_"
}
}
}

hidden SetContextLines([Sentry.SentryStackFrame] $sentryFrame, [string[]] $lines)
{
if ($lines.Count -lt $sentryFrame.LineNumber)
{
Write-Debug "Couldn't set frame context because the line number ($($sentryFrame.LineNumber)) is lower than the available number of source code lines ($($lines.Count))."
return
}

$numContextLines = 5

if ($null -eq $sentryFrame.ContextLine)
{
$sentryFrame.ContextLine = $lines[$sentryFrame.LineNumber - 1]
}

$preContextCount = [math]::Min($numContextLines, $sentryFrame.LineNumber - 1)
$postContextCount = [math]::Min($numContextLines, $lines.Count - $sentryFrame.LineNumber)

if ($sentryFrame.LineNumber -gt $numContextLines + 1)
{
$lines = $lines | Select-Object -Skip ($sentryFrame.LineNumber - $numContextLines - 1)
}

# Note: these are read-only in sentry-dotnet so we just update the underlying lists instead of replacing.
$sentryFrame.PreContext.Clear()
$lines | Select-Object -First $preContextCount | ForEach-Object { $sentryFrame.PreContext.Add($_) }
$sentryFrame.PostContext.Clear()
$lines | Select-Object -First $postContextCount -Skip ($preContextCount + 1) | ForEach-Object { $sentryFrame.PostContext.Add($_) }
}
}
2 changes: 1 addition & 1 deletion modules/Sentry/public/Out-Sentry.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function Out-Sentry
return
}

if ($options.AttachStackTrace -and $null -eq $processor.StackTraceFrames -and $null -eq $processor.StackTraceString)
if ($options.AttachStackTrace -and $null -eq $processor.StackTraceFrames)
{
$processor.StackTraceFrames = Get-PSCallStack | Select-Object -Skip 1
}
Expand Down
16 changes: 11 additions & 5 deletions tests/integration-test-script.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@ Set-StrictMode -Version latest
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true

Import-Module ../modules/Sentry/Sentry.psd1
. ./utils.ps1
. ./throwingshort.ps1
Import-Module ./modules/Sentry/Sentry.psd1
. ./tests/utils.ps1
. ./tests/throwingshort.ps1

function funcA
{
# Call to another file
funcC
}

$events = [System.Collections.Generic.List[Sentry.SentryEvent]]::new();
$transport = [RecordingTransport]::new()
StartSentryForEventTests ([ref] $events) ([ref] $transport)

try
{
funcC
funcA
}
catch
{
Expand All @@ -29,7 +35,7 @@ $thread.Stacktrace.Frames | ForEach-Object {
$value = $frame.$prop | Out-String -Width 500
if ("$value" -ne '')
{
"$($prop): $value"
"$($prop): $value".TrimEnd()
}
}
}
Loading
Loading