public

Demonstrate PowerShell memory leak with XmlSchemaSet

  • Download Gist
repro-xmlschemaset-memoryleak.ps1
PowerShell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
function cleanup() {
write-host "Cleaning up..."
remove-item $schemaFile
break
}
 
trap {
cleanup
}
 
# The following was stolen from http://powershellquiz.com/post/10429186577/a4-one-bit-of-difference
Add-Type -Language CSharp -TypeDefinition @'
public class NullString {
public override string ToString() {
return null;
}
}
'@
$null_for_dotnet_string = New-Object -TypeName NullString;
 
 
$TEST_SCHEMA = @'
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:x">
<element name="a" type="string"/>
<element name="b" type="string"/>
<element name="c" type="string"/>
<element name="d" type="string"/>
<element name="e" type="string"/>
<element name="f" type="string"/>
<element name="A" type="string"/>
<element name="B" type="string"/>
<element name="C" type="string"/>
<element name="D" type="string"/>
<element name="E" type="string"/>
<element name="F" type="string"/>
</schema>
'@
 
$schemaFileName = [System.IO.Path]::GetTempFileName()
 
$TEST_SCHEMA > $schemaFileName
 
$N = 100000
 
1..$N |% {
 
if ($_ % 100 -eq 0) { write-host -nonewline '.' }
 
$schemaSet = new-object -typename System.Xml.Schema.XmlSchemaSet
 
$dummy = register-objectevent $schemaSet ValidationEventHandler -MessageData $schemaFileName -Action {
$a = $args[1]
$e = $a.Exception
$topLevelFileName = $event.MessageData
write-host "$($topLevelFileName): $($a.Severity) in $($e.SourceUri) at line $($e.LineNumber) column $($e.LinePosition): $($e.Message)"
}
 
try {
$reader = [System.Xml.XmlReader]::Create($schemaFileName)
 
# Passing $null to a .NET method which expects a string
# doesn't work: PowerShell passes an empty string instead,
# which has a different (and incorrect) meaning for Add().
[void] $schemaSet.Add($null_for_dotnet_string, $reader)
# ATTEMPT: $schema = $schemaSet.Add($null_for_dotnet_string, $reader)
 
$reader.Close()
 
$schemaSet.Compile()
 
# ATTEMPT: [void] $schemaSet.RemoveRecursive($schema)
# ATTEMPT: remove-variable schema
} catch {
write-host "$($schemaFileName): Exception: $_"
}
 
# ATTEMPT: remove-variable reader
# ATTEMPT: remove-variable schemaSet
}
 
write-host

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.