repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/libraries/System.Private.CoreLib/src/System/Threading/ThreadInt64PersistentCounter.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Threading
{
internal sealed class ThreadInt64PersistentCounter
{
private static readonly LowLevelLock s_lock = new LowLevelLock();
[ThreadStatic]
private static List<ThreadLocalNodeFinalizationHelper>? t_nodeFinalizationHelpers;
private long _overflowCount;
private HashSet<ThreadLocalNode> _nodes = new HashSet<ThreadLocalNode>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Increment(object threadLocalCountObject)
{
Debug.Assert(threadLocalCountObject is ThreadLocalNode);
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Increment();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(object threadLocalCountObject, uint count)
{
Debug.Assert(threadLocalCountObject is ThreadLocalNode);
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Add(count);
}
public object CreateThreadLocalCountObject()
{
var node = new ThreadLocalNode(this);
List<ThreadLocalNodeFinalizationHelper>? nodeFinalizationHelpers = t_nodeFinalizationHelpers ??= new List<ThreadLocalNodeFinalizationHelper>(1);
nodeFinalizationHelpers.Add(new ThreadLocalNodeFinalizationHelper(node));
s_lock.Acquire();
try
{
_nodes.Add(node);
}
finally
{
s_lock.Release();
}
return node;
}
public long Count
{
get
{
s_lock.Acquire();
long count = _overflowCount;
try
{
foreach (ThreadLocalNode node in _nodes)
{
count += node.Count;
}
}
catch (OutOfMemoryException)
{
// Some allocation occurs above and it may be a bit awkward to get an OOM from this property getter
}
finally
{
s_lock.Release();
}
return count;
}
}
private sealed class ThreadLocalNode
{
private uint _count;
private readonly ThreadInt64PersistentCounter _counter;
public ThreadLocalNode(ThreadInt64PersistentCounter counter)
{
Debug.Assert(counter != null);
_counter = counter;
}
public void Dispose()
{
ThreadInt64PersistentCounter counter = _counter;
s_lock.Acquire();
try
{
counter._overflowCount += _count;
counter._nodes.Remove(this);
}
finally
{
s_lock.Release();
}
}
public uint Count => _count;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Increment()
{
uint newCount = _count + 1;
if (newCount != 0)
{
_count = newCount;
return;
}
OnAddOverflow(1);
}
public void Add(uint count)
{
Debug.Assert(count != 0);
uint newCount = _count + count;
if (newCount >= count)
{
_count = newCount;
return;
}
OnAddOverflow(count);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void OnAddOverflow(uint count)
{
Debug.Assert(count != 0);
// Accumulate the count for this add into the overflow count and reset the thread-local count
// The lock, in coordination with other places that read these values, ensures that both changes below become
// visible together
ThreadInt64PersistentCounter counter = _counter;
s_lock.Acquire();
try
{
counter._overflowCount += (long)_count + count;
_count = 0;
}
finally
{
s_lock.Release();
}
}
}
private sealed class ThreadLocalNodeFinalizationHelper
{
private readonly ThreadLocalNode _node;
public ThreadLocalNodeFinalizationHelper(ThreadLocalNode node)
{
Debug.Assert(node != null);
_node = node;
}
~ThreadLocalNodeFinalizationHelper() => _node.Dispose();
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Threading
{
internal sealed class ThreadInt64PersistentCounter
{
private static readonly LowLevelLock s_lock = new LowLevelLock();
[ThreadStatic]
private static List<ThreadLocalNodeFinalizationHelper>? t_nodeFinalizationHelpers;
private long _overflowCount;
private HashSet<ThreadLocalNode> _nodes = new HashSet<ThreadLocalNode>();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Increment(object threadLocalCountObject)
{
Debug.Assert(threadLocalCountObject is ThreadLocalNode);
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Increment();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(object threadLocalCountObject, uint count)
{
Debug.Assert(threadLocalCountObject is ThreadLocalNode);
Unsafe.As<ThreadLocalNode>(threadLocalCountObject).Add(count);
}
public object CreateThreadLocalCountObject()
{
var node = new ThreadLocalNode(this);
List<ThreadLocalNodeFinalizationHelper>? nodeFinalizationHelpers = t_nodeFinalizationHelpers ??= new List<ThreadLocalNodeFinalizationHelper>(1);
nodeFinalizationHelpers.Add(new ThreadLocalNodeFinalizationHelper(node));
s_lock.Acquire();
try
{
_nodes.Add(node);
}
finally
{
s_lock.Release();
}
return node;
}
public long Count
{
get
{
s_lock.Acquire();
long count = _overflowCount;
try
{
foreach (ThreadLocalNode node in _nodes)
{
count += node.Count;
}
}
catch (OutOfMemoryException)
{
// Some allocation occurs above and it may be a bit awkward to get an OOM from this property getter
}
finally
{
s_lock.Release();
}
return count;
}
}
private sealed class ThreadLocalNode
{
private uint _count;
private readonly ThreadInt64PersistentCounter _counter;
public ThreadLocalNode(ThreadInt64PersistentCounter counter)
{
Debug.Assert(counter != null);
_counter = counter;
}
public void Dispose()
{
ThreadInt64PersistentCounter counter = _counter;
s_lock.Acquire();
try
{
counter._overflowCount += _count;
counter._nodes.Remove(this);
}
finally
{
s_lock.Release();
}
}
public uint Count => _count;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Increment()
{
uint newCount = _count + 1;
if (newCount != 0)
{
_count = newCount;
return;
}
OnAddOverflow(1);
}
public void Add(uint count)
{
Debug.Assert(count != 0);
uint newCount = _count + count;
if (newCount >= count)
{
_count = newCount;
return;
}
OnAddOverflow(count);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void OnAddOverflow(uint count)
{
Debug.Assert(count != 0);
// Accumulate the count for this add into the overflow count and reset the thread-local count
// The lock, in coordination with other places that read these values, ensures that both changes below become
// visible together
ThreadInt64PersistentCounter counter = _counter;
s_lock.Acquire();
try
{
counter._overflowCount += (long)_count + count;
_count = 0;
}
finally
{
s_lock.Release();
}
}
}
private sealed class ThreadLocalNodeFinalizationHelper
{
private readonly ThreadLocalNode _node;
public ThreadLocalNodeFinalizationHelper(ThreadLocalNode node)
{
Debug.Assert(node != null);
_node = node;
}
~ThreadLocalNodeFinalizationHelper() => _node.Dispose();
}
}
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/Methodical/Arrays/range/int32_m1_il_d.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<DebugType>Full</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="int32_m1.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<DebugType>Full</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Include="int32_m1.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/Methodical/MDArray/DataTypes/ulong_cs_do.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="ulong.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="ulong.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _ICorJitInfo
#define _ICorJitInfo
#include "runtimedetails.h"
#include "methodcallsummarizer.h"
class interceptor_ICJI : public ICorJitInfo
{
#include "icorjitinfoimpl.h"
public:
// Added to help us track the original icji and be able to easily indirect
// to it. And a simple way to keep one memory manager instance per instance.
ICorJitInfo* original_ICorJitInfo;
MethodCallSummarizer* mcs;
};
#endif
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _ICorJitInfo
#define _ICorJitInfo
#include "runtimedetails.h"
#include "methodcallsummarizer.h"
class interceptor_ICJI : public ICorJitInfo
{
#include "icorjitinfoimpl.h"
public:
// Added to help us track the original icji and be able to easily indirect
// to it. And a simple way to keep one memory manager instance per instance.
ICorJitInfo* original_ICorJitInfo;
MethodCallSummarizer* mcs;
};
#endif
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/coreclr/nativeaot/Runtime/inc/type_traits.hpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// type_traits.hpp
//
// Type trait metaprogramming utilities.
//
#ifndef __TYPE_TRAITS_HPP__
#define __TYPE_TRAITS_HPP__
#include "CommonTypes.h"
namespace type_traits
{
namespace imp
{
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
////////////////////////////////////////////////////////////////////////////////
// Helper types Small and Big - guarantee that sizeof(Small) < sizeof(Big)
//
template <class T, class U>
struct conversion_helper
{
typedef char Small;
struct Big { char dummy[2]; };
static Big Test(...);
static Small Test(U);
static T MakeT();
};
////////////////////////////////////////////////////////////////////////////////
// class template conversion
// Figures out the conversion relationships between two types
// Invocations (T and U are types):
// a) conversion<T, U>::exists
// returns (at compile time) true if there is an implicit conversion from T
// to U (example: Derived to Base)
// b) conversion<T, U>::exists2Way
// returns (at compile time) true if there are both conversions from T
// to U and from U to T (example: int to char and back)
// c) conversion<T, U>::sameType
// returns (at compile time) true if T and U represent the same type
//
// NOTE: might not work if T and U are in a private inheritance hierarchy.
//
template <class T, class U>
struct conversion
{
typedef imp::conversion_helper<T, U> H;
static const bool exists = sizeof(typename H::Small) == sizeof((H::Test(H::MakeT())));
static const bool exists2Way = exists && conversion<U, T>::exists;
static const bool sameType = false;
};
template <class T>
struct conversion<T, T>
{
static const bool exists = true;
static const bool exists2Way = true;
static const bool sameType = true;
};
template <class T>
struct conversion<void, T>
{
static const bool exists = false;
static const bool exists2Way = false;
static const bool sameType = false;
};
template <class T>
struct conversion<T, void>
{
static const bool exists = false;
static const bool exists2Way = false;
static const bool sameType = false;
};
template <>
struct conversion<void, void>
{
static const bool exists = true;
static const bool exists2Way = true;
static const bool sameType = true;
};
template <bool>
struct is_base_of_helper;
template <>
struct is_base_of_helper<true> : public true_type {} ;
template <>
struct is_base_of_helper<false> : public false_type {} ;
}// imp
////////////////////////////////////////////////////////////////////////////////
// is_base_of::value is typedefed to be true if TDerived derives from TBase
// and false otherwise.
//
//
// NOTE: use TR1 type_traits::is_base_of when available.
//
#ifdef _MSC_VER
template <typename TBase, typename TDerived>
struct is_base_of : public imp::is_base_of_helper<__is_base_of( TBase, TDerived)> {};
#else
// Note that we need to compare pointer types here, since conversion of types by-value
// just tells us whether or not an implicit conversion constructor exists. We handle
// type parameters that are already pointers specially; see below.
template <typename TBase, typename TDerived>
struct is_base_of : public imp::is_base_of_helper<imp::conversion<TDerived *, TBase *>::exists> {};
// Specialization to handle type parameters that are already pointers.
template <typename TBase, typename TDerived>
struct is_base_of<TBase *, TDerived *> : public imp::is_base_of_helper<imp::conversion<TDerived *, TBase *>::exists> {};
// Specialization to handle invalid mixing of pointer types.
template <typename TBase, typename TDerived>
struct is_base_of<TBase *, TDerived> : public imp::false_type {};
// Specialization to handle invalid mixing of pointer types.
template <typename TBase, typename TDerived>
struct is_base_of<TBase, TDerived *> : public imp::false_type {};
#endif
////////////////////////////////////////////////////////////////////////////////
// Remove const qualifications, if any. Access using remove_const::type
//
template <typename T> struct remove_const { typedef T type; };
template <typename T> struct remove_const<T const> { typedef T type; };
////////////////////////////////////////////////////////////////////////////////
// is_signed::value is true if T is a signed integral type, false otherwise.
//
template <typename T>
struct is_signed { static const bool value = (static_cast<T>(-1) < 0); };
}
////////////////////////////////////////////////////////////////////////////////
// These are related to type traits, but they are more like asserts of type
// traits in that the result is that either the compiler does or does not
// produce an error.
//
namespace type_constraints
{
////////////////////////////////////////////////////////////////////////////////
// derived_from will produce a compiler error if TDerived does not
// derive from TBase.
//
// NOTE: use TR1 type_traits::is_base_of when available.
//
template<class TBase, class TDerived> struct is_base_of
{
is_base_of()
{
static_assert((type_traits::is_base_of<TBase, TDerived>::value),
"is_base_of() constraint violation: TDerived does not derive from TBase");
}
};
}; // namespace type_constraints
namespace rh { namespace std
{
// Import some select components of the STL
// TEMPLATE FUNCTION for_each
template<class _InIt, class _Fn1>
inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First);
return (_Func);
}
template<class _InIt, class _Ty>
inline
_InIt find(_InIt _First, _InIt _Last, const _Ty& _Val)
{ // find first matching _Val
for (; _First != _Last; ++_First)
if (*_First == _Val)
break;
return (_First);
}
template<class _InIt, class _Pr>
inline
_InIt find_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // find first satisfying _Pred
for (; _First != _Last; ++_First)
if (_Pred(*_First))
break;
return (_First);
}
template<class _InIt, class _Ty>
inline
bool exists(_InIt _First, _InIt _Last, const _Ty& _Val)
{
return find(_First, _Last, _Val) != _Last;
}
template<class _InIt, class _Pr>
inline
bool exists_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
return find_if(_First, _Last, _Pred) != _Last;
}
template<class _InIt, class _Ty>
inline
uintptr_t count(_InIt _First, _InIt _Last, const _Ty& _Val)
{
uintptr_t _Ret = 0;
for (; _First != _Last; _First++)
if (*_First == _Val)
++_Ret;
return _Ret;
}
template<class _InIt, class _Pr>
inline
uintptr_t count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
uintptr_t _Ret = 0;
for (; _First != _Last; _First++)
if (_Pred(*_First))
++_Ret;
return _Ret;
}
// Forward declaration, each collection requires specialization
template<class _FwdIt, class _Ty>
inline
_FwdIt remove(_FwdIt _First, _FwdIt _Last, const _Ty& _Val);
} // namespace std
} // namespace rh
#if 0
// -----------------------------------------------------------------
// Holding place for unused-but-possibly-useful-in-the-future code.
// -------------------------------------------------
// This belongs in type_traits.hpp
//
// is_pointer::value is true if the type is a pointer, false otherwise
//
template <typename T> struct is_pointer : public false_type {};
template <typename T> struct is_pointer<T *> : public true_type {};
//
// Remove pointer from type, if it has one. Use remove_pointer::type
// Further specialized in daccess.h
//
template <typename T> struct remove_pointer { typedef T type; };
template <typename T> struct remove_pointer<T *> { typedef T type; };
// -------------------------------------------------
// This belongs in daccess.h
namespace type_traits
{
//
// is_pointer::value is true if the type is a pointer, false otherwise
// specialized from type_traits.hpp
//
template <typename T> struct is_pointer<typename __DPtr<T> > : public type_traits::true_type {};
//
// remove_pointer::type is T with one less pointer qualification, if it had one.
// specialized from type_traits.hpp
//
template <typename T> struct remove_pointer<typename __DPtr<T> > { typedef T type; };
} // type_traits
namespace dac
{
//
// is_dptr::value is true if T is a __DPtr, false otherwise.
// This is a partial specialization case for the positive case.
//
//template <typename T> struct is_dptr<typename __DPtr<T> > : public type_traits::true_type {};
}
#endif
#endif
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// type_traits.hpp
//
// Type trait metaprogramming utilities.
//
#ifndef __TYPE_TRAITS_HPP__
#define __TYPE_TRAITS_HPP__
#include "CommonTypes.h"
namespace type_traits
{
namespace imp
{
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
////////////////////////////////////////////////////////////////////////////////
// Helper types Small and Big - guarantee that sizeof(Small) < sizeof(Big)
//
template <class T, class U>
struct conversion_helper
{
typedef char Small;
struct Big { char dummy[2]; };
static Big Test(...);
static Small Test(U);
static T MakeT();
};
////////////////////////////////////////////////////////////////////////////////
// class template conversion
// Figures out the conversion relationships between two types
// Invocations (T and U are types):
// a) conversion<T, U>::exists
// returns (at compile time) true if there is an implicit conversion from T
// to U (example: Derived to Base)
// b) conversion<T, U>::exists2Way
// returns (at compile time) true if there are both conversions from T
// to U and from U to T (example: int to char and back)
// c) conversion<T, U>::sameType
// returns (at compile time) true if T and U represent the same type
//
// NOTE: might not work if T and U are in a private inheritance hierarchy.
//
template <class T, class U>
struct conversion
{
typedef imp::conversion_helper<T, U> H;
static const bool exists = sizeof(typename H::Small) == sizeof((H::Test(H::MakeT())));
static const bool exists2Way = exists && conversion<U, T>::exists;
static const bool sameType = false;
};
template <class T>
struct conversion<T, T>
{
static const bool exists = true;
static const bool exists2Way = true;
static const bool sameType = true;
};
template <class T>
struct conversion<void, T>
{
static const bool exists = false;
static const bool exists2Way = false;
static const bool sameType = false;
};
template <class T>
struct conversion<T, void>
{
static const bool exists = false;
static const bool exists2Way = false;
static const bool sameType = false;
};
template <>
struct conversion<void, void>
{
static const bool exists = true;
static const bool exists2Way = true;
static const bool sameType = true;
};
template <bool>
struct is_base_of_helper;
template <>
struct is_base_of_helper<true> : public true_type {} ;
template <>
struct is_base_of_helper<false> : public false_type {} ;
}// imp
////////////////////////////////////////////////////////////////////////////////
// is_base_of::value is typedefed to be true if TDerived derives from TBase
// and false otherwise.
//
//
// NOTE: use TR1 type_traits::is_base_of when available.
//
#ifdef _MSC_VER
template <typename TBase, typename TDerived>
struct is_base_of : public imp::is_base_of_helper<__is_base_of( TBase, TDerived)> {};
#else
// Note that we need to compare pointer types here, since conversion of types by-value
// just tells us whether or not an implicit conversion constructor exists. We handle
// type parameters that are already pointers specially; see below.
template <typename TBase, typename TDerived>
struct is_base_of : public imp::is_base_of_helper<imp::conversion<TDerived *, TBase *>::exists> {};
// Specialization to handle type parameters that are already pointers.
template <typename TBase, typename TDerived>
struct is_base_of<TBase *, TDerived *> : public imp::is_base_of_helper<imp::conversion<TDerived *, TBase *>::exists> {};
// Specialization to handle invalid mixing of pointer types.
template <typename TBase, typename TDerived>
struct is_base_of<TBase *, TDerived> : public imp::false_type {};
// Specialization to handle invalid mixing of pointer types.
template <typename TBase, typename TDerived>
struct is_base_of<TBase, TDerived *> : public imp::false_type {};
#endif
////////////////////////////////////////////////////////////////////////////////
// Remove const qualifications, if any. Access using remove_const::type
//
template <typename T> struct remove_const { typedef T type; };
template <typename T> struct remove_const<T const> { typedef T type; };
////////////////////////////////////////////////////////////////////////////////
// is_signed::value is true if T is a signed integral type, false otherwise.
//
template <typename T>
struct is_signed { static const bool value = (static_cast<T>(-1) < 0); };
}
////////////////////////////////////////////////////////////////////////////////
// These are related to type traits, but they are more like asserts of type
// traits in that the result is that either the compiler does or does not
// produce an error.
//
namespace type_constraints
{
////////////////////////////////////////////////////////////////////////////////
// derived_from will produce a compiler error if TDerived does not
// derive from TBase.
//
// NOTE: use TR1 type_traits::is_base_of when available.
//
template<class TBase, class TDerived> struct is_base_of
{
is_base_of()
{
static_assert((type_traits::is_base_of<TBase, TDerived>::value),
"is_base_of() constraint violation: TDerived does not derive from TBase");
}
};
}; // namespace type_constraints
namespace rh { namespace std
{
// Import some select components of the STL
// TEMPLATE FUNCTION for_each
template<class _InIt, class _Fn1>
inline
_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
{ // perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First);
return (_Func);
}
template<class _InIt, class _Ty>
inline
_InIt find(_InIt _First, _InIt _Last, const _Ty& _Val)
{ // find first matching _Val
for (; _First != _Last; ++_First)
if (*_First == _Val)
break;
return (_First);
}
template<class _InIt, class _Pr>
inline
_InIt find_if(_InIt _First, _InIt _Last, _Pr _Pred)
{ // find first satisfying _Pred
for (; _First != _Last; ++_First)
if (_Pred(*_First))
break;
return (_First);
}
template<class _InIt, class _Ty>
inline
bool exists(_InIt _First, _InIt _Last, const _Ty& _Val)
{
return find(_First, _Last, _Val) != _Last;
}
template<class _InIt, class _Pr>
inline
bool exists_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
return find_if(_First, _Last, _Pred) != _Last;
}
template<class _InIt, class _Ty>
inline
uintptr_t count(_InIt _First, _InIt _Last, const _Ty& _Val)
{
uintptr_t _Ret = 0;
for (; _First != _Last; _First++)
if (*_First == _Val)
++_Ret;
return _Ret;
}
template<class _InIt, class _Pr>
inline
uintptr_t count_if(_InIt _First, _InIt _Last, _Pr _Pred)
{
uintptr_t _Ret = 0;
for (; _First != _Last; _First++)
if (_Pred(*_First))
++_Ret;
return _Ret;
}
// Forward declaration, each collection requires specialization
template<class _FwdIt, class _Ty>
inline
_FwdIt remove(_FwdIt _First, _FwdIt _Last, const _Ty& _Val);
} // namespace std
} // namespace rh
#if 0
// -----------------------------------------------------------------
// Holding place for unused-but-possibly-useful-in-the-future code.
// -------------------------------------------------
// This belongs in type_traits.hpp
//
// is_pointer::value is true if the type is a pointer, false otherwise
//
template <typename T> struct is_pointer : public false_type {};
template <typename T> struct is_pointer<T *> : public true_type {};
//
// Remove pointer from type, if it has one. Use remove_pointer::type
// Further specialized in daccess.h
//
template <typename T> struct remove_pointer { typedef T type; };
template <typename T> struct remove_pointer<T *> { typedef T type; };
// -------------------------------------------------
// This belongs in daccess.h
namespace type_traits
{
//
// is_pointer::value is true if the type is a pointer, false otherwise
// specialized from type_traits.hpp
//
template <typename T> struct is_pointer<typename __DPtr<T> > : public type_traits::true_type {};
//
// remove_pointer::type is T with one less pointer qualification, if it had one.
// specialized from type_traits.hpp
//
template <typename T> struct remove_pointer<typename __DPtr<T> > { typedef T type; };
} // type_traits
namespace dac
{
//
// is_dptr::value is true if T is a __DPtr, false otherwise.
// This is a partial specialization case for the positive case.
//
//template <typename T> struct is_dptr<typename __DPtr<T> > : public type_traits::true_type {};
}
#endif
#endif
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/IL_Conformance/Old/Conformance_Base/mul_ovf_u2.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="mul_ovf_u2.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="mul_ovf_u2.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/coreclr/tools/aot/crossgen2/crossgen2_crossarch.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<CrossHostArch>$(BuildArchitecture)</CrossHostArch>
<OutputPath>$(RuntimeBinDir)/$(CrossHostArch)/crossgen2</OutputPath>
<UseAppHost>false</UseAppHost>
</PropertyGroup>
<Import Project="crossgen2.props" />
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<CrossHostArch>$(BuildArchitecture)</CrossHostArch>
<OutputPath>$(RuntimeBinDir)/$(CrossHostArch)/crossgen2</OutputPath>
<UseAppHost>false</UseAppHost>
</PropertyGroup>
<Import Project="crossgen2.props" />
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/HardwareIntrinsics/General/Vector128/BitwiseAnd.Double.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void BitwiseAndDouble()
{
var test = new VectorBinaryOpTest__BitwiseAndDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__BitwiseAndDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__BitwiseAndDouble testClass)
{
var result = Vector128.BitwiseAnd(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__BitwiseAndDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public VectorBinaryOpTest__BitwiseAndDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.BitwiseAnd(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseAnd), new Type[] {
typeof(Vector128<Double>),
typeof(Vector128<Double>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseAnd), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Double));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.BitwiseAnd(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Vector128.BitwiseAnd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__BitwiseAndDouble();
var result = Vector128.BitwiseAnd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.BitwiseAnd(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.BitwiseAnd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != (BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != (BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.BitwiseAnd)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void BitwiseAndDouble()
{
var test = new VectorBinaryOpTest__BitwiseAndDouble();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__BitwiseAndDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(VectorBinaryOpTest__BitwiseAndDouble testClass)
{
var result = Vector128.BitwiseAnd(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static VectorBinaryOpTest__BitwiseAndDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public VectorBinaryOpTest__BitwiseAndDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.BitwiseAnd(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseAnd), new Type[] {
typeof(Vector128<Double>),
typeof(Vector128<Double>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseAnd), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Double));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.BitwiseAnd(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Vector128.BitwiseAnd(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__BitwiseAndDouble();
var result = Vector128.BitwiseAnd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.BitwiseAnd(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.BitwiseAnd(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != (BitConverter.DoubleToInt64Bits(left[0]) & BitConverter.DoubleToInt64Bits(right[0])))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != (BitConverter.DoubleToInt64Bits(left[i]) & BitConverter.DoubleToInt64Bits(right[i])))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.BitwiseAnd)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/Regression/VS-ia64-JIT/M00/b81763/b81763.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildProjectName).il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/libraries/System.IO.UnmanagedMemoryStream/System.IO.UnmanagedMemoryStream.sln
|
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "..\..\coreclr\System.Private.CoreLib\System.Private.CoreLib.csproj", "{074D8726-9CC3-43B5-9D28-1AD33A6100F7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreamConformanceTests", "..\Common\tests\StreamConformanceTests\StreamConformanceTests.csproj", "{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream", "ref\System.IO.UnmanagedMemoryStream.csproj", "{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream", "src\System.IO.UnmanagedMemoryStream.csproj", "{658B1534-3B9E-4108-9AFE-161562723E9D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream.Tests", "tests\System.IO.UnmanagedMemoryStream.Tests.csproj", "{D14DC8D4-F45E-412D-AE98-CA07F900347B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{5CB1579E-E830-4812-A7F5-0E33E1847BF6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{00BCBF77-11E9-45BC-A663-D1904B92C0E9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A8D21009-1410-4367-8616-2075882003FF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{7BB3C727-EA87-416E-84DD-34ADD5540067}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{F0F69F17-CFD8-4C03-B86D-C95F0F8D78EC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
Checked|Any CPU = Checked|Any CPU
Checked|x64 = Checked|x64
Checked|x86 = Checked|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|Any CPU.ActiveCfg = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|Any CPU.Build.0 = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x64.ActiveCfg = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x64.Build.0 = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x86.ActiveCfg = Debug|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x86.Build.0 = Debug|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|Any CPU.ActiveCfg = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|Any CPU.Build.0 = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x64.ActiveCfg = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x64.Build.0 = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x86.ActiveCfg = Release|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x86.Build.0 = Release|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|Any CPU.ActiveCfg = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|Any CPU.Build.0 = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x64.ActiveCfg = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x64.Build.0 = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x86.ActiveCfg = Checked|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x86.Build.0 = Checked|x86
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x64.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x64.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x86.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x86.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|Any CPU.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x64.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x64.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x86.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x86.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|Any CPU.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x64.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x64.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x86.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x86.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x64.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x64.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x86.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x86.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|Any CPU.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x64.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x64.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x86.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x86.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|Any CPU.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x64.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x64.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x86.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x86.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x64.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x64.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x86.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x86.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|Any CPU.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x64.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x64.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x86.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x86.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|Any CPU.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x64.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x64.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x86.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x86.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x64.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x64.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x86.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x86.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|Any CPU.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x64.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x64.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x86.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x86.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|Any CPU.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x64.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x64.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x86.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x86.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x64.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x64.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x86.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x86.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|Any CPU.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x64.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x64.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x86.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x86.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|Any CPU.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x64.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x64.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x86.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x86.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x64.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x64.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x86.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x86.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|Any CPU.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x64.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x64.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x86.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x86.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|Any CPU.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x64.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x64.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x86.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x86.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x64.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x64.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x86.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x86.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|Any CPU.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x64.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x64.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x86.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x86.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|Any CPU.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x64.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x64.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x86.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x86.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x64.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x64.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x86.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x86.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|Any CPU.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x64.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x64.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x86.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x86.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|Any CPU.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x64.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x64.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x86.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x86.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{074D8726-9CC3-43B5-9D28-1AD33A6100F7} = {A8D21009-1410-4367-8616-2075882003FF}
{658B1534-3B9E-4108-9AFE-161562723E9D} = {A8D21009-1410-4367-8616-2075882003FF}
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{D14DC8D4-F45E-412D-AE98-CA07F900347B} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F} = {F0F69F17-CFD8-4C03-B86D-C95F0F8D78EC}
{5CB1579E-E830-4812-A7F5-0E33E1847BF6} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
{00BCBF77-11E9-45BC-A663-D1904B92C0E9} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {819EC888-7F7A-4501-AC44-653366DC0DB8}
EndGlobalSection
EndGlobal
|
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "..\..\coreclr\System.Private.CoreLib\System.Private.CoreLib.csproj", "{074D8726-9CC3-43B5-9D28-1AD33A6100F7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StreamConformanceTests", "..\Common\tests\StreamConformanceTests\StreamConformanceTests.csproj", "{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream", "ref\System.IO.UnmanagedMemoryStream.csproj", "{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream", "src\System.IO.UnmanagedMemoryStream.csproj", "{658B1534-3B9E-4108-9AFE-161562723E9D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.IO.UnmanagedMemoryStream.Tests", "tests\System.IO.UnmanagedMemoryStream.Tests.csproj", "{D14DC8D4-F45E-412D-AE98-CA07F900347B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{5CB1579E-E830-4812-A7F5-0E33E1847BF6}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{00BCBF77-11E9-45BC-A663-D1904B92C0E9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A8D21009-1410-4367-8616-2075882003FF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{7BB3C727-EA87-416E-84DD-34ADD5540067}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{F0F69F17-CFD8-4C03-B86D-C95F0F8D78EC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
Checked|Any CPU = Checked|Any CPU
Checked|x64 = Checked|x64
Checked|x86 = Checked|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|Any CPU.ActiveCfg = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|Any CPU.Build.0 = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x64.ActiveCfg = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x64.Build.0 = Debug|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x86.ActiveCfg = Debug|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Debug|x86.Build.0 = Debug|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|Any CPU.ActiveCfg = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|Any CPU.Build.0 = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x64.ActiveCfg = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x64.Build.0 = Release|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x86.ActiveCfg = Release|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Release|x86.Build.0 = Release|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|Any CPU.ActiveCfg = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|Any CPU.Build.0 = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x64.ActiveCfg = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x64.Build.0 = Checked|x64
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x86.ActiveCfg = Checked|x86
{074D8726-9CC3-43B5-9D28-1AD33A6100F7}.Checked|x86.Build.0 = Checked|x86
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x64.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x64.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x86.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Debug|x86.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|Any CPU.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x64.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x64.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x86.ActiveCfg = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Release|x86.Build.0 = Release|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|Any CPU.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x64.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x64.Build.0 = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x86.ActiveCfg = Debug|Any CPU
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE}.Checked|x86.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x64.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x64.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x86.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Debug|x86.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|Any CPU.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x64.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x64.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x86.ActiveCfg = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Release|x86.Build.0 = Release|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|Any CPU.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x64.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x64.Build.0 = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x86.ActiveCfg = Debug|Any CPU
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E}.Checked|x86.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x64.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x64.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x86.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Debug|x86.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|Any CPU.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x64.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x64.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x86.ActiveCfg = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Release|x86.Build.0 = Release|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|Any CPU.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x64.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x64.Build.0 = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x86.ActiveCfg = Debug|Any CPU
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F}.Checked|x86.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x64.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x64.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x86.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Debug|x86.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|Any CPU.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x64.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x64.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x86.ActiveCfg = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Release|x86.Build.0 = Release|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|Any CPU.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x64.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x64.Build.0 = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x86.ActiveCfg = Debug|Any CPU
{658B1534-3B9E-4108-9AFE-161562723E9D}.Checked|x86.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x64.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x64.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x86.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Debug|x86.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|Any CPU.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x64.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x64.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x86.ActiveCfg = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Release|x86.Build.0 = Release|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|Any CPU.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x64.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x64.Build.0 = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x86.ActiveCfg = Debug|Any CPU
{D14DC8D4-F45E-412D-AE98-CA07F900347B}.Checked|x86.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x64.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x64.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x86.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Debug|x86.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|Any CPU.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x64.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x64.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x86.ActiveCfg = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Release|x86.Build.0 = Release|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|Any CPU.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x64.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x64.Build.0 = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x86.ActiveCfg = Debug|Any CPU
{5CB1579E-E830-4812-A7F5-0E33E1847BF6}.Checked|x86.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x64.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x64.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x86.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Debug|x86.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|Any CPU.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x64.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x64.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x86.ActiveCfg = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Release|x86.Build.0 = Release|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|Any CPU.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x64.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x64.Build.0 = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x86.ActiveCfg = Debug|Any CPU
{00BCBF77-11E9-45BC-A663-D1904B92C0E9}.Checked|x86.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x64.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x64.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x86.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Debug|x86.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|Any CPU.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x64.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x64.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x86.ActiveCfg = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Release|x86.Build.0 = Release|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|Any CPU.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|Any CPU.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x64.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x64.Build.0 = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x86.ActiveCfg = Debug|Any CPU
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E}.Checked|x86.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{074D8726-9CC3-43B5-9D28-1AD33A6100F7} = {A8D21009-1410-4367-8616-2075882003FF}
{658B1534-3B9E-4108-9AFE-161562723E9D} = {A8D21009-1410-4367-8616-2075882003FF}
{9963A1DA-8EBD-47EF-8BF2-7B6444BE6FCE} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{7DC8F0E9-5D6C-47F7-AE83-9AB1180AF51E} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{D14DC8D4-F45E-412D-AE98-CA07F900347B} = {7BB3C727-EA87-416E-84DD-34ADD5540067}
{9ED000E5-2F8D-4B49-85BD-70E34AB2A26F} = {F0F69F17-CFD8-4C03-B86D-C95F0F8D78EC}
{5CB1579E-E830-4812-A7F5-0E33E1847BF6} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
{00BCBF77-11E9-45BC-A663-D1904B92C0E9} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
{D6653CCB-7EF2-4B4F-86D5-0FC47FDFBC9E} = {8A43D0EF-B87B-4046-963C-3DFA9ADA62FB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {819EC888-7F7A-4501-AC44-653366DC0DB8}
EndGlobalSection
EndGlobal
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1040/Generated1040.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated1040.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated1040.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest117/Generated117.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated117.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated117.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IAsyncStateMachineBox.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
/// <summary>
/// An interface implemented by all <see cref="AsyncTaskMethodBuilder{TResult}.AsyncStateMachineBox{TStateMachine}"/> instances, regardless of generics.
/// </summary>
internal interface IAsyncStateMachineBox
{
/// <summary>Move the state machine forward.</summary>
void MoveNext();
/// <summary>
/// Gets an action for moving forward the contained state machine.
/// This will lazily-allocate the delegate as needed.
/// </summary>
Action MoveNextAction { get; }
/// <summary>Gets the state machine as a boxed object. This should only be used for debugging purposes.</summary>
IAsyncStateMachine GetStateMachineObject();
/// <summary>Clears the state of the box.</summary>
void ClearStateUponCompletion();
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.CompilerServices
{
/// <summary>
/// An interface implemented by all <see cref="AsyncTaskMethodBuilder{TResult}.AsyncStateMachineBox{TStateMachine}"/> instances, regardless of generics.
/// </summary>
internal interface IAsyncStateMachineBox
{
/// <summary>Move the state machine forward.</summary>
void MoveNext();
/// <summary>
/// Gets an action for moving forward the contained state machine.
/// This will lazily-allocate the delegate as needed.
/// </summary>
Action MoveNextAction { get; }
/// <summary>Gets the state machine as a boxed object. This should only be used for debugging purposes.</summary>
IAsyncStateMachine GetStateMachineObject();
/// <summary>Clears the state of the box.</summary>
void ClearStateUponCompletion();
}
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest30/Generated30.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated30.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated30.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/Methodical/Invoke/SEH/catchfinally_tail_d.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="catchfinally_tail.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="catchfinally_tail.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/Extract.Int32.1.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractInt321()
{
var test = new ExtractScalarTest__ExtractInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractScalarTest__ExtractInt321
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ExtractScalarTest__ExtractInt321 testClass)
{
var result = Sse41.Extract(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ExtractScalarTest__ExtractInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ExtractScalarTest__ExtractInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Extract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Extract(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Extract(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Extract(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractScalarTest__ExtractInt321();
var result = Sse41.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Extract(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((result[0] != firstOp[1]))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtractInt321()
{
var test = new ExtractScalarTest__ExtractInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ExtractScalarTest__ExtractInt321
{
private struct TestStruct
{
public Vector128<Int32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(ExtractScalarTest__ExtractInt321 testClass)
{
var result = Sse41.Extract(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar;
private Vector128<Int32> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable;
static ExtractScalarTest__ExtractInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public ExtractScalarTest__ExtractInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Extract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Extract(
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Extract(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Extract(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr);
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr));
var result = Sse41.Extract(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractScalarTest__ExtractInt321();
var result = Sse41.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Extract(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Extract(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray = new Int32[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((result[0] != firstOp[1]))
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/Directed/PREFIX/unaligned/2/initblk.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="initblk.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="initblk.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/CharSet.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.InteropServices
{
// Use this in P/Invoke function prototypes to specify
// which character set to use when marshalling Strings.
// Using Ansi will marshal the strings as 1 byte char*'s.
// Using Unicode will marshal the strings as 2 byte wchar*'s.
// Generally you probably want to use Auto, which does the
// right thing 99% of the time.
public enum CharSet
{
None = 1, // User didn't specify how to marshal strings.
Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars.
Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars.
Auto = 4, // Marshal Strings in the right way for the target system.
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Runtime.InteropServices
{
// Use this in P/Invoke function prototypes to specify
// which character set to use when marshalling Strings.
// Using Ansi will marshal the strings as 1 byte char*'s.
// Using Unicode will marshal the strings as 2 byte wchar*'s.
// Generally you probably want to use Auto, which does the
// right thing 99% of the time.
public enum CharSet
{
None = 1, // User didn't specify how to marshal strings.
Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars.
Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars.
Auto = 4, // Marshal Strings in the right way for the target system.
}
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/coreclr/debug/di/process.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// File: process.cpp
//
//
//*****************************************************************************
#include "stdafx.h"
#include "primitives.h"
#include "safewrap.h"
#include "check.h"
#ifndef SM_REMOTESESSION
#define SM_REMOTESESSION 0x1000
#endif
#include "corpriv.h"
#include "corexcep.h"
#include "../../dlls/mscorrc/resource.h"
#include <limits.h>
#include <sstring.h>
// @dbgtodo shim: process has some private hooks into the shim.
#include "shimpriv.h"
#include "metadataexports.h"
#include "readonlydatatargetfacade.h"
#include "metahost.h"
// Keep this around for retail debugging. It's very very useful because
// it's global state that we can always find, regardless of how many locals the compiler
// optimizes away ;)
struct RSDebuggingInfo;
extern RSDebuggingInfo * g_pRSDebuggingInfo;
//---------------------------------------------------------------------------------------
//
// OpenVirtualProcessImpl method called by the shim to get an ICorDebugProcess4 instance
//
// Arguments:
// clrInstanceId - target pointer identifying which CLR in the Target to debug.
// pDataTarget - data target abstraction.
// hDacModule - the handle of the appropriate DAC dll for this runtime
// riid - interface ID to query for.
// ppProcessOut - new object for target, interface ID matches riid.
// ppFlagsOut - currently only has 1 bit to indicate whether or not this runtime
// instance will send a managed event after attach
//
// Return Value:
// S_OK on success. Else failure
//
// Assumptions:
//
// Notes:
// The outgoing process object can be cleaned up by calling Detach (which
// will reset the Attach bit.)
// @dbgtodo attach-bit: need to determine fate of attach bit.
//
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcessImpl(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
CLR_DEBUGGING_VERSION * pMaxDebuggerSupportedVersion,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
HRESULT hr = S_OK;
RSExtSmartPtr<CordbProcess> pProcess;
PUBLIC_API_ENTRY(NULL);
EX_TRY
{
if ( (pDataTarget == NULL) || (clrInstanceId == 0) || (pMaxDebuggerSupportedVersion == NULL) ||
((pFlagsOut == NULL) && (ppInstance == NULL))
)
{
ThrowHR(E_INVALIDARG);
}
// We consider the top 8 bits of the struct version to be the only part that represents
// a breaking change. This gives us some freedom in the future to have the debugger
// opt into getting more data.
const WORD kMajorMask = 0xff00;
const WORD kMaxStructMajor = 0;
if ((pMaxDebuggerSupportedVersion->wStructVersion & kMajorMask) > kMaxStructMajor)
{
// Don't know how to interpret the version structure
ThrowHR(CORDBG_E_UNSUPPORTED_VERSION_STRUCT);
}
// This process object is intended to be used for the V3 pipeline, and so
// much of the process from V2 is not being used. For example,
// - there is no ShimProcess object
// - there is no w32et thread (all threads are effectively an event thread)
// - the stop state is 'live', which corresponds to CordbProcess not knowing what
// its stop state really is (because that is now controlled by the shim).
ProcessDescriptor pd = ProcessDescriptor::CreateUninitialized();
IfFailThrow(CordbProcess::OpenVirtualProcess(
clrInstanceId,
pDataTarget, // takes a reference
hDacModule,
NULL, // Cordb
&pd, // 0 for V3 cases (pShim == NULL).
NULL, // no Shim in V3 cases
&pProcess));
// CordbProcess::OpenVirtualProcess already did the external addref to pProcess.
// Since pProcess is a smart ptr, it will external release in this function.
// Living reference will be the one from the QI.
// get the managed debug event pending flag
if(pFlagsOut != NULL)
{
hr = pProcess->GetAttachStateFlags(pFlagsOut);
if(FAILED(hr))
{
ThrowHR(hr);
}
}
//
// Check to make sure the debugger supports debugging this version
// Note that it's important that we still store the flags (above) in this case
//
if (!CordbProcess::IsCompatibleWith(pMaxDebuggerSupportedVersion->wMajor))
{
// Not compatible - don't keep the process instance, and return this specific error-code
ThrowHR(CORDBG_E_UNSUPPORTED_FORWARD_COMPAT);
}
//
// Now Query for the requested interface
//
if(ppInstance != NULL)
{
IfFailThrow(pProcess->QueryInterface(riid, reinterpret_cast<void**> (ppInstance)));
}
// if you have to add code here that could fail make sure ppInstance gets released and NULL'ed at exit
}
EX_CATCH_HRESULT(hr);
if((FAILED(hr) || ppInstance == NULL) && pProcess != NULL)
{
// The process has a strong reference to itself which is only released by neutering it.
// Since we aren't handing out the ref then we need to clean it up
_ASSERTE(ppInstance == NULL || *ppInstance == NULL);
pProcess->Neuter();
}
return hr;
};
//---------------------------------------------------------------------------------------
//
// OpenVirtualProcessImpl2 method called by the dbgshim to get an ICorDebugProcess4 instance
//
// Arguments:
// clrInstanceId - target pointer identifying which CLR in the Target to debug.
// pDataTarget - data target abstraction.
// pDacModulePath - the module path of the appropriate DAC dll for this runtime
// riid - interface ID to query for.
// ppProcessOut - new object for target, interface ID matches riid.
// ppFlagsOut - currently only has 1 bit to indicate whether or not this runtime
// instance will send a managed event after attach
//
// Return Value:
// S_OK on success. Else failure
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcessImpl2(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
LPCWSTR pDacModulePath,
CLR_DEBUGGING_VERSION * pMaxDebuggerSupportedVersion,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
HMODULE hDac = LoadLibraryW(pDacModulePath);
if (hDac == NULL)
{
return HRESULT_FROM_WIN32(GetLastError());
}
return OpenVirtualProcessImpl(clrInstanceId, pDataTarget, hDac, pMaxDebuggerSupportedVersion, riid, ppInstance, pFlagsOut);
}
//---------------------------------------------------------------------------------------
// DEPRECATED - use OpenVirtualProcessImpl
// OpenVirtualProcess method used by the shim in CLR v4 Beta1
// We'd like a beta1 shim/VS to still be able to open dumps using a CLR v4 Beta2+ mscordbi.dll,
// so we'll leave this in place (at least until after Beta2 is in wide use).
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcess2(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
CLR_DEBUGGING_VERSION maxVersion = {0};
maxVersion.wMajor = 4;
return OpenVirtualProcessImpl(clrInstanceId, pDataTarget, hDacModule, &maxVersion, riid, ppInstance, pFlagsOut);
}
//---------------------------------------------------------------------------------------
// DEPRECATED - use OpenVirtualProcessImpl
// Public OpenVirtualProcess method to get an ICorDebugProcess4 instance
// Used directly in CLR v4 pre Beta1 - can probably be safely removed now
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcess(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
REFIID riid,
IUnknown ** ppInstance)
{
return OpenVirtualProcess2(clrInstanceId, pDataTarget, NULL, riid, ppInstance, NULL);
};
//-----------------------------------------------------------------------------
// Most Hresults to Unrecoverable error indicate an internal error
// in the Right-Side.
// However, a few are legal (eg, "could actually happen in a retail scenario and
// not indicate an issue in mscorbi"). Track that here.
//-----------------------------------------------------------------------------
bool IsLegalFatalError(HRESULT hr)
{
return
(hr == CORDBG_E_INCOMPATIBLE_PROTOCOL) ||
(hr == CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS) ||
(hr == CORDBG_E_UNCOMPATIBLE_PLATFORMS) ||
(hr == CORDBG_E_MISMATCHED_CORWKS_AND_DACWKS_DLLS) ||
// This should only happen in the case of a security attack on us.
(hr == E_ACCESSDENIED) ||
(hr == E_FAIL);
}
//-----------------------------------------------------------------------------
// Safe wait. Use this anytime we're waiting on:
// - an event signaled by the helper thread.
// - something signaled by a thread that holds the process lock.
// Note that we must preserve GetLastError() semantics.
//-----------------------------------------------------------------------------
inline DWORD SafeWaitForSingleObject(CordbProcess * p, HANDLE h, DWORD dwTimeout)
{
// Can't hold process lock while blocking
_ASSERTE(!p->ThreadHoldsProcessLock());
return ::WaitForSingleObject(h, dwTimeout);
}
#define CORDB_WAIT_TIMEOUT 360000 // milliseconds
//---------------------------------------------------------------------------------------
//
// Get the timeout value used in waits.
//
// Return Value:
// Number of milliseconds to waite or possible INFINITE (-1).
//
//
// Notes:
// Uses registry values for fine tuning.
//
// static
static inline DWORD CordbGetWaitTimeout()
{
#ifdef _DEBUG
// 0 = Wait forever
// 1 = Wait for CORDB_WAIT_TIMEOUT
// n = Wait for n milliseconds
static ConfigDWORD cordbWaitTimeout;
DWORD dwTimeoutVal = cordbWaitTimeout.val(CLRConfig::INTERNAL_DbgWaitTimeout);
if (dwTimeoutVal == 0)
return DWORD(-1);
else if (dwTimeoutVal != 1)
return dwTimeoutVal;
else
#endif
{
return CORDB_WAIT_TIMEOUT;
}
}
//----------------------------------------------------------------------------
// Implementation of IDacDbiInterface::IMetaDataLookup.
// lookup Internal Metadata Importer keyed by PEAssembly
// isILMetaDataForNGENImage is true iff the IMDInternalImport returned represents a pointer to
// metadata from an IL image when the module was an ngen'ed image.
IMDInternalImport * CordbProcess::LookupMetaData(VMPTR_PEAssembly vmPEAssembly, bool &isILMetaDataForNGENImage)
{
INTERNAL_DAC_CALLBACK(this);
HASHFIND hashFindAppDomain;
HASHFIND hashFindModule;
IMDInternalImport * pMDII = NULL;
isILMetaDataForNGENImage = false;
// Check to see if one of the cached modules has the metadata we need
// If not we will do a more exhaustive search below
for (CordbAppDomain * pAppDomain = m_appDomains.FindFirst(&hashFindAppDomain);
pAppDomain != NULL;
pAppDomain = m_appDomains.FindNext(&hashFindAppDomain))
{
for (CordbModule * pModule = pAppDomain->m_modules.FindFirst(&hashFindModule);
pModule != NULL;
pModule = pAppDomain->m_modules.FindNext(&hashFindModule))
{
if (pModule->GetPEFile() == vmPEAssembly)
{
pMDII = NULL;
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = pModule->GetInternalMD();
);
if(pMDII != NULL)
return pMDII;
}
}
}
// Cache didn't have it... time to search harder
PrepopulateAppDomainsOrThrow();
// There may be perf issues here. The DAC may make a lot of metadata requests, and so
// this may be an area for potential perf optimizations if we find things running slow.
// enumerate through all Modules
for (CordbAppDomain * pAppDomain = m_appDomains.FindFirst(&hashFindAppDomain);
pAppDomain != NULL;
pAppDomain = m_appDomains.FindNext(&hashFindAppDomain))
{
pAppDomain->PrepopulateModules();
for (CordbModule * pModule = pAppDomain->m_modules.FindFirst(&hashFindModule);
pModule != NULL;
pModule = pAppDomain->m_modules.FindNext(&hashFindModule))
{
if (pModule->GetPEFile() == vmPEAssembly)
{
pMDII = NULL;
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = pModule->GetInternalMD();
);
if ( pMDII == NULL)
{
// If we couldn't get metadata from the CordbModule, then we need to ask the
// debugger if it can find the metadata elsewhere.
// If this was live debugging, we should have just gotten the memory contents.
// Thus this code is for dump debugging, when you don't have the metadata in the dump.
pMDII = LookupMetaDataFromDebugger(vmPEAssembly, isILMetaDataForNGENImage, pModule);
}
return pMDII;
}
}
}
return NULL;
}
IMDInternalImport * CordbProcess::LookupMetaDataFromDebugger(
VMPTR_PEAssembly vmPEAssembly,
bool &isILMetaDataForNGENImage,
CordbModule * pModule)
{
DWORD dwImageTimeStamp = 0;
DWORD dwImageSize = 0;
bool isNGEN = false;
StringCopyHolder filePath;
IMDInternalImport * pMDII = NULL;
// First, see if the debugger can locate the exact metadata we want.
if (this->GetDAC()->GetMetaDataFileInfoFromPEFile(vmPEAssembly, dwImageTimeStamp, dwImageSize, isNGEN, &filePath))
{
_ASSERTE(filePath.IsSet());
// Since we track modules by their IL images, that presents a little bit of oddness here. The correct
// thing to do is preferentially load the NI content.
// We don't discriminate between timestamps & sizes becuase CLRv4 deterministic NGEN guarantees that the
// IL image and NGEN image have the same timestamp and size. Should that guarantee change, this code
// will be horribly broken.
// If we happen to have an NI file path, use it instead.
const WCHAR * pwszFilePath = pModule->GetNGenImagePath();
if (pwszFilePath)
{
// Force the issue, regardless of the older codepath's opinion.
isNGEN = true;
}
else
{
pwszFilePath = (WCHAR *)filePath;
}
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = LookupMetaDataFromDebuggerForSingleFile(pModule, pwszFilePath, dwImageTimeStamp, dwImageSize);
);
// If it's an ngen'ed image and the debugger couldn't find it, we can use the metadata from
// the corresponding IL image if the debugger can locate it.
filePath.Clear();
if ((pMDII == NULL) &&
(isNGEN) &&
(this->GetDAC()->GetILImageInfoFromNgenPEFile(vmPEAssembly, dwImageTimeStamp, dwImageSize, &filePath)))
{
_ASSERTE(filePath.IsSet());
WCHAR *mutableFilePath = (WCHAR *)filePath;
size_t pathLen = wcslen(mutableFilePath);
const WCHAR *nidll = W(".ni.dll");
const WCHAR *niexe = W(".ni.exe");
const size_t dllLen = wcslen(nidll); // used for ni.exe as well
if (pathLen > dllLen && _wcsicmp(mutableFilePath+pathLen-dllLen, nidll) == 0)
{
wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".dll"));
}
else if (pathLen > dllLen && _wcsicmp(mutableFilePath+pathLen-dllLen, niexe) == 0)
{
wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".exe"));
}
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = LookupMetaDataFromDebuggerForSingleFile(pModule, mutableFilePath, dwImageTimeStamp, dwImageSize);
);
if (pMDII != NULL)
{
isILMetaDataForNGENImage = true;
}
}
}
return pMDII;
}
// We do not know if the image being sent to us is an IL image or ngen image.
// CordbProcess::LookupMetaDataFromDebugger() has this knowledge when it looks up the file to hand off
// to this function.
// DacDbiInterfaceImpl::GetMDImport() has this knowledge in the isNGEN flag.
// The CLR v2 code that windbg used made a distinction whether the metadata came from
// the exact binary or not (i.e. were we getting metadata from the IL image and using
// it against the ngen image?) but that information was never used and so not brought forward.
// It would probably be more interesting generally to track whether the debugger gives us back
// a file that bears some relationship to the file we asked for, which would catch the NI/IL case
// as well.
IMDInternalImport * CordbProcess::LookupMetaDataFromDebuggerForSingleFile(
CordbModule * pModule,
LPCWSTR pwszFilePath,
DWORD dwTimeStamp,
DWORD dwSize)
{
INTERNAL_DAC_CALLBACK(this);
ULONG32 cchLocalImagePath = MAX_LONGPATH;
ULONG32 cchLocalImagePathRequired;
NewArrayHolder<WCHAR> pwszLocalFilePath = NULL;
IMDInternalImport * pMDII = NULL;
const HRESULT E_NSF_BUFFER = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
HRESULT hr = E_NSF_BUFFER;
for(unsigned i=0; i<2 && hr == E_NSF_BUFFER; i++)
{
if (pwszLocalFilePath != NULL)
pwszLocalFilePath.Release();
if (NULL == (pwszLocalFilePath = new (nothrow) WCHAR[cchLocalImagePath+1]))
ThrowHR(E_OUTOFMEMORY);
cchLocalImagePathRequired = 0;
hr = m_pMetaDataLocator->GetMetaData(pwszFilePath,
dwTimeStamp,
dwSize,
cchLocalImagePath,
&cchLocalImagePathRequired,
pwszLocalFilePath);
pwszLocalFilePath[cchLocalImagePath] = W('\0');
cchLocalImagePath = cchLocalImagePathRequired;
}
if (SUCCEEDED(hr))
{
hr = pModule->InitPublicMetaDataFromFile(pwszLocalFilePath, ofReadOnly, false);
if (SUCCEEDED(hr))
{
// While we're successfully returning a metadata reader, remember that there's
// absolutely no guarantee this metadata is an exact match for the vmPEAssembly.
// The debugger could literally send us back a path to any managed file with
// metadata content that is readable and we'll 'succeed'.
// For now, this is by-design. A debugger should be allowed to decide if it wants
// to take a risk by returning 'mostly matching' metadata to see if debugging is
// possible in the absence of a true match.
pMDII = pModule->GetInternalMD();
}
}
return pMDII;
}
//---------------------------------------------------------------------------------------
//
// Implement IDacDbiInterface::IAllocator::Alloc
// Expected to throws on error.
//
// Arguments:
// lenBytes - size of the byte array to allocate
//
// Return Value:
// Return the newly allocated byte array, or throw on OOM
//
// Notes:
// Since this function is a callback from DAC, it must not take the process lock.
// If it does, we may deadlock between the DD lock and the process lock.
// If we really need to take the process lock for whatever reason, we must take it in the DBI functions
// which call the DAC API that ends up calling this function.
// See code:InternalDacCallbackHolder for more information.
//
void * CordbProcess::Alloc(SIZE_T lenBytes)
{
return new BYTE[lenBytes]; // throws
}
//---------------------------------------------------------------------------------------
//
// Implements IDacDbiInterface::IAllocator::Free
//
// Arguments:
// p - pointer to the memory to be released
//
// Notes:
// Since this function is a callback from DAC, it must not take the process lock.
// If it does, we may deadlock between the DD lock and the process lock.
// If we really need to take the process lock for whatever reason, we must take it in the DBI functions
// which call the DAC API that ends up calling this function.
// See code:InternalDacCallbackHolder for more information.
//
void CordbProcess::Free(void * p)
{
// This shouldn't throw.
delete [] ((BYTE *) p);
}
//---------------------------------------------------------------------------------------
//
// #DBIVersionChecking
//
// There are a few checks we need to do to make sure we are using the matching DBI and DAC for a particular
// version of the runtime.
//
// 1. Runtime vs. DBI
// - Desktop
// This is done by making sure that the CorDebugInterfaceVersion passed to code:CreateCordbObject is
// compatible with the version of the DBI.
//
// - Windows CoreCLR
// This is done by dbgshim.dll. It checks whether the runtime DLL and the DBI DLL have the same
// product version. See CreateDebuggingInterfaceForVersion() in dbgshim.cpp.
//
// - Remote transport (Mac CoreCLR + CoreSystem CoreCLR)
// Since there is no dbgshim.dll for a remote CoreCLR, we have to do this check in some other place.
// We do this in code:CordbProcess::CreateDacDbiInterface, by calling
// code:DacDbiInterfaceImpl::CheckDbiVersion right after we have created the DDMarshal.
// The IDacDbiInterface implementation on remote device checks the product version of the device
// coreclr by:
// mac - looking at the Info.plist file in the CoreCLR bundle.
// CoreSystem - this check is skipped at the moment, but should be implemented if we release it
//
// The one twist here is that the DBI needs to communicate with the IDacDbiInterface
// implementation on the device BEFORE it can verify the product versions. This means that we need to
// have one IDacDbiInterface API which is consistent across all versions of the IDacDbiInterface.
// This puts two constraints on CheckDbiVersion():
//
// 1. It has to be the first API on the IDacDbiInterface.
// - Otherwise, a wrong version of the DBI may end up calling a different API on the
// IDacDbiInterface and getting random results. (Really what matters is that it is
// protocol message id 0, at present the source code position implies the message id)
//
// 2. Its parameters cannot change.
// - Otherwise, we may run into random errors when we marshal/unmarshal the arguments for the
// call to CheckDbiVersion(). Debugging will still fail, but we won't get the
// version mismatch error. (Again, the protocol is what ultimately matters)
// - To mitigate the impact of this constraint, we use the code:DbiVersion structure.
// In addition to the DBI version, it also contains a format number (in case we decide to
// check something else in the future), a breaking change number so that we can force
// breaking changes between a DBI and a DAC, and space reserved for future use.
//
// 2. DBI vs. DAC
// - Desktop and Windows CoreCLR (old architecture)
// No verification is done. There is a transitive implication that if DBI matches runtime and DAC matches
// runtime then DBI matches DAC. Technically because the DBI only matches runtime on major version number
// runtime and DAC could be from different builds. However because we service all three binaries together
// and DBI always loads the DAC that is sitting in the same directory DAC and DBI generally get tight
// version coupling. A user with admin privleges could put different builds together and no version check
// would ever fail though.
//
// - Desktop and Windows CoreCLR (new architecture)
// No verification is done. Similar to above its implied that if DBI matches runtime and runtime matches
// DAC then DBI matches DAC. The only difference is that here both the DBI and DAC are provided by the
// debugger. We provide timestamp and filesize for both binaries which are relatively strongly bound hints,
// but there is no enforcement on the returned binaries beyond the runtime compat checking.
//
// - Remote transport (Mac CoreCLR and CoreSystem CoreCLR)
// Because the transport exists between DBI and DAC it becomes much more important to do a versioning check
//
// Mac - currently does a tightly bound version check between DBI and the runtime (CheckDbiVersion() above),
// which transitively gives a tightly bound check to DAC. In same function there is also a check that is
// logically a DAC DBI protocol check, verifying that the m_dwProtocolBreakingChangeCounter of DbiVersion
// matches. However this check should be weaker than the build version check and doesn't add anything here.
//
// CoreSystem - currently skips the tightly bound version check to make internal deployment and usage easier.
// We want to use old desktop side debugger components to target newer CoreCLR builds, only forcing a desktop
// upgrade when the protocol actually does change. To do this we use two checks:
// 1. The breaking change counter in CheckDbiVersion() whenever a dev knows they are breaking back
// compat and wants to be explicit about it. This is the same as mac above.
// 2. During the auto-generation of the DDMarshal classes we take an MD5 hash of IDacDbiInterface source
// code and embed it in two DDMarshal functions, one which runs locally and one that runs remotely.
// If both DBI and DAC were built from the same source then the local and remote hashes will match. If the
// hashes don't match then we assume there has been a been a breaking change in the protocol. Note
// this hash could have both false-positives and false-negatives. False positives could occur when
// IDacDbiInterface is changed in a trivial way, such as changing a comment. False negatives could
// occur when the semantics of the protocol are changed even though the interface is not. Another
// case would be changing the DDMarshal proxy generation code. In addition to the hashes we also
// embed timestamps when the auto-generated code was produced. However this isn't used for version
// matching, only as a hint to indicate which of two mismatched versions is newer.
//
//
// 3. Runtime vs. DAC
// - Desktop, Windows CoreCLR, CoreSystem CoreCLR
// In both cases we check this by matching the timestamp in the debug directory of the runtime image
// and the timestamp we store in the DAC table when we generate the DAC dll. This is done in
// code:ClrDataAccess::VerifyDlls.
//
// - Mac CoreCLR
// On Mac, we don't have a timestamp in the runtime image. Instead, we rely on checking the 16-byte
// UUID in the image. This UUID is used to check whether a symbol file matches the image, so
// conceptually it's the same as the timestamp we use on Windows. This is also done in
// code:ClrDataAccess::VerifyDlls.
//
//---------------------------------------------------------------------------------------
//
// Instantiates a DacDbi Interface object in a live-debugging scenario that matches
// the current instance of mscorwks in this process.
//
// Return Value:
// Returns on success. Else throws.
//
// Assumptions:
// Client will code:CordbProcess::FreeDac when its done with the DacDbi interface.
// Caller has initialized clrInstanceId.
//
// Notes:
// This looks for the DAC next to this current DBI. This assumes that Dac and Dbi are both on
// the local file system. That assumption will break in zero-copy deployment scenarios.
//
//---------------------------------------------------------------------------------------
void
CordbProcess::CreateDacDbiInterface()
{
_ASSERTE(m_pDACDataTarget != NULL);
_ASSERTE(m_pDacPrimitives == NULL); // don't double-init
// Caller has already determined which CLR in the target is being debugged.
_ASSERTE(m_clrInstanceId != 0);
m_pDacPrimitives = NULL;
HRESULT hrStatus = S_OK;
// Non-marshalling path for live local dac.
// in the new arch we can get the module from OpenVirtualProcess2 but in the shim case
// and the deprecated OpenVirtualProcess case we must assume it comes from DAC in the
// same directory as DBI
if(m_hDacModule == NULL)
{
m_hDacModule.Assign(ShimProcess::GetDacModule());
}
//
// Get the access interface, passing our callback interfaces (data target, allocator and metadata lookup)
//
IDacDbiInterface::IAllocator * pAllocator = this;
IDacDbiInterface::IMetaDataLookup * pMetaDataLookup = this;
typedef HRESULT (STDAPICALLTYPE * PFN_DacDbiInterfaceInstance)(
ICorDebugDataTarget *,
CORDB_ADDRESS,
IDacDbiInterface::IAllocator *,
IDacDbiInterface::IMetaDataLookup *,
IDacDbiInterface **);
IDacDbiInterface* pInterfacePtr = NULL;
PFN_DacDbiInterfaceInstance pfnEntry = (PFN_DacDbiInterfaceInstance)GetProcAddress(m_hDacModule, "DacDbiInterfaceInstance");
if (!pfnEntry)
{
ThrowLastError();
}
hrStatus = pfnEntry(m_pDACDataTarget, m_clrInstanceId, pAllocator, pMetaDataLookup, &pInterfacePtr);
IfFailThrow(hrStatus);
// We now have a resource, pInterfacePtr, that needs to be freed.
m_pDacPrimitives = pInterfacePtr;
// Setup DAC target consistency checking based on what we're using for DBI
m_pDacPrimitives->DacSetTargetConsistencyChecks( m_fAssertOnTargetInconsistency );
}
//---------------------------------------------------------------------------------------
//
// Is the DAC/DBI interface initialized?
//
// Return Value:
// TRUE iff init.
//
// Notes:
// The RS will try to initialize DD as soon as it detects the runtime as loaded.
// If the DD interface has not initialized, then it very likely the runtime has not
// been loaded into the target.
//
BOOL CordbProcess::IsDacInitialized()
{
return m_pDacPrimitives != NULL;
}
//---------------------------------------------------------------------------------------
//
// Get the DAC interface.
//
// Return Value:
// the Dac/Dbi interface pointer to the process.
// Never returns NULL.
//
// Assumptions:
// Caller is responsible for ensuring Data-Target is safe to access (eg, not
// currently running).
// Caller is responsible for ensuring DAC-cache is flushed. Call code:CordbProcess::ForceDacFlush
// as needed.
//
//---------------------------------------------------------------------------------------
IDacDbiInterface * CordbProcess::GetDAC()
{
// Since the DD primitives may throw, easiest way to model that is to make this throw.
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// We should always have the DAC/DBI interface.
_ASSERTE(m_pDacPrimitives != NULL);
return m_pDacPrimitives;
}
//---------------------------------------------------------------------------------------
// Get the Data-Target
//
// Returns:
// pointer to the data-target. Should be non-null.
// Lifetime of the pointer is until this process object is neutered.
//
ICorDebugDataTarget * CordbProcess::GetDataTarget()
{
return m_pDACDataTarget;
}
//---------------------------------------------------------------------------------------
// Create a CordbProcess object around an existing OS process.
//
// Arguments:
// pDataTarget - abstracts access to the debuggee.
// clrInstanceId - identifies the CLR instance within the debuggee. (This is the
// base address of mscorwks)
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// This should go away - we can get the functionality from the pShim.
// If this is null, then pShim must be null too.
// processID - OS process ID of target process. 0 if pShim == NULL.
// pShim - shim counter part object. This allows hooks back for v2 compat. This will
// go away once we no longer support V2 backwards compat.
// This must be non-null for any V2 paths (including non-DAC-ized code).
// If this is null, then we're in a V3 path.
// ppProcess - out parameter for new process object. This gets addreffed.
//
// Return Value:
// S_OK on success, and *ppProcess set to newly created debuggee object. Else error.
//
// Notes:
// @dbgtodo - , shim: Cordb, and pShim will all eventually go away.
//
//---------------------------------------------------------------------------------------
// static
HRESULT CordbProcess::OpenVirtualProcess(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
Cordb* pCordb,
const ProcessDescriptor * pProcessDescriptor,
ShimProcess * pShim,
CordbProcess ** ppProcess)
{
_ASSERTE(pDataTarget != NULL);
// In DEBUG builds, verify that we do actually have an ICorDebugDataTarget (i.e. that
// someone hasn't messed up the COM interop marshalling, etc.).
#ifdef _DEBUG
{
IUnknown * pTempDt;
HRESULT hrQi = pDataTarget->QueryInterface(IID_ICorDebugDataTarget, (void**)&pTempDt);
_ASSERTE_MSG(SUCCEEDED(hrQi), "OpenVirtualProcess was passed something that isn't actually an ICorDebugDataTarget");
pTempDt->Release();
}
#endif
// If we're emulating V2, then both pCordb and pShim are non-NULL.
// If we're doing a real V3 path, then they're both NULL.
// Either way, they should have the same null-status.
_ASSERTE((pCordb == NULL) == (pShim == NULL));
// If we're doing real V3, then we must have a real instance ID
_ASSERTE(!((pShim == NULL) && (clrInstanceId == 0)));
*ppProcess = NULL;
HRESULT hr = S_OK;
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
pProcess.Assign(new (nothrow) CordbProcess(clrInstanceId, pDataTarget, hDacModule, pCordb, pProcessDescriptor, pShim));
if (pProcess == NULL)
{
return E_OUTOFMEMORY;
}
ICorDebugProcess * pThis = pProcess;
(void)pThis; //prevent "unused variable" error from GCC
// CordbProcess::Init may need shim hooks, so connect Shim now.
// This will bump reference count.
if (pShim != NULL)
{
pShim->SetProcess(pProcess);
_ASSERTE(pShim->GetProcess() == pThis);
_ASSERTE(pShim->GetWin32EventThread() != NULL);
}
hr = pProcess->Init();
if (SUCCEEDED(hr))
{
*ppProcess = pProcess;
pProcess->ExternalAddRef();
}
else
{
// handle failure path
pProcess->CleanupHalfBakedLeftSide();
if (pShim != NULL)
{
// Shim still needs to be disposed to clean up other resources.
pShim->SetProcess(NULL);
}
// In failure case, pProcess's dtor will do the final release.
}
return hr;
}
//---------------------------------------------------------------------------------------
// CordbProcess constructor
//
// Arguments:
// pDataTarget - Pointer to an implementation of ICorDebugDataTarget
// (or ICorDebugMutableDataTarget), which virtualizes access to the process.
// clrInstanceId - representation of the CLR to debug in the process. Must be specified
// (non-zero) if pShim is NULL. If 0, use the first CLR that we see.
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// pW32 - Pointer to the Win32 event thread to use when processing events for this
// process.
// dwProcessID - For V3, 0.
// Else for shim codepaths, the processID of the process this object will represent.
// pShim - Pointer to the shim for handling V2 debuggers on the V3 architecture.
//
//---------------------------------------------------------------------------------------
CordbProcess::CordbProcess(ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
Cordb * pCordb,
const ProcessDescriptor * pProcessDescriptor,
ShimProcess * pShim)
: CordbBase(NULL, pProcessDescriptor->m_Pid, enumCordbProcess),
m_fDoDelayedManagedAttached(false),
m_cordb(pCordb),
m_handle(NULL),
m_processDescriptor(*pProcessDescriptor),
m_detached(false),
m_uninitializedStop(false),
m_exiting(false),
m_terminated(false),
m_unrecoverableError(false),
m_specialDeferment(false),
m_helperThreadDead(false),
m_loaderBPReceived(false),
m_cOutstandingEvals(0),
m_cOutstandingHandles(0),
m_clrInstanceId(clrInstanceId),
m_stopCount(0),
m_synchronized(false),
m_syncCompleteReceived(false),
m_pShim(pShim),
m_userThreads(11),
m_oddSync(false),
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads(11),
#endif
m_appDomains(11),
m_sharedAppDomain(0),
m_steppers(11),
m_continueCounter(1),
m_flushCounter(0),
m_leftSideEventAvailable(NULL),
m_leftSideEventRead(NULL),
#if defined(FEATURE_INTEROP_DEBUGGING)
m_leftSideUnmanagedWaitEvent(NULL),
#endif // FEATURE_INTEROP_DEBUGGING
m_initialized(false),
m_stopRequested(false),
m_stopWaitEvent(NULL),
#ifdef FEATURE_INTEROP_DEBUGGING
m_cFirstChanceHijackedThreads(0),
m_unmanagedEventQueue(NULL),
m_lastQueuedUnmanagedEvent(NULL),
m_lastQueuedOOBEvent(NULL),
m_outOfBandEventQueue(NULL),
m_lastDispatchedIBEvent(NULL),
m_dispatchingUnmanagedEvent(false),
m_dispatchingOOBEvent(false),
m_doRealContinueAfterOOBBlock(false),
m_state(0),
#endif // FEATURE_INTEROP_DEBUGGING
m_helperThreadId(0),
m_pPatchTable(NULL),
m_cPatch(0),
m_rgData(NULL),
m_rgNextPatch(NULL),
m_rgUncommitedOpcode(NULL),
m_minPatchAddr(MAX_ADDRESS),
m_maxPatchAddr(MIN_ADDRESS),
m_iFirstPatch(0),
m_hHelperThread(NULL),
m_dispatchedEvent(DB_IPCE_DEBUGGER_INVALID),
m_pDefaultAppDomain(NULL),
m_hDacModule(hDacModule),
m_pDacPrimitives(NULL),
m_pEventChannel(NULL),
m_fAssertOnTargetInconsistency(false),
m_runtimeOffsetsInitialized(false),
m_writableMetadataUpdateMode(LegacyCompatPolicy)
{
_ASSERTE((m_id == 0) == (pShim == NULL));
HRESULT hr = pDataTarget->QueryInterface(IID_ICorDebugDataTarget, reinterpret_cast<void **>(&m_pDACDataTarget));
IfFailThrow(hr);
#ifdef FEATURE_INTEROP_DEBUGGING
m_DbgSupport.m_DebugEventQueueIdx = 0;
m_DbgSupport.m_TotalNativeEvents = 0;
m_DbgSupport.m_TotalIB = 0;
m_DbgSupport.m_TotalOOB = 0;
m_DbgSupport.m_TotalCLR = 0;
#endif // FEATURE_INTEROP_DEBUGGING
g_pRSDebuggingInfo->m_MRUprocess = this;
// This is a strong reference to ourselves.
// This is cleared in code:CordbProcess::Neuter
m_pProcess.Assign(this);
#ifdef _DEBUG
// On Debug builds, we'll ASSERT by default whenever the target appears to be corrupt or
// otherwise inconsistent (both in DAC and DBI). But we also need the ability to
// explicitly test corrupt targets.
// Tests should set COMPlus_DbgIgnoreInconsistentTarget=1 to suppress these asserts
// Note that this controls two things:
// 1) DAC behavior - see code:IDacDbiInterface::DacSetTargetConsistencyChecks
// 2) RS-only consistency asserts - see code:CordbProcess::TargetConsistencyCheck
if( !CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgDisableTargetConsistencyAsserts) )
{
m_fAssertOnTargetInconsistency = true;
}
#endif
}
/*
A list of which resources owned by this object are accounted for.
UNKNOWN
Cordb* m_cordb;
CordbHashTable m_unmanagedThreads; // Released in CordbProcess but not removed from hash
DebuggerIPCEvent* m_lastQueuedEvent;
// CordbUnmannagedEvent is a struct which is not derrived from CordbBase.
// It contains a CordbUnmannagedThread which may need to be released.
CordbUnmanagedEvent *m_unmanagedEventQueue;
CordbUnmanagedEvent *m_lastQueuedUnmanagedEvent;
CordbUnmanagedEvent *m_outOfBandEventQueue;
CordbUnmanagedEvent *m_lastQueuedOOBEvent;
BYTE* m_pPatchTable;
BYTE *m_rgData;
void *m_pbRemoteBuf;
RESOLVED
// Nutered
CordbHashTable m_userThreads;
CordbHashTable m_appDomains;
// Cleaned up in ExitProcess
DebuggerIPCEvent* m_queuedEventList;
CordbHashTable m_steppers; // Closed in ~CordbProcess
// Closed in CloseIPCEventHandles called from ~CordbProcess
HANDLE m_leftSideEventAvailable;
HANDLE m_leftSideEventRead;
// Closed in ~CordbProcess
HANDLE m_handle;
HANDLE m_leftSideUnmanagedWaitEvent;
HANDLE m_stopWaitEvent;
// Deleted in ~CordbProcess
CRITICAL_SECTION m_processMutex;
*/
CordbProcess::~CordbProcess()
{
LOG((LF_CORDB, LL_INFO1000, "CP::~CP: deleting process 0x%08x\n", this));
DTOR_ENTRY(this);
_ASSERTE(IsNeutered());
_ASSERTE(m_cordb == NULL);
// We shouldn't still be in Cordb's list of processes. Unfortunately, our root Cordb object
// may have already been deleted b/c we're at the mercy of ref-counting, so we can't check.
_ASSERTE(m_sharedAppDomain == NULL);
m_processMutex.Destroy();
m_StopGoLock.Destroy();
// These handles were cleared in neuter
_ASSERTE(m_handle == NULL);
#if defined(FEATURE_INTEROP_DEBUGGING)
_ASSERTE(m_leftSideUnmanagedWaitEvent == NULL);
#endif // FEATURE_INTEROP_DEBUGGING
_ASSERTE(m_stopWaitEvent == NULL);
// Set this to mark that we really did cleanup.
}
//-----------------------------------------------------------------------------
// Static build helper.
// This will create a process under the pCordb root, and add it to the list.
// We don't return the process - caller gets the pid and looks it up under
// the Cordb object.
//
// Arguments:
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// szProgramName - Name of the program to execute.
// szProgramArgs - Command line arguments for the process.
// lpProcessAttributes - OS-specific attributes for process creation.
// lpThreadAttributes - OS-specific attributes for thread creation.
// fInheritFlags - OS-specific flag for child process inheritance.
// dwCreationFlags - OS-specific creation flags.
// lpEnvironment - OS-specific environmental strings.
// szCurrentDirectory - OS-specific string for directory to run in.
// lpStartupInfo - OS-specific info on startup.
// lpProcessInformation - OS-specific process information buffer.
// corDebugFlags - What type of process to create, currently always managed.
//-----------------------------------------------------------------------------
HRESULT ShimProcess::CreateProcess(
Cordb * pCordb,
ICorDebugRemoteTarget * pRemoteTarget,
LPCWSTR szProgramName,
_In_z_ LPWSTR szProgramArgs,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL fInheritHandles,
DWORD dwCreationFlags,
PVOID lpEnvironment,
LPCWSTR szCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
CorDebugCreateProcessFlags corDebugFlags
)
{
_ASSERTE(pCordb != NULL);
#if defined(FEATURE_DBGIPC_TRANSPORT_DI)
// The transport cannot deal with creating a suspended process (it needs the debugger to start up and
// listen for connections).
_ASSERTE((dwCreationFlags & CREATE_SUSPENDED) == 0);
#endif // FEATURE_DBGIPC_TRANSPORT_DI
HRESULT hr = S_OK;
RSExtSmartPtr<ShimProcess> pShim;
EX_TRY
{
pShim.Assign(new ShimProcess());
// Indicate that this process was started under the debugger as opposed to attaching later.
pShim->m_attached = false;
hr = pShim->CreateAndStartWin32ET(pCordb);
IfFailThrow(hr);
// Call out to newly created Win32-event Thread to create the process.
// If this succeeds, new CordbProcess will add a ref to the ShimProcess
hr = pShim->GetWin32EventThread()->SendCreateProcessEvent(pShim->GetMachineInfo(),
szProgramName,
szProgramArgs,
lpProcessAttributes,
lpThreadAttributes,
fInheritHandles,
dwCreationFlags,
lpEnvironment,
szCurrentDirectory,
lpStartupInfo,
lpProcessInformation,
corDebugFlags);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
// If this succeeds, then process takes ownership of thread. Else we need to kill it.
if (FAILED(hr))
{
if (pShim != NULL)
{
pShim->Dispose();
}
}
// Always release our ref to ShimProcess. If the Process was created, then it takes a reference.
return hr;
}
//-----------------------------------------------------------------------------
// Static build helper for the attach case.
// On success, this will add the process to the pCordb list, and then
// callers can look it up there by pid.
//
// Arguments:
// pCordb - root under which this all lives
// dwProcessID - OS process ID to attach to
// fWin32Attach - are we interop debugging?
//-----------------------------------------------------------------------------
HRESULT ShimProcess::DebugActiveProcess(
Cordb * pCordb,
ICorDebugRemoteTarget * pRemoteTarget,
const ProcessDescriptor * pProcessDescriptor,
BOOL fWin32Attach
)
{
_ASSERTE(pCordb != NULL);
HRESULT hr = S_OK;
RSExtSmartPtr<ShimProcess> pShim;
EX_TRY
{
pShim.Assign(new ShimProcess());
// Indicate that this process was attached to, asopposed to being started under the debugger.
pShim->m_attached = true;
hr = pShim->CreateAndStartWin32ET(pCordb);
IfFailThrow(hr);
// If this succeeds, new CordbProcess will add a ref to the ShimProcess
hr = pShim->GetWin32EventThread()->SendDebugActiveProcessEvent(pShim->GetMachineInfo(),
pProcessDescriptor,
fWin32Attach == TRUE,
NULL);
IfFailThrow(hr);
_ASSERTE(SUCCEEDED(hr));
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
// Don't do this when we are remote debugging since we won't be getting the loader breakpoint.
// We don't support JIT attach in remote debugging scenarios anyway.
//
// When doing jit attach for pure managed debugging we allow the native attach event to be signaled
// after DebugActiveProcess completes which means we must wait here long enough to have set the debuggee
// bit indicating managed attach is coming.
// However in interop debugging we can't do that because there are debug events which come before the
// loader breakpoint (which is how far we need to get to set the debuggee bit). If we blocked
// DebugActiveProcess there then the debug events would be refering to an ICorDebugProcess that hasn't
// yet been returned to the caller of DebugActiveProcess. Instead, for interop debugging we force the
// native debugger to wait until it gets the loader breakpoint to set the event. Note we can't converge
// on that solution for the pure managed case because there is no loader breakpoint event. Hence pure
// managed and interop debugging each require their own solution
//
// See bugs Dev10 600873 and 595322 for examples of what happens if we wait in interop or don't wait
// in pure managed respectively
//
// Long term this should all go away because we won't need to set a managed attach pending bit because
// there shouldn't be any IPC events involved in managed attach. There might not even be a notion of
// being 'managed attached'
if(!pShim->m_fIsInteropDebugging)
{
DWORD dwHandles = 2;
HANDLE arrHandles[2];
arrHandles[0] = pShim->m_terminatingEvent;
arrHandles[1] = pShim->m_markAttachPendingEvent;
// Wait for the completion of marking pending attach bit or debugger detaching
WaitForMultipleObjectsEx(dwHandles, arrHandles, FALSE, INFINITE, FALSE);
}
#endif //!FEATURE_DBGIPC_TRANSPORT_DI
}
EX_CATCH_HRESULT(hr);
// If this succeeds, then process takes ownership of thread. Else we need to kill it.
if (FAILED(hr))
{
if (pShim!= NULL)
{
pShim->Dispose();
}
}
// Always release our ref to ShimProcess. If the Process was created, then it takes a reference.
return hr;
}
//-----------------------------------------------------------------------------
// Neuter all of all children, but not the actual process object.
//
// Assumptions:
// This clears Right-side state. Assumptions about left-side state are either:
// 1. We're in a shutdown scenario, where all left-side state is already
// freed.
// 2. Caller already verified there are no left-side resources (eg, by calling
// code:CordbProcess::IsReadyForDetach)
// 3. Caller did code:CordbProcess::NeuterLeftSideResources first
// to clean up left-side resources.
//
// Notes:
// This could be called multiple times (code:CordbProcess::FlushAll), so
// be sure to null out any potential dangling pointers. State may be rebuilt
// up after each time.
void CordbProcess::NeuterChildren()
{
_ASSERTE(GetProcessLock()->HasLock());
// Frees left-side resources. See assumptions above.
m_LeftSideResourceCleanupList.NeuterAndClear(this);
m_EvalTable.Clear();
// Sweep neuter lists.
m_ExitNeuterList.NeuterAndClear(this);
m_ContinueNeuterList.NeuterAndClear(this);
m_userThreads.NeuterAndClear(GetProcessLock());
m_pDefaultAppDomain = NULL;
// Frees per-appdomain left-side resources. See assumptions above.
m_appDomains.NeuterAndClear(GetProcessLock());
if (m_sharedAppDomain != NULL)
{
m_sharedAppDomain->Neuter();
m_sharedAppDomain->InternalRelease();
m_sharedAppDomain = NULL;
}
m_steppers.NeuterAndClear(GetProcessLock());
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads.NeuterAndClear(GetProcessLock());
#endif // FEATURE_INTEROP_DEBUGGING
// Explicitly keep the Win32EventThread alive so that we can use it in the window
// between NeuterChildren + Neuter.
}
//-----------------------------------------------------------------------------
// Neuter
//
// When the process dies, remove all the resources associated with this object.
//
// Notes:
// Once we neuter ourself, we can no longer send IPC events. So this is useful
// on detach. This will be called on FlushAll (which has Whidbey detach
// semantics)
//-----------------------------------------------------------------------------
void CordbProcess::Neuter()
{
// Process's Neuter is at the top of the neuter tree. So we take the process-lock
// here and then all child items (appdomains, modules, etc) will assert
// that they hold the lock.
_ASSERTE(!this->ThreadHoldsProcessLock());
// Take the process lock.
RSLockHolder lockHolder(GetProcessLock());
NeuterChildren();
// Release the metadata interfaces
m_pMetaDispenser.Clear();
if (m_hHelperThread != NULL)
{
CloseHandle(m_hHelperThread);
m_hHelperThread = NULL;
}
{
lockHolder.Release();
{
// We may still hold the Stop-Go lock.
// @dbgtodo - left-side resources / shutdown, shim: Currently
// the shim shutdown is too interwoven with CordbProcess to split
// it out from the locks. Must fully hoist the W32ET and make
// it safely outside the RS, and outside the protection of RS
// locks.
PUBLIC_API_UNSAFE_ENTRY_FOR_SHIM(this);
// Now that all of our children are neutered, it should be safe to kill the W32ET.
// Shutdown the shim, and this will also shutdown the W32ET.
// Do this outside of the process-lock so that we can shutdown the
// W23ET.
if (m_pShim != NULL)
{
m_pShim->Dispose();
m_pShim.Clear();
}
}
lockHolder.Acquire();
}
// Unload DAC, and then release our final data target references
FreeDac();
m_pDACDataTarget.Clear();
m_pMutableDataTarget.Clear();
m_pMetaDataLocator.Clear();
if (m_pEventChannel != NULL)
{
m_pEventChannel->Delete();
m_pEventChannel = NULL;
}
// Need process lock to clear the patch table
ClearPatchTable();
CordbProcess::CloseIPCHandles();
CordbBase::Neuter();
m_cordb.Clear();
// Need to release this reference to ourselves. Other leaf objects may still hold
// strong references back to this CordbProcess object.
_ASSERTE(m_pProcess == this);
m_pProcess.Clear();
}
// Wrapper to return metadata dispenser.
//
// Notes:
// Does not adjust reference count of dispenser.
// Dispenser is destroyed in code:CordbProcess::Neuter
// Dispenser is non-null.
IMetaDataDispenserEx * CordbProcess::GetDispenser()
{
_ASSERTE(m_pMetaDispenser != NULL);
return m_pMetaDispenser;
}
void CordbProcess::CloseIPCHandles()
{
INTERNAL_API_ENTRY(this);
// Close off Right Side's handles.
if (m_leftSideEventAvailable != NULL)
{
CloseHandle(m_leftSideEventAvailable);
m_leftSideEventAvailable = NULL;
}
if (m_leftSideEventRead != NULL)
{
CloseHandle(m_leftSideEventRead);
m_leftSideEventRead = NULL;
}
if (m_handle != NULL)
{
// @dbgtodo - We should probably add asserts to all calls to CloseHandles(), but this has been
// a particularly problematic spot in the past for Mac debugging.
BOOL fSuccess = CloseHandle(m_handle);
(void)fSuccess; //prevent "unused variable" error from GCC
_ASSERTE(fSuccess);
m_handle = NULL;
}
#if defined(FEATURE_INTEROP_DEBUGGING)
if (m_leftSideUnmanagedWaitEvent != NULL)
{
CloseHandle(m_leftSideUnmanagedWaitEvent);
m_leftSideUnmanagedWaitEvent = NULL;
}
#endif // FEATURE_INTEROP_DEBUGGING
if (m_stopWaitEvent != NULL)
{
CloseHandle(m_stopWaitEvent);
m_stopWaitEvent = NULL;
}
}
//-----------------------------------------------------------------------------
// Create new OS Thread for the Win32 Event Thread (the thread used in interop-debugging to sniff
// native debug events). This is 1:1 w/ a CordbProcess object.
// This will then be used to actuall create the CordbProcess object.
// The process object will then take ownership of the thread.
//
// Arguments:
// pCordb - the root object that the process lives under
//
// Return values:
// S_OK on success.
//-----------------------------------------------------------------------------
HRESULT ShimProcess::CreateAndStartWin32ET(Cordb * pCordb)
{
//
// Create the win32 event listening thread
//
CordbWin32EventThread * pWin32EventThread = new (nothrow) CordbWin32EventThread(pCordb, this);
HRESULT hr = S_OK;
if (pWin32EventThread != NULL)
{
hr = pWin32EventThread->Init();
if (SUCCEEDED(hr))
{
hr = pWin32EventThread->Start();
}
if (FAILED(hr))
{
delete pWin32EventThread;
pWin32EventThread = NULL;
}
}
else
{
hr = E_OUTOFMEMORY;
}
m_pWin32EventThread = pWin32EventThread;
return ErrWrapper(hr);
}
//---------------------------------------------------------------------------------------
//
// Try to initialize the DAC. Called in scenarios where it may fail.
//
// Return Value:
// TRUE - DAC is initialized.
// FALSE - Not initialized, but can try again later. Common case if
// target has not yet loaded the runtime.
// Throws exception - fatal.
//
// Assumptions:
// Target is stopped by OS, so we can safely inspect it without it moving on us.
//
// Notes:
// This can be called eagerly to sniff if the LS is initialized.
//
//---------------------------------------------------------------------------------------
BOOL CordbProcess::TryInitializeDac()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// Target is stopped by OS, so we can safely inspect it without it moving on us.
// We want to avoid exceptions in the normal case, so we do some pre-checks
// to detect failure without relying on exceptions.
// Can't initialize DAC until mscorwks is loaded. So that's a sanity test.
HRESULT hr = EnsureClrInstanceIdSet();
if (FAILED(hr))
{
return FALSE;
}
// By this point, we know which CLR in the target to debug. That means there is a CLR
// in the target, and it's safe to initialize DAC.
_ASSERTE(m_clrInstanceId != 0);
// Now expect it to succeed
InitializeDac();
return TRUE;
}
//---------------------------------------------------------------------------------------
//
// Load & Init DAC, expecting to succeed.
//
// Return Value:
// Throws on failure.
//
// Assumptions:
// Caller invokes this at a point where they can expect it to succeed.
// This is called early in the startup path because DAC is needed for accessing
// data in the target.
//
// Notes:
// This needs to succeed, and should always succeed (baring a bad installation)
// so we assert on failure paths.
// This may be called mutliple times.
//
//---------------------------------------------------------------------------------------
void CordbProcess::InitializeDac()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
// For Mac debugginger, m_hDacModule is not used, and it will always be NULL. To check whether DAC has
// been initialized, we need to check something else, namely m_pDacPrimitives.
if (m_pDacPrimitives == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "About to load DAC\n"));
CreateDacDbiInterface(); // throws
}
else
{
LOG((LF_CORDB, LL_INFO1000, "Dac already loaded, 0x%p\n", (HMODULE)m_hDacModule));
}
// Always flush dac.
ForceDacFlush();
}
//---------------------------------------------------------------------------------------
//
// Free DAC resources
//
// Notes:
// This should clean up state such that code:CordbProcess::InitializeDac could be called again.
//
//---------------------------------------------------------------------------------------
void CordbProcess::FreeDac()
{
CONTRACTL
{
NOTHROW; // backout code.
}
CONTRACTL_END;
if (m_pDacPrimitives != NULL)
{
m_pDacPrimitives->Destroy();
m_pDacPrimitives = NULL;
}
if (m_hDacModule != NULL)
{
LOG((LF_CORDB, LL_INFO1000, "Unloading DAC\n"));
m_hDacModule.Clear();
}
}
IEventChannel * CordbProcess::GetEventChannel()
{
_ASSERTE(m_pEventChannel != NULL);
return m_pEventChannel;
}
//---------------------------------------------------------------------------------------
// Mark that the process is being interop-debugged.
//
// Notes:
// @dbgtodo shim: this should eventually move into the shim or go away.
// It's only to support V2 legacy interop-debugging.
// Called after code:CordbProcess::Init if we want to enable interop debugging.
// This allows us to separate out Interop-debugging flags from the core initialization,
// and paves the way for us to eventually remove it.
//
// Since we're always on the naitve-pipeline, the Enabling interop debugging just changes
// how the native debug events are being handled. So this must be called after Init, but
// before any events are actually handled.
// This mus be calle on the win32 event thread to gaurantee that it's called before WFDE.
void CordbProcess::EnableInteropDebugging()
{
CONTRACTL
{
THROWS;
PRECONDITION(m_pShim != NULL);
}
CONTRACTL_END;
// Must be on W32ET to gaurantee that we're called after Init yet before WFDE (which
// are both called on the W32et).
_ASSERTE(IsWin32EventThread());
#ifdef FEATURE_INTEROP_DEBUGGING
m_state |= PS_WIN32_ATTACHED;
if (GetDCB() != NULL)
{
GetDCB()->m_rightSideIsWin32Debugger = true;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
}
// Tell the Shim we're interop-debugging.
m_pShim->SetIsInteropDebugging(true);
#else
ThrowHR(CORDBG_E_INTEROP_NOT_SUPPORTED);
#endif
}
//---------------------------------------------------------------------------------------
//
// Init -- create any objects that the process object needs to operate.
//
// Arguments:
//
// Return Value:
// S_OK on success
//
// Assumptions:
// Called on Win32 Event Thread, after OS debugging pipeline is established but
// before WaitForDebugEvent / ContinueDebugEvent. This means the target is stopped.
//
// Notes:
// To enable interop-debugging, call code:CordbProcess::EnableInteropDebugging
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::Init()
{
INTERNAL_API_ENTRY(this);
HRESULT hr = S_OK;
BOOL fIsLSStarted = FALSE; // see meaning below.
FAIL_IF_NEUTERED(this);
EX_TRY
{
m_processMutex.Init("Process Lock", RSLock::cLockReentrant, RSLock::LL_PROCESS_LOCK);
m_StopGoLock.Init("Stop-Go Lock", RSLock::cLockReentrant, RSLock::LL_STOP_GO_LOCK);
#ifdef _DEBUG
m_appDomains.DebugSetRSLock(GetProcessLock());
m_userThreads.DebugSetRSLock(GetProcessLock());
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads.DebugSetRSLock(GetProcessLock());
#endif
m_steppers.DebugSetRSLock(GetProcessLock());
#endif
// See if the data target is mutable, and cache the mutable interface if it is
// We must initialize this before we try to use the data target to access the memory in the target process.
m_pMutableDataTarget.Clear(); // if we were called already, release
hr = m_pDACDataTarget->QueryInterface(IID_ICorDebugMutableDataTarget, (void**)&m_pMutableDataTarget);
if (!SUCCEEDED(hr))
{
// The data target doesn't support mutation. We'll fail any requests that require mutation.
m_pMutableDataTarget.Assign(new ReadOnlyDataTargetFacade());
}
m_pMetaDataLocator.Clear();
hr = m_pDACDataTarget->QueryInterface(IID_ICorDebugMetaDataLocator, reinterpret_cast<void **>(&m_pMetaDataLocator));
// Get the metadata dispenser.
hr = InternalCreateMetaDataDispenser(IID_IMetaDataDispenserEx, (void **)&m_pMetaDispenser);
// We statically link in the dispenser. We expect it to succeed, except for OOM, which
// debugger doesn't yet handle.
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
IfFailThrow(hr);
_ASSERTE(m_pMetaDispenser != NULL);
// In order to allow users to call the metadata reader from multiple threads we need to set
// a flag on the dispenser to create threadsafe readers. This is done best-effort but
// really shouldn't ever fail. See issue 696511.
VARIANT optionValue;
VariantInit(&optionValue);
V_VT(&optionValue) = VT_UI4;
V_UI4(&optionValue) = MDThreadSafetyOn;
m_pMetaDispenser->SetOption(MetaDataThreadSafetyOptions, &optionValue);
//
// Setup internal events.
// @dbgtodo shim: these events should eventually be in the shim.
//
// Managed debugging is built on the native-pipeline, and that will detect against double-attaches.
// @dbgtodo shim: In V2, LSEA + LSER were used by the LS's helper thread. Now with the V3 pipeline,
// that helper-thread uses native-debug events. The W32ET gets those events and then uses LSEA, LSER to
// signal existing RS infrastructure. Eventually get rid of LSEA, LSER completely.
//
m_leftSideEventAvailable = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_leftSideEventAvailable == NULL)
{
ThrowLastError();
}
m_leftSideEventRead = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_leftSideEventRead == NULL)
{
ThrowLastError();
}
m_stopWaitEvent = WszCreateEvent(NULL, TRUE, FALSE, NULL);
if (m_stopWaitEvent == NULL)
{
ThrowLastError();
}
if (m_pShim != NULL)
{
// Get a handle to the debuggee.
// This is not needed in the V3 pipeline because we don't assume we have a live, local, process.
m_handle = GetShim()->GetNativePipeline()->GetProcessHandle();
if (m_handle == NULL)
{
ThrowLastError();
}
}
// The LS startup goes through the following phases:
// 1) mscorwks not yet loaded (eg, any unmanaged app)
// 2) mscorwks loaded (DAC can now be used)
// 3) IPC Block created at OS level
// 4) IPC block data initialized (so we can read meainingful data from it)
// 5) LS marks that it's initialized (queryable by a DAC primitive) (may not be atomic)
// 6) LS fires a "Startup" exception (sniffed by WFDE).
//
// LS is currently stopped by OS debugging, so it's doesn't shift phases.
// From the RS's perspective:
// - after phase 5 is an attach
// - before phase 6 is a launch.
// This means there's an overlap: if we catch it at phase 5, we'll just get
// an extra Startup exception from phase 6, which is safe. This overlap is good
// because it means there's no bad window to do an attach in.
// fIsLSStarted means before phase 6 (eg, RS should expect a startup exception)
// Determines if the LS is started.
{
BOOL fReady = TryInitializeDac();
if (fReady)
{
// Invoke DAC primitive.
_ASSERTE(m_pDacPrimitives != NULL);
fIsLSStarted = m_pDacPrimitives->IsLeftSideInitialized();
}
else
{
_ASSERTE(m_pDacPrimitives == NULL);
// DAC is not yet loaded, so we're at least before phase 2, which is before phase 6.
// So leave fIsLSStarted = false. We'll get a startup exception later.
_ASSERTE(!fIsLSStarted);
}
}
if (fIsLSStarted)
{
// Left-side has started up. This is common for Attach cases when managed-code is already running.
if (m_pShim != NULL)
{
FinishInitializeIPCChannelWorker(); // throws
// At this point, the control block is complete and all four
// events are available and valid for the remote process.
// Request that the process object send an Attach IPC event.
// This is only used in an attach case.
// @dbgtodo sync: this flag can go away once the
// shim can use real sync APIs.
m_fDoDelayedManagedAttached = true;
}
else
{
// In the V3 pipeline case, if we have the DD-interface, then the runtime is loaded
// and we consider it initialized.
if (IsDacInitialized())
{
m_initialized = true;
}
}
}
else
{
// LS is not started yet. This would be common for "Launch" cases.
// We will get a Startup Exception notification when it does start.
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
CleanupHalfBakedLeftSide();
}
return hr;
}
COM_METHOD CordbProcess::CanCommitChanges(ULONG cSnapshots,
ICorDebugEditAndContinueSnapshot *pSnapshots[],
ICorDebugErrorInfoEnum **pError)
{
return E_NOTIMPL;
}
COM_METHOD CordbProcess::CommitChanges(ULONG cSnapshots,
ICorDebugEditAndContinueSnapshot *pSnapshots[],
ICorDebugErrorInfoEnum **pError)
{
return E_NOTIMPL;
}
//
// Terminating -- places the process into the terminated state. This should
// also get any blocking process functions unblocked so they'll return
// a failure code.
//
void CordbProcess::Terminating(BOOL fDetach)
{
INTERNAL_API_ENTRY(this);
LOG((LF_CORDB, LL_INFO1000,"CP::T: Terminating process 0x%x detach=%d\n", m_id, fDetach));
m_terminated = true;
m_cordb->ProcessStateChanged();
// Set events that may be blocking stuff.
// But don't set RSER unless we actually read the event. We don't block on RSER
// since that wait also checks the leftside's process handle.
SetEvent(m_leftSideEventRead);
SetEvent(m_leftSideEventAvailable);
SetEvent(m_stopWaitEvent);
if (m_pShim != NULL)
m_pShim->SetTerminatingEvent();
if (fDetach && (m_pEventChannel != NULL))
{
m_pEventChannel->Detach();
}
}
// Wrapper to give shim access to code:CordbProcess::QueueManagedAttachIfNeededWorker
void CordbProcess::QueueManagedAttachIfNeeded()
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
QueueManagedAttachIfNeededWorker();
}
//---------------------------------------------------------------------------------------
// Hook from Shim to request a managed attach IPC event
//
// Notes:
// Called by shim after the loader-breakpoint is handled.
// @dbgtodo sync: ths should go away once the shim can initiate
// a sync
void CordbProcess::QueueManagedAttachIfNeededWorker()
{
HRESULT hrQueue = S_OK;
// m_fDoDelayedManagedAttached ensures that we only send an Attach event if the LS is actually present.
if (m_fDoDelayedManagedAttached && GetShim()->GetAttached())
{
RSLockHolder lockHolder(&this->m_processMutex);
GetDAC()->MarkDebuggerAttachPending();
hrQueue = this->QueueManagedAttach();
}
if (m_pShim != NULL)
m_pShim->SetMarkAttachPendingEvent();
IfFailThrow(hrQueue);
}
//---------------------------------------------------------------------------------------
//
// QueueManagedAttach
//
// Send a managed attach. This is asynchronous and will return immediately.
//
// Return Value:
// S_OK on success
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::QueueManagedAttach()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_fDoDelayedManagedAttached);
m_fDoDelayedManagedAttached = false;
_ASSERTE(IsDacInitialized());
// We don't know what Queue it.
SendAttachProcessWorkItem * pItem = new (nothrow) SendAttachProcessWorkItem(this);
if (pItem == NULL)
{
return E_OUTOFMEMORY;
}
this->m_cordb->m_rcEventThread->QueueAsyncWorkItem(pItem);
return S_OK;
}
// However, we still want to synchronize.
// @dbgtodo sync: when we hoist attaching, we can send an DB_IPCE_ASYNC_BREAK event instead or Attach
// (for V2 semantics, we still need to synchronize the process)?
void SendAttachProcessWorkItem::Do()
{
HRESULT hr;
// This is being processed on the RCET, where it's safe to take the Stop-Go lock.
RSLockHolder ch(this->GetProcess()->GetStopGoLock());
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
// This just acts like an async-break, which will kick off things.
// This will not induce any faked attach events from the VM (like it did in V2).
// The Left-side will still slip foward allowing the async-break to happen, so
// we may get normal debug events in addition to the sync-complete.
//
// 1. In the common attach case, we should just get a sync-complete.
// 2. In Jit-attach cases, the LS is sending an event, and so we'll get that event and then the sync-complete.
GetProcess()->InitAsyncIPCEvent(event, DB_IPCE_ATTACHING, VMPTR_AppDomain::NullPtr());
// This should result in a sync-complete from the Left-side, which will be raised as an exception
// that the debugger passes into Filter and then internally goes through code:CordbProcess::TriageSyncComplete
// and that triggers code:CordbRCEventThread::FlushQueuedEvents to be called on the RCET.
// We already pre-queued a fake CreateProcess event.
// The left-side will also mark itself as attached in response to this event.
// We explicitly don't mark it as attached from the right-side because we want to let the left-side
// synchronize first (to stop all running threads) before marking the debugger as attached.
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::S: sending attach.\n", GetCurrentThreadId()));
hr = GetProcess()->SendIPCEvent(event, CorDBIPC_BUFFER_SIZE);
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::S: sent attach.\n", GetCurrentThreadId()));
}
//---------------------------------------------------------------------------------------
// Try to lookup a cached thread object
//
// Arguments:
// vmThread - vm identifier for thread.
//
// Returns:
// Thread object if cached; null if not yet cached.
//
// Notes:
// This does not create the thread object if it's not cached. Caching is unpredictable,
// and so this may appear to randomly return NULL.
// Callers should prefer code:CordbProcess::LookupOrCreateThread unless they expicitly
// want to check RS state.
CordbThread * CordbProcess::TryLookupThread(VMPTR_Thread vmThread)
{
return m_userThreads.GetBase(VmPtrToCookie(vmThread));
}
//---------------------------------------------------------------------------------------
// Lookup (or create) a CordbThread object by the given volatile OS id. Returns null if not a manged thread
//
// Arguments:
// dwThreadId - os thread id that a managed thread may be using.
//
// Returns:
// Thread instance if there is currently a managed thread scheduled to run on dwThreadId.
// NULL if this tid is not a valid Managed thread. (This is considered a common case)
// Throws on error.
//
// Notes:
// OS Thread ID is not fiber-safe, so this is a dangerous function to call.
// Avoid this as much as possible. Prefer using VMPTR_Thread and
// code:CordbProcess::LookupOrCreateThread instead of OS thread IDs.
// See code:CordbThread::GetID for details.
CordbThread * CordbProcess::TryLookupOrCreateThreadByVolatileOSId(DWORD dwThreadId)
{
PrepopulateThreadsOrThrow();
return TryLookupThreadByVolatileOSId(dwThreadId);
}
//---------------------------------------------------------------------------------------
// Lookup a cached CordbThread object by the tid. Returns null if not in the cache (which
// includes unmanged thread)
//
// Arguments:
// dwThreadId - os thread id that a managed thread may be using.
//
// Returns:
// Thread instance if there is currently a managed thread scheduled to run on dwThreadId.
// NULL if this tid is not a valid Managed thread. (This is considered a common case)
// Throws on error.
//
// Notes:
// Avoids this method:
// * OS Thread ID is not fiber-safe, so this is a dangerous function to call.
// * This is juts a Lookup, not LookupOrCreate, so it should only be used by methods
// that care about the RS state (instead of just LS state).
// Prefer using VMPTR_Thread and code:CordbProcess::LookupOrCreateThread
//
CordbThread * CordbProcess::TryLookupThreadByVolatileOSId(DWORD dwThreadId)
{
HASHFIND find;
for (CordbThread * pThread = m_userThreads.FindFirst(&find);
pThread != NULL;
pThread = m_userThreads.FindNext(&find))
{
_ASSERTE(pThread != NULL);
// Get the OS tid. This returns 0 if the thread is switched out.
DWORD dwThreadId2 = GetDAC()->TryGetVolatileOSThreadID(pThread->m_vmThreadToken);
if (dwThreadId2 == dwThreadId)
{
return pThread;
}
}
// This OS thread ID does not match any managed thread id.
return NULL;
}
//---------------------------------------------------------------------------------------
// Preferred CordbThread lookup routine.
//
// Arguments:
// vmThread - LS thread to lookup. Must be non-null.
//
// Returns:
// CordbThread instance for given vmThread. May return a previously cached
// instance or create a new instance. Never returns NULL.
// Throw on error.
CordbThread * CordbProcess::LookupOrCreateThread(VMPTR_Thread vmThread)
{
_ASSERTE(!vmThread.IsNull());
// Return if we have an existing instance.
CordbThread * pReturn = TryLookupThread(vmThread);
if (pReturn != NULL)
{
return pReturn;
}
RSInitHolder<CordbThread> pThread(new CordbThread(this, vmThread)); // throws
pReturn = pThread.TransferOwnershipToHash(&m_userThreads);
return pReturn;
}
HRESULT CordbProcess::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugProcess)
{
*pInterface = static_cast<ICorDebugProcess*>(this);
}
else if (id == IID_ICorDebugController)
{
*pInterface = static_cast<ICorDebugController*>(static_cast<ICorDebugProcess*>(this));
}
else if (id == IID_ICorDebugProcess2)
{
*pInterface = static_cast<ICorDebugProcess2*>(this);
}
else if (id == IID_ICorDebugProcess3)
{
*pInterface = static_cast<ICorDebugProcess3*>(this);
}
else if (id == IID_ICorDebugProcess4)
{
*pInterface = static_cast<ICorDebugProcess4*>(this);
}
else if (id == IID_ICorDebugProcess5)
{
*pInterface = static_cast<ICorDebugProcess5*>(this);
}
else if (id == IID_ICorDebugProcess7)
{
*pInterface = static_cast<ICorDebugProcess7*>(this);
}
else if (id == IID_ICorDebugProcess8)
{
*pInterface = static_cast<ICorDebugProcess8*>(this);
}
else if (id == IID_ICorDebugProcess11)
{
*pInterface = static_cast<ICorDebugProcess11*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugProcess*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
// Public implementation of ICorDebugProcess4::ProcessStateChanged
HRESULT CordbProcess::ProcessStateChanged(CorDebugStateChange eChange)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
switch(eChange)
{
case PROCESS_RUNNING:
FlushProcessRunning();
break;
case FLUSH_ALL:
FlushAll();
break;
default:
ThrowHR(E_INVALIDARG);
}
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHeap(ICorDebugHeapEnum **ppObjects)
{
if (!ppObjects)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
if (m_pDacPrimitives->AreGCStructuresValid())
{
CordbHeapEnum *pHeapEnum = new CordbHeapEnum(this);
GetContinueNeuterList()->Add(this, pHeapEnum);
hr = pHeapEnum->QueryInterface(__uuidof(ICorDebugHeapEnum), (void**)ppObjects);
}
else
{
hr = CORDBG_E_GC_STRUCTURES_INVALID;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetGCHeapInformation(COR_HEAPINFO *pHeapInfo)
{
if (!pHeapInfo)
return E_INVALIDARG;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
GetDAC()->GetGCHeapInformation(pHeapInfo);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHeapRegions(ICorDebugHeapSegmentEnum **ppRegions)
{
if (!ppRegions)
return E_INVALIDARG;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
DacDbiArrayList<COR_SEGMENT> segments;
hr = GetDAC()->GetHeapSegments(&segments);
if (SUCCEEDED(hr))
{
if (!segments.IsEmpty())
{
CordbHeapSegmentEnumerator *segEnum = new CordbHeapSegmentEnumerator(this, &segments[0], (DWORD)segments.Count());
GetContinueNeuterList()->Add(this, segEnum);
hr = segEnum->QueryInterface(__uuidof(ICorDebugHeapSegmentEnum), (void**)ppRegions);
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetObject(CORDB_ADDRESS addr, ICorDebugObjectValue **ppObject)
{
return this->GetObjectInternal(addr, nullptr, ppObject);
}
HRESULT CordbProcess::GetObjectInternal(CORDB_ADDRESS addr, CordbAppDomain* pAppDomainOverride, ICorDebugObjectValue **pObject)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
if (!m_pDacPrimitives->IsValidObject(addr))
{
hr = CORDBG_E_CORRUPT_OBJECT;
}
else if (pObject == NULL)
{
hr = E_INVALIDARG;
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
CordbAppDomain *cdbAppDomain = NULL;
CordbType *pType = NULL;
hr = GetTypeForObject(addr, pAppDomainOverride, &pType, &cdbAppDomain);
if (SUCCEEDED(hr))
{
_ASSERTE(pType != NULL);
_ASSERTE(cdbAppDomain != NULL);
DebuggerIPCE_ObjectData objData;
m_pDacPrimitives->GetBasicObjectInfo(addr, ELEMENT_TYPE_CLASS, cdbAppDomain->GetADToken(), &objData);
NewHolder<CordbObjectValue> pNewObjectValue(new CordbObjectValue(cdbAppDomain, pType, TargetBuffer(addr, (ULONG)objData.objSize), &objData));
hr = pNewObjectValue->Init();
if (SUCCEEDED(hr))
{
hr = pNewObjectValue->QueryInterface(__uuidof(ICorDebugObjectValue), (void**)pObject);
if (SUCCEEDED(hr))
pNewObjectValue.SuppressRelease();
}
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateGCReferences(BOOL enumerateWeakReferences, ICorDebugGCReferenceEnum **ppEnum)
{
if (!ppEnum)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
CordbRefEnum *pRefEnum = new CordbRefEnum(this, enumerateWeakReferences);
GetContinueNeuterList()->Add(this, pRefEnum);
hr = pRefEnum->QueryInterface(IID_ICorDebugGCReferenceEnum, (void**)ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHandles(CorGCReferenceType types, ICorDebugGCReferenceEnum **ppEnum)
{
if (!ppEnum)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
CordbRefEnum *pRefEnum = new CordbRefEnum(this, types);
GetContinueNeuterList()->Add(this, pRefEnum);
hr = pRefEnum->QueryInterface(IID_ICorDebugGCReferenceEnum, (void**)ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnableNGENPolicy(CorDebugNGENPolicy ePolicy)
{
return E_NOTIMPL;
}
HRESULT CordbProcess::GetTypeID(CORDB_ADDRESS obj, COR_TYPEID *pId)
{
if (pId == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
hr = GetProcess()->GetDAC()->GetTypeID(obj, pId);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetTypeForTypeID(COR_TYPEID id, ICorDebugType **ppType)
{
if (ppType == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
RSLockHolder stopGoLock(this->GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
EX_TRY
{
DebuggerIPCE_ExpandedTypeData data;
GetDAC()->GetObjectExpandedTypeInfoFromID(AllBoxed, VMPTR_AppDomain::NullPtr(), id, &data);
CordbType *type = 0;
hr = CordbType::TypeDataToType(GetSharedAppDomain(), &data, &type);
if (SUCCEEDED(hr))
hr = type->QueryInterface(IID_ICorDebugType, (void**)ppType);
}
EX_CATCH_HRESULT(hr);
return hr;
}
COM_METHOD CordbProcess::GetArrayLayout(COR_TYPEID id, COR_ARRAY_LAYOUT *pLayout)
{
if (pLayout == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetArrayLayout(id, pLayout);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::GetTypeLayout(COR_TYPEID id, COR_TYPE_LAYOUT *pLayout)
{
if (pLayout == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetTypeLayout(id, pLayout);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::GetTypeFields(COR_TYPEID id, ULONG32 celt, COR_FIELD fields[], ULONG32 *pceltNeeded)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetObjectFields(id, celt, fields, pceltNeeded);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::SetWriteableMetadataUpdateMode(WriteableMetadataUpdateMode flags)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
if(flags != LegacyCompatPolicy &&
flags != AlwaysShowUpdates)
{
hr = E_INVALIDARG;
}
else if(m_pShim != NULL)
{
if(flags != LegacyCompatPolicy)
{
hr = CORDBG_E_UNSUPPORTED;
}
}
if(SUCCEEDED(hr))
{
m_writableMetadataUpdateMode = flags;
}
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::EnableExceptionCallbacksOutsideOfMyCode(BOOL enableExceptionsOutsideOfJMC)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->SetSendExceptionsOutsideOfJMC(enableExceptionsOutsideOfJMC);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::EnableGCNotificationEvents(BOOL fEnable)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
hr = this->m_pDacPrimitives->EnableGCNotificationEvents(fEnable);
}
PUBLIC_API_END(hr);
return hr;
}
//-----------------------------------------------------------
// ICorDebugProcess11
//-----------------------------------------------------------
COM_METHOD CordbProcess::EnumerateLoaderHeapMemoryRegions(ICorDebugMemoryRangeEnum **ppRanges)
{
VALIDATE_POINTER_TO_OBJECT(ppRanges, ICorDebugMemoryRangeEnum **);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
DacDbiArrayList<COR_MEMORY_RANGE> heapRanges;
hr = GetDAC()->GetLoaderHeapMemoryRanges(&heapRanges);
if (SUCCEEDED(hr))
{
RSInitHolder<CordbMemoryRangeEnumerator> heapSegmentEnumerator(
new CordbMemoryRangeEnumerator(this, &heapRanges[0], (DWORD)heapRanges.Count()));
GetContinueNeuterList()->Add(this, heapSegmentEnumerator);
heapSegmentEnumerator.TransferOwnershipExternal(ppRanges);
}
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbProcess::GetTypeForObject(CORDB_ADDRESS addr, CordbAppDomain* pAppDomainOverride, CordbType **ppType, CordbAppDomain **pAppDomain)
{
VMPTR_AppDomain appDomain;
VMPTR_Module mod;
VMPTR_DomainAssembly domainAssembly;
HRESULT hr = E_FAIL;
if (GetDAC()->GetAppDomainForObject(addr, &appDomain, &mod, &domainAssembly))
{
if (pAppDomainOverride)
{
appDomain = pAppDomainOverride->GetADToken();
}
CordbAppDomain *cdbAppDomain = appDomain.IsNull() ? GetSharedAppDomain() : LookupOrCreateAppDomain(appDomain);
_ASSERTE(cdbAppDomain);
DebuggerIPCE_ExpandedTypeData data;
GetDAC()->GetObjectExpandedTypeInfo(AllBoxed, appDomain, addr, &data);
CordbType *type = 0;
hr = CordbType::TypeDataToType(cdbAppDomain, &data, &type);
if (SUCCEEDED(hr))
{
*ppType = type;
if (pAppDomain)
*pAppDomain = cdbAppDomain;
}
}
return hr;
}
// ******************************************
// CordbRefEnum
// ******************************************
CordbRefEnum::CordbRefEnum(CordbProcess *proc, BOOL walkWeakRefs)
: CordbBase(proc, 0, enumCordbHeap), mRefHandle(0), mEnumStacksFQ(TRUE),
mHandleMask((UINT32)(walkWeakRefs ? CorHandleAll : CorHandleStrongOnly))
{
}
CordbRefEnum::CordbRefEnum(CordbProcess *proc, CorGCReferenceType types)
: CordbBase(proc, 0, enumCordbHeap), mRefHandle(0), mEnumStacksFQ(FALSE),
mHandleMask((UINT32)types)
{
}
void CordbRefEnum::Neuter()
{
EX_TRY
{
if (mRefHandle)
{
GetProcess()->GetDAC()->DeleteRefWalk(mRefHandle);
mRefHandle = 0;
}
}
EX_CATCH
{
_ASSERTE(!"Hit an error freeing a ref walk.");
}
EX_END_CATCH(SwallowAllExceptions)
CordbBase::Neuter();
}
HRESULT CordbRefEnum::QueryInterface(REFIID riid, void **ppInterface)
{
if (ppInterface == NULL)
return E_INVALIDARG;
if (riid == IID_ICorDebugGCReferenceEnum)
{
*ppInterface = static_cast<ICorDebugGCReferenceEnum*>(this);
}
else if (riid == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown*>(static_cast<ICorDebugGCReferenceEnum*>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbRefEnum::Skip(ULONG celt)
{
return E_NOTIMPL;
}
HRESULT CordbRefEnum::Reset()
{
PUBLIC_API_ENTRY(this);
HRESULT hr = S_OK;
EX_TRY
{
if (mRefHandle)
{
GetProcess()->GetDAC()->DeleteRefWalk(mRefHandle);
mRefHandle = 0;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbRefEnum::Clone(ICorDebugEnum **ppEnum)
{
return E_NOTIMPL;
}
HRESULT CordbRefEnum::GetCount(ULONG *pcelt)
{
return E_NOTIMPL;
}
//
HRESULT CordbRefEnum::Next(ULONG celt, COR_GC_REFERENCE refs[], ULONG *pceltFetched)
{
if (refs == NULL || pceltFetched == NULL)
return E_POINTER;
CordbProcess *process = GetProcess();
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(process);
RSLockHolder procLockHolder(process->GetProcessLock());
EX_TRY
{
if (!mRefHandle)
hr = process->GetDAC()->CreateRefWalk(&mRefHandle, mEnumStacksFQ, mEnumStacksFQ, mHandleMask);
if (SUCCEEDED(hr))
{
DacGcReference dacRefs[32];
ULONG toFetch = ARRAY_SIZE(dacRefs);
ULONG total = 0;
for (ULONG c = 0; SUCCEEDED(hr) && c < (celt/ARRAY_SIZE(dacRefs) + 1); ++c)
{
// Fetch 32 references at a time, the last time, only fetch the remainder (that is, if
// the user didn't fetch a multiple of 32).
if (c == celt/ARRAY_SIZE(dacRefs))
toFetch = celt % ARRAY_SIZE(dacRefs);
ULONG fetched = 0;
hr = process->GetDAC()->WalkRefs(mRefHandle, toFetch, dacRefs, &fetched);
if (SUCCEEDED(hr))
{
for (ULONG i = 0; i < fetched; ++i)
{
CordbAppDomain *pDomain = process->LookupOrCreateAppDomain(dacRefs[i].vmDomain);
ICorDebugAppDomain *pAppDomain;
ICorDebugValue *pOutObject = NULL;
if (dacRefs[i].pObject & 1)
{
dacRefs[i].pObject &= ~1;
ICorDebugObjectValue *pObjValue = NULL;
hr = process->GetObject(dacRefs[i].pObject, &pObjValue);
if (SUCCEEDED(hr))
{
hr = pObjValue->QueryInterface(IID_ICorDebugValue, (void**)&pOutObject);
pObjValue->Release();
}
}
else
{
ICorDebugReferenceValue *tmpValue = NULL;
IfFailThrow(CordbReferenceValue::BuildFromGCHandle(pDomain,
dacRefs[i].objHnd,
&tmpValue));
if (SUCCEEDED(hr))
{
hr = tmpValue->QueryInterface(IID_ICorDebugValue, (void**)&pOutObject);
tmpValue->Release();
}
}
if (SUCCEEDED(hr) && pDomain)
{
hr = pDomain->QueryInterface(IID_ICorDebugAppDomain, (void**)&pAppDomain);
}
if (FAILED(hr))
break;
refs[total].Domain = pAppDomain;
refs[total].Location = pOutObject;
refs[total].Type = (CorGCReferenceType)dacRefs[i].dwType;
refs[total].ExtraData = dacRefs[i].i64ExtraData;
total++;
}
}
}
*pceltFetched = total;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ******************************************
// CordbHeapEnum
// ******************************************
CordbHeapEnum::CordbHeapEnum(CordbProcess *proc)
: CordbBase(proc, 0, enumCordbHeap), mHeapHandle(0)
{
}
HRESULT CordbHeapEnum::QueryInterface(REFIID riid, void **ppInterface)
{
if (ppInterface == NULL)
return E_INVALIDARG;
if (riid == IID_ICorDebugHeapEnum)
{
*ppInterface = static_cast<ICorDebugHeapEnum*>(this);
}
else if (riid == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown*>(static_cast<ICorDebugHeapEnum*>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbHeapEnum::Skip(ULONG celt)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::Reset()
{
Clear();
return S_OK;
}
void CordbHeapEnum::Clear()
{
EX_TRY
{
if (mHeapHandle)
{
GetProcess()->GetDAC()->DeleteHeapWalk(mHeapHandle);
mHeapHandle = 0;
}
}
EX_CATCH
{
_ASSERTE(!"Hit an error freeing the heap walk.");
}
EX_END_CATCH(SwallowAllExceptions)
}
HRESULT CordbHeapEnum::Clone(ICorDebugEnum **ppEnum)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::GetCount(ULONG *pcelt)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::Next(ULONG celt, COR_HEAPOBJECT objects[], ULONG *pceltFetched)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
RSLockHolder stopGoLock(this->GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
ULONG fetched = 0;
EX_TRY
{
if (mHeapHandle == 0)
{
hr = GetProcess()->GetDAC()->CreateHeapWalk(&mHeapHandle);
}
if (SUCCEEDED(hr))
{
hr = GetProcess()->GetDAC()->WalkHeap(mHeapHandle, celt, objects, &fetched);
_ASSERTE(fetched <= celt);
}
if (SUCCEEDED(hr))
{
// Return S_FALSE if we've reached the end of the enum.
if (fetched < celt)
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
// Set the fetched parameter to reflect the number of elements (if any)
// that were successfully saved to "objects"
if (pceltFetched)
*pceltFetched = fetched;
return hr;
}
//---------------------------------------------------------------------------------------
// Flush state for when the process starts running.
//
// Notes:
// Helper for code:CordbProcess::ProcessStateChanged.
// Since ICD Arrowhead does not own the eventing pipeline, it needs the debugger to
// notifying it of when the process is running again. This is like the counterpart
// to code:CordbProcess::Filter
void CordbProcess::FlushProcessRunning()
{
_ASSERTE(GetProcessLock()->HasLock());
// Update the continue counter.
m_continueCounter++;
// Safely dispose anything that should be neutered on continue.
MarkAllThreadsDirty();
ForceDacFlush();
}
//---------------------------------------------------------------------------------------
// Flush all cached state and bring us back to "cold startup"
//
// Notes:
// Helper for code:CordbProcess::ProcessStateChanged.
// This is used if the data-target changes underneath us in a way that is
// not consistent with the process running forward. For example, if for
// a time-travel debugger, the data-target may flow "backwards" in time.
//
void CordbProcess::FlushAll()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr;
_ASSERTE(GetProcessLock()->HasLock());
//
// First, determine if it's safe to Flush
//
hr = IsReadyForDetach();
IfFailThrow(hr);
// Check for outstanding CordbHandle values.
if (OutstandingHandles())
{
ThrowHR(CORDBG_E_DETACH_FAILED_OUTSTANDING_TARGET_RESOURCES);
}
// FlushAll is a superset of FlushProcessRunning.
// This will also ensure we clear the DAC cache.
FlushProcessRunning();
// If we detach before the CLR is loaded into the debuggee, then we can no-op a lot of work.
// We sure can't be sending IPC events to the LS before it exists.
NeuterChildren();
}
//---------------------------------------------------------------------------------------
//
// Detach the Debugger from the LS process.
//
//
// Return Value:
// S_OK on successful detach. Else errror.
//
// Assumptions:
// Target is stopped.
//
// Notes:
// Once we're detached, the LS can resume running and exit.
// So it's possible to get an ExitProcess callback in the middle of the Detach phase. If that happens,
// we must return CORDBG_E_PROCESS_TERMINATED and pretend that the exit happened before we tried to detach.
// Else if we detach successfully, return S_OK.
//
// @dbgtodo attach-bit: need to figure out semantics of Detach
// in V3, especially w.r.t to an attach bit.
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::Detach()
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if (IsInteropDebugging())
{
return CORDBG_E_INTEROP_NOT_SUPPORTED;
}
HRESULT hr = S_OK;
// A very important note: we require that the process is synchronized before doing a detach. This ensures
// that no events are on their way from the Left Side. We also require that the user has drained the
// managed event queue, but there is currently no way to really enforce that here.
// @todo- why can't we enforce that the managed event Q is drained?
ATT_REQUIRE_SYNCED_OR_NONINIT_MAY_FAIL(this);
hr = IsReadyForDetach();
if (FAILED(hr))
{
// Avoid neutering. Gives client a chance to fix detach issue and retry.
return hr;
}
// Since the detach may resume the LS and allow it to exit, which may invoke the EP callback
// which may destroy this process object, be sure to protect us w/ an extra AddRef/Release
RSSmartPtr<CordbProcess> pRef(this);
LOG((LF_CORDB, LL_INFO1000, "CP::Detach - beginning\n"));
if (m_pShim == NULL) // This API is moved off to the shim
{
// This is still invasive.
// Ignore failures. This will fail for a non-invasive target.
if (IsDacInitialized())
{
HRESULT hrIgnore = S_OK;
EX_TRY
{
GetDAC()->MarkDebuggerAttached(FALSE);
}
EX_CATCH_HRESULT(hrIgnore);
}
}
else
{
EX_TRY
{
DetachShim();
}
EX_CATCH_HRESULT(hr);
}
// Either way, neuter everything.
this->Neuter();
// Implicit release on pRef
LOG((LF_CORDB, LL_INFO1000, "CP::Detach - returning w/ hr=0x%x\n", hr));
return hr;
}
// Free up key left-side resources
//
// Called on detach
// This does key neutering of objects that hold left-side resources and require
// preemptively freeing the resources.
// After this, code:CordbProcess::Neuter should only affect right-side state.
void CordbProcess::NeuterChildrenLeftSideResources()
{
_ASSERTE(GetStopGoLock()->HasLock());
_ASSERTE(!GetProcessLock()->HasLock());
RSLockHolder lockHolder(GetProcessLock());
// Need process-lock to operate on hashtable, but can't yet Neuter under process-lock,
// so we have to copy the contents to an auxilary list which we can then traverse outside the lock.
RSPtrArray<CordbAppDomain> listAppDomains;
m_appDomains.CopyToArray(&listAppDomains);
// Must not hold process lock so that we can be safe to send IPC events
// to cleanup left-side resources.
lockHolder.Release();
_ASSERTE(!GetProcessLock()->HasLock());
// Frees left-side resources. This may send IPC events.
// This will make normal neutering a nop.
m_LeftSideResourceCleanupList.NeuterLeftSideResourcesAndClear(this);
for(unsigned int idx = 0; idx < listAppDomains.Length(); idx++)
{
CordbAppDomain * pAppDomain = listAppDomains[idx];
// CordbHandleValue is in the appdomain exit list, and that needs
// to send an IPC event to cleanup and release the handle from
// the GCs handle table.
pAppDomain->GetSweepableExitNeuterList()->NeuterLeftSideResourcesAndClear(this);
}
listAppDomains.Clear();
}
//---------------------------------------------------------------------------------------
// Detach the Debugger from the LS process for the V2 case
//
// Assumptions:
// This will NeuterChildren(), caller will do the real Neuter()
// Caller has already ensured that detach is safe.
//
// @dbgtodo attach-bit: this should be moved into the shim; need
// to figure out semantics for freeing left-side resources (especially GC
// handles) on detach.
void CordbProcess::DetachShim()
{
HASHFIND hashFind;
HRESULT hr = S_OK;
// If we detach before the CLR is loaded into the debuggee, then we can no-op a lot of work.
// We sure can't be sending IPC events to the LS before it exists.
if (m_initialized)
{
// The managed event queue is not necessarily drained. Cordbg could call detach between any callback.
// While the process is still stopped, neuter all of our children.
// This will make our Neuter() a nop and saves the W32ET from having to do dangerous work.
this->NeuterChildrenLeftSideResources();
{
RSLockHolder lockHolder(GetProcessLock());
this->NeuterChildren();
}
// Go ahead and detach from the entire process now. This is like sending a "Continue".
DebuggerIPCEvent * pIPCEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pIPCEvent, DB_IPCE_DETACH_FROM_PROCESS, true, VMPTR_AppDomain::NullPtr());
hr = m_cordb->SendIPCEvent(this, pIPCEvent, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, pIPCEvent->hr);
IfFailThrow(hr);
}
else
{
// @dbgtodo attach-bit: push this up, once detach IPC event is hoisted.
RSLockHolder lockHolder(GetProcessLock());
// Shouldn't have any appdomains.
(void)hashFind; //prevent "unused variable" error from GCC
_ASSERTE(m_appDomains.FindFirst(&hashFind) == NULL);
}
LOG((LF_CORDB, LL_INFO10000, "CP::Detach - got reply from LS\n"));
// It's possible that the LS may exit after they reply to our detach_from_process, but
// before we update our internal state that they're detached. So still have to check
// failure codes here.
hr = this->m_pShim->GetWin32EventThread()->SendDetachProcessEvent(this);
// Since we're auto-continuing when we detach, we should set the stop count back to zero.
// This (along w/ m_detached) prevents anyone from calling Continue on this process
// after this call returns.
m_stopCount = 0;
if (hr != CORDBG_E_PROCESS_TERMINATED)
{
// Remember that we've detached from this process object. This will prevent any further operations on
// this process, just in case... :)
// If LS exited, then don't set this flag because it overrides m_terminated when reporting errors;
// and we want to provide a consistent story about whether we detached or whether the LS exited.
m_detached = true;
}
IfFailThrow(hr);
// Now that all complicated cleanup is done, caller can do a final neuter.
// This will implicitly stop our Win32 event thread as well.
}
// Delete all events from the queue without dispatching. This is useful in shutdown.
// An event that is currently dispatching is not on the queue.
void CordbProcess::DeleteQueuedEvents()
{
INTERNAL_API_ENTRY(this);
// We must have the process lock to ensure that no one is trying to add an event
_ASSERTE(!ThreadHoldsProcessLock());
if (m_pShim != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this);
// DeleteAll() is part of the shim, and it will change external ref counts, so must really
// be marked as outside the RS.
m_pShim->GetManagedEventQueue()->DeleteAll();
}
}
//---------------------------------------------------------------------------------------
//
// Track that we're about to dispatch a managed event.
//
// Arguments:
// event - event being dispatched
//
// Assumptions:
// This is used to support code:CordbProcess::AreDispatchingEvent
// This is always called on the same thread as code:CordbProcess::FinishEventDispatch
void CordbProcess::StartEventDispatch(DebuggerIPCEventType event)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dispatchedEvent == DB_IPCE_DEBUGGER_INVALID);
_ASSERTE(event != DB_IPCE_DEBUGGER_INVALID);
m_dispatchedEvent = event;
}
//---------------------------------------------------------------------------------------
//
// Track that we're done dispatching a managed event.
//
//
// Assumptions:
// This is always called on the same thread as code:CordbProcess::StartEventDispatch
//
// Notes:
// @dbgtodo shim: eventually this goes into the shim when we hoist Continue
void CordbProcess::FinishEventDispatch()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dispatchedEvent != DB_IPCE_DEBUGGER_INVALID);
m_dispatchedEvent = DB_IPCE_DEBUGGER_INVALID;
}
//---------------------------------------------------------------------------------------
//
// Are we in the middle of dispatching an event?
//
// Notes:
// This is used by code::CordbProcess::ContinueInternal. Continue logic takes
// a shortcut if the continue is called on the dispatch thread.
// It doesn't matter which event is being dispatch; only that we're on the dispatch thread.
// @dbgtodo shim: eventually this goes into the shim when we hoist Continue
bool CordbProcess::AreDispatchingEvent()
{
LIMITED_METHOD_CONTRACT;
return m_dispatchedEvent != DB_IPCE_DEBUGGER_INVALID;
}
// Terminate the app. We'll still dispatch an ExitProcess callback, so the app
// must wait for that before calling Cordb::Terminate.
// If this fails, the client can always call the OS's TerminateProcess command
// to rudely kill the debuggee.
HRESULT CordbProcess::Terminate(unsigned int exitCode)
{
PUBLIC_API_ENTRY(this);
LOG((LF_CORDB, LL_INFO1000, "CP::Terminate: with exitcode %u\n", exitCode));
FAIL_IF_NEUTERED(this);
// @dbgtodo shutdown: eventually, all of Terminate() will be in the Shim.
// Free all the remaining events. Since this will call into the shim, do this outside of any locks.
// (ATT_ takes locks).
DeleteQueuedEvents();
ATT_REQUIRE_SYNCED_OR_NONINIT_MAY_FAIL(this);
// When we terminate the process, it's handle will become signaled and
// Win32 Event Thread will leap into action and call CordbWin32EventThread::ExitProcess
// Unfortunately, that may destroy this object if the ExitProcess callback
// decides to call Release() on the process.
// Indicate that the process is exiting so that (among other things) we don't try and
// send messages to the left side while it's being deleted.
Lock();
// In case we're continuing from the loader bp, we don't want to try and kick off an attach. :)
m_fDoDelayedManagedAttached = false;
m_exiting = true;
// We'd like to just take a lock around everything here, but that may deadlock us
// since W32ET will wait on the lock, and Continue may wait on W32ET.
// So we just do an extra AddRef/Release to make sure we're still around.
// @todo - could we move this smartptr up so that it's well-nested w/ the lock?
RSSmartPtr<CordbProcess> pRef(this);
Unlock();
// At any point after this call, the w32 ET may run the ExitProcess code which will race w/ the continue call.
// This call only posts a request that the process terminate and does not guarantee the process actually
// terminates. In particular, the process can not exit until any outstanding IO requests are done (on cancelled).
// It also can not exit if we have an outstanding not-continued native-debug event.
// Fortunately, the interesting work in terminate is done in ExitProcessWorkItem::Do, which can take the Stop-Go lock.
// Since we're currently holding the stop-go lock, that means we at least get some serialization.
//
// Note that on Windows, the process isn't really terminated until we receive the EXIT_PROCESS_DEBUG_EVENT.
// Before then, we can still still access the debuggee's address space. On the other, for Mac debugging,
// the process can die any time after this call, and so we can no longer call into the DAC.
GetShim()->GetNativePipeline()->TerminateProcess(exitCode);
// We just call Continue() so that the debugger doesn't have to. (It's arguably odd
// to call Continue() after Terminate).
// We're stopped & Synced.
// For interop-debugging this is very important because the Terminate may not really kill the process
// until after we continue from the current native debug event.
ContinueInternal(FALSE);
// Implicit release on pRef here (since it's going out of scope)...
// After this release, this object may be destroyed. So don't use any member functions
// (including Locks) after here.
return S_OK;
}
// This can be called at any time, even if we're in an unrecoverable error state.
HRESULT CordbProcess::GetID(DWORD *pdwProcessId)
{
PUBLIC_REENTRANT_API_ENTRY(this);
OK_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pdwProcessId, DWORD *);
HRESULT hr = S_OK;
EX_TRY
{
// This shouldn't be used in V3 paths. Normally, we can enforce that by checking against
// m_pShim. However, this API can be called after being neutered, in which case m_pShim is cleared.
// So check against 0 instead.
if (m_id == 0)
{
*pdwProcessId = 0;
ThrowHR(E_NOTIMPL);
}
*pdwProcessId = GetProcessDescriptor()->m_Pid;
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Helper to get process descriptor internally. We know we'll always succeed.
// This is more convient for internal callers since they can just use it as an expression
// without having to check HRESULTS.
const ProcessDescriptor* CordbProcess::GetProcessDescriptor()
{
// This shouldn't be used in V3 paths, in which case it's set to 0. Only the shim should be
// calling this. Assert to catch anybody else.
_ASSERTE(m_processDescriptor.IsInitialized());
return &m_processDescriptor;
}
HRESULT CordbProcess::GetHandle(HANDLE *phProcessHandle)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this); // Once we neuter the process, we close our OS handle to it.
VALIDATE_POINTER_TO_OBJECT(phProcessHandle, HANDLE *);
if (m_pShim == NULL)
{
_ASSERTE(!"CordbProcess::GetHandle() should be not be called on the new architecture");
*phProcessHandle = NULL;
return E_NOTIMPL;
}
else
{
*phProcessHandle = m_handle;
return S_OK;
}
}
HRESULT CordbProcess::IsRunning(BOOL *pbRunning)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pbRunning, BOOL*);
*pbRunning = !GetSynchronized();
return S_OK;
}
HRESULT CordbProcess::EnableSynchronization(BOOL bEnableSynchronization)
{
/* !!! */
PUBLIC_API_ENTRY(this);
return E_NOTIMPL;
}
HRESULT CordbProcess::Stop(DWORD dwTimeout)
{
PUBLIC_API_ENTRY(this);
CORDBRequireProcessStateOK(this);
HRESULT hr = StopInternal(dwTimeout, VMPTR_AppDomain::NullPtr());
return ErrWrapper(hr);
}
HRESULT CordbProcess::StopInternal(DWORD dwTimeout, VMPTR_AppDomain pAppDomainToken)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: stopping process 0x%x(%d) with timeout %d\n", m_id, m_id, dwTimeout));
INTERNAL_API_ENTRY(this);
// Stop + Continue are executed under the Stop-Go lock. This makes them atomic.
// We'll toggle the process-lock (b/c we communicate w/ the W32et, so just the process-lock is
// not sufficient to make this atomic).
// It's ok to take this lock before checking if the CordbProcess has been neutered because
// the lock is destroyed in the dtor after neutering.
RSLockHolder ch(&m_StopGoLock);
// Check if this CordbProcess has been neutered under the SG lock.
// Otherwise it's possible to race with Detach() and Terminate().
FAIL_IF_NEUTERED(this);
CORDBFailIfOnWin32EventThread(this);
if (m_pShim == NULL) // Stop/Go is moved off to the shim
{
return E_NOTIMPL;
}
DebuggerIPCEvent* event;
HRESULT hr = S_OK;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::SI, timeout=%d, this=%p\n", dwTimeout, this);
// Stop() is a syncronous (blocking) operation. Furthermore, we have no way to cancel the async-break request.
// Thus if we returned early on a timeout, then we'll be in a random state b/c the LS may get stopped at any
// later spot.
// One solution just require the param is INFINITE until we fix this and E_INVALIDARG if it's not.
// But that could be a breaking change (what if a debugger passes in a really large value that's effectively
// INFINITE).
// So we'll just ignore it and always treat it as infinite.
dwTimeout = INFINITE;
// Do the checks on the process state under the SG lock. This ensures that another thread cannot come in
// after we do the checks and take the lock before we do. For example, Detach() can race with Stop() such
// that:
// 1. Thread A calls CordbProcess::Detach() and takes the stop-go lock
// 2. Thread B calls CordbProcess::Stop(), passes all the checks, and then blocks on the stop-go lock
// 3. Thread A finishes the detach, invalides the process state, cleans all the resources, and then
// releases the stop-go lock
// 4. Thread B gets the lock, but everything has changed
CORDBRequireProcessStateOK(this);
Lock();
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
// Don't need to stop if the process hasn't even executed any managed code yet.
if (!m_initialized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process isn't initialized yet.\n"));
// Mark the process as synchronized so no events will be dispatched until the thing is continued.
SetSynchronized(true);
// Remember uninitialized stop...
m_uninitializedStop = true;
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're Win32 attached, then suspend all the unmanaged threads in the process.
// We may or may not be stopped at a native debug event.
if (IsInteropDebugging())
{
SuspendUnmanagedThreads();
}
#endif // FEATURE_INTEROP_DEBUGGING
// Get the RC Event Thread to stop listening to the process.
m_cordb->ProcessStateChanged();
hr = S_OK;
goto Exit;
}
// Don't need to stop if the process is already synchronized.
// @todo - Issue 129917. It's possible that we'll get a call to Stop when the LS is already stopped.
// Sending an AsyncBreak would deadlock here (b/c the LS will ignore the frivilous request,
// and thus never send a SyncComplete, and thus our Waiting on the SyncComplete will deadlock).
// We avoid this case by checking m_syncCompleteReceived (which should roughly correspond to
// the LS's m_stopped variable).
// One window this can happen is after a Continue() pings the RCET but before the RCET actually sweeps + flushes.
if (GetSynchronized() || GetSyncCompleteRecv())
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process was already synchronized. m_syncCompleteReceived=%d\n", GetSyncCompleteRecv()));
if (GetSyncCompleteRecv())
{
// We must be in that window alluded to above (while the RCET is sweeping). Re-ping the RCET.
SetSynchronized(true);
m_cordb->ProcessStateChanged();
}
hr = S_OK;
goto Exit;
}
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::S: process not sync'd, requesting stop.\n");
m_stopRequested = true;
// We don't want to dispatch any Win32 debug events while we're trying to stop.
// Setting m_specialDeferment=true means that any debug event we get will be queued and not dispatched.
// We do this to avoid a nested call to Continue.
// These defered events will get dispatched when somebody calls continue (and since they're calling
// stop now, they must call continue eventually).
// Note that if we got a Win32 debug event between when we took the Stop-Go lock above and now,
// that even may have been dispatched. We're ok because SSFW32Stop will hijack that event and continue it,
// and then all future events will be queued.
m_specialDeferment = true;
Unlock();
BOOL asyncBreakSent;
// We need to ensure that the helper thread is alive.
hr = this->StartSyncFromWin32Stop(&asyncBreakSent);
if (FAILED(hr))
{
return hr;
}
if (asyncBreakSent)
{
hr = S_OK;
Lock();
m_stopRequested = false;
goto Exit;
}
// Send the async break event to the RC.
event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_ASYNC_BREAK, false, pAppDomainToken);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::S: sending async stop to appd 0x%x.\n", VmPtrToCookie(pAppDomainToken));
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
if (FAILED(hr))
{
// We don't hold the lock so just return immediately. Don't adjust stop-count.
_ASSERTE(!ThreadHoldsProcessLock());
return hr;
}
LOG((LF_CORDB, LL_INFO1000, "CP::S: sent async stop to appd 0x%x.\n", VmPtrToCookie(pAppDomainToken)));
// Wait for the sync complete message to come in. Note: when the sync complete message arrives to the RCEventThread,
// it will mark the process as synchronized and _not_ dispatch any events. Instead, it will set m_stopWaitEvent
// which will let this function return. If the user wants to process any queued events, they will need to call
// Continue.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::S: waiting for event.\n");
DWORD ret;
ret = SafeWaitForSingleObject(this, m_stopWaitEvent, dwTimeout);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::S: got event, %d.\n", ret);
if (m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
if (ret == WAIT_OBJECT_0)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process stopped.\n"));
m_stopRequested = false;
m_cordb->ProcessStateChanged();
hr = S_OK;
Lock();
goto Exit;
}
else if (ret == WAIT_TIMEOUT)
{
hr = ErrWrapper(CORDBG_E_TIMEOUT);
}
else
hr = HRESULT_FROM_GetLastError();
// We came out of the wait, but we weren't signaled because a sync complete event came in. Re-check the process and
// remove the stop requested flag.
Lock();
m_stopRequested = false;
if (GetSynchronized())
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process stopped.\n"));
m_cordb->ProcessStateChanged();
hr = S_OK;
}
Exit:
_ASSERTE(ThreadHoldsProcessLock());
// Stop queuing any Win32 Debug events. We should be synchronized now.
m_specialDeferment = false;
if (SUCCEEDED(hr))
{
IncStopCount();
}
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::S: returning from Stop, hr=0x%08x, m_stopCount=%d.\n", hr, GetStopCount());
Unlock();
return hr;
}
//---------------------------------------------------------------------------------------
// Clear all RS state on all CordbThread objects.
//
// Notes:
// This clears all the thread-related state that the RS may have cached,
// such as locals, frames, etc.
// This would be called if the debugger is resuming execution.
void CordbProcess::MarkAllThreadsDirty()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
CordbThread * pThread;
HASHFIND find;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (pThread = m_userThreads.FindFirst(&find);
pThread != NULL;
pThread = m_userThreads.FindNext(&find))
{
_ASSERTE(pThread != NULL);
pThread->MarkStackFramesDirty();
}
ClearPatchTable();
}
HRESULT CordbProcess::Continue(BOOL fIsOutOfBand)
{
PUBLIC_API_ENTRY(this);
if (m_pShim == NULL) // This API is moved off to the shim
{
// bias towards failing with CORDBG_E_NUETERED.
FAIL_IF_NEUTERED(this);
return E_NOTIMPL;
}
HRESULT hr;
if (fIsOutOfBand)
{
#ifdef FEATURE_INTEROP_DEBUGGING
hr = ContinueOOB();
#else
hr = E_INVALIDARG;
#endif // FEATURE_INTEROP_DEBUGGING
}
else
{
hr = ContinueInternal(fIsOutOfBand);
}
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// ContinueOOB
//
// Continue the Win32 event as an out-of-band event.
//
// Return Value:
// S_OK on successful continue. Else error.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::ContinueOOB()
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
// If we're continuing from an out-of-band unmanaged event, then just go
// ahead and get the Win32 event thread to continue the process. No other
// work needs to be done (i.e., don't need to send a managed continue message
// or dispatch any events) because any processing done due to the out-of-band
// message can't alter the synchronized state of the process.
Lock();
_ASSERTE(m_outOfBandEventQueue != NULL);
// Are we calling this from the unmanaged callback?
if (m_dispatchingOOBEvent)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue while dispatching unmanaged out-of-band event.\n");
// We don't know what thread we're on here.
// Tell the Win32 event thread to continue when it returns from handling its unmanaged callback.
m_dispatchingOOBEvent = false;
Unlock();
}
else
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue outside of dispatching.\n");
// If we're not dispatching this, then they shouldn't be on the win32 event thread.
_ASSERTE(!this->IsWin32EventThread());
Unlock();
// Send an event to the Win32 event thread to do the continue. This is an out-of-band continue.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cOobUMContinue);
}
return hr;
}
#endif // FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// ContinueInternal
//
// Continue the Win32 event.
//
// Return Value:
// S_OK on success. Else error.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::ContinueInternal(BOOL fIsOutOfBand)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
// Continue has an ATT similar to ATT_REQUIRE_STOPPED_MAY_FAIL, but w/ some subtle differences.
// - if we're stopped at a native DE, but not synchronized, we don't want to sync.
// - We may get Debug events (especially native ones) at weird times, and thus we have to continue
// at weird times.
// External APIs should not have the process lock.
_ASSERTE(!ThreadHoldsProcessLock());
_ASSERTE(m_pShim != NULL);
// OutOfBand should use ContinueOOB
_ASSERTE(!fIsOutOfBand);
// Since Continue is process-wide, just use a null appdomain pointer.
VMPTR_AppDomain pAppDomainToken = VMPTR_AppDomain::NullPtr();
HRESULT hr = S_OK;
if (m_unrecoverableError)
{
return CORDBHRFromProcessState(this, NULL);
}
// We can't call ContinueInternal for an inband event on the win32 event thread.
// This is an issue in the CLR (or an API design decision, depending on your perspective).
// Continue() may send an IPC event and we can't do that on the win32 event thread.
CORDBFailIfOnWin32EventThread(this);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: continuing IB, this=0x%X\n", this);
// Stop + Continue are executed under the Stop-Go lock. This makes them atomic.
// We'll toggle the process-lock (b/c we communicate w/ the W32et, so that's not sufficient).
RSLockHolder rsLockHolder(&m_StopGoLock);
// Check for other failures (do these after we have the SG lock).
if (m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
if (m_detached)
{
return CORDBG_E_PROCESS_DETACHED;
}
Lock();
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
_ASSERTE(fIsOutOfBand == FALSE);
// If we've got multiple Stop calls, we need a Continue for each one. So, if the stop count > 1, just go ahead and
// return without doing anything. Note: this is only for in-band or managed events. OOB events are still handled as
// normal above.
_ASSERTE(GetStopCount() > 0);
if (GetStopCount() == 0)
{
Unlock();
_ASSERTE(!"Superflous Continue. ICorDebugProcess.Continue() called too many times");
return CORDBG_E_SUPERFLOUS_CONTINUE;
}
DecStopCount();
// We give managed events priority over unmanaged events. That way, the entire queued managed state can drain before
// we let any other unmanaged events through.
// Every stop or event must be matched by a corresponding Continue. m_stopCount counts outstanding stopping events
// along with calls to Stop. If the count is high at this point, we simply return. This ensures that even if someone
// calls Stop just as they're receiving an event that they can call Continue for that Stop and for that event
// without problems.
if (GetStopCount() > 0)
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: m_stopCount=%d, Continue just returning S_OK...\n", GetStopCount());
Unlock();
return S_OK;
}
// We're no longer stopped, so reset the m_stopWaitEvent.
ResetEvent(m_stopWaitEvent);
// If we're continuing from an uninitialized stop, then we don't need to do much at all. No event need be sent to
// the Left Side (duh, it isn't even there yet.) We just need to get the RC Event Thread to start listening to the
// process again, and resume any unmanaged threads if necessary.
if (m_uninitializedStop)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continuing from uninitialized stop.\n");
// No longer synchronized (it was a partial sync in the first place.)
SetSynchronized(false);
MarkAllThreadsDirty();
// No longer in an uninitialized stop.
m_uninitializedStop = false;
// Notify the RC Event Thread.
m_cordb->ProcessStateChanged();
Unlock();
#ifdef FEATURE_INTEROP_DEBUGGING
// We may or may not have a native debug event queued here.
// If Cordbg called Stop() from a native debug event (to get the process Synchronized), then
// we'll have a native debug event, and we need to continue it.
// If Cordbg called Stop() to do an AsyncBreak, then there's no native-debug event.
// If we're Win32 attached, resume all the unmanaged threads.
if (IsInteropDebugging())
{
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->SetState(CUES_UserContinued);
}
// Send to the Win32 event thread to do the unmanaged continue for us.
// If we're at a debug event, this will continue it.
// Else it will degenerate into ResumeUnmanagedThreads();
this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
}
#endif // FEATURE_INTEROP_DEBUGGING
return S_OK;
}
// If there are more managed events, get them dispatched now.
if (!m_pShim->GetManagedEventQueue()->IsEmpty() && GetSynchronized())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: managed event queued.\n");
// Mark that we're not synchronized anymore.
SetSynchronized(false);
// If the callback queue is not empty, then the LS is not actually continuing, and so our cached
// state is still valid.
// If we're in the middle of dispatching a managed event, then simply return. This indicates to HandleRCEvent
// that the user called Continue and HandleRCEvent will dispatch the next queued event. But if Continue was
// called outside the managed callback, all we have to do is tell the RC event thread that something about the
// process has changed and it will dispatch the next managed event.
if (!AreDispatchingEvent())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continuing while not dispatching managed event.\n");
m_cordb->ProcessStateChanged();
}
Unlock();
return S_OK;
}
// Neuter if we have an outstanding object.
// Only do this if we're really continuining the debuggee. So don't do this if our stop-count is high b/c we
// shouldn't neuter until we're done w/ the current event. And don't do this until we drain the current callback queue.
// Note that we can't hold the process lock while we do this b/c Neutering may send IPC events.
// However, we're still under the StopGo lock b/c that may help us serialize things.
// Sweep neuter list. This will catch anything that's marked as 'safe to neuter'. This includes
// all objects added to the 'neuter-on-Continue'.
// Only do this if we're synced- we don't want to do this if we're continuing from a Native Debug event.
if (GetSynchronized())
{
// Need process-lock to operate on hashtable, but can't yet Neuter under process-lock,
// so we have to copy the contents to an auxilary list which we can then traverse outside the lock.
RSPtrArray<CordbAppDomain> listAppDomains;
HRESULT hrCopy = S_OK;
EX_TRY // @dbgtodo cleanup: push this up
{
m_appDomains.CopyToArray(&listAppDomains);
}
EX_CATCH_HRESULT(hrCopy);
SetUnrecoverableIfFailed(GetProcess(), hrCopy);
m_ContinueNeuterList.NeuterAndClear(this);
// @dbgtodo left-side resources: eventually (once
// NeuterLeftSideResources is process-lock safe), do this all under the
// lock. Can't hold process lock b/c neutering left-side resources
// may send events.
Unlock();
// This may send IPC events.
// This will make normal neutering a nop.
// This will toggle the process lock.
m_LeftSideResourceCleanupList.SweepNeuterLeftSideResources(this);
// Many objects (especially CordbValue, FuncEval) don't have clear lifetime semantics and
// so they must be put into an exit-neuter list (Process/AppDomain) for worst-case scenarios.
// These objects are likely released early, and so we sweep them aggressively on each Continue (kind of like a mini-GC).
//
// One drawback is that there may be a lot of useless sweeping if the debugger creates a lot of
// objects that it holds onto. Consider instead of sweeping, have the object explicitly post itself
// to a list that's guaranteed to be cleared. This would let us avoid sweeping not-yet-ready objects.
// This will toggle the process lock
m_ExitNeuterList.SweepAllNeuterAtWillObjects(this);
for(unsigned int idx = 0; idx < listAppDomains.Length(); idx++)
{
CordbAppDomain * pAppDomain = listAppDomains[idx];
// CordbHandleValue is in the appdomain exit list, and that needs
// to send an IPC event to cleanup and release the handle from
// the GCs handle table.
// This will toggle the process lock.
pAppDomain->GetSweepableExitNeuterList()->SweepNeuterLeftSideResources(this);
}
listAppDomains.Clear();
Lock();
}
// At this point, if the managed event queue is empty, m_synchronized may still be true if we had previously
// synchronized.
#ifdef FEATURE_INTEROP_DEBUGGING
// Next, check for unmanaged events that may be queued. If there are some queued, then we need to get the Win32
// event thread to go ahead and dispatch the next one. If there aren't any queued, then we can just fall through and
// send the continue message to the left side. This works even if we have an outstanding ownership request, because
// until that answer is received, its just like the event hasn't happened yet.
//
// If we're terminated, then we've already continued from the last win32 event and so don't continue.
// @todo - or we could ensure the PS_SOME_THREADS_SUSPENDED | PS_HIJACKS_IN_PLACE are removed.
// Either way, we're just protecting against exit-process at strange times.
bool fDoWin32Continue = !m_terminated && ((m_state & (PS_WIN32_STOPPED | PS_SOME_THREADS_SUSPENDED | PS_HIJACKS_IN_PLACE)) != 0);
// We need to store this before marking the event user continued below
BOOL fHasUserUncontinuedEvents = HasUserUncontinuedNativeEvents();
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->SetState(CUES_UserContinued);
}
if (fHasUserUncontinuedEvents)
{
// ExitProcess is the last debug event we'll get. The Process Handle is not signaled until
// after we continue from ExitProcess. m_terminated is only set once we know the process is signaled.
// (This isn't 100% true for the detach case, but since you can't do interop detach, we don't care)
//_ASSERTE(!m_terminated);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: there are queued uncontinued events. m_dispatchingUnmanagedEvent = %d\n", m_dispatchingUnmanagedEvent);
// Are we being called while in the unmanaged event callback?
if (m_dispatchingUnmanagedEvent)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continue while dispatching.\n"));
// The Win32ET could have made a cross-thread call to Continue while dispatching,
// so we don't know if this is the win32 ET.
// Tell the Win32 thread to continue when it returns from handling its unmanaged callback.
m_dispatchingUnmanagedEvent = false;
// If there are no more unmanaged events, then we fall through and continue the process for real. Otherwise,
// we can simply return.
if (HasUndispatchedNativeEvents())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: more unmanaged events need dispatching.\n");
// Note: if we tried to access the Left Side while stopped but couldn't, then m_oddSync will be true. We
// need to reset it to false since we're continuing now.
m_oddSync = false;
Unlock();
return S_OK;
}
else
{
// Also, if there are no more unmanaged events, then when DispatchUnmanagedInBandEvent sees that
// m_dispatchingUnmanagedEvent is false, it will continue the process. So we set doWin32Continue to
// false here so that we don't try to double continue the process below.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: no more unmanaged events to dispatch.\n");
fDoWin32Continue = false;
}
}
else
{
// after the DebugEvent callback returned the continue still had no been issued. Then later
// on another thread the user called back to continue the event, which gets us to right here
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continue outside of dispatching.\n"));
// This should be the common place to Dispatch an IB event that was hijacked for sync.
// If we're not dispatching, this better not be the win32 event thread.
_ASSERTE(!IsWin32EventThread());
// If the event at the head of the queue is really the last event, or if the event at the head of the queue
// hasn't been dispatched yet, then we simply fall through and continue the process for real. However, if
// its not the last event, we send to the Win32 event thread and get it to continue, then we return.
if (HasUndispatchedNativeEvents())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: more unmanaged events need dispatching.\n");
// Note: if we tried to access the Left Side while stopped but couldn't, then m_oddSync will be true. We
// need to reset it to false since we're continuing now.
m_oddSync = false;
Unlock();
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
return hr;
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
// Both the managed and unmanaged event queues are now empty. Go
// ahead and continue the process for real.
LOG((LF_CORDB, LL_INFO1000, "CP::CI: headed for true continue.\n"));
// We need to check these while under the lock, but action must be
// taked outside of the lock.
bool fIsExiting = m_exiting;
bool fWasSynchronized = GetSynchronized();
// Mark that we're no longer synchronized.
if (fWasSynchronized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: process was synchronized.\n"));
SetSynchronized(false);
SetSyncCompleteRecv(false);
// we're no longer in a callback, so set flags to indicate that we've finished.
GetShim()->NotifyOnContinue();
// Flush will update state, including continue counter and marking
// frames dirty.
this->FlushProcessRunning();
// Tell the RC event thread that something about this process has changed.
m_cordb->ProcessStateChanged();
}
m_continueCounter++;
// If m_oddSync is set, then out last synchronization was due to us syncing the process because we were Win32
// stopped. Therefore, while we do need to do most of the work to continue the process below, we don't actually have
// to send the managed continue event. Setting wasSynchronized to false here helps us do that.
if (m_oddSync)
{
fWasSynchronized = false;
m_oddSync = false;
}
#ifdef FEATURE_INTEROP_DEBUGGING
// We must ensure that all managed threads are suspended here. We're about to let all managed threads run free via
// the managed continue message to the Left Side. If we don't suspend the managed threads, then they may start
// slipping forward even if we receive an in-band unmanaged event. We have to hijack in-band unmanaged events while
// getting the managed continue message over to the Left Side to keep the process running free. Otherwise, the
// SendIPCEvent will hang below. But in doing so, we could let managed threads slip to far. So we ensure they're all
// suspended here.
//
// Note: we only do this suspension if the helper thread hasn't died yet. If the helper thread has died, then we
// know that we're loosing the Runtime. No more managed code is going to run, so we don't bother trying to prevent
// managed threads from slipping via the call below.
//
// Note: we just remember here, under the lock, so we can unlock then wait for the syncing thread to free the
// debugger lock. Otherwise, we may block here and prevent someone from continuing from an OOB event, which also
// prevents the syncing thread from releasing the debugger lock like we want it to.
bool fNeedSuspend = fWasSynchronized && fDoWin32Continue && !m_helperThreadDead;
// If we receive a new in-band event once we unlock, we need to know to hijack it and keep going while we're still
// trying to send the managed continue event to the process.
if (fWasSynchronized && fDoWin32Continue && !fIsExiting)
{
m_specialDeferment = true;
}
if (fNeedSuspend)
{
// @todo - what does this actually accomplish? We already suspended everything when we first synced.
// Any thread that may hold a lock blocking the helper is
// inside of a can't stop region, and thus we won't suspend it.
SuspendUnmanagedThreads();
}
#endif // FEATURE_INTEROP_DEBUGGING
Unlock();
// Although we've released the Process-lock, we still have the Stop-Go lock.
_ASSERTE(m_StopGoLock.HasLock());
// If we're processing an ExitProcess managed event, then we don't want to really continue the process, so just fall
// thru. Note: we did let the unmanaged continue go through above for this case.
if (fIsExiting)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continuing from exit case.\n"));
}
else if (fWasSynchronized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: Sending continue to AppD:0x%x.\n", VmPtrToCookie(pAppDomainToken)));
#ifdef FEATURE_INTEROP_DEBUGGING
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Continue flags:special=%d, dowin32=%d\n", m_specialDeferment, fDoWin32Continue);
#endif
// Send to the RC to continue the process.
DebuggerIPCEvent * pEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pEvent, DB_IPCE_CONTINUE, false, pAppDomainToken);
hr = m_cordb->SendIPCEvent(this, pEvent, CorDBIPC_BUFFER_SIZE);
// It is possible that we continue and then the process immediately exits before the helper
// thread is finished continuing and can report success back to us. That's arguably a success
// case sinceu the process did indeed continue, but since we didn't get the acknowledgement,
// we can't be sure it's success. So we call it S_FALSE instead of S_OK.
// @todo - how do we handle other failure here?
if (hr == CORDBG_E_PROCESS_TERMINATED)
{
hr = S_FALSE;
}
_ASSERTE(SUCCEEDED(pEvent->hr));
LOG((LF_CORDB, LL_INFO1000, "CP::CI: Continue sent to AppD:0x%x.\n", VmPtrToCookie(pAppDomainToken)));
}
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're win32 attached to the Left side, then we need to win32 continue the process too (unless, of course, it's
// already been done above.)
//
// Note: we do this here because we want to get the Left Side to receive and ack our continue message above if we
// were sync'd. If we were sync'd, then by definition the process (and the helper thread) is running anyway, so all
// this continue is going to do is to let the threads that have been suspended go.
if (fDoWin32Continue)
{
#ifdef _DEBUG
{
// A little pause here extends the special deferment region and thus causes native-debug
// events to get hijacked. This test some wildly different corner case paths.
// See VSWhidbey bugs 131905, 168971
static DWORD dwRace = -1;
if (dwRace == -1)
dwRace = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgRace);
if ((dwRace & 1) == 1)
{
Sleep(30);
}
}
#endif
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: sending unmanaged continue.\n");
// Send to the Win32 event thread to do the unmanaged continue for us.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
}
#endif // FEATURE_INTEROP_DEBUGGING
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue done, returning.\n");
return hr;
}
HRESULT CordbProcess::HasQueuedCallbacks(ICorDebugThread *pThread,
BOOL *pbQueued)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pThread,ICorDebugThread *);
VALIDATE_POINTER_TO_OBJECT(pbQueued,BOOL *);
// Shim owns the event queue
if (m_pShim != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this); // Calling to shim, leaving RS.
*pbQueued = m_pShim->GetManagedEventQueue()->HasQueuedCallbacks(pThread);
return S_OK;
}
return E_NOTIMPL; // Not implemented in V3.
}
//
// A small helper function to convert a CordbBreakpoint to an ICorDebugBreakpoint based on its type.
//
static ICorDebugBreakpoint *CordbBreakpointToInterface(CordbBreakpoint * pBreakpoint)
{
_ASSERTE(pBreakpoint != NULL);
//
// I really dislike this. We've got three subclasses of CordbBreakpoint, but we store them all into the same hash
// (m_breakpoints), so when we get one out of the hash, we don't really know what type it is. But we need to know
// what type it is because we need to cast it to the proper interface before passing it out. I.e., when we create a
// function breakpoint, we return the breakpoint casted to an ICorDebugFunctionBreakpoint. But if we grab that same
// breakpoint out of the hash as a CordbBreakpoint and pass it out as an ICorDebugBreakpoint, then that's a
// different pointer, and its wrong. So I've added the type to the breakpoint so we can cast properly here. I'd love
// to do this a different way, though...
//
// -- Mon Dec 14 21:06:46 1998
//
switch(pBreakpoint->GetBPType())
{
case CBT_FUNCTION:
return static_cast<ICorDebugFunctionBreakpoint *>(static_cast<CordbFunctionBreakpoint *> (pBreakpoint));
break;
case CBT_MODULE:
return static_cast<ICorDebugModuleBreakpoint*>(static_cast<CordbModuleBreakpoint *> (pBreakpoint));
break;
case CBT_VALUE:
return static_cast<ICorDebugValueBreakpoint *>(static_cast<CordbValueBreakpoint *> (pBreakpoint));
break;
default:
_ASSERTE(!"Invalid breakpoint type!");
}
return NULL;
}
// Callback data for code:CordbProcess::GetAssembliesInLoadOrder
class ShimAssemblyCallbackData
{
public:
// Ctor to intialize callback data
//
// Arguments:
// pAppDomain - appdomain that the assemblies are in.
// pAssemblies - preallocated array of smart pointers to hold assemblies
// countAssemblies - size of pAssemblies in elements.
ShimAssemblyCallbackData(
CordbAppDomain * pAppDomain,
RSExtSmartPtr<ICorDebugAssembly>* pAssemblies,
ULONG countAssemblies)
{
_ASSERTE(pAppDomain != NULL);
_ASSERTE(pAssemblies != NULL);
m_pProcess = pAppDomain->GetProcess();
m_pAppDomain = pAppDomain;
m_pAssemblies = pAssemblies;
m_countElements = countAssemblies;
m_index = 0;
// Just to be safe, clear them all out
for(ULONG i = 0; i < countAssemblies; i++)
{
pAssemblies[i].Clear();
}
}
// Dtor
//
// Notes:
// This can assert end-of-enumeration invariants.
~ShimAssemblyCallbackData()
{
// Ensure that we went through all assemblies.
_ASSERTE(m_index == m_countElements);
}
// Callback invoked from DAC enumeration.
//
// arguments:
// vmDomainAssembly - VMPTR for assembly
// pData - a 'this' pointer
//
static void Callback(VMPTR_DomainAssembly vmDomainAssembly, void * pData)
{
ShimAssemblyCallbackData * pThis = static_cast<ShimAssemblyCallbackData *> (pData);
INTERNAL_DAC_CALLBACK(pThis->m_pProcess);
CordbAssembly * pAssembly = pThis->m_pAppDomain->LookupOrCreateAssembly(vmDomainAssembly);
pThis->SetAndMoveNext(pAssembly);
}
// Set the current index in the table and increment the cursor.
//
// Arguments:
// pAssembly - assembly from DAC enumerator
void SetAndMoveNext(CordbAssembly * pAssembly)
{
_ASSERTE(pAssembly != NULL);
if (m_index >= m_countElements)
{
// Enumerating the assemblies in the target should be fixed since
// the target is not running.
// We should never get here unless the target is unstable.
// The caller (the shim) pre-allocated the table of assemblies.
m_pProcess->TargetConsistencyCheck(!"Target changed assembly count");
return;
}
m_pAssemblies[m_index].Assign(pAssembly);
m_index++;
}
protected:
CordbProcess * m_pProcess;
CordbAppDomain * m_pAppDomain;
RSExtSmartPtr<ICorDebugAssembly>* m_pAssemblies;
ULONG m_countElements;
ULONG m_index;
};
//---------------------------------------------------------------------------------------
// Shim Helper to enumerate the assemblies in the load-order
//
// Arguments:
// pAppdomain - non-null appdomain to enumerate assemblies.
// pAssemblies - caller pre-allocated array to hold assemblies
// countAssemblies - size of the array.
//
// Notes:
// Caller preallocated array (likely from ICorDebugAssemblyEnum::GetCount),
// and now this function fills in the assemblies in the order they were
// loaded.
//
// The target should be stable, such that the number of assemblies in the
// target is stable, and therefore countAssemblies as determined by the
// shim via ICorDebugAssemblyEnum::GetCount should match the number of
// assemblies enumerated here.
//
// Called by code:ShimProcess::QueueFakeAttachEvents.
// This provides the assemblies in load-order. In contrast,
// ICorDebugAppDomain::EnumerateAssemblies is a random order. The shim needs
// load-order to match Whidbey semantics for dispatching fake load-assembly
// callbacks on attach. The debugger then uses the order
// in its module display window.
//
void CordbProcess::GetAssembliesInLoadOrder(
ICorDebugAppDomain * pAppDomain,
RSExtSmartPtr<ICorDebugAssembly>* pAssemblies,
ULONG countAssemblies)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
RSLockHolder lockHolder(GetProcessLock());
_ASSERTE(GetShim() != NULL);
CordbAppDomain * pAppDomainInternal = static_cast<CordbAppDomain *> (pAppDomain);
ShimAssemblyCallbackData data(pAppDomainInternal, pAssemblies, countAssemblies);
// Enumerate through and fill out pAssemblies table.
GetDAC()->EnumerateAssembliesInAppDomain(
pAppDomainInternal->GetADToken(),
ShimAssemblyCallbackData::Callback,
&data); // user data
// pAssemblies array has now been updated.
}
// Callback data for code:CordbProcess::GetModulesInLoadOrder
class ShimModuleCallbackData
{
public:
// Ctor to intialize callback data
//
// Arguments:
// pAssembly - assembly that the Modules are in.
// pModules - preallocated array of smart pointers to hold Modules
// countModules - size of pModules in elements.
ShimModuleCallbackData(
CordbAssembly * pAssembly,
RSExtSmartPtr<ICorDebugModule>* pModules,
ULONG countModules)
{
_ASSERTE(pAssembly != NULL);
_ASSERTE(pModules != NULL);
m_pProcess = pAssembly->GetAppDomain()->GetProcess();
m_pAssembly = pAssembly;
m_pModules = pModules;
m_countElements = countModules;
m_index = 0;
// Just to be safe, clear them all out
for(ULONG i = 0; i < countModules; i++)
{
pModules[i].Clear();
}
}
// Dtor
//
// Notes:
// This can assert end-of-enumeration invariants.
~ShimModuleCallbackData()
{
// Ensure that we went through all Modules.
_ASSERTE(m_index == m_countElements);
}
// Callback invoked from DAC enumeration.
//
// arguments:
// vmDomainAssembly - VMPTR for Module
// pData - a 'this' pointer
//
static void Callback(VMPTR_DomainAssembly vmDomainAssembly, void * pData)
{
ShimModuleCallbackData * pThis = static_cast<ShimModuleCallbackData *> (pData);
INTERNAL_DAC_CALLBACK(pThis->m_pProcess);
CordbModule * pModule = pThis->m_pAssembly->GetAppDomain()->LookupOrCreateModule(vmDomainAssembly);
pThis->SetAndMoveNext(pModule);
}
// Set the current index in the table and increment the cursor.
//
// Arguments:
// pModule - Module from DAC enumerator
void SetAndMoveNext(CordbModule * pModule)
{
_ASSERTE(pModule != NULL);
if (m_index >= m_countElements)
{
// Enumerating the Modules in the target should be fixed since
// the target is not running.
// We should never get here unless the target is unstable.
// The caller (the shim) pre-allocated the table of Modules.
m_pProcess->TargetConsistencyCheck(!"Target changed Module count");
return;
}
m_pModules[m_index].Assign(pModule);
m_index++;
}
protected:
CordbProcess * m_pProcess;
CordbAssembly * m_pAssembly;
RSExtSmartPtr<ICorDebugModule>* m_pModules;
ULONG m_countElements;
ULONG m_index;
};
//---------------------------------------------------------------------------------------
// Shim Helper to enumerate the Modules in the load-order
//
// Arguments:
// pAppdomain - non-null appdomain to enumerate Modules.
// pModules - caller pre-allocated array to hold Modules
// countModules - size of the array.
//
// Notes:
// Caller preallocated array (likely from ICorDebugModuleEnum::GetCount),
// and now this function fills in the Modules in the order they were
// loaded.
//
// The target should be stable, such that the number of Modules in the
// target is stable, and therefore countModules as determined by the
// shim via ICorDebugModuleEnum::GetCount should match the number of
// Modules enumerated here.
//
// Called by code:ShimProcess::QueueFakeAssemblyAndModuleEvent.
// This provides the Modules in load-order. In contrast,
// ICorDebugAssembly::EnumerateModules is a random order. The shim needs
// load-order to match Whidbey semantics for dispatching fake load-Module
// callbacks on attach. The most important thing is that the manifest module
// gets a LodModule callback before any secondary modules. For dynamic
// modules, this is necessary for operations on the secondary module
// that rely on manifest metadata (eg. GetSimpleName).
//
// @dbgtodo : This is almost identical to GetAssembliesInLoadOrder, and
// (together wih the CallbackData classes) seems a HUGE amount of code and
// complexity for such a simple thing. We also have extra code to order
// AppDomains and Threads. We should try and rip all of this extra complexity
// out, and replace it with better data structures for storing these items.
// Eg., if we used std::map, we could have efficient lookups and ordered
// enumerations. However, we do need to be careful about exposing new invariants
// through ICorDebug that customers may depend on, which could place a long-term
// compatibility burden on us. We could have a simple generic data structure
// (eg. built on std::hash_map and std::list) which provided efficient look-up
// and both in-order and random enumeration.
//
void CordbProcess::GetModulesInLoadOrder(
ICorDebugAssembly * pAssembly,
RSExtSmartPtr<ICorDebugModule>* pModules,
ULONG countModules)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
RSLockHolder lockHolder(GetProcessLock());
_ASSERTE(GetShim() != NULL);
CordbAssembly * pAssemblyInternal = static_cast<CordbAssembly *> (pAssembly);
ShimModuleCallbackData data(pAssemblyInternal, pModules, countModules);
// Enumerate through and fill out pModules table.
GetDAC()->EnumerateModulesInAssembly(
pAssemblyInternal->GetDomainAssemblyPtr(),
ShimModuleCallbackData::Callback,
&data); // user data
// pModules array has now been updated.
}
//---------------------------------------------------------------------------------------
// Callback to count the number of enumerations in a process.
//
// Arguments:
// id - the connection id.
// pName - name of the connection
// pUserData - an EnumerateConnectionsData
//
// Notes:
// Helper function for code:CordbProcess::QueueFakeConnectionEvents
//
// static
void CordbProcess::CountConnectionsCallback(DWORD id, LPCWSTR pName, void * pUserData)
{
}
//---------------------------------------------------------------------------------------
// Callback to enumerate all the connections in a process.
//
// Arguments:
// id - the connection id.
// pName - name of the connection
// pUserData - an EnumerateConnectionsData
//
// Notes:
// Helper function for code:CordbProcess::QueueFakeConnectionEvents
//
// static
void CordbProcess::EnumerateConnectionsCallback(DWORD id, LPCWSTR pName, void * pUserData)
{
}
//---------------------------------------------------------------------------------------
// Callback from Shim to queue fake Connection events on attach.
//
// Notes:
// See code:ShimProcess::QueueFakeAttachEvents
void CordbProcess::QueueFakeConnectionEvents()
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
}
//
// DispatchRCEvent -- dispatches a previously queued IPC event received
// from the runtime controller. This represents the last amount of processing
// the DI gets to do on an event before giving it to the user.
//
void CordbProcess::DispatchRCEvent()
{
INTERNAL_API_ENTRY(this);
CONTRACTL
{
// This is happening on the RCET thread, so there's no place to propagate an error back up.
NOTHROW;
}
CONTRACTL_END;
_ASSERTE(m_pShim != NULL); // V2 case
//
// Note: the current thread should have the process locked when it
// enters this method.
//
_ASSERTE(ThreadHoldsProcessLock());
// Create/Launch paths already ensured that we had a callback.
_ASSERTE(m_cordb != NULL);
_ASSERTE(m_cordb->m_managedCallback != NULL);
_ASSERTE(m_cordb->m_managedCallback2 != NULL);
_ASSERTE(m_cordb->m_managedCallback3 != NULL);
_ASSERTE(m_cordb->m_managedCallback4 != NULL);
// Bump up the stop count. Either we'll dispatch a managed event,
// or the logic below will decide not to dispatch one and call
// Continue itself. Either way, the stop count needs to go up by
// one...
_ASSERTE(this->GetSyncCompleteRecv());
SetSynchronized(true);
IncStopCount();
// As soon as we call Unlock(), we might get neutered and lose our reference to
// the shim. Grab it now for use later.
RSExtSmartPtr<ShimProcess> pShim(m_pShim);
Unlock();
_ASSERTE(!ThreadHoldsProcessLock());
// We want to stay synced until after the callbacks return. This is b/c we're on the RCET,
// and we may deadlock if we send IPC events on the RCET if we're not synced (see SendIPCEvent for details).
// So here, stopcount=1. The StopContinueHolder bumps it up to 2.
// - If Cordbg calls continue in the callback, that bumps it back down to 1, but doesn't actually continue.
// The holder dtor then bumps it down to 0, doing the real continue.
// - If Cordbg doesn't call continue in the callback, then stopcount stays at 2, holder dtor drops it down to 1,
// and then the holder was just a nop.
// This gives us delayed continues w/ no extra state flags.
// The debugger may call Detach() immediately after it returns from the callback, but before this thread returns
// from this function. Thus after we execute the callbacks, it's possible the CordbProcess object has been neutered.
// Since we're already sycned, the Stop from the holder here is practically a nop that just bumps up a count.
// Create an extra scope for the StopContinueHolder.
{
StopContinueHolder h;
HRESULT hr = h.Init(this);
if (FAILED(hr))
{
CORDBSetUnrecoverableError(this, hr, 0);
}
HRESULT hrCallback = S_OK;
// It's possible a ICorDebugProcess::Detach() may have occurred by now.
{
// @dbgtodo shim: eventually the entire RCET should be considered outside the RS.
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this);
// Snag the first event off the queue.
// Holder will call Delete, which will invoke virtual Dtor that will release ICD objects.
// Since these are external refs, we want to do it while "outside" the RS.
NewHolder<ManagedEvent> pEvent(pShim->DequeueManagedEvent());
// Normally pEvent shouldn't be NULL, since this method is called when the queue is not empty.
// But due to a race between CordbProcess::Terminate(), CordbWin32EventThread::ExitProcess() and this method
// it is totally possible that the queue has already been cleaned up and we can't expect that event is always available.
if (pEvent != NULL)
{
// Since we need to access a member (m_cordb), protect this block with a
// lock and a check for Neutering (in case process detach has just
// occurred). We'll release the lock around the dispatch later on.
RSLockHolder lockHolder(GetProcessLock());
if (!IsNeutered())
{
#ifdef _DEBUG
// On a debug build, keep track of the last IPC event we dispatched.
m_pDBGLastIPCEventType = pEvent->GetDebugCookie();
#endif
ManagedEvent::DispatchArgs args(m_cordb->m_managedCallback, m_cordb->m_managedCallback2, m_cordb->m_managedCallback3, m_cordb->m_managedCallback4);
{
// Release lock around the dispatch of the event
RSInverseLockHolder inverseLockHolder(GetProcessLock());
EX_TRY
{
// This dispatches almost directly into the user's callbacks.
// It does not update any RS state.
hrCallback = pEvent->Dispatch(args);
}
EX_CATCH_HRESULT(hrCallback);
}
}
}
} // we're now back inside the RS
if (hrCallback == E_NOTIMPL)
{
ContinueInternal(FALSE);
}
} // forces Continue to be called
Lock();
};
#ifdef _DEBUG
//---------------------------------------------------------------------------------------
// Debug-only callback to ensure that an appdomain is not available after the ExitAppDomain event.
//
// Arguments:
// vmAppDomain - appdomain from enumeration
// pUserData - pointer to a DbgAssertAppDomainDeletedData which contains the VMAppDomain that was just deleted.
// notes:
// see code:CordbProcess::DbgAssertAppDomainDeleted for details.
void CordbProcess::DbgAssertAppDomainDeletedCallback(VMPTR_AppDomain vmAppDomain, void * pUserData)
{
DbgAssertAppDomainDeletedData * pCallbackData = reinterpret_cast<DbgAssertAppDomainDeletedData *>(pUserData);
INTERNAL_DAC_CALLBACK(pCallbackData->m_pThis);
VMPTR_AppDomain vmAppDomainDeleted = pCallbackData->m_vmAppDomainDeleted;
CONSISTENCY_CHECK_MSGF((vmAppDomain != vmAppDomainDeleted),
("An ExitAppDomain event was sent for appdomain, but it still shows up in the enumeration.\n vmAppDomain=%p\n",
VmPtrToCookie(vmAppDomainDeleted)));
}
//---------------------------------------------------------------------------------------
// Debug-only helper to Assert that VMPTR is actually removed.
//
// Arguments:
// vmAppDomainDeleted - vmptr of appdomain that we just got exit event for.
// This should not be discoverable from the RS.
//
// Notes:
// See code:IDacDbiInterface#Enumeration for rules that we're asserting.
// Once the exit appdomain event is dispatched, the appdomain should not be discoverable by the RS.
// Else the RS may use the AppDomain* after it's deleted.
// This asserts that the AppDomain* is not discoverable.
//
// Since this is a debug-only function, it should have no side-effects.
void CordbProcess::DbgAssertAppDomainDeleted(VMPTR_AppDomain vmAppDomainDeleted)
{
DbgAssertAppDomainDeletedData callbackData;
callbackData.m_pThis = this;
callbackData.m_vmAppDomainDeleted = vmAppDomainDeleted;
GetDAC()->EnumerateAppDomains(
CordbProcess::DbgAssertAppDomainDeletedCallback,
&callbackData);
}
#endif // _DEBUG
//---------------------------------------------------------------------------------------
// Update state and potentially Dispatch a single event.
//
// Arguments:
// pEvent - non-null pointer to debug event.
// pCallback1 - callback object to dispatch on (for V1 callbacks)
// pCallback2 - 2nd callback object to dispatch on (for new V2 callbacks)
// pCallback3 - 3rd callback object to dispatch on (for new V4 callbacks)
//
//
// Returns:
// Nothing. Throws on error.
//
// Notes:
// Generally, this will dispatch exactly 1 callback. It may dispatch 0 callbacks if there is an error
// or in other corner cases (documented within the dispatch code below).
// Errors could occur because:
// - the event is corrupted (exceptional case)
// - the RS is corrupted / OOM (exceptional case)
// Exception errors here will propagate back to the Filter() call, and there's not really anything
// a debugger can do about an error here (perhaps report it to the user).
// Errors must leave IcorDebug in a consistent state.
//
// This is dispatched directly on the Win32Event Thread in response to calling Filter.
// Therefore, this can't send any IPC events (Not an issue once everything is DAC-ized).
// A V2 shim can provide a proxy calllack that takes these events and queues them and
// does the real dispatch to the user to emulate V2 semantics.
//
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
void CordbProcess::RawDispatchEvent(
DebuggerIPCEvent * pEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback1,
ICorDebugManagedCallback2 * pCallback2,
ICorDebugManagedCallback3 * pCallback3,
ICorDebugManagedCallback4 * pCallback4)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
// We start off with the lock, and we'll toggle it.
_ASSERTE(ThreadHoldsProcessLock());
//
// Call StartEventDispatch to true to guard against calls to Continue()
// from within the user's callback. We need Continue() to behave a little
// bit differently in such a case.
//
// Also note that Win32EventThread::ExitProcess will take the lock and free all
// events in the queue. (the current event is already off the queue, so
// it will be ok). But we can't do the EP callback in the middle of this dispatch
// so if this flag is set, EP will wait on the miscWaitEvent (which will
// get set in FlushQueuedEvents when we return from here) and let us finish here.
//
StartEventDispatch(pEvent->type);
// Keep strong references to these objects in case a callback deletes them from underneath us.
RSSmartPtr<CordbAppDomain> pAppDomain;
CordbThread * pThread = NULL;
// Get thread that this event is on. In attach scenarios, this may be the first time ICorDebug has seen this thread.
if (!pEvent->vmThread.IsNull())
{
pThread = LookupOrCreateThread(pEvent->vmThread);
}
if (!pEvent->vmAppDomain.IsNull())
{
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->vmAppDomain));
}
DWORD dwVolatileThreadId = 0;
if (pThread != NULL)
{
dwVolatileThreadId = pThread->GetUniqueId();
}
//
// Update the app domain that this thread lives in.
//
if ((pThread != NULL) && (pAppDomain != NULL))
{
// It shouldn't be possible for us to see an exited AppDomain here
_ASSERTE( !pAppDomain->IsNeutered() );
pThread->m_pAppDomain = pAppDomain;
}
_ASSERTE(pEvent != NULL);
_ASSERTE(pCallback1 != NULL);
_ASSERTE(pCallback2 != NULL);
_ASSERTE(pCallback3 != NULL);
_ASSERTE(pCallback4 != NULL);
STRESS_LOG1(LF_CORDB, LL_EVERYTHING, "Pre-Dispatch IPC event: %s\n", IPCENames::GetName(pEvent->type));
switch (pEvent->type & DB_IPCE_TYPE_MASK)
{
case DB_IPCE_CREATE_PROCESS:
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->CreateProcess(static_cast<ICorDebugProcess*> (this));
}
break;
case DB_IPCE_BREAKPOINT:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// Find the breakpoint object on this side.
CordbBreakpoint *pBreakpoint = NULL;
// We've found cases out in the wild where we get this event on a thread we don't recognize.
// We're not sure how this happens. Add a runtime check to protect ourselves to avoid the
// an AV. We still assert because this should not be happening.
// It likely means theres some issue where we failed to send a CreateThread notification.
TargetConsistencyCheck(pThread != NULL);
pBreakpoint = pAppDomain->m_breakpoints.GetBase(LsPtrToCookie(pEvent->BreakpointData.breakpointToken));
if (pBreakpoint != NULL)
{
ICorDebugBreakpoint * pIBreakpoint = CordbBreakpointToInterface(pBreakpoint);
_ASSERTE(pIBreakpoint != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, bp=0x%p", pThread, pBreakpoint);
pCallback1->Breakpoint(pAppDomain, pThread, pIBreakpoint);
}
}
}
break;
case DB_IPCE_BEFORE_GARBAGE_COLLECTION:
{
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->BeforeGarbageCollection(static_cast<ICorDebugProcess*>(this));
}
break;
}
case DB_IPCE_AFTER_GARBAGE_COLLECTION:
{
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->AfterGarbageCollection(static_cast<ICorDebugProcess*>(this));
}
break;
}
#ifdef FEATURE_DATABREAKPOINT
case DB_IPCE_DATA_BREAKPOINT:
{
_ASSERTE(pThread != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->DataBreakpoint(static_cast<ICorDebugProcess*>(this), pThread, reinterpret_cast<BYTE*>(&(pEvent->DataBreakpointData.context)), sizeof(CONTEXT));
}
break;
}
break;
#endif
case DB_IPCE_USER_BREAKPOINT:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: user breakpoint.\n",
GetCurrentThreadId());
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
_ASSERTE(pThread->m_pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->Break(pThread->m_pAppDomain, pThread);
}
}
break;
case DB_IPCE_STEP_COMPLETE:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: step complete.\n",
GetCurrentThreadId());
PREFIX_ASSUME(pThread != NULL);
CordbStepper * pStepper = m_steppers.GetBase(LsPtrToCookie(pEvent->StepData.stepperToken));
// It's possible the stepper is NULL if:
// - event X & step-complete are both in the queue
// - during dispatch for event X, Cordbg cancels the stepper (thus removing it from m_steppers)
// - the Step-Complete still stays in the queue, and so we're here, but out stepper's been removed.
// (This could happen for breakpoints too)
// Don't dispatch a callback if the stepper is NULL.
if (pStepper != NULL)
{
RSSmartPtr<CordbStepper> pRef(pStepper);
pStepper->m_active = false;
m_steppers.RemoveBase((ULONG_PTR)pStepper->m_id);
{
_ASSERTE(pThread->m_pAppDomain != NULL);
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thrad=0x%p, stepper=0x%p", pThread, pStepper);
pCallback1->StepComplete(pThread->m_pAppDomain, pThread, pStepper, pEvent->StepData.reason);
}
// implicit Release on pRef
}
}
break;
case DB_IPCE_EXCEPTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: exception.\n",
GetCurrentThreadId());
_ASSERTE(pAppDomain != NULL);
// For some exceptions very early in startup (eg, TypeLoad), this may have occurred before we
// even executed jitted code on the thread. We may have not received a CreateThread yet.
// In V2, we detected this and sent a LogMessage on a random thread.
// In V3, we lazily create the CordbThread objects (possibly before the CreateThread event),
// and so we know we should have one.
_ASSERTE(pThread != NULL);
pThread->SetExInfo(pEvent->Exception.vmExceptionHandle);
_ASSERTE(pThread->m_pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->Exception(pThread->m_pAppDomain, pThread, !pEvent->Exception.firstChance);
}
}
break;
case DB_IPCE_SYNC_COMPLETE:
_ASSERTE(!"Should have never queued a sync complete pEvent.");
break;
case DB_IPCE_THREAD_ATTACH:
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "RCET::DRCE: thread attach : ID=%x.\n", dwVolatileThreadId);
TargetConsistencyCheck(pThread != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "thread=0x%p", pThread);
pCallback1->CreateThread(pAppDomain, pThread);
}
}
break;
case DB_IPCE_THREAD_DETACH:
{
STRESS_LOG2(LF_CORDB, LL_INFO100, "[%x] RCET::HRCE: thread detach : ID=%x \n",
GetCurrentThreadId(), dwVolatileThreadId);
// If the runtime thread never entered managed code, there
// won't be a CordbThread, and CreateThread was never
// called, so don't bother calling ExitThread.
if (pThread != NULL)
{
AddToNeuterOnContinueList(pThread);
RSSmartPtr<CordbThread> pRefThread(pThread);
_ASSERTE(pAppDomain != NULL);
// A thread is reported as dead before we get the exit event.
// See code:IDacDbiInterface#IsThreadMarkedDead for the invariant being asserted here.
TargetConsistencyCheck(pThread->IsThreadDead());
// Enforce the enumeration invariants (see code:IDacDbiInterface#Enumeration)that the thread is not discoverable.
INDEBUG(pThread->DbgAssertThreadDeleted());
// Remove the thread from the hash. If we've removed it from the hash, we really should
// neuter it ... but that causes test failures.
// We'll neuter it in continue.
m_userThreads.RemoveBase(VmPtrToCookie(pThread->m_vmThreadToken));
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HRCE: sending thread detach.\n", GetCurrentThreadId()));
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->ExitThread(pAppDomain, pThread);
}
// Implicit release on thread & pAppDomain
}
}
break;
case DB_IPCE_METADATA_UPDATE:
{
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->MetadataUpdateData.vmDomainAssembly);
pModule->RefreshMetaData();
}
break;
case DB_IPCE_LOAD_MODULE:
{
_ASSERTE (pAppDomain != NULL);
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->LoadModuleData.vmDomainAssembly);
{
pModule->SetLoadEventContinueMarker();
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LoadModule(pAppDomain, pModule);
}
}
break;
case DB_IPCE_CREATE_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection change %d \n",
pEvent->CreateConnection.connectionId);
// pass back the connection id and the connection name.
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->CreateConnection(
this,
pEvent->CreateConnection.connectionId,
const_cast<WCHAR*> (pEvent->CreateConnection.wzConnectionName.GetString()));
}
break;
case DB_IPCE_DESTROY_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection destroyed %d \n",
pEvent->ConnectionChange.connectionId);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->DestroyConnection(this, pEvent->ConnectionChange.connectionId);
}
break;
case DB_IPCE_CHANGE_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection changed %d \n",
pEvent->ConnectionChange.connectionId);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->ChangeConnection(this, pEvent->ConnectionChange.connectionId);
}
break;
case DB_IPCE_UNLOAD_MODULE:
{
STRESS_LOG3(LF_CORDB, LL_INFO100, "RCET::HRCE: unload module on thread %#x Mod:0x%x AD:0x%08x\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->UnloadModuleData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain));
PREFIX_ASSUME (pAppDomain != NULL);
CordbModule *module = pAppDomain->LookupOrCreateModule(pEvent->UnloadModuleData.vmDomainAssembly);
if (module == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Already unloaded Module - continue()ing!" ));
break;
}
_ASSERTE(module != NULL);
INDEBUG(module->DbgAssertModuleDeleted());
// The appdomain we're unloading in must be the appdomain we were loaded in. Otherwise, we've got mismatched
// module and appdomain pointers. Bugs 65943 & 81728.
_ASSERTE(pAppDomain == module->GetAppDomain());
// Ensure the module gets neutered once we call continue.
AddToNeuterOnContinueList(module); // throws
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->UnloadModule(pAppDomain, module);
}
pAppDomain->m_modules.RemoveBase(VmPtrToCookie(pEvent->UnloadModuleData.vmDomainAssembly));
}
break;
case DB_IPCE_LOAD_CLASS:
{
CordbClass *pClass = NULL;
LOG((LF_CORDB, LL_INFO10000,
"RCET::HRCE: load class on thread %#x Tok:0x%08x Mod:0x%08x Asm:0x%08x AD:0x%08x\n",
dwVolatileThreadId,
pEvent->LoadClass.classMetadataToken,
VmPtrToCookie(pEvent->LoadClass.vmDomainAssembly),
LsPtrToCookie(pEvent->LoadClass.classDebuggerAssemblyToken),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
CordbModule* pModule = pAppDomain->LookupOrCreateModule(pEvent->LoadClass.vmDomainAssembly);
if (pModule == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Load Class on not-loaded Module - continue()ing!" ));
break;
}
_ASSERTE(pModule != NULL);
BOOL fDynamic = pModule->IsDynamic();
// If this is a class load in a dynamic module, the metadata has become invalid.
if (fDynamic)
{
pModule->RefreshMetaData();
}
hr = pModule->LookupOrCreateClass(pEvent->LoadClass.classMetadataToken, &pClass);
_ASSERTE(SUCCEEDED(hr) == (pClass != NULL));
IfFailThrow(hr);
// Prevent class load from being sent twice.
// @dbgtodo - Microsoft, cordbclass: this is legacy. Can this really happen? Investigate as we dac-ize CordbClass.
if (pClass->LoadEventSent())
{
// Dynamic modules are dynamic at the module level -
// you can't add a new version of a class once the module
// is baked.
// EnC adds completely new classes.
// There shouldn't be any other way to send multiple
// ClassLoad events.
// Except that there are race conditions between loading
// an appdomain, and loading a class, so if we get the extra
// class load, we should ignore it.
break; //out of the switch statement
}
pClass->SetLoadEventSent(TRUE);
if (pClass != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LoadClass(pAppDomain, pClass);
}
}
break;
case DB_IPCE_UNLOAD_CLASS:
{
LOG((LF_CORDB, LL_INFO10000,
"RCET::HRCE: unload class on thread %#x Tok:0x%08x Mod:0x%08x AD:0x%08x\n",
dwVolatileThreadId,
pEvent->UnloadClass.classMetadataToken,
VmPtrToCookie(pEvent->UnloadClass.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
// get the appdomain object
_ASSERTE (pAppDomain != NULL);
CordbModule *pModule = pAppDomain->LookupOrCreateModule(pEvent->UnloadClass.vmDomainAssembly);
if (pModule == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Unload Class on not-loaded Module - continue()ing!" ));
break;
}
_ASSERTE(pModule != NULL);
CordbClass *pClass = pModule->LookupClass(pEvent->UnloadClass.classMetadataToken);
if (pClass != NULL && !pClass->HasBeenUnloaded())
{
pClass->SetHasBeenUnloaded(true);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->UnloadClass(pAppDomain, pClass);
}
}
break;
case DB_IPCE_FIRST_LOG_MESSAGE:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
const WCHAR * pszContent = pEvent->FirstLogMessage.szContent.GetString();
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LogMessage(
pAppDomain,
pThread,
pEvent->FirstLogMessage.iLevel,
const_cast<WCHAR*> (pEvent->FirstLogMessage.szCategory.GetString()),
const_cast<WCHAR*> (pszContent));
}
}
break;
case DB_IPCE_LOGSWITCH_SET_MESSAGE:
{
LOG((LF_CORDB, LL_INFO10000,
"[%x] RCET::DRCE: Log Switch Setting Message.\n",
GetCurrentThreadId()));
_ASSERTE(pThread != NULL);
const WCHAR *pstrLogSwitchName = pEvent->LogSwitchSettingMessage.szSwitchName.GetString();
const WCHAR *pstrParentName = pEvent->LogSwitchSettingMessage.szParentSwitchName.GetString();
// from the thread object get the appdomain object
_ASSERTE(pAppDomain == pThread->m_pAppDomain);
_ASSERTE (pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LogSwitch(
pAppDomain,
pThread,
pEvent->LogSwitchSettingMessage.iLevel,
pEvent->LogSwitchSettingMessage.iReason,
const_cast<WCHAR*> (pstrLogSwitchName),
const_cast<WCHAR*> (pstrParentName));
}
}
break;
case DB_IPCE_CUSTOM_NOTIFICATION:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// determine first whether custom notifications for this type are enabled -- if not
// we just return without doing anything.
CordbClass * pNotificationClass = LookupClass(pAppDomain,
pEvent->CustomNotification.vmDomainAssembly,
pEvent->CustomNotification.classToken);
// if the class is NULL, that means the debugger never enabled notifications for it. Otherwise,
// the CordbClass instance would already have been created when the notifications were
// enabled.
if ((pNotificationClass != NULL) && pNotificationClass->CustomNotificationsEnabled())
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback3->CustomNotification(pThread, pAppDomain);
}
}
break;
case DB_IPCE_CREATE_APP_DOMAIN:
{
STRESS_LOG2(LF_CORDB, LL_INFO100,
"RCET::HRCE: create appdomain on thread %#x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->vmAppDomain));
// Enumerate may have prepopulated the appdomain, so check if it already exists.
// Either way, still send the CreateEvent. (We don't want to skip the Create event
// just because the debugger did an enumerate)
// We remove AppDomains from the hash as soon as they are exited.
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->AppDomainData.vmAppDomain));
_ASSERTE(pAppDomain != NULL); // throws on failure
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->CreateAppDomain(this, pAppDomain);
}
}
break;
case DB_IPCE_EXIT_APP_DOMAIN:
{
STRESS_LOG2(LF_CORDB, LL_INFO100, "RCET::HRCE: exit appdomain on thread %#x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->vmAppDomain));
// In debug-only builds, assert that the appdomain is indeed deleted and not discoverable.
INDEBUG(DbgAssertAppDomainDeleted(pEvent->vmAppDomain));
// If we get an ExitAD message for which we have no AppDomain, then ignore it.
// This can happen if an AD gets torn down very early (before the LS AD is to the
// point that it can be published).
// This could also happen if we attach a debugger right before the Exit event is sent.
// In this case, the debuggee is no longer publishing the appdomain.
if (pAppDomain == NULL)
{
break;
}
_ASSERTE (pAppDomain != NULL);
// See if this is the default AppDomain exiting. This should only happen very late in
// the shutdown cycle, and so we shouldn't do anything significant with m_pDefaultDomain==NULL.
// We should try and remove m_pDefaultDomain entirely since we can't count on it always existing.
if (pAppDomain == m_pDefaultAppDomain)
{
m_pDefaultAppDomain = NULL;
}
// Update any threads which were last seen in this AppDomain. We don't
// get any notification when a thread leaves an AppDomain, so our idea
// of what AppDomain the thread is in may be out of date.
UpdateThreadsForAdUnload( pAppDomain );
// This will still maintain weak references so we could call Continue.
AddToNeuterOnContinueList(pAppDomain);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->ExitAppDomain(this, pAppDomain);
}
// @dbgtodo appdomain: This should occur before the callback.
// Even after ExitAppDomain, the outside world will want to continue calling
// Continue (and thus they may need to call CordbAppDomain::GetProcess(), which Neutering
// would clear). Thus we can't neuter yet.
// Remove this app domain. This means any attempt to lookup the AppDomain
// will fail (which we do at the top of this method). Since any threads (incorrectly) referring
// to this AppDomain have been moved to the default AppDomain, no one should be
// interested in looking this AppDomain up anymore.
m_appDomains.RemoveBase(VmPtrToCookie(pEvent->vmAppDomain));
}
break;
case DB_IPCE_LOAD_ASSEMBLY:
{
LOG((LF_CORDB, LL_INFO100,
"RCET::HRCE: load assembly on thread %#x Asm:0x%08x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->AssemblyData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
// Determine if this Assembly is cached.
CordbAssembly * pAssembly = pAppDomain->LookupOrCreateAssembly(pEvent->AssemblyData.vmDomainAssembly);
_ASSERTE(pAssembly != NULL); // throws on error
// If created, or have, an Assembly, notify callback.
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->LoadAssembly(pAppDomain, pAssembly);
}
}
break;
case DB_IPCE_UNLOAD_ASSEMBLY:
{
LOG((LF_CORDB, LL_INFO100, "RCET::DRCE: unload assembly on thread %#x Asm:0x%x AD:0x%x\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->AssemblyData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
CordbAssembly * pAssembly = pAppDomain->LookupOrCreateAssembly(pEvent->AssemblyData.vmDomainAssembly);
if (pAssembly == NULL)
{
// No assembly. This could happen if we attach right before an unload event is sent.
return;
}
_ASSERTE(pAssembly != NULL);
INDEBUG(pAssembly->DbgAssertAssemblyDeleted());
// Ensure the assembly gets neutered when we call continue.
AddToNeuterOnContinueList(pAssembly); // throws
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->UnloadAssembly(pAppDomain, pAssembly);
}
pAppDomain->RemoveAssemblyFromCache(pEvent->AssemblyData.vmDomainAssembly);
}
break;
case DB_IPCE_FUNC_EVAL_COMPLETE:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::DRCE: func eval complete.\n"));
CordbEval *pEval = NULL;
{
pEval = pEvent->FuncEvalComplete.funcEvalKey.UnWrapAndRemove(this);
if (pEval == NULL)
{
_ASSERTE(!"Bogus FuncEval handle in IPC block.");
// Bogus handle in IPC block.
break;
}
}
_ASSERTE(pEval != NULL);
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
CONSISTENCY_CHECK_MSGF(pEval->m_DbgAppDomainStarted == pAppDomain,
("AppDomain changed from Func-Eval. Eval=%p, Started=%p, Now=%p\n",
pEval, pEval->m_DbgAppDomainStarted, (void*) pAppDomain));
// Hold the data about the result in the CordbEval for later.
pEval->m_complete = true;
pEval->m_successful = !!pEvent->FuncEvalComplete.successful;
pEval->m_aborted = !!pEvent->FuncEvalComplete.aborted;
pEval->m_resultAddr = pEvent->FuncEvalComplete.resultAddr;
pEval->m_vmObjectHandle = pEvent->FuncEvalComplete.vmObjectHandle;
pEval->m_resultType = pEvent->FuncEvalComplete.resultType;
pEval->m_resultAppDomainToken = pEvent->FuncEvalComplete.vmAppDomain;
CordbAppDomain *pResultAppDomain = LookupOrCreateAppDomain(pEvent->FuncEvalComplete.vmAppDomain);
_ASSERTE(OutstandingEvalCount() > 0);
DecrementOutstandingEvalCount();
CONSISTENCY_CHECK_MSGF(pEval->m_DbgAppDomainStarted == pAppDomain,
("AppDomain changed from Func-Eval. Eval=%p, Started=%p, Now=%p\n",
pEval, pEval->m_DbgAppDomainStarted, (void*) pAppDomain));
// If we did this func eval with this thread stopped at an excpetion, then we need to pretend as if we
// really didn't continue from the exception, since, of course, we really didn't on the Left Side.
if (pEval->IsEvalDuringException())
{
pThread->SetExInfo(pEval->m_vmThreadOldExceptionHandle);
}
bool fEvalCompleted = pEval->m_successful || pEval->m_aborted;
// If a CallFunction() is aborted, the LHS may not complete the abort
// immediately and hence we cant do a SendCleanup() at that point. Also,
// the debugger may (incorrectly) release the CordbEval before this
// DB_IPCE_FUNC_EVAL_COMPLETE event is received. Hence, we maintain an
// extra ref-count to determine when this can be done.
// Note that this can cause a two-way DB_IPCE_FUNC_EVAL_CLEANUP event
// to be sent. Hence, it has to be done before the Continue (see issue 102745).
// Note that if the debugger has already (incorrectly) released the CordbEval,
// pEval will be pointing to garbage and should not be used by the debugger.
if (fEvalCompleted)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, eval=0x%p. (Complete)", pThread, pEval);
pCallback1->EvalComplete(pResultAppDomain, pThread, pEval);
}
else
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "pThread=0x%p, eval=0x%p. (Exception)", pThread, pEval);
pCallback1->EvalException(pResultAppDomain, pThread, pEval);
}
// This release may send an DB_IPCE_FUNC_EVAL_CLEANUP IPC event. That's ok b/c
// we're still synced even if if Continue was called inside the callback.
// That's because the StopContinueHolder bumped up the stopcount.
// Corresponding AddRef() in CallFunction().
// @todo - this is leaked if we don't get an EvalComplete event (eg, process exits with
// in middle of func-eval).
pEval->Release();
}
break;
case DB_IPCE_NAME_CHANGE:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::HRCE: Name Change %d 0x%p\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->NameChange.vmAppDomain)));
pThread = NULL;
pAppDomain.Clear();
if (pEvent->NameChange.eventType == THREAD_NAME_CHANGE)
{
// Lookup the CordbThread that matches this runtime thread.
if (!pEvent->NameChange.vmThread.IsNull())
{
pThread = LookupOrCreateThread(pEvent->NameChange.vmThread);
}
}
else
{
_ASSERTE (pEvent->NameChange.eventType == APP_DOMAIN_NAME_CHANGE);
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->NameChange.vmAppDomain));
if (pAppDomain)
{
pAppDomain->InvalidateName();
}
}
if (pThread || pAppDomain)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->NameChange(pAppDomain, pThread);
}
}
break;
case DB_IPCE_UPDATE_MODULE_SYMS:
{
RSExtSmartPtr<IStream> pStream;
// Find the app domain the module lives in.
_ASSERTE (pAppDomain != NULL);
// Find the Right Side module for this module.
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->UpdateModuleSymsData.vmDomainAssembly);
_ASSERTE(pModule != NULL);
// This is a legacy event notification for updated PDBs.
// Creates a new IStream object. Ownership is handed off via callback.
IDacDbiInterface::SymbolFormat symFormat = pModule->GetInMemorySymbolStream(&pStream);
// We shouldn't get this event if there aren't PDB symbols waiting. Specifically we don't want
// to incur the cost of copying over ILDB symbols here without the debugger asking for them.
// Eventually we may remove this callback as well and always rely on explicit requests.
_ASSERTE(symFormat == IDacDbiInterface::kSymbolFormatPDB);
if (symFormat == IDacDbiInterface::kSymbolFormatPDB)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
_ASSERTE(pStream != NULL); // Shouldn't send the event if we don't have a stream.
pCallback1->UpdateModuleSymbols(pAppDomain, pModule, pStream);
}
}
break;
case DB_IPCE_MDA_NOTIFICATION:
{
RSInitHolder<CordbMDA> pMDA(new CordbMDA(this, &pEvent->MDANotification)); // throws
// Ctor leaves both internal + ext Ref at 0, adding to neuter list bumps int-ref up to 1.
// Neutering will dump it back down to zero.
this->AddToNeuterOnExitList(pMDA);
// We bump up and down the external ref so that even if the callback doensn't touch the refs,
// our Ext-Release here will still cause a 1->0 ext-ref transition, which will get it
// swept on the neuter list.
RSExtSmartPtr<ICorDebugMDA> pExternalMDARef;
pMDA.TransferOwnershipExternal(&pExternalMDARef);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->MDANotification(
this,
pThread, // may be null
pExternalMDARef);
// pExternalMDARef's dtor will do an external release,
// which is very significant because it may be the one that does the 1->0 ext ref transition,
// which may mean cause the "NeuterAtWill" bit to get flipped on this CordbMDA object.
// Since this is an external release, do it in the PUBLIC_CALLBACK scope.
pExternalMDARef.Clear();
}
break;
}
case DB_IPCE_CONTROL_C_EVENT:
{
hr = S_FALSE;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->ControlCTrap((ICorDebugProcess*) this);
}
}
break;
// EnC Remap opportunity
case DB_IPCE_ENC_REMAP:
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: EnC Remap!.\n",
GetCurrentThreadId()));
_ASSERTE(NULL != pAppDomain);
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->EnCRemap.vmDomainAssembly);
PREFIX_ASSUME(pModule != NULL);
CordbFunction * pCurFunction = NULL;
CordbFunction * pResumeFunction = NULL;
// lookup the version of the function that we are mapping from
// this is the one that is currently running
pCurFunction = pModule->LookupOrCreateFunction(
pEvent->EnCRemap.funcMetadataToken, pEvent->EnCRemap.currentVersionNumber);
// lookup the version of the function that we are mapping to
// it will always be the most recent
pResumeFunction = pModule->LookupOrCreateFunction(
pEvent->EnCRemap.funcMetadataToken, pEvent->EnCRemap.resumeVersionNumber);
_ASSERTE(pCurFunction->GetEnCVersionNumber() < pResumeFunction->GetEnCVersionNumber());
RSSmartPtr<CordbFunction> pRefCurFunction(pCurFunction);
RSSmartPtr<CordbFunction> pRefResumeFunction(pResumeFunction);
// Verify we're not about to overwrite an outstanding remap IP
// This should only be set while a remap opportunity is being handled,
// and cleared (by CordbThread::MarkStackFramesDirty) on Continue.
// We want to be absolutely sure we don't accidentally keep a stale pointer
// around because it would point to arbitrary stack space in the CLR potentially
// leading to stack corruption.
_ASSERTE( pThread->m_EnCRemapFunctionIP == NULL );
// Stash the address of the remap IP buffer. This indicates that calling
// RemapFunction is valid and provides a communications channel between the RS
// and LS for the remap IL offset.
pThread->m_EnCRemapFunctionIP = pEvent->EnCRemap.resumeILOffset;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->FunctionRemapOpportunity(
pAppDomain,
pThread,
pCurFunction,
pResumeFunction,
(ULONG32)pEvent->EnCRemap.currentILOffset);
}
// Implicit release on pCurFunction and pResumeFunction.
}
break;
// EnC Remap complete
case DB_IPCE_ENC_REMAP_COMPLETE:
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: EnC Remap Complete!.\n",
GetCurrentThreadId()));
_ASSERTE(NULL != pAppDomain);
CordbModule* pModule = pAppDomain->LookupOrCreateModule(pEvent->EnCRemap.vmDomainAssembly);
PREFIX_ASSUME(pModule != NULL);
// Find the function we're remapping to, which must be the latest version
CordbFunction *pRemapFunction=
pModule->LookupFunctionLatestVersion(pEvent->EnCRemapComplete.funcMetadataToken);
PREFIX_ASSUME(pRemapFunction != NULL);
// Dispatch the FunctionRemapComplete callback
RSSmartPtr<CordbFunction> pRef(pRemapFunction);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->FunctionRemapComplete(pAppDomain, pThread, pRemapFunction);
}
// Implicit release on pRemapFunction via holder
}
break;
case DB_IPCE_BREAKPOINT_SET_ERROR:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::DRCE: breakpoint set error.\n"));
RSSmartPtr<CordbBreakpoint> pRef;
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// Find the breakpoint object on this side.
CordbBreakpoint * pBreakpoint = NULL;
if (pThread == NULL)
{
// We've found cases out in the wild where we get this event on a thread we don't recognize.
// We're not sure how this happens. Add a runtime check to protect ourselves to avoid the
// an AV. We still assert because this should not be happening.
// It likely means theres some issue where we failed to send a CreateThread notification.
STRESS_LOG1(LF_CORDB, LL_INFO1000, "BreakpointSetError on unrecognized thread. %p\n", pBreakpoint);
_ASSERTE(!"Missing thread on bp set error");
break;
}
pBreakpoint = pAppDomain->m_breakpoints.GetBase(LsPtrToCookie(pEvent->BreakpointSetErrorData.breakpointToken));
if (pBreakpoint != NULL)
{
ICorDebugBreakpoint * pIBreakpoint = CordbBreakpointToInterface(pBreakpoint);
_ASSERTE(pIBreakpoint != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, bp=0x%p", pThread, pBreakpoint);
pCallback1->BreakpointSetError(pAppDomain, pThread, pIBreakpoint, 0);
}
}
// Implicit release on pRef.
}
break;
case DB_IPCE_EXCEPTION_CALLBACK2:
{
STRESS_LOG4(LF_CORDB, LL_INFO100,
"RCET::DRCE: Exception2 0x%p 0x%X 0x%X 0x%X\n",
pEvent->ExceptionCallback2.framePointer.GetSPValue(),
pEvent->ExceptionCallback2.nOffset,
pEvent->ExceptionCallback2.eventType,
pEvent->ExceptionCallback2.dwFlags
);
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This could be a thread that
// has never run any managed code, so let's just ignore the exception. We should have
// already sent a log message about this situation for the EXCEPTION callback above.
_ASSERTE( pEvent->ExceptionCallback2.eventType == DEBUG_EXCEPTION_UNHANDLED );
break;
}
pThread->SetExInfo(pEvent->ExceptionCallback2.vmExceptionHandle);
//
// Send all the information back to the debugger.
//
RSSmartPtr<CordbFrame> pFrame;
FramePointer fp = pEvent->ExceptionCallback2.framePointer;
if (fp != LEAF_MOST_FRAME)
{
// The interface forces us to to pass a FramePointer via an ICorDebugFrame.
// However, we can't get a real ICDFrame without a stackwalk, and we don't
// want to do a stackwalk now. so pass a netuered proxy frame. The shim
// can map this to a real frame.
// See comments at CordbPlaceHolderFrame class for details.
pFrame.Assign(new CordbPlaceholderFrame(this, fp));
}
CorDebugExceptionCallbackType type = pEvent->ExceptionCallback2.eventType;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE3(this, pLockHolder, pEvent, "pThread=0x%p, frame=%p, type=%d", pThread, (ICorDebugFrame*) pFrame, type);
hr = pCallback2->Exception(
pThread->m_pAppDomain,
pThread,
pFrame,
(ULONG32)(pEvent->ExceptionCallback2.nOffset),
type,
pEvent->ExceptionCallback2.dwFlags);
}
}
break;
case DB_IPCE_EXCEPTION_UNWIND:
{
STRESS_LOG2(LF_CORDB, LL_INFO100,
"RCET::DRCE: Exception Unwind 0x%X 0x%X\n",
pEvent->ExceptionCallback2.eventType,
pEvent->ExceptionCallback2.dwFlags
);
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This probably should never
// happen (if it's unwinding, then we expect a managed frame on the stack, and so we should
// know about the thread), but if it does fall back to ignoring the exception.
_ASSERTE( !"Got unwind event for unknown exception" );
break;
}
//
// Send all the information back to the debugger.
//
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "pThread=0x%p", pThread);
hr = pCallback2->ExceptionUnwind(
pThread->m_pAppDomain,
pThread,
pEvent->ExceptionUnwind.eventType,
pEvent->ExceptionUnwind.dwFlags);
}
}
break;
case DB_IPCE_INTERCEPT_EXCEPTION_COMPLETE:
{
STRESS_LOG0(LF_CORDB, LL_INFO100, "RCET::DRCE: Exception Interception Complete.\n");
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This probably should never
// happen (if it's unwinding, then we expect a managed frame on the stack, and so we should
// know about the thread), but if it does fall back to ignoring the exception.
_ASSERTE( !"Got complete event for unknown exception" );
break;
}
//
// Tell the debugger that the exception has been intercepted. This is similar to the
// notification we give when we start unwinding for a non-intercepted exception, except that the
// interception has been completed at this point, which means that we are conceptually at the end
// of the second pass.
//
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "pThread=0x%p", pThread);
hr = pCallback2->ExceptionUnwind(
pThread->m_pAppDomain,
pThread,
DEBUG_EXCEPTION_INTERCEPTED,
0);
}
}
break;
#ifdef TEST_DATA_CONSISTENCY
case DB_IPCE_TEST_CRST:
{
EX_TRY
{
// the left side has signaled that we should test whether pEvent->TestCrstData.vmCrst is held
GetDAC()->TestCrst(pEvent->TestCrstData.vmCrst);
}
EX_CATCH_HRESULT(hr);
if (pEvent->TestCrstData.fOkToTake)
{
_ASSERTE(hr == S_OK);
if (hr != S_OK)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
else // the lock was already held
{
// see if we threw because the lock was held
_ASSERTE(hr == CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
if (hr != CORDBG_E_PROCESS_NOT_SYNCHRONIZED)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
}
break;
case DB_IPCE_TEST_RWLOCK:
{
EX_TRY
{
// the left side has signaled that we should test whether pEvent->TestRWLockData.vmRWLock is held
GetDAC()->TestRWLock(pEvent->TestRWLockData.vmRWLock);
}
EX_CATCH_HRESULT(hr);
if (pEvent->TestRWLockData.fOkToTake)
{
_ASSERTE(hr == S_OK);
if (hr != S_OK)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
else // the lock was already held
{
// see if we threw because the lock was held
_ASSERTE(hr == CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
if (hr != CORDBG_E_PROCESS_NOT_SYNCHRONIZED)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
}
break;
#endif
default:
_ASSERTE(!"Unknown event");
LOG((LF_CORDB, LL_INFO1000,
"[%x] RCET::HRCE: Unknown event: 0x%08x\n",
GetCurrentThreadId(), pEvent->type));
}
FinishEventDispatch();
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
//---------------------------------------------------------------------------------------
// Callback for prepopulating threads.
//
// Arugments:
// vmThread - thread as part of the eunmeration.
// pUserData - data supplied with callback. It's a CordbProcess* object.
//
// static
void CordbProcess::ThreadEnumerationCallback(VMPTR_Thread vmThread, void * pUserData)
{
CordbProcess * pThis = reinterpret_cast<CordbProcess *> (pUserData);
INTERNAL_DAC_CALLBACK(pThis);
STRESS_LOG0(LF_CORDB, LL_INFO1000, "ThreadEnumerationCallback()\n");
// Do lookup / lazy-create.
pThis->LookupOrCreateThread(vmThread);
}
//---------------------------------------------------------------------------------------
// Fully build up the CordbThread cache to match VM state.
void CordbProcess::PrepopulateThreadsOrThrow()
{
RSLockHolder lockHolder(GetProcessLock());
if (IsDacInitialized())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "PrepopulateThreadsOrThrow()\n");
GetDAC()->EnumerateThreads(ThreadEnumerationCallback, this);
}
}
//---------------------------------------------------------------------------------------
// Create a Thread enumerator
//
// Arguments:
// pOwnerObj - object (a CordbProcess or CordbThread) that will own the enumerator.
// pOwnerList - the neuter list that the enumerator will live on
// pHolder - an outparameter for the enumerator to be initialized.
//
void CordbProcess::BuildThreadEnum(CordbBase * pOwnerObj, NeuterList * pOwnerList, RSInitHolder<CordbHashTableEnum> * pHolder)
{
CordbHashTableEnum::BuildOrThrow(
pOwnerObj,
pOwnerList,
&m_userThreads,
IID_ICorDebugThreadEnum,
pHolder);
}
// Public implementation of ICorDebugProcess::EnumerateThreads
HRESULT CordbProcess::EnumerateThreads(ICorDebugThreadEnum **ppThreads)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
if (m_detached)
{
// #Detach_Check:
//
// FUTURE: Consider adding this IF block to the PUBLIC_API macros so that
// typical public APIs fail quickly if we're trying to do a detach. For
// now, I'm hand-adding this check only to the few problematic APIs that get
// called while queuing the fake attach events. In these cases, it is not
// enough to check if CordbProcess::IsNeutered(), as the detaching thread
// may have begun the detaching and neutering process, but not be
// finished--in which case m_detached is true, but
// CordbProcess::IsNeutered() is still false.
ThrowHR(CORDBG_E_PROCESS_DETACHED);
}
ValidateOrThrow(ppThreads);
RSInitHolder<CordbHashTableEnum> pEnum;
InternalEnumerateThreads(pEnum.GetAddr());
pEnum.TransferOwnershipExternal(ppThreads);
}
PUBLIC_API_END(hr);
return hr;
}
// Internal implementation of EnumerateThreads
VOID CordbProcess::InternalEnumerateThreads(RSInitHolder<CordbHashTableEnum> *ppThreads)
{
INTERNAL_API_ENTRY(this);
// Needs to prepopulate
PrepopulateThreadsOrThrow();
BuildThreadEnum(this, this->GetContinueNeuterList(), ppThreads);
}
// Implementation of ICorDebugProcess::GetThread
HRESULT CordbProcess::GetThread(DWORD dwThreadId, ICorDebugThread **ppThread)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppThread, ICorDebugThread **);
// No good pre-existing ATT_* contract for this.
// Because for legacy, we have to allow this on the win32 event thread.
*ppThread = NULL;
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
if (m_detached)
{
// See code:CordbProcess::EnumerateThreads#Detach_Check
ThrowHR(CORDBG_E_PROCESS_DETACHED);
}
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
if (pThread == NULL)
{
// This is a common case because we may be looking up an unmanaged thread.
hr = E_INVALIDARG;
}
else
{
*ppThread = static_cast<ICorDebugThread*> (pThread);
pThread->ExternalAddRef();
}
}
EX_CATCH_HRESULT(hr);
LOG((LF_CORDB, LL_INFO10000, "CP::GT returns id=0x%x hr=0x%x ppThread=0x%p",
dwThreadId, hr, *ppThread));
return hr;
}
HRESULT CordbProcess::ThreadForFiberCookie(DWORD fiberCookie,
ICorDebugThread **ppThread)
{
return E_NOTIMPL;
}
HRESULT CordbProcess::GetHelperThreadID(DWORD *pThreadID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
_ASSERTE(m_pShim != NULL);
if (pThreadID == NULL)
{
return (E_INVALIDARG);
}
HRESULT hr = S_OK;
// Return the ID of the current helper thread. There may be no thread in the process, or there may be a true helper
// thread.
if ((m_helperThreadId != 0) && !m_helperThreadDead)
{
*pThreadID = m_helperThreadId;
}
else if ((GetDCB() != NULL) && (GetDCB()->m_helperThreadId != 0))
{
EX_TRY
{
// be sure we have the latest information
UpdateRightSideDCB();
*pThreadID = GetDCB()->m_helperThreadId;
}
EX_CATCH_HRESULT(hr);
}
else
{
*pThreadID = 0;
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Sends IPC event to set all the managed threads, except for the one given, to the given state
//
// Arguments:
// state - The state to set the threads to.
// pExceptThread - The thread to not set. This is usually the thread that is currently
// sending an IPC event to the RS, and should be excluded.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
HRESULT CordbProcess::SetAllThreadsDebugState(CorDebugThreadState state,
ICorDebugThread * pExceptThread)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pExceptThread, ICorDebugThread *);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
if (GetShim() == NULL)
{
return E_NOTIMPL;
}
CordbThread * pCordbExceptThread = static_cast<CordbThread *> (pExceptThread);
LOG((LF_CORDB, LL_INFO1000, "CP::SATDS: except thread=0x%08x 0x%x\n",
pExceptThread,
(pCordbExceptThread != NULL) ? pCordbExceptThread->m_id : 0));
// Send one event to the Left Side to twiddle each thread's state.
DebuggerIPCEvent event;
InitIPCEvent(&event, DB_IPCE_SET_ALL_DEBUG_STATE, true, VMPTR_AppDomain::NullPtr());
event.SetAllDebugState.vmThreadToken = ((pCordbExceptThread != NULL) ?
pCordbExceptThread->m_vmThreadToken : VMPTR_Thread::NullPtr());
event.SetAllDebugState.debugState = state;
HRESULT hr = SendIPCEvent(&event, sizeof(DebuggerIPCEvent));
hr = WORST_HR(hr, event.hr);
// If that worked, then loop over all the threads on this side and set their states.
if (SUCCEEDED(hr))
{
RSLockHolder lockHolder(GetProcessLock());
HASHFIND hashFind;
CordbThread * pThread;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (pThread = m_userThreads.FindFirst(&hashFind);
pThread != NULL;
pThread = m_userThreads.FindNext(&hashFind))
{
if (pThread != pCordbExceptThread)
{
pThread->m_debugState = state;
}
}
}
return hr;
}
HRESULT CordbProcess::EnumerateObjects(ICorDebugObjectEnum **ppObjects)
{
/* !!! */
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppObjects, ICorDebugObjectEnum **);
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Determines if the target address is a "CLR transition stub".
//
// Arguments:
// address - The address of an instruction to check in the target address space.
// pfTransitionStub - Space to store the result, TRUE if the address belongs to a
// transition stub, FALSE if not. Only valid if this method returns a success code.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::IsTransitionStub(CORDB_ADDRESS address, BOOL *pfTransitionStub)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pfTransitionStub, BOOL *);
// Default to FALSE
*pfTransitionStub = FALSE;
if (this->m_helperThreadDead)
{
return S_OK;
}
// If we're not initialized, then it can't be a stub...
if (!m_initialized)
{
return S_OK;
}
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
EX_TRY
{
DebuggerIPCEvent eventData;
InitIPCEvent(&eventData, DB_IPCE_IS_TRANSITION_STUB, true, VMPTR_AppDomain::NullPtr());
eventData.IsTransitionStub.address = CORDB_ADDRESS_TO_PTR(address);
hr = SendIPCEvent(&eventData, sizeof(eventData));
hr = WORST_HR(hr, eventData.hr);
IfFailThrow(hr);
_ASSERTE(eventData.type == DB_IPCE_IS_TRANSITION_STUB_RESULT);
*pfTransitionStub = eventData.IsTransitionStubResult.isStub;
LOG((LF_CORDB, LL_INFO1000, "CP::ITS: addr=0x%p result=%d\n", address, *pfTransitionStub));
// @todo - beware that IsTransitionStub has a very important sideeffect - it synchronizes the runtime!
// This for example covers an OS bug where SetThreadContext may silently fail if we're not synchronized.
// (See IMDArocess::SetThreadContext for details on that bug).
// If we ever stop using IPC events here and only use DAC; we need to be aware of that.
// Check against DAC primitives
{
BOOL fIsStub2 = GetDAC()->IsTransitionStub(address);
(void)fIsStub2; //prevent "unused variable" error from GCC
CONSISTENCY_CHECK_MSGF(*pfTransitionStub == fIsStub2, ("IsStub2 failed, DAC2:%d, IPC:%d, addr:0x%p", (int) fIsStub2, (int) *pfTransitionStub, CORDB_ADDRESS_TO_PTR(address)));
}
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::ITS: FAILED hr=0x%x\n", hr));
}
return hr;
}
HRESULT CordbProcess::SetStopState(DWORD threadID, CorDebugThreadState state)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return E_NOTIMPL;
}
HRESULT CordbProcess::IsOSSuspended(DWORD threadID, BOOL *pbSuspended)
{
PUBLIC_API_ENTRY(this);
// Gotta have a place for the result!
if (!pbSuspended)
return E_INVALIDARG;
FAIL_IF_NEUTERED(this);
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
// Have we seen this thread?
CordbUnmanagedThread *ut = GetUnmanagedThread(threadID);
// If we have, and if we've suspended it, then say so.
if (ut && ut->IsSuspended())
{
*pbSuspended = TRUE;
}
else
{
*pbSuspended = FALSE;
}
#else
// Not interop-debugging, we never OS suspend.
*pbSuspended = FALSE;
#endif
return S_OK;
}
//
// This routine reads a thread context from the process being debugged, taking into account the fact that the context
// record may be a different size than the one we compiled with. On systems < NT5, then OS doesn't usually allocate
// space for the extended registers. However, the CONTEXT struct that we compile with does have this space.
//
HRESULT CordbProcess::SafeReadThreadContext(LSPTR_CONTEXT pContext, DT_CONTEXT * pCtx)
{
HRESULT hr = S_OK;
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
EX_TRY
{
void *pRemoteContext = pContext.UnsafeGet();
TargetBuffer tbFull(pRemoteContext, sizeof(DT_CONTEXT));
// The context may have 2 parts:
// 1. Base register, which are always present.
// 2. Optional extended registers, which are only present if CONTEXT_EXTENDED_REGISTERS is set
// in the flags.
// At a minimum we have room for a whole context up to the extended registers.
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
ULONG32 minContextSize = offsetof(DT_CONTEXT, ExtendedRegisters);
#else
ULONG32 minContextSize = sizeof(DT_CONTEXT);
#endif
// Read the minimum part.
TargetBuffer tbMin = tbFull.SubBuffer(0, minContextSize);
SafeReadBuffer(tbMin, (BYTE*) pCtx);
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
void *pCurExtReg = (void*)((UINT_PTR)pCtx + minContextSize);
TargetBuffer tbExtended = tbFull.SubBuffer(minContextSize);
// Now, read the extended registers if the context contains them. If the context does not have extended registers,
// just set them to zero.
if (SUCCEEDED(hr) && (pCtx->ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS)
{
SafeReadBuffer(tbExtended, (BYTE*) pCurExtReg);
}
else
{
memset(pCurExtReg, 0, tbExtended.cbSize);
}
#endif
}
EX_CATCH_HRESULT(hr);
return hr;
}
//
// This routine writes a thread context to the process being debugged, taking into account the fact that the context
// record may be a different size than the one we compiled with. On systems < NT5, then OS doesn't usually allocate
// space for the extended registers. However, the CONTEXT struct that we compile with does have this space.
//
HRESULT CordbProcess::SafeWriteThreadContext(LSPTR_CONTEXT pContext, const DT_CONTEXT * pCtx)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
DWORD sizeToWrite = sizeof(DT_CONTEXT);
BYTE * pRemoteContext = (BYTE*) pContext.UnsafeGet();
BYTE * pCtxSource = (BYTE*) pCtx;
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
// If our context has extended registers, then write the whole thing. Otherwise, just write the minimum part.
if ((pCtx->ContextFlags & DT_CONTEXT_EXTENDED_REGISTERS) != DT_CONTEXT_EXTENDED_REGISTERS)
{
sizeToWrite = offsetof(DT_CONTEXT, ExtendedRegisters);
}
#endif
// 64 bit windows puts space for the first 6 stack parameters in the CONTEXT structure so that
// kernel to usermode transitions don't have to allocate a CONTEXT and do a seperate sub rsp
// to allocate stack spill space for the arguments. This means that writing to P1Home - P6Home
// will overwrite the arguments of some function higher on the stack, very bad. Conceptually you
// can think of these members as not being part of the context, ie they don't represent something
// which gets saved or restored on context switches. They are just space we shouldn't overwrite.
// See issue 630276 for more details.
#if defined TARGET_AMD64
pRemoteContext += offsetof(CONTEXT, ContextFlags); // immediately follows the 6 parameters P1-P6
pCtxSource += offsetof(CONTEXT, ContextFlags);
sizeToWrite -= offsetof(CONTEXT, ContextFlags);
#endif
EX_TRY
{
// Write the context.
TargetBuffer tb(pRemoteContext, sizeToWrite);
SafeWriteBuffer(tb, (const BYTE*) pCtxSource);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetThreadContext(DWORD threadID, ULONG32 contextSize, BYTE context[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x\n", threadID));
DT_CONTEXT * pContext;
if (contextSize != sizeof(DT_CONTEXT))
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, context size is invalid.\n", threadID));
return E_INVALIDARG;
}
pContext = reinterpret_cast<DT_CONTEXT *>(context);
VALIDATE_POINTER_TO_OBJECT_ARRAY(context, BYTE, contextSize, true, true);
if (this->IsInteropDebugging())
{
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
// Find the unmanaged thread
CordbUnmanagedThread *ut = GetUnmanagedThread(threadID);
if (ut == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
return E_INVALIDARG;
}
return ut->GetThreadContext((DT_CONTEXT*)context);
#else
return E_NOTIMPL;
#endif
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder lockHolder(GetProcessLock());
HRESULT hr = S_OK;
EX_TRY
{
CordbThread* thread = this->TryLookupThreadByVolatileOSId(threadID);
if (thread == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
hr = E_INVALIDARG;
}
else
{
DT_CONTEXT* managedContext;
hr = thread->GetManagedContext(&managedContext);
*pContext = *managedContext;
}
}
EX_CATCH_HRESULT(hr)
return hr;
}
}
// Public implementation of ICorDebugProcess::SetThreadContext.
// @dbgtodo interop-debugging: this should go away in V3. Use the data-target instead. This is
// interop-debugging aware (and cooperates with hijacks)
HRESULT CordbProcess::SetThreadContext(DWORD threadID, ULONG32 contextSize, BYTE context[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
HRESULT hr = S_OK;
// @todo - could we look at the context flags and return E_INVALIDARG if they're bad?
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_ARRAY(context, BYTE, contextSize, true, true);
if (contextSize != sizeof(DT_CONTEXT))
{
LOG((LF_CORDB, LL_INFO10000, "CP::STC: thread=0x%x, context size is invalid.\n", threadID));
return E_INVALIDARG;
}
DT_CONTEXT* pContext = (DT_CONTEXT*)context;
if (this->IsInteropDebugging())
{
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
CordbUnmanagedThread *ut = NULL;
// Find the unmanaged thread
ut = GetUnmanagedThread(threadID);
if (ut == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::STC: thread=0x%x, thread is invalid.\n", threadID));
return E_INVALIDARG;
}
hr = ut->SetThreadContext(pContext);
// Update the register set for the leaf-unmanaged chain so that it's consistent w/ the context.
// We may not necessarily be synchronized, and so these frames may be stale. Even so, no harm done.
if (SUCCEEDED(hr))
{
// @dbgtodo stackwalk: this should all disappear with V3 stackwalker and getting rid of SetThreadContext.
EX_TRY
{
// Find the managed thread. Returns NULL if thread is not managed.
// If we don't have a thread prveiously cached, then there's no state to update.
CordbThread * pThread = TryLookupThreadByVolatileOSId(threadID);
if (pThread != NULL)
{
// In V2, we used to update the CONTEXT of the leaf chain if the chain is an unmanaged chain.
// In Arrowhead, we just force a cleanup of the stackwalk cache. This is a more correct
// thing to do anyway, since the CONTEXT being set could be anything.
pThread->CleanupStack();
}
}
EX_CATCH_HRESULT(hr);
}
#else
return E_NOTIMPL;
#endif
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder lockHolder(GetProcessLock());
EX_TRY
{
CordbThread* thread = this->TryLookupThreadByVolatileOSId(threadID);
if (thread == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
hr = E_INVALIDARG;
}
hr = thread->SetManagedContext(pContext);
}
EX_CATCH
{
hr = E_FAIL;
}
EX_END_CATCH(SwallowAllExceptions)
}
return hr;
}
// @dbgtodo ICDProcess - When we DACize this function, we should use code:DacReplacePatches
HRESULT CordbProcess::ReadMemory(CORDB_ADDRESS address,
DWORD size,
BYTE buffer[],
SIZE_T *read)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
// A read of 0 bytes is okay.
if (size == 0)
return S_OK;
VALIDATE_POINTER_TO_OBJECT_ARRAY(buffer, BYTE, size, true, true);
VALIDATE_POINTER_TO_OBJECT(buffer, SIZE_T *);
if (address == NULL)
return E_INVALIDARG;
// If no read parameter is supplied, we ignore it. This matches the semantics of kernel32!ReadProcessMemory.
SIZE_T dummyRead;
if (read == NULL)
{
read = &dummyRead;
}
*read = 0;
HRESULT hr = S_OK;
CORDBRequireProcessStateOK(this);
// Grab the memory we want to read
// Note that this will return success on a partial read
ULONG32 cbRead;
hr = GetDataTarget()->ReadVirtual(address, buffer, size, &cbRead);
if (FAILED(hr))
{
hr = CORDBG_E_READVIRTUAL_FAILURE;
goto LExit;
}
// Read at least one byte
*read = (SIZE_T) cbRead;
// There seem to be strange cases where ReadProcessMemory will return a seemingly negative number into *read, which
// is an unsigned value. So we check the sanity of *read by ensuring that its no bigger than the size we tried to
// read.
if ((*read > 0) && (*read <= size))
{
LOG((LF_CORDB, LL_INFO100000, "CP::RM: read %d bytes from 0x%08x, first byte is 0x%x\n",
*read, (DWORD)address, buffer[0]));
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
// If m_pPatchTable is NULL, then it's been cleaned out b/c of a Continue for the left side. Get the table
// again. Only do this, of course, if the managed state of the process is initialized.
if (m_pPatchTable == NULL)
{
hr = RefreshPatchTable(address, *read, buffer);
}
else
{
// The previously fetched table is still good, so run through it & see if any patches are applicable
hr = AdjustBuffer(address, *read, buffer, NULL, AB_READ);
}
}
}
LExit:
if (FAILED(hr))
{
RSLockHolder ch(&this->m_processMutex);
ClearPatchTable();
}
else if (*read < size)
{
// Unlike the DT api, our API is supposed to return an error on partial read
hr = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
return hr;
}
// Update patches & buffer to make the left-side's usage of patches transparent
// to our client. Behavior depends on AB_MODE:
// AB_READ:
// - use the RS patch table structure to replace patch opcodes in buffer.
// AB_WRITE:
// - update the RS patch table structure w/ new replace-opcode values
// if we've written over them. And put the int3 back in for write-memory.
//
// Note: If we're writing memory over top of a patch, then it must be JITted or stub code.
// Writing over JITed or Stub code can be dangerous since the CLR may not expect it
// (eg. JIT data structures about the code layout may be incorrect), but in certain
// narrow cases it may be safe (eg. replacing a constant). VS says they wouldn't expect
// this to work, but we'll keep the support in for legacy reasons.
//
// address, size - describe buffer in LS memory
// buffer - local copy of buffer that will be read/written from/to LS.
// bufferCopy - for writeprocessmemory, copy of original buffer (w/o injected patches)
// pbUpdatePatchTable - flag if patchtable got dirty and needs to be updated.
HRESULT CordbProcess::AdjustBuffer( CORDB_ADDRESS address,
SIZE_T size,
BYTE buffer[],
BYTE **bufferCopy,
AB_MODE mode,
BOOL *pbUpdatePatchTable)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
if ( address == NULL
|| size == NULL
|| buffer == NULL
|| (mode != AB_READ && mode != AB_WRITE) )
return E_INVALIDARG;
if (pbUpdatePatchTable != NULL )
*pbUpdatePatchTable = FALSE;
// If we don't have a patch table loaded, then return S_OK since there are no patches to adjust
if (m_pPatchTable == NULL)
return S_OK;
//is the requested memory completely out-of-range?
if ((m_minPatchAddr > (address + (size - 1))) ||
(m_maxPatchAddr < address))
{
return S_OK;
}
// Without runtime offsets, we can't adjust - this should only ever happen on dumps, where there's
// no W32ET to get the offsets, and so they stay zeroed
if (!m_runtimeOffsetsInitialized)
return S_OK;
LOG((LF_CORDB,LL_INFO10000, "CordbProcess::AdjustBuffer at addr 0x%p\n", address));
if (mode == AB_WRITE)
{
// We don't want to mess up the original copy of the buffer, so
// for right now, just copy it wholesale.
(*bufferCopy) = new (nothrow) BYTE[size];
if (NULL == (*bufferCopy))
return E_OUTOFMEMORY;
memmove((*bufferCopy), buffer, size);
}
ULONG iNextFree = m_iFirstPatch;
while( iNextFree != DPT_TERMINATING_INDEX )
{
BYTE *DebuggerControllerPatch = m_pPatchTable + m_runtimeOffsets.m_cbPatch*iNextFree;
PRD_TYPE opcode = *(PRD_TYPE *)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode);
CORDB_ADDRESS patchAddress = PTR_TO_CORDB_ADDRESS(*(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr));
if (IsPatchInRequestedRange(address, size, patchAddress))
{
if (mode == AB_READ)
{
CORDbgSetInstructionEx(buffer, address, patchAddress, opcode, size);
}
else if (mode == AB_WRITE)
{
_ASSERTE( pbUpdatePatchTable != NULL );
_ASSERTE( bufferCopy != NULL );
//There can be multiple patches at the same address: we don't want 2nd+ patches to get the
// break opcode, so we read from the unmodified copy.
m_rgUncommitedOpcode[iNextFree] =
CORDbgGetInstructionEx(*bufferCopy, address, patchAddress, opcode, size);
//put the breakpoint into the memory itself
CORDbgInsertBreakpointEx(buffer, address, patchAddress, opcode, size);
*pbUpdatePatchTable = TRUE;
}
else
_ASSERTE( !"CordbProcess::AdjustBuffergiven non(Read|Write) mode!" );
}
iNextFree = m_rgNextPatch[iNextFree];
}
// If we created a copy of the buffer but didn't modify it, then free it now.
if( ( mode == AB_WRITE ) && ( !*pbUpdatePatchTable ) )
{
delete [] *bufferCopy;
*bufferCopy = NULL;
}
return S_OK;
}
void CordbProcess::CommitBufferAdjustments( CORDB_ADDRESS start,
CORDB_ADDRESS end )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
_ASSERTE(m_runtimeOffsetsInitialized);
ULONG iPatch = m_iFirstPatch;
while( iPatch != DPT_TERMINATING_INDEX )
{
BYTE *DebuggerControllerPatch = m_pPatchTable +
m_runtimeOffsets.m_cbPatch*iPatch;
BYTE *patchAddress = *(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr);
if (IsPatchInRequestedRange(start, (SIZE_T)(end - start), PTR_TO_CORDB_ADDRESS(patchAddress)) &&
!PRDIsBreakInst(&(m_rgUncommitedOpcode[iPatch])))
{
//copy this back to the copy of the patch table
*(PRD_TYPE *)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode) =
m_rgUncommitedOpcode[iPatch];
}
iPatch = m_rgNextPatch[iPatch];
}
}
void CordbProcess::ClearBufferAdjustments( )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(this->ThreadHoldsProcessLock());
ULONG iPatch = m_iFirstPatch;
while( iPatch != DPT_TERMINATING_INDEX )
{
InitializePRDToBreakInst(&(m_rgUncommitedOpcode[iPatch]));
iPatch = m_rgNextPatch[iPatch];
}
}
void CordbProcess::ClearPatchTable(void )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(this->ThreadHoldsProcessLock());
if (m_pPatchTable != NULL )
{
delete [] m_pPatchTable;
m_pPatchTable = NULL;
delete [] m_rgNextPatch;
m_rgNextPatch = NULL;
delete [] m_rgUncommitedOpcode;
m_rgUncommitedOpcode = NULL;
m_iFirstPatch = DPT_TERMINATING_INDEX;
m_minPatchAddr = MAX_ADDRESS;
m_maxPatchAddr = MIN_ADDRESS;
m_rgData = NULL;
m_cPatch = 0;
}
}
HRESULT CordbProcess::RefreshPatchTable(CORDB_ADDRESS address, SIZE_T size, BYTE buffer[])
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
HRESULT hr = S_OK;
BYTE *rgb = NULL;
// All of m_runtimeOffsets will be zeroed out if there's been no call to code:CordbProcess::GetRuntimeOffsets.
// Thus for things to work, we'd have to have a live target that went and got the real values.
// For dumps, things are still all zeroed out because we don't have any events sent to the W32ET, don't
// have a live process to investigate, etc.
if (!m_runtimeOffsetsInitialized)
return S_OK;
_ASSERTE( m_runtimeOffsets.m_cbOpcode == sizeof(PRD_TYPE) );
CORDBRequireProcessStateOK(this);
if (m_pPatchTable == NULL )
{
// First, check to be sure the patch table is valid on the Left Side. If its not, then we won't read it.
BOOL fPatchTableValid = FALSE;
hr = SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_runtimeOffsets.m_pPatchTableValid), &fPatchTableValid);
if (FAILED(hr) || !fPatchTableValid)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
return S_OK;
}
SIZE_T offStart = 0;
SIZE_T offEnd = 0;
UINT cbTableSlice = 0;
// Grab the patch table info
offStart = min(m_runtimeOffsets.m_offRgData, m_runtimeOffsets.m_offCData);
offEnd = max(m_runtimeOffsets.m_offRgData, m_runtimeOffsets.m_offCData) + sizeof(SIZE_T);
cbTableSlice = (UINT)(offEnd - offStart);
if (cbTableSlice == 0)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
return S_OK;
}
EX_TRY
{
rgb = new BYTE[cbTableSlice]; // throws
TargetBuffer tbSlice((BYTE*)m_runtimeOffsets.m_pPatches + offStart, cbTableSlice);
this->SafeReadBuffer(tbSlice, rgb); // Throws;
// Note that rgData is a pointer in the left side address space
m_rgData = *(BYTE**)(rgb + m_runtimeOffsets.m_offRgData - offStart);
m_cPatch = *(ULONG*)(rgb + m_runtimeOffsets.m_offCData - offStart);
// Grab the patch table
UINT cbPatchTable = (UINT)(m_cPatch * m_runtimeOffsets.m_cbPatch);
if (cbPatchTable == 0)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
_ASSERTE(hr == S_OK);
goto LExit; // can't return since we're in a Try/Catch
}
// Throwing news
m_pPatchTable = new BYTE[ cbPatchTable ];
m_rgNextPatch = new ULONG[m_cPatch];
m_rgUncommitedOpcode = new PRD_TYPE[m_cPatch];
TargetBuffer tb(m_rgData, cbPatchTable);
this->SafeReadBuffer(tb, m_pPatchTable); // Throws
//As we go through the patch table we do a number of things:
//
// 1. collect min,max address seen for quick fail check
//
// 2. Link all valid entries into a linked list, the first entry of which is m_iFirstPatch
//
// 3. Initialize m_rgUncommitedOpcode, so that we can undo local patch table changes if WriteMemory can't write
// atomically.
//
// 4. If the patch is in the memory we grabbed, unapply it.
ULONG iDebuggerControllerPatchPrev = DPT_TERMINATING_INDEX;
m_minPatchAddr = MAX_ADDRESS;
m_maxPatchAddr = MIN_ADDRESS;
m_iFirstPatch = DPT_TERMINATING_INDEX;
for (ULONG iPatch = 0; iPatch < m_cPatch;iPatch++)
{
// <REVISIT_TODO>@todo port: we're making assumptions about the size of opcodes,address pointers, etc</REVISIT_TODO>
BYTE *DebuggerControllerPatch = m_pPatchTable + m_runtimeOffsets.m_cbPatch * iPatch;
PRD_TYPE opcode = *(PRD_TYPE*)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode);
CORDB_ADDRESS patchAddress = PTR_TO_CORDB_ADDRESS(*(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr));
// A non-zero opcode indicates to us that this patch is valid.
if (!PRDIsEmpty(opcode))
{
_ASSERTE( patchAddress != 0 );
// (1), above
// Note that GetPatchEndAddr() returns the address immediately AFTER the patch,
// so we have to subtract 1 from it below.
if (m_minPatchAddr > patchAddress )
m_minPatchAddr = patchAddress;
if (m_maxPatchAddr < patchAddress )
m_maxPatchAddr = GetPatchEndAddr(patchAddress) - 1;
// (2), above
if ( m_iFirstPatch == DPT_TERMINATING_INDEX)
{
m_iFirstPatch = iPatch;
_ASSERTE( iPatch != DPT_TERMINATING_INDEX);
}
if (iDebuggerControllerPatchPrev != DPT_TERMINATING_INDEX)
{
m_rgNextPatch[iDebuggerControllerPatchPrev] = iPatch;
}
iDebuggerControllerPatchPrev = iPatch;
// (3), above
InitializePRDToBreakInst(&(m_rgUncommitedOpcode[iPatch]));
// (4), above
if (IsPatchInRequestedRange(address, size, patchAddress))
{
_ASSERTE( buffer != NULL );
_ASSERTE( size != NULL );
//unapply the patch here.
CORDbgSetInstructionEx(buffer, address, patchAddress, opcode, size);
}
}
}
if (iDebuggerControllerPatchPrev != DPT_TERMINATING_INDEX)
{
m_rgNextPatch[iDebuggerControllerPatchPrev] = DPT_TERMINATING_INDEX;
}
}
LExit:
;
EX_CATCH_HRESULT(hr);
}
if (rgb != NULL )
{
delete [] rgb;
}
if (FAILED( hr ) )
{
ClearPatchTable();
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given an address, see if there is a patch in the patch table that matches it and return
// if its an unmanaged patch or not.
//
// Arguments:
// address - The address of an instruction to check in the target address space.
// pfPatchFound - Space to store the result, TRUE if the address belongs to a
// patch, FALSE if not. Only valid if this method returns a success code.
// pfPatchIsUnmanaged - Space to store the result, TRUE if the address is a patch
// and the patch is unmanaged, FALSE if not. Only valid if this method returns a
// success code.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
// Note: this method is pretty in-efficient. It refreshes the patch table, then scans it.
// Refreshing the patch table involves a scan, too, so this method could be folded
// with that.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::FindPatchByAddress(CORDB_ADDRESS address, bool *pfPatchFound, bool *pfPatchIsUnmanaged)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE((pfPatchFound != NULL) && (pfPatchIsUnmanaged != NULL));
_ASSERTE(m_runtimeOffsetsInitialized);
FAIL_IF_NEUTERED(this);
*pfPatchFound = false;
*pfPatchIsUnmanaged = false;
// First things first. If the process isn't initialized, then there can be no patch table, so we know the breakpoint
// doesn't belong to the Runtime.
if (!m_initialized)
{
return S_OK;
}
// This method is called from the main loop of the win32 event thread in response to a first chance breakpoint event
// that we know is not a flare. The process has been runnning, and it may have invalidated the patch table, so we'll
// flush it here before refreshing it to make sure we've got the right thing.
//
// Note: we really should have the Left Side mark the patch table dirty to help optimize this.
ClearPatchTable();
// Refresh the patch table.
HRESULT hr = RefreshPatchTable();
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: failed to refresh the patch table\n"));
return hr;
}
// If there is no patch table yet, then we know there is no patch at the given address, so return S_OK with
// *patchFound = false.
if (m_pPatchTable == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: no patch table\n"));
return S_OK;
}
// Scan the patch table for a matching patch.
for (ULONG iNextPatch = m_iFirstPatch; iNextPatch != DPT_TERMINATING_INDEX; iNextPatch = m_rgNextPatch[iNextPatch])
{
BYTE *patch = m_pPatchTable + (m_runtimeOffsets.m_cbPatch * iNextPatch);
BYTE *patchAddress = *(BYTE**)(patch + m_runtimeOffsets.m_offAddr);
DWORD traceType = *(DWORD*)(patch + m_runtimeOffsets.m_offTraceType);
if (address == PTR_TO_CORDB_ADDRESS(patchAddress))
{
*pfPatchFound = true;
if (traceType == m_runtimeOffsets.m_traceTypeUnmanaged)
{
*pfPatchIsUnmanaged = true;
#if defined(_DEBUG)
HRESULT hrDac = S_OK;
EX_TRY
{
// We should be able to double check w/ DAC that this really is outside of the runtime.
IDacDbiInterface::AddressType addrType = GetDAC()->GetAddressType(address);
CONSISTENCY_CHECK_MSGF(addrType == IDacDbiInterface::kAddressUnrecognized, ("Bad address type = %d", addrType));
}
EX_CATCH_HRESULT(hrDac);
CONSISTENCY_CHECK_MSGF(SUCCEEDED(hrDac), ("DAC::GetAddressType failed, hr=0x%08x", hrDac));
#endif
}
break;
}
}
// If we didn't find a patch, its actually still possible that this breakpoint exception belongs to us. There are
// races with very large numbers of threads entering the Runtime through the same managed function. We will have
// multiple threads adding and removing ref counts to an int 3 in the code stream. Sometimes, this count will go to
// zero and the int 3 will be removed, then it will come back up and the int 3 will be replaced. The in-process
// logic takes pains to ensure that such cases are handled properly, therefore we need to perform the same check
// here to make the correct decision. Basically, the check is to see if there is indeed an int 3 at the exception
// address. If there is _not_ an int 3 there, then we've hit this race. We will lie and say a managed patch was
// found to cover this case. This is tracking the logic in DebuggerController::ScanForTriggers, where we call
// IsPatched.
if (*pfPatchFound == false)
{
// Read one instruction from the faulting address...
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
PRD_TYPE TrapCheck = 0;
#else
BYTE TrapCheck = 0;
#endif
HRESULT hr2 = SafeReadStruct(address, &TrapCheck);
if (SUCCEEDED(hr2) && (TrapCheck != CORDbg_BREAK_INSTRUCTION))
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: patchFound=true based on odd missing int 3 case.\n"));
*pfPatchFound = true;
}
}
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: patchFound=%d, patchIsUnmanaged=%d\n", *pfPatchFound, *pfPatchIsUnmanaged));
return S_OK;
}
HRESULT CordbProcess::WriteMemory(CORDB_ADDRESS address, DWORD size,
BYTE buffer[], SIZE_T *written)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
CORDBRequireProcessStateOK(this);
_ASSERTE(m_runtimeOffsetsInitialized);
if (size == 0 || address == NULL)
return E_INVALIDARG;
VALIDATE_POINTER_TO_OBJECT_ARRAY(buffer, BYTE, size, true, true);
VALIDATE_POINTER_TO_OBJECT(written, SIZE_T *);
#if defined(_DEBUG) && defined(FEATURE_INTEROP_DEBUGGING)
// Shouldn't be using this to write int3. Use UM BP API instead.
// This is technically legal (what if the '0xcc' is data or something), so we can't fail in retail.
// But we can add this debug-only check to help VS migrate to the new API.
static ConfigDWORD configCheckInt3;
DWORD fCheckInt3 = configCheckInt3.val(CLRConfig::INTERNAL_DbgCheckInt3);
if (fCheckInt3)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
if (size == 1 && buffer[0] == 0xCC)
{
CONSISTENCY_CHECK_MSGF(false,
("You're using ICorDebugProcess::WriteMemory() to write an 'int3' (1 byte 0xCC) at address 0x%p.\n"
"If you're trying to set a breakpoint, you should be using ICorDebugProcess::SetUnmanagedBreakpoint() instead.\n"
"(This assert is only enabled under the COM+ knob DbgCheckInt3.)\n",
CORDB_ADDRESS_TO_PTR(address)));
}
#endif // TARGET_X86 || TARGET_AMD64
// check if we're replaced an opcode.
if (size == 1)
{
RSLockHolder ch(&this->m_processMutex);
NativePatch * p = GetNativePatch(CORDB_ADDRESS_TO_PTR(address));
if (p != NULL)
{
CONSISTENCY_CHECK_MSGF(false,
("You're using ICorDebugProcess::WriteMemory() to write an 'opcode (0x%x)' at address 0x%p.\n"
"There's already a native patch at that address from ICorDebugProcess::SetUnmanagedBreakpoint().\n"
"If you're trying to remove the breakpoint, use ICDProcess::ClearUnmanagedBreakpoint() instead.\n"
"(This assert is only enabled under the COM+ knob DbgCheckInt3.)\n",
(DWORD) (buffer[0]), CORDB_ADDRESS_TO_PTR(address)));
}
}
}
#endif // _DEBUG && FEATURE_INTEROP_DEBUGGING
*written = 0;
HRESULT hr = S_OK;
HRESULT hrSaved = hr; // this will hold the 'real' hresult in case of a
// partially completed operation
HRESULT hrPartialCopy = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
BOOL bUpdateOriginalPatchTable = FALSE;
BYTE *bufferCopy = NULL;
// Only update the patch table if the managed state of the process
// is initialized.
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
if (m_pPatchTable == NULL )
{
if (!SUCCEEDED( hr = RefreshPatchTable() ) )
{
goto LExit;
}
}
if ( !SUCCEEDED( hr = AdjustBuffer( address,
size,
buffer,
&bufferCopy,
AB_WRITE,
&bUpdateOriginalPatchTable)))
{
goto LExit;
}
}
//conveniently enough, SafeWriteBuffer will throw if it can't complete the entire operation
EX_TRY
{
TargetBuffer tb(address, size);
SafeWriteBuffer(tb, buffer); // throws
*written = tb.cbSize; // DT's Write does everything or fails.
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
if(hr != hrPartialCopy)
goto LExit;
else
hrSaved = hr;
}
LOG((LF_CORDB, LL_INFO100000, "CP::WM: wrote %d bytes at 0x%08x, first byte is 0x%x\n",
*written, (DWORD)address, buffer[0]));
if (bUpdateOriginalPatchTable == TRUE )
{
{
RSLockHolder ch(&this->m_processMutex);
//don't tweak patch table for stuff that isn't written to LeftSide
CommitBufferAdjustments(address, address + *written);
}
// The only way this should be able to fail is if
//someone else fiddles with the memory protections on the
//left side while it's frozen
EX_TRY
{
TargetBuffer tb(m_rgData, (ULONG) (m_cPatch*m_runtimeOffsets.m_cbPatch));
SafeWriteBuffer(tb, m_pPatchTable);
}
EX_CATCH_HRESULT(hr);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
}
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
m_continueCounter++;
LExit:
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
ClearBufferAdjustments( );
}
//we messed up our local copy, so get a clean copy the next time
//we need it
if (bUpdateOriginalPatchTable==TRUE)
{
if (bufferCopy != NULL)
{
memmove(buffer, bufferCopy, size);
delete [] bufferCopy;
}
}
if (FAILED( hr ))
{
//we messed up our local copy, so get a clean copy the next time
//we need it
if (bUpdateOriginalPatchTable==TRUE)
{
RSLockHolder ch(&this->m_processMutex);
ClearPatchTable();
}
}
else if( FAILED(hrSaved) )
{
hr = hrSaved;
}
return hr;
}
HRESULT CordbProcess::ClearCurrentException(DWORD threadID)
{
#ifndef FEATURE_INTEROP_DEBUGGING
return E_INVALIDARG;
#else
PUBLIC_API_ENTRY(this);
RSLockHolder lockHolder(GetProcessLock());
// There's something wrong if you're calling this an there are no queued unmanaged events.
if ((m_unmanagedEventQueue == NULL) && (m_outOfBandEventQueue == NULL))
return E_INVALIDARG;
// Grab the unmanaged thread object.
CordbUnmanagedThread *pUThread = GetUnmanagedThread(threadID);
if (pUThread == NULL)
return E_INVALIDARG;
LOG((LF_CORDB, LL_INFO1000, "CP::CCE: tid=0x%x\n", threadID));
// We clear both the IB and OOB event.
if (pUThread->HasIBEvent() && !pUThread->IBEvent()->IsEventUserContinued())
{
pUThread->IBEvent()->SetState(CUES_ExceptionCleared);
}
if (pUThread->HasOOBEvent())
{
// must decide exception status _before_ we continue the event.
_ASSERTE(!pUThread->OOBEvent()->IsEventContinuedUnhijacked());
pUThread->OOBEvent()->SetState(CUES_ExceptionCleared);
}
// If the thread is hijacked, then set the thread's debugger word to 0 to indicate to it that the
// exception has been cleared.
if (pUThread->IsGenericHijacked())
{
HRESULT hr = pUThread->SetEEDebuggerWord(0);
_ASSERTE(SUCCEEDED(hr));
}
return S_OK;
#endif // FEATURE_INTEROP_DEBUGGING
}
#ifdef FEATURE_INTEROP_DEBUGGING
CordbUnmanagedThread *CordbProcess::HandleUnmanagedCreateThread(DWORD dwThreadId, HANDLE hThread, void *lpThreadLocalBase)
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedThread *ut = new (nothrow) CordbUnmanagedThread(this, dwThreadId, hThread, lpThreadLocalBase);
if (ut != NULL)
{
HRESULT hr = m_unmanagedThreads.AddBase(ut); // InternalAddRef, release on EXIT_THREAD events.
if (!SUCCEEDED(hr))
{
delete ut;
ut = NULL;
LOG((LF_CORDB, LL_INFO10000, "Failed adding unmanaged thread to process!\n"));
CORDBSetUnrecoverableError(this, hr, 0);
}
}
else
{
LOG((LF_CORDB, LL_INFO10000, "New CordbThread failed!\n"));
CORDBSetUnrecoverableError(this, E_OUTOFMEMORY, 0);
}
return ut;
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Initializes the DAC
// Arguments: none--initializes the DAC for this CordbProcess instance
// Note: Throws on error
//-----------------------------------------------------------------------------
void CordbProcess::InitDac()
{
// Go-Go DAC power!!
HRESULT hr = S_OK;
EX_TRY
{
InitializeDac();
}
EX_CATCH_HRESULT(hr);
// We Need DAC to debug for both Managed & Interop.
if (FAILED(hr))
{
// We assert here b/c we're trying to be friendly. Most likely, the cause is either:
// - a bad installation
// - a CLR dev built mscorwks but didn't build DAC.
SIMPLIFYING_ASSUMPTION_MSGF(false, ("Failed to load DAC while for debugging. hr=0x%08x", hr));
ThrowHR(hr);
}
} //CordbProcess::InitDac
// Update the entire RS copy of the debugger control block by reading the LS copy. The RS copy is treated as
// a throw-away temporary buffer, rather than a true cache. That is, we make no assumptions about the
// validity of the information over time. Thus, before using any of the values, we need to update it. We
// update everything for simplicity; any perf hit we take by doing this instead of updating the individual
// fields we want at any given point isn't significant, particularly if we are updating multiple fields.
// Arguments:
// none, but reads process memory from the LS debugger control block
// Return Value: none (copies from LS DCB to RS buffer GetDCB())
// Note: throws if SafeReadBuffer fails
void CordbProcess::UpdateRightSideDCB()
{
IfFailThrow(m_pEventChannel->UpdateRightSideDCB());
} // CordbProcess::UpdateRightSideDCB
// Update a single field with a value stored in the RS copy of the DCB. We can't update the entire LS DCB
// because in some cases, the LS and RS are simultaneously initializing the DCB. If we initialize a field on
// the RS and write back the whole thing, we may overwrite something the LS has initialized in the interim.
// Arguments:
// input: rsFieldAddr - the address of the field in the RS copy of the DCB that we want to write back to
// the LS DCB. We use this to compute the offset of the field from the beginning of the
// DCB and then add this offset to the starting address of the LS DCB to get the LS
// address of the field we are updating
// size - the size of the field we're updating.
// Return value: none
// Note: throws if SafeWriteBuffer fails
void CordbProcess::UpdateLeftSideDCBField(void * rsFieldAddr, SIZE_T size)
{
IfFailThrow(m_pEventChannel->UpdateLeftSideDCBField(rsFieldAddr, size));
} // CordbProcess::UpdateRightSideDCB
//-----------------------------------------------------------------------------
// Gets the remote address of the event block for the Target and verifies that it's valid.
// We use this address when we need to read from or write to the debugger control block.
// Also allocates the RS buffer used for temporary storage for information from the DCB and
// copies the LS DCB into the RS buffer.
// Arguments:
// output: pfBlockExists - true iff the LS DCB has been successfully allocated. Note that
// we need this information even if the function throws, so we can't simply send it back
// as a return value.
// Return value:
// None, but allocates GetDCB() on success. If the LS DCB has not
// been successfully initialized or if this throws, GetDCB() will be NULL.
//
// Notes:
// Throws on error
//
//-----------------------------------------------------------------------------
void CordbProcess::GetEventBlock(BOOL * pfBlockExists)
{
if (GetDCB() == NULL) // we only need to do this once
{
_ASSERTE(m_pShim != NULL);
_ASSERTE(ThreadHoldsProcessLock());
// This will Initialize the DAC/DBI interface.
BOOL fDacReady = TryInitializeDac();
if (fDacReady)
{
// Ensure that we have a DAC interface.
_ASSERTE(m_pDacPrimitives != NULL);
// This is not technically necessary for Mac debugging. The event channel doesn't rely on
// knowing the target address of the DCB on the LS.
CORDB_ADDRESS pLeftSideDCB = NULL;
pLeftSideDCB = (GetDAC()->GetDebuggerControlBlockAddress());
if (pLeftSideDCB == NULL)
{
*pfBlockExists = false;
ThrowHR(CORDBG_E_DEBUGGING_NOT_POSSIBLE);
}
IfFailThrow(NewEventChannelForThisPlatform(pLeftSideDCB,
m_pMutableDataTarget,
GetProcessDescriptor(),
m_pShim->GetMachineInfo(),
&m_pEventChannel));
_ASSERTE(m_pEventChannel != NULL);
// copy information from left side DCB
UpdateRightSideDCB();
// Verify that the control block is valid.
// This will throw on error.
VerifyControlBlock();
*pfBlockExists = true;
}
else
{
// we can't initialize the DAC, so we can't get the block
*pfBlockExists = false;
}
}
else // we got the block before
{
*pfBlockExists = true;
}
} // CordbProcess::GetEventBlock()
//
// Verify that the version info in the control block matches what we expect. The minimum supported protocol from the
// Left Side must be greater or equal to the minimum required protocol of the Right Side. Note: its the Left Side's job
// to conform to whatever protocol the Right Side requires, so long as minimum is supported.
//
void CordbProcess::VerifyControlBlock()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
if (GetDCB()->m_DCBSize == 0)
{
// the LS is still initializing the DCB
ThrowHR(CORDBG_E_DEBUGGING_NOT_POSSIBLE);
}
// Fill in the protocol numbers for the Right Side and update the LS DCB.
GetDCB()->m_rightSideProtocolCurrent = CorDB_RightSideProtocolCurrent;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideProtocolCurrent), sizeof(GetDCB()->m_rightSideProtocolCurrent));
GetDCB()->m_rightSideProtocolMinSupported = CorDB_RightSideProtocolMinSupported;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideProtocolMinSupported),
sizeof(GetDCB()->m_rightSideProtocolMinSupported));
// For Telesto, Dbi and Wks have a more flexible versioning allowed, as described by the Debugger
// Version Protocol String in DEBUGGER_PROTOCOL_STRING in DbgIpcEvents.h. This allows different build
// numbers, but the other protocol numbers should still match.
// These assertions verify that the debug manager is behaving correctly.
// An assertion failure here means that the runtime version of the debuggee is different from the runtime version of
// the debugger is capable of debugging.
// The Debug Manager should properly match LS & RS, and thus guarantee that this assert should never fire.
// But just in case the installation is corrupted, we'll check it.
if (GetDCB()->m_DCBSize != sizeof(DebuggerIPCControlBlock))
{
CONSISTENCY_CHECK_MSGF(false, ("DCB in LS is %d bytes, in RS is %d bytes. Version mismatch!!\n",
GetDCB()->m_DCBSize, sizeof(DebuggerIPCControlBlock)));
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
// The Left Side has to support at least our minimum required protocol.
if (GetDCB()->m_leftSideProtocolCurrent < GetDCB()->m_rightSideProtocolMinSupported)
{
_ASSERTE(GetDCB()->m_leftSideProtocolCurrent >= GetDCB()->m_rightSideProtocolMinSupported);
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
// The Left Side has to be able to emulate at least our minimum required protocol.
if (GetDCB()->m_leftSideProtocolMinSupported > GetDCB()->m_rightSideProtocolCurrent)
{
_ASSERTE(GetDCB()->m_leftSideProtocolMinSupported <= GetDCB()->m_rightSideProtocolCurrent);
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
#ifdef _DEBUG
char buf[MAX_LONGPATH];
DWORD len = GetEnvironmentVariableA("CORDBG_NotCompatibleTest", buf, sizeof(buf));
_ASSERTE(len < sizeof(buf));
if (len > 0)
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
#endif
if (GetDCB()->m_bHostingInFiber)
{
ThrowHR(CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS);
}
_ASSERTE(!GetDCB()->m_rightSideShouldCreateHelperThread);
} // CordbProcess::VerifyControlBlock
//-----------------------------------------------------------------------------
// This is the CordbProcess objects chance to inspect the DCB and intialize stuff
//
// Return Value:
// Typical HRESULT return values, nothing abnormal.
// If succeeded, then the block exists and is valid.
//
//-----------------------------------------------------------------------------
HRESULT CordbProcess::GetRuntimeOffsets()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
UpdateRightSideDCB();
// Can't get a handle to the helper thread if the target is remote.
// If we got this far w/o failing, then we should be able to get the helper thread handle.
// RS will handle not having the helper-thread handle, so we just make a best effort here.
DWORD dwHelperTid = GetDCB()->m_realHelperThreadId;
_ASSERTE(dwHelperTid != 0);
{
#if TARGET_UNIX
m_hHelperThread = NULL; //RS is supposed to be able to live without a helper thread handle.
#else
m_hHelperThread = OpenThread(SYNCHRONIZE, FALSE, dwHelperTid);
CONSISTENCY_CHECK_MSGF(m_hHelperThread != NULL, ("Failed to get helper-thread handle. tid=0x%x\n", dwHelperTid));
#endif
}
// get the remote address of the runtime offsets structure and read the structure itself
HRESULT hrRead = SafeReadStruct(PTR_TO_CORDB_ADDRESS(GetDCB()->m_pRuntimeOffsets), &m_runtimeOffsets);
if (FAILED(hrRead))
{
return hrRead;
}
LOG((LF_CORDB, LL_INFO10000, "CP::GRO: got runtime offsets: \n"));
#ifdef FEATURE_INTEROP_DEBUGGING
LOG((LF_CORDB, LL_INFO10000, " m_genericHijackFuncAddr= 0x%p\n",
m_runtimeOffsets.m_genericHijackFuncAddr));
LOG((LF_CORDB, LL_INFO10000, " m_signalHijackStartedBPAddr= 0x%p\n",
m_runtimeOffsets.m_signalHijackStartedBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_excepNotForRuntimeBPAddr= 0x%p\n",
m_runtimeOffsets.m_excepNotForRuntimeBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_notifyRSOfSyncCompleteBPAddr= 0x%p\n",
m_runtimeOffsets.m_notifyRSOfSyncCompleteBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_debuggerWordTLSIndex= 0x%08x\n",
m_runtimeOffsets.m_debuggerWordTLSIndex));
#endif // FEATURE_INTEROP_DEBUGGING
LOG((LF_CORDB, LL_INFO10000, " m_TLSIndex= 0x%08x\n",
m_runtimeOffsets.m_TLSIndex));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadStateOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadStateOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadStateNCOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadStateNCOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadPGCDisabledOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadPGCDisabledOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadPGCDisabledValue= 0x%08x\n",
m_runtimeOffsets.m_EEThreadPGCDisabledValue));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadFrameOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadFrameOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadMaxNeededSize= 0x%08x\n",
m_runtimeOffsets.m_EEThreadMaxNeededSize));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadSteppingStateMask= 0x%08x\n",
m_runtimeOffsets.m_EEThreadSteppingStateMask));
LOG((LF_CORDB, LL_INFO10000, " m_EEMaxFrameValue= 0x%08x\n",
m_runtimeOffsets.m_EEMaxFrameValue));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadDebuggerFilterContextOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadDebuggerFilterContextOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEFrameNextOffset= 0x%08x\n",
m_runtimeOffsets.m_EEFrameNextOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEIsManagedExceptionStateMask= 0x%08x\n",
m_runtimeOffsets.m_EEIsManagedExceptionStateMask));
LOG((LF_CORDB, LL_INFO10000, " m_pPatches= 0x%08x\n",
m_runtimeOffsets.m_pPatches));
LOG((LF_CORDB, LL_INFO10000, " m_offRgData= 0x%08x\n",
m_runtimeOffsets.m_offRgData));
LOG((LF_CORDB, LL_INFO10000, " m_offCData= 0x%08x\n",
m_runtimeOffsets.m_offCData));
LOG((LF_CORDB, LL_INFO10000, " m_cbPatch= 0x%08x\n",
m_runtimeOffsets.m_cbPatch));
LOG((LF_CORDB, LL_INFO10000, " m_offAddr= 0x%08x\n",
m_runtimeOffsets.m_offAddr));
LOG((LF_CORDB, LL_INFO10000, " m_offOpcode= 0x%08x\n",
m_runtimeOffsets.m_offOpcode));
LOG((LF_CORDB, LL_INFO10000, " m_cbOpcode= 0x%08x\n",
m_runtimeOffsets.m_cbOpcode));
LOG((LF_CORDB, LL_INFO10000, " m_offTraceType= 0x%08x\n",
m_runtimeOffsets.m_offTraceType));
LOG((LF_CORDB, LL_INFO10000, " m_traceTypeUnmanaged= 0x%08x\n",
m_runtimeOffsets.m_traceTypeUnmanaged));
#ifdef FEATURE_INTEROP_DEBUGGING
// Flares are only used for interop debugging.
// Do check that the flares are all at unique offsets.
// Since this is determined at link-time, we need a run-time check (an
// assert isn't good enough, since this would only happen in a super
// optimized / bbt run).
{
const void * flares[] = {
m_runtimeOffsets.m_signalHijackStartedBPAddr,
m_runtimeOffsets.m_excepForRuntimeHandoffStartBPAddr,
m_runtimeOffsets.m_excepForRuntimeHandoffCompleteBPAddr,
m_runtimeOffsets.m_signalHijackCompleteBPAddr,
m_runtimeOffsets.m_excepNotForRuntimeBPAddr,
m_runtimeOffsets.m_notifyRSOfSyncCompleteBPAddr,
};
const int NumFlares = ARRAY_SIZE(flares);
// Ensure that all of the flares are unique.
for(int i = 0; i < NumFlares; i++)
{
for(int j = i+1; j < NumFlares; j++)
{
if (flares[i] == flares[j])
{
// If we ever fail here, that means the LS build is busted.
// This assert is useful if we drop a checked RS onto a retail
// LS (that's legal).
_ASSERTE(!"LS has matching Flares.");
LOG((LF_CORDB, LL_ALWAYS, "Failing because of matching flares.\n"));
return CORDBG_E_INCOMPATIBLE_PROTOCOL;
}
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
m_runtimeOffsetsInitialized = true;
return S_OK;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Resume hijacked threads.
//-----------------------------------------------------------------------------
void CordbProcess::ResumeHijackedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
_ASSERTE(ThreadHoldsProcessLock());
LOG((LF_CORDB, LL_INFO10000, "CP::RHT: entered\n"));
if (this->m_state & (CordbProcess::PS_SOME_THREADS_SUSPENDED | CordbProcess::PS_HIJACKS_IN_PLACE))
{
// On XP, This will also resume the threads suspended for Sync.
this->ResumeUnmanagedThreads();
}
// Hijacks send their ownership flares and then wait on this event. By setting this
// we let the hijacks run free.
if (this->m_leftSideUnmanagedWaitEvent != NULL)
{
SetEvent(this->m_leftSideUnmanagedWaitEvent);
}
else
{
// Only reason we expect to not have this event is if the CLR hasn't been loaded yet.
// In that case, we won't hijack, so nobody's listening for this event either.
_ASSERTE(!m_initialized);
}
}
//-----------------------------------------------------------------------------
// For debugging support, record the win32 events.
// Note that although this is for debugging, we want it in retail because we'll
// be debugging retail most of the time :(
// pEvent - the win32 debug event we just received
// pUThread - our unmanaged thread object for the event. We could look it up
// from pEvent->dwThreadId, but passed in for perf reasons.
//-----------------------------------------------------------------------------
void CordbProcess::DebugRecordWin32Event(const DEBUG_EVENT * pEvent, CordbUnmanagedThread * pUThread)
{
_ASSERTE(ThreadHoldsProcessLock());
// Although we could look up the Unmanaged thread, it's faster to have it just passed in.
// So here we do a consistency check.
_ASSERTE(pUThread != NULL);
_ASSERTE(pUThread->m_id == pEvent->dwThreadId);
m_DbgSupport.m_TotalNativeEvents++; // bump up the counter.
MiniDebugEvent * pMiniEvent = &m_DbgSupport.m_DebugEventQueue[m_DbgSupport.m_DebugEventQueueIdx];
pMiniEvent->code = (BYTE) pEvent->dwDebugEventCode;
pMiniEvent->pUThread = pUThread;
DWORD tid = pEvent->dwThreadId;
// Record debug-event specific data.
switch(pEvent->dwDebugEventCode)
{
case LOAD_DLL_DEBUG_EVENT:
pMiniEvent->u.ModuleData.pBaseAddress = pEvent->u.LoadDll.lpBaseOfDll;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=0x%8x, Load Dll. Addr=%p\n",
tid,
pEvent->u.LoadDll.lpBaseOfDll);
break;
case UNLOAD_DLL_DEBUG_EVENT:
pMiniEvent->u.ModuleData.pBaseAddress = pEvent->u.UnloadDll.lpBaseOfDll;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=0x%8x, Unload Dll. Addr=%p\n",
tid,
pEvent->u.UnloadDll.lpBaseOfDll);
break;
case EXCEPTION_DEBUG_EVENT:
pMiniEvent->u.ExceptionData.pAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
pMiniEvent->u.ExceptionData.dwCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
STRESS_LOG3(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=%8x, (1) Exception. Code=0x%08x, Addr=%p\n",
tid,
pMiniEvent->u.ExceptionData.dwCode,
pMiniEvent->u.ExceptionData.pAddress
);
break;
default:
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received tid=%8x, %d\n", tid, pEvent->dwDebugEventCode);
break;
}
// Go to the next entry in the queue.
m_DbgSupport.m_DebugEventQueueIdx = (m_DbgSupport.m_DebugEventQueueIdx + 1) % DEBUG_EVENTQUEUE_SIZE;
}
void CordbProcess::QueueUnmanagedEvent(CordbUnmanagedThread *pUThread, const DEBUG_EVENT *pEvent)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_pShim != NULL);
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: queued unmanaged event %d for thread 0x%x\n",
pEvent->dwDebugEventCode, pUThread->m_id));
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
// Copy the event into the given thread
CordbUnmanagedEvent *ue;
// Use the primary IB event slot unless this is the special stack overflow event case.
if (!pUThread->HasSpecialStackOverflowCase())
ue = pUThread->IBEvent();
else
ue = pUThread->IBEvent2();
if(pUThread->HasIBEvent() && !pUThread->HasSpecialStackOverflowCase())
{
// Any event being replaced should at least have been continued outside of the hijack
// We don't track whether or not we expect the exception to retrigger but if we are replacing
// the event then it did not.
_ASSERTE(ue->IsEventContinuedUnhijacked());
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: A previously seen event is being discarded 0x%x 0x%p\n",
ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode,
ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionAddress));
DequeueUnmanagedEvent(ue->m_owner);
}
memcpy(&(ue->m_currentDebugEvent), pEvent, sizeof(DEBUG_EVENT));
ue->m_state = CUES_IsIBEvent;
ue->m_next = NULL;
// Enqueue the event.
pUThread->SetState(CUTS_HasIBEvent);
if (m_unmanagedEventQueue == NULL)
m_unmanagedEventQueue = ue;
else
m_lastQueuedUnmanagedEvent->m_next = ue;
m_lastQueuedUnmanagedEvent = ue;
}
void CordbProcess::DequeueUnmanagedEvent(CordbUnmanagedThread *ut)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_unmanagedEventQueue != NULL);
_ASSERTE(ut->HasIBEvent() || ut->HasSpecialStackOverflowCase());
_ASSERTE(ThreadHoldsProcessLock());
CordbUnmanagedEvent *ue;
if (ut->HasIBEvent())
ue = ut->IBEvent();
else
{
ue = ut->IBEvent2();
// Since we're dequeuing the special stack overflow event, we're no longer in the special stack overflow case.
ut->ClearState(CUTS_HasSpecialStackOverflowCase);
}
DWORD ec = ue->m_currentDebugEvent.dwDebugEventCode;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dequeue unmanaged event %d for thread 0x%x\n", ec, ut->m_id));
_ASSERTE(ec == EXCEPTION_DEBUG_EVENT);
CordbUnmanagedEvent **tmp = &m_unmanagedEventQueue;
CordbUnmanagedEvent **prev = NULL;
// Note: this supports out-of-order dequeing of unmanaged events. This is necessary because we queue events even if
// we're not clear on the ownership question. When we get the answer, and if the event belongs to the Runtime, we go
// ahead and yank the event out of the queue, wherever it may be.
while (*tmp && *tmp != ue)
{
prev = tmp;
tmp = &((*tmp)->m_next);
}
_ASSERTE(*tmp == ue);
*tmp = (*tmp)->m_next;
if (m_unmanagedEventQueue == NULL)
m_lastQueuedUnmanagedEvent = NULL;
else if (m_lastQueuedUnmanagedEvent == ue)
{
_ASSERTE(prev != NULL);
m_lastQueuedUnmanagedEvent = *prev;
}
ut->ClearState(CUTS_HasIBEvent);
}
void CordbProcess::QueueOOBUnmanagedEvent(CordbUnmanagedThread *pUThread, const DEBUG_EVENT * pEvent)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(!pUThread->HasOOBEvent());
_ASSERTE(IsWin32EventThread());
_ASSERTE(m_pShim != NULL);
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: queued OOB unmanaged event %d for thread 0x%x\n",
pEvent->dwDebugEventCode, pUThread->m_id));
// Copy the event into the given thread
CordbUnmanagedEvent *ue = pUThread->OOBEvent();
memcpy(&(ue->m_currentDebugEvent), pEvent, sizeof(DEBUG_EVENT));
ue->m_state = CUES_None;
ue->m_next = NULL;
// Enqueue the event.
pUThread->SetState(CUTS_HasOOBEvent);
if (m_outOfBandEventQueue == NULL)
m_outOfBandEventQueue = ue;
else
m_lastQueuedOOBEvent->m_next = ue;
m_lastQueuedOOBEvent = ue;
}
void CordbProcess::DequeueOOBUnmanagedEvent(CordbUnmanagedThread *ut)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_outOfBandEventQueue != NULL);
_ASSERTE(ut->HasOOBEvent());
_ASSERTE(ThreadHoldsProcessLock());
CordbUnmanagedEvent *ue = ut->OOBEvent();
DWORD ec = ue->m_currentDebugEvent.dwDebugEventCode;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dequeue OOB unmanaged event %d for thread 0x%x\n", ec, ut->m_id));
CordbUnmanagedEvent **tmp = &m_outOfBandEventQueue;
CordbUnmanagedEvent **prev = NULL;
// Note: this supports out-of-order dequeing of unmanaged events. This is necessary because we queue events even if
// we're not clear on the ownership question. When we get the answer, and if the event belongs to the Runtime, we go
// ahead and yank the event out of the queue, wherever it may be.
while (*tmp && *tmp != ue)
{
prev = tmp;
tmp = &((*tmp)->m_next);
}
_ASSERTE(*tmp == ue);
*tmp = (*tmp)->m_next;
if (m_outOfBandEventQueue == NULL)
m_lastQueuedOOBEvent = NULL;
else if (m_lastQueuedOOBEvent == ue)
{
_ASSERTE(prev != NULL);
m_lastQueuedOOBEvent = *prev;
}
ut->ClearState(CUTS_HasOOBEvent);
}
HRESULT CordbProcess::SuspendUnmanagedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
// Iterate over all unmanaged threads...
CordbUnmanagedThread* ut;
HASHFIND find;
for (ut = m_unmanagedThreads.FindFirst(&find); ut != NULL; ut = m_unmanagedThreads.FindNext(&find))
{
// Don't suspend any thread in a can't stop region. This includes cooperative mode threads & preemptive
// threads that haven't pushed a NativeTransitionFrame. The ultimate problem here is that a thread
// in this state is effectively inside the runtime, and thus may take a lock that blocks the helper thread.
// IsCan'tStop also includes the helper thread & hijacked threads - which we shouldn't suspend anyways.
// Only suspend those unmanaged threads that aren't already suspended by us and that aren't already hijacked by
// us.
if (!ut->IsSuspended() &&
!ut->IsDeleted() &&
!ut->IsCantStop() &&
!ut->IsBlockingForSync()
)
{
LOG((LF_CORDB, LL_INFO1000, "CP::SUT: suspending unmanaged thread 0x%x, handle 0x%x\n", ut->m_id, ut->m_handle));
DWORD succ = SuspendThread(ut->m_handle);
if (succ == 0xFFFFFFFF)
{
// This is okay... the thread may be dying after an ExitThread event.
LOG((LF_CORDB, LL_INFO1000, "CP::SUT: failed to suspend thread 0x%x\n", ut->m_id));
}
else
{
m_state |= PS_SOME_THREADS_SUSPENDED;
ut->SetState(CUTS_Suspended);
}
}
}
return S_OK;
}
HRESULT CordbProcess::ResumeUnmanagedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
FAIL_IF_NEUTERED(this);
// Iterate over all unmanaged threads...
CordbUnmanagedThread* ut;
HASHFIND find;
for (ut = m_unmanagedThreads.FindFirst(&find); ut != NULL; ut = m_unmanagedThreads.FindNext(&find))
{
// Only resume those unmanaged threads that were suspended by us.
if (ut->IsSuspended())
{
LOG((LF_CORDB, LL_INFO1000, "CP::RUT: resuming unmanaged thread 0x%x\n", ut->m_id));
DWORD succ = ResumeThread(ut->m_handle);
if (succ == 0xFFFFFFFF)
{
LOG((LF_CORDB, LL_INFO1000, "CP::RUT: failed to resume thread 0x%x\n", ut->m_id));
}
else
ut->ClearState(CUTS_Suspended);
}
}
m_state &= ~PS_SOME_THREADS_SUSPENDED;
return S_OK;
}
//-----------------------------------------------------------------------------
// DispatchUnmanagedInBandEvent
//
// Handler for Win32 events already known to be Unmanaged and in-band.
//-----------------------------------------------------------------------------
void CordbProcess::DispatchUnmanagedInBandEvent()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
// There should be no queued OOB events!!! If there are, then we have a breakdown in our protocol, since all OOB
// events should be dispatched before attempting to really continue from any in-band event.
_ASSERTE(m_outOfBandEventQueue == NULL);
_ASSERTE(m_cordb != NULL);
_ASSERTE(m_cordb->m_unmanagedCallback != NULL);
_ASSERTE(!m_dispatchingUnmanagedEvent);
CordbUnmanagedThread * pUnmanagedThread = NULL;
CordbUnmanagedEvent * pUnmanagedEvent = m_unmanagedEventQueue;
while (true)
{
// get the next queued event that isn't dispatched yet
while(pUnmanagedEvent != NULL && pUnmanagedEvent->IsDispatched())
{
pUnmanagedEvent = pUnmanagedEvent->m_next;
}
if(pUnmanagedEvent == NULL)
break;
// Get the thread for this event
_ASSERTE(pUnmanagedThread == NULL);
pUnmanagedThread = pUnmanagedEvent->m_owner;
_ASSERTE(pUnmanagedThread != NULL);
// We better not have dispatched it yet!
_ASSERTE(!pUnmanagedEvent->IsDispatched());
// We shouldn't be dispatching IB events on a thread that has exited.
// Though it's possible that the thread may exit *after* the IB event has been dispatched
// if it gets hijacked.
_ASSERTE(!pUnmanagedThread->IsDeleted());
// Make sure we keep the thread alive while we're playing with it.
pUnmanagedThread->InternalAddRef();
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dispatching unmanaged event %d for thread 0x%x\n",
pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, pUnmanagedThread->m_id));
m_dispatchingUnmanagedEvent = true;
// Add/Remove a reference which is scoped to the time that m_lastDispatchedIBEvent
// is set to pUnmanagedEvent (it is an interior pointer)
// see DevDiv issue 818301 for more details
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->m_owner->InternalRelease();
m_lastDispatchedIBEvent = NULL;
}
pUnmanagedThread->InternalAddRef();
m_lastDispatchedIBEvent = pUnmanagedEvent;
pUnmanagedEvent->SetState(CUES_Dispatched);
IncStopCount();
Unlock();
{
// Interface is semantically const, but does not include const in signature.
DEBUG_EVENT * pEvent = const_cast<DEBUG_EVENT *> (&(pUnmanagedEvent->m_currentDebugEvent));
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this,pEvent, FALSE);
m_cordb->m_unmanagedCallback->DebugEvent(pEvent, FALSE);
}
Lock();
// Calling IMDA::Continue() will set m_dispatchingUnmanagedEvent = false.
// So if Continue() was called && we have more events, we'll loop and dispatch more events.
// Else we'll break out of the while loop.
if(m_dispatchingUnmanagedEvent)
break;
// Continue was called in the dispatch callback, but that continue path just
// clears the dispatch flag and returns. The continue right here is the logical
// completion of the user's continue request
// Note it is sometimes the case that these events have already been continued because
// they had defered dispatching. At the time of deferal they were immediately continued.
// If the event is already continued then this continue becomes a no-op.
m_pShim->GetWin32EventThread()->DoDbgContinue(this, pUnmanagedEvent);
// Release our reference to the unmanaged thread that we dispatched
// This event should have been continued long ago...
_ASSERTE(!pUnmanagedThread->IBEvent()->IsEventWaitingForContinue());
pUnmanagedThread->InternalRelease();
pUnmanagedThread = NULL;
}
m_dispatchingUnmanagedEvent = false;
// Release our reference to the last thread that we dispatched now...
if(pUnmanagedThread)
{
pUnmanagedThread->InternalRelease();
pUnmanagedThread = NULL;
}
}
//-----------------------------------------------------------------------------
// DispatchUnmanagedOOBEvent
//
// Handler for Win32 events already known to be Unmanaged and out-of-band.
//-----------------------------------------------------------------------------
void CordbProcess::DispatchUnmanagedOOBEvent()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
// There should be OOB events queued...
_ASSERTE(m_outOfBandEventQueue != NULL);
_ASSERTE(m_cordb->m_unmanagedCallback != NULL);
do
{
// Get the first event in the OOB Queue...
CordbUnmanagedEvent * pUnmanagedEvent = m_outOfBandEventQueue;
CordbUnmanagedThread * pUnmanagedThread = pUnmanagedEvent->m_owner;
// Make sure we keep the thread alive while we're playing with it.
RSSmartPtr<CordbUnmanagedThread> pRef(pUnmanagedThread);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::DUE: dispatching OOB unmanaged event %d for thread 0x%x\n",
GetCurrentThreadId(), pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, pUnmanagedThread->m_id));
m_dispatchingOOBEvent = true;
pUnmanagedEvent->SetState(CUES_Dispatched);
Unlock();
{
// Interface is semantically const, but does not include const in signature.
DEBUG_EVENT * pEvent = const_cast<DEBUG_EVENT *> (&(pUnmanagedEvent->m_currentDebugEvent));
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this, pEvent, TRUE);
m_cordb->m_unmanagedCallback->DebugEvent(pEvent, TRUE);
}
Lock();
// If they called Continue from the callback, then continue the OOB event right now before dispatching the next
// one.
if (!m_dispatchingOOBEvent)
{
DequeueOOBUnmanagedEvent(pUnmanagedThread);
// Should not have continued from this debug event yet.
_ASSERTE(pUnmanagedEvent->IsEventWaitingForContinue());
// Do a little extra work if that was an OOB exception event...
HRESULT hr = pUnmanagedEvent->m_owner->FixupAfterOOBException(pUnmanagedEvent);
_ASSERTE(SUCCEEDED(hr));
// Go ahead and continue now...
this->m_pShim->GetWin32EventThread()->DoDbgContinue(this, pUnmanagedEvent);
}
// Implicit release of pUnmanagedThread via pRef
}
while (!m_dispatchingOOBEvent && (m_outOfBandEventQueue != NULL));
m_dispatchingOOBEvent = false;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: done dispatching OOB events. Queue=0x%08x\n", m_outOfBandEventQueue));
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// StartSyncFromWin32Stop
//
// Get the process from a Fozen state or a Live state to a Synchronized State.
// Note that Process Exit is considered to be synchronized.
// This is a nop if we're not Interop Debugging.
// If this function succeeds, we're in a synchronized state.
//
// Arguments:
// pfAsyncBreakSent - returns if this method sent an async-break or not.
//
// Return value:
// typical HRESULT return values, nothing sinister here.
//-----------------------------------------------------------------------------
HRESULT CordbProcess::StartSyncFromWin32Stop(BOOL * pfAsyncBreakSent)
{
INTERNAL_API_ENTRY(this);
if (m_pShim == NULL) // This API is moved off to the shim
{
return E_NOTIMPL;
}
HRESULT hr = S_OK;
// Caller should have taken the stop-go lock. This prevents us from racing w/ a continue.
_ASSERTE(m_StopGoLock.HasLock());
// Process should be init before we try to sync it.
_ASSERTE(this->m_initialized);
// If nobody's listening for an AsyncBreak, and we're not stopped, then our caller
// doesn't know if we're sending an AsyncBreak or not; and thus we may not continue.
// Failing this assert means that we're stopping but we don't think we're going to get a continue
// down the road, and thus we're headed for a deadlock.
_ASSERTE((pfAsyncBreakSent != NULL) || (m_stopCount > 0));
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = FALSE;
}
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're win32 stopped (but not out-of-band win32 stopped), or if we're running free on the Left Side but we're
// just not synchronized (and we're win32 attached), then go ahead and do an internal continue and send an async
// break event to get the Left Side sync'd up.
//
// The process can be running free as far as Win32 events are concerned, but still not synchronized as far as the
// Runtime is concerned. This can happen in a lot of cases where we end up with the Runtime not sync'd but with the
// process running free due to hijacking, etc...
if (((m_state & CordbProcess::PS_WIN32_STOPPED) && (m_outOfBandEventQueue == NULL)) ||
(!GetSynchronized() && IsInteropDebugging()))
{
Lock();
if (((m_state & CordbProcess::PS_WIN32_STOPPED) && (m_outOfBandEventQueue == NULL)) ||
(!GetSynchronized() && IsInteropDebugging()))
{
// This can't be the win32 ET b/c we need that thread to be alive and pumping win32 DE so that
// our Async Break can get across.
// So nobody should ever be calling this on the w32 ET. But they could, since we do trickle in from
// outside APIs. So we need a retail check.
if (IsWin32EventThread())
{
_ASSERTE(!"Don't call this API on the W32 Event Thread");
Unlock();
return ErrWrapper(CORDBG_E_CANT_CALL_ON_THIS_THREAD);
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sending internal continue\n", GetCurrentThreadId());
// Can't do this on the win32 event thread.
_ASSERTE(!this->IsWin32EventThread());
// If the helper thread is already dead, then we just return as if we sync'd the process.
if (m_helperThreadDead)
{
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = TRUE;
}
// Mark the process as synchronized so no events will be dispatched until the thing is
// continued. However, the marking here is not a usual marking for synchronized. It has special
// semantics when we're interop debugging. We use m_oddSync to remember this so that we can take special
// action in Continue().
SetSynchronized(true);
m_oddSync = true;
// Get the RC Event Thread to stop listening to the process.
m_cordb->ProcessStateChanged();
Unlock();
return S_OK;
}
m_stopRequested = true;
// See ::Stop for why we defer this. The delayed events will be dispatched when some one calls continue.
// And we know they'll call continue b/c (stopCount > 0) || (our caller knows we're sending an AsyncBreak).
m_specialDeferment = true;
Unlock();
// If the process gets synchronized between the Unlock() and here, then SendUnmanagedContinue() will end up
// not doing anything at all since a) it holds the process lock when working and b) it gates everything on
// if the process is sync'd or not. This is exactly what we want.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cInternalUMContinue);
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: internal continue returned\n", GetCurrentThreadId()));
// Send an async break to the left side now that its running.
DebuggerIPCEvent * pEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pEvent, DB_IPCE_ASYNC_BREAK, false, VMPTR_AppDomain::NullPtr());
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sending async stop\n", GetCurrentThreadId()));
// If the process gets synchronized between the Unlock() and here, then this message will do nothing (Left
// Side catches it) and we'll never get a response, and it won't hurt anything.
hr = m_cordb->SendIPCEvent(this, pEvent, CorDBIPC_BUFFER_SIZE);
// @Todo- how do we handle a failure here?
// If the send returns with the helper thread being dead, then we know we don't need to wait for the process
// to sync.
if (!m_helperThreadDead)
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sent async stop, waiting for event\n", GetCurrentThreadId());
// If we got synchronized between the Unlock() and here its okay since m_stopWaitEvent is still high
// from the last sync.
DWORD dwWaitResult = SafeWaitForSingleObject(this, m_stopWaitEvent, INFINITE);
STRESS_LOG2(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: got event, %d\n", GetCurrentThreadId(), dwWaitResult);
_ASSERTE(dwWaitResult == WAIT_OBJECT_0);
}
Lock();
m_specialDeferment = false;
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = TRUE;
}
// If the helper thread died while we were trying to send an event to it, then we just do the same odd sync
// logic we do above.
if (m_helperThreadDead)
{
SetSynchronized(true);
m_oddSync = true;
hr = S_OK;
}
m_stopRequested = false;
m_cordb->ProcessStateChanged();
}
Unlock();
}
#endif // FEATURE_INTEROP_DEBUGGING
return hr;
}
// Check if the left side has exited. If so, get the right-side
// into shutdown mode. Only use this to avert us from going into
// an unrecoverable error.
bool CordbProcess::CheckIfLSExited()
{
// Check by waiting on the handle with no timeout.
if (WaitForSingleObject(m_handle, 0) == WAIT_OBJECT_0)
{
Lock();
m_terminated = true;
m_exiting = true;
Unlock();
}
LOG((LF_CORDB, LL_INFO10, "CP::IsLSExited() returning '%s'\n",
m_exiting ? "true" : "false"));
return m_exiting;
}
// Call this if something really bad happened and we can't do
// anything meaningful with the CordbProcess.
void CordbProcess::UnrecoverableError(HRESULT errorHR,
unsigned int errorCode,
const char *errorFile,
unsigned int errorLine)
{
LOG((LF_CORDB, LL_INFO10, "[%x] CP::UE: unrecoverable error 0x%08x "
"(%d) %s:%d\n",
GetCurrentThreadId(),
errorHR, errorCode, errorFile, errorLine));
// We definitely want to know about any of these.
STRESS_LOG3(LF_CORDB, LL_EVERYTHING, "Unrecoverable Error:0x%08x, File=%s, line=%d\n", errorHR, errorFile, errorLine);
// It's possible for an unrecoverable error to occur if the user detaches the
// debugger while inside CordbProcess::DispatchRCEvent() (as that function deliberately
// calls Unlock() while calling into the Shim). Detect such cases here & bail before we
// try to access invalid fields on this CordbProcess.
//
// Normally, we'd need to take the cordb process lock around the IsNeutered check
// (and the code that follows). And perhaps this is a good thing to do in the
// future. But for now we're not for two reasons:
//
// 1) It's scary. We're in UnrecoverableError() for gosh sake. I don't know all
// the possible bad states we can be in to get here. Will taking the process lock
// have ordering issues? Will the process lock even be valid to take here (or might
// we AV)? Since this is error handling, we should probably be as light as we can
// not to cause more errors.
//
// 2) It's unnecessary. For the Watson dump I investigated that caused this fix in
// the first place, we already detached before entering UnrecoverableError()
// (indeed, the only reason we're in UnrecoverableError is that we already detached
// and that caused a prior API to fail). Thus, there's no timing issue (in that
// case, anyway), wrt to entering UnrecoverableError() and detaching / neutering.
if (IsNeutered())
return;
#ifdef _DEBUG
// Ping our error trapping logic
HRESULT hrDummy;
hrDummy = ErrWrapper(errorHR);
#endif
if (m_pShim == NULL)
{
// @dbgtodo - , shim: Once everything is hoisted, we can remove
// this code.
// In the v3 case, we should never get an unrecoverable error. Instead, the HR should be propagated
// and returned at the top-level public API.
_ASSERTE(!"Unrecoverable error dispatched in V3 case.");
}
CONSISTENCY_CHECK_MSGF(IsLegalFatalError(errorHR), ("Unrecoverable internal error: hr=0x%08x!", errorHR));
if (!IsLegalFatalError(errorHR) || (errorHR != CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS))
{
// This will throw everything into a Zombie state. The ATT_ macros will check this and fail immediately.
m_unrecoverableError = true;
//
// Mark the process as no longer synchronized.
//
Lock();
SetSynchronized(false);
IncStopCount();
Unlock();
}
// Set the error flags in the process so that if parts of it are
// still alive, it will realize that its in this mode and do the
// right thing.
if (GetDCB() != NULL)
{
GetDCB()->m_errorHR = errorHR;
GetDCB()->m_errorCode = errorCode;
EX_TRY
{
UpdateLeftSideDCBField(&(GetDCB()->m_errorHR), sizeof(GetDCB()->m_errorHR));
UpdateLeftSideDCBField(&(GetDCB()->m_errorCode), sizeof(GetDCB()->m_errorCode));
}
EX_CATCH
{
_ASSERTE(!"Writing process memory failed, perhaps due to an unexpected disconnection from the target.");
}
EX_END_CATCH(SwallowAllExceptions);
}
//
// Let the user know that we've hit an unrecoverable error.
//
if (m_cordb->m_managedCallback)
{
// We are about to send DebuggerError call back. The state of RS is undefined.
// So we use the special Public Callback. We may be holding locks and stuff.
// We may also be deeply nested within the RS.
PUBLIC_CALLBACK_IN_THIS_SCOPE_DEBUGGERERROR(this);
m_cordb->m_managedCallback->DebuggerError((ICorDebugProcess*) this,
errorHR,
errorCode);
}
}
HRESULT CordbProcess::CheckForUnrecoverableError()
{
HRESULT hr = S_OK;
if (GetDCB() != NULL)
{
// be sure we have the latest information
UpdateRightSideDCB();
if (GetDCB()->m_errorHR != S_OK)
{
UnrecoverableError(GetDCB()->m_errorHR,
GetDCB()->m_errorCode,
__FILE__, __LINE__);
hr = GetDCB()->m_errorHR;
}
}
return hr;
}
/*
* EnableLogMessages enables/disables sending of log messages to the
* debugger for logging.
*/
HRESULT CordbProcess::EnableLogMessages(BOOL fOnOff)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_ENABLE_LOG_MESSAGES, false, VMPTR_AppDomain::NullPtr());
event->LogSwitchSettingMessage.iLevel = (int)fOnOff;
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::EnableLogMessages: EnableLogMessages=%d sent.\n",
GetCurrentThreadId(), fOnOff));
return hr;
}
/*
* ModifyLogSwitch modifies the specified switch's severity level.
*/
COM_METHOD CordbProcess::ModifyLogSwitch(_In_z_ WCHAR *pLogSwitchName, LONG lLevel)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
_ASSERTE (pLogSwitchName != NULL);
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_MODIFY_LOGSWITCH, false, VMPTR_AppDomain::NullPtr());
event->LogSwitchSettingMessage.iLevel = lLevel;
event->LogSwitchSettingMessage.szSwitchName.SetStringTruncate(pLogSwitchName);
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::ModifyLogSwitch: ModifyLogSwitch sent.\n",
GetCurrentThreadId()));
return hr;
}
//-----------------------------------------------------------------------------
// Writes a buffer from the target and performs checks similar to SafeWriteStruct
//
// Arguments:
// tb - TargetBuffer which represents the target memory we want to write to
// pLocalBuffer - local pointer into source buffer
// cbSize - the size of local buffer
//
// Exceptions
// On error throws the result of WriteVirtual unless a short write is performed,
// in which case throws ERROR_PARTIAL_COPY
//
void CordbProcess::SafeWriteBuffer(TargetBuffer tb,
const BYTE * pLocalBuffer)
{
_ASSERTE(m_pMutableDataTarget != NULL);
HRESULT hr = m_pMutableDataTarget->WriteVirtual(tb.pAddress,
pLocalBuffer,
tb.cbSize);
IfFailThrow(hr);
}
//-----------------------------------------------------------------------------
// Reads a buffer from the target and performs checks similar to SafeWriteStruct
//
// Arguments:
// tb - TargetBuffer which represents the target memory to read from
// pLocalBuffer - local pointer into source buffer
// cbSize - the size of the remote buffer
// throwOnError - determines whether the function throws exceptions or returns HRESULTs
// in failure cases
//
// Exceptions:
// If throwOnError is TRUE
// On error always throws the special CORDBG_E_READVIRTUAL_FAILURE, unless a short write is performed
// in which case throws ERROR_PARTIAL_COPY
// If throwOnError is FALSE
// No exceptions are thrown, and instead the same error codes are returned as HRESULTs
//
HRESULT CordbProcess::SafeReadBuffer(TargetBuffer tb, BYTE * pLocalBuffer, BOOL throwOnError)
{
ULONG32 cbRead;
HRESULT hr = m_pDACDataTarget->ReadVirtual(tb.pAddress,
pLocalBuffer,
tb.cbSize,
&cbRead);
if (FAILED(hr))
{
if (throwOnError)
ThrowHR(CORDBG_E_READVIRTUAL_FAILURE);
else
return CORDBG_E_READVIRTUAL_FAILURE;
}
if (cbRead != tb.cbSize)
{
if (throwOnError)
ThrowWin32(ERROR_PARTIAL_COPY);
else
return HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
return S_OK;
}
//---------------------------------------------------------------------------------------
// Lookup or create an appdomain.
//
// Arguments:
// vmAppDomain - CLR appdomain to lookup
//
// Returns:
// Instance of CordbAppDomain for the given appdomain. This is a cached instance.
// If the CordbAppDomain does not yet exist, it will be created and added to the cache.
// Never returns NULL. Throw on error.
CordbAppDomain * CordbProcess::LookupOrCreateAppDomain(VMPTR_AppDomain vmAppDomain)
{
CordbAppDomain * pAppDomain = m_appDomains.GetBase(VmPtrToCookie(vmAppDomain));
if (pAppDomain != NULL)
{
return pAppDomain;
}
return CacheAppDomain(vmAppDomain);
}
CordbAppDomain * CordbProcess::GetSharedAppDomain()
{
if (m_sharedAppDomain == NULL)
{
CordbAppDomain *pAD = new CordbAppDomain(this, VMPTR_AppDomain::NullPtr());
if (InterlockedCompareExchangeT<CordbAppDomain*>(&m_sharedAppDomain, pAD, NULL) != NULL)
{
delete pAD;
}
m_sharedAppDomain->InternalAddRef();
}
return m_sharedAppDomain;
}
//---------------------------------------------------------------------------------------
//
// Add a new appdomain to the cache.
//
// Arguments:
// vmAppDomain - appdomain to add.
//
// Return Value:
// Pointer to newly created appdomain, which should be the normal case.
// Throws on failure. Never returns null.
//
// Assumptions:
// Caller ensure the appdomain is not already cached.
// Caller should have stop-go lock, which provides thread-safety.
//
// Notes:
// This sets unrecoverable error on failure.
//
//---------------------------------------------------------------------------------------
CordbAppDomain * CordbProcess::CacheAppDomain(VMPTR_AppDomain vmAppDomain)
{
INTERNAL_API_ENTRY(GetProcess());
_ASSERTE(GetProcessLock()->HasLock());
RSInitHolder<CordbAppDomain> pAppDomain;
pAppDomain.Assign(new CordbAppDomain(this, vmAppDomain)); // throws
// Add to the hash. This will addref the pAppDomain.
// Caller ensures we're not already cached.
// The cache will take ownership.
m_appDomains.AddBaseOrThrow(pAppDomain);
// If this assert fires, then it likely means the target is corrupted.
TargetConsistencyCheck(m_pDefaultAppDomain == NULL);
m_pDefaultAppDomain = pAppDomain;
CordbAppDomain * pReturn = pAppDomain;
pAppDomain.ClearAndMarkDontNeuter();
_ASSERTE(pReturn != NULL);
return pReturn;
}
//---------------------------------------------------------------------------------------
//
// Callback for Appdomain enumeration.
//
// Arguments:
// vmAppDomain - new appdomain to add to enumeration
// pUserData - data passed with callback (a 'this' ptr for CordbProcess)
//
//
// Assumptions:
// Invoked as callback from code:CordbProcess::PrepopulateAppDomains
//
//
//---------------------------------------------------------------------------------------
// static
void CordbProcess::AppDomainEnumerationCallback(VMPTR_AppDomain vmAppDomain, void * pUserData)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
CordbProcess * pProcess = static_cast<CordbProcess *> (pUserData);
INTERNAL_DAC_CALLBACK(pProcess);
pProcess->LookupOrCreateAppDomain(vmAppDomain);
}
//---------------------------------------------------------------------------------------
//
// Traverse appdomains in the target and build up our list.
//
// Arguments:
//
// Return Value:
// returns on success.
// Throws on error. AppDomain cache may be partially populated.
//
// Assumptions:
// This is an non-invasive inspection operation called when the debuggee is stopped.
//
// Notes:
// This can be called multiple times. If the list is non-empty, it will nop.
//---------------------------------------------------------------------------------------
void CordbProcess::PrepopulateAppDomainsOrThrow()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
if (!IsDacInitialized())
{
return;
}
// DD-primitive that invokes a callback. This may throw.
GetDAC()->EnumerateAppDomains(
CordbProcess::AppDomainEnumerationCallback,
this);
}
//---------------------------------------------------------------------------------------
//
// EnumerateAppDomains enumerates all app domains in the process.
//
// Arguments:
// ppAppDomains - get appdomain enumerator
//
// Return Value:
// S_OK on success.
//
// Assumptions:
//
//
// Notes:
// This operation is non-invasive target.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::EnumerateAppDomains(ICorDebugAppDomainEnum **ppAppDomains)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
ValidateOrThrow(ppAppDomains);
// Ensure list is populated.
PrepopulateAppDomainsOrThrow();
RSInitHolder<CordbHashTableEnum> pEnum;
CordbHashTableEnum::BuildOrThrow(
this,
GetContinueNeuterList(),
&m_appDomains,
IID_ICorDebugAppDomainEnum,
pEnum.GetAddr());
*ppAppDomains = static_cast<ICorDebugAppDomainEnum*> (pEnum);
pEnum->ExternalAddRef();
pEnum.ClearAndMarkDontNeuter();
}
PUBLIC_API_END(hr);
return hr;
}
/*
* GetObject returns the runtime process object.
* Note: This method is not yet implemented.
*/
HRESULT CordbProcess::GetObject(ICorDebugValue **ppObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppObject, ICorDebugObjectValue **);
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Given a taskid, finding the corresponding thread. The function can fail if we do not
// find any thread with the given taskid
//
// Arguments:
// taskId - The task ID to look for.
// ppThread - OUT: Space for storing the thread corresponding to the taskId given.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
HRESULT CordbProcess::GetThreadForTaskID(TASKID taskId, ICorDebugThread2 ** ppThread)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
if (ppThread == NULL)
{
ThrowHR(E_INVALIDARG);
}
// On initialization, the task ID of every thread is INVALID_TASK_ID, unless a host is present and
// the host calls IClrTask::SetTaskIdentifier(). So we need to explicitly check for INVALID_TASK_ID
// here and return NULL if necessary. We return S_FALSE because that's the return value for the case
// where we can't find a thread for the specified task ID.
if (taskId == INVALID_TASK_ID)
{
*ppThread = NULL;
hr = S_FALSE;
}
else
{
PrepopulateThreadsOrThrow();
// now find the ICorDebugThread corresponding to it
CordbThread * pThread;
HASHFIND hashFind;
for (pThread = m_userThreads.FindFirst(&hashFind);
pThread != NULL;
pThread = m_userThreads.FindNext(&hashFind))
{
if (pThread->GetTaskID() == taskId)
{
break;
}
}
if (pThread == NULL)
{
*ppThread = NULL;
hr = S_FALSE;
}
else
{
*ppThread = pThread;
pThread->ExternalAddRef();
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbProcess::GetThreadForTaskid
HRESULT
CordbProcess::GetVersion(COR_VERSION* pVersion)
{
if (NULL == pVersion)
{
return E_INVALIDARG;
}
//
// Because we require a matching version of mscordbi.dll to debug a certain version of the runtime,
// we can just use constants found in this particular mscordbi.dll to determine the version of the left side.
pVersion->dwMajor = RuntimeProductMajorVersion;
pVersion->dwMinor = RuntimeProductMinorVersion;
pVersion->dwBuild = RuntimeProductPatchVersion;
pVersion->dwSubBuild = 0;
return S_OK;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Search for a native patch given the address. Return null if not found.
// Since we return an address, this is only valid until the table is disturbed.
//-----------------------------------------------------------------------------
NativePatch * CordbProcess::GetNativePatch(const void * pAddress)
{
_ASSERTE(ThreadHoldsProcessLock());
int cTotal = m_NativePatchList.Count();
NativePatch * pTable = m_NativePatchList.Table();
if (pTable == NULL)
{
return NULL;
}
for(int i = 0; i < cTotal; i++)
{
if (pTable[i].pAddress == pAddress)
{
return &pTable[i];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Is there an break-opcode (int3 on x86) at the address in the debuggee?
//-----------------------------------------------------------------------------
bool CordbProcess::IsBreakOpcodeAtAddress(const void * address)
{
// There should have been an int3 there already. Since we already put it in there,
// we should be able to safely read it out.
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
PRD_TYPE opcodeTest = 0;
#elif defined(TARGET_AMD64) || defined(TARGET_X86)
BYTE opcodeTest = 0;
#else
PORTABILITY_ASSERT("NYI: Architecture specific opcode type to read");
#endif
HRESULT hr = SafeReadStruct(PTR_TO_CORDB_ADDRESS(address), &opcodeTest);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
return (opcodeTest == CORDbg_BREAK_INSTRUCTION);
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// CordbProcess::SetUnmanagedBreakpoint
// Called by a native debugger to add breakpoints during Interop.
// address - remote address into the debuggee
// bufsize, buffer[] - initial size & buffer for the opcode that we're replacing.
// buflen - size of the buffer that we write to.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::SetUnmanagedBreakpoint(CORDB_ADDRESS address, ULONG32 bufsize, BYTE buffer[], ULONG32 * bufLen)
{
LOG((LF_CORDB, LL_INFO100, "CP::SetUnBP: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(!ThreadHoldsProcessLock());
Lock();
HRESULT hr = SetUnmanagedBreakpointInternal(address, bufsize, buffer, bufLen);
Unlock();
return hr;
#endif
}
//-----------------------------------------------------------------------------
// CordbProcess::SetUnmanagedBreakpointInternal
// The worker behind SetUnmanagedBreakpoint, this function can set both public
// breakpoints used by the debugger and internal breakpoints used for utility
// purposes in interop debugging.
// address - remote address into the debuggee
// bufsize, buffer[] - initial size & buffer for the opcode that we're replacing.
// buflen - size of the buffer that we write to.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::SetUnmanagedBreakpointInternal(CORDB_ADDRESS address, ULONG32 bufsize, BYTE buffer[], ULONG32 * bufLen)
{
LOG((LF_CORDB, LL_INFO100, "CP::SetUnBPI: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr = S_OK;
NativePatch * p = NULL;
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const BYTE patch = CORDbg_BREAK_INSTRUCTION;
BYTE opcode;
#elif defined(TARGET_ARM64)
const PRD_TYPE patch = CORDbg_BREAK_INSTRUCTION;
PRD_TYPE opcode;
#else
PORTABILITY_ASSERT("NYI: CordbProcess::SetUnmanagedBreakpoint, interop debugging NYI on this platform");
hr = E_NOTIMPL;
goto ErrExit;
#endif
// Make sure args are good
if ((buffer == NULL) || (bufsize < sizeof(patch)) || (bufLen == NULL))
{
hr = E_INVALIDARG;
goto ErrExit;
}
// Fail if there's already a patch at this address.
if (GetNativePatch(CORDB_ADDRESS_TO_PTR(address)) != NULL)
{
hr = CORDBG_E_NATIVE_PATCH_ALREADY_AT_ADDR;
goto ErrExit;
}
// Preallocate this now so that if are oom, we can fail before we get half-way through.
p = m_NativePatchList.Append();
if (p == NULL)
{
hr = E_OUTOFMEMORY;
goto ErrExit;
}
// Read out opcode. 1 byte on x86
hr = ApplyRemotePatch(this, CORDB_ADDRESS_TO_PTR(address), &p->opcode);
if (FAILED(hr))
goto ErrExit;
// It's all successful, so now update our out-params & internal bookkeaping.
#if defined(TARGET_X86) || defined(TARGET_AMD64)
opcode = (BYTE)p->opcode;
buffer[0] = opcode;
#elif defined(TARGET_ARM64)
opcode = p->opcode;
memcpy_s(buffer, bufsize, &opcode, sizeof(opcode));
#else
PORTABILITY_ASSERT("NYI: CordbProcess::SetUnmanagedBreakpoint, interop debugging NYI on this platform");
#endif
*bufLen = sizeof(opcode);
p->pAddress = CORDB_ADDRESS_TO_PTR(address);
p->opcode = opcode;
_ASSERTE(SUCCEEDED(hr));
ErrExit:
// If we failed, then free the patch
if (FAILED(hr) && (p != NULL))
{
m_NativePatchList.Delete(*p);
}
return hr;
#endif // FEATURE_INTEROP_DEBUGGING
}
//-----------------------------------------------------------------------------
// CordbProcess::ClearUnmanagedBreakpoint
// Called by a native debugger to remove breakpoints during Interop.
// The patch is deleted even if the function fails.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::ClearUnmanagedBreakpoint(CORDB_ADDRESS address)
{
LOG((LF_CORDB, LL_INFO100, "CP::ClearUnBP: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(!ThreadHoldsProcessLock());
HRESULT hr = S_OK;
PRD_TYPE opcode;
Lock();
// Make sure this is a valid patch.
int cTotal = m_NativePatchList.Count();
NativePatch * pTable = m_NativePatchList.Table();
if (pTable == NULL)
{
hr = CORDBG_E_NO_NATIVE_PATCH_AT_ADDR;
goto ErrExit;
}
int i;
for(i = 0; i < cTotal; i++)
{
if (pTable[i].pAddress == CORDB_ADDRESS_TO_PTR(address))
break;
}
if (i >= cTotal)
{
hr = CORDBG_E_NO_NATIVE_PATCH_AT_ADDR;
goto ErrExit;
}
// Found it! Remove it from our table. Note that this may shuffle table contents
// around, so don't keep pointers into the table.
opcode = pTable[i].opcode;
m_NativePatchList.Delete(pTable[i]);
_ASSERTE(m_NativePatchList.Count() == cTotal - 1);
// Now remove the patch.
// Just call through to Write ProcessMemory
hr = RemoveRemotePatch(this, CORDB_ADDRESS_TO_PTR(address), opcode);
if (FAILED(hr))
goto ErrExit;
// Our internal bookeaping was already updated to remove the patch, so now we're done.
// If we had a failure, we should have already bailed.
_ASSERTE(SUCCEEDED(hr));
ErrExit:
Unlock();
return hr;
#endif // FEATURE_INTEROP_DEBUGGING
}
//------------------------------------------------------------------------------------
// StopCount, Sync, SyncReceived form our stop-status. This status is super-critical
// to most hangs, so we stress log it.
//------------------------------------------------------------------------------------
void CordbProcess::SetSynchronized(bool fSynch)
{
_ASSERTE(ThreadHoldsProcessLock() || !"Must have process lock to toggle SyncStatus");
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: set sync=%d\n", fSynch);
m_synchronized = fSynch;
}
bool CordbProcess::GetSynchronized()
{
// This can be accessed whether we're Locked or not. This means that the result
// may change underneath us.
return m_synchronized;
}
void CordbProcess::IncStopCount()
{
_ASSERTE(ThreadHoldsProcessLock());
m_stopCount++;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: Inc StopCount=%d\n", m_stopCount);
}
void CordbProcess::DecStopCount()
{
// We can inc w/ just the process lock (b/c we can dispatch events from the W32ET)
// But decrementing (eg, Continue), requires the stop-go lock.
// This if an operation takes the SG lock, it ensures we don't continue from underneath it.
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
_ASSERTE(ThreadHoldsProcessLock());
m_stopCount--;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: Dec StopCount=%d\n", m_stopCount);
}
// Just gets whether we're stopped or not (m_stopped > 0).
// You only need the StopGo lock for this.
bool CordbProcess::IsStopped()
{
// We don't require the process-lock, just the SG-lock.
// Holding the SG lock prevents another thread from continuing underneath you.
// (see DecStopCount()).
// But you could still be running free, and have another thread stop-underneath you.
// Thus IsStopped() leans towards returning false.
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
return (m_stopCount > 0);
}
int CordbProcess::GetStopCount()
{
_ASSERTE(ThreadHoldsProcessLock());
return m_stopCount;
}
bool CordbProcess::GetSyncCompleteRecv()
{
_ASSERTE(ThreadHoldsProcessLock());
return m_syncCompleteReceived;
}
void CordbProcess::SetSyncCompleteRecv(bool fSyncRecv)
{
_ASSERTE(ThreadHoldsProcessLock());
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: set syncRecv=%d\n", fSyncRecv);
m_syncCompleteReceived = fSyncRecv;
}
// This can be used if we ever need the RS to emulate old behavior of previous versions.
// This can not be used in QIs to deny queries for new interfaces.
// QIs must be consistent across the lifetime of an object. Say CordbThread used this in a QI
// do deny returning a ICorDebugThread2 interface when emulating v1.1. Once that Thread is neutered,
// it no longer has a pointer to the process, and it no longer knows if it should be denying
// the v2.0 query. An object's QI can't start returning new interfaces onces its neutered.
bool CordbProcess::SupportsVersion(CorDebugInterfaceVersion featureVersion)
{
_ASSERTE(featureVersion == CorDebugVersion_2_0);
return true;
}
//---------------------------------------------------------------------------------------
// Add an object to the process's Left-Side resource cleanup list
//
// Arguments:
// pObject - non-null object to be added
//
// Notes:
// This list tracks objects with process-scope that hold left-side
// resources (like func-eval).
// See code:CordbAppDomain::GetSweepableExitNeuterList for per-appdomain
// objects with left-side resources.
void CordbProcess::AddToLeftSideResourceCleanupList(CordbBase * pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
m_LeftSideResourceCleanupList.Add(this, pObject);
}
// This list will get actively swept (looking for objects w/ external ref = 0) between continues.
void CordbProcess::AddToNeuterOnExitList(CordbBase *pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
HRESULT hr = S_OK;
EX_TRY
{
this->m_ExitNeuterList.Add(this, pObject);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
// Mark that this object should be neutered the next time we Continue the process.
void CordbProcess::AddToNeuterOnContinueList(CordbBase *pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
m_ContinueNeuterList.Add(this, pObject); // throws
}
/* ------------------------------------------------------------------------- *
* Runtime Controller Event Thread class
* ------------------------------------------------------------------------- */
//
// Constructor
//
CordbRCEventThread::CordbRCEventThread(Cordb* cordb)
{
_ASSERTE(cordb != NULL);
m_cordb.Assign(cordb);
m_thread = NULL;
m_threadId = 0;
m_run = TRUE;
m_threadControlEvent = NULL;
m_processStateChanged = FALSE;
g_pRSDebuggingInfo->m_RCET = this;
}
//
// Destructor. Cleans up all of the open handles and such.
// This expects that the thread has been stopped and has terminated
// before being called.
//
CordbRCEventThread::~CordbRCEventThread()
{
if (m_threadControlEvent != NULL)
CloseHandle(m_threadControlEvent);
if (m_thread != NULL)
CloseHandle(m_thread);
g_pRSDebuggingInfo->m_RCET = NULL;
}
//
// Init sets up all the objects that the thread will need to run.
//
HRESULT CordbRCEventThread::Init()
{
if (m_cordb == NULL)
return E_INVALIDARG;
m_threadControlEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_threadControlEvent == NULL)
return HRESULT_FROM_GetLastError();
return S_OK;
}
#if defined(FEATURE_INTEROP_DEBUGGING)
//
// Helper to duplicate a handle or thorw
//
// Arguments:
// pLocalHandle - handle to duplicate into the remote process
// pRemoteHandle - RemoteHandle structure in IPC block to hold the remote handle.
// Return value:
// None. Throws on error.
//
void CordbProcess::DuplicateHandleToLocalProcess(HANDLE * pLocalHandle, RemoteHANDLE * pRemoteHandle)
{
_ASSERTE(m_pShim != NULL);
// Dup RSEA and RSER into this process if we don't already have them.
// On Launch, we don't have them yet, but on attach we do.
if (*pLocalHandle == NULL)
{
BOOL fSuccess = pRemoteHandle->DuplicateToLocalProcess(m_handle, pLocalHandle);
if (!fSuccess)
{
ThrowLastError();
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
// Public entry wrapper for code:CordbProcess::FinishInitializeIPCChannelWorker
void CordbProcess::FinishInitializeIPCChannel()
{
// This is called directly from a shim callback.
PUBLIC_API_ENTRY_FOR_SHIM(this);
FinishInitializeIPCChannelWorker();
}
//
// Initialize the IPC channel. After this, IPC events can flow in both ways.
//
// Return value:
// Returns S_OK on success.
//
// Notes:
// This will dispatch an UnrecoverableError callback if it fails.
// This will also initialize key state in the CordbProcess object.
//
// @dbgtodo remove helper-thread: this should eventually go away once we get rid of IPC events.
//
void CordbProcess::FinishInitializeIPCChannelWorker()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
_ASSERTE(m_pShim != NULL);
RSLockHolder lockHolder(&this->m_processMutex);
// If it's already initialized, then nothing left to do.
// this protects us if this function is called multiple times.
if (m_initialized)
{
_ASSERTE(GetDCB() != NULL);
return;
}
EX_TRY
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HFRCE: first event..., process %p\n", GetCurrentThreadId(), this));
BOOL fBlockExists;
GetEventBlock(&fBlockExists); // throws on error
LOG((LF_CORDB, LL_EVERYTHING, "Size of CdbP is %d\n", sizeof(CordbProcess)));
m_pEventChannel->Init(m_handle);
#if defined(FEATURE_INTEROP_DEBUGGING)
DuplicateHandleToLocalProcess(&m_leftSideUnmanagedWaitEvent, &GetDCB()->m_leftSideUnmanagedWaitEvent);
#endif // FEATURE_INTEROP_DEBUGGING
// Read the Runtime Offsets struct out of the debuggee.
hr = GetRuntimeOffsets();
IfFailThrow(hr);
// we need to be careful here. The LS will have a thread running free that may be initializing
// fields of the DCB (specifically it may be setting up the helper thread), so we need to make sure
// we don't overwrite any fields that the LS is writing. We need to be sure we only write to RS
// status fields.
m_initialized = true;
GetDCB()->m_rightSideIsWin32Debugger = IsInteropDebugging();
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HFRCE: ...went fine\n", GetCurrentThreadId()));
_ASSERTE(SUCCEEDED(hr));
} EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
return;
}
// We only land here on failure cases.
// We must have jumped to this label. Maybe we didn't set HR, so check now.
STRESS_LOG1(LF_CORDB, LL_INFO1000, "HFCR: FAILED hr=0x%08x\n", hr);
CloseIPCHandles();
// Rethrow
ThrowHR(hr);
}
//---------------------------------------------------------------------------------------
// Marshals over a string buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_BaseBuffer::CopyLSDataToRSWorker(ICorDebugDataTarget * pTarget)
{
//
const DWORD cbCacheSize = m_cbSize;
// SHOULD not happen for more than once in well-behaved case.
if (m_pbRS != NULL)
{
SIMPLIFYING_ASSUMPTION(!"m_pbRS is non-null; is this a corrupted event?");
ThrowHR(E_INVALIDARG);
}
NewArrayHolder<BYTE> pData(new BYTE[cbCacheSize]);
ULONG32 cbRead;
HRESULT hrRead = pTarget->ReadVirtual(PTR_TO_CORDB_ADDRESS(m_pbLS), pData, cbCacheSize , &cbRead);
if(FAILED(hrRead))
{
hrRead = CORDBG_E_READVIRTUAL_FAILURE;
}
if (SUCCEEDED(hrRead) && (cbCacheSize != cbRead))
{
hrRead = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
IfFailThrow(hrRead);
// Now do Transfer
m_pbRS = pData;
pData.SuppressRelease();
}
//---------------------------------------------------------------------------------------
// Marshals over a Byte buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_ByteBuffer::CopyLSDataToRS(ICorDebugDataTarget * pTarget)
{
CopyLSDataToRSWorker(pTarget);
}
//---------------------------------------------------------------------------------------
// Marshals over a string buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_StringBuffer::CopyLSDataToRS(ICorDebugDataTarget * pTarget)
{
CopyLSDataToRSWorker(pTarget);
// Ensure we're a valid, well-formed string.
// @dbgtodo - this should only happen in corrupted scenarios. Perhaps a better HR here?
// - null terminated.
// - no embedded nulls.
const WCHAR * pString = GetString();
SIZE_T dwExpectedLenWithNull = m_cbSize / sizeof(WCHAR);
// Should at least have 1 character for the null-terminator.
if (dwExpectedLenWithNull == 0)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
// Ensure that there's a null where we expect it to be.
if (pString[dwExpectedLenWithNull-1] != 0)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
// Now we know it's safe to call wcslen. The buffer is local, so we know the pages are there.
// And we know there's a null capping the max length of the string.
SIZE_T dwActualLenWithNull = wcslen(pString) + 1;
if (dwActualLenWithNull != dwExpectedLenWithNull)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
}
//---------------------------------------------------------------------------------------
// Marshals the arguments in a managed-debug event.
//
// Arguments:
// pManagedEvent - (IN/OUT) debug event to marshal. Events are not usable in the host process
// until they are marshalled. This will marshal the event in-place, and may convert
// some target addresses to host addresses.
//
// Return Value:
// S_OK on success. Else Error.
//
// Assumptions:
// Target is currently stopped and inspectable.
// After the event is marshalled, it has resources that must be cleaned up
// by calling code:DeleteIPCEventHelper.
//
// Notes:
// Call a Copy function (CopyManagedEventFromTarget, CopyRCEventFromIPCBlock)to
// get the event to marshal.
// This will marshal args from the target into the host.
// The debug event is fixed size. But since the debuggee is stopped, this can copy
// arbitrary-length buffers out of of the debuggee.
//
// This could be rolled into code:CordbProcess::RawDispatchEvent
//---------------------------------------------------------------------------------------
void CordbProcess::MarshalManagedEvent(DebuggerIPCEvent * pManagedEvent)
{
CONTRACTL
{
THROWS;
// Event has already been copied, now we do some quick Marshalling.
// Thsi should be a private local copy, and not the one in the IPC block or Target.
PRECONDITION(CheckPointer(pManagedEvent));
}
CONTRACTL_END;
IfFailThrow(pManagedEvent->hr);
// This may throw part way through marshalling. But that's ok because
// code:DeleteIPCEventHelper can cleanup a partially-marshalled event.
// Do a pre-processing on the event
switch (pManagedEvent->type & DB_IPCE_TYPE_MASK)
{
case DB_IPCE_MDA_NOTIFICATION:
{
pManagedEvent->MDANotification.szName.CopyLSDataToRS(this->m_pDACDataTarget);
pManagedEvent->MDANotification.szDescription.CopyLSDataToRS(this->m_pDACDataTarget);
pManagedEvent->MDANotification.szXml.CopyLSDataToRS(this->m_pDACDataTarget);
break;
}
case DB_IPCE_FIRST_LOG_MESSAGE:
{
pManagedEvent->FirstLogMessage.szContent.CopyLSDataToRS(this->m_pDACDataTarget);
break;
}
default:
break;
}
}
//---------------------------------------------------------------------------------------
// Copy a managed debug event from the target process into this local process
//
// Arguments:
// pRecord - native-debug event serving as the envelope for the managed event.
// pLocalManagedEvent - (dst) required local buffer to hold managed event.
//
// Return Value:
// * True if the event belongs to this runtime. This is very useful when multiple CLRs are
// loaded into the target and all sending events wit the same exception code.
// * False if this does not belong to this instance of ICorDebug. (perhaps it's an event
// intended for another instance of the CLR in the target, or some rogue user code happening
// to use our exception code).
// In either case, the event can still be cleaned up via code:DeleteIPCEventHelper.
//
// Throws on error. In the error case, the contents of pLocalManagedEvent are undefined.
// They may have been partially copied from the target. The local managed event does not own
// any resources until it's marshalled, so the buffer can be ignored if this function fails.
//
// Assumptions:
//
// Notes:
// The events are sent form the target via code:Debugger::SendRawEvent
// This just does a raw Byte copy, but does not do any Marshalling.
// This should always succeed in the well-behaved case. However, A bad debuggee can
// always send a poor-formed debug event.
// We don't distinguish between a badly formed event and an event that's not ours.
// The event still needs to be Marshaled before being used. (see code:CordbProcess::MarshalManagedEvent)
//
//---------------------------------------------------------------------------------------
#if defined(_MSC_VER) && defined(TARGET_ARM)
// This is a temporary workaround for an ARM specific MS C++ compiler bug (internal LKG build 18.1).
// Branch < if (ptrRemoteManagedEvent == NULL) > was always taken and the function always returned false.
// TODO: It should be removed once the bug is fixed.
#pragma optimize("", off)
#endif
bool CordbProcess::CopyManagedEventFromTarget(
const EXCEPTION_RECORD * pRecord,
DebuggerIPCEvent * pLocalManagedEvent)
{
_ASSERTE(pRecord != NULL);
_ASSERTE(pLocalManagedEvent != NULL);
// Initialize the event enough such backout code can call code:DeleteIPCEventHelper.
pLocalManagedEvent->type = DB_IPCE_DEBUGGER_INVALID;
// Ensure we have a CLR instance ID by now. Either we had one already, or we're in
// V2 mode and this is the startup event, and so we'll set it now.
HRESULT hr = EnsureClrInstanceIdSet();
IfFailThrow(hr);
_ASSERTE(m_clrInstanceId != 0);
// Determine if the event is really a debug event, and for our instance.
CORDB_ADDRESS ptrRemoteManagedEvent = IsEventDebuggerNotification(pRecord, m_clrInstanceId);
if (ptrRemoteManagedEvent == NULL)
{
return false;
}
// What we are doing on Windows here is dangerous. Any buffer for IPC events must be at least
// CorDBIPC_BUFFER_SIZE big, but here we are only copying sizeof(DebuggerIPCEvent). Fortunately, the
// only case where an IPC event is bigger than sizeof(DebuggerIPCEvent) is for the second category
// described in the comment for code:IEventChannel. In this case, we are just transferring the IPC
// event from the native pipeline to the event channel, and the event channel will read it directly from
// the send buffer on the LS. See code:CordbRCEventThread::WaitForIPCEventFromProcess.
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
hr = SafeReadStruct(ptrRemoteManagedEvent, pLocalManagedEvent);
#else
// For Mac remote debugging the address returned above is actually a local address.
// Also, we need to copy the entire buffer because once a debug event is read from the debugger
// transport, it won't be available afterwards.
memcpy(reinterpret_cast<BYTE *>(pLocalManagedEvent),
CORDB_ADDRESS_TO_PTR(ptrRemoteManagedEvent),
CorDBIPC_BUFFER_SIZE);
hr = S_OK;
#endif
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
IfFailThrow(hr);
return true;
}
#if defined(_MSC_VER) && defined(TARGET_ARM)
#pragma optimize("", on)
#endif
//---------------------------------------------------------------------------------------
// EnsureClrInstanceIdSet - Ensure we have a CLR Instance ID to debug
//
// In Arrowhead scenarios, the debugger is required to pass a valid CLR instance ID
// to us in OpenVirtualProcess. In V2 scenarios, for compatibility, we'll allow a
// CordbProcess object to exist for a process that doesn't yet have the CLR loaded.
// In this case the CLR instance ID will start off as 0, but be filled in when we see the
// startup exception indicating the CLR has been loaded.
//
// If we don't already have an instance ID, this function sets it to the only CLR in the
// target process. This requires that a CLR be loaded in the target process.
//
// Return Value:
// S_OK - if m_clrInstanceId was already set, or is now set to a valid CLR instance ID
// an error HRESULT - if m_clrInstanceId was 0, and cannot be set to a valid value
// (i.e. because we cannot find a CLR in the target process).
//
// Note that we need to probe for this on attach, and it's common to attach before the
// CLR has been loaded, so we avoid using exceptions for this common case.
//
HRESULT CordbProcess::EnsureClrInstanceIdSet()
{
// If we didn't expect a specific CLR, then attempt to attach to any.
if (m_clrInstanceId == 0)
{
// The only case in which we were allowed to request the "default" CLR instance
// ID is when we're running in V2 mode. In V3, the client is required to pass
// a non-zero value to OpenVirtualProcess. Since V2 is no longer supported we
// no longer attempt to find it.
if(m_cordb->GetTargetCLR() != 0)
{
m_clrInstanceId = PTR_TO_CORDB_ADDRESS(m_cordb->GetTargetCLR());
return S_OK;
}
// In V3, the client is required to pass a non-zero value to OpenVirtualProcess.
// In V2 mode we should be setting target CLR up front but return an error
// if we haven't.
_ASSERTE(m_pShim != NULL);
return E_UNEXPECTED;
}
// We've (now) got a valid CLR instance id
return S_OK;
}
//---------------------------------------------------------------------------------------
// // Copy event from IPC block into local.
//
// Arguments:
// pLocalManagedEvent - required local buffer to hold managed event.
//
// Return Value:
// None. Always succeeds.
//
// Assumptions:
// The IPC block has already been opened and filled in with an event.
//
// Notes:
// This is copying from a shared-memory block, which is treated as local memory.
// This just does a raw Byte copy, but does not do any Marshalling.
// This does no validation on the event.
// The event still needs to be Marshaled before being used. (see code:CordbProcess::MarshalManagedEvent)
//
//---------------------------------------------------------------------------------------
void inline CordbProcess::CopyRCEventFromIPCBlock(DebuggerIPCEvent * pLocalManagedEvent)
{
_ASSERTE(pLocalManagedEvent != NULL);
IfFailThrow(m_pEventChannel->GetEventFromLeftSide(pLocalManagedEvent));
}
// Return true if this is the RCEvent thread, else false.
bool CordbRCEventThread::IsRCEventThread()
{
return (m_threadId == GetCurrentThreadId());
}
//---------------------------------------------------------------------------------------
// Runtime assert, throws CORDBG_E_TARGET_INCONSISTENT if the expression is not true.
//
// Arguments:
// fExpression - assert parameter. If true, this function is a nop. If false,
// this will throw a CORDBG_E_TARGET_INCONSISTENT error.
//
// Notes:
// Use this for runtime checks to validate assumptions about the data-target.
// IcorDebug can't trust that data from the debugee is consistent (perhaps it's
// corrupted).
void CordbProcess::TargetConsistencyCheck(bool fExpression)
{
if (!fExpression)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "Target consistency check failed");
// When debugging possibly corrupt targets, this failure may be expected. For debugging purposes,
// assert if we're not expecting any target inconsistencies.
CONSISTENCY_CHECK_MSG( !m_fAssertOnTargetInconsistency, "Target consistency check failed unexpectedly");
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
}
//
// SendIPCEvent -- send an IPC event to the runtime controller. All this
// really does is copy the event into the process's send buffer and sets
// the RSEA then waits on RSER.
//
// Note: when sending a two-way event (replyRequired = true), the
// eventSize must be large enough for both the event sent and the
// result event.
//
// Returns whether the event was sent successfully. This is different than event->eventHr.
//
HRESULT CordbRCEventThread::SendIPCEvent(CordbProcess* process,
DebuggerIPCEvent* event,
SIZE_T eventSize)
{
_ASSERTE(process != NULL);
_ASSERTE(event != NULL);
_ASSERTE(process->GetShim() != NULL);
#ifdef _DEBUG
// We need to be synchronized whenever we're sending an IPC Event.
// This may require our callers' using a Stop-Continue holder.
// Attach + AsyncBreak are the only (obvious) exceptions.
// For continue, we set Sync-Status to false before sending, so we exclude that too.
// Everybody else should only be sending events when synced. We should never ever ever
// send an event from a CorbXYZ dtor (b/c that would be called at any random time). Instead,
// use a NeuterList.
switch (event->type)
{
case DB_IPCE_ATTACHING:
case DB_IPCE_ASYNC_BREAK:
case DB_IPCE_CONTINUE:
break;
default:
CONSISTENCY_CHECK_MSGF(process->GetSynchronized(), ("Must by synced while sending IPC event: %s (0x%x)",
IPCENames::GetName(event->type), event->type));
}
#endif
LOG((LF_CORDB, LL_EVERYTHING, "SendIPCEvent in CordbRCEventThread called\n"));
// For simplicity sake, we have the following conservative invariants when sending IPC events:
// - Always hold the Stop-Go lock.
// - never on the W32ET.
// - Never hold the Process-lock (this allows the w32et to take that lock to pump)
// Must have the stop-go lock to send an IPC event.
CONSISTENCY_CHECK_MSGF(process->GetStopGoLock()->HasLock(), ("Must have stop-go lock to send event. proc=%p, event=%s",
process, IPCENames::GetName(event->type)));
// The w32 ET will need to take the process lock. So if we're holding it here, then we'll
// deadlock (since W32 ET is blocked on lock, which we would hold; and we're blocked on W32 ET
// to keep pumping.
_ASSERTE(!process->ThreadHoldsProcessLock() || !"Can't hold P-lock while sending blocking IPC event");
// Can't be on the w32 ET, or we can't be pumping.
// Although we can trickle in here from public APIs, our caller should have validated
// that we weren't on the w32et, so the assert here is justified. But just in case there's something we missed,
// we have a runtime check (as a final backstop against a deadlock).
_ASSERTE(!process->IsWin32EventThread());
CORDBFailIfOnWin32EventThread(process);
// If this is an async event, then we expect it to be sent while the process is locked.
if (event->asyncSend)
{
// This may be on the w32et, so we can't hold the stop-go lock.
_ASSERTE(event->type == DB_IPCE_ATTACHING); // only async event should be attaching.
}
// This will catch us if we've detached or exited.
// Note if we exited, then we should have been neutered and so shouldn't even be sending an IPC event,
// but just in case, we'll check.
CORDBRequireProcessStateOK(process);
#ifdef _DEBUG
// We should never send an Async Break on the RCET. This will deadlock.
// - if we're on the RCET, we should be stopped, and thus Stop() should just bump up a stop count,
// and not actually send an AsyncBreak.
// - Delayed-Continues help enforce this.
// This is a special case of the deadlock check below.
if (IsRCEventThread())
{
_ASSERTE(event->type != DB_IPCE_ASYNC_BREAK);
}
#endif
#ifdef _DEBUG
// This assert protects us against a deadlock.
// 1) (RCET) blocked on (This function): If we're on the RCET, then the RCET is blocked until we return (duh).
// 2) (LS) blocked on (RCET): If the LS is not synchronized, then it may be sending an event to the RCET, and thus blocked on the RCET.
// 3) (Helper thread) blocked on (LS): That LS thread may be holding a lock that the helper thread needs, thus blocking the helper thread.
// 4) (This function) blocked on (Helper Thread): We block until the helper thread can process our IPC event.
// #4 is not true for async events.
//
// If we hit this assert, it means we may get the deadlock above and we're calling SendIPCEvent at a time we shouldn't.
// Note this race is as old as dirt.
if (IsRCEventThread() && !event->asyncSend)
{
// Note that w/ Continue & Attach, GetSynchronized() has a different meaning and the race above won't happen.
BOOL fPossibleDeadlock = process->GetSynchronized() || (event->type == DB_IPCE_CONTINUE) || (event->type == DB_IPCE_ATTACHING);
CONSISTENCY_CHECK_MSGF(fPossibleDeadlock, ("Possible deadlock while sending: '%s'\n", IPCENames::GetName(event->type)));
}
#endif
// Cache this process into the MRU so that we can find it if we're debugging in retail.
g_pRSDebuggingInfo->m_MRUprocess = process;
HRESULT hr = S_OK;
HRESULT hrEvent = S_OK;
_ASSERTE(event != NULL);
// NOTE: the eventSize parameter is only so you can specify an event size that is SMALLER than the process send
// buffer size!!
if (eventSize > CorDBIPC_BUFFER_SIZE)
return E_INVALIDARG;
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: sending %s to AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(event->type), VmPtrToCookie(event->vmAppDomain), process->m_id, process->m_id);
// For 2-way events, this check is unnecessary (since we already check for LS exit)
// But for async events, we need this.
// So just check it up here and make everyone's life easier.
if (process->m_terminated)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "CRCET::SIPCE: LS already terminated, shortcut exiting\n");
return CORDBG_E_PROCESS_TERMINATED;
}
// If the helper thread has died, we can't send an IPC event (and it's never coming back either).
// Although we do wait on the thread's handle, there are strange windows where the thread's handle
// is not yet signaled even though we've continued from the exit-thread event for the helper.
if (process->m_helperThreadDead)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "CRCET::SIPCE: Helper-thread dead, shortcut exiting\n");
return CORDBG_E_PROCESS_TERMINATED;
}
BOOL fUnrecoverableError = TRUE;
EX_TRY
{
hr = process->GetEventChannel()->SendEventToLeftSide(event, eventSize);
fUnrecoverableError = FALSE;
}
EX_CATCH_HRESULT(hr);
// If we're sending a Continue() event, then after this, the LS may run free.
// If this is the last managed event before the LS exits, (which is the case
// if we're responding to either an Exit-Thread or if we respond to a Detach)
// the LS may exit at anytime from here on, so we need to be careful.
if (fUnrecoverableError)
{
_ASSERTE(FAILED(hr));
CORDBSetUnrecoverableError(process, hr, 0);
}
else
{
// Get a handle to the target process - this call always succeeds
HANDLE hLSProcess = NULL;
process->GetHandle(&hLSProcess);
// We take locks to ensure that the CordbProcess object is still alive,
// even if the OS process exited.
_ASSERTE(hLSProcess != NULL);
// Check if Sending the IPC event failed
if (FAILED(hr))
{
// The failure to send an event may be due to the target process terminating
// (especially, but not exclusively, in the case of async events).
// There is a race here - we can't rely on any check above SendEventToLeftSide
// to tell us whether the process has exited yet.
// Check for that case and return an accurate hresult.
DWORD ret = WaitForSingleObject(hLSProcess, 0);
if (ret == WAIT_OBJECT_0)
{
return CORDBG_E_PROCESS_TERMINATED;
}
// Some other failure sending the IPC event - just return it.
return hr;
}
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: sent...\n");
// If this is an async send, then don't wait for the left side to acknowledge that its read the event.
_ASSERTE(!event->asyncSend || !event->replyRequired);
if (process->GetEventChannel()->NeedToWaitForAck(event))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000,"CRCET::SIPCE: waiting for left side to read event. (on RSER)\n");
DWORD ret;
// Wait for either a reply (common case) or the left side to go away.
// We can't detach while waiting for a reply (because detach needs to send events).
// All of the outcomes from this wait are completely disjoint.
// It's possible for the LS to reply and then exit normally (Thread_Detach, Process_Detach)
// and so ExitProcess may have been called, but it doesn't matter.
enum {
ID_RSER = WAIT_OBJECT_0,
ID_LSPROCESS,
ID_HELPERTHREAD,
};
// Only wait on the helper thread for cases where the process is stopped (and thus we don't expect it do exit on us).
// If the process is running and we lose our helper thread, it ought to be during shutdown and we ough to
// follow up with an exit.
// This includes when we've dispatch Native events, and it includes the AsyncBreak sent to get us from a
// win32 frozen state to a synchronized state).
HANDLE hHelperThread = NULL;
if (process->IsStopped())
{
hHelperThread = process->GetHelperThreadHandle();
}
// Note that in case of a tie (multiple handles signaled), WaitForMultipleObjects gives
// priority to the handle earlier in the array.
HANDLE waitSet[] = { process->GetEventChannel()->GetRightSideEventAckHandle(), hLSProcess, hHelperThread};
DWORD cWaitSet = ARRAY_SIZE(waitSet);
if (hHelperThread == NULL)
{
cWaitSet--;
}
do
{
ret = WaitForMultipleObjectsEx(cWaitSet, waitSet, FALSE, CordbGetWaitTimeout(), FALSE);
// If we timeout because we're waiting for an uncontinued OOB event, we need to just keep waiting.
} while ((ret == WAIT_TIMEOUT) && process->IsWaitingForOOBEvent());
switch(ret)
{
case ID_RSER:
// Normal reply from LS.
// This is set iff the LS replied to our event. The LS may have exited since it replied
// but we don't care. We still have the reply and we'll pass it on.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side read the event.\n");
// If this was a two-way event, then the result is already ready for us. Simply copy the result back
// over the original event that was sent. Otherwise, the left side has simply read the event and is
// processing it...
if (event->replyRequired)
{
process->GetEventChannel()->GetReplyFromLeftSide(event, eventSize);
hrEvent = event->hr;
}
break;
case ID_LSPROCESS:
// Left side exited on us.
// ExitProcess may or may not have been called here (since it's on a different thread).
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side exiting while RS was waiting for reply.\n");
hr = CORDBG_E_PROCESS_TERMINATED;
break;
case ID_HELPERTHREAD:
// We can only send most IPC events while the LS is synchronized. We shouldn't lose our helper thread
// when synced under any sort of normal conditions.
// This won't fire if the process already exited, because LSPROCESS gets higher priority in the wait
// (since it was placed earlier).
// Thus the only "legitimate" window where this could happen would be in a shutdown scenario after
// the helper is dead but before the process has died. We shouldn't be synced in that scenario,
// so we shouldn't be sending IPC events during it.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: lost helper thread.\n");
// Assert because we want to know if we ever actually hit this in any detectable scenario.
// However, shutdown can occur in preemptive mode. Thus if the RS does an AsyncBreak late
// enough, then the LS will appear to be stopped but may still shutdown.
// Since the debuggee can exit asynchronously at any time (eg, suppose somebody forcefully
// kills it with taskman), this doesn't introduce a new case.
// That aside, it would be great to be able to assert this:
//_ASSERTE(!"Potential deadlock - Randomly Lost helper thread");
// We'll piggy back this on the terminated case.
hr = CORDBG_E_PROCESS_TERMINATED;
break;
default:
{
// If we timed out/failed, check the left side to see if it is in the unrecoverable error mode. If it is,
// return the HR from the left side that caused the error. Otherwise, return that we timed out and that
// we don't really know why.
HRESULT realHR = (ret == WAIT_FAILED) ? HRESULT_FROM_GetLastError() : ErrWrapper(CORDBG_E_TIMEOUT);
hr = process->CheckForUnrecoverableError();
if (hr == S_OK)
{
CORDBSetUnrecoverableError(process, realHR, 0);
hr = realHR;
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side timeout/fail while RS waiting for reply. hr = 0x%08x\n", hr);
}
break;
}
// If the LS picked up RSEA, it will be reset (since it's an auto event).
// But in the case that the wait failed or that the LS exited, we need to explicitly reset RSEA
if (hr != S_OK)
{
process->GetEventChannel()->ClearEventForLeftSide();
}
// Done waiting for reply.
}
}
process->ForceDacFlush();
// The hr and hrEvent are 2 very different things.
// hr tells us whether the event was sent successfully.
// hrEvent tells us how the LS responded to it.
// if FAILED(hr), then hrEvent is useless b/c the LS never got it.
// But if SUCCEEDED(hr), then hrEvent may still have failed and that could be
// valuable information.
return hr;
}
//---------------------------------------------------------------------------------------
// FlushQueuedEvents flushes a process's event queue.
//
// Arguments:
// pProcess - non-null process object whose queue will be drained
//
// Notes:
// @dbgtodo shim: this should be part of the shim.
// This dispatches events that are queued up. The queue is populated by
// the shim's proxy callback (see code:ShimProxyCallback). This will dispatch events
// to the 'real' callback supplied by the debugger. This will dispatch events
// as long as the debugger keeps calling continue.
//
// This requires that the process lock be held, although it will toggle the lock.
void CordbRCEventThread::FlushQueuedEvents(CordbProcess* process)
{
CONTRACTL
{
NOTHROW; // This is happening on the RCET thread, so there's no place to propagate an error back up.
}
CONTRACTL_END;
STRESS_LOG0(LF_CORDB,LL_INFO10000, "CRCET::FQE: Beginning to flush queue\n");
_ASSERTE(process->GetShim() != NULL);
// We should only call this is we already have queued events
_ASSERTE(!process->GetShim()->GetManagedEventQueue()->IsEmpty());
//
// Dispatch queued events so long as they keep calling Continue()
// before returning from their callback. If they call Continue(),
// process->m_synchronized will be false again and we know to
// loop around and dispatch the next event.
//
_ASSERTE(process->ThreadHoldsProcessLock());
// Give shim a chance to queue any faked attach events. Grab a pointer to the
// ShimProcess now, while we still hold the process lock. Once we release the lock,
// GetShim() may not work.
RSExtSmartPtr<ShimProcess> pShim(process->GetShim());
// Release lock before we call out to shim to Queue fake events.
{
RSInverseLockHolder inverseLockHolder(process->GetProcessLock());
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(pProcess);
// Because we've released the lock, at any point from here forward the
// CorDbProcess may suddenly get neutered if the user detaches the debugger.
pShim->QueueFakeAttachEventsIfNeeded(false);
}
}
// Now that we're holding the process lock again, we can safely check whether
// process has become neutered
if (process->IsNeutered())
{
return;
}
{
// Main dispatch loop here. DispatchRCEvent will take events out of the
// queue and invoke callbacks
do
{
// DispatchRCEvent will mark the process as stopped before dispatching.
process->DispatchRCEvent();
LOG((LF_CORDB,LL_INFO10000, "CRCET::FQE: Finished w/ "
"DispatchRCEvent\n"));
}
while (process->GetSyncCompleteRecv() &&
(process->GetSynchronized() == false) &&
(process->GetShim() != NULL) && // may have lost Shim if we detached while dispatch
(!process->GetShim()->GetManagedEventQueue()->IsEmpty()) &&
(process->m_unrecoverableError == false));
}
//
// If they returned from a callback without calling Continue() then
// the process is still synchronized, so let the rc event thread
// know that it need to update its process list and remove the
// process's event.
//
if (process->GetSynchronized())
{
ProcessStateChanged();
}
LOG((LF_CORDB,LL_INFO10000, "CRCET::FQE: finished\n"));
}
//---------------------------------------------------------------------------------------
// Preliminary Handle an Notification event from the target. This may queue the event,
// but does not actually dispatch the event.
//
// Arguments:
// pManagedEvent - local managed-event. On success, this function assumes ownership of the
// event and will delete its memory. Assumed that caller allocated via 'new'.
// pCallback - callback obecjt to dispatch events on.
//
// Return Value:
// None. Throws on error. On error, caller still owns the pManagedEvent and must free it.
//
// Assumptions:
// This should be called once a notification event is received from the target.
//
// Notes:
// HandleRCEvent -- handle an IPC event received from the runtime controller.
// This will update ICorDebug state and immediately dispatch the event.
//
//---------------------------------------------------------------------------------------
void CordbProcess::HandleRCEvent(
DebuggerIPCEvent * pManagedEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback)
{
CONTRACTL
{
THROWS;
PRECONDITION(CheckPointer(pManagedEvent));
PRECONDITION(CheckPointer(pCallback));
PRECONDITION(ThreadHoldsProcessLock());
}
CONTRACTL_END;
if (!this->IsSafeToSendEvents() || this->m_exiting)
{
return;
}
// Marshals over some standard data from event.
MarshalManagedEvent(pManagedEvent);
STRESS_LOG4(LF_CORDB, LL_INFO1000, "RCET::TP: Got %s for AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(pManagedEvent->type), VmPtrToCookie(pManagedEvent->vmAppDomain), this->m_id, this->m_id);
RSExtSmartPtr<ICorDebugManagedCallback2> pCallback2;
pCallback->QueryInterface(IID_ICorDebugManagedCallback2, reinterpret_cast<void **> (&pCallback2));
RSExtSmartPtr<ICorDebugManagedCallback3> pCallback3;
pCallback->QueryInterface(IID_ICorDebugManagedCallback3, reinterpret_cast<void **> (&pCallback3));
RSExtSmartPtr<ICorDebugManagedCallback4> pCallback4;
pCallback->QueryInterface(IID_ICorDebugManagedCallback4, reinterpret_cast<void **> (&pCallback4));
// Dispatch directly. May not necessarily dispatch an event.
// Toggles the lock to dispatch callbacks.
RawDispatchEvent(pManagedEvent, pLockHolder, pCallback, pCallback2, pCallback3, pCallback4);
}
//
// ProcessStateChanged -- tell the rc event thread that the ICorDebug's
// process list has changed by setting its flag and thread control event.
// This will cause the rc event thread to update its set of handles to wait
// on.
//
void CordbRCEventThread::ProcessStateChanged()
{
m_cordb->LockProcessList();
STRESS_LOG0(LF_CORDB, LL_INFO100000, "CRCET::ProcessStateChanged\n");
m_processStateChanged = TRUE;
SetEvent(m_threadControlEvent);
m_cordb->UnlockProcessList();
}
//---------------------------------------------------------------------------------------
// Primary loop of the Runtime Controller event thread. This routine loops during the
// debug session taking IPC events from the IPC block and calling out to process them.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Notes:
// @dbgtodo shim: eventually hoist the entire RCET into the shim.
//---------------------------------------------------------------------------------------
void CordbRCEventThread::ThreadProc()
{
HANDLE waitSet[MAXIMUM_WAIT_OBJECTS];
CordbProcess * rgProcessSet[MAXIMUM_WAIT_OBJECTS];
unsigned int waitCount;
#ifdef _DEBUG
memset(&rgProcessSet, NULL, MAXIMUM_WAIT_OBJECTS * sizeof(CordbProcess *));
memset(&waitSet, NULL, MAXIMUM_WAIT_OBJECTS * sizeof(HANDLE));
#endif
// First event to wait on is always the thread control event.
waitSet[0] = m_threadControlEvent;
rgProcessSet[0] = NULL;
waitCount = 1;
while (m_run)
{
DWORD dwStatus = WaitForMultipleObjectsEx(waitCount, waitSet, FALSE, 2000, FALSE);
if (dwStatus == WAIT_FAILED)
{
STRESS_LOG1(LF_CORDB, LL_INFO10000, "CordbRCEventThread::ThreadProc WaitFor"
"MultipleObjects failed: 0x%x\n", GetLastError());
}
#ifdef _DEBUG
else if ((dwStatus >= WAIT_OBJECT_0) && (dwStatus < WAIT_OBJECT_0 + waitCount) && m_run)
{
// Got an event. Figure out which process it came from.
unsigned int procNumber = dwStatus - WAIT_OBJECT_0;
if (procNumber != 0)
{
// @dbgtodo shim: rip all of this out. Leave the assert in for now to verify that we're not accidentally
// going down this codepath. Once we rip this out, we can also simplify some of the code below.
// Notification events (including Sync-complete) should be coming from Win32 event thread via
// V3 pipeline.
_ASSERTE(!"Shouldn't be here");
}
}
#endif
// Empty any queued work items.
DrainWorkerQueue();
// Check a flag to see if we need to update our list of processes to wait on.
if (m_processStateChanged)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "RCET::TP: refreshing process list.\n");
unsigned int i;
//
// free the old wait list
//
for (i = 1; i < waitCount; i++)
{
rgProcessSet[i]->InternalRelease();
}
// Pass 1: iterate the hash of all processes and collect the unsynchronized ones into the wait list.
// Note that Stop / Continue can still be called on a different thread while we're doing this.
m_cordb->LockProcessList();
m_processStateChanged = FALSE;
waitCount = 1;
CordbSafeHashTable<CordbProcess> * pHashTable = m_cordb->GetProcessList();
HASHFIND hashFind;
CordbProcess * pProcess;
for (pProcess = pHashTable->FindFirst(&hashFind); pProcess != NULL; pProcess = pHashTable->FindNext(&hashFind))
{
_ASSERTE(waitCount < MAXIMUM_WAIT_OBJECTS);
if( waitCount >= MAXIMUM_WAIT_OBJECTS )
{
break;
}
// Only listen to unsynchronized processes. Processes that are synchronized will not send events without
// being asked by us first, so there is no need to async listen to them.
//
// Note: if a process is not synchronized then there is no way for it to transition to the syncrhonized
// state without this thread receiving an event and taking action. So there is no need to lock the
// per-process mutex when checking the process's synchronized flag here.
if (!pProcess->GetSynchronized() && pProcess->IsSafeToSendEvents())
{
STRESS_LOG2(LF_CORDB, LL_INFO1000, "RCET::TP: listening to process 0x%x(%d)\n",
pProcess->m_id, pProcess->m_id);
waitSet[waitCount] = pProcess->m_leftSideEventAvailable;
rgProcessSet[waitCount] = pProcess;
rgProcessSet[waitCount]->InternalAddRef();
waitCount++;
}
}
m_cordb->UnlockProcessList();
// Pass 2: for each process that we placed in the wait list, determine if there are any existing queued
// events that need to be flushed.
// Start i at 1 to skip the control event...
i = 1;
while(i < waitCount)
{
pProcess = rgProcessSet[i];
// Take the process lock so we can check the queue safely
pProcess->Lock();
// Now that we've just locked the processes, we can safely inspect it and dispatch events.
// The process may have changed since when we first added it to the process list in Pass 1,
// so we can't make any assumptions about whether it's sync, live, or exiting.
// Flush the queue if necessary. Note, we only do this if we've actually received a SyncComplete message
// from this process. If we haven't received a SyncComplete yet, then we don't attempt to drain any
// queued events yet. They'll be drained when the SyncComplete event is actually received.
if (pProcess->GetSyncCompleteRecv() &&
(pProcess->GetShim() != NULL) &&
!pProcess->GetSynchronized())
{
if (pProcess->GetShim()->GetManagedEventQueue()->IsEmpty())
{
// Effectively what we are doing here is to continue everything without actually
// handling an event. We can get here if the event raised by the LS is a duplicate
// creation event, which the shim discards without adding it to the event queue.
// See code:ShimProcess::IsDuplicateCreationEvent.
//
// To continue, we need to increment the stop count first. Also, we can't call
// Continue() while holding the process lock.
pProcess->SetSynchronized(true);
pProcess->IncStopCount();
pProcess->Unlock();
pProcess->ContinueInternal(FALSE);
pProcess->Lock();
}
else
{
// This may toggle the process-lock
FlushQueuedEvents(pProcess);
}
}
// Flushing could have left the process synchronized...
// Common case is if the callback didn't call Continue().
if (pProcess->GetSynchronized())
{
// remove the process from the wait list by moving all the other processes down one.
if ((i + 1) < waitCount)
{
memcpy(&rgProcessSet[i], &(rgProcessSet[i+1]), sizeof(rgProcessSet[0]) * (waitCount - i - 1));
memcpy(&waitSet[i], &waitSet[i+1], sizeof(waitSet[0]) * (waitCount - i - 1));
}
// drop the count of processes to wait on
waitCount--;
pProcess->Unlock();
// make sure to release the reference we added when the process was added to the wait list.
pProcess->InternalRelease();
// We don't have to increment i because we've copied the next element into
// the current value at i.
}
else
{
// Even after flushing, its still not syncd, so leave it in the wait list.
pProcess->Unlock();
// Increment i normally.
i++;
}
}
} // end ProcessStateChanged
} // while (m_run)
#ifdef _DEBUG_IMPL
// We intentionally return while leaking some CordbProcess objects inside
// rgProcessSet, in some cases (e.g., I've seen this happen when detaching from a
// debuggee almost immediately after attaching to it). In the future, we should
// really consider not leaking these anymore. However, I'm unsure how safe it is to just
// go and InternalRelease() those guys, as above we intentionally DON'T release them when
// they're not synchronized. So for now, to make debug builds happy, exclude those
// references when we run CheckMemLeaks() later on. In our next side-by-side release,
// consider actually doing InternalRelease() on the remaining CordbProcesses on
// retail, and then we can remove the following loop.
for (UINT i=1; i < waitCount; i++)
{
InterlockedDecrement(&Cordb::s_DbgMemTotalOutstandingInternalRefs);
}
#endif //_DEBUG_IMPL
}
//
// This is the thread's real thread proc. It simply calls to the
// thread proc on the given object.
//
/*static*/
DWORD WINAPI CordbRCEventThread::ThreadProc(LPVOID parameter)
{
CordbRCEventThread * pThread = (CordbRCEventThread *) parameter;
INTERNAL_THREAD_ENTRY(pThread);
pThread->ThreadProc();
return 0;
}
template<typename T>
InterlockedStack<T>::InterlockedStack()
{
m_pHead = NULL;
}
template<typename T>
InterlockedStack<T>::~InterlockedStack()
{
// This is an arbitrary choice. We expect the stacks be drained.
_ASSERTE(m_pHead == NULL);
}
// Thread safe pushes + pops.
// Many threads can push simultaneously.
// Only 1 thread can pop.
template<typename T>
void InterlockedStack<T>::Push(T * pItem)
{
// InterlockedCompareExchangePointer(&dest, ex, comp).
// Really behaves like:
// val = *dest;
// if (*dest == comp) { *dest = ex; }
// return val;
//
// We can do a thread-safe assign { comp = dest; dest = ex } via:
// do { comp = dest } while (ICExPtr(&dest, ex, comp) != comp));
do
{
pItem->m_next = m_pHead;
}
while(InterlockedCompareExchangeT(&m_pHead, pItem, pItem->m_next) != pItem->m_next);
}
// Returns NULL on empty,
// else returns the head of the list.
template<typename T>
T * InterlockedStack<T>::Pop()
{
if (m_pHead == NULL)
{
return NULL;
}
// This allows 1 thread to Pop() and race against N threads doing a Push().
T * pItem = NULL;
do
{
pItem = m_pHead;
} while(InterlockedCompareExchangeT(&m_pHead, pItem->m_next, pItem) != pItem);
return pItem;
}
// RCET will take ownership of this item and delete it.
// This can be done w/o taking any locks (thus it can be called from any lock context)
// This may race w/ the RCET draining the queue.
void CordbRCEventThread::QueueAsyncWorkItem(RCETWorkItem * pItem)
{
// @todo -
// Non-blocking insert into queue.
_ASSERTE(pItem != NULL);
m_WorkerStack.Push(pItem);
// Ping the RCET so that it drains the queue.
SetEvent(m_threadControlEvent);
}
// Execute & delete all workitems in the queue.
// This can be done w/o taking any locks. (though individual items may take locks).
void CordbRCEventThread::DrainWorkerQueue()
{
_ASSERTE(IsRCEventThread());
while(true)
{
RCETWorkItem* pCur = m_WorkerStack.Pop();
if (pCur == NULL)
{
break;
}
pCur->Do();
delete pCur;
}
}
//---------------------------------------------------------------------------------------
// Wait for an reply from the debuggee.
//
// Arguments:
// pProcess - process for debuggee.
// pAppDomain - not used.
// pEvent - caller-allocated event to be filled out.
// This is expected to be at least as big as CorDBIPC_BUFFER_SIZE.
//
// Return Value:
// S_OK on success. else failure.
//
// Assumptions:
// Caller allocates
//
// Notes:
// WaitForIPCEventFromProcess waits for an event from just the specified
// process. This should only be called when the process is in a synchronized
// state, which ensures that the RCEventThread isn't listening to the
// process's event, too, which would get confusing.
//
// @dbgtodo - this function should eventually be obsolete once everything
// is using DAC calls instead of helper-thread.
//
//---------------------------------------------------------------------------------------
HRESULT CordbRCEventThread::WaitForIPCEventFromProcess(CordbProcess * pProcess,
CordbAppDomain * pAppDomain,
DebuggerIPCEvent * pEvent)
{
CORDBRequireProcessStateOKAndSync(pProcess, pAppDomain);
DWORD dwStatus;
HRESULT hr = S_OK;
do
{
dwStatus = SafeWaitForSingleObject(pProcess,
pProcess->m_leftSideEventAvailable,
CordbGetWaitTimeout());
if (pProcess->m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
// If we timeout because we're waiting for an uncontinued OOB event, we need to just keep waiting.
} while ((dwStatus == WAIT_TIMEOUT) && pProcess->IsWaitingForOOBEvent());
if (dwStatus == WAIT_OBJECT_0)
{
pProcess->CopyRCEventFromIPCBlock(pEvent);
EX_TRY
{
pProcess->MarshalManagedEvent(pEvent);
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: Got %s for AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(pEvent->type),
VmPtrToCookie(pEvent->vmAppDomain),
pProcess->m_id,
pProcess->m_id);
}
EX_CATCH_HRESULT(hr)
SetEvent(pProcess->m_leftSideEventRead);
return hr;
}
else if (dwStatus == WAIT_TIMEOUT)
{
//
// If we timed out, check the left side to see if it is in the
// unrecoverable error mode. If it is, return the HR from the
// left side that caused the error. Otherwise, return that we timed
// out and that we don't really know why.
//
HRESULT realHR = ErrWrapper(CORDBG_E_TIMEOUT);
hr = pProcess->CheckForUnrecoverableError();
if (hr == S_OK)
{
CORDBSetUnrecoverableError(pProcess, realHR, 0);
return realHR;
}
else
return hr;
}
else
{
_ASSERTE(dwStatus == WAIT_FAILED);
hr = HRESULT_FROM_GetLastError();
CORDBSetUnrecoverableError(pProcess, hr, 0);
return hr;
}
}
//
// Start actually creates and starts the thread.
//
HRESULT CordbRCEventThread::Start()
{
if (m_threadControlEvent == NULL)
{
return E_INVALIDARG;
}
m_thread = CreateThread(NULL,
0,
&CordbRCEventThread::ThreadProc,
(LPVOID) this,
0,
&m_threadId);
if (m_thread == NULL)
{
return HRESULT_FROM_GetLastError();
}
return S_OK;
}
//
// Stop causes the thread to stop receiving events and exit. It
// waits for it to exit before returning.
//
HRESULT CordbRCEventThread::Stop()
{
if (m_thread != NULL)
{
LOG((LF_CORDB, LL_INFO100000, "CRCET::Stop\n"));
m_run = FALSE;
SetEvent(m_threadControlEvent);
DWORD ret = WaitForSingleObject(m_thread, INFINITE);
if (ret != WAIT_OBJECT_0)
{
return HRESULT_FROM_GetLastError();
}
}
m_cordb.Clear();
return S_OK;
}
/* ------------------------------------------------------------------------- *
* Win32 Event Thread class
* ------------------------------------------------------------------------- */
enum
{
W32ETA_NONE = 0,
W32ETA_CREATE_PROCESS = 1,
W32ETA_ATTACH_PROCESS = 2,
W32ETA_CONTINUE = 3,
W32ETA_DETACH = 4
};
//---------------------------------------------------------------------------------------
// Constructor
//
// Arguments:
// pCordb - Pointer to the owning cordb object for this event thread.
// pShim - Pointer to the shim for supporting V2 debuggers on V3 architecture.
//
//---------------------------------------------------------------------------------------
CordbWin32EventThread::CordbWin32EventThread(
Cordb * pCordb,
ShimProcess * pShim
) :
m_thread(NULL), m_threadControlEvent(NULL),
m_actionTakenEvent(NULL), m_run(TRUE),
m_action(W32ETA_NONE)
{
m_cordb.Assign(pCordb);
_ASSERTE(pCordb != NULL);
m_pShim = pShim;
m_pNativePipeline = NULL;
}
//
// Destructor. Cleans up all of the open handles and such.
// This expects that the thread has been stopped and has terminated
// before being called.
//
CordbWin32EventThread::~CordbWin32EventThread()
{
if (m_thread != NULL)
CloseHandle(m_thread);
if (m_threadControlEvent != NULL)
CloseHandle(m_threadControlEvent);
if (m_actionTakenEvent != NULL)
CloseHandle(m_actionTakenEvent);
if (m_pNativePipeline != NULL)
{
m_pNativePipeline->Delete();
m_pNativePipeline = NULL;
}
m_sendToWin32EventThreadMutex.Destroy();
}
//
// Init sets up all the objects that the thread will need to run.
//
HRESULT CordbWin32EventThread::Init()
{
if (m_cordb == NULL)
return E_INVALIDARG;
m_sendToWin32EventThreadMutex.Init("Win32-Send lock", RSLock::cLockFlat, RSLock::LL_WIN32_SEND_LOCK);
m_threadControlEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_threadControlEvent == NULL)
return HRESULT_FROM_GetLastError();
m_actionTakenEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_actionTakenEvent == NULL)
return HRESULT_FROM_GetLastError();
m_pNativePipeline = NewPipelineWithDebugChecks();
if (m_pNativePipeline == NULL)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
//
// Main function of the Win32 Event Thread
//
void CordbWin32EventThread::ThreadProc()
{
#if defined(RSCONTRACTS)
DbgRSThread::GetThread()->SetThreadType(DbgRSThread::cW32ET);
// The win32 ET conceptually holds a lock (all threads do).
DbgRSThread::GetThread()->TakeVirtualLock(RSLock::LL_WIN32_EVENT_THREAD);
#endif
// In V2, the debuggee decides what to do if the debugger rudely exits / detaches. (This is
// handled by host policy). With the OS native-debuggging pipeline, the debugger by default
// kills the debuggee if it exits. To emulate V2 behavior, we need to override that default.
BOOL fOk = m_pNativePipeline->DebugSetProcessKillOnExit(FALSE);
(void)fOk; //prevent "unused variable" error from GCC
_ASSERTE(fOk);
// Run the top-level event loop.
Win32EventLoop();
#if defined(RSCONTRACTS)
// The win32 ET conceptually holds a lock (all threads do).
DbgRSThread::GetThread()->ReleaseVirtualLock(RSLock::LL_WIN32_EVENT_THREAD);
#endif
}
// Define a holder that calls code:DeleteIPCEventHelper
using DeleteIPCEventHolder = SpecializedWrapper<DebuggerIPCEvent, DeleteIPCEventHelper>;
//---------------------------------------------------------------------------------------
//
// Helper to clean up IPCEvent before deleting it.
// This must be called after an event is marshalled via code:CordbProcess::MarshalManagedEvent
//
// Arguments:
// pManagedEvent - managed event to delete.
//
// Notes:
// This can delete a partially marshalled event.
//
void DeleteIPCEventHelper(DebuggerIPCEvent *pManagedEvent)
{
CONTRACTL
{
// This is backout code that shouldn't need to throw.
NOTHROW;
}
CONTRACTL_END;
if (pManagedEvent == NULL)
{
return;
}
switch (pManagedEvent->type & DB_IPCE_TYPE_MASK)
{
// so far only this event need to cleanup.
case DB_IPCE_MDA_NOTIFICATION:
pManagedEvent->MDANotification.szName.CleanUp();
pManagedEvent->MDANotification.szDescription.CleanUp();
pManagedEvent->MDANotification.szXml.CleanUp();
break;
case DB_IPCE_FIRST_LOG_MESSAGE:
pManagedEvent->FirstLogMessage.szContent.CleanUp();
break;
default:
break;
}
delete [] (BYTE *)pManagedEvent;
}
//---------------------------------------------------------------------------------------
// Handle a CLR specific notification event.
//
// Arguments:
// pManagedEvent - non-null pointer to a managed event.
// pLockHolder - hold to process lock that gets toggled if this dispatches an event.
// pCallback - callback to dispatch potential managed events.
//
// Return Value:
// Throws on error.
//
// Assumptions:
// Target is stopped. Record was already determined to be a CLR event.
//
// Notes:
// This is called after caller does WaitForDebugEvent.
// Any exception this Filter does not recognize is treated as kNotClr.
// Currently, this includes both managed-exceptions and unmanaged ones.
// For interop-debugging, the interop logic will handle all kNotClr and triage if
// it's really a non-CLR exception.
//
//---------------------------------------------------------------------------------------
void CordbProcess::FilterClrNotification(
DebuggerIPCEvent * pManagedEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback)
{
CONTRACTL
{
THROWS;
PRECONDITION(CheckPointer(pManagedEvent));
PRECONDITION(CheckPointer(pCallback));
PRECONDITION(ThreadHoldsProcessLock());
}
CONTRACTL_END;
// There are 3 types of events from the LS:
// 1) Replies (eg, corresponding to WaitForIPCEvent)
// we need to set LSEA/wait on LSER.
// 2) Sync-Complete (kind of like a special notification)
// Ping the helper
// 3) Notifications (eg, Module-load):
// these are dispatched immediately.
// 4) Left-side Startup event
// IF we're synced, then we must be getting a "Reply".
bool fReply = this->GetSynchronized();
LOG((LF_CORDB, LL_INFO10000, "CP::FCN - Received event %s; fReply: %d\n",
IPCENames::GetName(pManagedEvent->type),
fReply));
if (fReply)
{
//
_ASSERTE(m_pShim != NULL);
//
// Case 1: Reply
//
pLockHolder->Release();
_ASSERTE(!ThreadHoldsProcessLock());
// Save the IPC event and wake up the thread which is waiting for it from the LS.
GetEventChannel()->SaveEventFromLeftSide(pManagedEvent);
SetEvent(this->m_leftSideEventAvailable);
// Some other thread called code:CordbRCEventThread::WaitForIPCEventFromProcess, and
// that will respond here and set the event.
DWORD dwResult = WaitForSingleObject(this->m_leftSideEventRead, CordbGetWaitTimeout());
pLockHolder->Acquire();
if (dwResult != WAIT_OBJECT_0)
{
// The wait failed. This is probably WAIT_TIMEOUT which suggests a deadlock/assert on
// the RCEventThread.
CONSISTENCY_CHECK_MSGF(false, ("WaitForSingleObject failed: %d", dwResult));
ThrowHR(CORDBG_E_TIMEOUT);
}
}
else
{
if (pManagedEvent->type == DB_IPCE_LEFTSIDE_STARTUP)
{
//
// Case 4: Left-side startup event. We'll mark that we're attached from oop.
//
// Now that LS is started, we should definitely be able to instantiate DAC.
InitializeDac();
// @dbgtodo 'attach-bit': we don't want the debugger automatically invading the process.
GetDAC()->MarkDebuggerAttached(TRUE);
}
else if (pManagedEvent->type == DB_IPCE_SYNC_COMPLETE)
{
// Since V3 doesn't request syncs, it shouldn't get sync-complete.
// @dbgtodo sync: this changes when V3 can explicitly request an AsyncBreak.
_ASSERTE(m_pShim != NULL);
//
// Case 2: Sync Complete
//
HandleSyncCompleteReceived();
}
else
{
//
// Case 3: Notification. This will dispatch the event immediately.
//
// Toggles the process-lock if it dispatches callbacks.
HandleRCEvent(pManagedEvent, pLockHolder, pCallback);
} // end Notification
}
}
//
// If the thread has an unhandled managed exception, hijack it.
//
// Arguments:
// dwThreadId - OS Thread id.
//
// Returns:
// True if hijacked; false if not.
//
// Notes:
// This is called from shim to emulate being synchronized at an unhandled
// exception.
// Other ICorDebug operations could calls this (eg, func-eval at 2nd chance).
BOOL CordbProcess::HijackThreadForUnhandledExceptionIfNeeded(DWORD dwThreadId)
{
PUBLIC_API_ENTRY(this); // from Shim
BOOL fHijacked = FALSE;
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
// OS will not execute the Unhandled Exception Filter under native debugger, so
// we need to hijack the thread to get it to execute the UEF, which will then do
// work for unhandled managed exceptions.
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
if (pThread != NULL)
{
// If the thread has a managed exception, then we should have a pThread object.
if (pThread->HasUnhandledNativeException())
{
_ASSERTE(pThread->IsThreadExceptionManaged()); // should have been marked earlier
pThread->HijackForUnhandledException();
fHijacked = TRUE;
}
}
}
EX_CATCH_HRESULT(hr);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return fHijacked;
}
//---------------------------------------------------------------------------------------
// Validate the given exception record or throw.
//
// Arguments:
// pRawRecord - non-null raw bytes of the exception
// countBytes - number of bytes in pRawRecord buffer.
// format - format of pRawRecord
//
// Returns:
// A type-safe exception record from the raw buffer.
//
// Notes:
// This is a helper for code:CordbProcess::Filter.
// This can do consistency checks on the incoming parameters such as:
// * verify countBytes matches the expected size for the given format.
// * verify the format is supported.
//
// If we let a given ICD understand multiple formats (eg, have x86 understand both Exr32 and
// Exr64), this would be the spot to allow the conversion.
//
const EXCEPTION_RECORD * CordbProcess::ValidateExceptionRecord(
const BYTE pRawRecord[],
DWORD countBytes,
CorDebugRecordFormat format)
{
ValidateOrThrow(pRawRecord);
//
// Check format against expected platform.
//
// @dbgtodo - , cross-plat: Once we do cross-plat, these should be based off target-architecture not host's.
#if defined(HOST_64BIT)
if (format != FORMAT_WINDOWS_EXCEPTIONRECORD64)
{
ThrowHR(E_INVALIDARG);
}
#else
if (format != FORMAT_WINDOWS_EXCEPTIONRECORD32)
{
ThrowHR(E_INVALIDARG);
}
#endif
// @dbgtodo cross-plat: once we do cross-plat, need to use correct EXCEPTION_RECORD variant.
if (countBytes != sizeof(EXCEPTION_RECORD))
{
ThrowHR(E_INVALIDARG);
}
const EXCEPTION_RECORD * pRecord = reinterpret_cast<const EXCEPTION_RECORD *> (pRawRecord);
return pRecord;
};
// Return value: S_OK or indication that no more room exists for enabled types
HRESULT CordbProcess::SetEnableCustomNotification(ICorDebugClass * pClass, BOOL fEnable)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this); // takes the lock
ValidateOrThrow(pClass);
((CordbClass *)pClass)->SetCustomNotifications(fEnable);
PUBLIC_API_END(hr);
return hr;
} // CordbProcess::SetEnableCustomNotification
//---------------------------------------------------------------------------------------
// Public implementation of ICDProcess4::Filter
//
// Arguments:
// pRawRecord - non-null raw bytes of the exception
// countBytes - number of bytes in pRawRecord buffer.
// format - format of pRawRecord
// dwFlags - flags providing auxillary info for exception record.
// dwThreadId - thread that exception occurred on.
// pCallback - callback to dispatch potential managed events on.
// pContinueStatus - Continuation status for exception. This dictates what
// to pass to kernel32!ContinueDebugEvent().
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// Target is stopped.
//
// Notes:
// The exception could be anything, including:
// - a CLR notification,
// - a random managed exception (both from managed code or the runtime),
// - a non-CLR exception
//
// This is cross-platform. The {pRawRecord, countBytes, format} describe events
// on an arbitrary target architecture. On windows, this will be an EXCEPTION_RECORD.
//
HRESULT CordbProcess::Filter(
const BYTE pRawRecord[],
DWORD countBytes,
CorDebugRecordFormat format,
DWORD dwFlags,
DWORD dwThreadId,
ICorDebugManagedCallback * pCallback,
DWORD * pContinueStatus
)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this); // takes the lock
{
//
// Validate parameters
//
// If we don't care about the continue status, we leave it untouched.
ValidateOrThrow(pContinueStatus);
ValidateOrThrow(pCallback);
const EXCEPTION_RECORD * pRecord = ValidateExceptionRecord(pRawRecord, countBytes, format);
DWORD dwFirstChance = (dwFlags & IS_FIRST_CHANCE);
//
// Deal with 2nd-chance exceptions. Don't actually hijack now (that's too invasive),
// but mark that we have the exception in case a future operation (eg, func-eval) needs to hijack.
//
if (!dwFirstChance)
{
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
// If we don't have a managed-thread object, then it certainly can't have a throwable.
// It's possible this is still an exception from the native portion of the runtime,
// but that's ok, we'll just treat it as a native exception.
// This could be expensive, don't want to do it often... (definitely not on every Filter).
// OS will not execute the Unhandled Exception Filter under native debugger, so
// we need to hijack the thread to get it to execute the UEF, which will then do
// work for unhandled managed exceptions.
if ((pThread != NULL) && pThread->IsThreadExceptionManaged())
{
// Copy exception record for future use in case we decide to hijack.
pThread->SetUnhandledNativeException(pRecord);
}
// we don't care about 2nd-chance exceptions, unless we decide to hijack it later.
}
//
// Deal with CLR notifications
//
else if (pRecord->ExceptionCode == CLRDBG_NOTIFICATION_EXCEPTION_CODE) // Special event code
{
//
// This may not be for us, or we may not have a managed thread object:
// 1. Anybody can raise an exception with this exception code, so can't assume this belongs to us yet.
// 2. Notifications may come on unmanaged threads if they're coming from MDAs or CLR internal events
// fired before the thread is created.
//
BYTE * pManagedEventBuffer = new BYTE[CorDBIPC_BUFFER_SIZE];
DeleteIPCEventHolder pManagedEvent(reinterpret_cast<DebuggerIPCEvent *>(pManagedEventBuffer));
bool fOwner = CopyManagedEventFromTarget(pRecord, pManagedEvent);
if (fOwner)
{
// This toggles the lock if it dispatches callbacks
FilterClrNotification(pManagedEvent, GET_PUBLIC_LOCK_HOLDER(), pCallback);
// Cancel any notification events from target. These are just supposed to notify ICD and not
// actually be real exceptions in the target.
// Canceling here also prevents a VectoredExceptionHandler in the target from picking
// up exceptions for the CLR.
*pContinueStatus = DBG_CONTINUE;
}
// holder will invoke DeleteIPCEventHelper(pManagedEvent).
}
}
PUBLIC_API_END(hr);
// we may not find the correct mscordacwks so fail gracefully
_ASSERTE(SUCCEEDED(hr) || (hr != HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)));
return hr;
}
//---------------------------------------------------------------------------------------
// Wrapper to invoke ICorDebugMutableDataTarget::ContinueStatusChanged
//
// Arguments:
// dwContinueStatus - new continue status
//
// Returns:
// None. Throw on error.
//
// Notes:
// Initial continue status is returned from code:CordbProcess::Filter.
// Some operations (mainly hijacking on a 2nd-chance exception), may need to
// override that continue status.
// ICorDebug operations invoke a callback on the data-target to notify the debugger
// of a change in status. Debugger may fail the request.
//
void CordbProcess::ContinueStatusChanged(DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus)
{
HRESULT hr = m_pMutableDataTarget->ContinueStatusChanged(dwThreadId, dwContinueStatus);
IfFailThrow(hr);
}
//---------------------------------------------------------------------------------------
// Request a synchronization to occur after a debug event is dispatched.
//
// Note:
// This is called in response to a managed debug event, and so we know that we have
// a worker thread in the process (the one that just sent the event!)
// This can not be called asynchronously.
//---------------------------------------------------------------------------------------
void CordbProcess::RequestSyncAtEvent()
{
GetDAC()->RequestSyncAtEvent();
}
//---------------------------------------------------------------------------------------
//
// Primary loop of the Win32 debug event thread.
//
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Notes:
// This is it, you've found it, the main guy. This function loops as long as the
// debugger is around calling the OS WaitForDebugEvent() API. It takes the OS Debug
// Event and filters it thru the right-side, continuing the process if not recognized.
//
// @dbgtodo shim: this will become part of the shim.
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::Win32EventLoop()
{
// This must be called from the win32 event thread.
_ASSERTE(IsWin32EventThread());
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: entered win32 event loop\n"));
DEBUG_EVENT event;
// Allow the timeout for WFDE to be adjustable. Default to 25 ms based off perf numbers (see issue VSWhidbey 132368).
DWORD dwWFDETimeout = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_DbgWFDETimeout);
while (m_run)
{
BOOL fEventAvailable = FALSE;
// We should not have any locks right now.
// Have to wait on 2 sources:
// WaitForMultipleObjects - ping for messages (create, attach, Continue, detach) and also
// process exits in the managed-only case.
// Native Debug Events - This is a huge perf hit so we want to avoid it whenever we can.
// Only wait on these if we're interop debugging and if the process is not frozen.
// A frozen process can't send any debug events, so don't bother looking for them.
unsigned int cWaitCount = 1;
HANDLE rghWaitSet[2];
rghWaitSet[0] = m_threadControlEvent;
DWORD dwWaitTimeout = INFINITE;
if (m_pProcess != NULL)
{
// Process is always built on Native debugging pipeline, so it needs to always be prepared to call WFDE
// As an optimization, if the target is stopped, then we can avoid calling WFDE.
{
#ifndef FEATURE_INTEROP_DEBUGGING
// Managed-only, never win32 stopped, so always check for an event.
dwWaitTimeout = 0;
fEventAvailable = m_pNativePipeline->WaitForDebugEvent(&event, dwWFDETimeout, m_pProcess);
#else
// Wait for a Win32 debug event from any processes that we may be attached to as the Win32 debugger.
const bool fIsWin32Stopped = (m_pProcess->m_state & CordbProcess::PS_WIN32_STOPPED) != 0;
const bool fSkipWFDE = fIsWin32Stopped;
const bool fIsInteropDebugging = m_pProcess->IsInteropDebugging();
(void)fIsInteropDebugging; //prevent "unused variable" error from GCC
// Assert checks
_ASSERTE(fIsInteropDebugging == m_pShim->IsInteropDebugging());
if (!fSkipWFDE)
{
dwWaitTimeout = 0;
fEventAvailable = m_pNativePipeline->WaitForDebugEvent(&event, dwWFDETimeout, m_pProcess);
}
else
{
// If we're managed-only debugging, then the process should always be running,
// which means we always need to be calling WFDE to pump potential debug events.
// If we're interop-debugging, then the process can be stopped at a native-debug event,
// in which case we don't have to call WFDE until we resume it again.
// So we can only skip the WFDE when we're interop-debugging.
_ASSERTE(fIsInteropDebugging);
}
#endif // FEATURE_INTEROP_DEBUGGING
}
} // end m_pProcess != NULL
#if defined(FEATURE_INTEROP_DEBUGGING)
// While interop-debugging, the process may get killed rudely underneath us, even if we haven't
// continued the last debug event. In such cases, The process object will get signalled normally.
// If we didn't just get a native-exitProcess event, then listen on the process handle for exit.
// (this includes all managed-only debugging)
// It's very important to establish this before we go into the WaitForMutlipleObjects below
// because the debuggee may exit while we're sitting in that loop (waiting for the debugger to call Continue).
bool fDidNotJustGetExitProcessEvent = !fEventAvailable || (event.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
#else
// In non-interop scenarios, we'll never get any native debug events, let alone an ExitProcess native event.
bool fDidNotJustGetExitProcessEvent = true;
#endif // FEATURE_INTEROP_DEBUGGING
// The m_pProcess handle will get nulled out after we process the ExitProcess event, and
// that will ensure that we only wait for an Exit event once.
if ((m_pProcess != NULL) && fDidNotJustGetExitProcessEvent)
{
rghWaitSet[1] = m_pProcess->UnsafeGetProcessHandle();
cWaitCount = 2;
}
// See if any process that we aren't attached to as the Win32 debugger have exited. (Note: this is a
// polling action if we are also waiting for Win32 debugger events. We're also looking at the thread
// control event here, too, to see if we're supposed to do something, like attach.
DWORD dwStatus = WaitForMultipleObjectsEx(cWaitCount, rghWaitSet, FALSE, dwWaitTimeout, FALSE);
_ASSERTE((dwStatus == WAIT_TIMEOUT) || (dwStatus < cWaitCount));
if (!m_run)
{
_ASSERTE(m_action == W32ETA_NONE);
break;
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL - got event , ret=%d, has w32 dbg event=%d\n",
dwStatus, fEventAvailable));
// If we haven't timed out, or if it wasn't the thread control event
// that was set, then a process has
// exited...
if ((dwStatus != WAIT_TIMEOUT) && (dwStatus != WAIT_OBJECT_0))
{
// Grab the process that exited.
_ASSERTE((dwStatus - WAIT_OBJECT_0) == 1);
ExitProcess(false); // not detach
fEventAvailable = false;
}
// Should we create a process?
else if (m_action == W32ETA_CREATE_PROCESS)
{
CreateProcess();
}
// Should we attach to a process?
else if (m_action == W32ETA_ATTACH_PROCESS)
{
AttachProcess();
}
// Should we detach from a process?
else if (m_action == W32ETA_DETACH)
{
ExitProcess(true); // detach case
// Once we detach, we don't need to continue any outstanding event.
// So act like we never got the event.
fEventAvailable = false;
PREFIX_ASSUME(m_pProcess == NULL); // W32 cleared process pointer
}
#ifdef FEATURE_INTEROP_DEBUGGING
// Should we continue the process?
else if (m_action == W32ETA_CONTINUE)
{
HandleUnmanagedContinue();
}
#endif // FEATURE_INTEROP_DEBUGGING
// We don't need to sweep the FCH threads since we never hijack a thread in cooperative mode.
// Only process an event if one is available.
if (!fEventAvailable)
{
continue;
}
// The only ref we have is the one in the ProcessList hash;
// If we dispatch an ExitProcess event, we may even lose that.
// But since the CordbProcess is our parent object, we know it won't go away until
// it neuters us, so we can safely proceed.
// Find the process this event is for.
PREFIX_ASSUME(m_pProcess != NULL);
_ASSERTE(m_pProcess->m_id == GetProcessId(&event)); // should only get events for our proc
g_pRSDebuggingInfo->m_MRUprocess = m_pProcess;
// Must flush the dac cache since we were just running.
m_pProcess->ForceDacFlush();
// So we've filtered out CLR events.
// Let the shim handle the remaining events. This will call back into Filter() if appropriate.
// This will also ensure the debug event gets continued.
HRESULT hrShim = S_OK;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(NULL);
hrShim = m_pShim->HandleWin32DebugEvent(&event);
}
// Any errors from the shim (eg. failure to load DAC) are unrecoverable
SetUnrecoverableIfFailed(m_pProcess, hrShim);
} // loop
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: exiting event loop\n"));
return;
}
//---------------------------------------------------------------------------------------
//
// Returns if the current thread is the win32 thread.
//
// Return Value:
// true iff this is the win32 event thread.
//
//---------------------------------------------------------------------------------------
bool CordbProcess::IsWin32EventThread()
{
_ASSERTE((m_pShim != NULL) || !"Don't check win32 event thread in V3 cases");
return m_pShim->IsWin32EventThread();
}
//---------------------------------------------------------------------------------------
// Call when the sync complete event is received and can be processed.
//
// Notes:
// This is called when the RS gets the sync-complete from the LS and can process it.
//
// This has a somewhat elaborate contract to fill between Interop-debugging, Async-Break, draining the
// managed event-queue, and coordinating with the dispatch thread (RCET).
//
// @dbgtodo - this should eventually get hoisted into the shim.
void CordbProcess::HandleSyncCompleteReceived()
{
_ASSERTE(ThreadHoldsProcessLock());
this->SetSyncCompleteRecv(true);
// If some thread is waiting for the process to sync, notify that it can go now.
if (this->m_stopRequested)
{
this->SetSynchronized(true);
SetEvent(this->m_stopWaitEvent);
}
else
{
// Note: we set the m_stopWaitEvent all the time and leave it high while we're stopped. This
// must be done after we've checked m_stopRequested.
SetEvent(this->m_stopWaitEvent);
// Otherwise, simply mark that the state of the process has changed and let the
// managed event dispatch logic take over.
//
// Note: process->m_synchronized remains false, which indicates to the RC event
// thread that it can dispatch the next managed event.
m_cordb->ProcessStateChanged();
}
}
#ifdef FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// Get (create if needed) the unmanaged thread for an unmanaged debug event.
//
// Arguments:
// event - native debug event.
//
// Return Value:
// Unmanaged thread corresponding to the native debug event.
//
//
// Notes:
// Thread may be newly allocated, or may be existing. CordbProcess holds
// list of all CordbUnmanagedThreads, and will handle freeing memory.
//
//---------------------------------------------------------------------------------------
CordbUnmanagedThread * CordbProcess::GetUnmanagedThreadFromEvent(const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr;
CordbUnmanagedThread * pUnmanagedThread = NULL;
// Remember newly created threads.
if (pEvent->dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
{
// We absolutely should have an unmanaged callback by this point.
// That means that the client debugger should have called ICorDebug::SetUnmanagedHandler by now.
// However, we can't actually enforce that (see comment in ICorDebug::SetUnmanagedHandler for details),
// so we do a runtime check to check this.
// This is an extremely gross API misuse and an issue in the client if the callback is not set yet.
// Without the unmanaged callback, we absolutely can't do interop-debugging. We assert (checked builds) and
// dispatch unrecoverable error (retail builds) to avoid an AV.
if (this->m_cordb->m_unmanagedCallback == NULL)
{
CONSISTENCY_CHECK_MSGF((this->m_cordb->m_unmanagedCallback != NULL),
("GROSS API misuse!!\nNo unmanaged callback set by the time we've received CreateProcess debug event for proces 0x%x.\n",
pEvent->dwProcessId));
CORDBSetUnrecoverableError(this, CORDBG_E_INTEROP_NOT_SUPPORTED, 0);
// Returning NULL will tell caller not to dispatch event to client. We have no callback object to dispatch upon.
return NULL;
}
pUnmanagedThread = this->HandleUnmanagedCreateThread(pEvent->dwThreadId,
pEvent->u.CreateProcessInfo.hThread,
pEvent->u.CreateProcessInfo.lpThreadLocalBase);
// Managed-attach won't start until after Cordbg continues from the loader-bp.
}
else if (pEvent->dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT)
{
pUnmanagedThread = this->HandleUnmanagedCreateThread(pEvent->dwThreadId,
pEvent->u.CreateThread.hThread,
pEvent->u.CreateThread.lpThreadLocalBase);
BOOL fBlockExists = FALSE;
hr = S_OK;
EX_TRY
{
// See if we have the debugger control block yet...
this->GetEventBlock(&fBlockExists);
// If we have the debugger control block, and if that control block has the address of the thread proc for
// the helper thread, then we're initialized enough on the Left Side to recgonize the helper thread based on
// its thread proc's address.
if (this->GetDCB() != NULL)
{
// get the latest LS DCB information
UpdateRightSideDCB();
if ((this->GetDCB()->m_helperThreadStartAddr != NULL) && (pUnmanagedThread != NULL))
{
void * pStartAddr = pEvent->u.CreateThread.lpStartAddress;
if (pStartAddr == this->GetDCB()->m_helperThreadStartAddr)
{
// Remember the ID of the helper thread.
this->m_helperThreadId = pEvent->dwThreadId;
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: Left Side Helper Thread is 0x%x\n", pEvent->dwThreadId));
}
}
}
}
EX_CATCH_HRESULT(hr)
{
if (fBlockExists && FAILED(hr))
{
_ASSERTE(IsLegalFatalError(hr));
// Send up the DebuggerError event
this->UnrecoverableError(hr, 0, NULL, 0);
// Kill the process.
// RS will pump events until we LS process exits.
TerminateProcess(this->m_handle, hr);
return pUnmanagedThread;
}
}
}
else
{
// Find the unmanaged thread that this event is for.
pUnmanagedThread = this->GetUnmanagedThread(pEvent->dwThreadId);
}
return pUnmanagedThread;
}
//---------------------------------------------------------------------------------------
//
// Handle a native-debug event representing a managed sync-complete event.
//
//
// Return Value:
// Reaction telling caller how to respond to the native-debug event.
//
// Assumptions:
// Called within the Triage process after receiving a native-debug event.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageSyncComplete()
{
_ASSERTE(ThreadHoldsProcessLock());
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TSC: received 'sync complete' flare.\n");
_ASSERTE(IsInteropDebugging());
// Note: we really don't need to be suspending Runtime threads that we know have tripped
// here. If we ever end up with a nice, quick way to know that about each unmanaged thread, then
// we should put that to good use here.
this->SuspendUnmanagedThreads();
this->HandleSyncCompleteReceived();
// Let the process run free.
return REACTION(cIgnore);
// At this point, all managed threads are stopped at safe places and all unmanaged
// threads are either suspended or hijacked. All stopped managed threads are also hard
// suspended (due to the call to SuspendUnmanagedThreads above) except for the thread
// that sent the sync complete flare.
// We've handled this exception, so skip all further processing.
UNREACHABLE();
}
//-----------------------------------------------------------------------------
// Triage a breakpoint (non-flare) on a "normal" thread.
//-----------------------------------------------------------------------------
Reaction CordbProcess::TriageBreakpoint(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr = S_OK;
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
_ASSERTE(dwExCode == STATUS_BREAKPOINT);
// There are three cases here:
//
// 1. The breakpoint definetly belongs to the Runtime. (I.e., a BP in our patch table that
// is in managed code.) In this case, we continue the process with
// DBG_EXCEPTION_NOT_HANDLED, which lets the in-process exception logic kick in as if we
// weren't here.
//
// 2. The breakpoint is definetly not ours. (I.e., a BP that is not in our patch table.) We
// pass these up as regular exception events, doing the can't stop check as usual.
//
// 3. We're not sure. (I.e., a BP in our patch table, but set in unmangaed code.) In this
// case, we hijack as usual, also with can't stop check as usual.
bool fPatchFound = false;
bool fPatchIsUnmanaged = false;
hr = this->FindPatchByAddress(PTR_TO_CORDB_ADDRESS(pExAddress),
&fPatchFound,
&fPatchIsUnmanaged);
if (SUCCEEDED(hr))
{
if (fPatchFound)
{
#ifdef _DEBUG
// What if managed & native patch the same address? That could happen on a step out M --> U.
{
NativePatch * pNativePatch = GetNativePatch(pExAddress);
SIMPLIFYING_ASSUMPTION_MSGF(pNativePatch == NULL, ("Have Managed & native patch at 0x%p", pExAddress));
}
#endif
// BP could be ours... if its unmanaged, then we still need to hijack, so fall
// through to that logic. Otherwise, its ours.
if (!fPatchIsUnmanaged)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"belongs to runtime due to patch table match.\n"));
return REACTION(cCLR);
}
else
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"matched in patch table, but its unmanaged so might hijack anyway.\n"));
// If we're in cooperative mode, then we must have a inproc handler, and don't need to hijack
// One way this can happen is the patch placed for a func-eval complete is hit in coop-mode.
if (pUnmanagedThread->GetEEPGCDisabled())
{
LOG((LF_CORDB, LL_INFO10000, "Already in coop-mode, don't need to hijack\n"));
return REACTION(cCLR);
}
else
{
return REACTION(cBreakpointRequiringHijack);
}
}
UNREACHABLE();
}
else // Patch not found
{
// If we're here, then we have a BP that's not in the managed patch table, and not
// in the native patch list. This should be rare. Perhaps an int3 / DebugBreak() / Assert in
// the native code stream.
// Anyway, we don't know about this patch so we can't skip it. The only thing we can do
// is chuck it up to Cordbg and hope they can help us. Note that this is the same case
// we were in w. V1.
// BP doesn't belong to CLR ... so dispatch it to Cordbg as either make it IB or OOB.
// @todo - make the runtime 1 giant Can't stop region.
bool fCantStop = pUnmanagedThread->IsCantStop();
#ifdef _DEBUG
// We rarely expect a raw int3 here. Add a debug check that will assert.
// Tests that know they don't have raw int3 can enable this regkey to get
// extra coverage.
static DWORD s_fBreakOnRawInt3 = -1;
if (s_fBreakOnRawInt3 == -1)
s_fBreakOnRawInt3 = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgBreakOnRawInt3);
if (s_fBreakOnRawInt3)
{
CONSISTENCY_CHECK_MSGF(false, ("Unexpected Raw int3 at:%p on tid 0x%x (%d). CantStop=%d."
"This assert is used by specific tests to get extra checks."
"For normal cases it's ignorable and is enabled by setting DbgBreakOnRawInt3==1.",
pExAddress, pEvent->dwThreadId, pEvent->dwThreadId, fCantStop));
}
#endif
if (fCantStop)
{
// If we're in a can't stop region, then its OOB no matter what at this point.
return REACTION(cOOB);
}
else
{
// PGC must be enabled if we're going to stop for an IB event.
bool PGCDisabled = pUnmanagedThread->GetEEPGCDisabled();
_ASSERTE(!PGCDisabled);
// Bp is definitely not ours, and PGC is not disabled, so in-band exception.
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"does not belong to the runtime due to failed patch table match.\n"));
return REACTION(cInband);
}
UNREACHABLE();
}
UNREACHABLE();
}
else
{
// Patch table lookup failed? Only on OOM or if ReadProcessMemory fails...
_ASSERTE(!"Patch table lookup failed!");
CORDBSetUnrecoverableError(this, hr, 0);
return REACTION(cOOB);
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a "normal" 1st chance exception on a "normal" thread.
// Not hijacked, not the helper thread, not a flare, etc.. This is the common
// case for a native exception from native code.
//
// Arguments:
// pUnmanagedThread - Pointer to the CordbUnmanagedThread object that we want to hijack.
// pEvent - Pointer to the debug event which contains the exception code and address.
//
// Return Value:
// The Reaction tells if the event is in-band, out-of-band, CLR specific or ignorable.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::Triage1stChanceNonSpecial(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
// This had better not be a flare. If it is, that means we have some race that unmarked
// the hijacks.
_ASSERTE(!ExceptionIsFlare(dwExCode, pExAddress));
// Any first chance exception could belong to the Runtime, so long as the Runtime has actually been
// initialized. Here we'll setup a first-chance hijack for this thread so that it can give us the
// true answer that we need.
// But none of those exceptions could possibly be ours unless we have a managed thread to go with
// this unmanaged thread. A non-NULL EEThreadPtr tells us that there is indeed a managed thread for
// this unmanaged thread, even if the Right Side hasn't received a managed ThreadCreate message yet.
REMOTE_PTR pEEThread;
hr = pUnmanagedThread->GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
if (pEEThread == NULL)
{
// No managed thread, so it can't possibly belong to the runtime!
// But it may still be in a can't-stop region (think some goofy shutdown case).
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
// We have to be careful here. A Runtime thread may be in a place where we cannot let an
// unmanaged exception stop it. For instance, an unmanaged user breakpoint set on
// WaitForSingleObject will prevent Runtime threads from sending events to the Right Side. So at
// various points below, we check to see if this Runtime thread is in a place were we can't let
// it stop, and if so then we jump over to the out-of-band dispatch logic and treat this
// exception as out-of-band. The debugger is supposed to continue from the out-of-band event
// properly and help us avoid this problem altogether.
// Grab a few flags from the thread's state...
bool fThreadStepping = false;
bool fSpecialManagedException = false;
pUnmanagedThread->GetEEState(&fThreadStepping, &fSpecialManagedException);
// If we've got a single step exception, and if the Left Side has indicated that it was
// stepping the thread, then the exception is ours.
if (dwExCode == STATUS_SINGLE_STEP)
{
if (fThreadStepping)
{
// Yup, its the Left Side that was stepping the thread...
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: single step exception belongs to the runtime.\n");
return REACTION(cCLR);
}
// Any single step that is triggered when the thread's state doesn't indicate that
// we were stepping the thread automatically gets passed out as an unmanged event.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: single step exception "
"does not belong to the runtime.\n");
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
UNREACHABLE();
}
#ifdef CorDB_Short_Circuit_First_Chance_Ownership
// If the runtime indicates that this is a special exception being thrown within the runtime,
// then its ours no matter what.
else if (fSpecialManagedException)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: exception belongs to the runtime due to "
"special managed exception marking.\n");
return REACTION(cCLR);
}
else if ((dwExCode == EXCEPTION_COMPLUS) || (dwExCode == EXCEPTION_HIJACK))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000,
"W32ET::W32EL: exception belongs to Runtime due to match on built in exception code\n");
return REACTION(cCLR);
}
else if (dwExCode == EXCEPTION_MSVC)
{
// The runtime may use C++ exceptions internally. We can still report these
// to the debugger as long as we're outside of a can't-stop region.
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cCLR);
}
else
{
return REACTION(cInband);
}
}
else if (dwExCode == STATUS_BREAKPOINT)
{
return TriageBreakpoint(pUnmanagedThread, pEvent);
}// end BP case
#endif
// It's not a breakpoint or single-step. Now it just comes down to the address from where
// the exception is coming from. If it's managed, we give it back to the CLR. If it's
// from native, then we dispatch to Cordbg.
// We can use DAC to figure this out from Out-of-process.
_ASSERTE(dwExCode != STATUS_BREAKPOINT); // BP were already handled.
// Use DAC to decide if it's ours or not w/o going inproc.
CORDB_ADDRESS address = PTR_TO_CORDB_ADDRESS(pExAddress);
IDacDbiInterface::AddressType addrType;
addrType = GetDAC()->GetAddressType(address);
bool fIsCorCode =((addrType == IDacDbiInterface::kAddressManagedMethod) ||
(addrType == IDacDbiInterface::kAddressRuntimeManagedCode) ||
(addrType == IDacDbiInterface::kAddressRuntimeUnmanagedCode));
STRESS_LOG2(LF_CORDB, LL_INFO1000, "W32ET::W32EL: IsCorCode(0x%I64p)=%d\n", address, fIsCorCode);
if (fIsCorCode)
{
return REACTION(cCLR);
}
else
{
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a 1st-chance exception when the CLR is initialized.
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// A 1st-chance event has a wide spectrum of possibility including:
// - It may be unmanaged or managed.
// - Or it may be an execution control exception for managed-exceution
// - thread skipping an OOB event.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageExcep1stChanceAndInit(CordbUnmanagedThread * pUnmanagedThread,
const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_runtimeOffsetsInitialized);
NativePatch * pNativePatch = NULL;
DebuggerIPCRuntimeOffsets * pIPCRuntimeOffsets = &(this->m_runtimeOffsets);
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
LOG((LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Enter\n"));
#ifdef _DEBUG
// Some Interop bugs involve threads that land at a bad IP. Since we're interop-debugging, we can't
// attach a debugger to the LS. So we have some debug mode where we enable the SS flag and thus
// produce a trace of where a thread is going.
if (pUnmanagedThread->IsDEBUGTrace() && (dwExCode == STATUS_SINGLE_STEP))
{
pUnmanagedThread->ClearState(CUTS_DEBUG_SingleStep);
LOG((LF_CORDB, LL_INFO10000, "DEBUG TRACE, thread %4x at IP: 0x%p\n", pUnmanagedThread->m_id, pExAddress));
// Clear the exception and pretend this never happened.
return REACTION(cIgnore);
}
#endif
// If we were stepping for exception retrigger and got the single step and it should be hidden then just ignore it.
// Anything that isn't cInbandExceptionRetrigger will cause the debug event to be dequeued, stepping turned off, and
// it will count as not retriggering
// TODO: I don't think the IsSSFlagNeeded() check is needed here though it doesn't break anything
if (pUnmanagedThread->IsSSFlagNeeded() && pUnmanagedThread->IsSSFlagHidden() && (dwExCode == STATUS_SINGLE_STEP))
{
LOG((LF_CORDB, LL_INFO10000, "CP::TE1stCAI: ignoring hidden single step\n"));
return REACTION(cIgnore);
}
// Is this a breakpoint indicating that the Left Side is now synchronized?
if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_notifyRSOfSyncCompleteBPAddr))
{
return TriageSyncComplete();
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_excepForRuntimeHandoffCompleteBPAddr))
{
_ASSERTE(!"This should be unused now");
// This notification means that a thread that had been first-chance hijacked is now
// finally leaving the hijack.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'first chance hijack handoff complete' flare.\n");
// Let the process run.
return REACTION(cIgnore);
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_signalHijackCompleteBPAddr))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'hijack complete' flare.\n");
return REACTION(cInbandHijackComplete);
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == m_runtimeOffsets.m_signalHijackStartedBPAddr))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'hijack started' flare.\n");
return REACTION(cFirstChanceHijackStarted);
}
else if ((dwExCode == STATUS_BREAKPOINT) && ((pNativePatch = GetNativePatch(pExAddress)) != NULL) )
{
// We hit a native BP placed by Cordbg. This could happen on any thread (including helper)
bool fCantStop = pUnmanagedThread->IsCantStop();
// REVISIT_TODO: if the user also set a breakpoint here then we should dispatch to the debugger
// and rely on the debugger to get us past this. Should be a rare case though.
if (fCantStop)
{
// Need to skip it completely; never dispatch.
pUnmanagedThread->SetupForSkipBreakpoint(pNativePatch);
// Debuggee will single step over the patch, and fire a SS exception.
// We'll then call FixupForSkipBreakpoint, and continue the process.
return REACTION(cIgnore);
}
else
{
// Native patch in native code. A very common scenario.
// Dispatch as an IB event to Cordbg.
STRESS_LOG1(LF_CORDB, LL_INFO10000, "Native patch in native code (at %p), dispatching as IB event.\n", pExAddress);
return REACTION(cInband);
}
UNREACHABLE();
}
else if ((dwExCode == STATUS_BREAKPOINT) && !IsBreakOpcodeAtAddress(pExAddress))
{
// If we got an int3 exception, but there's not actually an int3 at the address, then just reset the IP
// to the address. This can happen if the int 3 is cleared after the thread has dispatched it (in which case
// WFDE will pick it up) but before we realize it's one of ours.
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Phantom Int3: Tid=0x%x, addr=%p\n", pEvent->dwThreadId, pExAddress);
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
BOOL fSuccess = DbiGetThreadContext(pUnmanagedThread->m_handle, &context);
_ASSERTE(fSuccess);
if (fSuccess)
{
// Backup IP to point to the instruction we need to execute. Continuing from a breakpoint exception
// continues execution at the instruction after the breakpoint, but we need to continue where the
// breakpoint was.
CORDbgSetIP(&context, (LPVOID) pExAddress);
fSuccess = DbiSetThreadContext(pUnmanagedThread->m_handle, &context);
_ASSERTE(fSuccess);
}
return REACTION(cIgnore);
}
else if (pUnmanagedThread->IsSkippingNativePatch())
{
// If we Single-Step over an exception, then the OS never gives us the single-step event.
// Thus if we're skipping a native patch, we don't care what exception event we got.
LOG((LF_CORDB, LL_INFO100000, "Done skipping native patch. Ex=0x%x\n, IsSS=%d",
dwExCode,
(dwExCode == STATUS_SINGLE_STEP)));
// This is the 2nd half of skipping a native patch.
// This could happen on any thread (including helper)
// We've already removed the opcode and now we just finished a single-step over it.
// So put the patch back in, and continue the process.
pUnmanagedThread->FixupForSkipBreakpoint();
return REACTION(cIgnore);
}
else if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
// We should never ever get a single-step event from the helper thread.
CONSISTENCY_CHECK_MSGF(dwExCode != STATUS_SINGLE_STEP, (
"Single-Step exception on helper thread (tid=0x%x/%d) in debuggee process (pid=0x%x/%d).\n"
"For more information, attach a debuggee non-invasively to the LS to get the callstack.\n",
pUnmanagedThread->m_id,
pUnmanagedThread->m_id,
this->m_id,
this->m_id));
// We ignore any first chance exceptions from the helper thread. There are lots of places
// on the left side where we attempt to dereference bad object refs and such that will be
// handled by exception handlers already in place.
//
// Note: we check this after checking for the sync complete notification, since that can
// come from the helper thread.
//
// Note: we do let single step and breakpoint exceptions go through to the debugger for processing.
if ((dwExCode != STATUS_BREAKPOINT) && (dwExCode != STATUS_SINGLE_STEP))
{
return REACTION(cCLR);
}
else
{
// Since the helper thread is part of the "can't stop" region, we should have already
// skipped any BPs on it.
// However, any Assert on the helper thread will hit this case.
CONSISTENCY_CHECK_MSGF((dwExCode != STATUS_BREAKPOINT), (
"Assert on helper thread (tid=0x%x/%d) in debuggee process (pid=0x%x/%d).\n"
"For more information, attach a debuggee non-invasively to the LS to get the callstack.\n",
pUnmanagedThread->m_id,
pUnmanagedThread->m_id,
this->m_id,
this->m_id));
// These breakpoint and single step exceptions have to be dispatched to the debugger as
// out-of-band events. This tells the debugger that they must continue from these events
// immediatly, and that no interaction with the Left Side is allowed until they do so. This
// makes sense, since these events are on the helper thread.
return REACTION(cOOB);
}
UNREACHABLE();
}
else if (pUnmanagedThread->IsFirstChanceHijacked() && this->ExceptionIsFlare(dwExCode, pExAddress))
{
_ASSERTE(!"This should be unused now");
}
else if (pUnmanagedThread->IsGenericHijacked())
{
if (this->ExceptionIsFlare(dwExCode, pExAddress))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: fixing up from generic hijack.\n");
_ASSERTE(dwExCode == STATUS_BREAKPOINT);
// Fixup the thread from the generic hijack.
pUnmanagedThread->FixupFromGenericHijack();
// We force continue from this flare, since its only purpose was to notify us that we had to
// fixup the thread from a generic hijack.
return REACTION(cIgnore);
}
else
{
// We might reach here due to the stack overflow issue, due to target
// memory corruption, or even due to an exception thrown during hijacking
BOOL bStackOverflow = FALSE;
if (dwExCode == STATUS_ACCESS_VIOLATION || dwExCode == STATUS_STACK_OVERFLOW)
{
CORDB_ADDRESS stackLimit;
CORDB_ADDRESS stackBase;
if (pUnmanagedThread->GetStackRange(&stackBase, &stackLimit))
{
TADDR addr = pEvent->u.Exception.ExceptionRecord.ExceptionInformation[1];
if (stackLimit <= addr && addr < stackBase)
bStackOverflow = TRUE;
}
else
{
// to limit the impact of the change we'll consider failure to retrieve the stack
// bounds as stack overflow as well
bStackOverflow = TRUE;
}
}
if (!bStackOverflow)
{
// generic hijack means we're in CantStop, so return cOOB
return REACTION(cOOB);
}
// If generichijacked and its not a flare, and the address referenced is on the stack then we've
// got our special stack overflow case. Take off generic hijacked, mark that the helper thread
// is dead, throw this event on the floor, and pop anyone in SendIPCEvent out of their wait.
pUnmanagedThread->ClearState(CUTS_GenericHijacked);
this->m_helperThreadDead = true;
// This only works on Windows, not on Mac. We don't support interop-debugging on Mac anyway.
SetEvent(m_pEventChannel->GetRightSideEventAckHandle());
// Note: we remember that this was a second chance event from one of the special stack overflow
// cases with CUES_ExceptionUnclearable. This tells us to force the process to terminate when we
// continue from the event. Since for some odd reason the OS decides to re-raise this exception
// (first chance then second chance) infinitely.
_ASSERTE(pUnmanagedThread->HasIBEvent());
pUnmanagedThread->IBEvent()->SetState(CUES_ExceptionUnclearable);
//newEvent = false;
return REACTION(cInband_NotNewEvent);
}
}
else
{
LOG((LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Triage1stChanceNonSpecial\n"));
Reaction r(REACTION(cOOB));
HRESULT hrCheck = S_OK;;
EX_TRY
{
r = Triage1stChanceNonSpecial(pUnmanagedThread, pEvent);
}
EX_CATCH_HRESULT(hrCheck);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hrCheck));
SetUnrecoverableIfFailed(this, hrCheck);
return r;
}
// At this point, any first-chance exceptions that could be special have been handled. Any
// first-chance exception that we're still processing at this point is destined to be
// dispatched as an unmanaged event.
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a 2nd-chance exception when the CLR is initialized.
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// We already hijacked 2nd-chance managed exceptions, so this is just handling
// some V2 Interop corner cases.
// @dbgtodo interop: this should eventually completely go away with the V3 design.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageExcep2ndChanceAndInit(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
#ifdef _DEBUG
// For debugging, add an extra knob that let us break on any 2nd chance exceptions.
// Most tests don't throw 2nd-chance, so we could have this enabled most of the time and
// catch bogus 2nd chance exceptions
static DWORD dwNo2ndChance = -1;
if (dwNo2ndChance == -1)
{
dwNo2ndChance = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgNo2ndChance);
}
if (dwNo2ndChance)
{
CONSISTENCY_CHECK_MSGF(false, ("2nd chance exception occurred on LS thread=0x%x, code=0x%08x, address=0x%p\n"
"This assert is firing b/c you explicitly requested it by having the 'DbgNo2ndChance' knob enabled.\n"
"Disable it to avoid asserts on 2nd chance.",
pUnmanagedThread->m_id,
dwExCode,
pEvent->u.Exception.ExceptionRecord.ExceptionAddress));
}
#endif
// Second chance exception, Runtime initialized. It could belong to the Runtime, so we'll check. If it
// does, then we'll hijack the thread. Otherwise, well just fall through and let it get
// dispatched. Note: we do this so that the CLR's unhandled exception logic gets a chance to run even
// though we've got a win32 debugger attached. But the unhandled exception logic never touches
// breakpoint or single step exceptions, so we ignore those here, too.
// There are strange cases with stack overflow exceptions. If a nieve application catches a stack
// overflow exception and handles it, without resetting the guard page, then the app will get an AV when
// it overflows the stack a second time. We will get the first chance AV, but when we continue from it the
// OS won't run any SEH handlers, so our FCH won't actually work. Instead, we'll get the AV back on
// second chance right away, and we'll end up right here.
if (this->IsSpecialStackOverflowCase(pUnmanagedThread, pEvent))
{
// IsSpecialStackOverflowCase will queue the event for us, so its no longer a "new event". Setting
// newEvent = false here basically prevents us from playing with the event anymore and we fall down
// to the dispatch logic below, which will get our already queued first chance AV dispatched for
// this thread.
//newEvent = false;
return REACTION(cInband_NotNewEvent);
}
else if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
// A second chance exception from the helper thread. This is pretty bad... we just force continue
// from them and hope for the best.
return REACTION(cCLR);
}
if(pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
//---------------------------------------------------------------------------------------
//
// Triage a win32 Debug event to get a reaction
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// This is the main triage routine for Win32 debug events, this delegates to the
// 1st and 2nd chance routines above appropriately.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageWin32DebugEvent(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
// Lots of special cases for exception events. The vast majority of hybrid debugging work that takes
// place is in response to exception events. The work below will consider certian exception events
// special cases and rather than letting them be queued and dispatched, they will be handled right
// here.
if (pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CP::TW32DE: unmanaged exception on "
"tid 0x%x, code 0x%08x, addr 0x%08x, chance %d\n",
pEvent->dwThreadId,
pEvent->u.Exception.ExceptionRecord.ExceptionCode,
pEvent->u.Exception.ExceptionRecord.ExceptionAddress,
2-pEvent->u.Exception.dwFirstChance);
#ifdef LOGGING
if (pEvent->u.Exception.ExceptionRecord.ExceptionCode == STATUS_ACCESS_VIOLATION)
{
LOG((LF_CORDB, LL_INFO1000, "\t<%s> address 0x%08x\n",
pEvent->u.Exception.ExceptionRecord.ExceptionInformation[0] ? "write to" : "read from",
pEvent->u.Exception.ExceptionRecord.ExceptionInformation[1]));
}
#endif
// Mark the loader bp for kicks. We won't start managed attach until native attach is finished.
if (!this->m_loaderBPReceived)
{
// If its a first chance breakpoint, and its the first one, then its the loader breakpoint.
if (pEvent->u.Exception.dwFirstChance &&
(pEvent->u.Exception.ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT))
{
LOG((LF_CORDB, LL_INFO1000, "CP::TW32DE: loader breakpoint received.\n"));
// Remember that we've received the loader BP event.
this->m_loaderBPReceived = true;
// We never hijack the loader BP anymore (CLR 2.0+).
// This is b/c w/ interop-attach, we don't start the managed-attach until _after_ Cordbg
// continues from the loader-bp.
}
} // end of loader bp.
// This event might be the retriggering of an event we already saw but previously had to hijack
if(pUnmanagedThread->HasIBEvent())
{
const EXCEPTION_RECORD* pRecord1 = &(pEvent->u.Exception.ExceptionRecord);
const EXCEPTION_RECORD* pRecord2 = &(pUnmanagedThread->IBEvent()->m_currentDebugEvent.u.Exception.ExceptionRecord);
if(pRecord1->ExceptionCode == pRecord2->ExceptionCode &&
pRecord1->ExceptionFlags == pRecord2->ExceptionFlags &&
pRecord1->ExceptionAddress == pRecord2->ExceptionAddress)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TW32DE: event is continuation of previously hijacked event.\n");
// if we continued from the hijack then we should have already dispatched this event
_ASSERTE(pUnmanagedThread->IBEvent()->IsDispatched());
return REACTION(cInbandExceptionRetrigger);
}
}
// We only care about exception events if they are first chance events and if the Runtime is
// initialized within the process. Otherwise, we don't do anything special with them.
if (pEvent->u.Exception.dwFirstChance && this->m_initialized)
{
return TriageExcep1stChanceAndInit(pUnmanagedThread, pEvent);
}
else if (!pEvent->u.Exception.dwFirstChance && this->m_initialized)
{
return TriageExcep2ndChanceAndInit(pUnmanagedThread, pEvent);
}
else
{
// An exception event, but the Runtime hasn't been initialize. I.e., its an exception event
// that we will never try to hijack.
return REACTION(cInband);
}
UNREACHABLE();
}
else
// OOB
{
return REACTION(cOOB);
}
}
//---------------------------------------------------------------------------------------
//
// Top-level handler for a win32 debug event during Interop-debugging.
//
// Arguments:
// event - native debug event to handle.
//
// Assumptions:
// The process just got a native debug event via WaitForDebugEvent
//
// Notes:
// The function will Triage the excpetion and then handle it based on the
// appropriate reaction (see: code:Reaction).
//
// @dbgtodo interop: this should all go into the shim.
//---------------------------------------------------------------------------------------
void CordbProcess::HandleDebugEventForInteropDebugging(const DEBUG_EVENT * pEvent)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
_ASSERTE(IsInteropDebugging() || !"Only do this in real interop handling path");
STRESS_LOG3(LF_CORDB, LL_INFO1000, "W32ET::W32EL: got unmanaged event %d on thread 0x%x, proc 0x%x\n",
pEvent->dwDebugEventCode, pEvent->dwThreadId, pEvent->dwProcessId);
// Get the Lock.
_ASSERTE(!this->ThreadHoldsProcessLock());
RSSmartPtr<CordbProcess> pRef(this); // make sure we're alive...
RSLockHolder processLockHolder(&this->m_processMutex);
// If we get a new Win32 Debug event, then we need to flush any cached oop data structures.
// This includes refreshing DAC and our patch table.
ForceDacFlush();
ClearPatchTable();
#ifdef _DEBUG
// We want to detect if we've deadlocked. Unfortunately, w/ interop debugging, there can be a lot of
// deadtime since we need to wait for a debug event. Thus the CPU usage may appear to be at 0%, but
// we're not deadlocked b/c we're still receiving debug events.
// So ping every X debug events.
static int s_cCount = 0;
static int s_iPingLevel = -1;
if (s_iPingLevel == -1)
{
s_iPingLevel = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgPingInterop);
}
if (s_iPingLevel != 0)
{
s_cCount++;
if (s_cCount >= s_iPingLevel)
{
s_cCount = 0;
::Beep(1000,100);
// Refresh so we can adjust ping level midstream.
s_iPingLevel = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgPingInterop);
}
}
#endif
bool fNewEvent = true;
// Mark the process as stopped.
this->m_state |= CordbProcess::PS_WIN32_STOPPED;
CordbUnmanagedThread * pUnmanagedThread = GetUnmanagedThreadFromEvent(pEvent);
// In retail, if there is no unmanaged thread then we just continue and loop back around. UnrecoverableError has
// already been set in this case. Note: there is an issue in the Win32 debugging API that can cause duplicate
// ExitThread events. We therefore must handle not finding an unmanaged thread gracefully.
_ASSERTE((pUnmanagedThread != NULL) || (pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT));
if (pUnmanagedThread == NULL)
{
// Note: we use ContinueDebugEvent directly here since our continue is very simple and all of our other
// continue mechanisms rely on having an UnmanagedThread object to play with ;)
STRESS_LOG2(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Continuing without thread on tid 0x%x, code=0x%x\n",
pEvent->dwThreadId,
pEvent->dwDebugEventCode);
this->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
BOOL fOk = ContinueDebugEvent(pEvent->dwProcessId, pEvent->dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
_ASSERTE(fOk || !"ContinueDebugEvent failed when he have no thread. Debuggee is likely hung");
return;
}
// There's an innate race such that we can get a Debug Event even after we've suspended a thread.
// This can happen if the thread has already dispatched the debug event but we haven't called WFDE to pick it up
// yet. This is sufficiently goofy that we want to stress log it.
if (pUnmanagedThread->IsSuspended())
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Thread 0x%x is suspended\n", pEvent->dwThreadId);
}
// For debugging races in retail, we'll keep a rolling queue of win32 debug events.
this->DebugRecordWin32Event(pEvent, pUnmanagedThread);
// Check to see if shutdown of the in-proc debugging services has begun. If it has, then we know we'll no longer
// be running any managed code, and we know that we can stop hijacking threads. We remember this by setting
// m_initialized to false, thus preventing most things from happening elsewhere.
// Don't even bother checking the DCB fields until it's been verified (m_initialized == true)
if (this->m_initialized && (this->GetDCB() != NULL))
{
UpdateRightSideDCB();
if (this->GetDCB()->m_shutdownBegun)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: shutdown begun...\n");
this->m_initialized = false;
}
}
#ifdef _DEBUG
//Verify that GetThreadContext agrees with the exception address
if (pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
DT_CONTEXT tempDebugContext;
tempDebugContext.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(pUnmanagedThread->m_handle, &tempDebugContext);
CordbUnmanagedThread::LogContext(&tempDebugContext);
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const ULONG_PTR breakpointOpcodeSize = 1;
#elif defined(TARGET_ARM64)
const ULONG_PTR breakpointOpcodeSize = 4;
#else
const ULONG_PTR breakpointOpcodeSize = 1;
PORTABILITY_ASSERT("NYI: Breakpoint size offset for this platform");
#endif
_ASSERTE(CORDbgGetIP(&tempDebugContext) == pEvent->u.Exception.ExceptionRecord.ExceptionAddress ||
(DWORD)(size_t)CORDbgGetIP(&tempDebugContext) == ((DWORD)(size_t)pEvent->u.Exception.ExceptionRecord.ExceptionAddress)+breakpointOpcodeSize);
}
#endif
// This call will decide what to do w/ the the win32 event we just got. It does a lot of work.
Reaction reaction = TriageWin32DebugEvent(pUnmanagedThread, pEvent);
// Stress-log the reaction.
#ifdef _DEBUG
STRESS_LOG3(LF_CORDB, LL_INFO1000, "Reaction: %d (%s), line=%d\n",
reaction.GetType(),
reaction.GetReactionName(),
reaction.GetLine());
#else
STRESS_LOG1(LF_CORDB, LL_INFO1000, "Reaction: %d\n", reaction.GetType());
#endif
// Make sure the lock wasn't accidentally released.
_ASSERTE(ThreadHoldsProcessLock());
CordbWin32EventThread * pW32EventThread = this->m_pShim->GetWin32EventThread();
_ASSERTE(pW32EventThread != NULL);
// if we were waiting for a retriggered exception but received any other event then turn
// off the single stepping and dequeue the IB event. Right now we only use the SS flag internally
// for stepping during possible retrigger.
if(reaction.GetType() != Reaction::cInbandExceptionRetrigger && pUnmanagedThread->IsSSFlagNeeded())
{
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
_ASSERTE(pUnmanagedEvent->IsIBEvent());
_ASSERTE(pUnmanagedEvent->IsEventContinuedUnhijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
LOG((LF_CORDB, LL_INFO100000, "CP::HDEFID: IB event did not retrigger ue=0x%p\n", pUnmanagedEvent));
DequeueUnmanagedEvent(pUnmanagedThread);
pUnmanagedThread->EndStepping();
}
switch(reaction.GetType())
{
// Common for flares.
case Reaction::cIgnore:
// Shouldn't be suspending in the first place with outstanding flares.
_ASSERTE(!pUnmanagedThread->IsSuspended());
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
case Reaction::cCLR:
// Don't care if thread is suspended here. We'll just let the thread continue whatever it's doing.
this->m_DbgSupport.m_TotalCLR++;
// If this is for the CLR, then we just continue unhandled and know that the CLR has
// a handler inplace to deal w/ this exception.
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_EXCEPTION_NOT_HANDLED, false);
goto LDone;
case Reaction::cInband_NotNewEvent:
fNewEvent = false;
// fall through to Inband case...
case Reaction::cInband:
{
this->m_DbgSupport.m_TotalIB++;
// Hijack in-band events (exception events, exit threads) if there is already an event at the head
// of the queue or if the process is currently synchronized. Of course, we only do this if the
// process is initialized.
//
// Note: we also hijack these left over in-band events if we're actively trying to send the
// managed continue message to the Left Side. This is controlled by m_specialDeferment below.
// Only exceptions can be IB events - everything else is OOB.
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
// CLR internal exceptions should be sent back to the CLR and never treated as inband events.
// If this assert fires, the event was triaged wrong.
CONSISTENCY_CHECK_MSGF((pEvent->u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_COMPLUS),
("Attempting to dispatch a CLR internal exception as an Inband event. Reaction line=%d\n",
reaction.GetLine()));
_ASSERTE(!pUnmanagedThread->IsCantStop());
// We need to decide whether or not to dispatch this event immediately
// We defer it to enforce that we only dispatch 1 IB event at a time (managed events are
// considered IB here).
// This means if:
// 1) there's already an outstanding unmanaged inband event (an event the user has not continued from)
// 2) If the process is synchronized (since that means we've already dispatched a managed event).
// 3) If we've received a SyncComplete event, but aren't yet Sync. This will almost always be the same as
// whether we're synced, but has a distict quality. It's always set by the w32 event thread in Interop,
// and so it's guaranteed to be serialized against this check here (also on the w32et).
// 4) Special deferment - This covers the region where we're sending a Stop/Continue IPC event across.
// We defer it here to keep the Helper thread alive so that it can handle these IPC events.
// Queued events will be dispatched when continue is called.
BOOL fHasUserUncontinuedNativeEvents = HasUserUncontinuedNativeEvents();
bool fDeferInbandEvent = (fHasUserUncontinuedNativeEvents ||
GetSynchronized() ||
GetSyncCompleteRecv() ||
m_specialDeferment);
// If we've got a new event, queue it.
if (fNewEvent)
{
this->QueueUnmanagedEvent(pUnmanagedThread, pEvent);
}
if (fNewEvent && this->m_initialized && fDeferInbandEvent)
{
STRESS_LOG4(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Needed to defer dispatching event: %d %d %d %d\n",
fHasUserUncontinuedNativeEvents,
GetSynchronized(),
GetSyncCompleteRecv(),
m_specialDeferment);
// this continues the IB debug event into the hijack
// the process is now running again
pW32EventThread->DoDbgContinue(this, pUnmanagedThread->IBEvent());
// Since we've hijacked this event, we don't need to do any further processing.
goto LDone;
}
else
{
// No need to defer the dispatch, do it now
this->DispatchUnmanagedInBandEvent();
goto LDone;
}
UNREACHABLE();
}
case Reaction::cFirstChanceHijackStarted:
{
// determine the logical event we are handling, if any
CordbUnmanagedEvent* pUnmanagedEvent = NULL;
if(pUnmanagedThread->HasIBEvent())
{
pUnmanagedEvent = pUnmanagedThread->IBEvent();
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB hijack starting, ue=0x%p\n", pUnmanagedEvent));
// fetch the LS memory set up for this hijack
REMOTE_PTR pDebuggerWord = NULL;
DebuggerIPCFirstChanceData fcd;
pUnmanagedThread->GetEEDebuggerWord(&pDebuggerWord);
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: old fcd DebugCounter=0x%x\n", fcd.debugCounter));
// determine what action the LS should take
if(pUnmanagedThread->IsBlockingForSync())
{
// there should be an event we hijacked in this case
_ASSERTE(pUnmanagedEvent != NULL);
// block that event
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: blocking\n"));
fcd.action = HIJACK_ACTION_WAIT;
fcd.debugCounter = 0x2;
SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
}
else
{
// we don't need to block. We want the vectored handler to just exit
// as if it wasn't there
_ASSERTE(fcd.action == HIJACK_ACTION_EXIT_UNHANDLED);
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: not blocking\n"));
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: continuing from flare\n"));
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
}
case Reaction::cInbandHijackComplete:
{
// We now execute the hijack worker even when not actually hijacked
// so can't assert this
//_ASSERTE(pUnmanagedThread->IsFirstChanceHijacked());
// we should not be stepping at the end of hijacks
_ASSERTE(!pUnmanagedThread->IsSSFlagHidden());
_ASSERTE(!pUnmanagedThread->IsSSFlagNeeded());
// if we were hijacked then clean up
if(pUnmanagedThread->IsFirstChanceHijacked())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: hijack complete will restore context...\n"));
DT_CONTEXT tempContext = { 0 };
tempContext.ContextFlags = DT_CONTEXT_FULL;
HRESULT hr = pUnmanagedThread->GetThreadContext(&tempContext);
_ASSERTE(SUCCEEDED(hr));
// The sync hijack returns normally but the m2uHandoff hijack needs to have the IP
// deliberately restored
if(!pUnmanagedThread->IsBlockingForSync())
{
// restore the context to the current un-hijacked context
BOOL succ = DbiSetThreadContext(pUnmanagedThread->m_handle, &tempContext);
_ASSERTE(succ);
// Because hijacks don't return normally they might have pushed handlers without poping them
// back off. To take care of that we explicitly restore the old SEH chain.
#ifdef TARGET_X86
hr = pUnmanagedThread->RestoreLeafSeh();
_ASSERTE(SUCCEEDED(hr));
#endif
}
else
{
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB hijack completing, continuing unhijacked ue=0x%p\n", pUnmanagedEvent));
_ASSERTE(pUnmanagedEvent->IsEventContinuedHijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
_ASSERTE(pUnmanagedEvent->IsEventUserContinued());
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
// fetch the LS memory set up for this hijack
REMOTE_PTR pDebuggerWord = NULL;
DebuggerIPCFirstChanceData fcd;
pUnmanagedThread->GetEEDebuggerWord(&pDebuggerWord);
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: pDebuggerWord is 0x%p\n", pDebuggerWord));
//set the correct continuation action based upon the user's selection
if(pUnmanagedEvent->IsExceptionCleared())
{
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: exception cleared\n"));
fcd.action = HIJACK_ACTION_EXIT_HANDLED;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: exception not cleared\n"));
fcd.action = HIJACK_ACTION_EXIT_UNHANDLED;
}
//
// LS context is restored here so that execution continues from next instruction that caused the hijack.
// We shouldn't always restore the LS context though.
// Consider the following case where this can cause issues:
// Debuggee process hits an exception and calls KERNELBASE!RaiseException, debugger gets the notification and
// prepares for first-chance hijack. Debugger(DBI) saves the current thread context (see SetupFirstChanceHijackForSync) which is restored
// later below (see SafeWriteThreadContext call) when the process is in VEH (CLRVectoredExceptionHandlerShim->FirstChanceSuspendHijackWorker).
// The thread context that got saved(by SetupFirstChanceHijackForSync) was for when the thread was executing RaiseException and when
// this context gets restored in VEH, the thread resumes after the exception handler with a context that is not same as one with which
// it entered. This inconsistency can lead to bad execution code-paths or even a debuggee crash.
//
// Example case where we should definitely update the LS context:
// After a DbgBreakPoint call, IP gets updated to point to the instruction after int 3 and this is the context saved by debugger.
// The IP in context passed to VEH still points to int 3 though and if we don't update the LS context in VEH, the breakpoint
// instruction will get executed again.
//
// Here's a list of cases when we update the LS context:
// * we know that context was explicitly updated during this hijack, OR
// * if single-stepping flag was set on it originally, OR
// * if this was a breakpoint event
// Note that above list is a heuristic and it is possible that we need to add more such cases in future.
//
BOOL isBreakPointEvent = (pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT);
if (pUnmanagedThread->IsContextSet() || IsSSFlagEnabled(&tempContext) || isBreakPointEvent)
{
_ASSERTE(fcd.pLeftSideContext != NULL);
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: updating LS context at 0x%p\n", fcd.pLeftSideContext));
// write the new context over the old one on the LS
SafeWriteThreadContext(fcd.pLeftSideContext, &tempContext);
}
// Write the new Fcd data to the LS
fcd.debugCounter = 0x1;
SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
fcd.debugCounter = 0;
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
_ASSERTE(fcd.debugCounter == 1);
DequeueUnmanagedEvent(pUnmanagedThread);
}
_ASSERTE(m_cFirstChanceHijackedThreads > 0);
m_cFirstChanceHijackedThreads--;
if(m_cFirstChanceHijackedThreads == 0)
{
m_state &= ~PS_HIJACKS_IN_PLACE;
}
pUnmanagedThread->ClearState(CUTS_FirstChanceHijacked);
pUnmanagedThread->ClearState(CUTS_BlockingForSync);
// if the user set the context it either was already applied (m2uHandoff hijack)
// or is about to be applied when the hijack returns (sync hijack).
// There may still a small window where it won't appear accurate that
// we just have to live with
pUnmanagedThread->ClearState(CUTS_HasContextSet);
}
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
// We've handled this event. Skip further processing.
goto LDone;
}
case Reaction::cBreakpointRequiringHijack:
{
HRESULT hr = pUnmanagedThread->SetupFirstChanceHijack(EHijackReason::kM2UHandoff, &(pEvent->u.Exception.ExceptionRecord));
_ASSERTE(SUCCEEDED(hr));
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
}
case Reaction::cInbandExceptionRetrigger:
{
// this should be unused now
_ASSERTE(FALSE);
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
_ASSERTE(pUnmanagedEvent->IsIBEvent());
_ASSERTE(pUnmanagedEvent->IsEventContinuedUnhijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB event completing, continuing ue=0x%p\n", pUnmanagedEvent));
DequeueUnmanagedEvent(pUnmanagedThread);
// If this event came from RaiseException then flush the context to ensure we won't use it until we re-enter
if(pUnmanagedEvent->m_owner->IsRaiseExceptionHijacked())
{
pUnmanagedEvent->m_owner->RestoreFromRaiseExceptionHijack();
pUnmanagedEvent->m_owner->ClearRaiseExceptionEntryContext();
}
else // otherwise we should have been stepping
{
pUnmanagedThread->EndStepping();
}
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread,
pUnmanagedEvent->IsExceptionCleared() ? DBG_CONTINUE : DBG_EXCEPTION_NOT_HANDLED, false);
// We've handled this event. Skip further processing.
goto LDone;
}
case Reaction::cOOB:
{
// Don't care if this thread claimed to be suspended or not. Dispatch event anyways. After all,
// OOB events can come at *any* time.
// This thread may be suspended. We don't care.
this->m_DbgSupport.m_TotalOOB++;
// Not an inband event. This includes ALL non-exception events (including EXIT_THREAD) as
// well as any exception that can't be hijacked (ex, an exception on the helper thread).
// If this is an exit thread or exit process event, then we need to mark the unmanaged thread as
// exited for later.
if ((pEvent->dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) ||
(pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT))
{
pUnmanagedThread->SetState(CUTS_Deleted);
}
// If we get an exit process or exit thread event on the helper thread, then we know we're loosing
// the Left Side, so go ahead and remember that the helper thread has died.
if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
if ((pEvent->dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) ||
(pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT))
{
this->m_helperThreadDead = true;
}
}
// Queue the current out-of-band event.
this->QueueOOBUnmanagedEvent(pUnmanagedThread, pEvent);
// Go ahead and dispatch the event if its the first one.
if (this->m_outOfBandEventQueue == pUnmanagedThread->OOBEvent())
{
// Set this to true to indicate to Continue() that we're in the unamnaged callback.
CordbUnmanagedEvent * pUnmanagedEvent = pUnmanagedThread->OOBEvent();
this->m_dispatchingOOBEvent = true;
pUnmanagedEvent->SetState(CUES_Dispatched);
this->Unlock();
// Handler should have been registered by now.
_ASSERTE(this->m_cordb->m_unmanagedCallback != NULL);
// Call the callback with fIsOutOfBand = TRUE.
{
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this, pEvent, TRUE);
this->m_cordb->m_unmanagedCallback->DebugEvent(const_cast<DEBUG_EVENT*> (pEvent), TRUE);
}
this->Lock();
// If m_dispatchingOOBEvent is false, that means that the user called Continue() from within
// the callback. We know that we can go ahead and continue the process now.
if (this->m_dispatchingOOBEvent == false)
{
// Note: this call will dispatch more OOB events if necessary.
pW32EventThread->UnmanagedContinue(this, cOobUMContinue);
}
else
{
// We're not dispatching anymore, so set this back to false.
this->m_dispatchingOOBEvent = false;
}
}
// We've handled this event. Skip further processing.
goto LDone;
}
} // end Switch on Reaction
UNREACHABLE();
LDone:
// Process Lock implicitly released by holder.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: done processing event.\n");
return;
}
//
// Returns true if the exception is a flare from the left side, false otherwise.
//
bool CordbProcess::ExceptionIsFlare(DWORD exceptionCode, const void *exceptionAddress)
{
_ASSERTE(m_runtimeOffsetsInitialized);
// Can't have a flare if the left side isn't initialized
if (m_initialized)
{
DebuggerIPCRuntimeOffsets *pRO = &m_runtimeOffsets;
// All flares are breakpoints...
if (exceptionCode == STATUS_BREAKPOINT)
{
// Does the breakpoint address match a flare address?
if ((exceptionAddress == pRO->m_signalHijackStartedBPAddr) ||
(exceptionAddress == pRO->m_excepForRuntimeHandoffStartBPAddr) ||
(exceptionAddress == pRO->m_excepForRuntimeHandoffCompleteBPAddr) ||
(exceptionAddress == pRO->m_signalHijackCompleteBPAddr) ||
(exceptionAddress == pRO->m_excepNotForRuntimeBPAddr) ||
(exceptionAddress == pRO->m_notifyRSOfSyncCompleteBPAddr))
return true;
}
}
return false;
}
#endif // FEATURE_INTEROP_DEBUGGING
// Allocate a buffer in the target and copy data into it.
//
// Arguments:
// pDomain - an appdomain associated with the allocation request.
// bufferSize - size of the buffer in bytes
// bufferFrom - local buffer of data (bufferSize bytes) to copy data from.
// ppRes - address into target of allocated buffer
//
// Returns:
// S_OK on success, else error.
HRESULT CordbProcess::GetAndWriteRemoteBuffer(CordbAppDomain *pDomain, unsigned int bufferSize, const void *bufferFrom, void **ppRes)
{
_ASSERTE(ppRes != NULL);
*ppRes = NULL;
HRESULT hr = S_OK;
EX_TRY
{
TargetBuffer tbTarget = GetRemoteBuffer(bufferSize); // throws
SafeWriteBuffer(tbTarget, (const BYTE*) bufferFrom); // throws
// Succeeded.
*ppRes = CORDB_ADDRESS_TO_PTR(tbTarget.pAddress);
}
EX_CATCH_HRESULT(hr);
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//
// Checks to see if the given second chance exception event actually signifies the death of the process due to a second
// stack overflow special case.
//
// There are strange cases with stack overflow exceptions. If a nieve application catches a stack overflow exception and
// handles it, without resetting the guard page, then the app will get an AV when it overflows the stack a second time. We
// will get the first chance AV, but when we continue from it the OS won't run any SEH handlers, so our FCH won't
// actually work. Instead, we'll get the AV back on second chance right away.
//
bool CordbProcess::IsSpecialStackOverflowCase(CordbUnmanagedThread *pUThread, const DEBUG_EVENT *pEvent)
{
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
_ASSERTE(pEvent->u.Exception.dwFirstChance == 0);
// If this is not an AV, it can't be our special case.
if (pEvent->u.Exception.ExceptionRecord.ExceptionCode != STATUS_ACCESS_VIOLATION)
return false;
// If the thread isn't already first chance hijacked, it can't be our special case.
if (!pUThread->IsFirstChanceHijacked())
return false;
// The first chance hijack didn't take, so we're not FCH anymore and we're not waiting for an answer
// anymore... Note: by leaving this thread completely unhijacked, we'll report its true context, which is correct.
pUThread->ClearState(CUTS_FirstChanceHijacked);
// The process is techincally dead as a door nail here, so we'll mark that the helper thread is dead so our managed
// API bails nicely.
m_helperThreadDead = true;
// Remember we're in our special case.
pUThread->SetState(CUTS_HasSpecialStackOverflowCase);
// Now, remember the second chance AV event in the second IB event slot for this thread and add it to the end of the
// IB event queue.
QueueUnmanagedEvent(pUThread, pEvent);
// Note: returning true will ensure that the queued first chance AV for this thread is dispatched.
return true;
}
//-----------------------------------------------------------------------------
// Longhorn broke ContinueDebugEvent.
// In previous OS releases, DBG_CONTINUE would continue a non-continuable exception.
// In longhorn, we need to pass the DBG_FORCE_CONTINUE flag to do that.
// Note that all CLR exceptions are non-continuable.
// Now instead of DBG_CONTINUE, we need to pass DBG_FORCE_CONTINUE.
//-----------------------------------------------------------------------------
// Currently we don't have headers for the longhorn winnt.h. So we need to privately declare
// this here. We have a check such that if we do get headers, the value won't change underneath us.
#define MY_DBG_FORCE_CONTINUE ((DWORD )0x00010003L)
#ifndef DBG_FORCE_CONTINUE
#define DBG_FORCE_CONTINUE MY_DBG_FORCE_CONTINUE
#else
static_assert_no_msg(DBG_FORCE_CONTINUE == MY_DBG_FORCE_CONTINUE);
#endif
DWORD GetDbgContinueFlag()
{
// Currently, default to not using the new DBG_FORCE_CONTINUE flag.
static ConfigDWORD fNoFlagKey;
bool fNoFlag = fNoFlagKey.val(CLRConfig::UNSUPPORTED_DbgNoForceContinue) != 0;
if (!fNoFlag)
{
return DBG_FORCE_CONTINUE;
}
else
{
return DBG_CONTINUE;
}
}
// Some Interop bugs involve threads that land at a bad IP. Since we're interop-debugging, we can't
// attach a debugger to the LS. So we have some debug mode where we enable the SS flag and thus
// produce a trace of where a thread is going.
#ifdef _DEBUG
void EnableDebugTrace(CordbUnmanagedThread *ut)
{
// To enable, attach w/ a debugger and either set fTrace==true, or setip.
static bool fTrace = false;
if (!fTrace)
return;
// Give us a nop so that we can setip in the optimized case.
#ifdef TARGET_X86
__asm {
nop
}
#endif
fTrace = true;
CordbProcess *pProcess = ut->GetProcess();
// Get the context
HRESULT hr = S_OK;
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
hr = pProcess->GetThreadContext((DWORD) ut->m_id, sizeof(context), (BYTE*)&context);
if (FAILED(hr))
return;
// If the flag is already set, then don't set it again - that will just get confusing.
if (IsSSFlagEnabled(&context))
{
return;
}
_ASSERTE(CORDbgGetIP(&context) != 0);
SetSSFlag(&context);
// If SS flag not set, enable it. And remeber that it's us so we know how to handle
// it when we get the debug event.
hr = pProcess->SetThreadContext((DWORD)ut->m_id, sizeof(context), (BYTE*)&context);
ut->SetState(CUTS_DEBUG_SingleStep);
}
#endif // _DEBUG
//-----------------------------------------------------------------------------
// DoDbgContinue
//
// Continues from a specific Win32 DEBUG_EVENT.
//
// Arguments:
// pProcess - The process to continue.
// pUnmanagedEvent - The event to continue.
//
//-----------------------------------------------------------------------------
void CordbWin32EventThread::DoDbgContinue(CordbProcess *pProcess,
CordbUnmanagedEvent *pUnmanagedEvent)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
_ASSERTE(pUnmanagedEvent != NULL);
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
STRESS_LOG3(LF_CORDB, LL_INFO1000,
"W32ET::DDC: continue with ue=0x%p, thread=0x%p, tid=0x%x\n",
pUnmanagedEvent,
pUnmanagedEvent->m_owner,
pUnmanagedEvent->m_owner->m_id);
#ifdef _DEBUG
EnableDebugTrace(pUnmanagedEvent->m_owner);
#endif
if (pUnmanagedEvent->IsEventContinuedHijacked())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Skiping DoDbgContinue because event was already"
" continued hijacked, ue=0x%p\n", pUnmanagedEvent));
return;
}
BOOL threadIsHijacked = (pUnmanagedEvent->m_owner->IsFirstChanceHijacked() ||
pUnmanagedEvent->m_owner->IsGenericHijacked());
BOOL eventIsIB = (pUnmanagedEvent->m_owner->HasIBEvent() &&
pUnmanagedEvent->m_owner->IBEvent() == pUnmanagedEvent);
_ASSERTE((DWORD) pProcess->m_id == pUnmanagedEvent->m_currentDebugEvent.dwProcessId);
_ASSERTE(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED);
DWORD dwContType;
if(eventIsIB)
{
// 3 cases here...
// event was already hijacked
if(threadIsHijacked)
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, already hijacked, ue=0x%p\n", pUnmanagedEvent));
pUnmanagedEvent->SetState(CUES_EventContinuedHijacked);
dwContType = !pUnmanagedEvent->m_owner->IsBlockingForSync() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
// event was not hijacked but has been dispatched
else if(!threadIsHijacked && pUnmanagedEvent->IsDispatched())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, not hijacked, ue=0x%p\n", pUnmanagedEvent));
_ASSERTE(pUnmanagedEvent->IsDispatched());
_ASSERTE(pUnmanagedEvent->IsEventUserContinued());
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
dwContType = pUnmanagedEvent->IsExceptionCleared() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
// The event was never hijacked and so will never need to retrigger, get rid
// of it right now. If it had been hijacked then we would dequeue it either after the
// hijack complete flare or one instruction after that when it has had a chance to retrigger
pProcess->DequeueUnmanagedEvent(pUnmanagedEvent->m_owner);
}
// event was not hijacked nor dispatched
else // if(!threadIsHijacked && !pUnmanagedEvent->IsDispatched())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, now hijacked, ue=0x%p\n", pUnmanagedEvent));
HRESULT hr = pProcess->HijackIBEvent(pUnmanagedEvent);
_ASSERTE(SUCCEEDED(hr));
pUnmanagedEvent->SetState(CUES_EventContinuedHijacked);
dwContType = !pUnmanagedEvent->m_owner->IsBlockingForSync() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
}
else
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing OB, ue=0x%p\n", pUnmanagedEvent));
// we might actually be hijacked here, but if we are it should be for a previous IB event
// we just mark all OB events as continued unhijacked
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
dwContType = pUnmanagedEvent->IsExceptionCleared() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
// If the exception is marked as unclearable, then make sure the continue type is correct and force the process
// to terminate.
if (pUnmanagedEvent->IsExceptionUnclearable())
{
TerminateProcess(pProcess->UnsafeGetProcessHandle(), pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode);
dwContType = DBG_EXCEPTION_NOT_HANDLED;
}
// If we're continuing from the loader-bp, then send the managed attach here.
// (Note this will only be set if the runtime was loaded when we first tried to attach).
// We assume that the loader-bp is the 1st BP exception. This is naive,
// since it's not 100% accurate (someone could CreateThread w/ a threadproc of DebugBreak).
// But it's the best we can do.
// Note that it's critical we do this BEFORE continuing the process. If this is mixed-mode, we've already
// told VS about this breakpoint, and so it's set the attach-complete event. As soon as we continue this debug
// event the process can start moving again, so the CLR needs to know to wait for a managed attach.
DWORD dwEventCode = pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode;
if (dwEventCode == EXCEPTION_DEBUG_EVENT)
{
EXCEPTION_DEBUG_INFO * pDebugInfo = &pUnmanagedEvent->m_currentDebugEvent.u.Exception;
if (pDebugInfo->dwFirstChance && pDebugInfo->ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT)
{
HRESULT hrIgnore = S_OK;
EX_TRY
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::DDC: Continuing from LdrBp, doing managed attach.\n"));
pProcess->QueueManagedAttachIfNeededWorker();
}
EX_CATCH_HRESULT(hrIgnore);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hrIgnore));
}
}
STRESS_LOG4(LF_CORDB, LL_INFO1000,
"W32ET::DDC: calling ContinueDebugEvent(0x%x, 0x%x, 0x%x), process state=0x%x\n",
pProcess->m_id, pUnmanagedEvent->m_owner->m_id, dwContType, pProcess->m_state);
// Actually continue the debug event
pProcess->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
BOOL fSuccess = m_pNativePipeline->ContinueDebugEvent((DWORD)pProcess->m_id, (DWORD)pUnmanagedEvent->m_owner->m_id, dwContType);
// ContinueDebugEvent may 'fail' if we force kill the debuggee while stopped at the exit-process event.
if (!fSuccess && (dwEventCode != EXIT_PROCESS_DEBUG_EVENT))
{
_ASSERTE(!"ContinueDebugEvent failed!");
CORDBSetUnrecoverableError(pProcess, HRESULT_FROM_GetLastError(), 0);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::DDC: Last error after ContinueDebugEvent is %d\n", GetLastError());
}
// If this thread is marked for deletion (exit thread or exit process event on it), then we need to delete the
// unmanaged thread object.
if ((dwEventCode == EXIT_PROCESS_DEBUG_EVENT) || (dwEventCode == EXIT_THREAD_DEBUG_EVENT))
{
CordbUnmanagedThread * pUnmanagedThread = pUnmanagedEvent->m_owner;
_ASSERTE(pUnmanagedThread->IsDeleted());
// Thread may have a hijacked inband event on it. Thus it's actually running free from the OS perspective,
// and fair game to be terminated. In that case, we need to auto-dequeue the event.
// This will just prevent the RS from making the underlying call to ContinueDebugEvent on this thread
// for the inband event. Since we've already lost the thread, that's actually exactly what we want.
if (pUnmanagedThread->HasIBEvent())
{
pProcess->DequeueUnmanagedEvent(pUnmanagedThread);
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "Removing thread 0x%x (%d) from process list\n", pUnmanagedThread->m_id);
pProcess->m_unmanagedThreads.RemoveBase((ULONG_PTR)pUnmanagedThread->m_id);
}
// If we just continued from an exit process event, then its time to do the exit processing.
if (dwEventCode == EXIT_PROCESS_DEBUG_EVENT)
{
pProcess->Unlock();
ExitProcess(false); // not detach case
pProcess->Lock();
}
}
//---------------------------------------------------------------------------------------
//
// ForceDbgContinue continues from the last Win32 DEBUG_EVENT on the given thread, no matter what it was.
//
// Arguments:
// pProcess - process object to continue
// pUnmanagedThread - unmanaged thread object (maybe null if we're doing a raw cotninue)
// contType - continuation status (DBG_CONTINUE or DBG_EXCEPTION_NOT_HANDLED)
// fContinueProcess - do we resume hijacks?
//
void CordbWin32EventThread::ForceDbgContinue(CordbProcess *pProcess, CordbUnmanagedThread *pUnmanagedThread, DWORD contType,
bool fContinueProcess)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(pUnmanagedThread != NULL);
STRESS_LOG4(LF_CORDB, LL_INFO1000,
"W32ET::FDC: force continue with 0x%x (%s), contProcess=%d, tid=0x%x\n",
contType,
(contType == DBG_CONTINUE) ? "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED",
fContinueProcess,
pUnmanagedThread->m_id);
if (fContinueProcess)
{
pProcess->ResumeHijackedThreads();
}
if (contType == DBG_CONTINUE)
{
contType = GetDbgContinueFlag();
}
_ASSERTE(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED);
// Remove the Win32 stopped flag so long as the OOB event queue is empty. We're forcing a continue here, so by
// definition this should be the case...
_ASSERTE(pProcess->m_outOfBandEventQueue == NULL);
pProcess->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
STRESS_LOG4(LF_CORDB, LL_INFO1000, "W32ET::FDC: calling ContinueDebugEvent(0x%x, 0x%x, 0x%x), process state=0x%x\n",
pProcess->m_id, pUnmanagedThread->m_id, contType, pProcess->m_state);
#ifdef _DEBUG
EnableDebugTrace(pUnmanagedThread);
#endif
BOOL ret = m_pNativePipeline->ContinueDebugEvent((DWORD)pProcess->m_id, (DWORD)pUnmanagedThread->m_id, contType);
if (!ret)
{
// This could in theory fail from Process exit, but that really would only be on the DoDbgContinue path.
_ASSERTE(!"ContinueDebugEvent failed #2!");
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::DDC: Last error after ContinueDebugEvent is %d\n", GetLastError());
}
}
#endif // FEATURE_INTEROP_DEBUGGING
//
// This is the thread's real thread proc. It simply calls to the
// thread proc on the given object.
//
/*static*/ DWORD WINAPI CordbWin32EventThread::ThreadProc(LPVOID parameter)
{
CordbWin32EventThread* t = (CordbWin32EventThread*) parameter;
INTERNAL_THREAD_ENTRY(t);
t->ThreadProc();
return 0;
}
//
// Send a CreateProcess event to the Win32 thread to have it create us
// a new process.
//
HRESULT CordbWin32EventThread::SendCreateProcessEvent(
MachineInfo machineInfo,
LPCWSTR programName,
_In_z_ LPWSTR programArgs,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
PVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
CorDebugCreateProcessFlags corDebugFlags)
{
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
LOG((LF_CORDB, LL_EVERYTHING, "CordbWin32EventThread::SCPE Called\n"));
m_actionData.createData.machineInfo = machineInfo;
m_actionData.createData.programName = programName;
m_actionData.createData.programArgs = programArgs;
m_actionData.createData.lpProcessAttributes = lpProcessAttributes;
m_actionData.createData.lpThreadAttributes = lpThreadAttributes;
m_actionData.createData.bInheritHandles = bInheritHandles;
m_actionData.createData.dwCreationFlags = dwCreationFlags;
m_actionData.createData.lpEnvironment = lpEnvironment;
m_actionData.createData.lpCurrentDirectory = lpCurrentDirectory;
m_actionData.createData.lpStartupInfo = lpStartupInfo;
m_actionData.createData.lpProcessInformation = lpProcessInformation;
m_actionData.createData.corDebugFlags = corDebugFlags;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_CREATE_PROCESS;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
LOG((LF_CORDB, LL_EVERYTHING, "Process Handle is: %x, m_threadControlEvent is %x\n",
(UINT_PTR)m_actionData.createData.lpProcessInformation->hProcess, (UINT_PTR)m_threadControlEvent));
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//---------------------------------------------------------------------------------------
//
// Create a process
//
// Assumptions:
// This occurs on the win32 event thread. It is invokved via
// a message sent from code:CordbWin32EventThread::SendCreateProcessEvent
//
// Notes:
// Create a new process. This is called in the context of the Win32
// event thread to ensure that if we're Win32 debugging the process
// that the same thread that waits for debugging events will be the
// thread that creates the process.
//
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::CreateProcess()
{
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
DWORD dwCreationFlags = m_actionData.createData.dwCreationFlags;
// If the creation flags has DEBUG_PROCESS in them, then we're
// Win32 debugging this process. Otherwise, we have to create
// suspended to give us time to setup up our side of the IPC
// channel.
BOOL fInteropDebugging =
#if defined(FEATURE_INTEROP_DEBUGGING)
(dwCreationFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS));
#else
false; // Interop not supported.
#endif
// Have Win32 create the process...
hr = m_pNativePipeline->CreateProcessUnderDebugger(
m_actionData.createData.machineInfo,
m_actionData.createData.programName,
m_actionData.createData.programArgs,
m_actionData.createData.lpProcessAttributes,
m_actionData.createData.lpThreadAttributes,
m_actionData.createData.bInheritHandles,
dwCreationFlags,
m_actionData.createData.lpEnvironment,
m_actionData.createData.lpCurrentDirectory,
m_actionData.createData.lpStartupInfo,
m_actionData.createData.lpProcessInformation);
if (SUCCEEDED(hr))
{
// Process ID is filled in after process is succesfully created.
DWORD dwProcessId = m_actionData.createData.lpProcessInformation->dwProcessId;
ProcessDescriptor pd = ProcessDescriptor::FromPid(dwProcessId);
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
hr = m_pShim->InitializeDataTarget(&pd);
if (SUCCEEDED(hr))
{
// To emulate V2 semantics, we pass 0 for the clrInstanceID into
// OpenVirtualProcess. This will then connect to the first CLR
// loaded.
const ULONG64 cFirstClrLoaded = 0;
hr = CordbProcess::OpenVirtualProcess(cFirstClrLoaded, m_pShim->GetDataTarget(), NULL, m_cordb, &pd, m_pShim, &pProcess);
}
// Shouldn't happen on a create, only an attach
_ASSERTE(hr != CORDBG_E_DEBUGGER_ALREADY_ATTACHED);
// Remember the process in the global list of processes.
if (SUCCEEDED(hr))
{
EX_TRY
{
// Mark if we're interop-debugging
if (fInteropDebugging)
{
pProcess->EnableInteropDebugging();
}
m_cordb->AddProcess(pProcess); // will take ref if it succeeds
}
EX_CATCH_HRESULT(hr);
}
// If we're Win32 attached to this process, then increment the
// proper count, otherwise add this process to the wait set
// and resume the process's main thread.
if (SUCCEEDED(hr))
{
_ASSERTE(m_pProcess == NULL);
m_pProcess.Assign(pProcess);
}
}
//
// Signal the hr to the caller.
//
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
//
// Send a DebugActiveProcess event to the Win32 thread to have it attach to
// a new process.
//
HRESULT CordbWin32EventThread::SendDebugActiveProcessEvent(
MachineInfo machineInfo,
const ProcessDescriptor *pProcessDescriptor,
bool fWin32Attach,
CordbProcess *pProcess)
{
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
m_actionData.attachData.machineInfo = machineInfo;
m_actionData.attachData.processDescriptor = *pProcessDescriptor;
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
m_actionData.attachData.fWin32Attach = fWin32Attach;
#endif
m_actionData.attachData.pProcess = pProcess;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_ATTACH_PROCESS;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//-----------------------------------------------------------------------------
// Is the given thread id a helper thread (real or worker?)
//-----------------------------------------------------------------------------
bool CordbProcess::IsHelperThreadWorked(DWORD tid)
{
// Check against the id gained by sniffing Thread-Create events.
if (tid == this->m_helperThreadId)
{
return true;
}
// Now check for potential datate in the IPC block. If not there,
// then we know it can't be the helper.
DebuggerIPCControlBlock * pDCB = this->GetDCB();
if (pDCB == NULL)
{
return false;
}
// get the latest information from the LS DCB
UpdateRightSideDCB();
return
(tid == pDCB->m_realHelperThreadId) ||
(tid == pDCB->m_temporaryHelperThreadId);
}
//---------------------------------------------------------------------------------------
//
// Cleans up the Left Side's DCB after a failed attach attempt.
//
// Assumptions:
// Called when the left-site failed initialization
//
// Notes:
// This can be called multiple times.
//---------------------------------------------------------------------------------------
void CordbProcess::CleanupHalfBakedLeftSide()
{
if (GetDCB() != NULL)
{
EX_TRY
{
GetDCB()->m_rightSideIsWin32Debugger = false;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
if (m_pEventChannel != NULL)
{
m_pEventChannel->Delete();
m_pEventChannel = NULL;
}
}
EX_CATCH
{
_ASSERTE(!"Writing process memory failed, perhaps due to an unexpected disconnection from the target.");
}
EX_END_CATCH(SwallowAllExceptions);
}
// Close and null out the various handles and events, including our process handle m_handle.
CloseIPCHandles();
m_cordb.Clear();
// This process object is Dead-On-Arrival, so it doesn't really have anything to neuter.
// But for safekeeping, we'll mark it as neutered.
UnsafeNeuterDeadObject();
}
//---------------------------------------------------------------------------------------
//
// Attach to an existing process.
//
//
// Assumptions:
// Called on W32Event Thread, in response to event sent by
// code:CordbWin32EventThread::SendDebugActiveProcessEvent
//
// Notes:
// Attach to a process. This is called in the context of the Win32
// event thread to ensure that if we're Win32 debugging the process
// that the same thread that waits for debugging events will be the
// thread that attaches the process.
//
// @dbgtodo shim: this will be part of the shim
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::AttachProcess()
{
_ASSERTE(IsWin32EventThread());
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
ProcessDescriptor processDescriptor = m_actionData.attachData.processDescriptor;
bool fNativeAttachSucceeded = false;
// Always do OS attach to the target.
// By this point, the pid should be valid (because OpenProcess above), pending some race where the process just exited.
// The OS will enforce that only 1 debugger is attached.
// Common failure paths here would be: access denied, double-attach
{
hr = m_pNativePipeline->DebugActiveProcess(m_actionData.attachData.machineInfo,
processDescriptor);
if (FAILED(hr))
{
goto LExit;
}
fNativeAttachSucceeded = true;
}
hr = m_pShim->InitializeDataTarget(&processDescriptor);
if (FAILED(hr))
{
goto LExit;
}
// To emulate V2 semantics, we pass 0 for the clrInstanceID into
// OpenVirtualProcess. This will then connect to the first CLR
// loaded.
{
const ULONG64 cFirstClrLoaded = 0;
hr = CordbProcess::OpenVirtualProcess(cFirstClrLoaded, m_pShim->GetDataTarget(), NULL, m_cordb, &processDescriptor, m_pShim, &pProcess);
if (FAILED(hr))
{
goto LExit;
}
}
// Remember the process in the global list of processes.
// The caller back in code:Cordb::DebugActiveProcess will then get this by fetching it from the list.
EX_TRY
{
// Don't allow attach if any metadata/IL updates have been applied
if (pProcess->GetDAC()->MetadataUpdatesApplied())
{
hr = CORDBG_E_ASSEMBLY_UPDATES_APPLIED;
goto LExit;
}
// Mark interop-debugging
if (m_actionData.attachData.IsInteropDebugging())
{
pProcess->EnableInteropDebugging(); // Throwing
}
m_cordb->AddProcess(pProcess); // will take ref if it succeeds
// Queue fake Attach event for CreateProcess
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(pProcess);
m_pShim->BeginQueueFakeAttachEvents();
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
goto LExit;
}
_ASSERTE(m_pProcess == NULL);
m_pProcess.Assign(pProcess);
pProcess.Clear(); // ownership transfered to m_pProcess
// Should have succeeded if we got to this point.
_ASSERTE(SUCCEEDED(hr));
LExit:
if (FAILED(hr))
{
// If we succeed to do a native-attach, but then failed elsewhere, try to native-detach.
if (fNativeAttachSucceeded)
{
m_pNativePipeline->DebugActiveProcessStop(processDescriptor.m_Pid);
}
if (pProcess != NULL)
{
// Safe to call this even if the process wasn't added.
m_cordb->RemoveProcess(pProcess);
pProcess->CleanupHalfBakedLeftSide();
pProcess.Clear();
}
m_pProcess.Clear();
}
//
// Signal the hr to the caller.
//
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
// Note that the actual 'DetachProcess' method is really ExitProcess with CW32ET_UNKNOWN_PROCESS_SLOT ==
// processSlot
HRESULT CordbWin32EventThread::SendDetachProcessEvent(CordbProcess *pProcess)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::SDPE\n"));
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
m_actionData.detachData.pProcess = pProcess;
// m_action is set last so that the win32 event thread can inspect it and take action without actually
// having to take any locks. The lock around this here is simply to prevent multiple threads from making
// requests at the same time.
m_action = W32ETA_DETACH;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//
// Send a UnmanagedContinue event to the Win32 thread to have it
// continue from an unmanged debug event.
//
HRESULT CordbWin32EventThread::SendUnmanagedContinue(CordbProcess *pProcess,
EUMContinueType eContType)
{
HRESULT hr = S_OK;
// If this were being called on the win32 EventThread, we'd deadlock.
_ASSERTE(!IsWin32EventThread());
// This can't hold the process lock, b/c we're making a cross-thread call,
// and our target will need the process lock.
_ASSERTE(!pProcess->ThreadHoldsProcessLock());
LockSendToWin32EventThreadMutex();
m_actionData.continueData.process = pProcess;
m_actionData.continueData.eContType = eContType;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_CONTINUE;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//
// Handle unmanaged continue. Continue an unmanaged debug
// event. Deferes to UnmanagedContinue. This is called in the context
// of the Win32 event thread to ensure that if we're Win32 debugging
// the process that the same thread that waits for debugging events
// will be the thread that continues the process.
//
void CordbWin32EventThread::HandleUnmanagedContinue()
{
_ASSERTE(IsWin32EventThread());
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
// Continue the process
CordbProcess *pProcess = m_actionData.continueData.process;
// If we lost the process object, we must have exited.
if (m_pProcess != NULL)
{
_ASSERTE(m_pProcess != NULL);
_ASSERTE(pProcess == m_pProcess);
_ASSERTE(!pProcess->ThreadHoldsProcessLock());
RSSmartPtr<CordbProcess> proc(pProcess);
RSLockHolder ch(&pProcess->m_processMutex);
hr = UnmanagedContinue(pProcess, m_actionData.continueData.eContType);
}
// Signal the hr to the caller.
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
//
// Continue an unmanaged debug event. This is called in the context of the Win32 Event thread to ensure that the same
// thread that waits for debug events will be the thread that continues the process.
//
HRESULT CordbWin32EventThread::UnmanagedContinue(CordbProcess *pProcess,
EUMContinueType eContType)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
_ASSERTE(m_pShim != NULL);
HRESULT hr = S_OK;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "UM Continue. type=%d\n", eContType);
if (eContType == cOobUMContinue)
{
_ASSERTE(pProcess->m_outOfBandEventQueue != NULL);
// Dequeue the OOB event.
CordbUnmanagedEvent *ue = pProcess->m_outOfBandEventQueue;
CordbUnmanagedThread *ut = ue->m_owner;
pProcess->DequeueOOBUnmanagedEvent(ut);
// Do a little extra work if that was an OOB exception event...
hr = ue->m_owner->FixupAfterOOBException(ue);
_ASSERTE(SUCCEEDED(hr));
// Continue from the event.
DoDbgContinue(pProcess, ue);
// If there are more queued OOB events, dispatch them now.
if (pProcess->m_outOfBandEventQueue != NULL)
pProcess->DispatchUnmanagedOOBEvent();
// Note: if we previously skipped letting the entire process go on an IB continue due to a blocking OOB event,
// and if the OOB event queue is now empty, then go ahead and let the process continue now...
if ((pProcess->m_doRealContinueAfterOOBBlock == true) &&
(pProcess->m_outOfBandEventQueue == NULL))
goto doRealContinue;
}
else if (eContType == cInternalUMContinue)
{
// We're trying to get into a synced state which means we need the process running (potentially
// with some threads hijacked) in order to have the helper thread do the sync.
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue.\n"));
if (!pProcess->GetSynchronized())
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, !sync'd.\n"));
pProcess->ResumeUnmanagedThreads();
// the event we may need to hijack and continue;
CordbUnmanagedEvent* pEvent = pProcess->m_lastQueuedUnmanagedEvent;
// It is possible to be stopped at either an IB or an OOB event here. We only want to
// continue from an IB event here though
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED && pEvent != NULL &&
pEvent->IsEventWaitingForContinue())
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, frozen on IB event.\n"));
// There should be a uncontinued IB event at the head of the queue
_ASSERTE(pEvent->IsIBEvent());
_ASSERTE(!pEvent->IsEventContinuedUnhijacked());
_ASSERTE(!pEvent->IsEventContinuedHijacked());
// Ensure that the event is hijacked now (it may not have been before) so that the
// thread does not slip forward during the sync process. After that we can safely continue
// it.
pProcess->HijackIBEvent(pEvent);
m_pShim->GetWin32EventThread()->DoDbgContinue(pProcess, pEvent);
}
}
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, done.\n"));
}
else
{
// If we're here, then we know 100% for sure that we've successfully gotten the managed continue event to the
// Left Side, so we can stop force hijacking left over in-band events now. Note: if we had hijacked any such
// events, they'll be dispatched below since they're properly queued.
pProcess->m_specialDeferment = false;
// We don't actually do any work if there is an outstanding out-of-band event. When we do continue from the
// out-of-band event, we'll do this work, too.
if (pProcess->m_outOfBandEventQueue != NULL)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: ignoring real continue due to block by out-of-band event(s).\n"));
_ASSERTE(pProcess->m_doRealContinueAfterOOBBlock == false);
pProcess->m_doRealContinueAfterOOBBlock = true;
}
else
{
doRealContinue:
// This is either the Frozen -> Running transition or a
// Synced -> Running transition
_ASSERTE(pProcess->m_outOfBandEventQueue == NULL);
pProcess->m_doRealContinueAfterOOBBlock = false;
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: continuing the process.\n"));
// Dispatch any more queued in-band events, or if there are none then just continue the process.
//
// Note: don't dispatch more events if we've already sent up the ExitProcess event... those events are just
// lost.
if ((pProcess->HasUndispatchedNativeEvents()) && (pProcess->m_exiting == false))
{
pProcess->DispatchUnmanagedInBandEvent();
}
else
{
// If the unmanaged event queue is empty now, and the process is synchronized, and there are queued
// managed events, then go ahead and get more managed events dispatched.
//
// Note: don't dispatch more events if we've already sent up the ExitProcess event... those events are
// just lost.
if (pProcess->GetSynchronized() && (!m_pShim->GetManagedEventQueue()->IsEmpty()) && (pProcess->m_exiting == false))
{
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED)
{
DoDbgContinue(pProcess, pProcess->m_lastDispatchedIBEvent);
// This if should not be necessary, I am just being extra careful because this
// fix is going in late - see issue 818301
_ASSERTE(pProcess->m_lastDispatchedIBEvent != NULL);
if(pProcess->m_lastDispatchedIBEvent != NULL)
{
pProcess->m_lastDispatchedIBEvent->m_owner->InternalRelease();
pProcess->m_lastDispatchedIBEvent = NULL;
}
}
// Now, get more managed events dispatched.
pProcess->SetSynchronized(false);
pProcess->MarkAllThreadsDirty();
m_cordb->ProcessStateChanged();
}
else
{
// free all the hijacked threads that hit native debug events
pProcess->ResumeHijackedThreads();
// after continuing the here the process should be running completely
// free... no hijacks, no suspended threads, and of course not frozen
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED)
{
DoDbgContinue(pProcess, pProcess->m_lastDispatchedIBEvent);
// This if should not be necessary, I am just being extra careful because this
// fix is going in late - see issue 818301
_ASSERTE(pProcess->m_lastDispatchedIBEvent != NULL);
if(pProcess->m_lastDispatchedIBEvent != NULL)
{
pProcess->m_lastDispatchedIBEvent->m_owner->InternalRelease();
pProcess->m_lastDispatchedIBEvent = NULL;
}
}
}
}
// Implicit Release on UT
}
}
return hr;
}
#endif // FEATURE_INTEROP_DEBUGGING
void ExitProcessWorkItem::Do()
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "ExitProcessWorkItem proc=%p\n", GetProcess());
// This is being called on the RCET.
// That's the thread that dispatches managed events. Since it's calling us now, we know
// it can't be dispatching a managed event, and so we don't need to both waiting for it
{
// Get the SG lock here to coordinate against any other continues.
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder ch2(&(GetProcess()->m_processMutex));
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: ExitProcess callback\n"));
// We're synchronized now, so mark the process as such.
GetProcess()->SetSynchronized(true);
GetProcess()->IncStopCount();
// By the time we release the SG + Process locks here, the process object has been
// marked as exiting + terminated (by the w32et which queued us). Future attemps to
// continue should fail, and thus we should remain synchronized.
}
// Just to be safe, neuter any children before the exit process callback.
{
RSLockHolder ch(GetProcess()->GetProcessLock());
// Release the process.
GetProcess()->NeuterChildren();
}
RSSmartPtr<Cordb> pCordb(NULL);
// There is a race condition here where the debuggee process is killed while we are processing a process
// detach. We queue the process exit event for the Win32 event thread before queueing the process detach
// event. By the time this function is executed, we may have neutered the CordbProcess already as a
// result of code:CordbProcess::Detach. Detect that case here under the SG lock.
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
if (!GetProcess()->IsNeutered())
{
_ASSERTE(GetProcess()->m_cordb != NULL);
pCordb.Assign(GetProcess()->m_cordb);
}
}
// Move this into Shim?
// Invoke the ExitProcess callback. This is very important since the a shell
// may rely on it for proper shutdown and may hang if they don't get it.
// We don't expect Cordbg to continue from this (we're certainly not going to wait for it).
if ((pCordb != NULL) && (pCordb->m_managedCallback != NULL))
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(GetProcess());
pCordb->m_managedCallback->ExitProcess(GetProcess());
}
// This CordbProcess object now has no reservations against a client calling ICorDebug::Terminate.
// That call may race against the CordbProcess::Neuter below, but since we already neutered the children,
// that neuter call will not do anything interesting that will conflict with Terminate.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: returned from ExitProcess callback\n"));
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
// Release the process.
GetProcess()->Neuter();
}
// Our dtor will release the Process object.
// This may be the final release on the process.
}
//---------------------------------------------------------------------------------------
//
// Handles process exiting and detach cases
//
// Arguments:
// fDetach - true if detaching, false if process is exiting.
//
// Return Value:
// The type of the next argument in the signature,
// normalized.
//
// Assumptions:
// On exit, the process has already exited and we detected this by either an EXIT_PROCESS
// native debug event, or by waiting on the process handle.
// On detach, the process is stil live.
//
// Notes:
// ExitProcess is called when a process exits or detaches.
// This does our final cleanup and removes the process from our wait sets.
// We're either here because we're detaching (fDetach == TRUE), or because the process has really exited,
// and we're doing shutdown logic.
//
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::ExitProcess(bool fDetach)
{
INTERNAL_API_ENTRY(this);
// Consider the following when you're modifying this function:
// - The OS can kill the debuggee at any time.
// - ExitProcess can race with detach.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: begin ExitProcess, detach=%d\n", fDetach));
// For the Mac remote debugging transport, DebugActiveProcessStop() is a nop. The transport will be
// shut down later when we neuter the CordbProcess.
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
// @dbgtodo shim: this is a primitive workaround for interop-detach
// Eventually, the Debugger owns the detach pipeline, so this won't be necessary.
if (fDetach && (m_pProcess != NULL))
{
HRESULT hr = m_pNativePipeline->DebugActiveProcessStop(m_pProcess->GetProcessDescriptor()->m_Pid);
// We don't expect detach to fail (we check earlier for common conditions that
// may cause it to fail)
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
if( FAILED(hr) )
{
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
return;
}
}
#endif // !FEATURE_DBGIPC_TRANSPORT_DI
// We don't really care if we're on the Win32 thread or not here. We just want to be sure that
// the LS Exit case and the Detach case both occur on the same thread. This makes it much easier
// to assert that if we exit while detaching, EP is only called once.
// If we ever decide to make the RCET listen on the LS process handle for EP(exit), then we should also
// make the EP(detach) handled on the RCET (via DoFavor() ).
_ASSERTE(IsWin32EventThread());
// So either the Exit case or Detach case must happen first.
// 1) If Detach first, then LS process is removed from wait set and so EP(Exit) will never happen
// because we check wait set after returning from EP(Detach).
// 2) If Exit is first, m_pProcess gets set=NULL. EP(detach) will still get called, so explicitly check that.
if (fDetach && ((m_pProcess == NULL) || m_pProcess->m_terminated))
{
// m_terminated is only set after the LS exits.
// So the only way (fDetach && m_terminated) is true is if the LS exited while detaching. In that case
// we already called EP(exit) and we don't want to call it again for EP(detach). So return here.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: In EP(detach), but EP(exit) already called. Early failure\n"));
m_actionResult = CORDBG_E_PROCESS_TERMINATED;
SetEvent(m_actionTakenEvent);
return;
}
// We null m_pProcess at the end here, so
// Only way we could get here w/ null process is if we're called twice. We can only be called
// by detach or exit. Can't detach twice, can't exit twice, so must have been one of each.
// If exit is first, we got removed from the wait set, so 2nd call must be detach and we'd catch
// that above. If detach is first, we'd get removed from the wait set and so exit would never happen.
_ASSERTE(m_pProcess != NULL);
_ASSERTE(!m_pProcess->ThreadHoldsProcessLock());
// Mark the process teminated. After this, the RCET will never call FlushQueuedEvents. It will
// ignore all events it receives (including a SyncComplete) and the RCET also does not listen
// to terminated processes (so ProcessStateChange() won't cause a FQE either).
m_pProcess->Terminating(fDetach);
// Take care of the race where the process exits right after the user calls Continue() from the last
// managed event but before the handler has actually returned.
//
// Also, To get through this lock means that either:
// 1. FlushQueuedEvents is not currently executing and no one will call FQE.
// 2. FQE is exiting but is in the middle of a callback (so AreDispatchingEvent = true)
//
m_pProcess->Lock();
m_pProcess->m_exiting = true;
if (fDetach)
{
m_pProcess->SetSynchronized(false);
}
// If we are exiting, we *must* dispatch the ExitProcess callback, but we will delete all the events
// in the queue and not bother dispatching anything else. If (and only if) we are currently dispatching
// an event, then we will wait while that event is finished before invoking ExitProcess.
// (Note that a dispatched event has already been removed from the queue)
// Remove the process from the global list of processes.
m_cordb->RemoveProcess(m_pProcess);
if (fDetach)
{
// Signal the hr to the caller.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: Detach: send result back!\n"));
m_actionResult = S_OK;
SetEvent(m_actionTakenEvent);
}
m_pProcess->Unlock();
// Delete all queued events
m_pProcess->DeleteQueuedEvents();
// If we're detaching, then the Detach already neutered everybody, so nothing here.
// If we're exiting, then we still need to neuter things, but we can't do that on this thread,
// so we queue it. We also need to dispatch an exit process callback. We'll queue that onto the RCET
// and dispatch it inband w/the other callbacks.
if (!fDetach)
{
#ifdef TARGET_UNIX
// Cleanup the transport pipe and semaphore files that might be left by the target (LS) process.
m_pNativePipeline->CleanupTargetProcess();
#endif
ExitProcessWorkItem * pItem = new (nothrow) ExitProcessWorkItem(m_pProcess);
if (pItem != NULL)
{
m_cordb->m_rcEventThread->QueueAsyncWorkItem(pItem);
}
}
// This will remove the process from our wait lists (so that we don't send multiple ExitProcess events).
m_pProcess.Clear();
}
//
// Start actually creates and starts the thread.
//
HRESULT CordbWin32EventThread::Start()
{
HRESULT hr = S_OK;
if (m_threadControlEvent == NULL)
return E_INVALIDARG;
// Create the thread suspended to make sure that m_threadId is set
// before CordbWin32EventThread::ThreadProc runs
// Stack size = 0x80000 = 512KB
m_thread = CreateThread(NULL, 0x80000, &CordbWin32EventThread::ThreadProc,
(LPVOID) this, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, &m_threadId);
if (m_thread == NULL)
return HRESULT_FROM_GetLastError();
DWORD succ = ResumeThread(m_thread);
if (succ == (DWORD)-1)
return HRESULT_FROM_GetLastError();
return hr;
}
//
// Stop causes the thread to stop receiving events and exit. It
// waits for it to exit before returning.
//
HRESULT CordbWin32EventThread::Stop()
{
HRESULT hr = S_OK;
// m_pProcess may be NULL from CordbWin32EventThread::ExitProcess
// Can't block on W32ET while holding the process-lock since the W32ET may need that to exit.
// But since m_pProcess may be null, we can't enforce that.
if (m_thread != NULL)
{
LockSendToWin32EventThreadMutex();
m_action = W32ETA_NONE;
m_run = FALSE;
SetEvent(m_threadControlEvent);
UnlockSendToWin32EventThreadMutex();
DWORD ret = WaitForSingleObject(m_thread, INFINITE);
if (ret != WAIT_OBJECT_0)
hr = HRESULT_FROM_GetLastError();
}
m_pProcess.Clear();
m_cordb.Clear();
return hr;
}
// Allocate a buffer of cbBuffer bytes in the target.
//
// Arguments:
// cbBuffer - count of bytes for the buffer.
//
// Returns:
// a TargetBuffer describing the new memory region in the target.
// Throws on error.
TargetBuffer CordbProcess::GetRemoteBuffer(ULONG cbBuffer)
{
INTERNAL_SYNC_API_ENTRY(this); //
// Create and initialize the event as synchronous
DebuggerIPCEvent event;
InitIPCEvent(&event,
DB_IPCE_GET_BUFFER,
true,
VMPTR_AppDomain::NullPtr());
// Indicate the buffer size wanted
event.GetBuffer.bufSize = cbBuffer;
// Make the request, which is synchronous
HRESULT hr = SendIPCEvent(&event, sizeof(event));
IfFailThrow(hr);
_ASSERTE(event.type == DB_IPCE_GET_BUFFER_RESULT);
IfFailThrow(event.GetBufferResult.hr);
// The request succeeded. Return the newly allocated range.
return TargetBuffer(event.GetBufferResult.pBuffer, cbBuffer);
}
/*
* This will release a previously allocated left side buffer.
*/
HRESULT CordbProcess::ReleaseRemoteBuffer(void **ppBuffer)
{
INTERNAL_SYNC_API_ENTRY(this); //
_ASSERTE(m_pShim != NULL);
// Create and initialize the event as synchronous
DebuggerIPCEvent event;
InitIPCEvent(&event,
DB_IPCE_RELEASE_BUFFER,
true,
VMPTR_AppDomain::NullPtr());
// Indicate the buffer to release
event.ReleaseBuffer.pBuffer = (*ppBuffer);
// Make the request, which is synchronous
HRESULT hr = SendIPCEvent(&event, sizeof(event));
TESTANDRETURNHR(hr);
(*ppBuffer) = NULL;
// Indicate success
return event.ReleaseBufferResult.hr;
}
HRESULT CordbProcess::SetDesiredNGENCompilerFlags(DWORD dwFlags)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return CORDBG_E_NGEN_NOT_SUPPORTED;
}
HRESULT CordbProcess::GetDesiredNGENCompilerFlags(DWORD *pdwFlags )
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pdwFlags, DWORD*);
*pdwFlags = 0;
CordbProcess *pProcess = GetProcess();
ATT_REQUIRE_STOPPED_MAY_FAIL(pProcess);
HRESULT hr = S_OK;
EX_TRY
{
hr = pProcess->GetDAC()->GetNGENCompilerFlags(pdwFlags);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//-----------------------------------------------------------------------------
// Get an ICorDebugReference Value for the GC handle.
// handle - raw bits for the GC handle.
// pOutHandle
//-----------------------------------------------------------------------------
HRESULT CordbProcess::GetReferenceValueFromGCHandle(
UINT_PTR gcHandle,
ICorDebugReferenceValue **pOutValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
VALIDATE_POINTER_TO_OBJECT(pOutValue, ICorDebugReferenceValue*);
*pOutValue = NULL;
HRESULT hr = S_OK;
EX_TRY
{
if (gcHandle == NULL)
{
ThrowHR(CORDBG_E_BAD_REFERENCE_VALUE);
}
IDacDbiInterface* pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetVmObjectHandle(gcHandle);
if(!pDAC->IsVmObjectHandleValid(vmObjHandle))
{
ThrowHR(CORDBG_E_BAD_REFERENCE_VALUE);
}
ULONG appDomainId = pDAC->GetAppDomainIdFromVmObjectHandle(vmObjHandle);
VMPTR_AppDomain vmAppDomain = pDAC->GetAppDomainFromId(appDomainId);
RSLockHolder lockHolder(GetProcessLock());
CordbAppDomain * pAppDomain = LookupOrCreateAppDomain(vmAppDomain);
lockHolder.Release();
// Now that we finally have the AppDomain, we can go ahead and get a ReferenceValue
// from the ObjectHandle.
hr = CordbReferenceValue::BuildFromGCHandle(pAppDomain, vmObjHandle, pOutValue);
_ASSERTE(SUCCEEDED(hr) == (*pOutValue != NULL));
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//-----------------------------------------------------------------------------
// Return count of outstanding GC handles held by CordbHandleValue objects
LONG CordbProcess::OutstandingHandles()
{
return m_cOutstandingHandles;
}
//-----------------------------------------------------------------------------
// Increment the outstanding handle count for code:CordbProces::OutstandingHandles
// This is the inverse of code:CordbProces::DecrementOutstandingHandles
void CordbProcess::IncrementOutstandingHandles()
{
_ASSERTE(ThreadHoldsProcessLock());
m_cOutstandingHandles++;
}
//-----------------------------------------------------------------------------
// Decrement the outstanding handle count for code:CordbProces::OutstandingHandles
// This is the inverse of code:CordbProces::IncrementOutstandingHandles
void CordbProcess::DecrementOutstandingHandles()
{
_ASSERTE(ThreadHoldsProcessLock());
m_cOutstandingHandles--;
}
/*
* IsReadyForDetach
*
* This method encapsulates all logic for deciding if it is ok for a debugger to
* detach from the process at this time.
*
* Parameters: None.
*
* Returns: S_OK if it is ok to detach, else a specific HRESULT describing why it
* is not ok to detach.
*
*/
HRESULT CordbProcess::IsReadyForDetach()
{
INTERNAL_API_ENTRY(this);
// Always safe to detach in V3 case.
if (m_pShim == NULL)
{
return S_OK;
}
// If not initialized yet, then there are no detach liabilities.
if (!m_initialized)
{
return S_OK;
}
RSLockHolder lockHolder(&this->m_processMutex);
//
// If there are any outstanding func-evals then fail the detach.
//
if (OutstandingEvalCount() != 0)
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_EVALS;
}
// V2 didn't check outstanding handles (code:CordbProcess::OutstandingHandles)
// because it could automatically clean those up on detach.
//
// If there are any outstanding steppers then fail the detach.
//
if (m_steppers.IsInitialized() && (m_steppers.GetCount() > 0))
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_STEPPERS;
}
//
// If there are any outstanding breakpoints then fail the detach.
//
HASHFIND foundAppDomain;
CordbAppDomain *pAppDomain = m_appDomains.FindFirst(&foundAppDomain);
while (pAppDomain != NULL)
{
if (pAppDomain->m_breakpoints.IsInitialized() && (pAppDomain->m_breakpoints.GetCount() > 0))
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_BREAKPOINTS;
}
// Check for any outstanding EnC modules.
HASHFIND foundModule;
CordbModule * pModule = pAppDomain->m_modules.FindFirst(&foundModule);
while (pModule != NULL)
{
if (pModule->m_EnCCount > 0)
{
return CORDBG_E_DETACH_FAILED_ON_ENC;
}
pModule = pAppDomain->m_modules.FindNext(&foundModule);
}
pAppDomain = m_appDomains.FindNext(&foundAppDomain);
}
return S_OK;
}
/*
* Look for any thread which was last seen in the specified AppDomain.
* The CordbAppDomain object is about to be neutered due to an AD Unload
* So the thread must no longer be considered to be in that domain.
* Note that this is a workaround due to the existance of the (possibly incorrect)
* cached AppDomain value. Ideally we would remove the cached value entirely
* and there would be no need for this.
*
* @dbgtodo: , appdomain: We should remove CordbThread::m_pAppDomain in the V3 architecture.
* If we need the thread's current domain, we should get it accurately with DAC.
*/
void CordbProcess::UpdateThreadsForAdUnload(CordbAppDomain * pAppDomain)
{
INTERNAL_API_ENTRY(this);
// If we're doing an AD unload then we should have already seen the ATTACH
// notification for the default domain.
//_ASSERTE( m_pDefaultAppDomain != NULL );
// @dbgtodo appdomain: fix Default domain invariants with DAC-izing Appdomain work.
RSLockHolder lockHolder(GetProcessLock());
CordbThread* t;
HASHFIND find;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (t = m_userThreads.FindFirst(&find);
t != NULL;
t = m_userThreads.FindNext(&find))
{
if( t->GetAppDomain() == pAppDomain )
{
// This thread cannot actually be in this AppDomain anymore (since it's being
// unloaded). Reset it to point to the default AppDomain
t->m_pAppDomain = m_pDefaultAppDomain;
}
}
}
// CordbProcess::LookupClass
// Looks up a previously constructed CordbClass instance without creating. May return NULL if the
// CordbClass instance doesn't exist.
// Argument: (in) vmDomainAssembly - pointer to the domain assembly for the module
// (in) mdTypeDef - metadata token for the class
// Return value: pointer to a previously created CordbClass instance or NULL in none exists
CordbClass * CordbProcess::LookupClass(ICorDebugAppDomain * pAppDomain, VMPTR_DomainAssembly vmDomainAssembly, mdTypeDef classToken)
{
_ASSERTE(ThreadHoldsProcessLock());
if (pAppDomain != NULL)
{
CordbModule * pModule = ((CordbAppDomain *)pAppDomain)->m_modules.GetBase(VmPtrToCookie(vmDomainAssembly));
if (pModule != NULL)
{
return pModule->LookupClass(classToken);
}
}
return NULL;
} // CordbProcess::LookupClass
//---------------------------------------------------------------------------------------
// Look for a specific module in the process.
//
// Arguments:
// vmDomainAssembly - non-null module to lookup
//
// Returns:
// a CordbModule object for the given cookie. Object may be from the cache, or created
// lazily.
// Never returns null. Throws on error.
//
// Notes:
// A VMPTR_DomainAssembly has appdomain affinity, but is ultimately scoped to a process.
// So if we get a raw VMPTR_DomainAssembly (eg, from the stackwalker or from some other
// lookup function), then we need to do a process wide lookup since we don't know which
// appdomain it's in. If you know the appdomain, you can use code:CordbAppDomain::LookupOrCreateModule.
//
CordbModule * CordbProcess::LookupOrCreateModule(VMPTR_DomainAssembly vmDomainAssembly)
{
INTERNAL_API_ENTRY(this);
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
_ASSERTE(!vmDomainAssembly.IsNull());
DomainAssemblyInfo data;
GetDAC()->GetDomainAssemblyData(vmDomainAssembly, &data); // throws
CordbAppDomain * pAppDomain = LookupOrCreateAppDomain(data.vmAppDomain);
return pAppDomain->LookupOrCreateModule(vmDomainAssembly);
}
//---------------------------------------------------------------------------------------
// Determine if the process has any in-band queued events which have not been dispatched
//
// Returns:
// TRUE iff there are undispatched IB events
//
#ifdef FEATURE_INTEROP_DEBUGGING
BOOL CordbProcess::HasUndispatchedNativeEvents()
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedEvent* pEvent = m_unmanagedEventQueue;
while(pEvent != NULL && pEvent->IsDispatched())
{
pEvent = pEvent->m_next;
}
return pEvent != NULL;
}
#endif
//---------------------------------------------------------------------------------------
// Determine if the process has any in-band queued events which have not been user continued
//
// Returns:
// TRUE iff there are user uncontinued IB events
//
#ifdef FEATURE_INTEROP_DEBUGGING
BOOL CordbProcess::HasUserUncontinuedNativeEvents()
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedEvent* pEvent = m_unmanagedEventQueue;
while(pEvent != NULL && pEvent->IsEventUserContinued())
{
pEvent = pEvent->m_next;
}
return pEvent != NULL;
}
#endif
//---------------------------------------------------------------------------------------
// Hijack the thread which had this event. If the thread is already hijacked this method
// has no effect.
//
// Arguments:
// pUnmanagedEvent - the debug event which requires us to hijack
//
// Returns:
// S_OK on success, failing HRESULT if the hijack could not be set up
//
#ifdef FEATURE_INTEROP_DEBUGGING
HRESULT CordbProcess::HijackIBEvent(CordbUnmanagedEvent * pUnmanagedEvent)
{
// Can't hijack after the event has already been continued hijacked
_ASSERTE(!pUnmanagedEvent->IsEventContinuedHijacked());
// Can only hijack IB events
_ASSERTE(pUnmanagedEvent->IsIBEvent());
// If we already hijacked the event then there is nothing left to do
if(pUnmanagedEvent->m_owner->IsFirstChanceHijacked() ||
pUnmanagedEvent->m_owner->IsGenericHijacked())
{
return S_OK;
}
ResetEvent(this->m_leftSideUnmanagedWaitEvent);
if (pUnmanagedEvent->m_currentDebugEvent.u.Exception.dwFirstChance)
{
HRESULT hr = pUnmanagedEvent->m_owner->SetupFirstChanceHijackForSync();
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return hr;
}
else // Second chance exceptions must be generic hijacked.
{
HRESULT hr = pUnmanagedEvent->m_owner->SetupGenericHijack(pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, &pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return hr;
}
}
#endif
// Sets a bitfield reflecting the managed debugging state at the time of
// the jit attach.
HRESULT CordbProcess::GetAttachStateFlags(CLR_DEBUGGING_PROCESS_FLAGS *pFlags)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
if(pFlags == NULL)
hr = E_POINTER;
else
*pFlags = GetDAC()->GetAttachStateFlags();
}
PUBLIC_API_END(hr);
return hr;
}
// Determine if this version of ICorDebug is compatibile with the ICorDebug in the specified major CLR version
bool CordbProcess::IsCompatibleWith(DWORD clrMajorVersion)
{
// The debugger versioning policy is that debuggers generally need to opt-in to supporting major new
// versions of the CLR. Often new versions of the CLR violate some invariant that previous debuggers assume
// (eg. hot/cold splitting in Whidbey, multiple CLRs in a process in CLR v4), and neither VS or the CLR
// teams generally want the support burden of forward compatibility.
//
// If this assert is firing for you, its probably because the major version
// number of the clr.dll has changed. This assert is here to remind you to do a bit of other
// work you may not have realized you needed to do so that our versioning works smoothly
// for debugging. You probably want to contact the CLR DST team if you are a
// non-debugger person hitting this. DON'T JUST DELETE THIS ASSERT!!!
//
// 1) You should ensure new versions of all ICorDebug users in DevDiv (VS Debugger, MDbg, etc.)
// are using a creation path that explicitly specifies that they support this new major
// version of the CLR.
// 2) You should file an issue to track blocking earlier debuggers from targetting this
// version of the CLR (i.e. update requiredVersion to the new CLR major
// version). To enable a smooth internal transition, this often isn't done until absolutely
// necessary (sometimes as late as Beta2).
// 3) You can consider updating the CLR_ID guid used by the shim to recognize a CLR, but only
// if it's important to completely hide newer CLRs from the shim. The expectation now
// is that we won't need to do this (i.e. we'd like VS to give a nice error message about
// needed a newer version of the debugger, rather than just acting as if a process has no CLR).
// 4) Update this assert so that it no longer fires for your new CLR version or any of
// the previous versions, but don't delete the assert...
// the next CLR version after yours will probably need the same reminder
_ASSERTE_MSG(clrMajorVersion <= 4,
"Found major CLR version greater than 4 in mscordbi.dll from CLRv4 - contact CLRDST");
// This knob lets us enable forward compatibility for internal scenarios, and also simulate new
// versions of the runtime for testing the failure user-experience in a version of the debugger
// before it is shipped.
// We don't want to risk customers getting this, so for RTM builds this must be CHK-only.
// To aid in internal transition, we may temporarily enable this in RET builds, but when
// doing so must file a bug to track making it CHK only again before RTM.
// For example, Dev10 Beta2 shipped with this knob, but it was made CHK-only at the start of RC.
// In theory we might have a point release someday where we break debugger compat, but
// it seems unlikely and since this knob is unsupported anyway we can always extend it
// then (support reading a string value, etc.). So for now we just map the number
// to the major CLR version number.
DWORD requiredVersion = 0;
#ifdef _DEBUG
requiredVersion = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_Debugging_RequiredVersion);
#endif
// If unset (the only supported configuration), then we require a debugger designed for CLRv4
// for desktop, where we do not allow forward compat.
// For SL, we allow forward compat. Right now, that means SLv2+ debugger requests can be
// honored for SLv4.
if (requiredVersion <= 0)
{
requiredVersion = 2;
}
// Compare the version we were created for against the minimum required
return (clrMajorVersion >= requiredVersion);
}
bool CordbProcess::IsThreadSuspendedOrHijacked(ICorDebugThread * pICorDebugThread)
{
// An RS lock can be held while this is called. Specifically,
// CordbThread::EnumerateChains may be on the stack, and it uses
// ATT_REQUIRE_STOPPED_MAY_FAIL, which holds the CordbProcess::m_StopGoLock lock for
// its entire duration. As a result, this needs to be considered a reentrant API. See
// comments above code:PrivateShimCallbackHolder for more info.
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(this);
CordbThread * pCordbThread = static_cast<CordbThread *> (pICorDebugThread);
return GetDAC()->IsThreadSuspendedOrHijacked(pCordbThread->m_vmThreadToken);
}
void CordbProcess::HandleControlCTrapResult(HRESULT result)
{
RSLockHolder ch(GetStopGoLock());
DebuggerIPCEvent eventControlCResult;
InitIPCEvent(&eventControlCResult,
DB_IPCE_CONTROL_C_EVENT_RESULT,
false,
VMPTR_AppDomain::NullPtr());
// Indicate whether the debugger has handled the event.
eventControlCResult.hr = result;
// Send the reply to the LS.
SendIPCEvent(&eventControlCResult, sizeof(eventControlCResult));
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// File: process.cpp
//
//
//*****************************************************************************
#include "stdafx.h"
#include "primitives.h"
#include "safewrap.h"
#include "check.h"
#ifndef SM_REMOTESESSION
#define SM_REMOTESESSION 0x1000
#endif
#include "corpriv.h"
#include "corexcep.h"
#include "../../dlls/mscorrc/resource.h"
#include <limits.h>
#include <sstring.h>
// @dbgtodo shim: process has some private hooks into the shim.
#include "shimpriv.h"
#include "metadataexports.h"
#include "readonlydatatargetfacade.h"
#include "metahost.h"
// Keep this around for retail debugging. It's very very useful because
// it's global state that we can always find, regardless of how many locals the compiler
// optimizes away ;)
struct RSDebuggingInfo;
extern RSDebuggingInfo * g_pRSDebuggingInfo;
//---------------------------------------------------------------------------------------
//
// OpenVirtualProcessImpl method called by the shim to get an ICorDebugProcess4 instance
//
// Arguments:
// clrInstanceId - target pointer identifying which CLR in the Target to debug.
// pDataTarget - data target abstraction.
// hDacModule - the handle of the appropriate DAC dll for this runtime
// riid - interface ID to query for.
// ppProcessOut - new object for target, interface ID matches riid.
// ppFlagsOut - currently only has 1 bit to indicate whether or not this runtime
// instance will send a managed event after attach
//
// Return Value:
// S_OK on success. Else failure
//
// Assumptions:
//
// Notes:
// The outgoing process object can be cleaned up by calling Detach (which
// will reset the Attach bit.)
// @dbgtodo attach-bit: need to determine fate of attach bit.
//
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcessImpl(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
CLR_DEBUGGING_VERSION * pMaxDebuggerSupportedVersion,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
HRESULT hr = S_OK;
RSExtSmartPtr<CordbProcess> pProcess;
PUBLIC_API_ENTRY(NULL);
EX_TRY
{
if ( (pDataTarget == NULL) || (clrInstanceId == 0) || (pMaxDebuggerSupportedVersion == NULL) ||
((pFlagsOut == NULL) && (ppInstance == NULL))
)
{
ThrowHR(E_INVALIDARG);
}
// We consider the top 8 bits of the struct version to be the only part that represents
// a breaking change. This gives us some freedom in the future to have the debugger
// opt into getting more data.
const WORD kMajorMask = 0xff00;
const WORD kMaxStructMajor = 0;
if ((pMaxDebuggerSupportedVersion->wStructVersion & kMajorMask) > kMaxStructMajor)
{
// Don't know how to interpret the version structure
ThrowHR(CORDBG_E_UNSUPPORTED_VERSION_STRUCT);
}
// This process object is intended to be used for the V3 pipeline, and so
// much of the process from V2 is not being used. For example,
// - there is no ShimProcess object
// - there is no w32et thread (all threads are effectively an event thread)
// - the stop state is 'live', which corresponds to CordbProcess not knowing what
// its stop state really is (because that is now controlled by the shim).
ProcessDescriptor pd = ProcessDescriptor::CreateUninitialized();
IfFailThrow(CordbProcess::OpenVirtualProcess(
clrInstanceId,
pDataTarget, // takes a reference
hDacModule,
NULL, // Cordb
&pd, // 0 for V3 cases (pShim == NULL).
NULL, // no Shim in V3 cases
&pProcess));
// CordbProcess::OpenVirtualProcess already did the external addref to pProcess.
// Since pProcess is a smart ptr, it will external release in this function.
// Living reference will be the one from the QI.
// get the managed debug event pending flag
if(pFlagsOut != NULL)
{
hr = pProcess->GetAttachStateFlags(pFlagsOut);
if(FAILED(hr))
{
ThrowHR(hr);
}
}
//
// Check to make sure the debugger supports debugging this version
// Note that it's important that we still store the flags (above) in this case
//
if (!CordbProcess::IsCompatibleWith(pMaxDebuggerSupportedVersion->wMajor))
{
// Not compatible - don't keep the process instance, and return this specific error-code
ThrowHR(CORDBG_E_UNSUPPORTED_FORWARD_COMPAT);
}
//
// Now Query for the requested interface
//
if(ppInstance != NULL)
{
IfFailThrow(pProcess->QueryInterface(riid, reinterpret_cast<void**> (ppInstance)));
}
// if you have to add code here that could fail make sure ppInstance gets released and NULL'ed at exit
}
EX_CATCH_HRESULT(hr);
if((FAILED(hr) || ppInstance == NULL) && pProcess != NULL)
{
// The process has a strong reference to itself which is only released by neutering it.
// Since we aren't handing out the ref then we need to clean it up
_ASSERTE(ppInstance == NULL || *ppInstance == NULL);
pProcess->Neuter();
}
return hr;
};
//---------------------------------------------------------------------------------------
//
// OpenVirtualProcessImpl2 method called by the dbgshim to get an ICorDebugProcess4 instance
//
// Arguments:
// clrInstanceId - target pointer identifying which CLR in the Target to debug.
// pDataTarget - data target abstraction.
// pDacModulePath - the module path of the appropriate DAC dll for this runtime
// riid - interface ID to query for.
// ppProcessOut - new object for target, interface ID matches riid.
// ppFlagsOut - currently only has 1 bit to indicate whether or not this runtime
// instance will send a managed event after attach
//
// Return Value:
// S_OK on success. Else failure
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcessImpl2(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
LPCWSTR pDacModulePath,
CLR_DEBUGGING_VERSION * pMaxDebuggerSupportedVersion,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
HMODULE hDac = LoadLibraryW(pDacModulePath);
if (hDac == NULL)
{
return HRESULT_FROM_WIN32(GetLastError());
}
return OpenVirtualProcessImpl(clrInstanceId, pDataTarget, hDac, pMaxDebuggerSupportedVersion, riid, ppInstance, pFlagsOut);
}
//---------------------------------------------------------------------------------------
// DEPRECATED - use OpenVirtualProcessImpl
// OpenVirtualProcess method used by the shim in CLR v4 Beta1
// We'd like a beta1 shim/VS to still be able to open dumps using a CLR v4 Beta2+ mscordbi.dll,
// so we'll leave this in place (at least until after Beta2 is in wide use).
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcess2(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
REFIID riid,
IUnknown ** ppInstance,
CLR_DEBUGGING_PROCESS_FLAGS* pFlagsOut)
{
CLR_DEBUGGING_VERSION maxVersion = {0};
maxVersion.wMajor = 4;
return OpenVirtualProcessImpl(clrInstanceId, pDataTarget, hDacModule, &maxVersion, riid, ppInstance, pFlagsOut);
}
//---------------------------------------------------------------------------------------
// DEPRECATED - use OpenVirtualProcessImpl
// Public OpenVirtualProcess method to get an ICorDebugProcess4 instance
// Used directly in CLR v4 pre Beta1 - can probably be safely removed now
//---------------------------------------------------------------------------------------
STDAPI DLLEXPORT OpenVirtualProcess(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
REFIID riid,
IUnknown ** ppInstance)
{
return OpenVirtualProcess2(clrInstanceId, pDataTarget, NULL, riid, ppInstance, NULL);
};
//-----------------------------------------------------------------------------
// Most Hresults to Unrecoverable error indicate an internal error
// in the Right-Side.
// However, a few are legal (eg, "could actually happen in a retail scenario and
// not indicate an issue in mscorbi"). Track that here.
//-----------------------------------------------------------------------------
bool IsLegalFatalError(HRESULT hr)
{
return
(hr == CORDBG_E_INCOMPATIBLE_PROTOCOL) ||
(hr == CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS) ||
(hr == CORDBG_E_UNCOMPATIBLE_PLATFORMS) ||
(hr == CORDBG_E_MISMATCHED_CORWKS_AND_DACWKS_DLLS) ||
// This should only happen in the case of a security attack on us.
(hr == E_ACCESSDENIED) ||
(hr == E_FAIL);
}
//-----------------------------------------------------------------------------
// Safe wait. Use this anytime we're waiting on:
// - an event signaled by the helper thread.
// - something signaled by a thread that holds the process lock.
// Note that we must preserve GetLastError() semantics.
//-----------------------------------------------------------------------------
inline DWORD SafeWaitForSingleObject(CordbProcess * p, HANDLE h, DWORD dwTimeout)
{
// Can't hold process lock while blocking
_ASSERTE(!p->ThreadHoldsProcessLock());
return ::WaitForSingleObject(h, dwTimeout);
}
#define CORDB_WAIT_TIMEOUT 360000 // milliseconds
//---------------------------------------------------------------------------------------
//
// Get the timeout value used in waits.
//
// Return Value:
// Number of milliseconds to waite or possible INFINITE (-1).
//
//
// Notes:
// Uses registry values for fine tuning.
//
// static
static inline DWORD CordbGetWaitTimeout()
{
#ifdef _DEBUG
// 0 = Wait forever
// 1 = Wait for CORDB_WAIT_TIMEOUT
// n = Wait for n milliseconds
static ConfigDWORD cordbWaitTimeout;
DWORD dwTimeoutVal = cordbWaitTimeout.val(CLRConfig::INTERNAL_DbgWaitTimeout);
if (dwTimeoutVal == 0)
return DWORD(-1);
else if (dwTimeoutVal != 1)
return dwTimeoutVal;
else
#endif
{
return CORDB_WAIT_TIMEOUT;
}
}
//----------------------------------------------------------------------------
// Implementation of IDacDbiInterface::IMetaDataLookup.
// lookup Internal Metadata Importer keyed by PEAssembly
// isILMetaDataForNGENImage is true iff the IMDInternalImport returned represents a pointer to
// metadata from an IL image when the module was an ngen'ed image.
IMDInternalImport * CordbProcess::LookupMetaData(VMPTR_PEAssembly vmPEAssembly, bool &isILMetaDataForNGENImage)
{
INTERNAL_DAC_CALLBACK(this);
HASHFIND hashFindAppDomain;
HASHFIND hashFindModule;
IMDInternalImport * pMDII = NULL;
isILMetaDataForNGENImage = false;
// Check to see if one of the cached modules has the metadata we need
// If not we will do a more exhaustive search below
for (CordbAppDomain * pAppDomain = m_appDomains.FindFirst(&hashFindAppDomain);
pAppDomain != NULL;
pAppDomain = m_appDomains.FindNext(&hashFindAppDomain))
{
for (CordbModule * pModule = pAppDomain->m_modules.FindFirst(&hashFindModule);
pModule != NULL;
pModule = pAppDomain->m_modules.FindNext(&hashFindModule))
{
if (pModule->GetPEFile() == vmPEAssembly)
{
pMDII = NULL;
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = pModule->GetInternalMD();
);
if(pMDII != NULL)
return pMDII;
}
}
}
// Cache didn't have it... time to search harder
PrepopulateAppDomainsOrThrow();
// There may be perf issues here. The DAC may make a lot of metadata requests, and so
// this may be an area for potential perf optimizations if we find things running slow.
// enumerate through all Modules
for (CordbAppDomain * pAppDomain = m_appDomains.FindFirst(&hashFindAppDomain);
pAppDomain != NULL;
pAppDomain = m_appDomains.FindNext(&hashFindAppDomain))
{
pAppDomain->PrepopulateModules();
for (CordbModule * pModule = pAppDomain->m_modules.FindFirst(&hashFindModule);
pModule != NULL;
pModule = pAppDomain->m_modules.FindNext(&hashFindModule))
{
if (pModule->GetPEFile() == vmPEAssembly)
{
pMDII = NULL;
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = pModule->GetInternalMD();
);
if ( pMDII == NULL)
{
// If we couldn't get metadata from the CordbModule, then we need to ask the
// debugger if it can find the metadata elsewhere.
// If this was live debugging, we should have just gotten the memory contents.
// Thus this code is for dump debugging, when you don't have the metadata in the dump.
pMDII = LookupMetaDataFromDebugger(vmPEAssembly, isILMetaDataForNGENImage, pModule);
}
return pMDII;
}
}
}
return NULL;
}
IMDInternalImport * CordbProcess::LookupMetaDataFromDebugger(
VMPTR_PEAssembly vmPEAssembly,
bool &isILMetaDataForNGENImage,
CordbModule * pModule)
{
DWORD dwImageTimeStamp = 0;
DWORD dwImageSize = 0;
bool isNGEN = false;
StringCopyHolder filePath;
IMDInternalImport * pMDII = NULL;
// First, see if the debugger can locate the exact metadata we want.
if (this->GetDAC()->GetMetaDataFileInfoFromPEFile(vmPEAssembly, dwImageTimeStamp, dwImageSize, isNGEN, &filePath))
{
_ASSERTE(filePath.IsSet());
// Since we track modules by their IL images, that presents a little bit of oddness here. The correct
// thing to do is preferentially load the NI content.
// We don't discriminate between timestamps & sizes becuase CLRv4 deterministic NGEN guarantees that the
// IL image and NGEN image have the same timestamp and size. Should that guarantee change, this code
// will be horribly broken.
// If we happen to have an NI file path, use it instead.
const WCHAR * pwszFilePath = pModule->GetNGenImagePath();
if (pwszFilePath)
{
// Force the issue, regardless of the older codepath's opinion.
isNGEN = true;
}
else
{
pwszFilePath = (WCHAR *)filePath;
}
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = LookupMetaDataFromDebuggerForSingleFile(pModule, pwszFilePath, dwImageTimeStamp, dwImageSize);
);
// If it's an ngen'ed image and the debugger couldn't find it, we can use the metadata from
// the corresponding IL image if the debugger can locate it.
filePath.Clear();
if ((pMDII == NULL) &&
(isNGEN) &&
(this->GetDAC()->GetILImageInfoFromNgenPEFile(vmPEAssembly, dwImageTimeStamp, dwImageSize, &filePath)))
{
_ASSERTE(filePath.IsSet());
WCHAR *mutableFilePath = (WCHAR *)filePath;
size_t pathLen = wcslen(mutableFilePath);
const WCHAR *nidll = W(".ni.dll");
const WCHAR *niexe = W(".ni.exe");
const size_t dllLen = wcslen(nidll); // used for ni.exe as well
if (pathLen > dllLen && _wcsicmp(mutableFilePath+pathLen-dllLen, nidll) == 0)
{
wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".dll"));
}
else if (pathLen > dllLen && _wcsicmp(mutableFilePath+pathLen-dllLen, niexe) == 0)
{
wcscpy_s(mutableFilePath+pathLen-dllLen, dllLen, W(".exe"));
}
ALLOW_DATATARGET_MISSING_MEMORY(
pMDII = LookupMetaDataFromDebuggerForSingleFile(pModule, mutableFilePath, dwImageTimeStamp, dwImageSize);
);
if (pMDII != NULL)
{
isILMetaDataForNGENImage = true;
}
}
}
return pMDII;
}
// We do not know if the image being sent to us is an IL image or ngen image.
// CordbProcess::LookupMetaDataFromDebugger() has this knowledge when it looks up the file to hand off
// to this function.
// DacDbiInterfaceImpl::GetMDImport() has this knowledge in the isNGEN flag.
// The CLR v2 code that windbg used made a distinction whether the metadata came from
// the exact binary or not (i.e. were we getting metadata from the IL image and using
// it against the ngen image?) but that information was never used and so not brought forward.
// It would probably be more interesting generally to track whether the debugger gives us back
// a file that bears some relationship to the file we asked for, which would catch the NI/IL case
// as well.
IMDInternalImport * CordbProcess::LookupMetaDataFromDebuggerForSingleFile(
CordbModule * pModule,
LPCWSTR pwszFilePath,
DWORD dwTimeStamp,
DWORD dwSize)
{
INTERNAL_DAC_CALLBACK(this);
ULONG32 cchLocalImagePath = MAX_LONGPATH;
ULONG32 cchLocalImagePathRequired;
NewArrayHolder<WCHAR> pwszLocalFilePath = NULL;
IMDInternalImport * pMDII = NULL;
const HRESULT E_NSF_BUFFER = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
HRESULT hr = E_NSF_BUFFER;
for(unsigned i=0; i<2 && hr == E_NSF_BUFFER; i++)
{
if (pwszLocalFilePath != NULL)
pwszLocalFilePath.Release();
if (NULL == (pwszLocalFilePath = new (nothrow) WCHAR[cchLocalImagePath+1]))
ThrowHR(E_OUTOFMEMORY);
cchLocalImagePathRequired = 0;
hr = m_pMetaDataLocator->GetMetaData(pwszFilePath,
dwTimeStamp,
dwSize,
cchLocalImagePath,
&cchLocalImagePathRequired,
pwszLocalFilePath);
pwszLocalFilePath[cchLocalImagePath] = W('\0');
cchLocalImagePath = cchLocalImagePathRequired;
}
if (SUCCEEDED(hr))
{
hr = pModule->InitPublicMetaDataFromFile(pwszLocalFilePath, ofReadOnly, false);
if (SUCCEEDED(hr))
{
// While we're successfully returning a metadata reader, remember that there's
// absolutely no guarantee this metadata is an exact match for the vmPEAssembly.
// The debugger could literally send us back a path to any managed file with
// metadata content that is readable and we'll 'succeed'.
// For now, this is by-design. A debugger should be allowed to decide if it wants
// to take a risk by returning 'mostly matching' metadata to see if debugging is
// possible in the absence of a true match.
pMDII = pModule->GetInternalMD();
}
}
return pMDII;
}
//---------------------------------------------------------------------------------------
//
// Implement IDacDbiInterface::IAllocator::Alloc
// Expected to throws on error.
//
// Arguments:
// lenBytes - size of the byte array to allocate
//
// Return Value:
// Return the newly allocated byte array, or throw on OOM
//
// Notes:
// Since this function is a callback from DAC, it must not take the process lock.
// If it does, we may deadlock between the DD lock and the process lock.
// If we really need to take the process lock for whatever reason, we must take it in the DBI functions
// which call the DAC API that ends up calling this function.
// See code:InternalDacCallbackHolder for more information.
//
void * CordbProcess::Alloc(SIZE_T lenBytes)
{
return new BYTE[lenBytes]; // throws
}
//---------------------------------------------------------------------------------------
//
// Implements IDacDbiInterface::IAllocator::Free
//
// Arguments:
// p - pointer to the memory to be released
//
// Notes:
// Since this function is a callback from DAC, it must not take the process lock.
// If it does, we may deadlock between the DD lock and the process lock.
// If we really need to take the process lock for whatever reason, we must take it in the DBI functions
// which call the DAC API that ends up calling this function.
// See code:InternalDacCallbackHolder for more information.
//
void CordbProcess::Free(void * p)
{
// This shouldn't throw.
delete [] ((BYTE *) p);
}
//---------------------------------------------------------------------------------------
//
// #DBIVersionChecking
//
// There are a few checks we need to do to make sure we are using the matching DBI and DAC for a particular
// version of the runtime.
//
// 1. Runtime vs. DBI
// - Desktop
// This is done by making sure that the CorDebugInterfaceVersion passed to code:CreateCordbObject is
// compatible with the version of the DBI.
//
// - Windows CoreCLR
// This is done by dbgshim.dll. It checks whether the runtime DLL and the DBI DLL have the same
// product version. See CreateDebuggingInterfaceForVersion() in dbgshim.cpp.
//
// - Remote transport (Mac CoreCLR + CoreSystem CoreCLR)
// Since there is no dbgshim.dll for a remote CoreCLR, we have to do this check in some other place.
// We do this in code:CordbProcess::CreateDacDbiInterface, by calling
// code:DacDbiInterfaceImpl::CheckDbiVersion right after we have created the DDMarshal.
// The IDacDbiInterface implementation on remote device checks the product version of the device
// coreclr by:
// mac - looking at the Info.plist file in the CoreCLR bundle.
// CoreSystem - this check is skipped at the moment, but should be implemented if we release it
//
// The one twist here is that the DBI needs to communicate with the IDacDbiInterface
// implementation on the device BEFORE it can verify the product versions. This means that we need to
// have one IDacDbiInterface API which is consistent across all versions of the IDacDbiInterface.
// This puts two constraints on CheckDbiVersion():
//
// 1. It has to be the first API on the IDacDbiInterface.
// - Otherwise, a wrong version of the DBI may end up calling a different API on the
// IDacDbiInterface and getting random results. (Really what matters is that it is
// protocol message id 0, at present the source code position implies the message id)
//
// 2. Its parameters cannot change.
// - Otherwise, we may run into random errors when we marshal/unmarshal the arguments for the
// call to CheckDbiVersion(). Debugging will still fail, but we won't get the
// version mismatch error. (Again, the protocol is what ultimately matters)
// - To mitigate the impact of this constraint, we use the code:DbiVersion structure.
// In addition to the DBI version, it also contains a format number (in case we decide to
// check something else in the future), a breaking change number so that we can force
// breaking changes between a DBI and a DAC, and space reserved for future use.
//
// 2. DBI vs. DAC
// - Desktop and Windows CoreCLR (old architecture)
// No verification is done. There is a transitive implication that if DBI matches runtime and DAC matches
// runtime then DBI matches DAC. Technically because the DBI only matches runtime on major version number
// runtime and DAC could be from different builds. However because we service all three binaries together
// and DBI always loads the DAC that is sitting in the same directory DAC and DBI generally get tight
// version coupling. A user with admin privleges could put different builds together and no version check
// would ever fail though.
//
// - Desktop and Windows CoreCLR (new architecture)
// No verification is done. Similar to above its implied that if DBI matches runtime and runtime matches
// DAC then DBI matches DAC. The only difference is that here both the DBI and DAC are provided by the
// debugger. We provide timestamp and filesize for both binaries which are relatively strongly bound hints,
// but there is no enforcement on the returned binaries beyond the runtime compat checking.
//
// - Remote transport (Mac CoreCLR and CoreSystem CoreCLR)
// Because the transport exists between DBI and DAC it becomes much more important to do a versioning check
//
// Mac - currently does a tightly bound version check between DBI and the runtime (CheckDbiVersion() above),
// which transitively gives a tightly bound check to DAC. In same function there is also a check that is
// logically a DAC DBI protocol check, verifying that the m_dwProtocolBreakingChangeCounter of DbiVersion
// matches. However this check should be weaker than the build version check and doesn't add anything here.
//
// CoreSystem - currently skips the tightly bound version check to make internal deployment and usage easier.
// We want to use old desktop side debugger components to target newer CoreCLR builds, only forcing a desktop
// upgrade when the protocol actually does change. To do this we use two checks:
// 1. The breaking change counter in CheckDbiVersion() whenever a dev knows they are breaking back
// compat and wants to be explicit about it. This is the same as mac above.
// 2. During the auto-generation of the DDMarshal classes we take an MD5 hash of IDacDbiInterface source
// code and embed it in two DDMarshal functions, one which runs locally and one that runs remotely.
// If both DBI and DAC were built from the same source then the local and remote hashes will match. If the
// hashes don't match then we assume there has been a been a breaking change in the protocol. Note
// this hash could have both false-positives and false-negatives. False positives could occur when
// IDacDbiInterface is changed in a trivial way, such as changing a comment. False negatives could
// occur when the semantics of the protocol are changed even though the interface is not. Another
// case would be changing the DDMarshal proxy generation code. In addition to the hashes we also
// embed timestamps when the auto-generated code was produced. However this isn't used for version
// matching, only as a hint to indicate which of two mismatched versions is newer.
//
//
// 3. Runtime vs. DAC
// - Desktop, Windows CoreCLR, CoreSystem CoreCLR
// In both cases we check this by matching the timestamp in the debug directory of the runtime image
// and the timestamp we store in the DAC table when we generate the DAC dll. This is done in
// code:ClrDataAccess::VerifyDlls.
//
// - Mac CoreCLR
// On Mac, we don't have a timestamp in the runtime image. Instead, we rely on checking the 16-byte
// UUID in the image. This UUID is used to check whether a symbol file matches the image, so
// conceptually it's the same as the timestamp we use on Windows. This is also done in
// code:ClrDataAccess::VerifyDlls.
//
//---------------------------------------------------------------------------------------
//
// Instantiates a DacDbi Interface object in a live-debugging scenario that matches
// the current instance of mscorwks in this process.
//
// Return Value:
// Returns on success. Else throws.
//
// Assumptions:
// Client will code:CordbProcess::FreeDac when its done with the DacDbi interface.
// Caller has initialized clrInstanceId.
//
// Notes:
// This looks for the DAC next to this current DBI. This assumes that Dac and Dbi are both on
// the local file system. That assumption will break in zero-copy deployment scenarios.
//
//---------------------------------------------------------------------------------------
void
CordbProcess::CreateDacDbiInterface()
{
_ASSERTE(m_pDACDataTarget != NULL);
_ASSERTE(m_pDacPrimitives == NULL); // don't double-init
// Caller has already determined which CLR in the target is being debugged.
_ASSERTE(m_clrInstanceId != 0);
m_pDacPrimitives = NULL;
HRESULT hrStatus = S_OK;
// Non-marshalling path for live local dac.
// in the new arch we can get the module from OpenVirtualProcess2 but in the shim case
// and the deprecated OpenVirtualProcess case we must assume it comes from DAC in the
// same directory as DBI
if(m_hDacModule == NULL)
{
m_hDacModule.Assign(ShimProcess::GetDacModule());
}
//
// Get the access interface, passing our callback interfaces (data target, allocator and metadata lookup)
//
IDacDbiInterface::IAllocator * pAllocator = this;
IDacDbiInterface::IMetaDataLookup * pMetaDataLookup = this;
typedef HRESULT (STDAPICALLTYPE * PFN_DacDbiInterfaceInstance)(
ICorDebugDataTarget *,
CORDB_ADDRESS,
IDacDbiInterface::IAllocator *,
IDacDbiInterface::IMetaDataLookup *,
IDacDbiInterface **);
IDacDbiInterface* pInterfacePtr = NULL;
PFN_DacDbiInterfaceInstance pfnEntry = (PFN_DacDbiInterfaceInstance)GetProcAddress(m_hDacModule, "DacDbiInterfaceInstance");
if (!pfnEntry)
{
ThrowLastError();
}
hrStatus = pfnEntry(m_pDACDataTarget, m_clrInstanceId, pAllocator, pMetaDataLookup, &pInterfacePtr);
IfFailThrow(hrStatus);
// We now have a resource, pInterfacePtr, that needs to be freed.
m_pDacPrimitives = pInterfacePtr;
// Setup DAC target consistency checking based on what we're using for DBI
m_pDacPrimitives->DacSetTargetConsistencyChecks( m_fAssertOnTargetInconsistency );
}
//---------------------------------------------------------------------------------------
//
// Is the DAC/DBI interface initialized?
//
// Return Value:
// TRUE iff init.
//
// Notes:
// The RS will try to initialize DD as soon as it detects the runtime as loaded.
// If the DD interface has not initialized, then it very likely the runtime has not
// been loaded into the target.
//
BOOL CordbProcess::IsDacInitialized()
{
return m_pDacPrimitives != NULL;
}
//---------------------------------------------------------------------------------------
//
// Get the DAC interface.
//
// Return Value:
// the Dac/Dbi interface pointer to the process.
// Never returns NULL.
//
// Assumptions:
// Caller is responsible for ensuring Data-Target is safe to access (eg, not
// currently running).
// Caller is responsible for ensuring DAC-cache is flushed. Call code:CordbProcess::ForceDacFlush
// as needed.
//
//---------------------------------------------------------------------------------------
IDacDbiInterface * CordbProcess::GetDAC()
{
// Since the DD primitives may throw, easiest way to model that is to make this throw.
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// We should always have the DAC/DBI interface.
_ASSERTE(m_pDacPrimitives != NULL);
return m_pDacPrimitives;
}
//---------------------------------------------------------------------------------------
// Get the Data-Target
//
// Returns:
// pointer to the data-target. Should be non-null.
// Lifetime of the pointer is until this process object is neutered.
//
ICorDebugDataTarget * CordbProcess::GetDataTarget()
{
return m_pDACDataTarget;
}
//---------------------------------------------------------------------------------------
// Create a CordbProcess object around an existing OS process.
//
// Arguments:
// pDataTarget - abstracts access to the debuggee.
// clrInstanceId - identifies the CLR instance within the debuggee. (This is the
// base address of mscorwks)
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// This should go away - we can get the functionality from the pShim.
// If this is null, then pShim must be null too.
// processID - OS process ID of target process. 0 if pShim == NULL.
// pShim - shim counter part object. This allows hooks back for v2 compat. This will
// go away once we no longer support V2 backwards compat.
// This must be non-null for any V2 paths (including non-DAC-ized code).
// If this is null, then we're in a V3 path.
// ppProcess - out parameter for new process object. This gets addreffed.
//
// Return Value:
// S_OK on success, and *ppProcess set to newly created debuggee object. Else error.
//
// Notes:
// @dbgtodo - , shim: Cordb, and pShim will all eventually go away.
//
//---------------------------------------------------------------------------------------
// static
HRESULT CordbProcess::OpenVirtualProcess(
ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
Cordb* pCordb,
const ProcessDescriptor * pProcessDescriptor,
ShimProcess * pShim,
CordbProcess ** ppProcess)
{
_ASSERTE(pDataTarget != NULL);
// In DEBUG builds, verify that we do actually have an ICorDebugDataTarget (i.e. that
// someone hasn't messed up the COM interop marshalling, etc.).
#ifdef _DEBUG
{
IUnknown * pTempDt;
HRESULT hrQi = pDataTarget->QueryInterface(IID_ICorDebugDataTarget, (void**)&pTempDt);
_ASSERTE_MSG(SUCCEEDED(hrQi), "OpenVirtualProcess was passed something that isn't actually an ICorDebugDataTarget");
pTempDt->Release();
}
#endif
// If we're emulating V2, then both pCordb and pShim are non-NULL.
// If we're doing a real V3 path, then they're both NULL.
// Either way, they should have the same null-status.
_ASSERTE((pCordb == NULL) == (pShim == NULL));
// If we're doing real V3, then we must have a real instance ID
_ASSERTE(!((pShim == NULL) && (clrInstanceId == 0)));
*ppProcess = NULL;
HRESULT hr = S_OK;
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
pProcess.Assign(new (nothrow) CordbProcess(clrInstanceId, pDataTarget, hDacModule, pCordb, pProcessDescriptor, pShim));
if (pProcess == NULL)
{
return E_OUTOFMEMORY;
}
ICorDebugProcess * pThis = pProcess;
(void)pThis; //prevent "unused variable" error from GCC
// CordbProcess::Init may need shim hooks, so connect Shim now.
// This will bump reference count.
if (pShim != NULL)
{
pShim->SetProcess(pProcess);
_ASSERTE(pShim->GetProcess() == pThis);
_ASSERTE(pShim->GetWin32EventThread() != NULL);
}
hr = pProcess->Init();
if (SUCCEEDED(hr))
{
*ppProcess = pProcess;
pProcess->ExternalAddRef();
}
else
{
// handle failure path
pProcess->CleanupHalfBakedLeftSide();
if (pShim != NULL)
{
// Shim still needs to be disposed to clean up other resources.
pShim->SetProcess(NULL);
}
// In failure case, pProcess's dtor will do the final release.
}
return hr;
}
//---------------------------------------------------------------------------------------
// CordbProcess constructor
//
// Arguments:
// pDataTarget - Pointer to an implementation of ICorDebugDataTarget
// (or ICorDebugMutableDataTarget), which virtualizes access to the process.
// clrInstanceId - representation of the CLR to debug in the process. Must be specified
// (non-zero) if pShim is NULL. If 0, use the first CLR that we see.
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// pW32 - Pointer to the Win32 event thread to use when processing events for this
// process.
// dwProcessID - For V3, 0.
// Else for shim codepaths, the processID of the process this object will represent.
// pShim - Pointer to the shim for handling V2 debuggers on the V3 architecture.
//
//---------------------------------------------------------------------------------------
CordbProcess::CordbProcess(ULONG64 clrInstanceId,
IUnknown * pDataTarget,
HMODULE hDacModule,
Cordb * pCordb,
const ProcessDescriptor * pProcessDescriptor,
ShimProcess * pShim)
: CordbBase(NULL, pProcessDescriptor->m_Pid, enumCordbProcess),
m_fDoDelayedManagedAttached(false),
m_cordb(pCordb),
m_handle(NULL),
m_processDescriptor(*pProcessDescriptor),
m_detached(false),
m_uninitializedStop(false),
m_exiting(false),
m_terminated(false),
m_unrecoverableError(false),
m_specialDeferment(false),
m_helperThreadDead(false),
m_loaderBPReceived(false),
m_cOutstandingEvals(0),
m_cOutstandingHandles(0),
m_clrInstanceId(clrInstanceId),
m_stopCount(0),
m_synchronized(false),
m_syncCompleteReceived(false),
m_pShim(pShim),
m_userThreads(11),
m_oddSync(false),
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads(11),
#endif
m_appDomains(11),
m_sharedAppDomain(0),
m_steppers(11),
m_continueCounter(1),
m_flushCounter(0),
m_leftSideEventAvailable(NULL),
m_leftSideEventRead(NULL),
#if defined(FEATURE_INTEROP_DEBUGGING)
m_leftSideUnmanagedWaitEvent(NULL),
#endif // FEATURE_INTEROP_DEBUGGING
m_initialized(false),
m_stopRequested(false),
m_stopWaitEvent(NULL),
#ifdef FEATURE_INTEROP_DEBUGGING
m_cFirstChanceHijackedThreads(0),
m_unmanagedEventQueue(NULL),
m_lastQueuedUnmanagedEvent(NULL),
m_lastQueuedOOBEvent(NULL),
m_outOfBandEventQueue(NULL),
m_lastDispatchedIBEvent(NULL),
m_dispatchingUnmanagedEvent(false),
m_dispatchingOOBEvent(false),
m_doRealContinueAfterOOBBlock(false),
m_state(0),
#endif // FEATURE_INTEROP_DEBUGGING
m_helperThreadId(0),
m_pPatchTable(NULL),
m_cPatch(0),
m_rgData(NULL),
m_rgNextPatch(NULL),
m_rgUncommitedOpcode(NULL),
m_minPatchAddr(MAX_ADDRESS),
m_maxPatchAddr(MIN_ADDRESS),
m_iFirstPatch(0),
m_hHelperThread(NULL),
m_dispatchedEvent(DB_IPCE_DEBUGGER_INVALID),
m_pDefaultAppDomain(NULL),
m_hDacModule(hDacModule),
m_pDacPrimitives(NULL),
m_pEventChannel(NULL),
m_fAssertOnTargetInconsistency(false),
m_runtimeOffsetsInitialized(false),
m_writableMetadataUpdateMode(LegacyCompatPolicy)
{
_ASSERTE((m_id == 0) == (pShim == NULL));
HRESULT hr = pDataTarget->QueryInterface(IID_ICorDebugDataTarget, reinterpret_cast<void **>(&m_pDACDataTarget));
IfFailThrow(hr);
#ifdef FEATURE_INTEROP_DEBUGGING
m_DbgSupport.m_DebugEventQueueIdx = 0;
m_DbgSupport.m_TotalNativeEvents = 0;
m_DbgSupport.m_TotalIB = 0;
m_DbgSupport.m_TotalOOB = 0;
m_DbgSupport.m_TotalCLR = 0;
#endif // FEATURE_INTEROP_DEBUGGING
g_pRSDebuggingInfo->m_MRUprocess = this;
// This is a strong reference to ourselves.
// This is cleared in code:CordbProcess::Neuter
m_pProcess.Assign(this);
#ifdef _DEBUG
// On Debug builds, we'll ASSERT by default whenever the target appears to be corrupt or
// otherwise inconsistent (both in DAC and DBI). But we also need the ability to
// explicitly test corrupt targets.
// Tests should set COMPlus_DbgIgnoreInconsistentTarget=1 to suppress these asserts
// Note that this controls two things:
// 1) DAC behavior - see code:IDacDbiInterface::DacSetTargetConsistencyChecks
// 2) RS-only consistency asserts - see code:CordbProcess::TargetConsistencyCheck
if( !CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgDisableTargetConsistencyAsserts) )
{
m_fAssertOnTargetInconsistency = true;
}
#endif
}
/*
A list of which resources owned by this object are accounted for.
UNKNOWN
Cordb* m_cordb;
CordbHashTable m_unmanagedThreads; // Released in CordbProcess but not removed from hash
DebuggerIPCEvent* m_lastQueuedEvent;
// CordbUnmannagedEvent is a struct which is not derrived from CordbBase.
// It contains a CordbUnmannagedThread which may need to be released.
CordbUnmanagedEvent *m_unmanagedEventQueue;
CordbUnmanagedEvent *m_lastQueuedUnmanagedEvent;
CordbUnmanagedEvent *m_outOfBandEventQueue;
CordbUnmanagedEvent *m_lastQueuedOOBEvent;
BYTE* m_pPatchTable;
BYTE *m_rgData;
void *m_pbRemoteBuf;
RESOLVED
// Nutered
CordbHashTable m_userThreads;
CordbHashTable m_appDomains;
// Cleaned up in ExitProcess
DebuggerIPCEvent* m_queuedEventList;
CordbHashTable m_steppers; // Closed in ~CordbProcess
// Closed in CloseIPCEventHandles called from ~CordbProcess
HANDLE m_leftSideEventAvailable;
HANDLE m_leftSideEventRead;
// Closed in ~CordbProcess
HANDLE m_handle;
HANDLE m_leftSideUnmanagedWaitEvent;
HANDLE m_stopWaitEvent;
// Deleted in ~CordbProcess
CRITICAL_SECTION m_processMutex;
*/
CordbProcess::~CordbProcess()
{
LOG((LF_CORDB, LL_INFO1000, "CP::~CP: deleting process 0x%08x\n", this));
DTOR_ENTRY(this);
_ASSERTE(IsNeutered());
_ASSERTE(m_cordb == NULL);
// We shouldn't still be in Cordb's list of processes. Unfortunately, our root Cordb object
// may have already been deleted b/c we're at the mercy of ref-counting, so we can't check.
_ASSERTE(m_sharedAppDomain == NULL);
m_processMutex.Destroy();
m_StopGoLock.Destroy();
// These handles were cleared in neuter
_ASSERTE(m_handle == NULL);
#if defined(FEATURE_INTEROP_DEBUGGING)
_ASSERTE(m_leftSideUnmanagedWaitEvent == NULL);
#endif // FEATURE_INTEROP_DEBUGGING
_ASSERTE(m_stopWaitEvent == NULL);
// Set this to mark that we really did cleanup.
}
//-----------------------------------------------------------------------------
// Static build helper.
// This will create a process under the pCordb root, and add it to the list.
// We don't return the process - caller gets the pid and looks it up under
// the Cordb object.
//
// Arguments:
// pCordb - Pointer to the implementation of the owning Cordb object implementing the
// owning ICD interface.
// szProgramName - Name of the program to execute.
// szProgramArgs - Command line arguments for the process.
// lpProcessAttributes - OS-specific attributes for process creation.
// lpThreadAttributes - OS-specific attributes for thread creation.
// fInheritFlags - OS-specific flag for child process inheritance.
// dwCreationFlags - OS-specific creation flags.
// lpEnvironment - OS-specific environmental strings.
// szCurrentDirectory - OS-specific string for directory to run in.
// lpStartupInfo - OS-specific info on startup.
// lpProcessInformation - OS-specific process information buffer.
// corDebugFlags - What type of process to create, currently always managed.
//-----------------------------------------------------------------------------
HRESULT ShimProcess::CreateProcess(
Cordb * pCordb,
ICorDebugRemoteTarget * pRemoteTarget,
LPCWSTR szProgramName,
_In_z_ LPWSTR szProgramArgs,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL fInheritHandles,
DWORD dwCreationFlags,
PVOID lpEnvironment,
LPCWSTR szCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
CorDebugCreateProcessFlags corDebugFlags
)
{
_ASSERTE(pCordb != NULL);
#if defined(FEATURE_DBGIPC_TRANSPORT_DI)
// The transport cannot deal with creating a suspended process (it needs the debugger to start up and
// listen for connections).
_ASSERTE((dwCreationFlags & CREATE_SUSPENDED) == 0);
#endif // FEATURE_DBGIPC_TRANSPORT_DI
HRESULT hr = S_OK;
RSExtSmartPtr<ShimProcess> pShim;
EX_TRY
{
pShim.Assign(new ShimProcess());
// Indicate that this process was started under the debugger as opposed to attaching later.
pShim->m_attached = false;
hr = pShim->CreateAndStartWin32ET(pCordb);
IfFailThrow(hr);
// Call out to newly created Win32-event Thread to create the process.
// If this succeeds, new CordbProcess will add a ref to the ShimProcess
hr = pShim->GetWin32EventThread()->SendCreateProcessEvent(pShim->GetMachineInfo(),
szProgramName,
szProgramArgs,
lpProcessAttributes,
lpThreadAttributes,
fInheritHandles,
dwCreationFlags,
lpEnvironment,
szCurrentDirectory,
lpStartupInfo,
lpProcessInformation,
corDebugFlags);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
// If this succeeds, then process takes ownership of thread. Else we need to kill it.
if (FAILED(hr))
{
if (pShim != NULL)
{
pShim->Dispose();
}
}
// Always release our ref to ShimProcess. If the Process was created, then it takes a reference.
return hr;
}
//-----------------------------------------------------------------------------
// Static build helper for the attach case.
// On success, this will add the process to the pCordb list, and then
// callers can look it up there by pid.
//
// Arguments:
// pCordb - root under which this all lives
// dwProcessID - OS process ID to attach to
// fWin32Attach - are we interop debugging?
//-----------------------------------------------------------------------------
HRESULT ShimProcess::DebugActiveProcess(
Cordb * pCordb,
ICorDebugRemoteTarget * pRemoteTarget,
const ProcessDescriptor * pProcessDescriptor,
BOOL fWin32Attach
)
{
_ASSERTE(pCordb != NULL);
HRESULT hr = S_OK;
RSExtSmartPtr<ShimProcess> pShim;
EX_TRY
{
pShim.Assign(new ShimProcess());
// Indicate that this process was attached to, asopposed to being started under the debugger.
pShim->m_attached = true;
hr = pShim->CreateAndStartWin32ET(pCordb);
IfFailThrow(hr);
// If this succeeds, new CordbProcess will add a ref to the ShimProcess
hr = pShim->GetWin32EventThread()->SendDebugActiveProcessEvent(pShim->GetMachineInfo(),
pProcessDescriptor,
fWin32Attach == TRUE,
NULL);
IfFailThrow(hr);
_ASSERTE(SUCCEEDED(hr));
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
// Don't do this when we are remote debugging since we won't be getting the loader breakpoint.
// We don't support JIT attach in remote debugging scenarios anyway.
//
// When doing jit attach for pure managed debugging we allow the native attach event to be signaled
// after DebugActiveProcess completes which means we must wait here long enough to have set the debuggee
// bit indicating managed attach is coming.
// However in interop debugging we can't do that because there are debug events which come before the
// loader breakpoint (which is how far we need to get to set the debuggee bit). If we blocked
// DebugActiveProcess there then the debug events would be refering to an ICorDebugProcess that hasn't
// yet been returned to the caller of DebugActiveProcess. Instead, for interop debugging we force the
// native debugger to wait until it gets the loader breakpoint to set the event. Note we can't converge
// on that solution for the pure managed case because there is no loader breakpoint event. Hence pure
// managed and interop debugging each require their own solution
//
// See bugs Dev10 600873 and 595322 for examples of what happens if we wait in interop or don't wait
// in pure managed respectively
//
// Long term this should all go away because we won't need to set a managed attach pending bit because
// there shouldn't be any IPC events involved in managed attach. There might not even be a notion of
// being 'managed attached'
if(!pShim->m_fIsInteropDebugging)
{
DWORD dwHandles = 2;
HANDLE arrHandles[2];
arrHandles[0] = pShim->m_terminatingEvent;
arrHandles[1] = pShim->m_markAttachPendingEvent;
// Wait for the completion of marking pending attach bit or debugger detaching
WaitForMultipleObjectsEx(dwHandles, arrHandles, FALSE, INFINITE, FALSE);
}
#endif //!FEATURE_DBGIPC_TRANSPORT_DI
}
EX_CATCH_HRESULT(hr);
// If this succeeds, then process takes ownership of thread. Else we need to kill it.
if (FAILED(hr))
{
if (pShim!= NULL)
{
pShim->Dispose();
}
}
// Always release our ref to ShimProcess. If the Process was created, then it takes a reference.
return hr;
}
//-----------------------------------------------------------------------------
// Neuter all of all children, but not the actual process object.
//
// Assumptions:
// This clears Right-side state. Assumptions about left-side state are either:
// 1. We're in a shutdown scenario, where all left-side state is already
// freed.
// 2. Caller already verified there are no left-side resources (eg, by calling
// code:CordbProcess::IsReadyForDetach)
// 3. Caller did code:CordbProcess::NeuterLeftSideResources first
// to clean up left-side resources.
//
// Notes:
// This could be called multiple times (code:CordbProcess::FlushAll), so
// be sure to null out any potential dangling pointers. State may be rebuilt
// up after each time.
void CordbProcess::NeuterChildren()
{
_ASSERTE(GetProcessLock()->HasLock());
// Frees left-side resources. See assumptions above.
m_LeftSideResourceCleanupList.NeuterAndClear(this);
m_EvalTable.Clear();
// Sweep neuter lists.
m_ExitNeuterList.NeuterAndClear(this);
m_ContinueNeuterList.NeuterAndClear(this);
m_userThreads.NeuterAndClear(GetProcessLock());
m_pDefaultAppDomain = NULL;
// Frees per-appdomain left-side resources. See assumptions above.
m_appDomains.NeuterAndClear(GetProcessLock());
if (m_sharedAppDomain != NULL)
{
m_sharedAppDomain->Neuter();
m_sharedAppDomain->InternalRelease();
m_sharedAppDomain = NULL;
}
m_steppers.NeuterAndClear(GetProcessLock());
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads.NeuterAndClear(GetProcessLock());
#endif // FEATURE_INTEROP_DEBUGGING
// Explicitly keep the Win32EventThread alive so that we can use it in the window
// between NeuterChildren + Neuter.
}
//-----------------------------------------------------------------------------
// Neuter
//
// When the process dies, remove all the resources associated with this object.
//
// Notes:
// Once we neuter ourself, we can no longer send IPC events. So this is useful
// on detach. This will be called on FlushAll (which has Whidbey detach
// semantics)
//-----------------------------------------------------------------------------
void CordbProcess::Neuter()
{
// Process's Neuter is at the top of the neuter tree. So we take the process-lock
// here and then all child items (appdomains, modules, etc) will assert
// that they hold the lock.
_ASSERTE(!this->ThreadHoldsProcessLock());
// Take the process lock.
RSLockHolder lockHolder(GetProcessLock());
NeuterChildren();
// Release the metadata interfaces
m_pMetaDispenser.Clear();
if (m_hHelperThread != NULL)
{
CloseHandle(m_hHelperThread);
m_hHelperThread = NULL;
}
{
lockHolder.Release();
{
// We may still hold the Stop-Go lock.
// @dbgtodo - left-side resources / shutdown, shim: Currently
// the shim shutdown is too interwoven with CordbProcess to split
// it out from the locks. Must fully hoist the W32ET and make
// it safely outside the RS, and outside the protection of RS
// locks.
PUBLIC_API_UNSAFE_ENTRY_FOR_SHIM(this);
// Now that all of our children are neutered, it should be safe to kill the W32ET.
// Shutdown the shim, and this will also shutdown the W32ET.
// Do this outside of the process-lock so that we can shutdown the
// W23ET.
if (m_pShim != NULL)
{
m_pShim->Dispose();
m_pShim.Clear();
}
}
lockHolder.Acquire();
}
// Unload DAC, and then release our final data target references
FreeDac();
m_pDACDataTarget.Clear();
m_pMutableDataTarget.Clear();
m_pMetaDataLocator.Clear();
if (m_pEventChannel != NULL)
{
m_pEventChannel->Delete();
m_pEventChannel = NULL;
}
// Need process lock to clear the patch table
ClearPatchTable();
CordbProcess::CloseIPCHandles();
CordbBase::Neuter();
m_cordb.Clear();
// Need to release this reference to ourselves. Other leaf objects may still hold
// strong references back to this CordbProcess object.
_ASSERTE(m_pProcess == this);
m_pProcess.Clear();
}
// Wrapper to return metadata dispenser.
//
// Notes:
// Does not adjust reference count of dispenser.
// Dispenser is destroyed in code:CordbProcess::Neuter
// Dispenser is non-null.
IMetaDataDispenserEx * CordbProcess::GetDispenser()
{
_ASSERTE(m_pMetaDispenser != NULL);
return m_pMetaDispenser;
}
void CordbProcess::CloseIPCHandles()
{
INTERNAL_API_ENTRY(this);
// Close off Right Side's handles.
if (m_leftSideEventAvailable != NULL)
{
CloseHandle(m_leftSideEventAvailable);
m_leftSideEventAvailable = NULL;
}
if (m_leftSideEventRead != NULL)
{
CloseHandle(m_leftSideEventRead);
m_leftSideEventRead = NULL;
}
if (m_handle != NULL)
{
// @dbgtodo - We should probably add asserts to all calls to CloseHandles(), but this has been
// a particularly problematic spot in the past for Mac debugging.
BOOL fSuccess = CloseHandle(m_handle);
(void)fSuccess; //prevent "unused variable" error from GCC
_ASSERTE(fSuccess);
m_handle = NULL;
}
#if defined(FEATURE_INTEROP_DEBUGGING)
if (m_leftSideUnmanagedWaitEvent != NULL)
{
CloseHandle(m_leftSideUnmanagedWaitEvent);
m_leftSideUnmanagedWaitEvent = NULL;
}
#endif // FEATURE_INTEROP_DEBUGGING
if (m_stopWaitEvent != NULL)
{
CloseHandle(m_stopWaitEvent);
m_stopWaitEvent = NULL;
}
}
//-----------------------------------------------------------------------------
// Create new OS Thread for the Win32 Event Thread (the thread used in interop-debugging to sniff
// native debug events). This is 1:1 w/ a CordbProcess object.
// This will then be used to actuall create the CordbProcess object.
// The process object will then take ownership of the thread.
//
// Arguments:
// pCordb - the root object that the process lives under
//
// Return values:
// S_OK on success.
//-----------------------------------------------------------------------------
HRESULT ShimProcess::CreateAndStartWin32ET(Cordb * pCordb)
{
//
// Create the win32 event listening thread
//
CordbWin32EventThread * pWin32EventThread = new (nothrow) CordbWin32EventThread(pCordb, this);
HRESULT hr = S_OK;
if (pWin32EventThread != NULL)
{
hr = pWin32EventThread->Init();
if (SUCCEEDED(hr))
{
hr = pWin32EventThread->Start();
}
if (FAILED(hr))
{
delete pWin32EventThread;
pWin32EventThread = NULL;
}
}
else
{
hr = E_OUTOFMEMORY;
}
m_pWin32EventThread = pWin32EventThread;
return ErrWrapper(hr);
}
//---------------------------------------------------------------------------------------
//
// Try to initialize the DAC. Called in scenarios where it may fail.
//
// Return Value:
// TRUE - DAC is initialized.
// FALSE - Not initialized, but can try again later. Common case if
// target has not yet loaded the runtime.
// Throws exception - fatal.
//
// Assumptions:
// Target is stopped by OS, so we can safely inspect it without it moving on us.
//
// Notes:
// This can be called eagerly to sniff if the LS is initialized.
//
//---------------------------------------------------------------------------------------
BOOL CordbProcess::TryInitializeDac()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// Target is stopped by OS, so we can safely inspect it without it moving on us.
// We want to avoid exceptions in the normal case, so we do some pre-checks
// to detect failure without relying on exceptions.
// Can't initialize DAC until mscorwks is loaded. So that's a sanity test.
HRESULT hr = EnsureClrInstanceIdSet();
if (FAILED(hr))
{
return FALSE;
}
// By this point, we know which CLR in the target to debug. That means there is a CLR
// in the target, and it's safe to initialize DAC.
_ASSERTE(m_clrInstanceId != 0);
// Now expect it to succeed
InitializeDac();
return TRUE;
}
//---------------------------------------------------------------------------------------
//
// Load & Init DAC, expecting to succeed.
//
// Return Value:
// Throws on failure.
//
// Assumptions:
// Caller invokes this at a point where they can expect it to succeed.
// This is called early in the startup path because DAC is needed for accessing
// data in the target.
//
// Notes:
// This needs to succeed, and should always succeed (baring a bad installation)
// so we assert on failure paths.
// This may be called mutliple times.
//
//---------------------------------------------------------------------------------------
void CordbProcess::InitializeDac()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
// For Mac debugginger, m_hDacModule is not used, and it will always be NULL. To check whether DAC has
// been initialized, we need to check something else, namely m_pDacPrimitives.
if (m_pDacPrimitives == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "About to load DAC\n"));
CreateDacDbiInterface(); // throws
}
else
{
LOG((LF_CORDB, LL_INFO1000, "Dac already loaded, 0x%p\n", (HMODULE)m_hDacModule));
}
// Always flush dac.
ForceDacFlush();
}
//---------------------------------------------------------------------------------------
//
// Free DAC resources
//
// Notes:
// This should clean up state such that code:CordbProcess::InitializeDac could be called again.
//
//---------------------------------------------------------------------------------------
void CordbProcess::FreeDac()
{
CONTRACTL
{
NOTHROW; // backout code.
}
CONTRACTL_END;
if (m_pDacPrimitives != NULL)
{
m_pDacPrimitives->Destroy();
m_pDacPrimitives = NULL;
}
if (m_hDacModule != NULL)
{
LOG((LF_CORDB, LL_INFO1000, "Unloading DAC\n"));
m_hDacModule.Clear();
}
}
IEventChannel * CordbProcess::GetEventChannel()
{
_ASSERTE(m_pEventChannel != NULL);
return m_pEventChannel;
}
//---------------------------------------------------------------------------------------
// Mark that the process is being interop-debugged.
//
// Notes:
// @dbgtodo shim: this should eventually move into the shim or go away.
// It's only to support V2 legacy interop-debugging.
// Called after code:CordbProcess::Init if we want to enable interop debugging.
// This allows us to separate out Interop-debugging flags from the core initialization,
// and paves the way for us to eventually remove it.
//
// Since we're always on the naitve-pipeline, the Enabling interop debugging just changes
// how the native debug events are being handled. So this must be called after Init, but
// before any events are actually handled.
// This mus be calle on the win32 event thread to gaurantee that it's called before WFDE.
void CordbProcess::EnableInteropDebugging()
{
CONTRACTL
{
THROWS;
PRECONDITION(m_pShim != NULL);
}
CONTRACTL_END;
// Must be on W32ET to gaurantee that we're called after Init yet before WFDE (which
// are both called on the W32et).
_ASSERTE(IsWin32EventThread());
#ifdef FEATURE_INTEROP_DEBUGGING
m_state |= PS_WIN32_ATTACHED;
if (GetDCB() != NULL)
{
GetDCB()->m_rightSideIsWin32Debugger = true;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
}
// Tell the Shim we're interop-debugging.
m_pShim->SetIsInteropDebugging(true);
#else
ThrowHR(CORDBG_E_INTEROP_NOT_SUPPORTED);
#endif
}
//---------------------------------------------------------------------------------------
//
// Init -- create any objects that the process object needs to operate.
//
// Arguments:
//
// Return Value:
// S_OK on success
//
// Assumptions:
// Called on Win32 Event Thread, after OS debugging pipeline is established but
// before WaitForDebugEvent / ContinueDebugEvent. This means the target is stopped.
//
// Notes:
// To enable interop-debugging, call code:CordbProcess::EnableInteropDebugging
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::Init()
{
INTERNAL_API_ENTRY(this);
HRESULT hr = S_OK;
BOOL fIsLSStarted = FALSE; // see meaning below.
FAIL_IF_NEUTERED(this);
EX_TRY
{
m_processMutex.Init("Process Lock", RSLock::cLockReentrant, RSLock::LL_PROCESS_LOCK);
m_StopGoLock.Init("Stop-Go Lock", RSLock::cLockReentrant, RSLock::LL_STOP_GO_LOCK);
#ifdef _DEBUG
m_appDomains.DebugSetRSLock(GetProcessLock());
m_userThreads.DebugSetRSLock(GetProcessLock());
#ifdef FEATURE_INTEROP_DEBUGGING
m_unmanagedThreads.DebugSetRSLock(GetProcessLock());
#endif
m_steppers.DebugSetRSLock(GetProcessLock());
#endif
// See if the data target is mutable, and cache the mutable interface if it is
// We must initialize this before we try to use the data target to access the memory in the target process.
m_pMutableDataTarget.Clear(); // if we were called already, release
hr = m_pDACDataTarget->QueryInterface(IID_ICorDebugMutableDataTarget, (void**)&m_pMutableDataTarget);
if (!SUCCEEDED(hr))
{
// The data target doesn't support mutation. We'll fail any requests that require mutation.
m_pMutableDataTarget.Assign(new ReadOnlyDataTargetFacade());
}
m_pMetaDataLocator.Clear();
hr = m_pDACDataTarget->QueryInterface(IID_ICorDebugMetaDataLocator, reinterpret_cast<void **>(&m_pMetaDataLocator));
// Get the metadata dispenser.
hr = InternalCreateMetaDataDispenser(IID_IMetaDataDispenserEx, (void **)&m_pMetaDispenser);
// We statically link in the dispenser. We expect it to succeed, except for OOM, which
// debugger doesn't yet handle.
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
IfFailThrow(hr);
_ASSERTE(m_pMetaDispenser != NULL);
// In order to allow users to call the metadata reader from multiple threads we need to set
// a flag on the dispenser to create threadsafe readers. This is done best-effort but
// really shouldn't ever fail. See issue 696511.
VARIANT optionValue;
VariantInit(&optionValue);
V_VT(&optionValue) = VT_UI4;
V_UI4(&optionValue) = MDThreadSafetyOn;
m_pMetaDispenser->SetOption(MetaDataThreadSafetyOptions, &optionValue);
//
// Setup internal events.
// @dbgtodo shim: these events should eventually be in the shim.
//
// Managed debugging is built on the native-pipeline, and that will detect against double-attaches.
// @dbgtodo shim: In V2, LSEA + LSER were used by the LS's helper thread. Now with the V3 pipeline,
// that helper-thread uses native-debug events. The W32ET gets those events and then uses LSEA, LSER to
// signal existing RS infrastructure. Eventually get rid of LSEA, LSER completely.
//
m_leftSideEventAvailable = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_leftSideEventAvailable == NULL)
{
ThrowLastError();
}
m_leftSideEventRead = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_leftSideEventRead == NULL)
{
ThrowLastError();
}
m_stopWaitEvent = WszCreateEvent(NULL, TRUE, FALSE, NULL);
if (m_stopWaitEvent == NULL)
{
ThrowLastError();
}
if (m_pShim != NULL)
{
// Get a handle to the debuggee.
// This is not needed in the V3 pipeline because we don't assume we have a live, local, process.
m_handle = GetShim()->GetNativePipeline()->GetProcessHandle();
if (m_handle == NULL)
{
ThrowLastError();
}
}
// The LS startup goes through the following phases:
// 1) mscorwks not yet loaded (eg, any unmanaged app)
// 2) mscorwks loaded (DAC can now be used)
// 3) IPC Block created at OS level
// 4) IPC block data initialized (so we can read meainingful data from it)
// 5) LS marks that it's initialized (queryable by a DAC primitive) (may not be atomic)
// 6) LS fires a "Startup" exception (sniffed by WFDE).
//
// LS is currently stopped by OS debugging, so it's doesn't shift phases.
// From the RS's perspective:
// - after phase 5 is an attach
// - before phase 6 is a launch.
// This means there's an overlap: if we catch it at phase 5, we'll just get
// an extra Startup exception from phase 6, which is safe. This overlap is good
// because it means there's no bad window to do an attach in.
// fIsLSStarted means before phase 6 (eg, RS should expect a startup exception)
// Determines if the LS is started.
{
BOOL fReady = TryInitializeDac();
if (fReady)
{
// Invoke DAC primitive.
_ASSERTE(m_pDacPrimitives != NULL);
fIsLSStarted = m_pDacPrimitives->IsLeftSideInitialized();
}
else
{
_ASSERTE(m_pDacPrimitives == NULL);
// DAC is not yet loaded, so we're at least before phase 2, which is before phase 6.
// So leave fIsLSStarted = false. We'll get a startup exception later.
_ASSERTE(!fIsLSStarted);
}
}
if (fIsLSStarted)
{
// Left-side has started up. This is common for Attach cases when managed-code is already running.
if (m_pShim != NULL)
{
FinishInitializeIPCChannelWorker(); // throws
// At this point, the control block is complete and all four
// events are available and valid for the remote process.
// Request that the process object send an Attach IPC event.
// This is only used in an attach case.
// @dbgtodo sync: this flag can go away once the
// shim can use real sync APIs.
m_fDoDelayedManagedAttached = true;
}
else
{
// In the V3 pipeline case, if we have the DD-interface, then the runtime is loaded
// and we consider it initialized.
if (IsDacInitialized())
{
m_initialized = true;
}
}
}
else
{
// LS is not started yet. This would be common for "Launch" cases.
// We will get a Startup Exception notification when it does start.
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
CleanupHalfBakedLeftSide();
}
return hr;
}
COM_METHOD CordbProcess::CanCommitChanges(ULONG cSnapshots,
ICorDebugEditAndContinueSnapshot *pSnapshots[],
ICorDebugErrorInfoEnum **pError)
{
return E_NOTIMPL;
}
COM_METHOD CordbProcess::CommitChanges(ULONG cSnapshots,
ICorDebugEditAndContinueSnapshot *pSnapshots[],
ICorDebugErrorInfoEnum **pError)
{
return E_NOTIMPL;
}
//
// Terminating -- places the process into the terminated state. This should
// also get any blocking process functions unblocked so they'll return
// a failure code.
//
void CordbProcess::Terminating(BOOL fDetach)
{
INTERNAL_API_ENTRY(this);
LOG((LF_CORDB, LL_INFO1000,"CP::T: Terminating process 0x%x detach=%d\n", m_id, fDetach));
m_terminated = true;
m_cordb->ProcessStateChanged();
// Set events that may be blocking stuff.
// But don't set RSER unless we actually read the event. We don't block on RSER
// since that wait also checks the leftside's process handle.
SetEvent(m_leftSideEventRead);
SetEvent(m_leftSideEventAvailable);
SetEvent(m_stopWaitEvent);
if (m_pShim != NULL)
m_pShim->SetTerminatingEvent();
if (fDetach && (m_pEventChannel != NULL))
{
m_pEventChannel->Detach();
}
}
// Wrapper to give shim access to code:CordbProcess::QueueManagedAttachIfNeededWorker
void CordbProcess::QueueManagedAttachIfNeeded()
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
QueueManagedAttachIfNeededWorker();
}
//---------------------------------------------------------------------------------------
// Hook from Shim to request a managed attach IPC event
//
// Notes:
// Called by shim after the loader-breakpoint is handled.
// @dbgtodo sync: ths should go away once the shim can initiate
// a sync
void CordbProcess::QueueManagedAttachIfNeededWorker()
{
HRESULT hrQueue = S_OK;
// m_fDoDelayedManagedAttached ensures that we only send an Attach event if the LS is actually present.
if (m_fDoDelayedManagedAttached && GetShim()->GetAttached())
{
RSLockHolder lockHolder(&this->m_processMutex);
GetDAC()->MarkDebuggerAttachPending();
hrQueue = this->QueueManagedAttach();
}
if (m_pShim != NULL)
m_pShim->SetMarkAttachPendingEvent();
IfFailThrow(hrQueue);
}
//---------------------------------------------------------------------------------------
//
// QueueManagedAttach
//
// Send a managed attach. This is asynchronous and will return immediately.
//
// Return Value:
// S_OK on success
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::QueueManagedAttach()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_fDoDelayedManagedAttached);
m_fDoDelayedManagedAttached = false;
_ASSERTE(IsDacInitialized());
// We don't know what Queue it.
SendAttachProcessWorkItem * pItem = new (nothrow) SendAttachProcessWorkItem(this);
if (pItem == NULL)
{
return E_OUTOFMEMORY;
}
this->m_cordb->m_rcEventThread->QueueAsyncWorkItem(pItem);
return S_OK;
}
// However, we still want to synchronize.
// @dbgtodo sync: when we hoist attaching, we can send an DB_IPCE_ASYNC_BREAK event instead or Attach
// (for V2 semantics, we still need to synchronize the process)?
void SendAttachProcessWorkItem::Do()
{
HRESULT hr;
// This is being processed on the RCET, where it's safe to take the Stop-Go lock.
RSLockHolder ch(this->GetProcess()->GetStopGoLock());
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
// This just acts like an async-break, which will kick off things.
// This will not induce any faked attach events from the VM (like it did in V2).
// The Left-side will still slip foward allowing the async-break to happen, so
// we may get normal debug events in addition to the sync-complete.
//
// 1. In the common attach case, we should just get a sync-complete.
// 2. In Jit-attach cases, the LS is sending an event, and so we'll get that event and then the sync-complete.
GetProcess()->InitAsyncIPCEvent(event, DB_IPCE_ATTACHING, VMPTR_AppDomain::NullPtr());
// This should result in a sync-complete from the Left-side, which will be raised as an exception
// that the debugger passes into Filter and then internally goes through code:CordbProcess::TriageSyncComplete
// and that triggers code:CordbRCEventThread::FlushQueuedEvents to be called on the RCET.
// We already pre-queued a fake CreateProcess event.
// The left-side will also mark itself as attached in response to this event.
// We explicitly don't mark it as attached from the right-side because we want to let the left-side
// synchronize first (to stop all running threads) before marking the debugger as attached.
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::S: sending attach.\n", GetCurrentThreadId()));
hr = GetProcess()->SendIPCEvent(event, CorDBIPC_BUFFER_SIZE);
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::S: sent attach.\n", GetCurrentThreadId()));
}
//---------------------------------------------------------------------------------------
// Try to lookup a cached thread object
//
// Arguments:
// vmThread - vm identifier for thread.
//
// Returns:
// Thread object if cached; null if not yet cached.
//
// Notes:
// This does not create the thread object if it's not cached. Caching is unpredictable,
// and so this may appear to randomly return NULL.
// Callers should prefer code:CordbProcess::LookupOrCreateThread unless they expicitly
// want to check RS state.
CordbThread * CordbProcess::TryLookupThread(VMPTR_Thread vmThread)
{
return m_userThreads.GetBase(VmPtrToCookie(vmThread));
}
//---------------------------------------------------------------------------------------
// Lookup (or create) a CordbThread object by the given volatile OS id. Returns null if not a manged thread
//
// Arguments:
// dwThreadId - os thread id that a managed thread may be using.
//
// Returns:
// Thread instance if there is currently a managed thread scheduled to run on dwThreadId.
// NULL if this tid is not a valid Managed thread. (This is considered a common case)
// Throws on error.
//
// Notes:
// OS Thread ID is not fiber-safe, so this is a dangerous function to call.
// Avoid this as much as possible. Prefer using VMPTR_Thread and
// code:CordbProcess::LookupOrCreateThread instead of OS thread IDs.
// See code:CordbThread::GetID for details.
CordbThread * CordbProcess::TryLookupOrCreateThreadByVolatileOSId(DWORD dwThreadId)
{
PrepopulateThreadsOrThrow();
return TryLookupThreadByVolatileOSId(dwThreadId);
}
//---------------------------------------------------------------------------------------
// Lookup a cached CordbThread object by the tid. Returns null if not in the cache (which
// includes unmanged thread)
//
// Arguments:
// dwThreadId - os thread id that a managed thread may be using.
//
// Returns:
// Thread instance if there is currently a managed thread scheduled to run on dwThreadId.
// NULL if this tid is not a valid Managed thread. (This is considered a common case)
// Throws on error.
//
// Notes:
// Avoids this method:
// * OS Thread ID is not fiber-safe, so this is a dangerous function to call.
// * This is juts a Lookup, not LookupOrCreate, so it should only be used by methods
// that care about the RS state (instead of just LS state).
// Prefer using VMPTR_Thread and code:CordbProcess::LookupOrCreateThread
//
CordbThread * CordbProcess::TryLookupThreadByVolatileOSId(DWORD dwThreadId)
{
HASHFIND find;
for (CordbThread * pThread = m_userThreads.FindFirst(&find);
pThread != NULL;
pThread = m_userThreads.FindNext(&find))
{
_ASSERTE(pThread != NULL);
// Get the OS tid. This returns 0 if the thread is switched out.
DWORD dwThreadId2 = GetDAC()->TryGetVolatileOSThreadID(pThread->m_vmThreadToken);
if (dwThreadId2 == dwThreadId)
{
return pThread;
}
}
// This OS thread ID does not match any managed thread id.
return NULL;
}
//---------------------------------------------------------------------------------------
// Preferred CordbThread lookup routine.
//
// Arguments:
// vmThread - LS thread to lookup. Must be non-null.
//
// Returns:
// CordbThread instance for given vmThread. May return a previously cached
// instance or create a new instance. Never returns NULL.
// Throw on error.
CordbThread * CordbProcess::LookupOrCreateThread(VMPTR_Thread vmThread)
{
_ASSERTE(!vmThread.IsNull());
// Return if we have an existing instance.
CordbThread * pReturn = TryLookupThread(vmThread);
if (pReturn != NULL)
{
return pReturn;
}
RSInitHolder<CordbThread> pThread(new CordbThread(this, vmThread)); // throws
pReturn = pThread.TransferOwnershipToHash(&m_userThreads);
return pReturn;
}
HRESULT CordbProcess::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugProcess)
{
*pInterface = static_cast<ICorDebugProcess*>(this);
}
else if (id == IID_ICorDebugController)
{
*pInterface = static_cast<ICorDebugController*>(static_cast<ICorDebugProcess*>(this));
}
else if (id == IID_ICorDebugProcess2)
{
*pInterface = static_cast<ICorDebugProcess2*>(this);
}
else if (id == IID_ICorDebugProcess3)
{
*pInterface = static_cast<ICorDebugProcess3*>(this);
}
else if (id == IID_ICorDebugProcess4)
{
*pInterface = static_cast<ICorDebugProcess4*>(this);
}
else if (id == IID_ICorDebugProcess5)
{
*pInterface = static_cast<ICorDebugProcess5*>(this);
}
else if (id == IID_ICorDebugProcess7)
{
*pInterface = static_cast<ICorDebugProcess7*>(this);
}
else if (id == IID_ICorDebugProcess8)
{
*pInterface = static_cast<ICorDebugProcess8*>(this);
}
else if (id == IID_ICorDebugProcess11)
{
*pInterface = static_cast<ICorDebugProcess11*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugProcess*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
// Public implementation of ICorDebugProcess4::ProcessStateChanged
HRESULT CordbProcess::ProcessStateChanged(CorDebugStateChange eChange)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
switch(eChange)
{
case PROCESS_RUNNING:
FlushProcessRunning();
break;
case FLUSH_ALL:
FlushAll();
break;
default:
ThrowHR(E_INVALIDARG);
}
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHeap(ICorDebugHeapEnum **ppObjects)
{
if (!ppObjects)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
if (m_pDacPrimitives->AreGCStructuresValid())
{
CordbHeapEnum *pHeapEnum = new CordbHeapEnum(this);
GetContinueNeuterList()->Add(this, pHeapEnum);
hr = pHeapEnum->QueryInterface(__uuidof(ICorDebugHeapEnum), (void**)ppObjects);
}
else
{
hr = CORDBG_E_GC_STRUCTURES_INVALID;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetGCHeapInformation(COR_HEAPINFO *pHeapInfo)
{
if (!pHeapInfo)
return E_INVALIDARG;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
GetDAC()->GetGCHeapInformation(pHeapInfo);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHeapRegions(ICorDebugHeapSegmentEnum **ppRegions)
{
if (!ppRegions)
return E_INVALIDARG;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
DacDbiArrayList<COR_SEGMENT> segments;
hr = GetDAC()->GetHeapSegments(&segments);
if (SUCCEEDED(hr))
{
if (!segments.IsEmpty())
{
CordbHeapSegmentEnumerator *segEnum = new CordbHeapSegmentEnumerator(this, &segments[0], (DWORD)segments.Count());
GetContinueNeuterList()->Add(this, segEnum);
hr = segEnum->QueryInterface(__uuidof(ICorDebugHeapSegmentEnum), (void**)ppRegions);
}
else
{
hr = E_OUTOFMEMORY;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetObject(CORDB_ADDRESS addr, ICorDebugObjectValue **ppObject)
{
return this->GetObjectInternal(addr, nullptr, ppObject);
}
HRESULT CordbProcess::GetObjectInternal(CORDB_ADDRESS addr, CordbAppDomain* pAppDomainOverride, ICorDebugObjectValue **pObject)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
if (!m_pDacPrimitives->IsValidObject(addr))
{
hr = CORDBG_E_CORRUPT_OBJECT;
}
else if (pObject == NULL)
{
hr = E_INVALIDARG;
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
CordbAppDomain *cdbAppDomain = NULL;
CordbType *pType = NULL;
hr = GetTypeForObject(addr, pAppDomainOverride, &pType, &cdbAppDomain);
if (SUCCEEDED(hr))
{
_ASSERTE(pType != NULL);
_ASSERTE(cdbAppDomain != NULL);
DebuggerIPCE_ObjectData objData;
m_pDacPrimitives->GetBasicObjectInfo(addr, ELEMENT_TYPE_CLASS, cdbAppDomain->GetADToken(), &objData);
NewHolder<CordbObjectValue> pNewObjectValue(new CordbObjectValue(cdbAppDomain, pType, TargetBuffer(addr, (ULONG)objData.objSize), &objData));
hr = pNewObjectValue->Init();
if (SUCCEEDED(hr))
{
hr = pNewObjectValue->QueryInterface(__uuidof(ICorDebugObjectValue), (void**)pObject);
if (SUCCEEDED(hr))
pNewObjectValue.SuppressRelease();
}
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateGCReferences(BOOL enumerateWeakReferences, ICorDebugGCReferenceEnum **ppEnum)
{
if (!ppEnum)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
CordbRefEnum *pRefEnum = new CordbRefEnum(this, enumerateWeakReferences);
GetContinueNeuterList()->Add(this, pRefEnum);
hr = pRefEnum->QueryInterface(IID_ICorDebugGCReferenceEnum, (void**)ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnumerateHandles(CorGCReferenceType types, ICorDebugGCReferenceEnum **ppEnum)
{
if (!ppEnum)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
CordbRefEnum *pRefEnum = new CordbRefEnum(this, types);
GetContinueNeuterList()->Add(this, pRefEnum);
hr = pRefEnum->QueryInterface(IID_ICorDebugGCReferenceEnum, (void**)ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::EnableNGENPolicy(CorDebugNGENPolicy ePolicy)
{
return E_NOTIMPL;
}
HRESULT CordbProcess::GetTypeID(CORDB_ADDRESS obj, COR_TYPEID *pId)
{
if (pId == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
EX_TRY
{
hr = GetProcess()->GetDAC()->GetTypeID(obj, pId);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetTypeForTypeID(COR_TYPEID id, ICorDebugType **ppType)
{
if (ppType == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
RSLockHolder stopGoLock(this->GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
EX_TRY
{
DebuggerIPCE_ExpandedTypeData data;
GetDAC()->GetObjectExpandedTypeInfoFromID(AllBoxed, VMPTR_AppDomain::NullPtr(), id, &data);
CordbType *type = 0;
hr = CordbType::TypeDataToType(GetSharedAppDomain(), &data, &type);
if (SUCCEEDED(hr))
hr = type->QueryInterface(IID_ICorDebugType, (void**)ppType);
}
EX_CATCH_HRESULT(hr);
return hr;
}
COM_METHOD CordbProcess::GetArrayLayout(COR_TYPEID id, COR_ARRAY_LAYOUT *pLayout)
{
if (pLayout == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetArrayLayout(id, pLayout);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::GetTypeLayout(COR_TYPEID id, COR_TYPE_LAYOUT *pLayout)
{
if (pLayout == NULL)
return E_POINTER;
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetTypeLayout(id, pLayout);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::GetTypeFields(COR_TYPEID id, ULONG32 celt, COR_FIELD fields[], ULONG32 *pceltNeeded)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->GetObjectFields(id, celt, fields, pceltNeeded);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::SetWriteableMetadataUpdateMode(WriteableMetadataUpdateMode flags)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
if(flags != LegacyCompatPolicy &&
flags != AlwaysShowUpdates)
{
hr = E_INVALIDARG;
}
else if(m_pShim != NULL)
{
if(flags != LegacyCompatPolicy)
{
hr = CORDBG_E_UNSUPPORTED;
}
}
if(SUCCEEDED(hr))
{
m_writableMetadataUpdateMode = flags;
}
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::EnableExceptionCallbacksOutsideOfMyCode(BOOL enableExceptionsOutsideOfJMC)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
hr = GetProcess()->GetDAC()->SetSendExceptionsOutsideOfJMC(enableExceptionsOutsideOfJMC);
PUBLIC_API_END(hr);
return hr;
}
COM_METHOD CordbProcess::EnableGCNotificationEvents(BOOL fEnable)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
hr = this->m_pDacPrimitives->EnableGCNotificationEvents(fEnable);
}
PUBLIC_API_END(hr);
return hr;
}
//-----------------------------------------------------------
// ICorDebugProcess11
//-----------------------------------------------------------
COM_METHOD CordbProcess::EnumerateLoaderHeapMemoryRegions(ICorDebugMemoryRangeEnum **ppRanges)
{
VALIDATE_POINTER_TO_OBJECT(ppRanges, ICorDebugMemoryRangeEnum **);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
DacDbiArrayList<COR_MEMORY_RANGE> heapRanges;
hr = GetDAC()->GetLoaderHeapMemoryRanges(&heapRanges);
if (SUCCEEDED(hr))
{
RSInitHolder<CordbMemoryRangeEnumerator> heapSegmentEnumerator(
new CordbMemoryRangeEnumerator(this, &heapRanges[0], (DWORD)heapRanges.Count()));
GetContinueNeuterList()->Add(this, heapSegmentEnumerator);
heapSegmentEnumerator.TransferOwnershipExternal(ppRanges);
}
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbProcess::GetTypeForObject(CORDB_ADDRESS addr, CordbAppDomain* pAppDomainOverride, CordbType **ppType, CordbAppDomain **pAppDomain)
{
VMPTR_AppDomain appDomain;
VMPTR_Module mod;
VMPTR_DomainAssembly domainAssembly;
HRESULT hr = E_FAIL;
if (GetDAC()->GetAppDomainForObject(addr, &appDomain, &mod, &domainAssembly))
{
if (pAppDomainOverride)
{
appDomain = pAppDomainOverride->GetADToken();
}
CordbAppDomain *cdbAppDomain = appDomain.IsNull() ? GetSharedAppDomain() : LookupOrCreateAppDomain(appDomain);
_ASSERTE(cdbAppDomain);
DebuggerIPCE_ExpandedTypeData data;
GetDAC()->GetObjectExpandedTypeInfo(AllBoxed, appDomain, addr, &data);
CordbType *type = 0;
hr = CordbType::TypeDataToType(cdbAppDomain, &data, &type);
if (SUCCEEDED(hr))
{
*ppType = type;
if (pAppDomain)
*pAppDomain = cdbAppDomain;
}
}
return hr;
}
// ******************************************
// CordbRefEnum
// ******************************************
CordbRefEnum::CordbRefEnum(CordbProcess *proc, BOOL walkWeakRefs)
: CordbBase(proc, 0, enumCordbHeap), mRefHandle(0), mEnumStacksFQ(TRUE),
mHandleMask((UINT32)(walkWeakRefs ? CorHandleAll : CorHandleStrongOnly))
{
}
CordbRefEnum::CordbRefEnum(CordbProcess *proc, CorGCReferenceType types)
: CordbBase(proc, 0, enumCordbHeap), mRefHandle(0), mEnumStacksFQ(FALSE),
mHandleMask((UINT32)types)
{
}
void CordbRefEnum::Neuter()
{
EX_TRY
{
if (mRefHandle)
{
GetProcess()->GetDAC()->DeleteRefWalk(mRefHandle);
mRefHandle = 0;
}
}
EX_CATCH
{
_ASSERTE(!"Hit an error freeing a ref walk.");
}
EX_END_CATCH(SwallowAllExceptions)
CordbBase::Neuter();
}
HRESULT CordbRefEnum::QueryInterface(REFIID riid, void **ppInterface)
{
if (ppInterface == NULL)
return E_INVALIDARG;
if (riid == IID_ICorDebugGCReferenceEnum)
{
*ppInterface = static_cast<ICorDebugGCReferenceEnum*>(this);
}
else if (riid == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown*>(static_cast<ICorDebugGCReferenceEnum*>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbRefEnum::Skip(ULONG celt)
{
return E_NOTIMPL;
}
HRESULT CordbRefEnum::Reset()
{
PUBLIC_API_ENTRY(this);
HRESULT hr = S_OK;
EX_TRY
{
if (mRefHandle)
{
GetProcess()->GetDAC()->DeleteRefWalk(mRefHandle);
mRefHandle = 0;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbRefEnum::Clone(ICorDebugEnum **ppEnum)
{
return E_NOTIMPL;
}
HRESULT CordbRefEnum::GetCount(ULONG *pcelt)
{
return E_NOTIMPL;
}
//
HRESULT CordbRefEnum::Next(ULONG celt, COR_GC_REFERENCE refs[], ULONG *pceltFetched)
{
if (refs == NULL || pceltFetched == NULL)
return E_POINTER;
CordbProcess *process = GetProcess();
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(process);
RSLockHolder procLockHolder(process->GetProcessLock());
EX_TRY
{
if (!mRefHandle)
hr = process->GetDAC()->CreateRefWalk(&mRefHandle, mEnumStacksFQ, mEnumStacksFQ, mHandleMask);
if (SUCCEEDED(hr))
{
DacGcReference dacRefs[32];
ULONG toFetch = ARRAY_SIZE(dacRefs);
ULONG total = 0;
for (ULONG c = 0; SUCCEEDED(hr) && c < (celt/ARRAY_SIZE(dacRefs) + 1); ++c)
{
// Fetch 32 references at a time, the last time, only fetch the remainder (that is, if
// the user didn't fetch a multiple of 32).
if (c == celt/ARRAY_SIZE(dacRefs))
toFetch = celt % ARRAY_SIZE(dacRefs);
ULONG fetched = 0;
hr = process->GetDAC()->WalkRefs(mRefHandle, toFetch, dacRefs, &fetched);
if (SUCCEEDED(hr))
{
for (ULONG i = 0; i < fetched; ++i)
{
CordbAppDomain *pDomain = process->LookupOrCreateAppDomain(dacRefs[i].vmDomain);
ICorDebugAppDomain *pAppDomain;
ICorDebugValue *pOutObject = NULL;
if (dacRefs[i].pObject & 1)
{
dacRefs[i].pObject &= ~1;
ICorDebugObjectValue *pObjValue = NULL;
hr = process->GetObject(dacRefs[i].pObject, &pObjValue);
if (SUCCEEDED(hr))
{
hr = pObjValue->QueryInterface(IID_ICorDebugValue, (void**)&pOutObject);
pObjValue->Release();
}
}
else
{
ICorDebugReferenceValue *tmpValue = NULL;
IfFailThrow(CordbReferenceValue::BuildFromGCHandle(pDomain,
dacRefs[i].objHnd,
&tmpValue));
if (SUCCEEDED(hr))
{
hr = tmpValue->QueryInterface(IID_ICorDebugValue, (void**)&pOutObject);
tmpValue->Release();
}
}
if (SUCCEEDED(hr) && pDomain)
{
hr = pDomain->QueryInterface(IID_ICorDebugAppDomain, (void**)&pAppDomain);
}
if (FAILED(hr))
break;
refs[total].Domain = pAppDomain;
refs[total].Location = pOutObject;
refs[total].Type = (CorGCReferenceType)dacRefs[i].dwType;
refs[total].ExtraData = dacRefs[i].i64ExtraData;
total++;
}
}
}
*pceltFetched = total;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ******************************************
// CordbHeapEnum
// ******************************************
CordbHeapEnum::CordbHeapEnum(CordbProcess *proc)
: CordbBase(proc, 0, enumCordbHeap), mHeapHandle(0)
{
}
HRESULT CordbHeapEnum::QueryInterface(REFIID riid, void **ppInterface)
{
if (ppInterface == NULL)
return E_INVALIDARG;
if (riid == IID_ICorDebugHeapEnum)
{
*ppInterface = static_cast<ICorDebugHeapEnum*>(this);
}
else if (riid == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown*>(static_cast<ICorDebugHeapEnum*>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbHeapEnum::Skip(ULONG celt)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::Reset()
{
Clear();
return S_OK;
}
void CordbHeapEnum::Clear()
{
EX_TRY
{
if (mHeapHandle)
{
GetProcess()->GetDAC()->DeleteHeapWalk(mHeapHandle);
mHeapHandle = 0;
}
}
EX_CATCH
{
_ASSERTE(!"Hit an error freeing the heap walk.");
}
EX_END_CATCH(SwallowAllExceptions)
}
HRESULT CordbHeapEnum::Clone(ICorDebugEnum **ppEnum)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::GetCount(ULONG *pcelt)
{
return E_NOTIMPL;
}
HRESULT CordbHeapEnum::Next(ULONG celt, COR_HEAPOBJECT objects[], ULONG *pceltFetched)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
RSLockHolder stopGoLock(this->GetProcess()->GetStopGoLock());
RSLockHolder procLock(this->GetProcess()->GetProcessLock());
ULONG fetched = 0;
EX_TRY
{
if (mHeapHandle == 0)
{
hr = GetProcess()->GetDAC()->CreateHeapWalk(&mHeapHandle);
}
if (SUCCEEDED(hr))
{
hr = GetProcess()->GetDAC()->WalkHeap(mHeapHandle, celt, objects, &fetched);
_ASSERTE(fetched <= celt);
}
if (SUCCEEDED(hr))
{
// Return S_FALSE if we've reached the end of the enum.
if (fetched < celt)
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
// Set the fetched parameter to reflect the number of elements (if any)
// that were successfully saved to "objects"
if (pceltFetched)
*pceltFetched = fetched;
return hr;
}
//---------------------------------------------------------------------------------------
// Flush state for when the process starts running.
//
// Notes:
// Helper for code:CordbProcess::ProcessStateChanged.
// Since ICD Arrowhead does not own the eventing pipeline, it needs the debugger to
// notifying it of when the process is running again. This is like the counterpart
// to code:CordbProcess::Filter
void CordbProcess::FlushProcessRunning()
{
_ASSERTE(GetProcessLock()->HasLock());
// Update the continue counter.
m_continueCounter++;
// Safely dispose anything that should be neutered on continue.
MarkAllThreadsDirty();
ForceDacFlush();
}
//---------------------------------------------------------------------------------------
// Flush all cached state and bring us back to "cold startup"
//
// Notes:
// Helper for code:CordbProcess::ProcessStateChanged.
// This is used if the data-target changes underneath us in a way that is
// not consistent with the process running forward. For example, if for
// a time-travel debugger, the data-target may flow "backwards" in time.
//
void CordbProcess::FlushAll()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr;
_ASSERTE(GetProcessLock()->HasLock());
//
// First, determine if it's safe to Flush
//
hr = IsReadyForDetach();
IfFailThrow(hr);
// Check for outstanding CordbHandle values.
if (OutstandingHandles())
{
ThrowHR(CORDBG_E_DETACH_FAILED_OUTSTANDING_TARGET_RESOURCES);
}
// FlushAll is a superset of FlushProcessRunning.
// This will also ensure we clear the DAC cache.
FlushProcessRunning();
// If we detach before the CLR is loaded into the debuggee, then we can no-op a lot of work.
// We sure can't be sending IPC events to the LS before it exists.
NeuterChildren();
}
//---------------------------------------------------------------------------------------
//
// Detach the Debugger from the LS process.
//
//
// Return Value:
// S_OK on successful detach. Else errror.
//
// Assumptions:
// Target is stopped.
//
// Notes:
// Once we're detached, the LS can resume running and exit.
// So it's possible to get an ExitProcess callback in the middle of the Detach phase. If that happens,
// we must return CORDBG_E_PROCESS_TERMINATED and pretend that the exit happened before we tried to detach.
// Else if we detach successfully, return S_OK.
//
// @dbgtodo attach-bit: need to figure out semantics of Detach
// in V3, especially w.r.t to an attach bit.
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::Detach()
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if (IsInteropDebugging())
{
return CORDBG_E_INTEROP_NOT_SUPPORTED;
}
HRESULT hr = S_OK;
// A very important note: we require that the process is synchronized before doing a detach. This ensures
// that no events are on their way from the Left Side. We also require that the user has drained the
// managed event queue, but there is currently no way to really enforce that here.
// @todo- why can't we enforce that the managed event Q is drained?
ATT_REQUIRE_SYNCED_OR_NONINIT_MAY_FAIL(this);
hr = IsReadyForDetach();
if (FAILED(hr))
{
// Avoid neutering. Gives client a chance to fix detach issue and retry.
return hr;
}
// Since the detach may resume the LS and allow it to exit, which may invoke the EP callback
// which may destroy this process object, be sure to protect us w/ an extra AddRef/Release
RSSmartPtr<CordbProcess> pRef(this);
LOG((LF_CORDB, LL_INFO1000, "CP::Detach - beginning\n"));
if (m_pShim == NULL) // This API is moved off to the shim
{
// This is still invasive.
// Ignore failures. This will fail for a non-invasive target.
if (IsDacInitialized())
{
HRESULT hrIgnore = S_OK;
EX_TRY
{
GetDAC()->MarkDebuggerAttached(FALSE);
}
EX_CATCH_HRESULT(hrIgnore);
}
}
else
{
EX_TRY
{
DetachShim();
}
EX_CATCH_HRESULT(hr);
}
// Either way, neuter everything.
this->Neuter();
// Implicit release on pRef
LOG((LF_CORDB, LL_INFO1000, "CP::Detach - returning w/ hr=0x%x\n", hr));
return hr;
}
// Free up key left-side resources
//
// Called on detach
// This does key neutering of objects that hold left-side resources and require
// preemptively freeing the resources.
// After this, code:CordbProcess::Neuter should only affect right-side state.
void CordbProcess::NeuterChildrenLeftSideResources()
{
_ASSERTE(GetStopGoLock()->HasLock());
_ASSERTE(!GetProcessLock()->HasLock());
RSLockHolder lockHolder(GetProcessLock());
// Need process-lock to operate on hashtable, but can't yet Neuter under process-lock,
// so we have to copy the contents to an auxilary list which we can then traverse outside the lock.
RSPtrArray<CordbAppDomain> listAppDomains;
m_appDomains.CopyToArray(&listAppDomains);
// Must not hold process lock so that we can be safe to send IPC events
// to cleanup left-side resources.
lockHolder.Release();
_ASSERTE(!GetProcessLock()->HasLock());
// Frees left-side resources. This may send IPC events.
// This will make normal neutering a nop.
m_LeftSideResourceCleanupList.NeuterLeftSideResourcesAndClear(this);
for(unsigned int idx = 0; idx < listAppDomains.Length(); idx++)
{
CordbAppDomain * pAppDomain = listAppDomains[idx];
// CordbHandleValue is in the appdomain exit list, and that needs
// to send an IPC event to cleanup and release the handle from
// the GCs handle table.
pAppDomain->GetSweepableExitNeuterList()->NeuterLeftSideResourcesAndClear(this);
}
listAppDomains.Clear();
}
//---------------------------------------------------------------------------------------
// Detach the Debugger from the LS process for the V2 case
//
// Assumptions:
// This will NeuterChildren(), caller will do the real Neuter()
// Caller has already ensured that detach is safe.
//
// @dbgtodo attach-bit: this should be moved into the shim; need
// to figure out semantics for freeing left-side resources (especially GC
// handles) on detach.
void CordbProcess::DetachShim()
{
HASHFIND hashFind;
HRESULT hr = S_OK;
// If we detach before the CLR is loaded into the debuggee, then we can no-op a lot of work.
// We sure can't be sending IPC events to the LS before it exists.
if (m_initialized)
{
// The managed event queue is not necessarily drained. Cordbg could call detach between any callback.
// While the process is still stopped, neuter all of our children.
// This will make our Neuter() a nop and saves the W32ET from having to do dangerous work.
this->NeuterChildrenLeftSideResources();
{
RSLockHolder lockHolder(GetProcessLock());
this->NeuterChildren();
}
// Go ahead and detach from the entire process now. This is like sending a "Continue".
DebuggerIPCEvent * pIPCEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pIPCEvent, DB_IPCE_DETACH_FROM_PROCESS, true, VMPTR_AppDomain::NullPtr());
hr = m_cordb->SendIPCEvent(this, pIPCEvent, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, pIPCEvent->hr);
IfFailThrow(hr);
}
else
{
// @dbgtodo attach-bit: push this up, once detach IPC event is hoisted.
RSLockHolder lockHolder(GetProcessLock());
// Shouldn't have any appdomains.
(void)hashFind; //prevent "unused variable" error from GCC
_ASSERTE(m_appDomains.FindFirst(&hashFind) == NULL);
}
LOG((LF_CORDB, LL_INFO10000, "CP::Detach - got reply from LS\n"));
// It's possible that the LS may exit after they reply to our detach_from_process, but
// before we update our internal state that they're detached. So still have to check
// failure codes here.
hr = this->m_pShim->GetWin32EventThread()->SendDetachProcessEvent(this);
// Since we're auto-continuing when we detach, we should set the stop count back to zero.
// This (along w/ m_detached) prevents anyone from calling Continue on this process
// after this call returns.
m_stopCount = 0;
if (hr != CORDBG_E_PROCESS_TERMINATED)
{
// Remember that we've detached from this process object. This will prevent any further operations on
// this process, just in case... :)
// If LS exited, then don't set this flag because it overrides m_terminated when reporting errors;
// and we want to provide a consistent story about whether we detached or whether the LS exited.
m_detached = true;
}
IfFailThrow(hr);
// Now that all complicated cleanup is done, caller can do a final neuter.
// This will implicitly stop our Win32 event thread as well.
}
// Delete all events from the queue without dispatching. This is useful in shutdown.
// An event that is currently dispatching is not on the queue.
void CordbProcess::DeleteQueuedEvents()
{
INTERNAL_API_ENTRY(this);
// We must have the process lock to ensure that no one is trying to add an event
_ASSERTE(!ThreadHoldsProcessLock());
if (m_pShim != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this);
// DeleteAll() is part of the shim, and it will change external ref counts, so must really
// be marked as outside the RS.
m_pShim->GetManagedEventQueue()->DeleteAll();
}
}
//---------------------------------------------------------------------------------------
//
// Track that we're about to dispatch a managed event.
//
// Arguments:
// event - event being dispatched
//
// Assumptions:
// This is used to support code:CordbProcess::AreDispatchingEvent
// This is always called on the same thread as code:CordbProcess::FinishEventDispatch
void CordbProcess::StartEventDispatch(DebuggerIPCEventType event)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dispatchedEvent == DB_IPCE_DEBUGGER_INVALID);
_ASSERTE(event != DB_IPCE_DEBUGGER_INVALID);
m_dispatchedEvent = event;
}
//---------------------------------------------------------------------------------------
//
// Track that we're done dispatching a managed event.
//
//
// Assumptions:
// This is always called on the same thread as code:CordbProcess::StartEventDispatch
//
// Notes:
// @dbgtodo shim: eventually this goes into the shim when we hoist Continue
void CordbProcess::FinishEventDispatch()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_dispatchedEvent != DB_IPCE_DEBUGGER_INVALID);
m_dispatchedEvent = DB_IPCE_DEBUGGER_INVALID;
}
//---------------------------------------------------------------------------------------
//
// Are we in the middle of dispatching an event?
//
// Notes:
// This is used by code::CordbProcess::ContinueInternal. Continue logic takes
// a shortcut if the continue is called on the dispatch thread.
// It doesn't matter which event is being dispatch; only that we're on the dispatch thread.
// @dbgtodo shim: eventually this goes into the shim when we hoist Continue
bool CordbProcess::AreDispatchingEvent()
{
LIMITED_METHOD_CONTRACT;
return m_dispatchedEvent != DB_IPCE_DEBUGGER_INVALID;
}
// Terminate the app. We'll still dispatch an ExitProcess callback, so the app
// must wait for that before calling Cordb::Terminate.
// If this fails, the client can always call the OS's TerminateProcess command
// to rudely kill the debuggee.
HRESULT CordbProcess::Terminate(unsigned int exitCode)
{
PUBLIC_API_ENTRY(this);
LOG((LF_CORDB, LL_INFO1000, "CP::Terminate: with exitcode %u\n", exitCode));
FAIL_IF_NEUTERED(this);
// @dbgtodo shutdown: eventually, all of Terminate() will be in the Shim.
// Free all the remaining events. Since this will call into the shim, do this outside of any locks.
// (ATT_ takes locks).
DeleteQueuedEvents();
ATT_REQUIRE_SYNCED_OR_NONINIT_MAY_FAIL(this);
// When we terminate the process, it's handle will become signaled and
// Win32 Event Thread will leap into action and call CordbWin32EventThread::ExitProcess
// Unfortunately, that may destroy this object if the ExitProcess callback
// decides to call Release() on the process.
// Indicate that the process is exiting so that (among other things) we don't try and
// send messages to the left side while it's being deleted.
Lock();
// In case we're continuing from the loader bp, we don't want to try and kick off an attach. :)
m_fDoDelayedManagedAttached = false;
m_exiting = true;
// We'd like to just take a lock around everything here, but that may deadlock us
// since W32ET will wait on the lock, and Continue may wait on W32ET.
// So we just do an extra AddRef/Release to make sure we're still around.
// @todo - could we move this smartptr up so that it's well-nested w/ the lock?
RSSmartPtr<CordbProcess> pRef(this);
Unlock();
// At any point after this call, the w32 ET may run the ExitProcess code which will race w/ the continue call.
// This call only posts a request that the process terminate and does not guarantee the process actually
// terminates. In particular, the process can not exit until any outstanding IO requests are done (on cancelled).
// It also can not exit if we have an outstanding not-continued native-debug event.
// Fortunately, the interesting work in terminate is done in ExitProcessWorkItem::Do, which can take the Stop-Go lock.
// Since we're currently holding the stop-go lock, that means we at least get some serialization.
//
// Note that on Windows, the process isn't really terminated until we receive the EXIT_PROCESS_DEBUG_EVENT.
// Before then, we can still still access the debuggee's address space. On the other, for Mac debugging,
// the process can die any time after this call, and so we can no longer call into the DAC.
GetShim()->GetNativePipeline()->TerminateProcess(exitCode);
// We just call Continue() so that the debugger doesn't have to. (It's arguably odd
// to call Continue() after Terminate).
// We're stopped & Synced.
// For interop-debugging this is very important because the Terminate may not really kill the process
// until after we continue from the current native debug event.
ContinueInternal(FALSE);
// Implicit release on pRef here (since it's going out of scope)...
// After this release, this object may be destroyed. So don't use any member functions
// (including Locks) after here.
return S_OK;
}
// This can be called at any time, even if we're in an unrecoverable error state.
HRESULT CordbProcess::GetID(DWORD *pdwProcessId)
{
PUBLIC_REENTRANT_API_ENTRY(this);
OK_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pdwProcessId, DWORD *);
HRESULT hr = S_OK;
EX_TRY
{
// This shouldn't be used in V3 paths. Normally, we can enforce that by checking against
// m_pShim. However, this API can be called after being neutered, in which case m_pShim is cleared.
// So check against 0 instead.
if (m_id == 0)
{
*pdwProcessId = 0;
ThrowHR(E_NOTIMPL);
}
*pdwProcessId = GetProcessDescriptor()->m_Pid;
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Helper to get process descriptor internally. We know we'll always succeed.
// This is more convient for internal callers since they can just use it as an expression
// without having to check HRESULTS.
const ProcessDescriptor* CordbProcess::GetProcessDescriptor()
{
// This shouldn't be used in V3 paths, in which case it's set to 0. Only the shim should be
// calling this. Assert to catch anybody else.
_ASSERTE(m_processDescriptor.IsInitialized());
return &m_processDescriptor;
}
HRESULT CordbProcess::GetHandle(HANDLE *phProcessHandle)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this); // Once we neuter the process, we close our OS handle to it.
VALIDATE_POINTER_TO_OBJECT(phProcessHandle, HANDLE *);
if (m_pShim == NULL)
{
_ASSERTE(!"CordbProcess::GetHandle() should be not be called on the new architecture");
*phProcessHandle = NULL;
return E_NOTIMPL;
}
else
{
*phProcessHandle = m_handle;
return S_OK;
}
}
HRESULT CordbProcess::IsRunning(BOOL *pbRunning)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pbRunning, BOOL*);
*pbRunning = !GetSynchronized();
return S_OK;
}
HRESULT CordbProcess::EnableSynchronization(BOOL bEnableSynchronization)
{
/* !!! */
PUBLIC_API_ENTRY(this);
return E_NOTIMPL;
}
HRESULT CordbProcess::Stop(DWORD dwTimeout)
{
PUBLIC_API_ENTRY(this);
CORDBRequireProcessStateOK(this);
HRESULT hr = StopInternal(dwTimeout, VMPTR_AppDomain::NullPtr());
return ErrWrapper(hr);
}
HRESULT CordbProcess::StopInternal(DWORD dwTimeout, VMPTR_AppDomain pAppDomainToken)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: stopping process 0x%x(%d) with timeout %d\n", m_id, m_id, dwTimeout));
INTERNAL_API_ENTRY(this);
// Stop + Continue are executed under the Stop-Go lock. This makes them atomic.
// We'll toggle the process-lock (b/c we communicate w/ the W32et, so just the process-lock is
// not sufficient to make this atomic).
// It's ok to take this lock before checking if the CordbProcess has been neutered because
// the lock is destroyed in the dtor after neutering.
RSLockHolder ch(&m_StopGoLock);
// Check if this CordbProcess has been neutered under the SG lock.
// Otherwise it's possible to race with Detach() and Terminate().
FAIL_IF_NEUTERED(this);
CORDBFailIfOnWin32EventThread(this);
if (m_pShim == NULL) // Stop/Go is moved off to the shim
{
return E_NOTIMPL;
}
DebuggerIPCEvent* event;
HRESULT hr = S_OK;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::SI, timeout=%d, this=%p\n", dwTimeout, this);
// Stop() is a syncronous (blocking) operation. Furthermore, we have no way to cancel the async-break request.
// Thus if we returned early on a timeout, then we'll be in a random state b/c the LS may get stopped at any
// later spot.
// One solution just require the param is INFINITE until we fix this and E_INVALIDARG if it's not.
// But that could be a breaking change (what if a debugger passes in a really large value that's effectively
// INFINITE).
// So we'll just ignore it and always treat it as infinite.
dwTimeout = INFINITE;
// Do the checks on the process state under the SG lock. This ensures that another thread cannot come in
// after we do the checks and take the lock before we do. For example, Detach() can race with Stop() such
// that:
// 1. Thread A calls CordbProcess::Detach() and takes the stop-go lock
// 2. Thread B calls CordbProcess::Stop(), passes all the checks, and then blocks on the stop-go lock
// 3. Thread A finishes the detach, invalides the process state, cleans all the resources, and then
// releases the stop-go lock
// 4. Thread B gets the lock, but everything has changed
CORDBRequireProcessStateOK(this);
Lock();
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
// Don't need to stop if the process hasn't even executed any managed code yet.
if (!m_initialized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process isn't initialized yet.\n"));
// Mark the process as synchronized so no events will be dispatched until the thing is continued.
SetSynchronized(true);
// Remember uninitialized stop...
m_uninitializedStop = true;
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're Win32 attached, then suspend all the unmanaged threads in the process.
// We may or may not be stopped at a native debug event.
if (IsInteropDebugging())
{
SuspendUnmanagedThreads();
}
#endif // FEATURE_INTEROP_DEBUGGING
// Get the RC Event Thread to stop listening to the process.
m_cordb->ProcessStateChanged();
hr = S_OK;
goto Exit;
}
// Don't need to stop if the process is already synchronized.
// @todo - Issue 129917. It's possible that we'll get a call to Stop when the LS is already stopped.
// Sending an AsyncBreak would deadlock here (b/c the LS will ignore the frivilous request,
// and thus never send a SyncComplete, and thus our Waiting on the SyncComplete will deadlock).
// We avoid this case by checking m_syncCompleteReceived (which should roughly correspond to
// the LS's m_stopped variable).
// One window this can happen is after a Continue() pings the RCET but before the RCET actually sweeps + flushes.
if (GetSynchronized() || GetSyncCompleteRecv())
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process was already synchronized. m_syncCompleteReceived=%d\n", GetSyncCompleteRecv()));
if (GetSyncCompleteRecv())
{
// We must be in that window alluded to above (while the RCET is sweeping). Re-ping the RCET.
SetSynchronized(true);
m_cordb->ProcessStateChanged();
}
hr = S_OK;
goto Exit;
}
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::S: process not sync'd, requesting stop.\n");
m_stopRequested = true;
// We don't want to dispatch any Win32 debug events while we're trying to stop.
// Setting m_specialDeferment=true means that any debug event we get will be queued and not dispatched.
// We do this to avoid a nested call to Continue.
// These defered events will get dispatched when somebody calls continue (and since they're calling
// stop now, they must call continue eventually).
// Note that if we got a Win32 debug event between when we took the Stop-Go lock above and now,
// that even may have been dispatched. We're ok because SSFW32Stop will hijack that event and continue it,
// and then all future events will be queued.
m_specialDeferment = true;
Unlock();
BOOL asyncBreakSent;
// We need to ensure that the helper thread is alive.
hr = this->StartSyncFromWin32Stop(&asyncBreakSent);
if (FAILED(hr))
{
return hr;
}
if (asyncBreakSent)
{
hr = S_OK;
Lock();
m_stopRequested = false;
goto Exit;
}
// Send the async break event to the RC.
event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_ASYNC_BREAK, false, pAppDomainToken);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::S: sending async stop to appd 0x%x.\n", VmPtrToCookie(pAppDomainToken));
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
if (FAILED(hr))
{
// We don't hold the lock so just return immediately. Don't adjust stop-count.
_ASSERTE(!ThreadHoldsProcessLock());
return hr;
}
LOG((LF_CORDB, LL_INFO1000, "CP::S: sent async stop to appd 0x%x.\n", VmPtrToCookie(pAppDomainToken)));
// Wait for the sync complete message to come in. Note: when the sync complete message arrives to the RCEventThread,
// it will mark the process as synchronized and _not_ dispatch any events. Instead, it will set m_stopWaitEvent
// which will let this function return. If the user wants to process any queued events, they will need to call
// Continue.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::S: waiting for event.\n");
DWORD ret;
ret = SafeWaitForSingleObject(this, m_stopWaitEvent, dwTimeout);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::S: got event, %d.\n", ret);
if (m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
if (ret == WAIT_OBJECT_0)
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process stopped.\n"));
m_stopRequested = false;
m_cordb->ProcessStateChanged();
hr = S_OK;
Lock();
goto Exit;
}
else if (ret == WAIT_TIMEOUT)
{
hr = ErrWrapper(CORDBG_E_TIMEOUT);
}
else
hr = HRESULT_FROM_GetLastError();
// We came out of the wait, but we weren't signaled because a sync complete event came in. Re-check the process and
// remove the stop requested flag.
Lock();
m_stopRequested = false;
if (GetSynchronized())
{
LOG((LF_CORDB, LL_INFO1000, "CP::S: process stopped.\n"));
m_cordb->ProcessStateChanged();
hr = S_OK;
}
Exit:
_ASSERTE(ThreadHoldsProcessLock());
// Stop queuing any Win32 Debug events. We should be synchronized now.
m_specialDeferment = false;
if (SUCCEEDED(hr))
{
IncStopCount();
}
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::S: returning from Stop, hr=0x%08x, m_stopCount=%d.\n", hr, GetStopCount());
Unlock();
return hr;
}
//---------------------------------------------------------------------------------------
// Clear all RS state on all CordbThread objects.
//
// Notes:
// This clears all the thread-related state that the RS may have cached,
// such as locals, frames, etc.
// This would be called if the debugger is resuming execution.
void CordbProcess::MarkAllThreadsDirty()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
CordbThread * pThread;
HASHFIND find;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (pThread = m_userThreads.FindFirst(&find);
pThread != NULL;
pThread = m_userThreads.FindNext(&find))
{
_ASSERTE(pThread != NULL);
pThread->MarkStackFramesDirty();
}
ClearPatchTable();
}
HRESULT CordbProcess::Continue(BOOL fIsOutOfBand)
{
PUBLIC_API_ENTRY(this);
if (m_pShim == NULL) // This API is moved off to the shim
{
// bias towards failing with CORDBG_E_NUETERED.
FAIL_IF_NEUTERED(this);
return E_NOTIMPL;
}
HRESULT hr;
if (fIsOutOfBand)
{
#ifdef FEATURE_INTEROP_DEBUGGING
hr = ContinueOOB();
#else
hr = E_INVALIDARG;
#endif // FEATURE_INTEROP_DEBUGGING
}
else
{
hr = ContinueInternal(fIsOutOfBand);
}
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// ContinueOOB
//
// Continue the Win32 event as an out-of-band event.
//
// Return Value:
// S_OK on successful continue. Else error.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::ContinueOOB()
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
// If we're continuing from an out-of-band unmanaged event, then just go
// ahead and get the Win32 event thread to continue the process. No other
// work needs to be done (i.e., don't need to send a managed continue message
// or dispatch any events) because any processing done due to the out-of-band
// message can't alter the synchronized state of the process.
Lock();
_ASSERTE(m_outOfBandEventQueue != NULL);
// Are we calling this from the unmanaged callback?
if (m_dispatchingOOBEvent)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue while dispatching unmanaged out-of-band event.\n");
// We don't know what thread we're on here.
// Tell the Win32 event thread to continue when it returns from handling its unmanaged callback.
m_dispatchingOOBEvent = false;
Unlock();
}
else
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue outside of dispatching.\n");
// If we're not dispatching this, then they shouldn't be on the win32 event thread.
_ASSERTE(!this->IsWin32EventThread());
Unlock();
// Send an event to the Win32 event thread to do the continue. This is an out-of-band continue.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cOobUMContinue);
}
return hr;
}
#endif // FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// ContinueInternal
//
// Continue the Win32 event.
//
// Return Value:
// S_OK on success. Else error.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::ContinueInternal(BOOL fIsOutOfBand)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
// Continue has an ATT similar to ATT_REQUIRE_STOPPED_MAY_FAIL, but w/ some subtle differences.
// - if we're stopped at a native DE, but not synchronized, we don't want to sync.
// - We may get Debug events (especially native ones) at weird times, and thus we have to continue
// at weird times.
// External APIs should not have the process lock.
_ASSERTE(!ThreadHoldsProcessLock());
_ASSERTE(m_pShim != NULL);
// OutOfBand should use ContinueOOB
_ASSERTE(!fIsOutOfBand);
// Since Continue is process-wide, just use a null appdomain pointer.
VMPTR_AppDomain pAppDomainToken = VMPTR_AppDomain::NullPtr();
HRESULT hr = S_OK;
if (m_unrecoverableError)
{
return CORDBHRFromProcessState(this, NULL);
}
// We can't call ContinueInternal for an inband event on the win32 event thread.
// This is an issue in the CLR (or an API design decision, depending on your perspective).
// Continue() may send an IPC event and we can't do that on the win32 event thread.
CORDBFailIfOnWin32EventThread(this);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: continuing IB, this=0x%X\n", this);
// Stop + Continue are executed under the Stop-Go lock. This makes them atomic.
// We'll toggle the process-lock (b/c we communicate w/ the W32et, so that's not sufficient).
RSLockHolder rsLockHolder(&m_StopGoLock);
// Check for other failures (do these after we have the SG lock).
if (m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
if (m_detached)
{
return CORDBG_E_PROCESS_DETACHED;
}
Lock();
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
_ASSERTE(fIsOutOfBand == FALSE);
// If we've got multiple Stop calls, we need a Continue for each one. So, if the stop count > 1, just go ahead and
// return without doing anything. Note: this is only for in-band or managed events. OOB events are still handled as
// normal above.
_ASSERTE(GetStopCount() > 0);
if (GetStopCount() == 0)
{
Unlock();
_ASSERTE(!"Superflous Continue. ICorDebugProcess.Continue() called too many times");
return CORDBG_E_SUPERFLOUS_CONTINUE;
}
DecStopCount();
// We give managed events priority over unmanaged events. That way, the entire queued managed state can drain before
// we let any other unmanaged events through.
// Every stop or event must be matched by a corresponding Continue. m_stopCount counts outstanding stopping events
// along with calls to Stop. If the count is high at this point, we simply return. This ensures that even if someone
// calls Stop just as they're receiving an event that they can call Continue for that Stop and for that event
// without problems.
if (GetStopCount() > 0)
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: m_stopCount=%d, Continue just returning S_OK...\n", GetStopCount());
Unlock();
return S_OK;
}
// We're no longer stopped, so reset the m_stopWaitEvent.
ResetEvent(m_stopWaitEvent);
// If we're continuing from an uninitialized stop, then we don't need to do much at all. No event need be sent to
// the Left Side (duh, it isn't even there yet.) We just need to get the RC Event Thread to start listening to the
// process again, and resume any unmanaged threads if necessary.
if (m_uninitializedStop)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continuing from uninitialized stop.\n");
// No longer synchronized (it was a partial sync in the first place.)
SetSynchronized(false);
MarkAllThreadsDirty();
// No longer in an uninitialized stop.
m_uninitializedStop = false;
// Notify the RC Event Thread.
m_cordb->ProcessStateChanged();
Unlock();
#ifdef FEATURE_INTEROP_DEBUGGING
// We may or may not have a native debug event queued here.
// If Cordbg called Stop() from a native debug event (to get the process Synchronized), then
// we'll have a native debug event, and we need to continue it.
// If Cordbg called Stop() to do an AsyncBreak, then there's no native-debug event.
// If we're Win32 attached, resume all the unmanaged threads.
if (IsInteropDebugging())
{
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->SetState(CUES_UserContinued);
}
// Send to the Win32 event thread to do the unmanaged continue for us.
// If we're at a debug event, this will continue it.
// Else it will degenerate into ResumeUnmanagedThreads();
this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
}
#endif // FEATURE_INTEROP_DEBUGGING
return S_OK;
}
// If there are more managed events, get them dispatched now.
if (!m_pShim->GetManagedEventQueue()->IsEmpty() && GetSynchronized())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: managed event queued.\n");
// Mark that we're not synchronized anymore.
SetSynchronized(false);
// If the callback queue is not empty, then the LS is not actually continuing, and so our cached
// state is still valid.
// If we're in the middle of dispatching a managed event, then simply return. This indicates to HandleRCEvent
// that the user called Continue and HandleRCEvent will dispatch the next queued event. But if Continue was
// called outside the managed callback, all we have to do is tell the RC event thread that something about the
// process has changed and it will dispatch the next managed event.
if (!AreDispatchingEvent())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continuing while not dispatching managed event.\n");
m_cordb->ProcessStateChanged();
}
Unlock();
return S_OK;
}
// Neuter if we have an outstanding object.
// Only do this if we're really continuining the debuggee. So don't do this if our stop-count is high b/c we
// shouldn't neuter until we're done w/ the current event. And don't do this until we drain the current callback queue.
// Note that we can't hold the process lock while we do this b/c Neutering may send IPC events.
// However, we're still under the StopGo lock b/c that may help us serialize things.
// Sweep neuter list. This will catch anything that's marked as 'safe to neuter'. This includes
// all objects added to the 'neuter-on-Continue'.
// Only do this if we're synced- we don't want to do this if we're continuing from a Native Debug event.
if (GetSynchronized())
{
// Need process-lock to operate on hashtable, but can't yet Neuter under process-lock,
// so we have to copy the contents to an auxilary list which we can then traverse outside the lock.
RSPtrArray<CordbAppDomain> listAppDomains;
HRESULT hrCopy = S_OK;
EX_TRY // @dbgtodo cleanup: push this up
{
m_appDomains.CopyToArray(&listAppDomains);
}
EX_CATCH_HRESULT(hrCopy);
SetUnrecoverableIfFailed(GetProcess(), hrCopy);
m_ContinueNeuterList.NeuterAndClear(this);
// @dbgtodo left-side resources: eventually (once
// NeuterLeftSideResources is process-lock safe), do this all under the
// lock. Can't hold process lock b/c neutering left-side resources
// may send events.
Unlock();
// This may send IPC events.
// This will make normal neutering a nop.
// This will toggle the process lock.
m_LeftSideResourceCleanupList.SweepNeuterLeftSideResources(this);
// Many objects (especially CordbValue, FuncEval) don't have clear lifetime semantics and
// so they must be put into an exit-neuter list (Process/AppDomain) for worst-case scenarios.
// These objects are likely released early, and so we sweep them aggressively on each Continue (kind of like a mini-GC).
//
// One drawback is that there may be a lot of useless sweeping if the debugger creates a lot of
// objects that it holds onto. Consider instead of sweeping, have the object explicitly post itself
// to a list that's guaranteed to be cleared. This would let us avoid sweeping not-yet-ready objects.
// This will toggle the process lock
m_ExitNeuterList.SweepAllNeuterAtWillObjects(this);
for(unsigned int idx = 0; idx < listAppDomains.Length(); idx++)
{
CordbAppDomain * pAppDomain = listAppDomains[idx];
// CordbHandleValue is in the appdomain exit list, and that needs
// to send an IPC event to cleanup and release the handle from
// the GCs handle table.
// This will toggle the process lock.
pAppDomain->GetSweepableExitNeuterList()->SweepNeuterLeftSideResources(this);
}
listAppDomains.Clear();
Lock();
}
// At this point, if the managed event queue is empty, m_synchronized may still be true if we had previously
// synchronized.
#ifdef FEATURE_INTEROP_DEBUGGING
// Next, check for unmanaged events that may be queued. If there are some queued, then we need to get the Win32
// event thread to go ahead and dispatch the next one. If there aren't any queued, then we can just fall through and
// send the continue message to the left side. This works even if we have an outstanding ownership request, because
// until that answer is received, its just like the event hasn't happened yet.
//
// If we're terminated, then we've already continued from the last win32 event and so don't continue.
// @todo - or we could ensure the PS_SOME_THREADS_SUSPENDED | PS_HIJACKS_IN_PLACE are removed.
// Either way, we're just protecting against exit-process at strange times.
bool fDoWin32Continue = !m_terminated && ((m_state & (PS_WIN32_STOPPED | PS_SOME_THREADS_SUSPENDED | PS_HIJACKS_IN_PLACE)) != 0);
// We need to store this before marking the event user continued below
BOOL fHasUserUncontinuedEvents = HasUserUncontinuedNativeEvents();
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->SetState(CUES_UserContinued);
}
if (fHasUserUncontinuedEvents)
{
// ExitProcess is the last debug event we'll get. The Process Handle is not signaled until
// after we continue from ExitProcess. m_terminated is only set once we know the process is signaled.
// (This isn't 100% true for the detach case, but since you can't do interop detach, we don't care)
//_ASSERTE(!m_terminated);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP::CI: there are queued uncontinued events. m_dispatchingUnmanagedEvent = %d\n", m_dispatchingUnmanagedEvent);
// Are we being called while in the unmanaged event callback?
if (m_dispatchingUnmanagedEvent)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continue while dispatching.\n"));
// The Win32ET could have made a cross-thread call to Continue while dispatching,
// so we don't know if this is the win32 ET.
// Tell the Win32 thread to continue when it returns from handling its unmanaged callback.
m_dispatchingUnmanagedEvent = false;
// If there are no more unmanaged events, then we fall through and continue the process for real. Otherwise,
// we can simply return.
if (HasUndispatchedNativeEvents())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: more unmanaged events need dispatching.\n");
// Note: if we tried to access the Left Side while stopped but couldn't, then m_oddSync will be true. We
// need to reset it to false since we're continuing now.
m_oddSync = false;
Unlock();
return S_OK;
}
else
{
// Also, if there are no more unmanaged events, then when DispatchUnmanagedInBandEvent sees that
// m_dispatchingUnmanagedEvent is false, it will continue the process. So we set doWin32Continue to
// false here so that we don't try to double continue the process below.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: no more unmanaged events to dispatch.\n");
fDoWin32Continue = false;
}
}
else
{
// after the DebugEvent callback returned the continue still had no been issued. Then later
// on another thread the user called back to continue the event, which gets us to right here
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continue outside of dispatching.\n"));
// This should be the common place to Dispatch an IB event that was hijacked for sync.
// If we're not dispatching, this better not be the win32 event thread.
_ASSERTE(!IsWin32EventThread());
// If the event at the head of the queue is really the last event, or if the event at the head of the queue
// hasn't been dispatched yet, then we simply fall through and continue the process for real. However, if
// its not the last event, we send to the Win32 event thread and get it to continue, then we return.
if (HasUndispatchedNativeEvents())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: more unmanaged events need dispatching.\n");
// Note: if we tried to access the Left Side while stopped but couldn't, then m_oddSync will be true. We
// need to reset it to false since we're continuing now.
m_oddSync = false;
Unlock();
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
return hr;
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
// Both the managed and unmanaged event queues are now empty. Go
// ahead and continue the process for real.
LOG((LF_CORDB, LL_INFO1000, "CP::CI: headed for true continue.\n"));
// We need to check these while under the lock, but action must be
// taked outside of the lock.
bool fIsExiting = m_exiting;
bool fWasSynchronized = GetSynchronized();
// Mark that we're no longer synchronized.
if (fWasSynchronized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: process was synchronized.\n"));
SetSynchronized(false);
SetSyncCompleteRecv(false);
// we're no longer in a callback, so set flags to indicate that we've finished.
GetShim()->NotifyOnContinue();
// Flush will update state, including continue counter and marking
// frames dirty.
this->FlushProcessRunning();
// Tell the RC event thread that something about this process has changed.
m_cordb->ProcessStateChanged();
}
m_continueCounter++;
// If m_oddSync is set, then out last synchronization was due to us syncing the process because we were Win32
// stopped. Therefore, while we do need to do most of the work to continue the process below, we don't actually have
// to send the managed continue event. Setting wasSynchronized to false here helps us do that.
if (m_oddSync)
{
fWasSynchronized = false;
m_oddSync = false;
}
#ifdef FEATURE_INTEROP_DEBUGGING
// We must ensure that all managed threads are suspended here. We're about to let all managed threads run free via
// the managed continue message to the Left Side. If we don't suspend the managed threads, then they may start
// slipping forward even if we receive an in-band unmanaged event. We have to hijack in-band unmanaged events while
// getting the managed continue message over to the Left Side to keep the process running free. Otherwise, the
// SendIPCEvent will hang below. But in doing so, we could let managed threads slip to far. So we ensure they're all
// suspended here.
//
// Note: we only do this suspension if the helper thread hasn't died yet. If the helper thread has died, then we
// know that we're loosing the Runtime. No more managed code is going to run, so we don't bother trying to prevent
// managed threads from slipping via the call below.
//
// Note: we just remember here, under the lock, so we can unlock then wait for the syncing thread to free the
// debugger lock. Otherwise, we may block here and prevent someone from continuing from an OOB event, which also
// prevents the syncing thread from releasing the debugger lock like we want it to.
bool fNeedSuspend = fWasSynchronized && fDoWin32Continue && !m_helperThreadDead;
// If we receive a new in-band event once we unlock, we need to know to hijack it and keep going while we're still
// trying to send the managed continue event to the process.
if (fWasSynchronized && fDoWin32Continue && !fIsExiting)
{
m_specialDeferment = true;
}
if (fNeedSuspend)
{
// @todo - what does this actually accomplish? We already suspended everything when we first synced.
// Any thread that may hold a lock blocking the helper is
// inside of a can't stop region, and thus we won't suspend it.
SuspendUnmanagedThreads();
}
#endif // FEATURE_INTEROP_DEBUGGING
Unlock();
// Although we've released the Process-lock, we still have the Stop-Go lock.
_ASSERTE(m_StopGoLock.HasLock());
// If we're processing an ExitProcess managed event, then we don't want to really continue the process, so just fall
// thru. Note: we did let the unmanaged continue go through above for this case.
if (fIsExiting)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: continuing from exit case.\n"));
}
else if (fWasSynchronized)
{
LOG((LF_CORDB, LL_INFO1000, "CP::CI: Sending continue to AppD:0x%x.\n", VmPtrToCookie(pAppDomainToken)));
#ifdef FEATURE_INTEROP_DEBUGGING
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Continue flags:special=%d, dowin32=%d\n", m_specialDeferment, fDoWin32Continue);
#endif
// Send to the RC to continue the process.
DebuggerIPCEvent * pEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pEvent, DB_IPCE_CONTINUE, false, pAppDomainToken);
hr = m_cordb->SendIPCEvent(this, pEvent, CorDBIPC_BUFFER_SIZE);
// It is possible that we continue and then the process immediately exits before the helper
// thread is finished continuing and can report success back to us. That's arguably a success
// case sinceu the process did indeed continue, but since we didn't get the acknowledgement,
// we can't be sure it's success. So we call it S_FALSE instead of S_OK.
// @todo - how do we handle other failure here?
if (hr == CORDBG_E_PROCESS_TERMINATED)
{
hr = S_FALSE;
}
_ASSERTE(SUCCEEDED(pEvent->hr));
LOG((LF_CORDB, LL_INFO1000, "CP::CI: Continue sent to AppD:0x%x.\n", VmPtrToCookie(pAppDomainToken)));
}
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're win32 attached to the Left side, then we need to win32 continue the process too (unless, of course, it's
// already been done above.)
//
// Note: we do this here because we want to get the Left Side to receive and ack our continue message above if we
// were sync'd. If we were sync'd, then by definition the process (and the helper thread) is running anyway, so all
// this continue is going to do is to let the threads that have been suspended go.
if (fDoWin32Continue)
{
#ifdef _DEBUG
{
// A little pause here extends the special deferment region and thus causes native-debug
// events to get hijacked. This test some wildly different corner case paths.
// See VSWhidbey bugs 131905, 168971
static DWORD dwRace = -1;
if (dwRace == -1)
dwRace = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgRace);
if ((dwRace & 1) == 1)
{
Sleep(30);
}
}
#endif
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: sending unmanaged continue.\n");
// Send to the Win32 event thread to do the unmanaged continue for us.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cRealUMContinue);
}
#endif // FEATURE_INTEROP_DEBUGGING
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::CI: continue done, returning.\n");
return hr;
}
HRESULT CordbProcess::HasQueuedCallbacks(ICorDebugThread *pThread,
BOOL *pbQueued)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pThread,ICorDebugThread *);
VALIDATE_POINTER_TO_OBJECT(pbQueued,BOOL *);
// Shim owns the event queue
if (m_pShim != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this); // Calling to shim, leaving RS.
*pbQueued = m_pShim->GetManagedEventQueue()->HasQueuedCallbacks(pThread);
return S_OK;
}
return E_NOTIMPL; // Not implemented in V3.
}
//
// A small helper function to convert a CordbBreakpoint to an ICorDebugBreakpoint based on its type.
//
static ICorDebugBreakpoint *CordbBreakpointToInterface(CordbBreakpoint * pBreakpoint)
{
_ASSERTE(pBreakpoint != NULL);
//
// I really dislike this. We've got three subclasses of CordbBreakpoint, but we store them all into the same hash
// (m_breakpoints), so when we get one out of the hash, we don't really know what type it is. But we need to know
// what type it is because we need to cast it to the proper interface before passing it out. I.e., when we create a
// function breakpoint, we return the breakpoint casted to an ICorDebugFunctionBreakpoint. But if we grab that same
// breakpoint out of the hash as a CordbBreakpoint and pass it out as an ICorDebugBreakpoint, then that's a
// different pointer, and its wrong. So I've added the type to the breakpoint so we can cast properly here. I'd love
// to do this a different way, though...
//
// -- Mon Dec 14 21:06:46 1998
//
switch(pBreakpoint->GetBPType())
{
case CBT_FUNCTION:
return static_cast<ICorDebugFunctionBreakpoint *>(static_cast<CordbFunctionBreakpoint *> (pBreakpoint));
break;
case CBT_MODULE:
return static_cast<ICorDebugModuleBreakpoint*>(static_cast<CordbModuleBreakpoint *> (pBreakpoint));
break;
case CBT_VALUE:
return static_cast<ICorDebugValueBreakpoint *>(static_cast<CordbValueBreakpoint *> (pBreakpoint));
break;
default:
_ASSERTE(!"Invalid breakpoint type!");
}
return NULL;
}
// Callback data for code:CordbProcess::GetAssembliesInLoadOrder
class ShimAssemblyCallbackData
{
public:
// Ctor to intialize callback data
//
// Arguments:
// pAppDomain - appdomain that the assemblies are in.
// pAssemblies - preallocated array of smart pointers to hold assemblies
// countAssemblies - size of pAssemblies in elements.
ShimAssemblyCallbackData(
CordbAppDomain * pAppDomain,
RSExtSmartPtr<ICorDebugAssembly>* pAssemblies,
ULONG countAssemblies)
{
_ASSERTE(pAppDomain != NULL);
_ASSERTE(pAssemblies != NULL);
m_pProcess = pAppDomain->GetProcess();
m_pAppDomain = pAppDomain;
m_pAssemblies = pAssemblies;
m_countElements = countAssemblies;
m_index = 0;
// Just to be safe, clear them all out
for(ULONG i = 0; i < countAssemblies; i++)
{
pAssemblies[i].Clear();
}
}
// Dtor
//
// Notes:
// This can assert end-of-enumeration invariants.
~ShimAssemblyCallbackData()
{
// Ensure that we went through all assemblies.
_ASSERTE(m_index == m_countElements);
}
// Callback invoked from DAC enumeration.
//
// arguments:
// vmDomainAssembly - VMPTR for assembly
// pData - a 'this' pointer
//
static void Callback(VMPTR_DomainAssembly vmDomainAssembly, void * pData)
{
ShimAssemblyCallbackData * pThis = static_cast<ShimAssemblyCallbackData *> (pData);
INTERNAL_DAC_CALLBACK(pThis->m_pProcess);
CordbAssembly * pAssembly = pThis->m_pAppDomain->LookupOrCreateAssembly(vmDomainAssembly);
pThis->SetAndMoveNext(pAssembly);
}
// Set the current index in the table and increment the cursor.
//
// Arguments:
// pAssembly - assembly from DAC enumerator
void SetAndMoveNext(CordbAssembly * pAssembly)
{
_ASSERTE(pAssembly != NULL);
if (m_index >= m_countElements)
{
// Enumerating the assemblies in the target should be fixed since
// the target is not running.
// We should never get here unless the target is unstable.
// The caller (the shim) pre-allocated the table of assemblies.
m_pProcess->TargetConsistencyCheck(!"Target changed assembly count");
return;
}
m_pAssemblies[m_index].Assign(pAssembly);
m_index++;
}
protected:
CordbProcess * m_pProcess;
CordbAppDomain * m_pAppDomain;
RSExtSmartPtr<ICorDebugAssembly>* m_pAssemblies;
ULONG m_countElements;
ULONG m_index;
};
//---------------------------------------------------------------------------------------
// Shim Helper to enumerate the assemblies in the load-order
//
// Arguments:
// pAppdomain - non-null appdomain to enumerate assemblies.
// pAssemblies - caller pre-allocated array to hold assemblies
// countAssemblies - size of the array.
//
// Notes:
// Caller preallocated array (likely from ICorDebugAssemblyEnum::GetCount),
// and now this function fills in the assemblies in the order they were
// loaded.
//
// The target should be stable, such that the number of assemblies in the
// target is stable, and therefore countAssemblies as determined by the
// shim via ICorDebugAssemblyEnum::GetCount should match the number of
// assemblies enumerated here.
//
// Called by code:ShimProcess::QueueFakeAttachEvents.
// This provides the assemblies in load-order. In contrast,
// ICorDebugAppDomain::EnumerateAssemblies is a random order. The shim needs
// load-order to match Whidbey semantics for dispatching fake load-assembly
// callbacks on attach. The debugger then uses the order
// in its module display window.
//
void CordbProcess::GetAssembliesInLoadOrder(
ICorDebugAppDomain * pAppDomain,
RSExtSmartPtr<ICorDebugAssembly>* pAssemblies,
ULONG countAssemblies)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
RSLockHolder lockHolder(GetProcessLock());
_ASSERTE(GetShim() != NULL);
CordbAppDomain * pAppDomainInternal = static_cast<CordbAppDomain *> (pAppDomain);
ShimAssemblyCallbackData data(pAppDomainInternal, pAssemblies, countAssemblies);
// Enumerate through and fill out pAssemblies table.
GetDAC()->EnumerateAssembliesInAppDomain(
pAppDomainInternal->GetADToken(),
ShimAssemblyCallbackData::Callback,
&data); // user data
// pAssemblies array has now been updated.
}
// Callback data for code:CordbProcess::GetModulesInLoadOrder
class ShimModuleCallbackData
{
public:
// Ctor to intialize callback data
//
// Arguments:
// pAssembly - assembly that the Modules are in.
// pModules - preallocated array of smart pointers to hold Modules
// countModules - size of pModules in elements.
ShimModuleCallbackData(
CordbAssembly * pAssembly,
RSExtSmartPtr<ICorDebugModule>* pModules,
ULONG countModules)
{
_ASSERTE(pAssembly != NULL);
_ASSERTE(pModules != NULL);
m_pProcess = pAssembly->GetAppDomain()->GetProcess();
m_pAssembly = pAssembly;
m_pModules = pModules;
m_countElements = countModules;
m_index = 0;
// Just to be safe, clear them all out
for(ULONG i = 0; i < countModules; i++)
{
pModules[i].Clear();
}
}
// Dtor
//
// Notes:
// This can assert end-of-enumeration invariants.
~ShimModuleCallbackData()
{
// Ensure that we went through all Modules.
_ASSERTE(m_index == m_countElements);
}
// Callback invoked from DAC enumeration.
//
// arguments:
// vmDomainAssembly - VMPTR for Module
// pData - a 'this' pointer
//
static void Callback(VMPTR_DomainAssembly vmDomainAssembly, void * pData)
{
ShimModuleCallbackData * pThis = static_cast<ShimModuleCallbackData *> (pData);
INTERNAL_DAC_CALLBACK(pThis->m_pProcess);
CordbModule * pModule = pThis->m_pAssembly->GetAppDomain()->LookupOrCreateModule(vmDomainAssembly);
pThis->SetAndMoveNext(pModule);
}
// Set the current index in the table and increment the cursor.
//
// Arguments:
// pModule - Module from DAC enumerator
void SetAndMoveNext(CordbModule * pModule)
{
_ASSERTE(pModule != NULL);
if (m_index >= m_countElements)
{
// Enumerating the Modules in the target should be fixed since
// the target is not running.
// We should never get here unless the target is unstable.
// The caller (the shim) pre-allocated the table of Modules.
m_pProcess->TargetConsistencyCheck(!"Target changed Module count");
return;
}
m_pModules[m_index].Assign(pModule);
m_index++;
}
protected:
CordbProcess * m_pProcess;
CordbAssembly * m_pAssembly;
RSExtSmartPtr<ICorDebugModule>* m_pModules;
ULONG m_countElements;
ULONG m_index;
};
//---------------------------------------------------------------------------------------
// Shim Helper to enumerate the Modules in the load-order
//
// Arguments:
// pAppdomain - non-null appdomain to enumerate Modules.
// pModules - caller pre-allocated array to hold Modules
// countModules - size of the array.
//
// Notes:
// Caller preallocated array (likely from ICorDebugModuleEnum::GetCount),
// and now this function fills in the Modules in the order they were
// loaded.
//
// The target should be stable, such that the number of Modules in the
// target is stable, and therefore countModules as determined by the
// shim via ICorDebugModuleEnum::GetCount should match the number of
// Modules enumerated here.
//
// Called by code:ShimProcess::QueueFakeAssemblyAndModuleEvent.
// This provides the Modules in load-order. In contrast,
// ICorDebugAssembly::EnumerateModules is a random order. The shim needs
// load-order to match Whidbey semantics for dispatching fake load-Module
// callbacks on attach. The most important thing is that the manifest module
// gets a LodModule callback before any secondary modules. For dynamic
// modules, this is necessary for operations on the secondary module
// that rely on manifest metadata (eg. GetSimpleName).
//
// @dbgtodo : This is almost identical to GetAssembliesInLoadOrder, and
// (together wih the CallbackData classes) seems a HUGE amount of code and
// complexity for such a simple thing. We also have extra code to order
// AppDomains and Threads. We should try and rip all of this extra complexity
// out, and replace it with better data structures for storing these items.
// Eg., if we used std::map, we could have efficient lookups and ordered
// enumerations. However, we do need to be careful about exposing new invariants
// through ICorDebug that customers may depend on, which could place a long-term
// compatibility burden on us. We could have a simple generic data structure
// (eg. built on std::hash_map and std::list) which provided efficient look-up
// and both in-order and random enumeration.
//
void CordbProcess::GetModulesInLoadOrder(
ICorDebugAssembly * pAssembly,
RSExtSmartPtr<ICorDebugModule>* pModules,
ULONG countModules)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
RSLockHolder lockHolder(GetProcessLock());
_ASSERTE(GetShim() != NULL);
CordbAssembly * pAssemblyInternal = static_cast<CordbAssembly *> (pAssembly);
ShimModuleCallbackData data(pAssemblyInternal, pModules, countModules);
// Enumerate through and fill out pModules table.
GetDAC()->EnumerateModulesInAssembly(
pAssemblyInternal->GetDomainAssemblyPtr(),
ShimModuleCallbackData::Callback,
&data); // user data
// pModules array has now been updated.
}
//---------------------------------------------------------------------------------------
// Callback to count the number of enumerations in a process.
//
// Arguments:
// id - the connection id.
// pName - name of the connection
// pUserData - an EnumerateConnectionsData
//
// Notes:
// Helper function for code:CordbProcess::QueueFakeConnectionEvents
//
// static
void CordbProcess::CountConnectionsCallback(DWORD id, LPCWSTR pName, void * pUserData)
{
}
//---------------------------------------------------------------------------------------
// Callback to enumerate all the connections in a process.
//
// Arguments:
// id - the connection id.
// pName - name of the connection
// pUserData - an EnumerateConnectionsData
//
// Notes:
// Helper function for code:CordbProcess::QueueFakeConnectionEvents
//
// static
void CordbProcess::EnumerateConnectionsCallback(DWORD id, LPCWSTR pName, void * pUserData)
{
}
//---------------------------------------------------------------------------------------
// Callback from Shim to queue fake Connection events on attach.
//
// Notes:
// See code:ShimProcess::QueueFakeAttachEvents
void CordbProcess::QueueFakeConnectionEvents()
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
}
//
// DispatchRCEvent -- dispatches a previously queued IPC event received
// from the runtime controller. This represents the last amount of processing
// the DI gets to do on an event before giving it to the user.
//
void CordbProcess::DispatchRCEvent()
{
INTERNAL_API_ENTRY(this);
CONTRACTL
{
// This is happening on the RCET thread, so there's no place to propagate an error back up.
NOTHROW;
}
CONTRACTL_END;
_ASSERTE(m_pShim != NULL); // V2 case
//
// Note: the current thread should have the process locked when it
// enters this method.
//
_ASSERTE(ThreadHoldsProcessLock());
// Create/Launch paths already ensured that we had a callback.
_ASSERTE(m_cordb != NULL);
_ASSERTE(m_cordb->m_managedCallback != NULL);
_ASSERTE(m_cordb->m_managedCallback2 != NULL);
_ASSERTE(m_cordb->m_managedCallback3 != NULL);
_ASSERTE(m_cordb->m_managedCallback4 != NULL);
// Bump up the stop count. Either we'll dispatch a managed event,
// or the logic below will decide not to dispatch one and call
// Continue itself. Either way, the stop count needs to go up by
// one...
_ASSERTE(this->GetSyncCompleteRecv());
SetSynchronized(true);
IncStopCount();
// As soon as we call Unlock(), we might get neutered and lose our reference to
// the shim. Grab it now for use later.
RSExtSmartPtr<ShimProcess> pShim(m_pShim);
Unlock();
_ASSERTE(!ThreadHoldsProcessLock());
// We want to stay synced until after the callbacks return. This is b/c we're on the RCET,
// and we may deadlock if we send IPC events on the RCET if we're not synced (see SendIPCEvent for details).
// So here, stopcount=1. The StopContinueHolder bumps it up to 2.
// - If Cordbg calls continue in the callback, that bumps it back down to 1, but doesn't actually continue.
// The holder dtor then bumps it down to 0, doing the real continue.
// - If Cordbg doesn't call continue in the callback, then stopcount stays at 2, holder dtor drops it down to 1,
// and then the holder was just a nop.
// This gives us delayed continues w/ no extra state flags.
// The debugger may call Detach() immediately after it returns from the callback, but before this thread returns
// from this function. Thus after we execute the callbacks, it's possible the CordbProcess object has been neutered.
// Since we're already sycned, the Stop from the holder here is practically a nop that just bumps up a count.
// Create an extra scope for the StopContinueHolder.
{
StopContinueHolder h;
HRESULT hr = h.Init(this);
if (FAILED(hr))
{
CORDBSetUnrecoverableError(this, hr, 0);
}
HRESULT hrCallback = S_OK;
// It's possible a ICorDebugProcess::Detach() may have occurred by now.
{
// @dbgtodo shim: eventually the entire RCET should be considered outside the RS.
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(this);
// Snag the first event off the queue.
// Holder will call Delete, which will invoke virtual Dtor that will release ICD objects.
// Since these are external refs, we want to do it while "outside" the RS.
NewHolder<ManagedEvent> pEvent(pShim->DequeueManagedEvent());
// Normally pEvent shouldn't be NULL, since this method is called when the queue is not empty.
// But due to a race between CordbProcess::Terminate(), CordbWin32EventThread::ExitProcess() and this method
// it is totally possible that the queue has already been cleaned up and we can't expect that event is always available.
if (pEvent != NULL)
{
// Since we need to access a member (m_cordb), protect this block with a
// lock and a check for Neutering (in case process detach has just
// occurred). We'll release the lock around the dispatch later on.
RSLockHolder lockHolder(GetProcessLock());
if (!IsNeutered())
{
#ifdef _DEBUG
// On a debug build, keep track of the last IPC event we dispatched.
m_pDBGLastIPCEventType = pEvent->GetDebugCookie();
#endif
ManagedEvent::DispatchArgs args(m_cordb->m_managedCallback, m_cordb->m_managedCallback2, m_cordb->m_managedCallback3, m_cordb->m_managedCallback4);
{
// Release lock around the dispatch of the event
RSInverseLockHolder inverseLockHolder(GetProcessLock());
EX_TRY
{
// This dispatches almost directly into the user's callbacks.
// It does not update any RS state.
hrCallback = pEvent->Dispatch(args);
}
EX_CATCH_HRESULT(hrCallback);
}
}
}
} // we're now back inside the RS
if (hrCallback == E_NOTIMPL)
{
ContinueInternal(FALSE);
}
} // forces Continue to be called
Lock();
};
#ifdef _DEBUG
//---------------------------------------------------------------------------------------
// Debug-only callback to ensure that an appdomain is not available after the ExitAppDomain event.
//
// Arguments:
// vmAppDomain - appdomain from enumeration
// pUserData - pointer to a DbgAssertAppDomainDeletedData which contains the VMAppDomain that was just deleted.
// notes:
// see code:CordbProcess::DbgAssertAppDomainDeleted for details.
void CordbProcess::DbgAssertAppDomainDeletedCallback(VMPTR_AppDomain vmAppDomain, void * pUserData)
{
DbgAssertAppDomainDeletedData * pCallbackData = reinterpret_cast<DbgAssertAppDomainDeletedData *>(pUserData);
INTERNAL_DAC_CALLBACK(pCallbackData->m_pThis);
VMPTR_AppDomain vmAppDomainDeleted = pCallbackData->m_vmAppDomainDeleted;
CONSISTENCY_CHECK_MSGF((vmAppDomain != vmAppDomainDeleted),
("An ExitAppDomain event was sent for appdomain, but it still shows up in the enumeration.\n vmAppDomain=%p\n",
VmPtrToCookie(vmAppDomainDeleted)));
}
//---------------------------------------------------------------------------------------
// Debug-only helper to Assert that VMPTR is actually removed.
//
// Arguments:
// vmAppDomainDeleted - vmptr of appdomain that we just got exit event for.
// This should not be discoverable from the RS.
//
// Notes:
// See code:IDacDbiInterface#Enumeration for rules that we're asserting.
// Once the exit appdomain event is dispatched, the appdomain should not be discoverable by the RS.
// Else the RS may use the AppDomain* after it's deleted.
// This asserts that the AppDomain* is not discoverable.
//
// Since this is a debug-only function, it should have no side-effects.
void CordbProcess::DbgAssertAppDomainDeleted(VMPTR_AppDomain vmAppDomainDeleted)
{
DbgAssertAppDomainDeletedData callbackData;
callbackData.m_pThis = this;
callbackData.m_vmAppDomainDeleted = vmAppDomainDeleted;
GetDAC()->EnumerateAppDomains(
CordbProcess::DbgAssertAppDomainDeletedCallback,
&callbackData);
}
#endif // _DEBUG
//---------------------------------------------------------------------------------------
// Update state and potentially Dispatch a single event.
//
// Arguments:
// pEvent - non-null pointer to debug event.
// pCallback1 - callback object to dispatch on (for V1 callbacks)
// pCallback2 - 2nd callback object to dispatch on (for new V2 callbacks)
// pCallback3 - 3rd callback object to dispatch on (for new V4 callbacks)
//
//
// Returns:
// Nothing. Throws on error.
//
// Notes:
// Generally, this will dispatch exactly 1 callback. It may dispatch 0 callbacks if there is an error
// or in other corner cases (documented within the dispatch code below).
// Errors could occur because:
// - the event is corrupted (exceptional case)
// - the RS is corrupted / OOM (exceptional case)
// Exception errors here will propagate back to the Filter() call, and there's not really anything
// a debugger can do about an error here (perhaps report it to the user).
// Errors must leave IcorDebug in a consistent state.
//
// This is dispatched directly on the Win32Event Thread in response to calling Filter.
// Therefore, this can't send any IPC events (Not an issue once everything is DAC-ized).
// A V2 shim can provide a proxy calllack that takes these events and queues them and
// does the real dispatch to the user to emulate V2 semantics.
//
#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
void CordbProcess::RawDispatchEvent(
DebuggerIPCEvent * pEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback1,
ICorDebugManagedCallback2 * pCallback2,
ICorDebugManagedCallback3 * pCallback3,
ICorDebugManagedCallback4 * pCallback4)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
// We start off with the lock, and we'll toggle it.
_ASSERTE(ThreadHoldsProcessLock());
//
// Call StartEventDispatch to true to guard against calls to Continue()
// from within the user's callback. We need Continue() to behave a little
// bit differently in such a case.
//
// Also note that Win32EventThread::ExitProcess will take the lock and free all
// events in the queue. (the current event is already off the queue, so
// it will be ok). But we can't do the EP callback in the middle of this dispatch
// so if this flag is set, EP will wait on the miscWaitEvent (which will
// get set in FlushQueuedEvents when we return from here) and let us finish here.
//
StartEventDispatch(pEvent->type);
// Keep strong references to these objects in case a callback deletes them from underneath us.
RSSmartPtr<CordbAppDomain> pAppDomain;
CordbThread * pThread = NULL;
// Get thread that this event is on. In attach scenarios, this may be the first time ICorDebug has seen this thread.
if (!pEvent->vmThread.IsNull())
{
pThread = LookupOrCreateThread(pEvent->vmThread);
}
if (!pEvent->vmAppDomain.IsNull())
{
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->vmAppDomain));
}
DWORD dwVolatileThreadId = 0;
if (pThread != NULL)
{
dwVolatileThreadId = pThread->GetUniqueId();
}
//
// Update the app domain that this thread lives in.
//
if ((pThread != NULL) && (pAppDomain != NULL))
{
// It shouldn't be possible for us to see an exited AppDomain here
_ASSERTE( !pAppDomain->IsNeutered() );
pThread->m_pAppDomain = pAppDomain;
}
_ASSERTE(pEvent != NULL);
_ASSERTE(pCallback1 != NULL);
_ASSERTE(pCallback2 != NULL);
_ASSERTE(pCallback3 != NULL);
_ASSERTE(pCallback4 != NULL);
STRESS_LOG1(LF_CORDB, LL_EVERYTHING, "Pre-Dispatch IPC event: %s\n", IPCENames::GetName(pEvent->type));
switch (pEvent->type & DB_IPCE_TYPE_MASK)
{
case DB_IPCE_CREATE_PROCESS:
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->CreateProcess(static_cast<ICorDebugProcess*> (this));
}
break;
case DB_IPCE_BREAKPOINT:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// Find the breakpoint object on this side.
CordbBreakpoint *pBreakpoint = NULL;
// We've found cases out in the wild where we get this event on a thread we don't recognize.
// We're not sure how this happens. Add a runtime check to protect ourselves to avoid the
// an AV. We still assert because this should not be happening.
// It likely means theres some issue where we failed to send a CreateThread notification.
TargetConsistencyCheck(pThread != NULL);
pBreakpoint = pAppDomain->m_breakpoints.GetBase(LsPtrToCookie(pEvent->BreakpointData.breakpointToken));
if (pBreakpoint != NULL)
{
ICorDebugBreakpoint * pIBreakpoint = CordbBreakpointToInterface(pBreakpoint);
_ASSERTE(pIBreakpoint != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, bp=0x%p", pThread, pBreakpoint);
pCallback1->Breakpoint(pAppDomain, pThread, pIBreakpoint);
}
}
}
break;
case DB_IPCE_BEFORE_GARBAGE_COLLECTION:
{
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->BeforeGarbageCollection(static_cast<ICorDebugProcess*>(this));
}
break;
}
case DB_IPCE_AFTER_GARBAGE_COLLECTION:
{
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->AfterGarbageCollection(static_cast<ICorDebugProcess*>(this));
}
break;
}
#ifdef FEATURE_DATABREAKPOINT
case DB_IPCE_DATA_BREAKPOINT:
{
_ASSERTE(pThread != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback4->DataBreakpoint(static_cast<ICorDebugProcess*>(this), pThread, reinterpret_cast<BYTE*>(&(pEvent->DataBreakpointData.context)), sizeof(CONTEXT));
}
break;
}
break;
#endif
case DB_IPCE_USER_BREAKPOINT:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: user breakpoint.\n",
GetCurrentThreadId());
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
_ASSERTE(pThread->m_pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->Break(pThread->m_pAppDomain, pThread);
}
}
break;
case DB_IPCE_STEP_COMPLETE:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: step complete.\n",
GetCurrentThreadId());
PREFIX_ASSUME(pThread != NULL);
CordbStepper * pStepper = m_steppers.GetBase(LsPtrToCookie(pEvent->StepData.stepperToken));
// It's possible the stepper is NULL if:
// - event X & step-complete are both in the queue
// - during dispatch for event X, Cordbg cancels the stepper (thus removing it from m_steppers)
// - the Step-Complete still stays in the queue, and so we're here, but out stepper's been removed.
// (This could happen for breakpoints too)
// Don't dispatch a callback if the stepper is NULL.
if (pStepper != NULL)
{
RSSmartPtr<CordbStepper> pRef(pStepper);
pStepper->m_active = false;
m_steppers.RemoveBase((ULONG_PTR)pStepper->m_id);
{
_ASSERTE(pThread->m_pAppDomain != NULL);
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thrad=0x%p, stepper=0x%p", pThread, pStepper);
pCallback1->StepComplete(pThread->m_pAppDomain, pThread, pStepper, pEvent->StepData.reason);
}
// implicit Release on pRef
}
}
break;
case DB_IPCE_EXCEPTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: exception.\n",
GetCurrentThreadId());
_ASSERTE(pAppDomain != NULL);
// For some exceptions very early in startup (eg, TypeLoad), this may have occurred before we
// even executed jitted code on the thread. We may have not received a CreateThread yet.
// In V2, we detected this and sent a LogMessage on a random thread.
// In V3, we lazily create the CordbThread objects (possibly before the CreateThread event),
// and so we know we should have one.
_ASSERTE(pThread != NULL);
pThread->SetExInfo(pEvent->Exception.vmExceptionHandle);
_ASSERTE(pThread->m_pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->Exception(pThread->m_pAppDomain, pThread, !pEvent->Exception.firstChance);
}
}
break;
case DB_IPCE_SYNC_COMPLETE:
_ASSERTE(!"Should have never queued a sync complete pEvent.");
break;
case DB_IPCE_THREAD_ATTACH:
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "RCET::DRCE: thread attach : ID=%x.\n", dwVolatileThreadId);
TargetConsistencyCheck(pThread != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "thread=0x%p", pThread);
pCallback1->CreateThread(pAppDomain, pThread);
}
}
break;
case DB_IPCE_THREAD_DETACH:
{
STRESS_LOG2(LF_CORDB, LL_INFO100, "[%x] RCET::HRCE: thread detach : ID=%x \n",
GetCurrentThreadId(), dwVolatileThreadId);
// If the runtime thread never entered managed code, there
// won't be a CordbThread, and CreateThread was never
// called, so don't bother calling ExitThread.
if (pThread != NULL)
{
AddToNeuterOnContinueList(pThread);
RSSmartPtr<CordbThread> pRefThread(pThread);
_ASSERTE(pAppDomain != NULL);
// A thread is reported as dead before we get the exit event.
// See code:IDacDbiInterface#IsThreadMarkedDead for the invariant being asserted here.
TargetConsistencyCheck(pThread->IsThreadDead());
// Enforce the enumeration invariants (see code:IDacDbiInterface#Enumeration)that the thread is not discoverable.
INDEBUG(pThread->DbgAssertThreadDeleted());
// Remove the thread from the hash. If we've removed it from the hash, we really should
// neuter it ... but that causes test failures.
// We'll neuter it in continue.
m_userThreads.RemoveBase(VmPtrToCookie(pThread->m_vmThreadToken));
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HRCE: sending thread detach.\n", GetCurrentThreadId()));
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->ExitThread(pAppDomain, pThread);
}
// Implicit release on thread & pAppDomain
}
}
break;
case DB_IPCE_METADATA_UPDATE:
{
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->MetadataUpdateData.vmDomainAssembly);
pModule->RefreshMetaData();
}
break;
case DB_IPCE_LOAD_MODULE:
{
_ASSERTE (pAppDomain != NULL);
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->LoadModuleData.vmDomainAssembly);
{
pModule->SetLoadEventContinueMarker();
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LoadModule(pAppDomain, pModule);
}
}
break;
case DB_IPCE_CREATE_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection change %d \n",
pEvent->CreateConnection.connectionId);
// pass back the connection id and the connection name.
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->CreateConnection(
this,
pEvent->CreateConnection.connectionId,
const_cast<WCHAR*> (pEvent->CreateConnection.wzConnectionName.GetString()));
}
break;
case DB_IPCE_DESTROY_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection destroyed %d \n",
pEvent->ConnectionChange.connectionId);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->DestroyConnection(this, pEvent->ConnectionChange.connectionId);
}
break;
case DB_IPCE_CHANGE_CONNECTION:
{
STRESS_LOG1(LF_CORDB, LL_INFO100,
"RCET::HRCE: Connection changed %d \n",
pEvent->ConnectionChange.connectionId);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->ChangeConnection(this, pEvent->ConnectionChange.connectionId);
}
break;
case DB_IPCE_UNLOAD_MODULE:
{
STRESS_LOG3(LF_CORDB, LL_INFO100, "RCET::HRCE: unload module on thread %#x Mod:0x%x AD:0x%08x\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->UnloadModuleData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain));
PREFIX_ASSUME (pAppDomain != NULL);
CordbModule *module = pAppDomain->LookupOrCreateModule(pEvent->UnloadModuleData.vmDomainAssembly);
if (module == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Already unloaded Module - continue()ing!" ));
break;
}
_ASSERTE(module != NULL);
INDEBUG(module->DbgAssertModuleDeleted());
// The appdomain we're unloading in must be the appdomain we were loaded in. Otherwise, we've got mismatched
// module and appdomain pointers. Bugs 65943 & 81728.
_ASSERTE(pAppDomain == module->GetAppDomain());
// Ensure the module gets neutered once we call continue.
AddToNeuterOnContinueList(module); // throws
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->UnloadModule(pAppDomain, module);
}
pAppDomain->m_modules.RemoveBase(VmPtrToCookie(pEvent->UnloadModuleData.vmDomainAssembly));
}
break;
case DB_IPCE_LOAD_CLASS:
{
CordbClass *pClass = NULL;
LOG((LF_CORDB, LL_INFO10000,
"RCET::HRCE: load class on thread %#x Tok:0x%08x Mod:0x%08x Asm:0x%08x AD:0x%08x\n",
dwVolatileThreadId,
pEvent->LoadClass.classMetadataToken,
VmPtrToCookie(pEvent->LoadClass.vmDomainAssembly),
LsPtrToCookie(pEvent->LoadClass.classDebuggerAssemblyToken),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
CordbModule* pModule = pAppDomain->LookupOrCreateModule(pEvent->LoadClass.vmDomainAssembly);
if (pModule == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Load Class on not-loaded Module - continue()ing!" ));
break;
}
_ASSERTE(pModule != NULL);
BOOL fDynamic = pModule->IsDynamic();
// If this is a class load in a dynamic module, the metadata has become invalid.
if (fDynamic)
{
pModule->RefreshMetaData();
}
hr = pModule->LookupOrCreateClass(pEvent->LoadClass.classMetadataToken, &pClass);
_ASSERTE(SUCCEEDED(hr) == (pClass != NULL));
IfFailThrow(hr);
// Prevent class load from being sent twice.
// @dbgtodo - Microsoft, cordbclass: this is legacy. Can this really happen? Investigate as we dac-ize CordbClass.
if (pClass->LoadEventSent())
{
// Dynamic modules are dynamic at the module level -
// you can't add a new version of a class once the module
// is baked.
// EnC adds completely new classes.
// There shouldn't be any other way to send multiple
// ClassLoad events.
// Except that there are race conditions between loading
// an appdomain, and loading a class, so if we get the extra
// class load, we should ignore it.
break; //out of the switch statement
}
pClass->SetLoadEventSent(TRUE);
if (pClass != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LoadClass(pAppDomain, pClass);
}
}
break;
case DB_IPCE_UNLOAD_CLASS:
{
LOG((LF_CORDB, LL_INFO10000,
"RCET::HRCE: unload class on thread %#x Tok:0x%08x Mod:0x%08x AD:0x%08x\n",
dwVolatileThreadId,
pEvent->UnloadClass.classMetadataToken,
VmPtrToCookie(pEvent->UnloadClass.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
// get the appdomain object
_ASSERTE (pAppDomain != NULL);
CordbModule *pModule = pAppDomain->LookupOrCreateModule(pEvent->UnloadClass.vmDomainAssembly);
if (pModule == NULL)
{
LOG((LF_CORDB, LL_INFO100, "Unload Class on not-loaded Module - continue()ing!" ));
break;
}
_ASSERTE(pModule != NULL);
CordbClass *pClass = pModule->LookupClass(pEvent->UnloadClass.classMetadataToken);
if (pClass != NULL && !pClass->HasBeenUnloaded())
{
pClass->SetHasBeenUnloaded(true);
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->UnloadClass(pAppDomain, pClass);
}
}
break;
case DB_IPCE_FIRST_LOG_MESSAGE:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
const WCHAR * pszContent = pEvent->FirstLogMessage.szContent.GetString();
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LogMessage(
pAppDomain,
pThread,
pEvent->FirstLogMessage.iLevel,
const_cast<WCHAR*> (pEvent->FirstLogMessage.szCategory.GetString()),
const_cast<WCHAR*> (pszContent));
}
}
break;
case DB_IPCE_LOGSWITCH_SET_MESSAGE:
{
LOG((LF_CORDB, LL_INFO10000,
"[%x] RCET::DRCE: Log Switch Setting Message.\n",
GetCurrentThreadId()));
_ASSERTE(pThread != NULL);
const WCHAR *pstrLogSwitchName = pEvent->LogSwitchSettingMessage.szSwitchName.GetString();
const WCHAR *pstrParentName = pEvent->LogSwitchSettingMessage.szParentSwitchName.GetString();
// from the thread object get the appdomain object
_ASSERTE(pAppDomain == pThread->m_pAppDomain);
_ASSERTE (pAppDomain != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->LogSwitch(
pAppDomain,
pThread,
pEvent->LogSwitchSettingMessage.iLevel,
pEvent->LogSwitchSettingMessage.iReason,
const_cast<WCHAR*> (pstrLogSwitchName),
const_cast<WCHAR*> (pstrParentName));
}
}
break;
case DB_IPCE_CUSTOM_NOTIFICATION:
{
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// determine first whether custom notifications for this type are enabled -- if not
// we just return without doing anything.
CordbClass * pNotificationClass = LookupClass(pAppDomain,
pEvent->CustomNotification.vmDomainAssembly,
pEvent->CustomNotification.classToken);
// if the class is NULL, that means the debugger never enabled notifications for it. Otherwise,
// the CordbClass instance would already have been created when the notifications were
// enabled.
if ((pNotificationClass != NULL) && pNotificationClass->CustomNotificationsEnabled())
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback3->CustomNotification(pThread, pAppDomain);
}
}
break;
case DB_IPCE_CREATE_APP_DOMAIN:
{
STRESS_LOG2(LF_CORDB, LL_INFO100,
"RCET::HRCE: create appdomain on thread %#x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->vmAppDomain));
// Enumerate may have prepopulated the appdomain, so check if it already exists.
// Either way, still send the CreateEvent. (We don't want to skip the Create event
// just because the debugger did an enumerate)
// We remove AppDomains from the hash as soon as they are exited.
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->AppDomainData.vmAppDomain));
_ASSERTE(pAppDomain != NULL); // throws on failure
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->CreateAppDomain(this, pAppDomain);
}
}
break;
case DB_IPCE_EXIT_APP_DOMAIN:
{
STRESS_LOG2(LF_CORDB, LL_INFO100, "RCET::HRCE: exit appdomain on thread %#x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->vmAppDomain));
// In debug-only builds, assert that the appdomain is indeed deleted and not discoverable.
INDEBUG(DbgAssertAppDomainDeleted(pEvent->vmAppDomain));
// If we get an ExitAD message for which we have no AppDomain, then ignore it.
// This can happen if an AD gets torn down very early (before the LS AD is to the
// point that it can be published).
// This could also happen if we attach a debugger right before the Exit event is sent.
// In this case, the debuggee is no longer publishing the appdomain.
if (pAppDomain == NULL)
{
break;
}
_ASSERTE (pAppDomain != NULL);
// See if this is the default AppDomain exiting. This should only happen very late in
// the shutdown cycle, and so we shouldn't do anything significant with m_pDefaultDomain==NULL.
// We should try and remove m_pDefaultDomain entirely since we can't count on it always existing.
if (pAppDomain == m_pDefaultAppDomain)
{
m_pDefaultAppDomain = NULL;
}
// Update any threads which were last seen in this AppDomain. We don't
// get any notification when a thread leaves an AppDomain, so our idea
// of what AppDomain the thread is in may be out of date.
UpdateThreadsForAdUnload( pAppDomain );
// This will still maintain weak references so we could call Continue.
AddToNeuterOnContinueList(pAppDomain);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->ExitAppDomain(this, pAppDomain);
}
// @dbgtodo appdomain: This should occur before the callback.
// Even after ExitAppDomain, the outside world will want to continue calling
// Continue (and thus they may need to call CordbAppDomain::GetProcess(), which Neutering
// would clear). Thus we can't neuter yet.
// Remove this app domain. This means any attempt to lookup the AppDomain
// will fail (which we do at the top of this method). Since any threads (incorrectly) referring
// to this AppDomain have been moved to the default AppDomain, no one should be
// interested in looking this AppDomain up anymore.
m_appDomains.RemoveBase(VmPtrToCookie(pEvent->vmAppDomain));
}
break;
case DB_IPCE_LOAD_ASSEMBLY:
{
LOG((LF_CORDB, LL_INFO100,
"RCET::HRCE: load assembly on thread %#x Asm:0x%08x AD:0x%08x \n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->AssemblyData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
// Determine if this Assembly is cached.
CordbAssembly * pAssembly = pAppDomain->LookupOrCreateAssembly(pEvent->AssemblyData.vmDomainAssembly);
_ASSERTE(pAssembly != NULL); // throws on error
// If created, or have, an Assembly, notify callback.
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->LoadAssembly(pAppDomain, pAssembly);
}
}
break;
case DB_IPCE_UNLOAD_ASSEMBLY:
{
LOG((LF_CORDB, LL_INFO100, "RCET::DRCE: unload assembly on thread %#x Asm:0x%x AD:0x%x\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->AssemblyData.vmDomainAssembly),
VmPtrToCookie(pEvent->vmAppDomain)));
_ASSERTE (pAppDomain != NULL);
CordbAssembly * pAssembly = pAppDomain->LookupOrCreateAssembly(pEvent->AssemblyData.vmDomainAssembly);
if (pAssembly == NULL)
{
// No assembly. This could happen if we attach right before an unload event is sent.
return;
}
_ASSERTE(pAssembly != NULL);
INDEBUG(pAssembly->DbgAssertAssemblyDeleted());
// Ensure the assembly gets neutered when we call continue.
AddToNeuterOnContinueList(pAssembly); // throws
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->UnloadAssembly(pAppDomain, pAssembly);
}
pAppDomain->RemoveAssemblyFromCache(pEvent->AssemblyData.vmDomainAssembly);
}
break;
case DB_IPCE_FUNC_EVAL_COMPLETE:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::DRCE: func eval complete.\n"));
CordbEval *pEval = NULL;
{
pEval = pEvent->FuncEvalComplete.funcEvalKey.UnWrapAndRemove(this);
if (pEval == NULL)
{
_ASSERTE(!"Bogus FuncEval handle in IPC block.");
// Bogus handle in IPC block.
break;
}
}
_ASSERTE(pEval != NULL);
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
CONSISTENCY_CHECK_MSGF(pEval->m_DbgAppDomainStarted == pAppDomain,
("AppDomain changed from Func-Eval. Eval=%p, Started=%p, Now=%p\n",
pEval, pEval->m_DbgAppDomainStarted, (void*) pAppDomain));
// Hold the data about the result in the CordbEval for later.
pEval->m_complete = true;
pEval->m_successful = !!pEvent->FuncEvalComplete.successful;
pEval->m_aborted = !!pEvent->FuncEvalComplete.aborted;
pEval->m_resultAddr = pEvent->FuncEvalComplete.resultAddr;
pEval->m_vmObjectHandle = pEvent->FuncEvalComplete.vmObjectHandle;
pEval->m_resultType = pEvent->FuncEvalComplete.resultType;
pEval->m_resultAppDomainToken = pEvent->FuncEvalComplete.vmAppDomain;
CordbAppDomain *pResultAppDomain = LookupOrCreateAppDomain(pEvent->FuncEvalComplete.vmAppDomain);
_ASSERTE(OutstandingEvalCount() > 0);
DecrementOutstandingEvalCount();
CONSISTENCY_CHECK_MSGF(pEval->m_DbgAppDomainStarted == pAppDomain,
("AppDomain changed from Func-Eval. Eval=%p, Started=%p, Now=%p\n",
pEval, pEval->m_DbgAppDomainStarted, (void*) pAppDomain));
// If we did this func eval with this thread stopped at an excpetion, then we need to pretend as if we
// really didn't continue from the exception, since, of course, we really didn't on the Left Side.
if (pEval->IsEvalDuringException())
{
pThread->SetExInfo(pEval->m_vmThreadOldExceptionHandle);
}
bool fEvalCompleted = pEval->m_successful || pEval->m_aborted;
// If a CallFunction() is aborted, the LHS may not complete the abort
// immediately and hence we cant do a SendCleanup() at that point. Also,
// the debugger may (incorrectly) release the CordbEval before this
// DB_IPCE_FUNC_EVAL_COMPLETE event is received. Hence, we maintain an
// extra ref-count to determine when this can be done.
// Note that this can cause a two-way DB_IPCE_FUNC_EVAL_CLEANUP event
// to be sent. Hence, it has to be done before the Continue (see issue 102745).
// Note that if the debugger has already (incorrectly) released the CordbEval,
// pEval will be pointing to garbage and should not be used by the debugger.
if (fEvalCompleted)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, eval=0x%p. (Complete)", pThread, pEval);
pCallback1->EvalComplete(pResultAppDomain, pThread, pEval);
}
else
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "pThread=0x%p, eval=0x%p. (Exception)", pThread, pEval);
pCallback1->EvalException(pResultAppDomain, pThread, pEval);
}
// This release may send an DB_IPCE_FUNC_EVAL_CLEANUP IPC event. That's ok b/c
// we're still synced even if if Continue was called inside the callback.
// That's because the StopContinueHolder bumped up the stopcount.
// Corresponding AddRef() in CallFunction().
// @todo - this is leaked if we don't get an EvalComplete event (eg, process exits with
// in middle of func-eval).
pEval->Release();
}
break;
case DB_IPCE_NAME_CHANGE:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::HRCE: Name Change %d 0x%p\n",
dwVolatileThreadId,
VmPtrToCookie(pEvent->NameChange.vmAppDomain)));
pThread = NULL;
pAppDomain.Clear();
if (pEvent->NameChange.eventType == THREAD_NAME_CHANGE)
{
// Lookup the CordbThread that matches this runtime thread.
if (!pEvent->NameChange.vmThread.IsNull())
{
pThread = LookupOrCreateThread(pEvent->NameChange.vmThread);
}
}
else
{
_ASSERTE (pEvent->NameChange.eventType == APP_DOMAIN_NAME_CHANGE);
pAppDomain.Assign(LookupOrCreateAppDomain(pEvent->NameChange.vmAppDomain));
if (pAppDomain)
{
pAppDomain->InvalidateName();
}
}
if (pThread || pAppDomain)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback1->NameChange(pAppDomain, pThread);
}
}
break;
case DB_IPCE_UPDATE_MODULE_SYMS:
{
RSExtSmartPtr<IStream> pStream;
// Find the app domain the module lives in.
_ASSERTE (pAppDomain != NULL);
// Find the Right Side module for this module.
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->UpdateModuleSymsData.vmDomainAssembly);
_ASSERTE(pModule != NULL);
// This is a legacy event notification for updated PDBs.
// Creates a new IStream object. Ownership is handed off via callback.
IDacDbiInterface::SymbolFormat symFormat = pModule->GetInMemorySymbolStream(&pStream);
// We shouldn't get this event if there aren't PDB symbols waiting. Specifically we don't want
// to incur the cost of copying over ILDB symbols here without the debugger asking for them.
// Eventually we may remove this callback as well and always rely on explicit requests.
_ASSERTE(symFormat == IDacDbiInterface::kSymbolFormatPDB);
if (symFormat == IDacDbiInterface::kSymbolFormatPDB)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
_ASSERTE(pStream != NULL); // Shouldn't send the event if we don't have a stream.
pCallback1->UpdateModuleSymbols(pAppDomain, pModule, pStream);
}
}
break;
case DB_IPCE_MDA_NOTIFICATION:
{
RSInitHolder<CordbMDA> pMDA(new CordbMDA(this, &pEvent->MDANotification)); // throws
// Ctor leaves both internal + ext Ref at 0, adding to neuter list bumps int-ref up to 1.
// Neutering will dump it back down to zero.
this->AddToNeuterOnExitList(pMDA);
// We bump up and down the external ref so that even if the callback doensn't touch the refs,
// our Ext-Release here will still cause a 1->0 ext-ref transition, which will get it
// swept on the neuter list.
RSExtSmartPtr<ICorDebugMDA> pExternalMDARef;
pMDA.TransferOwnershipExternal(&pExternalMDARef);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->MDANotification(
this,
pThread, // may be null
pExternalMDARef);
// pExternalMDARef's dtor will do an external release,
// which is very significant because it may be the one that does the 1->0 ext ref transition,
// which may mean cause the "NeuterAtWill" bit to get flipped on this CordbMDA object.
// Since this is an external release, do it in the PUBLIC_CALLBACK scope.
pExternalMDARef.Clear();
}
break;
}
case DB_IPCE_CONTROL_C_EVENT:
{
hr = S_FALSE;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
hr = pCallback1->ControlCTrap((ICorDebugProcess*) this);
}
}
break;
// EnC Remap opportunity
case DB_IPCE_ENC_REMAP:
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: EnC Remap!.\n",
GetCurrentThreadId()));
_ASSERTE(NULL != pAppDomain);
CordbModule * pModule = pAppDomain->LookupOrCreateModule(pEvent->EnCRemap.vmDomainAssembly);
PREFIX_ASSUME(pModule != NULL);
CordbFunction * pCurFunction = NULL;
CordbFunction * pResumeFunction = NULL;
// lookup the version of the function that we are mapping from
// this is the one that is currently running
pCurFunction = pModule->LookupOrCreateFunction(
pEvent->EnCRemap.funcMetadataToken, pEvent->EnCRemap.currentVersionNumber);
// lookup the version of the function that we are mapping to
// it will always be the most recent
pResumeFunction = pModule->LookupOrCreateFunction(
pEvent->EnCRemap.funcMetadataToken, pEvent->EnCRemap.resumeVersionNumber);
_ASSERTE(pCurFunction->GetEnCVersionNumber() < pResumeFunction->GetEnCVersionNumber());
RSSmartPtr<CordbFunction> pRefCurFunction(pCurFunction);
RSSmartPtr<CordbFunction> pRefResumeFunction(pResumeFunction);
// Verify we're not about to overwrite an outstanding remap IP
// This should only be set while a remap opportunity is being handled,
// and cleared (by CordbThread::MarkStackFramesDirty) on Continue.
// We want to be absolutely sure we don't accidentally keep a stale pointer
// around because it would point to arbitrary stack space in the CLR potentially
// leading to stack corruption.
_ASSERTE( pThread->m_EnCRemapFunctionIP == NULL );
// Stash the address of the remap IP buffer. This indicates that calling
// RemapFunction is valid and provides a communications channel between the RS
// and LS for the remap IL offset.
pThread->m_EnCRemapFunctionIP = pEvent->EnCRemap.resumeILOffset;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->FunctionRemapOpportunity(
pAppDomain,
pThread,
pCurFunction,
pResumeFunction,
(ULONG32)pEvent->EnCRemap.currentILOffset);
}
// Implicit release on pCurFunction and pResumeFunction.
}
break;
// EnC Remap complete
case DB_IPCE_ENC_REMAP_COMPLETE:
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::DRCE: EnC Remap Complete!.\n",
GetCurrentThreadId()));
_ASSERTE(NULL != pAppDomain);
CordbModule* pModule = pAppDomain->LookupOrCreateModule(pEvent->EnCRemap.vmDomainAssembly);
PREFIX_ASSUME(pModule != NULL);
// Find the function we're remapping to, which must be the latest version
CordbFunction *pRemapFunction=
pModule->LookupFunctionLatestVersion(pEvent->EnCRemapComplete.funcMetadataToken);
PREFIX_ASSUME(pRemapFunction != NULL);
// Dispatch the FunctionRemapComplete callback
RSSmartPtr<CordbFunction> pRef(pRemapFunction);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE(this, pLockHolder, pEvent);
pCallback2->FunctionRemapComplete(pAppDomain, pThread, pRemapFunction);
}
// Implicit release on pRemapFunction via holder
}
break;
case DB_IPCE_BREAKPOINT_SET_ERROR:
{
LOG((LF_CORDB, LL_INFO1000, "RCET::DRCE: breakpoint set error.\n"));
RSSmartPtr<CordbBreakpoint> pRef;
_ASSERTE(pThread != NULL);
_ASSERTE(pAppDomain != NULL);
// Find the breakpoint object on this side.
CordbBreakpoint * pBreakpoint = NULL;
if (pThread == NULL)
{
// We've found cases out in the wild where we get this event on a thread we don't recognize.
// We're not sure how this happens. Add a runtime check to protect ourselves to avoid the
// an AV. We still assert because this should not be happening.
// It likely means theres some issue where we failed to send a CreateThread notification.
STRESS_LOG1(LF_CORDB, LL_INFO1000, "BreakpointSetError on unrecognized thread. %p\n", pBreakpoint);
_ASSERTE(!"Missing thread on bp set error");
break;
}
pBreakpoint = pAppDomain->m_breakpoints.GetBase(LsPtrToCookie(pEvent->BreakpointSetErrorData.breakpointToken));
if (pBreakpoint != NULL)
{
ICorDebugBreakpoint * pIBreakpoint = CordbBreakpointToInterface(pBreakpoint);
_ASSERTE(pIBreakpoint != NULL);
{
PUBLIC_CALLBACK_IN_THIS_SCOPE2(this, pLockHolder, pEvent, "thread=0x%p, bp=0x%p", pThread, pBreakpoint);
pCallback1->BreakpointSetError(pAppDomain, pThread, pIBreakpoint, 0);
}
}
// Implicit release on pRef.
}
break;
case DB_IPCE_EXCEPTION_CALLBACK2:
{
STRESS_LOG4(LF_CORDB, LL_INFO100,
"RCET::DRCE: Exception2 0x%p 0x%X 0x%X 0x%X\n",
pEvent->ExceptionCallback2.framePointer.GetSPValue(),
pEvent->ExceptionCallback2.nOffset,
pEvent->ExceptionCallback2.eventType,
pEvent->ExceptionCallback2.dwFlags
);
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This could be a thread that
// has never run any managed code, so let's just ignore the exception. We should have
// already sent a log message about this situation for the EXCEPTION callback above.
_ASSERTE( pEvent->ExceptionCallback2.eventType == DEBUG_EXCEPTION_UNHANDLED );
break;
}
pThread->SetExInfo(pEvent->ExceptionCallback2.vmExceptionHandle);
//
// Send all the information back to the debugger.
//
RSSmartPtr<CordbFrame> pFrame;
FramePointer fp = pEvent->ExceptionCallback2.framePointer;
if (fp != LEAF_MOST_FRAME)
{
// The interface forces us to to pass a FramePointer via an ICorDebugFrame.
// However, we can't get a real ICDFrame without a stackwalk, and we don't
// want to do a stackwalk now. so pass a netuered proxy frame. The shim
// can map this to a real frame.
// See comments at CordbPlaceHolderFrame class for details.
pFrame.Assign(new CordbPlaceholderFrame(this, fp));
}
CorDebugExceptionCallbackType type = pEvent->ExceptionCallback2.eventType;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE3(this, pLockHolder, pEvent, "pThread=0x%p, frame=%p, type=%d", pThread, (ICorDebugFrame*) pFrame, type);
hr = pCallback2->Exception(
pThread->m_pAppDomain,
pThread,
pFrame,
(ULONG32)(pEvent->ExceptionCallback2.nOffset),
type,
pEvent->ExceptionCallback2.dwFlags);
}
}
break;
case DB_IPCE_EXCEPTION_UNWIND:
{
STRESS_LOG2(LF_CORDB, LL_INFO100,
"RCET::DRCE: Exception Unwind 0x%X 0x%X\n",
pEvent->ExceptionCallback2.eventType,
pEvent->ExceptionCallback2.dwFlags
);
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This probably should never
// happen (if it's unwinding, then we expect a managed frame on the stack, and so we should
// know about the thread), but if it does fall back to ignoring the exception.
_ASSERTE( !"Got unwind event for unknown exception" );
break;
}
//
// Send all the information back to the debugger.
//
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "pThread=0x%p", pThread);
hr = pCallback2->ExceptionUnwind(
pThread->m_pAppDomain,
pThread,
pEvent->ExceptionUnwind.eventType,
pEvent->ExceptionUnwind.dwFlags);
}
}
break;
case DB_IPCE_INTERCEPT_EXCEPTION_COMPLETE:
{
STRESS_LOG0(LF_CORDB, LL_INFO100, "RCET::DRCE: Exception Interception Complete.\n");
if (pThread == NULL)
{
// We've got an exception on a thread we don't know about. This probably should never
// happen (if it's unwinding, then we expect a managed frame on the stack, and so we should
// know about the thread), but if it does fall back to ignoring the exception.
_ASSERTE( !"Got complete event for unknown exception" );
break;
}
//
// Tell the debugger that the exception has been intercepted. This is similar to the
// notification we give when we start unwinding for a non-intercepted exception, except that the
// interception has been completed at this point, which means that we are conceptually at the end
// of the second pass.
//
{
PUBLIC_CALLBACK_IN_THIS_SCOPE1(this, pLockHolder, pEvent, "pThread=0x%p", pThread);
hr = pCallback2->ExceptionUnwind(
pThread->m_pAppDomain,
pThread,
DEBUG_EXCEPTION_INTERCEPTED,
0);
}
}
break;
#ifdef TEST_DATA_CONSISTENCY
case DB_IPCE_TEST_CRST:
{
EX_TRY
{
// the left side has signaled that we should test whether pEvent->TestCrstData.vmCrst is held
GetDAC()->TestCrst(pEvent->TestCrstData.vmCrst);
}
EX_CATCH_HRESULT(hr);
if (pEvent->TestCrstData.fOkToTake)
{
_ASSERTE(hr == S_OK);
if (hr != S_OK)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
else // the lock was already held
{
// see if we threw because the lock was held
_ASSERTE(hr == CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
if (hr != CORDBG_E_PROCESS_NOT_SYNCHRONIZED)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
}
break;
case DB_IPCE_TEST_RWLOCK:
{
EX_TRY
{
// the left side has signaled that we should test whether pEvent->TestRWLockData.vmRWLock is held
GetDAC()->TestRWLock(pEvent->TestRWLockData.vmRWLock);
}
EX_CATCH_HRESULT(hr);
if (pEvent->TestRWLockData.fOkToTake)
{
_ASSERTE(hr == S_OK);
if (hr != S_OK)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
else // the lock was already held
{
// see if we threw because the lock was held
_ASSERTE(hr == CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
if (hr != CORDBG_E_PROCESS_NOT_SYNCHRONIZED)
{
// we want to catch this in retail builds too
ThrowHR(E_FAIL);
}
}
}
break;
#endif
default:
_ASSERTE(!"Unknown event");
LOG((LF_CORDB, LL_INFO1000,
"[%x] RCET::HRCE: Unknown event: 0x%08x\n",
GetCurrentThreadId(), pEvent->type));
}
FinishEventDispatch();
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif
//---------------------------------------------------------------------------------------
// Callback for prepopulating threads.
//
// Arugments:
// vmThread - thread as part of the eunmeration.
// pUserData - data supplied with callback. It's a CordbProcess* object.
//
// static
void CordbProcess::ThreadEnumerationCallback(VMPTR_Thread vmThread, void * pUserData)
{
CordbProcess * pThis = reinterpret_cast<CordbProcess *> (pUserData);
INTERNAL_DAC_CALLBACK(pThis);
STRESS_LOG0(LF_CORDB, LL_INFO1000, "ThreadEnumerationCallback()\n");
// Do lookup / lazy-create.
pThis->LookupOrCreateThread(vmThread);
}
//---------------------------------------------------------------------------------------
// Fully build up the CordbThread cache to match VM state.
void CordbProcess::PrepopulateThreadsOrThrow()
{
RSLockHolder lockHolder(GetProcessLock());
if (IsDacInitialized())
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "PrepopulateThreadsOrThrow()\n");
GetDAC()->EnumerateThreads(ThreadEnumerationCallback, this);
}
}
//---------------------------------------------------------------------------------------
// Create a Thread enumerator
//
// Arguments:
// pOwnerObj - object (a CordbProcess or CordbThread) that will own the enumerator.
// pOwnerList - the neuter list that the enumerator will live on
// pHolder - an outparameter for the enumerator to be initialized.
//
void CordbProcess::BuildThreadEnum(CordbBase * pOwnerObj, NeuterList * pOwnerList, RSInitHolder<CordbHashTableEnum> * pHolder)
{
CordbHashTableEnum::BuildOrThrow(
pOwnerObj,
pOwnerList,
&m_userThreads,
IID_ICorDebugThreadEnum,
pHolder);
}
// Public implementation of ICorDebugProcess::EnumerateThreads
HRESULT CordbProcess::EnumerateThreads(ICorDebugThreadEnum **ppThreads)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
if (m_detached)
{
// #Detach_Check:
//
// FUTURE: Consider adding this IF block to the PUBLIC_API macros so that
// typical public APIs fail quickly if we're trying to do a detach. For
// now, I'm hand-adding this check only to the few problematic APIs that get
// called while queuing the fake attach events. In these cases, it is not
// enough to check if CordbProcess::IsNeutered(), as the detaching thread
// may have begun the detaching and neutering process, but not be
// finished--in which case m_detached is true, but
// CordbProcess::IsNeutered() is still false.
ThrowHR(CORDBG_E_PROCESS_DETACHED);
}
ValidateOrThrow(ppThreads);
RSInitHolder<CordbHashTableEnum> pEnum;
InternalEnumerateThreads(pEnum.GetAddr());
pEnum.TransferOwnershipExternal(ppThreads);
}
PUBLIC_API_END(hr);
return hr;
}
// Internal implementation of EnumerateThreads
VOID CordbProcess::InternalEnumerateThreads(RSInitHolder<CordbHashTableEnum> *ppThreads)
{
INTERNAL_API_ENTRY(this);
// Needs to prepopulate
PrepopulateThreadsOrThrow();
BuildThreadEnum(this, this->GetContinueNeuterList(), ppThreads);
}
// Implementation of ICorDebugProcess::GetThread
HRESULT CordbProcess::GetThread(DWORD dwThreadId, ICorDebugThread **ppThread)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppThread, ICorDebugThread **);
// No good pre-existing ATT_* contract for this.
// Because for legacy, we have to allow this on the win32 event thread.
*ppThread = NULL;
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
if (m_detached)
{
// See code:CordbProcess::EnumerateThreads#Detach_Check
ThrowHR(CORDBG_E_PROCESS_DETACHED);
}
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
if (pThread == NULL)
{
// This is a common case because we may be looking up an unmanaged thread.
hr = E_INVALIDARG;
}
else
{
*ppThread = static_cast<ICorDebugThread*> (pThread);
pThread->ExternalAddRef();
}
}
EX_CATCH_HRESULT(hr);
LOG((LF_CORDB, LL_INFO10000, "CP::GT returns id=0x%x hr=0x%x ppThread=0x%p",
dwThreadId, hr, *ppThread));
return hr;
}
HRESULT CordbProcess::ThreadForFiberCookie(DWORD fiberCookie,
ICorDebugThread **ppThread)
{
return E_NOTIMPL;
}
HRESULT CordbProcess::GetHelperThreadID(DWORD *pThreadID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
_ASSERTE(m_pShim != NULL);
if (pThreadID == NULL)
{
return (E_INVALIDARG);
}
HRESULT hr = S_OK;
// Return the ID of the current helper thread. There may be no thread in the process, or there may be a true helper
// thread.
if ((m_helperThreadId != 0) && !m_helperThreadDead)
{
*pThreadID = m_helperThreadId;
}
else if ((GetDCB() != NULL) && (GetDCB()->m_helperThreadId != 0))
{
EX_TRY
{
// be sure we have the latest information
UpdateRightSideDCB();
*pThreadID = GetDCB()->m_helperThreadId;
}
EX_CATCH_HRESULT(hr);
}
else
{
*pThreadID = 0;
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Sends IPC event to set all the managed threads, except for the one given, to the given state
//
// Arguments:
// state - The state to set the threads to.
// pExceptThread - The thread to not set. This is usually the thread that is currently
// sending an IPC event to the RS, and should be excluded.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
HRESULT CordbProcess::SetAllThreadsDebugState(CorDebugThreadState state,
ICorDebugThread * pExceptThread)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pExceptThread, ICorDebugThread *);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
if (GetShim() == NULL)
{
return E_NOTIMPL;
}
CordbThread * pCordbExceptThread = static_cast<CordbThread *> (pExceptThread);
LOG((LF_CORDB, LL_INFO1000, "CP::SATDS: except thread=0x%08x 0x%x\n",
pExceptThread,
(pCordbExceptThread != NULL) ? pCordbExceptThread->m_id : 0));
// Send one event to the Left Side to twiddle each thread's state.
DebuggerIPCEvent event;
InitIPCEvent(&event, DB_IPCE_SET_ALL_DEBUG_STATE, true, VMPTR_AppDomain::NullPtr());
event.SetAllDebugState.vmThreadToken = ((pCordbExceptThread != NULL) ?
pCordbExceptThread->m_vmThreadToken : VMPTR_Thread::NullPtr());
event.SetAllDebugState.debugState = state;
HRESULT hr = SendIPCEvent(&event, sizeof(DebuggerIPCEvent));
hr = WORST_HR(hr, event.hr);
// If that worked, then loop over all the threads on this side and set their states.
if (SUCCEEDED(hr))
{
RSLockHolder lockHolder(GetProcessLock());
HASHFIND hashFind;
CordbThread * pThread;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (pThread = m_userThreads.FindFirst(&hashFind);
pThread != NULL;
pThread = m_userThreads.FindNext(&hashFind))
{
if (pThread != pCordbExceptThread)
{
pThread->m_debugState = state;
}
}
}
return hr;
}
HRESULT CordbProcess::EnumerateObjects(ICorDebugObjectEnum **ppObjects)
{
/* !!! */
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppObjects, ICorDebugObjectEnum **);
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Determines if the target address is a "CLR transition stub".
//
// Arguments:
// address - The address of an instruction to check in the target address space.
// pfTransitionStub - Space to store the result, TRUE if the address belongs to a
// transition stub, FALSE if not. Only valid if this method returns a success code.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::IsTransitionStub(CORDB_ADDRESS address, BOOL *pfTransitionStub)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pfTransitionStub, BOOL *);
// Default to FALSE
*pfTransitionStub = FALSE;
if (this->m_helperThreadDead)
{
return S_OK;
}
// If we're not initialized, then it can't be a stub...
if (!m_initialized)
{
return S_OK;
}
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
EX_TRY
{
DebuggerIPCEvent eventData;
InitIPCEvent(&eventData, DB_IPCE_IS_TRANSITION_STUB, true, VMPTR_AppDomain::NullPtr());
eventData.IsTransitionStub.address = CORDB_ADDRESS_TO_PTR(address);
hr = SendIPCEvent(&eventData, sizeof(eventData));
hr = WORST_HR(hr, eventData.hr);
IfFailThrow(hr);
_ASSERTE(eventData.type == DB_IPCE_IS_TRANSITION_STUB_RESULT);
*pfTransitionStub = eventData.IsTransitionStubResult.isStub;
LOG((LF_CORDB, LL_INFO1000, "CP::ITS: addr=0x%p result=%d\n", address, *pfTransitionStub));
// @todo - beware that IsTransitionStub has a very important sideeffect - it synchronizes the runtime!
// This for example covers an OS bug where SetThreadContext may silently fail if we're not synchronized.
// (See IMDArocess::SetThreadContext for details on that bug).
// If we ever stop using IPC events here and only use DAC; we need to be aware of that.
// Check against DAC primitives
{
BOOL fIsStub2 = GetDAC()->IsTransitionStub(address);
(void)fIsStub2; //prevent "unused variable" error from GCC
CONSISTENCY_CHECK_MSGF(*pfTransitionStub == fIsStub2, ("IsStub2 failed, DAC2:%d, IPC:%d, addr:0x%p", (int) fIsStub2, (int) *pfTransitionStub, CORDB_ADDRESS_TO_PTR(address)));
}
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::ITS: FAILED hr=0x%x\n", hr));
}
return hr;
}
HRESULT CordbProcess::SetStopState(DWORD threadID, CorDebugThreadState state)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return E_NOTIMPL;
}
HRESULT CordbProcess::IsOSSuspended(DWORD threadID, BOOL *pbSuspended)
{
PUBLIC_API_ENTRY(this);
// Gotta have a place for the result!
if (!pbSuspended)
return E_INVALIDARG;
FAIL_IF_NEUTERED(this);
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
// Have we seen this thread?
CordbUnmanagedThread *ut = GetUnmanagedThread(threadID);
// If we have, and if we've suspended it, then say so.
if (ut && ut->IsSuspended())
{
*pbSuspended = TRUE;
}
else
{
*pbSuspended = FALSE;
}
#else
// Not interop-debugging, we never OS suspend.
*pbSuspended = FALSE;
#endif
return S_OK;
}
//
// This routine reads a thread context from the process being debugged, taking into account the fact that the context
// record may be a different size than the one we compiled with. On systems < NT5, then OS doesn't usually allocate
// space for the extended registers. However, the CONTEXT struct that we compile with does have this space.
//
HRESULT CordbProcess::SafeReadThreadContext(LSPTR_CONTEXT pContext, DT_CONTEXT * pCtx)
{
HRESULT hr = S_OK;
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
EX_TRY
{
void *pRemoteContext = pContext.UnsafeGet();
TargetBuffer tbFull(pRemoteContext, sizeof(DT_CONTEXT));
// The context may have 2 parts:
// 1. Base register, which are always present.
// 2. Optional extended registers, which are only present if CONTEXT_EXTENDED_REGISTERS is set
// in the flags.
// At a minimum we have room for a whole context up to the extended registers.
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
ULONG32 minContextSize = offsetof(DT_CONTEXT, ExtendedRegisters);
#else
ULONG32 minContextSize = sizeof(DT_CONTEXT);
#endif
// Read the minimum part.
TargetBuffer tbMin = tbFull.SubBuffer(0, minContextSize);
SafeReadBuffer(tbMin, (BYTE*) pCtx);
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
void *pCurExtReg = (void*)((UINT_PTR)pCtx + minContextSize);
TargetBuffer tbExtended = tbFull.SubBuffer(minContextSize);
// Now, read the extended registers if the context contains them. If the context does not have extended registers,
// just set them to zero.
if (SUCCEEDED(hr) && (pCtx->ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS)
{
SafeReadBuffer(tbExtended, (BYTE*) pCurExtReg);
}
else
{
memset(pCurExtReg, 0, tbExtended.cbSize);
}
#endif
}
EX_CATCH_HRESULT(hr);
return hr;
}
//
// This routine writes a thread context to the process being debugged, taking into account the fact that the context
// record may be a different size than the one we compiled with. On systems < NT5, then OS doesn't usually allocate
// space for the extended registers. However, the CONTEXT struct that we compile with does have this space.
//
HRESULT CordbProcess::SafeWriteThreadContext(LSPTR_CONTEXT pContext, const DT_CONTEXT * pCtx)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
DWORD sizeToWrite = sizeof(DT_CONTEXT);
BYTE * pRemoteContext = (BYTE*) pContext.UnsafeGet();
BYTE * pCtxSource = (BYTE*) pCtx;
#if defined(DT_CONTEXT_EXTENDED_REGISTERS)
// If our context has extended registers, then write the whole thing. Otherwise, just write the minimum part.
if ((pCtx->ContextFlags & DT_CONTEXT_EXTENDED_REGISTERS) != DT_CONTEXT_EXTENDED_REGISTERS)
{
sizeToWrite = offsetof(DT_CONTEXT, ExtendedRegisters);
}
#endif
// 64 bit windows puts space for the first 6 stack parameters in the CONTEXT structure so that
// kernel to usermode transitions don't have to allocate a CONTEXT and do a seperate sub rsp
// to allocate stack spill space for the arguments. This means that writing to P1Home - P6Home
// will overwrite the arguments of some function higher on the stack, very bad. Conceptually you
// can think of these members as not being part of the context, ie they don't represent something
// which gets saved or restored on context switches. They are just space we shouldn't overwrite.
// See issue 630276 for more details.
#if defined TARGET_AMD64
pRemoteContext += offsetof(CONTEXT, ContextFlags); // immediately follows the 6 parameters P1-P6
pCtxSource += offsetof(CONTEXT, ContextFlags);
sizeToWrite -= offsetof(CONTEXT, ContextFlags);
#endif
EX_TRY
{
// Write the context.
TargetBuffer tb(pRemoteContext, sizeToWrite);
SafeWriteBuffer(tb, (const BYTE*) pCtxSource);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbProcess::GetThreadContext(DWORD threadID, ULONG32 contextSize, BYTE context[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x\n", threadID));
DT_CONTEXT * pContext;
if (contextSize != sizeof(DT_CONTEXT))
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, context size is invalid.\n", threadID));
return E_INVALIDARG;
}
pContext = reinterpret_cast<DT_CONTEXT *>(context);
VALIDATE_POINTER_TO_OBJECT_ARRAY(context, BYTE, contextSize, true, true);
if (this->IsInteropDebugging())
{
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
// Find the unmanaged thread
CordbUnmanagedThread *ut = GetUnmanagedThread(threadID);
if (ut == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
return E_INVALIDARG;
}
return ut->GetThreadContext((DT_CONTEXT*)context);
#else
return E_NOTIMPL;
#endif
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder lockHolder(GetProcessLock());
HRESULT hr = S_OK;
EX_TRY
{
CordbThread* thread = this->TryLookupThreadByVolatileOSId(threadID);
if (thread == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
hr = E_INVALIDARG;
}
else
{
DT_CONTEXT* managedContext;
hr = thread->GetManagedContext(&managedContext);
*pContext = *managedContext;
}
}
EX_CATCH_HRESULT(hr)
return hr;
}
}
// Public implementation of ICorDebugProcess::SetThreadContext.
// @dbgtodo interop-debugging: this should go away in V3. Use the data-target instead. This is
// interop-debugging aware (and cooperates with hijacks)
HRESULT CordbProcess::SetThreadContext(DWORD threadID, ULONG32 contextSize, BYTE context[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
HRESULT hr = S_OK;
// @todo - could we look at the context flags and return E_INVALIDARG if they're bad?
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_ARRAY(context, BYTE, contextSize, true, true);
if (contextSize != sizeof(DT_CONTEXT))
{
LOG((LF_CORDB, LL_INFO10000, "CP::STC: thread=0x%x, context size is invalid.\n", threadID));
return E_INVALIDARG;
}
DT_CONTEXT* pContext = (DT_CONTEXT*)context;
if (this->IsInteropDebugging())
{
#ifdef FEATURE_INTEROP_DEBUGGING
RSLockHolder lockHolder(GetProcessLock());
CordbUnmanagedThread *ut = NULL;
// Find the unmanaged thread
ut = GetUnmanagedThread(threadID);
if (ut == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::STC: thread=0x%x, thread is invalid.\n", threadID));
return E_INVALIDARG;
}
hr = ut->SetThreadContext(pContext);
// Update the register set for the leaf-unmanaged chain so that it's consistent w/ the context.
// We may not necessarily be synchronized, and so these frames may be stale. Even so, no harm done.
if (SUCCEEDED(hr))
{
// @dbgtodo stackwalk: this should all disappear with V3 stackwalker and getting rid of SetThreadContext.
EX_TRY
{
// Find the managed thread. Returns NULL if thread is not managed.
// If we don't have a thread prveiously cached, then there's no state to update.
CordbThread * pThread = TryLookupThreadByVolatileOSId(threadID);
if (pThread != NULL)
{
// In V2, we used to update the CONTEXT of the leaf chain if the chain is an unmanaged chain.
// In Arrowhead, we just force a cleanup of the stackwalk cache. This is a more correct
// thing to do anyway, since the CONTEXT being set could be anything.
pThread->CleanupStack();
}
}
EX_CATCH_HRESULT(hr);
}
#else
return E_NOTIMPL;
#endif
}
else
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder lockHolder(GetProcessLock());
EX_TRY
{
CordbThread* thread = this->TryLookupThreadByVolatileOSId(threadID);
if (thread == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "CP::GTC: thread=0x%x, thread id is invalid.\n", threadID));
hr = E_INVALIDARG;
}
hr = thread->SetManagedContext(pContext);
}
EX_CATCH
{
hr = E_FAIL;
}
EX_END_CATCH(SwallowAllExceptions)
}
return hr;
}
// @dbgtodo ICDProcess - When we DACize this function, we should use code:DacReplacePatches
HRESULT CordbProcess::ReadMemory(CORDB_ADDRESS address,
DWORD size,
BYTE buffer[],
SIZE_T *read)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
// A read of 0 bytes is okay.
if (size == 0)
return S_OK;
VALIDATE_POINTER_TO_OBJECT_ARRAY(buffer, BYTE, size, true, true);
VALIDATE_POINTER_TO_OBJECT(buffer, SIZE_T *);
if (address == NULL)
return E_INVALIDARG;
// If no read parameter is supplied, we ignore it. This matches the semantics of kernel32!ReadProcessMemory.
SIZE_T dummyRead;
if (read == NULL)
{
read = &dummyRead;
}
*read = 0;
HRESULT hr = S_OK;
CORDBRequireProcessStateOK(this);
// Grab the memory we want to read
// Note that this will return success on a partial read
ULONG32 cbRead;
hr = GetDataTarget()->ReadVirtual(address, buffer, size, &cbRead);
if (FAILED(hr))
{
hr = CORDBG_E_READVIRTUAL_FAILURE;
goto LExit;
}
// Read at least one byte
*read = (SIZE_T) cbRead;
// There seem to be strange cases where ReadProcessMemory will return a seemingly negative number into *read, which
// is an unsigned value. So we check the sanity of *read by ensuring that its no bigger than the size we tried to
// read.
if ((*read > 0) && (*read <= size))
{
LOG((LF_CORDB, LL_INFO100000, "CP::RM: read %d bytes from 0x%08x, first byte is 0x%x\n",
*read, (DWORD)address, buffer[0]));
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
// If m_pPatchTable is NULL, then it's been cleaned out b/c of a Continue for the left side. Get the table
// again. Only do this, of course, if the managed state of the process is initialized.
if (m_pPatchTable == NULL)
{
hr = RefreshPatchTable(address, *read, buffer);
}
else
{
// The previously fetched table is still good, so run through it & see if any patches are applicable
hr = AdjustBuffer(address, *read, buffer, NULL, AB_READ);
}
}
}
LExit:
if (FAILED(hr))
{
RSLockHolder ch(&this->m_processMutex);
ClearPatchTable();
}
else if (*read < size)
{
// Unlike the DT api, our API is supposed to return an error on partial read
hr = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
return hr;
}
// Update patches & buffer to make the left-side's usage of patches transparent
// to our client. Behavior depends on AB_MODE:
// AB_READ:
// - use the RS patch table structure to replace patch opcodes in buffer.
// AB_WRITE:
// - update the RS patch table structure w/ new replace-opcode values
// if we've written over them. And put the int3 back in for write-memory.
//
// Note: If we're writing memory over top of a patch, then it must be JITted or stub code.
// Writing over JITed or Stub code can be dangerous since the CLR may not expect it
// (eg. JIT data structures about the code layout may be incorrect), but in certain
// narrow cases it may be safe (eg. replacing a constant). VS says they wouldn't expect
// this to work, but we'll keep the support in for legacy reasons.
//
// address, size - describe buffer in LS memory
// buffer - local copy of buffer that will be read/written from/to LS.
// bufferCopy - for writeprocessmemory, copy of original buffer (w/o injected patches)
// pbUpdatePatchTable - flag if patchtable got dirty and needs to be updated.
HRESULT CordbProcess::AdjustBuffer( CORDB_ADDRESS address,
SIZE_T size,
BYTE buffer[],
BYTE **bufferCopy,
AB_MODE mode,
BOOL *pbUpdatePatchTable)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
if ( address == NULL
|| size == NULL
|| buffer == NULL
|| (mode != AB_READ && mode != AB_WRITE) )
return E_INVALIDARG;
if (pbUpdatePatchTable != NULL )
*pbUpdatePatchTable = FALSE;
// If we don't have a patch table loaded, then return S_OK since there are no patches to adjust
if (m_pPatchTable == NULL)
return S_OK;
//is the requested memory completely out-of-range?
if ((m_minPatchAddr > (address + (size - 1))) ||
(m_maxPatchAddr < address))
{
return S_OK;
}
// Without runtime offsets, we can't adjust - this should only ever happen on dumps, where there's
// no W32ET to get the offsets, and so they stay zeroed
if (!m_runtimeOffsetsInitialized)
return S_OK;
LOG((LF_CORDB,LL_INFO10000, "CordbProcess::AdjustBuffer at addr 0x%p\n", address));
if (mode == AB_WRITE)
{
// We don't want to mess up the original copy of the buffer, so
// for right now, just copy it wholesale.
(*bufferCopy) = new (nothrow) BYTE[size];
if (NULL == (*bufferCopy))
return E_OUTOFMEMORY;
memmove((*bufferCopy), buffer, size);
}
ULONG iNextFree = m_iFirstPatch;
while( iNextFree != DPT_TERMINATING_INDEX )
{
BYTE *DebuggerControllerPatch = m_pPatchTable + m_runtimeOffsets.m_cbPatch*iNextFree;
PRD_TYPE opcode = *(PRD_TYPE *)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode);
CORDB_ADDRESS patchAddress = PTR_TO_CORDB_ADDRESS(*(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr));
if (IsPatchInRequestedRange(address, size, patchAddress))
{
if (mode == AB_READ)
{
CORDbgSetInstructionEx(buffer, address, patchAddress, opcode, size);
}
else if (mode == AB_WRITE)
{
_ASSERTE( pbUpdatePatchTable != NULL );
_ASSERTE( bufferCopy != NULL );
//There can be multiple patches at the same address: we don't want 2nd+ patches to get the
// break opcode, so we read from the unmodified copy.
m_rgUncommitedOpcode[iNextFree] =
CORDbgGetInstructionEx(*bufferCopy, address, patchAddress, opcode, size);
//put the breakpoint into the memory itself
CORDbgInsertBreakpointEx(buffer, address, patchAddress, opcode, size);
*pbUpdatePatchTable = TRUE;
}
else
_ASSERTE( !"CordbProcess::AdjustBuffergiven non(Read|Write) mode!" );
}
iNextFree = m_rgNextPatch[iNextFree];
}
// If we created a copy of the buffer but didn't modify it, then free it now.
if( ( mode == AB_WRITE ) && ( !*pbUpdatePatchTable ) )
{
delete [] *bufferCopy;
*bufferCopy = NULL;
}
return S_OK;
}
void CordbProcess::CommitBufferAdjustments( CORDB_ADDRESS start,
CORDB_ADDRESS end )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
_ASSERTE(m_runtimeOffsetsInitialized);
ULONG iPatch = m_iFirstPatch;
while( iPatch != DPT_TERMINATING_INDEX )
{
BYTE *DebuggerControllerPatch = m_pPatchTable +
m_runtimeOffsets.m_cbPatch*iPatch;
BYTE *patchAddress = *(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr);
if (IsPatchInRequestedRange(start, (SIZE_T)(end - start), PTR_TO_CORDB_ADDRESS(patchAddress)) &&
!PRDIsBreakInst(&(m_rgUncommitedOpcode[iPatch])))
{
//copy this back to the copy of the patch table
*(PRD_TYPE *)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode) =
m_rgUncommitedOpcode[iPatch];
}
iPatch = m_rgNextPatch[iPatch];
}
}
void CordbProcess::ClearBufferAdjustments( )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(this->ThreadHoldsProcessLock());
ULONG iPatch = m_iFirstPatch;
while( iPatch != DPT_TERMINATING_INDEX )
{
InitializePRDToBreakInst(&(m_rgUncommitedOpcode[iPatch]));
iPatch = m_rgNextPatch[iPatch];
}
}
void CordbProcess::ClearPatchTable(void )
{
INTERNAL_API_ENTRY(this);
_ASSERTE(this->ThreadHoldsProcessLock());
if (m_pPatchTable != NULL )
{
delete [] m_pPatchTable;
m_pPatchTable = NULL;
delete [] m_rgNextPatch;
m_rgNextPatch = NULL;
delete [] m_rgUncommitedOpcode;
m_rgUncommitedOpcode = NULL;
m_iFirstPatch = DPT_TERMINATING_INDEX;
m_minPatchAddr = MAX_ADDRESS;
m_maxPatchAddr = MIN_ADDRESS;
m_rgData = NULL;
m_cPatch = 0;
}
}
HRESULT CordbProcess::RefreshPatchTable(CORDB_ADDRESS address, SIZE_T size, BYTE buffer[])
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
_ASSERTE(m_initialized);
_ASSERTE(this->ThreadHoldsProcessLock());
HRESULT hr = S_OK;
BYTE *rgb = NULL;
// All of m_runtimeOffsets will be zeroed out if there's been no call to code:CordbProcess::GetRuntimeOffsets.
// Thus for things to work, we'd have to have a live target that went and got the real values.
// For dumps, things are still all zeroed out because we don't have any events sent to the W32ET, don't
// have a live process to investigate, etc.
if (!m_runtimeOffsetsInitialized)
return S_OK;
_ASSERTE( m_runtimeOffsets.m_cbOpcode == sizeof(PRD_TYPE) );
CORDBRequireProcessStateOK(this);
if (m_pPatchTable == NULL )
{
// First, check to be sure the patch table is valid on the Left Side. If its not, then we won't read it.
BOOL fPatchTableValid = FALSE;
hr = SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_runtimeOffsets.m_pPatchTableValid), &fPatchTableValid);
if (FAILED(hr) || !fPatchTableValid)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
return S_OK;
}
SIZE_T offStart = 0;
SIZE_T offEnd = 0;
UINT cbTableSlice = 0;
// Grab the patch table info
offStart = min(m_runtimeOffsets.m_offRgData, m_runtimeOffsets.m_offCData);
offEnd = max(m_runtimeOffsets.m_offRgData, m_runtimeOffsets.m_offCData) + sizeof(SIZE_T);
cbTableSlice = (UINT)(offEnd - offStart);
if (cbTableSlice == 0)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
return S_OK;
}
EX_TRY
{
rgb = new BYTE[cbTableSlice]; // throws
TargetBuffer tbSlice((BYTE*)m_runtimeOffsets.m_pPatches + offStart, cbTableSlice);
this->SafeReadBuffer(tbSlice, rgb); // Throws;
// Note that rgData is a pointer in the left side address space
m_rgData = *(BYTE**)(rgb + m_runtimeOffsets.m_offRgData - offStart);
m_cPatch = *(ULONG*)(rgb + m_runtimeOffsets.m_offCData - offStart);
// Grab the patch table
UINT cbPatchTable = (UINT)(m_cPatch * m_runtimeOffsets.m_cbPatch);
if (cbPatchTable == 0)
{
LOG((LF_CORDB, LL_INFO10000, "Wont refresh patch table because its not valid now.\n"));
_ASSERTE(hr == S_OK);
goto LExit; // can't return since we're in a Try/Catch
}
// Throwing news
m_pPatchTable = new BYTE[ cbPatchTable ];
m_rgNextPatch = new ULONG[m_cPatch];
m_rgUncommitedOpcode = new PRD_TYPE[m_cPatch];
TargetBuffer tb(m_rgData, cbPatchTable);
this->SafeReadBuffer(tb, m_pPatchTable); // Throws
//As we go through the patch table we do a number of things:
//
// 1. collect min,max address seen for quick fail check
//
// 2. Link all valid entries into a linked list, the first entry of which is m_iFirstPatch
//
// 3. Initialize m_rgUncommitedOpcode, so that we can undo local patch table changes if WriteMemory can't write
// atomically.
//
// 4. If the patch is in the memory we grabbed, unapply it.
ULONG iDebuggerControllerPatchPrev = DPT_TERMINATING_INDEX;
m_minPatchAddr = MAX_ADDRESS;
m_maxPatchAddr = MIN_ADDRESS;
m_iFirstPatch = DPT_TERMINATING_INDEX;
for (ULONG iPatch = 0; iPatch < m_cPatch;iPatch++)
{
// <REVISIT_TODO>@todo port: we're making assumptions about the size of opcodes,address pointers, etc</REVISIT_TODO>
BYTE *DebuggerControllerPatch = m_pPatchTable + m_runtimeOffsets.m_cbPatch * iPatch;
PRD_TYPE opcode = *(PRD_TYPE*)(DebuggerControllerPatch + m_runtimeOffsets.m_offOpcode);
CORDB_ADDRESS patchAddress = PTR_TO_CORDB_ADDRESS(*(BYTE**)(DebuggerControllerPatch + m_runtimeOffsets.m_offAddr));
// A non-zero opcode indicates to us that this patch is valid.
if (!PRDIsEmpty(opcode))
{
_ASSERTE( patchAddress != 0 );
// (1), above
// Note that GetPatchEndAddr() returns the address immediately AFTER the patch,
// so we have to subtract 1 from it below.
if (m_minPatchAddr > patchAddress )
m_minPatchAddr = patchAddress;
if (m_maxPatchAddr < patchAddress )
m_maxPatchAddr = GetPatchEndAddr(patchAddress) - 1;
// (2), above
if ( m_iFirstPatch == DPT_TERMINATING_INDEX)
{
m_iFirstPatch = iPatch;
_ASSERTE( iPatch != DPT_TERMINATING_INDEX);
}
if (iDebuggerControllerPatchPrev != DPT_TERMINATING_INDEX)
{
m_rgNextPatch[iDebuggerControllerPatchPrev] = iPatch;
}
iDebuggerControllerPatchPrev = iPatch;
// (3), above
InitializePRDToBreakInst(&(m_rgUncommitedOpcode[iPatch]));
// (4), above
if (IsPatchInRequestedRange(address, size, patchAddress))
{
_ASSERTE( buffer != NULL );
_ASSERTE( size != NULL );
//unapply the patch here.
CORDbgSetInstructionEx(buffer, address, patchAddress, opcode, size);
}
}
}
if (iDebuggerControllerPatchPrev != DPT_TERMINATING_INDEX)
{
m_rgNextPatch[iDebuggerControllerPatchPrev] = DPT_TERMINATING_INDEX;
}
}
LExit:
;
EX_CATCH_HRESULT(hr);
}
if (rgb != NULL )
{
delete [] rgb;
}
if (FAILED( hr ) )
{
ClearPatchTable();
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given an address, see if there is a patch in the patch table that matches it and return
// if its an unmanaged patch or not.
//
// Arguments:
// address - The address of an instruction to check in the target address space.
// pfPatchFound - Space to store the result, TRUE if the address belongs to a
// patch, FALSE if not. Only valid if this method returns a success code.
// pfPatchIsUnmanaged - Space to store the result, TRUE if the address is a patch
// and the patch is unmanaged, FALSE if not. Only valid if this method returns a
// success code.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
// Note: this method is pretty in-efficient. It refreshes the patch table, then scans it.
// Refreshing the patch table involves a scan, too, so this method could be folded
// with that.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::FindPatchByAddress(CORDB_ADDRESS address, bool *pfPatchFound, bool *pfPatchIsUnmanaged)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE((pfPatchFound != NULL) && (pfPatchIsUnmanaged != NULL));
_ASSERTE(m_runtimeOffsetsInitialized);
FAIL_IF_NEUTERED(this);
*pfPatchFound = false;
*pfPatchIsUnmanaged = false;
// First things first. If the process isn't initialized, then there can be no patch table, so we know the breakpoint
// doesn't belong to the Runtime.
if (!m_initialized)
{
return S_OK;
}
// This method is called from the main loop of the win32 event thread in response to a first chance breakpoint event
// that we know is not a flare. The process has been runnning, and it may have invalidated the patch table, so we'll
// flush it here before refreshing it to make sure we've got the right thing.
//
// Note: we really should have the Left Side mark the patch table dirty to help optimize this.
ClearPatchTable();
// Refresh the patch table.
HRESULT hr = RefreshPatchTable();
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: failed to refresh the patch table\n"));
return hr;
}
// If there is no patch table yet, then we know there is no patch at the given address, so return S_OK with
// *patchFound = false.
if (m_pPatchTable == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: no patch table\n"));
return S_OK;
}
// Scan the patch table for a matching patch.
for (ULONG iNextPatch = m_iFirstPatch; iNextPatch != DPT_TERMINATING_INDEX; iNextPatch = m_rgNextPatch[iNextPatch])
{
BYTE *patch = m_pPatchTable + (m_runtimeOffsets.m_cbPatch * iNextPatch);
BYTE *patchAddress = *(BYTE**)(patch + m_runtimeOffsets.m_offAddr);
DWORD traceType = *(DWORD*)(patch + m_runtimeOffsets.m_offTraceType);
if (address == PTR_TO_CORDB_ADDRESS(patchAddress))
{
*pfPatchFound = true;
if (traceType == m_runtimeOffsets.m_traceTypeUnmanaged)
{
*pfPatchIsUnmanaged = true;
#if defined(_DEBUG)
HRESULT hrDac = S_OK;
EX_TRY
{
// We should be able to double check w/ DAC that this really is outside of the runtime.
IDacDbiInterface::AddressType addrType = GetDAC()->GetAddressType(address);
CONSISTENCY_CHECK_MSGF(addrType == IDacDbiInterface::kAddressUnrecognized, ("Bad address type = %d", addrType));
}
EX_CATCH_HRESULT(hrDac);
CONSISTENCY_CHECK_MSGF(SUCCEEDED(hrDac), ("DAC::GetAddressType failed, hr=0x%08x", hrDac));
#endif
}
break;
}
}
// If we didn't find a patch, its actually still possible that this breakpoint exception belongs to us. There are
// races with very large numbers of threads entering the Runtime through the same managed function. We will have
// multiple threads adding and removing ref counts to an int 3 in the code stream. Sometimes, this count will go to
// zero and the int 3 will be removed, then it will come back up and the int 3 will be replaced. The in-process
// logic takes pains to ensure that such cases are handled properly, therefore we need to perform the same check
// here to make the correct decision. Basically, the check is to see if there is indeed an int 3 at the exception
// address. If there is _not_ an int 3 there, then we've hit this race. We will lie and say a managed patch was
// found to cover this case. This is tracking the logic in DebuggerController::ScanForTriggers, where we call
// IsPatched.
if (*pfPatchFound == false)
{
// Read one instruction from the faulting address...
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
PRD_TYPE TrapCheck = 0;
#else
BYTE TrapCheck = 0;
#endif
HRESULT hr2 = SafeReadStruct(address, &TrapCheck);
if (SUCCEEDED(hr2) && (TrapCheck != CORDbg_BREAK_INSTRUCTION))
{
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: patchFound=true based on odd missing int 3 case.\n"));
*pfPatchFound = true;
}
}
LOG((LF_CORDB, LL_INFO1000, "CP::FPBA: patchFound=%d, patchIsUnmanaged=%d\n", *pfPatchFound, *pfPatchIsUnmanaged));
return S_OK;
}
HRESULT CordbProcess::WriteMemory(CORDB_ADDRESS address, DWORD size,
BYTE buffer[], SIZE_T *written)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
CORDBRequireProcessStateOK(this);
_ASSERTE(m_runtimeOffsetsInitialized);
if (size == 0 || address == NULL)
return E_INVALIDARG;
VALIDATE_POINTER_TO_OBJECT_ARRAY(buffer, BYTE, size, true, true);
VALIDATE_POINTER_TO_OBJECT(written, SIZE_T *);
#if defined(_DEBUG) && defined(FEATURE_INTEROP_DEBUGGING)
// Shouldn't be using this to write int3. Use UM BP API instead.
// This is technically legal (what if the '0xcc' is data or something), so we can't fail in retail.
// But we can add this debug-only check to help VS migrate to the new API.
static ConfigDWORD configCheckInt3;
DWORD fCheckInt3 = configCheckInt3.val(CLRConfig::INTERNAL_DbgCheckInt3);
if (fCheckInt3)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
if (size == 1 && buffer[0] == 0xCC)
{
CONSISTENCY_CHECK_MSGF(false,
("You're using ICorDebugProcess::WriteMemory() to write an 'int3' (1 byte 0xCC) at address 0x%p.\n"
"If you're trying to set a breakpoint, you should be using ICorDebugProcess::SetUnmanagedBreakpoint() instead.\n"
"(This assert is only enabled under the COM+ knob DbgCheckInt3.)\n",
CORDB_ADDRESS_TO_PTR(address)));
}
#endif // TARGET_X86 || TARGET_AMD64
// check if we're replaced an opcode.
if (size == 1)
{
RSLockHolder ch(&this->m_processMutex);
NativePatch * p = GetNativePatch(CORDB_ADDRESS_TO_PTR(address));
if (p != NULL)
{
CONSISTENCY_CHECK_MSGF(false,
("You're using ICorDebugProcess::WriteMemory() to write an 'opcode (0x%x)' at address 0x%p.\n"
"There's already a native patch at that address from ICorDebugProcess::SetUnmanagedBreakpoint().\n"
"If you're trying to remove the breakpoint, use ICDProcess::ClearUnmanagedBreakpoint() instead.\n"
"(This assert is only enabled under the COM+ knob DbgCheckInt3.)\n",
(DWORD) (buffer[0]), CORDB_ADDRESS_TO_PTR(address)));
}
}
}
#endif // _DEBUG && FEATURE_INTEROP_DEBUGGING
*written = 0;
HRESULT hr = S_OK;
HRESULT hrSaved = hr; // this will hold the 'real' hresult in case of a
// partially completed operation
HRESULT hrPartialCopy = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
BOOL bUpdateOriginalPatchTable = FALSE;
BYTE *bufferCopy = NULL;
// Only update the patch table if the managed state of the process
// is initialized.
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
if (m_pPatchTable == NULL )
{
if (!SUCCEEDED( hr = RefreshPatchTable() ) )
{
goto LExit;
}
}
if ( !SUCCEEDED( hr = AdjustBuffer( address,
size,
buffer,
&bufferCopy,
AB_WRITE,
&bUpdateOriginalPatchTable)))
{
goto LExit;
}
}
//conveniently enough, SafeWriteBuffer will throw if it can't complete the entire operation
EX_TRY
{
TargetBuffer tb(address, size);
SafeWriteBuffer(tb, buffer); // throws
*written = tb.cbSize; // DT's Write does everything or fails.
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
if(hr != hrPartialCopy)
goto LExit;
else
hrSaved = hr;
}
LOG((LF_CORDB, LL_INFO100000, "CP::WM: wrote %d bytes at 0x%08x, first byte is 0x%x\n",
*written, (DWORD)address, buffer[0]));
if (bUpdateOriginalPatchTable == TRUE )
{
{
RSLockHolder ch(&this->m_processMutex);
//don't tweak patch table for stuff that isn't written to LeftSide
CommitBufferAdjustments(address, address + *written);
}
// The only way this should be able to fail is if
//someone else fiddles with the memory protections on the
//left side while it's frozen
EX_TRY
{
TargetBuffer tb(m_rgData, (ULONG) (m_cPatch*m_runtimeOffsets.m_cbPatch));
SafeWriteBuffer(tb, m_pPatchTable);
}
EX_CATCH_HRESULT(hr);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
}
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
m_continueCounter++;
LExit:
if (m_initialized)
{
RSLockHolder ch(&this->m_processMutex);
ClearBufferAdjustments( );
}
//we messed up our local copy, so get a clean copy the next time
//we need it
if (bUpdateOriginalPatchTable==TRUE)
{
if (bufferCopy != NULL)
{
memmove(buffer, bufferCopy, size);
delete [] bufferCopy;
}
}
if (FAILED( hr ))
{
//we messed up our local copy, so get a clean copy the next time
//we need it
if (bUpdateOriginalPatchTable==TRUE)
{
RSLockHolder ch(&this->m_processMutex);
ClearPatchTable();
}
}
else if( FAILED(hrSaved) )
{
hr = hrSaved;
}
return hr;
}
HRESULT CordbProcess::ClearCurrentException(DWORD threadID)
{
#ifndef FEATURE_INTEROP_DEBUGGING
return E_INVALIDARG;
#else
PUBLIC_API_ENTRY(this);
RSLockHolder lockHolder(GetProcessLock());
// There's something wrong if you're calling this an there are no queued unmanaged events.
if ((m_unmanagedEventQueue == NULL) && (m_outOfBandEventQueue == NULL))
return E_INVALIDARG;
// Grab the unmanaged thread object.
CordbUnmanagedThread *pUThread = GetUnmanagedThread(threadID);
if (pUThread == NULL)
return E_INVALIDARG;
LOG((LF_CORDB, LL_INFO1000, "CP::CCE: tid=0x%x\n", threadID));
// We clear both the IB and OOB event.
if (pUThread->HasIBEvent() && !pUThread->IBEvent()->IsEventUserContinued())
{
pUThread->IBEvent()->SetState(CUES_ExceptionCleared);
}
if (pUThread->HasOOBEvent())
{
// must decide exception status _before_ we continue the event.
_ASSERTE(!pUThread->OOBEvent()->IsEventContinuedUnhijacked());
pUThread->OOBEvent()->SetState(CUES_ExceptionCleared);
}
// If the thread is hijacked, then set the thread's debugger word to 0 to indicate to it that the
// exception has been cleared.
if (pUThread->IsGenericHijacked())
{
HRESULT hr = pUThread->SetEEDebuggerWord(0);
_ASSERTE(SUCCEEDED(hr));
}
return S_OK;
#endif // FEATURE_INTEROP_DEBUGGING
}
#ifdef FEATURE_INTEROP_DEBUGGING
CordbUnmanagedThread *CordbProcess::HandleUnmanagedCreateThread(DWORD dwThreadId, HANDLE hThread, void *lpThreadLocalBase)
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedThread *ut = new (nothrow) CordbUnmanagedThread(this, dwThreadId, hThread, lpThreadLocalBase);
if (ut != NULL)
{
HRESULT hr = m_unmanagedThreads.AddBase(ut); // InternalAddRef, release on EXIT_THREAD events.
if (!SUCCEEDED(hr))
{
delete ut;
ut = NULL;
LOG((LF_CORDB, LL_INFO10000, "Failed adding unmanaged thread to process!\n"));
CORDBSetUnrecoverableError(this, hr, 0);
}
}
else
{
LOG((LF_CORDB, LL_INFO10000, "New CordbThread failed!\n"));
CORDBSetUnrecoverableError(this, E_OUTOFMEMORY, 0);
}
return ut;
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Initializes the DAC
// Arguments: none--initializes the DAC for this CordbProcess instance
// Note: Throws on error
//-----------------------------------------------------------------------------
void CordbProcess::InitDac()
{
// Go-Go DAC power!!
HRESULT hr = S_OK;
EX_TRY
{
InitializeDac();
}
EX_CATCH_HRESULT(hr);
// We Need DAC to debug for both Managed & Interop.
if (FAILED(hr))
{
// We assert here b/c we're trying to be friendly. Most likely, the cause is either:
// - a bad installation
// - a CLR dev built mscorwks but didn't build DAC.
SIMPLIFYING_ASSUMPTION_MSGF(false, ("Failed to load DAC while for debugging. hr=0x%08x", hr));
ThrowHR(hr);
}
} //CordbProcess::InitDac
// Update the entire RS copy of the debugger control block by reading the LS copy. The RS copy is treated as
// a throw-away temporary buffer, rather than a true cache. That is, we make no assumptions about the
// validity of the information over time. Thus, before using any of the values, we need to update it. We
// update everything for simplicity; any perf hit we take by doing this instead of updating the individual
// fields we want at any given point isn't significant, particularly if we are updating multiple fields.
// Arguments:
// none, but reads process memory from the LS debugger control block
// Return Value: none (copies from LS DCB to RS buffer GetDCB())
// Note: throws if SafeReadBuffer fails
void CordbProcess::UpdateRightSideDCB()
{
IfFailThrow(m_pEventChannel->UpdateRightSideDCB());
} // CordbProcess::UpdateRightSideDCB
// Update a single field with a value stored in the RS copy of the DCB. We can't update the entire LS DCB
// because in some cases, the LS and RS are simultaneously initializing the DCB. If we initialize a field on
// the RS and write back the whole thing, we may overwrite something the LS has initialized in the interim.
// Arguments:
// input: rsFieldAddr - the address of the field in the RS copy of the DCB that we want to write back to
// the LS DCB. We use this to compute the offset of the field from the beginning of the
// DCB and then add this offset to the starting address of the LS DCB to get the LS
// address of the field we are updating
// size - the size of the field we're updating.
// Return value: none
// Note: throws if SafeWriteBuffer fails
void CordbProcess::UpdateLeftSideDCBField(void * rsFieldAddr, SIZE_T size)
{
IfFailThrow(m_pEventChannel->UpdateLeftSideDCBField(rsFieldAddr, size));
} // CordbProcess::UpdateRightSideDCB
//-----------------------------------------------------------------------------
// Gets the remote address of the event block for the Target and verifies that it's valid.
// We use this address when we need to read from or write to the debugger control block.
// Also allocates the RS buffer used for temporary storage for information from the DCB and
// copies the LS DCB into the RS buffer.
// Arguments:
// output: pfBlockExists - true iff the LS DCB has been successfully allocated. Note that
// we need this information even if the function throws, so we can't simply send it back
// as a return value.
// Return value:
// None, but allocates GetDCB() on success. If the LS DCB has not
// been successfully initialized or if this throws, GetDCB() will be NULL.
//
// Notes:
// Throws on error
//
//-----------------------------------------------------------------------------
void CordbProcess::GetEventBlock(BOOL * pfBlockExists)
{
if (GetDCB() == NULL) // we only need to do this once
{
_ASSERTE(m_pShim != NULL);
_ASSERTE(ThreadHoldsProcessLock());
// This will Initialize the DAC/DBI interface.
BOOL fDacReady = TryInitializeDac();
if (fDacReady)
{
// Ensure that we have a DAC interface.
_ASSERTE(m_pDacPrimitives != NULL);
// This is not technically necessary for Mac debugging. The event channel doesn't rely on
// knowing the target address of the DCB on the LS.
CORDB_ADDRESS pLeftSideDCB = NULL;
pLeftSideDCB = (GetDAC()->GetDebuggerControlBlockAddress());
if (pLeftSideDCB == NULL)
{
*pfBlockExists = false;
ThrowHR(CORDBG_E_DEBUGGING_NOT_POSSIBLE);
}
IfFailThrow(NewEventChannelForThisPlatform(pLeftSideDCB,
m_pMutableDataTarget,
GetProcessDescriptor(),
m_pShim->GetMachineInfo(),
&m_pEventChannel));
_ASSERTE(m_pEventChannel != NULL);
// copy information from left side DCB
UpdateRightSideDCB();
// Verify that the control block is valid.
// This will throw on error.
VerifyControlBlock();
*pfBlockExists = true;
}
else
{
// we can't initialize the DAC, so we can't get the block
*pfBlockExists = false;
}
}
else // we got the block before
{
*pfBlockExists = true;
}
} // CordbProcess::GetEventBlock()
//
// Verify that the version info in the control block matches what we expect. The minimum supported protocol from the
// Left Side must be greater or equal to the minimum required protocol of the Right Side. Note: its the Left Side's job
// to conform to whatever protocol the Right Side requires, so long as minimum is supported.
//
void CordbProcess::VerifyControlBlock()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
if (GetDCB()->m_DCBSize == 0)
{
// the LS is still initializing the DCB
ThrowHR(CORDBG_E_DEBUGGING_NOT_POSSIBLE);
}
// Fill in the protocol numbers for the Right Side and update the LS DCB.
GetDCB()->m_rightSideProtocolCurrent = CorDB_RightSideProtocolCurrent;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideProtocolCurrent), sizeof(GetDCB()->m_rightSideProtocolCurrent));
GetDCB()->m_rightSideProtocolMinSupported = CorDB_RightSideProtocolMinSupported;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideProtocolMinSupported),
sizeof(GetDCB()->m_rightSideProtocolMinSupported));
// For Telesto, Dbi and Wks have a more flexible versioning allowed, as described by the Debugger
// Version Protocol String in DEBUGGER_PROTOCOL_STRING in DbgIpcEvents.h. This allows different build
// numbers, but the other protocol numbers should still match.
// These assertions verify that the debug manager is behaving correctly.
// An assertion failure here means that the runtime version of the debuggee is different from the runtime version of
// the debugger is capable of debugging.
// The Debug Manager should properly match LS & RS, and thus guarantee that this assert should never fire.
// But just in case the installation is corrupted, we'll check it.
if (GetDCB()->m_DCBSize != sizeof(DebuggerIPCControlBlock))
{
CONSISTENCY_CHECK_MSGF(false, ("DCB in LS is %d bytes, in RS is %d bytes. Version mismatch!!\n",
GetDCB()->m_DCBSize, sizeof(DebuggerIPCControlBlock)));
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
// The Left Side has to support at least our minimum required protocol.
if (GetDCB()->m_leftSideProtocolCurrent < GetDCB()->m_rightSideProtocolMinSupported)
{
_ASSERTE(GetDCB()->m_leftSideProtocolCurrent >= GetDCB()->m_rightSideProtocolMinSupported);
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
// The Left Side has to be able to emulate at least our minimum required protocol.
if (GetDCB()->m_leftSideProtocolMinSupported > GetDCB()->m_rightSideProtocolCurrent)
{
_ASSERTE(GetDCB()->m_leftSideProtocolMinSupported <= GetDCB()->m_rightSideProtocolCurrent);
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
}
#ifdef _DEBUG
char buf[MAX_LONGPATH];
DWORD len = GetEnvironmentVariableA("CORDBG_NotCompatibleTest", buf, sizeof(buf));
_ASSERTE(len < sizeof(buf));
if (len > 0)
ThrowHR(CORDBG_E_INCOMPATIBLE_PROTOCOL);
#endif
if (GetDCB()->m_bHostingInFiber)
{
ThrowHR(CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS);
}
_ASSERTE(!GetDCB()->m_rightSideShouldCreateHelperThread);
} // CordbProcess::VerifyControlBlock
//-----------------------------------------------------------------------------
// This is the CordbProcess objects chance to inspect the DCB and intialize stuff
//
// Return Value:
// Typical HRESULT return values, nothing abnormal.
// If succeeded, then the block exists and is valid.
//
//-----------------------------------------------------------------------------
HRESULT CordbProcess::GetRuntimeOffsets()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
UpdateRightSideDCB();
// Can't get a handle to the helper thread if the target is remote.
// If we got this far w/o failing, then we should be able to get the helper thread handle.
// RS will handle not having the helper-thread handle, so we just make a best effort here.
DWORD dwHelperTid = GetDCB()->m_realHelperThreadId;
_ASSERTE(dwHelperTid != 0);
{
#if TARGET_UNIX
m_hHelperThread = NULL; //RS is supposed to be able to live without a helper thread handle.
#else
m_hHelperThread = OpenThread(SYNCHRONIZE, FALSE, dwHelperTid);
CONSISTENCY_CHECK_MSGF(m_hHelperThread != NULL, ("Failed to get helper-thread handle. tid=0x%x\n", dwHelperTid));
#endif
}
// get the remote address of the runtime offsets structure and read the structure itself
HRESULT hrRead = SafeReadStruct(PTR_TO_CORDB_ADDRESS(GetDCB()->m_pRuntimeOffsets), &m_runtimeOffsets);
if (FAILED(hrRead))
{
return hrRead;
}
LOG((LF_CORDB, LL_INFO10000, "CP::GRO: got runtime offsets: \n"));
#ifdef FEATURE_INTEROP_DEBUGGING
LOG((LF_CORDB, LL_INFO10000, " m_genericHijackFuncAddr= 0x%p\n",
m_runtimeOffsets.m_genericHijackFuncAddr));
LOG((LF_CORDB, LL_INFO10000, " m_signalHijackStartedBPAddr= 0x%p\n",
m_runtimeOffsets.m_signalHijackStartedBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_excepNotForRuntimeBPAddr= 0x%p\n",
m_runtimeOffsets.m_excepNotForRuntimeBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_notifyRSOfSyncCompleteBPAddr= 0x%p\n",
m_runtimeOffsets.m_notifyRSOfSyncCompleteBPAddr));
LOG((LF_CORDB, LL_INFO10000, " m_debuggerWordTLSIndex= 0x%08x\n",
m_runtimeOffsets.m_debuggerWordTLSIndex));
#endif // FEATURE_INTEROP_DEBUGGING
LOG((LF_CORDB, LL_INFO10000, " m_TLSIndex= 0x%08x\n",
m_runtimeOffsets.m_TLSIndex));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadStateOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadStateOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadStateNCOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadStateNCOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadPGCDisabledOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadPGCDisabledOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadPGCDisabledValue= 0x%08x\n",
m_runtimeOffsets.m_EEThreadPGCDisabledValue));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadFrameOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadFrameOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadMaxNeededSize= 0x%08x\n",
m_runtimeOffsets.m_EEThreadMaxNeededSize));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadSteppingStateMask= 0x%08x\n",
m_runtimeOffsets.m_EEThreadSteppingStateMask));
LOG((LF_CORDB, LL_INFO10000, " m_EEMaxFrameValue= 0x%08x\n",
m_runtimeOffsets.m_EEMaxFrameValue));
LOG((LF_CORDB, LL_INFO10000, " m_EEThreadDebuggerFilterContextOffset= 0x%08x\n",
m_runtimeOffsets.m_EEThreadDebuggerFilterContextOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEFrameNextOffset= 0x%08x\n",
m_runtimeOffsets.m_EEFrameNextOffset));
LOG((LF_CORDB, LL_INFO10000, " m_EEIsManagedExceptionStateMask= 0x%08x\n",
m_runtimeOffsets.m_EEIsManagedExceptionStateMask));
LOG((LF_CORDB, LL_INFO10000, " m_pPatches= 0x%08x\n",
m_runtimeOffsets.m_pPatches));
LOG((LF_CORDB, LL_INFO10000, " m_offRgData= 0x%08x\n",
m_runtimeOffsets.m_offRgData));
LOG((LF_CORDB, LL_INFO10000, " m_offCData= 0x%08x\n",
m_runtimeOffsets.m_offCData));
LOG((LF_CORDB, LL_INFO10000, " m_cbPatch= 0x%08x\n",
m_runtimeOffsets.m_cbPatch));
LOG((LF_CORDB, LL_INFO10000, " m_offAddr= 0x%08x\n",
m_runtimeOffsets.m_offAddr));
LOG((LF_CORDB, LL_INFO10000, " m_offOpcode= 0x%08x\n",
m_runtimeOffsets.m_offOpcode));
LOG((LF_CORDB, LL_INFO10000, " m_cbOpcode= 0x%08x\n",
m_runtimeOffsets.m_cbOpcode));
LOG((LF_CORDB, LL_INFO10000, " m_offTraceType= 0x%08x\n",
m_runtimeOffsets.m_offTraceType));
LOG((LF_CORDB, LL_INFO10000, " m_traceTypeUnmanaged= 0x%08x\n",
m_runtimeOffsets.m_traceTypeUnmanaged));
#ifdef FEATURE_INTEROP_DEBUGGING
// Flares are only used for interop debugging.
// Do check that the flares are all at unique offsets.
// Since this is determined at link-time, we need a run-time check (an
// assert isn't good enough, since this would only happen in a super
// optimized / bbt run).
{
const void * flares[] = {
m_runtimeOffsets.m_signalHijackStartedBPAddr,
m_runtimeOffsets.m_excepForRuntimeHandoffStartBPAddr,
m_runtimeOffsets.m_excepForRuntimeHandoffCompleteBPAddr,
m_runtimeOffsets.m_signalHijackCompleteBPAddr,
m_runtimeOffsets.m_excepNotForRuntimeBPAddr,
m_runtimeOffsets.m_notifyRSOfSyncCompleteBPAddr,
};
const int NumFlares = ARRAY_SIZE(flares);
// Ensure that all of the flares are unique.
for(int i = 0; i < NumFlares; i++)
{
for(int j = i+1; j < NumFlares; j++)
{
if (flares[i] == flares[j])
{
// If we ever fail here, that means the LS build is busted.
// This assert is useful if we drop a checked RS onto a retail
// LS (that's legal).
_ASSERTE(!"LS has matching Flares.");
LOG((LF_CORDB, LL_ALWAYS, "Failing because of matching flares.\n"));
return CORDBG_E_INCOMPATIBLE_PROTOCOL;
}
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
m_runtimeOffsetsInitialized = true;
return S_OK;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Resume hijacked threads.
//-----------------------------------------------------------------------------
void CordbProcess::ResumeHijackedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_pShim != NULL);
_ASSERTE(ThreadHoldsProcessLock());
LOG((LF_CORDB, LL_INFO10000, "CP::RHT: entered\n"));
if (this->m_state & (CordbProcess::PS_SOME_THREADS_SUSPENDED | CordbProcess::PS_HIJACKS_IN_PLACE))
{
// On XP, This will also resume the threads suspended for Sync.
this->ResumeUnmanagedThreads();
}
// Hijacks send their ownership flares and then wait on this event. By setting this
// we let the hijacks run free.
if (this->m_leftSideUnmanagedWaitEvent != NULL)
{
SetEvent(this->m_leftSideUnmanagedWaitEvent);
}
else
{
// Only reason we expect to not have this event is if the CLR hasn't been loaded yet.
// In that case, we won't hijack, so nobody's listening for this event either.
_ASSERTE(!m_initialized);
}
}
//-----------------------------------------------------------------------------
// For debugging support, record the win32 events.
// Note that although this is for debugging, we want it in retail because we'll
// be debugging retail most of the time :(
// pEvent - the win32 debug event we just received
// pUThread - our unmanaged thread object for the event. We could look it up
// from pEvent->dwThreadId, but passed in for perf reasons.
//-----------------------------------------------------------------------------
void CordbProcess::DebugRecordWin32Event(const DEBUG_EVENT * pEvent, CordbUnmanagedThread * pUThread)
{
_ASSERTE(ThreadHoldsProcessLock());
// Although we could look up the Unmanaged thread, it's faster to have it just passed in.
// So here we do a consistency check.
_ASSERTE(pUThread != NULL);
_ASSERTE(pUThread->m_id == pEvent->dwThreadId);
m_DbgSupport.m_TotalNativeEvents++; // bump up the counter.
MiniDebugEvent * pMiniEvent = &m_DbgSupport.m_DebugEventQueue[m_DbgSupport.m_DebugEventQueueIdx];
pMiniEvent->code = (BYTE) pEvent->dwDebugEventCode;
pMiniEvent->pUThread = pUThread;
DWORD tid = pEvent->dwThreadId;
// Record debug-event specific data.
switch(pEvent->dwDebugEventCode)
{
case LOAD_DLL_DEBUG_EVENT:
pMiniEvent->u.ModuleData.pBaseAddress = pEvent->u.LoadDll.lpBaseOfDll;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=0x%8x, Load Dll. Addr=%p\n",
tid,
pEvent->u.LoadDll.lpBaseOfDll);
break;
case UNLOAD_DLL_DEBUG_EVENT:
pMiniEvent->u.ModuleData.pBaseAddress = pEvent->u.UnloadDll.lpBaseOfDll;
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=0x%8x, Unload Dll. Addr=%p\n",
tid,
pEvent->u.UnloadDll.lpBaseOfDll);
break;
case EXCEPTION_DEBUG_EVENT:
pMiniEvent->u.ExceptionData.pAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
pMiniEvent->u.ExceptionData.dwCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
STRESS_LOG3(LF_CORDB, LL_INFO1000, "Win32 Debug Event received: tid=%8x, (1) Exception. Code=0x%08x, Addr=%p\n",
tid,
pMiniEvent->u.ExceptionData.dwCode,
pMiniEvent->u.ExceptionData.pAddress
);
break;
default:
STRESS_LOG2(LF_CORDB, LL_INFO1000, "Win32 Debug Event received tid=%8x, %d\n", tid, pEvent->dwDebugEventCode);
break;
}
// Go to the next entry in the queue.
m_DbgSupport.m_DebugEventQueueIdx = (m_DbgSupport.m_DebugEventQueueIdx + 1) % DEBUG_EVENTQUEUE_SIZE;
}
void CordbProcess::QueueUnmanagedEvent(CordbUnmanagedThread *pUThread, const DEBUG_EVENT *pEvent)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_pShim != NULL);
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: queued unmanaged event %d for thread 0x%x\n",
pEvent->dwDebugEventCode, pUThread->m_id));
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
// Copy the event into the given thread
CordbUnmanagedEvent *ue;
// Use the primary IB event slot unless this is the special stack overflow event case.
if (!pUThread->HasSpecialStackOverflowCase())
ue = pUThread->IBEvent();
else
ue = pUThread->IBEvent2();
if(pUThread->HasIBEvent() && !pUThread->HasSpecialStackOverflowCase())
{
// Any event being replaced should at least have been continued outside of the hijack
// We don't track whether or not we expect the exception to retrigger but if we are replacing
// the event then it did not.
_ASSERTE(ue->IsEventContinuedUnhijacked());
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: A previously seen event is being discarded 0x%x 0x%p\n",
ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode,
ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionAddress));
DequeueUnmanagedEvent(ue->m_owner);
}
memcpy(&(ue->m_currentDebugEvent), pEvent, sizeof(DEBUG_EVENT));
ue->m_state = CUES_IsIBEvent;
ue->m_next = NULL;
// Enqueue the event.
pUThread->SetState(CUTS_HasIBEvent);
if (m_unmanagedEventQueue == NULL)
m_unmanagedEventQueue = ue;
else
m_lastQueuedUnmanagedEvent->m_next = ue;
m_lastQueuedUnmanagedEvent = ue;
}
void CordbProcess::DequeueUnmanagedEvent(CordbUnmanagedThread *ut)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_unmanagedEventQueue != NULL);
_ASSERTE(ut->HasIBEvent() || ut->HasSpecialStackOverflowCase());
_ASSERTE(ThreadHoldsProcessLock());
CordbUnmanagedEvent *ue;
if (ut->HasIBEvent())
ue = ut->IBEvent();
else
{
ue = ut->IBEvent2();
// Since we're dequeuing the special stack overflow event, we're no longer in the special stack overflow case.
ut->ClearState(CUTS_HasSpecialStackOverflowCase);
}
DWORD ec = ue->m_currentDebugEvent.dwDebugEventCode;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dequeue unmanaged event %d for thread 0x%x\n", ec, ut->m_id));
_ASSERTE(ec == EXCEPTION_DEBUG_EVENT);
CordbUnmanagedEvent **tmp = &m_unmanagedEventQueue;
CordbUnmanagedEvent **prev = NULL;
// Note: this supports out-of-order dequeing of unmanaged events. This is necessary because we queue events even if
// we're not clear on the ownership question. When we get the answer, and if the event belongs to the Runtime, we go
// ahead and yank the event out of the queue, wherever it may be.
while (*tmp && *tmp != ue)
{
prev = tmp;
tmp = &((*tmp)->m_next);
}
_ASSERTE(*tmp == ue);
*tmp = (*tmp)->m_next;
if (m_unmanagedEventQueue == NULL)
m_lastQueuedUnmanagedEvent = NULL;
else if (m_lastQueuedUnmanagedEvent == ue)
{
_ASSERTE(prev != NULL);
m_lastQueuedUnmanagedEvent = *prev;
}
ut->ClearState(CUTS_HasIBEvent);
}
void CordbProcess::QueueOOBUnmanagedEvent(CordbUnmanagedThread *pUThread, const DEBUG_EVENT * pEvent)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(!pUThread->HasOOBEvent());
_ASSERTE(IsWin32EventThread());
_ASSERTE(m_pShim != NULL);
LOG((LF_CORDB, LL_INFO10000, "CP::QUE: queued OOB unmanaged event %d for thread 0x%x\n",
pEvent->dwDebugEventCode, pUThread->m_id));
// Copy the event into the given thread
CordbUnmanagedEvent *ue = pUThread->OOBEvent();
memcpy(&(ue->m_currentDebugEvent), pEvent, sizeof(DEBUG_EVENT));
ue->m_state = CUES_None;
ue->m_next = NULL;
// Enqueue the event.
pUThread->SetState(CUTS_HasOOBEvent);
if (m_outOfBandEventQueue == NULL)
m_outOfBandEventQueue = ue;
else
m_lastQueuedOOBEvent->m_next = ue;
m_lastQueuedOOBEvent = ue;
}
void CordbProcess::DequeueOOBUnmanagedEvent(CordbUnmanagedThread *ut)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(m_outOfBandEventQueue != NULL);
_ASSERTE(ut->HasOOBEvent());
_ASSERTE(ThreadHoldsProcessLock());
CordbUnmanagedEvent *ue = ut->OOBEvent();
DWORD ec = ue->m_currentDebugEvent.dwDebugEventCode;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dequeue OOB unmanaged event %d for thread 0x%x\n", ec, ut->m_id));
CordbUnmanagedEvent **tmp = &m_outOfBandEventQueue;
CordbUnmanagedEvent **prev = NULL;
// Note: this supports out-of-order dequeing of unmanaged events. This is necessary because we queue events even if
// we're not clear on the ownership question. When we get the answer, and if the event belongs to the Runtime, we go
// ahead and yank the event out of the queue, wherever it may be.
while (*tmp && *tmp != ue)
{
prev = tmp;
tmp = &((*tmp)->m_next);
}
_ASSERTE(*tmp == ue);
*tmp = (*tmp)->m_next;
if (m_outOfBandEventQueue == NULL)
m_lastQueuedOOBEvent = NULL;
else if (m_lastQueuedOOBEvent == ue)
{
_ASSERTE(prev != NULL);
m_lastQueuedOOBEvent = *prev;
}
ut->ClearState(CUTS_HasOOBEvent);
}
HRESULT CordbProcess::SuspendUnmanagedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
// Iterate over all unmanaged threads...
CordbUnmanagedThread* ut;
HASHFIND find;
for (ut = m_unmanagedThreads.FindFirst(&find); ut != NULL; ut = m_unmanagedThreads.FindNext(&find))
{
// Don't suspend any thread in a can't stop region. This includes cooperative mode threads & preemptive
// threads that haven't pushed a NativeTransitionFrame. The ultimate problem here is that a thread
// in this state is effectively inside the runtime, and thus may take a lock that blocks the helper thread.
// IsCan'tStop also includes the helper thread & hijacked threads - which we shouldn't suspend anyways.
// Only suspend those unmanaged threads that aren't already suspended by us and that aren't already hijacked by
// us.
if (!ut->IsSuspended() &&
!ut->IsDeleted() &&
!ut->IsCantStop() &&
!ut->IsBlockingForSync()
)
{
LOG((LF_CORDB, LL_INFO1000, "CP::SUT: suspending unmanaged thread 0x%x, handle 0x%x\n", ut->m_id, ut->m_handle));
DWORD succ = SuspendThread(ut->m_handle);
if (succ == 0xFFFFFFFF)
{
// This is okay... the thread may be dying after an ExitThread event.
LOG((LF_CORDB, LL_INFO1000, "CP::SUT: failed to suspend thread 0x%x\n", ut->m_id));
}
else
{
m_state |= PS_SOME_THREADS_SUSPENDED;
ut->SetState(CUTS_Suspended);
}
}
}
return S_OK;
}
HRESULT CordbProcess::ResumeUnmanagedThreads()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
FAIL_IF_NEUTERED(this);
// Iterate over all unmanaged threads...
CordbUnmanagedThread* ut;
HASHFIND find;
for (ut = m_unmanagedThreads.FindFirst(&find); ut != NULL; ut = m_unmanagedThreads.FindNext(&find))
{
// Only resume those unmanaged threads that were suspended by us.
if (ut->IsSuspended())
{
LOG((LF_CORDB, LL_INFO1000, "CP::RUT: resuming unmanaged thread 0x%x\n", ut->m_id));
DWORD succ = ResumeThread(ut->m_handle);
if (succ == 0xFFFFFFFF)
{
LOG((LF_CORDB, LL_INFO1000, "CP::RUT: failed to resume thread 0x%x\n", ut->m_id));
}
else
ut->ClearState(CUTS_Suspended);
}
}
m_state &= ~PS_SOME_THREADS_SUSPENDED;
return S_OK;
}
//-----------------------------------------------------------------------------
// DispatchUnmanagedInBandEvent
//
// Handler for Win32 events already known to be Unmanaged and in-band.
//-----------------------------------------------------------------------------
void CordbProcess::DispatchUnmanagedInBandEvent()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
// There should be no queued OOB events!!! If there are, then we have a breakdown in our protocol, since all OOB
// events should be dispatched before attempting to really continue from any in-band event.
_ASSERTE(m_outOfBandEventQueue == NULL);
_ASSERTE(m_cordb != NULL);
_ASSERTE(m_cordb->m_unmanagedCallback != NULL);
_ASSERTE(!m_dispatchingUnmanagedEvent);
CordbUnmanagedThread * pUnmanagedThread = NULL;
CordbUnmanagedEvent * pUnmanagedEvent = m_unmanagedEventQueue;
while (true)
{
// get the next queued event that isn't dispatched yet
while(pUnmanagedEvent != NULL && pUnmanagedEvent->IsDispatched())
{
pUnmanagedEvent = pUnmanagedEvent->m_next;
}
if(pUnmanagedEvent == NULL)
break;
// Get the thread for this event
_ASSERTE(pUnmanagedThread == NULL);
pUnmanagedThread = pUnmanagedEvent->m_owner;
_ASSERTE(pUnmanagedThread != NULL);
// We better not have dispatched it yet!
_ASSERTE(!pUnmanagedEvent->IsDispatched());
// We shouldn't be dispatching IB events on a thread that has exited.
// Though it's possible that the thread may exit *after* the IB event has been dispatched
// if it gets hijacked.
_ASSERTE(!pUnmanagedThread->IsDeleted());
// Make sure we keep the thread alive while we're playing with it.
pUnmanagedThread->InternalAddRef();
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: dispatching unmanaged event %d for thread 0x%x\n",
pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, pUnmanagedThread->m_id));
m_dispatchingUnmanagedEvent = true;
// Add/Remove a reference which is scoped to the time that m_lastDispatchedIBEvent
// is set to pUnmanagedEvent (it is an interior pointer)
// see DevDiv issue 818301 for more details
if(m_lastDispatchedIBEvent != NULL)
{
m_lastDispatchedIBEvent->m_owner->InternalRelease();
m_lastDispatchedIBEvent = NULL;
}
pUnmanagedThread->InternalAddRef();
m_lastDispatchedIBEvent = pUnmanagedEvent;
pUnmanagedEvent->SetState(CUES_Dispatched);
IncStopCount();
Unlock();
{
// Interface is semantically const, but does not include const in signature.
DEBUG_EVENT * pEvent = const_cast<DEBUG_EVENT *> (&(pUnmanagedEvent->m_currentDebugEvent));
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this,pEvent, FALSE);
m_cordb->m_unmanagedCallback->DebugEvent(pEvent, FALSE);
}
Lock();
// Calling IMDA::Continue() will set m_dispatchingUnmanagedEvent = false.
// So if Continue() was called && we have more events, we'll loop and dispatch more events.
// Else we'll break out of the while loop.
if(m_dispatchingUnmanagedEvent)
break;
// Continue was called in the dispatch callback, but that continue path just
// clears the dispatch flag and returns. The continue right here is the logical
// completion of the user's continue request
// Note it is sometimes the case that these events have already been continued because
// they had defered dispatching. At the time of deferal they were immediately continued.
// If the event is already continued then this continue becomes a no-op.
m_pShim->GetWin32EventThread()->DoDbgContinue(this, pUnmanagedEvent);
// Release our reference to the unmanaged thread that we dispatched
// This event should have been continued long ago...
_ASSERTE(!pUnmanagedThread->IBEvent()->IsEventWaitingForContinue());
pUnmanagedThread->InternalRelease();
pUnmanagedThread = NULL;
}
m_dispatchingUnmanagedEvent = false;
// Release our reference to the last thread that we dispatched now...
if(pUnmanagedThread)
{
pUnmanagedThread->InternalRelease();
pUnmanagedThread = NULL;
}
}
//-----------------------------------------------------------------------------
// DispatchUnmanagedOOBEvent
//
// Handler for Win32 events already known to be Unmanaged and out-of-band.
//-----------------------------------------------------------------------------
void CordbProcess::DispatchUnmanagedOOBEvent()
{
INTERNAL_API_ENTRY(this);
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
// There should be OOB events queued...
_ASSERTE(m_outOfBandEventQueue != NULL);
_ASSERTE(m_cordb->m_unmanagedCallback != NULL);
do
{
// Get the first event in the OOB Queue...
CordbUnmanagedEvent * pUnmanagedEvent = m_outOfBandEventQueue;
CordbUnmanagedThread * pUnmanagedThread = pUnmanagedEvent->m_owner;
// Make sure we keep the thread alive while we're playing with it.
RSSmartPtr<CordbUnmanagedThread> pRef(pUnmanagedThread);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::DUE: dispatching OOB unmanaged event %d for thread 0x%x\n",
GetCurrentThreadId(), pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, pUnmanagedThread->m_id));
m_dispatchingOOBEvent = true;
pUnmanagedEvent->SetState(CUES_Dispatched);
Unlock();
{
// Interface is semantically const, but does not include const in signature.
DEBUG_EVENT * pEvent = const_cast<DEBUG_EVENT *> (&(pUnmanagedEvent->m_currentDebugEvent));
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this, pEvent, TRUE);
m_cordb->m_unmanagedCallback->DebugEvent(pEvent, TRUE);
}
Lock();
// If they called Continue from the callback, then continue the OOB event right now before dispatching the next
// one.
if (!m_dispatchingOOBEvent)
{
DequeueOOBUnmanagedEvent(pUnmanagedThread);
// Should not have continued from this debug event yet.
_ASSERTE(pUnmanagedEvent->IsEventWaitingForContinue());
// Do a little extra work if that was an OOB exception event...
HRESULT hr = pUnmanagedEvent->m_owner->FixupAfterOOBException(pUnmanagedEvent);
_ASSERTE(SUCCEEDED(hr));
// Go ahead and continue now...
this->m_pShim->GetWin32EventThread()->DoDbgContinue(this, pUnmanagedEvent);
}
// Implicit release of pUnmanagedThread via pRef
}
while (!m_dispatchingOOBEvent && (m_outOfBandEventQueue != NULL));
m_dispatchingOOBEvent = false;
LOG((LF_CORDB, LL_INFO10000, "CP::DUE: done dispatching OOB events. Queue=0x%08x\n", m_outOfBandEventQueue));
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// StartSyncFromWin32Stop
//
// Get the process from a Fozen state or a Live state to a Synchronized State.
// Note that Process Exit is considered to be synchronized.
// This is a nop if we're not Interop Debugging.
// If this function succeeds, we're in a synchronized state.
//
// Arguments:
// pfAsyncBreakSent - returns if this method sent an async-break or not.
//
// Return value:
// typical HRESULT return values, nothing sinister here.
//-----------------------------------------------------------------------------
HRESULT CordbProcess::StartSyncFromWin32Stop(BOOL * pfAsyncBreakSent)
{
INTERNAL_API_ENTRY(this);
if (m_pShim == NULL) // This API is moved off to the shim
{
return E_NOTIMPL;
}
HRESULT hr = S_OK;
// Caller should have taken the stop-go lock. This prevents us from racing w/ a continue.
_ASSERTE(m_StopGoLock.HasLock());
// Process should be init before we try to sync it.
_ASSERTE(this->m_initialized);
// If nobody's listening for an AsyncBreak, and we're not stopped, then our caller
// doesn't know if we're sending an AsyncBreak or not; and thus we may not continue.
// Failing this assert means that we're stopping but we don't think we're going to get a continue
// down the road, and thus we're headed for a deadlock.
_ASSERTE((pfAsyncBreakSent != NULL) || (m_stopCount > 0));
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = FALSE;
}
#ifdef FEATURE_INTEROP_DEBUGGING
// If we're win32 stopped (but not out-of-band win32 stopped), or if we're running free on the Left Side but we're
// just not synchronized (and we're win32 attached), then go ahead and do an internal continue and send an async
// break event to get the Left Side sync'd up.
//
// The process can be running free as far as Win32 events are concerned, but still not synchronized as far as the
// Runtime is concerned. This can happen in a lot of cases where we end up with the Runtime not sync'd but with the
// process running free due to hijacking, etc...
if (((m_state & CordbProcess::PS_WIN32_STOPPED) && (m_outOfBandEventQueue == NULL)) ||
(!GetSynchronized() && IsInteropDebugging()))
{
Lock();
if (((m_state & CordbProcess::PS_WIN32_STOPPED) && (m_outOfBandEventQueue == NULL)) ||
(!GetSynchronized() && IsInteropDebugging()))
{
// This can't be the win32 ET b/c we need that thread to be alive and pumping win32 DE so that
// our Async Break can get across.
// So nobody should ever be calling this on the w32 ET. But they could, since we do trickle in from
// outside APIs. So we need a retail check.
if (IsWin32EventThread())
{
_ASSERTE(!"Don't call this API on the W32 Event Thread");
Unlock();
return ErrWrapper(CORDBG_E_CANT_CALL_ON_THIS_THREAD);
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sending internal continue\n", GetCurrentThreadId());
// Can't do this on the win32 event thread.
_ASSERTE(!this->IsWin32EventThread());
// If the helper thread is already dead, then we just return as if we sync'd the process.
if (m_helperThreadDead)
{
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = TRUE;
}
// Mark the process as synchronized so no events will be dispatched until the thing is
// continued. However, the marking here is not a usual marking for synchronized. It has special
// semantics when we're interop debugging. We use m_oddSync to remember this so that we can take special
// action in Continue().
SetSynchronized(true);
m_oddSync = true;
// Get the RC Event Thread to stop listening to the process.
m_cordb->ProcessStateChanged();
Unlock();
return S_OK;
}
m_stopRequested = true;
// See ::Stop for why we defer this. The delayed events will be dispatched when some one calls continue.
// And we know they'll call continue b/c (stopCount > 0) || (our caller knows we're sending an AsyncBreak).
m_specialDeferment = true;
Unlock();
// If the process gets synchronized between the Unlock() and here, then SendUnmanagedContinue() will end up
// not doing anything at all since a) it holds the process lock when working and b) it gates everything on
// if the process is sync'd or not. This is exactly what we want.
hr = this->m_pShim->GetWin32EventThread()->SendUnmanagedContinue(this, cInternalUMContinue);
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: internal continue returned\n", GetCurrentThreadId()));
// Send an async break to the left side now that its running.
DebuggerIPCEvent * pEvent = (DebuggerIPCEvent *) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(pEvent, DB_IPCE_ASYNC_BREAK, false, VMPTR_AppDomain::NullPtr());
LOG((LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sending async stop\n", GetCurrentThreadId()));
// If the process gets synchronized between the Unlock() and here, then this message will do nothing (Left
// Side catches it) and we'll never get a response, and it won't hurt anything.
hr = m_cordb->SendIPCEvent(this, pEvent, CorDBIPC_BUFFER_SIZE);
// @Todo- how do we handle a failure here?
// If the send returns with the helper thread being dead, then we know we don't need to wait for the process
// to sync.
if (!m_helperThreadDead)
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: sent async stop, waiting for event\n", GetCurrentThreadId());
// If we got synchronized between the Unlock() and here its okay since m_stopWaitEvent is still high
// from the last sync.
DWORD dwWaitResult = SafeWaitForSingleObject(this, m_stopWaitEvent, INFINITE);
STRESS_LOG2(LF_CORDB, LL_INFO1000, "[%x] CP::SSFW32S: got event, %d\n", GetCurrentThreadId(), dwWaitResult);
_ASSERTE(dwWaitResult == WAIT_OBJECT_0);
}
Lock();
m_specialDeferment = false;
if (pfAsyncBreakSent)
{
*pfAsyncBreakSent = TRUE;
}
// If the helper thread died while we were trying to send an event to it, then we just do the same odd sync
// logic we do above.
if (m_helperThreadDead)
{
SetSynchronized(true);
m_oddSync = true;
hr = S_OK;
}
m_stopRequested = false;
m_cordb->ProcessStateChanged();
}
Unlock();
}
#endif // FEATURE_INTEROP_DEBUGGING
return hr;
}
// Check if the left side has exited. If so, get the right-side
// into shutdown mode. Only use this to avert us from going into
// an unrecoverable error.
bool CordbProcess::CheckIfLSExited()
{
// Check by waiting on the handle with no timeout.
if (WaitForSingleObject(m_handle, 0) == WAIT_OBJECT_0)
{
Lock();
m_terminated = true;
m_exiting = true;
Unlock();
}
LOG((LF_CORDB, LL_INFO10, "CP::IsLSExited() returning '%s'\n",
m_exiting ? "true" : "false"));
return m_exiting;
}
// Call this if something really bad happened and we can't do
// anything meaningful with the CordbProcess.
void CordbProcess::UnrecoverableError(HRESULT errorHR,
unsigned int errorCode,
const char *errorFile,
unsigned int errorLine)
{
LOG((LF_CORDB, LL_INFO10, "[%x] CP::UE: unrecoverable error 0x%08x "
"(%d) %s:%d\n",
GetCurrentThreadId(),
errorHR, errorCode, errorFile, errorLine));
// We definitely want to know about any of these.
STRESS_LOG3(LF_CORDB, LL_EVERYTHING, "Unrecoverable Error:0x%08x, File=%s, line=%d\n", errorHR, errorFile, errorLine);
// It's possible for an unrecoverable error to occur if the user detaches the
// debugger while inside CordbProcess::DispatchRCEvent() (as that function deliberately
// calls Unlock() while calling into the Shim). Detect such cases here & bail before we
// try to access invalid fields on this CordbProcess.
//
// Normally, we'd need to take the cordb process lock around the IsNeutered check
// (and the code that follows). And perhaps this is a good thing to do in the
// future. But for now we're not for two reasons:
//
// 1) It's scary. We're in UnrecoverableError() for gosh sake. I don't know all
// the possible bad states we can be in to get here. Will taking the process lock
// have ordering issues? Will the process lock even be valid to take here (or might
// we AV)? Since this is error handling, we should probably be as light as we can
// not to cause more errors.
//
// 2) It's unnecessary. For the Watson dump I investigated that caused this fix in
// the first place, we already detached before entering UnrecoverableError()
// (indeed, the only reason we're in UnrecoverableError is that we already detached
// and that caused a prior API to fail). Thus, there's no timing issue (in that
// case, anyway), wrt to entering UnrecoverableError() and detaching / neutering.
if (IsNeutered())
return;
#ifdef _DEBUG
// Ping our error trapping logic
HRESULT hrDummy;
hrDummy = ErrWrapper(errorHR);
#endif
if (m_pShim == NULL)
{
// @dbgtodo - , shim: Once everything is hoisted, we can remove
// this code.
// In the v3 case, we should never get an unrecoverable error. Instead, the HR should be propagated
// and returned at the top-level public API.
_ASSERTE(!"Unrecoverable error dispatched in V3 case.");
}
CONSISTENCY_CHECK_MSGF(IsLegalFatalError(errorHR), ("Unrecoverable internal error: hr=0x%08x!", errorHR));
if (!IsLegalFatalError(errorHR) || (errorHR != CORDBG_E_CANNOT_DEBUG_FIBER_PROCESS))
{
// This will throw everything into a Zombie state. The ATT_ macros will check this and fail immediately.
m_unrecoverableError = true;
//
// Mark the process as no longer synchronized.
//
Lock();
SetSynchronized(false);
IncStopCount();
Unlock();
}
// Set the error flags in the process so that if parts of it are
// still alive, it will realize that its in this mode and do the
// right thing.
if (GetDCB() != NULL)
{
GetDCB()->m_errorHR = errorHR;
GetDCB()->m_errorCode = errorCode;
EX_TRY
{
UpdateLeftSideDCBField(&(GetDCB()->m_errorHR), sizeof(GetDCB()->m_errorHR));
UpdateLeftSideDCBField(&(GetDCB()->m_errorCode), sizeof(GetDCB()->m_errorCode));
}
EX_CATCH
{
_ASSERTE(!"Writing process memory failed, perhaps due to an unexpected disconnection from the target.");
}
EX_END_CATCH(SwallowAllExceptions);
}
//
// Let the user know that we've hit an unrecoverable error.
//
if (m_cordb->m_managedCallback)
{
// We are about to send DebuggerError call back. The state of RS is undefined.
// So we use the special Public Callback. We may be holding locks and stuff.
// We may also be deeply nested within the RS.
PUBLIC_CALLBACK_IN_THIS_SCOPE_DEBUGGERERROR(this);
m_cordb->m_managedCallback->DebuggerError((ICorDebugProcess*) this,
errorHR,
errorCode);
}
}
HRESULT CordbProcess::CheckForUnrecoverableError()
{
HRESULT hr = S_OK;
if (GetDCB() != NULL)
{
// be sure we have the latest information
UpdateRightSideDCB();
if (GetDCB()->m_errorHR != S_OK)
{
UnrecoverableError(GetDCB()->m_errorHR,
GetDCB()->m_errorCode,
__FILE__, __LINE__);
hr = GetDCB()->m_errorHR;
}
}
return hr;
}
/*
* EnableLogMessages enables/disables sending of log messages to the
* debugger for logging.
*/
HRESULT CordbProcess::EnableLogMessages(BOOL fOnOff)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_ENABLE_LOG_MESSAGES, false, VMPTR_AppDomain::NullPtr());
event->LogSwitchSettingMessage.iLevel = (int)fOnOff;
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::EnableLogMessages: EnableLogMessages=%d sent.\n",
GetCurrentThreadId(), fOnOff));
return hr;
}
/*
* ModifyLogSwitch modifies the specified switch's severity level.
*/
COM_METHOD CordbProcess::ModifyLogSwitch(_In_z_ WCHAR *pLogSwitchName, LONG lLevel)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
HRESULT hr = S_OK;
_ASSERTE (pLogSwitchName != NULL);
DebuggerIPCEvent *event = (DebuggerIPCEvent*) _alloca(CorDBIPC_BUFFER_SIZE);
InitIPCEvent(event, DB_IPCE_MODIFY_LOGSWITCH, false, VMPTR_AppDomain::NullPtr());
event->LogSwitchSettingMessage.iLevel = lLevel;
event->LogSwitchSettingMessage.szSwitchName.SetStringTruncate(pLogSwitchName);
hr = m_cordb->SendIPCEvent(this, event, CorDBIPC_BUFFER_SIZE);
hr = WORST_HR(hr, event->hr);
LOG((LF_CORDB, LL_INFO10000, "[%x] CP::ModifyLogSwitch: ModifyLogSwitch sent.\n",
GetCurrentThreadId()));
return hr;
}
//-----------------------------------------------------------------------------
// Writes a buffer from the target and performs checks similar to SafeWriteStruct
//
// Arguments:
// tb - TargetBuffer which represents the target memory we want to write to
// pLocalBuffer - local pointer into source buffer
// cbSize - the size of local buffer
//
// Exceptions
// On error throws the result of WriteVirtual unless a short write is performed,
// in which case throws ERROR_PARTIAL_COPY
//
void CordbProcess::SafeWriteBuffer(TargetBuffer tb,
const BYTE * pLocalBuffer)
{
_ASSERTE(m_pMutableDataTarget != NULL);
HRESULT hr = m_pMutableDataTarget->WriteVirtual(tb.pAddress,
pLocalBuffer,
tb.cbSize);
IfFailThrow(hr);
}
//-----------------------------------------------------------------------------
// Reads a buffer from the target and performs checks similar to SafeWriteStruct
//
// Arguments:
// tb - TargetBuffer which represents the target memory to read from
// pLocalBuffer - local pointer into source buffer
// cbSize - the size of the remote buffer
// throwOnError - determines whether the function throws exceptions or returns HRESULTs
// in failure cases
//
// Exceptions:
// If throwOnError is TRUE
// On error always throws the special CORDBG_E_READVIRTUAL_FAILURE, unless a short write is performed
// in which case throws ERROR_PARTIAL_COPY
// If throwOnError is FALSE
// No exceptions are thrown, and instead the same error codes are returned as HRESULTs
//
HRESULT CordbProcess::SafeReadBuffer(TargetBuffer tb, BYTE * pLocalBuffer, BOOL throwOnError)
{
ULONG32 cbRead;
HRESULT hr = m_pDACDataTarget->ReadVirtual(tb.pAddress,
pLocalBuffer,
tb.cbSize,
&cbRead);
if (FAILED(hr))
{
if (throwOnError)
ThrowHR(CORDBG_E_READVIRTUAL_FAILURE);
else
return CORDBG_E_READVIRTUAL_FAILURE;
}
if (cbRead != tb.cbSize)
{
if (throwOnError)
ThrowWin32(ERROR_PARTIAL_COPY);
else
return HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
return S_OK;
}
//---------------------------------------------------------------------------------------
// Lookup or create an appdomain.
//
// Arguments:
// vmAppDomain - CLR appdomain to lookup
//
// Returns:
// Instance of CordbAppDomain for the given appdomain. This is a cached instance.
// If the CordbAppDomain does not yet exist, it will be created and added to the cache.
// Never returns NULL. Throw on error.
CordbAppDomain * CordbProcess::LookupOrCreateAppDomain(VMPTR_AppDomain vmAppDomain)
{
CordbAppDomain * pAppDomain = m_appDomains.GetBase(VmPtrToCookie(vmAppDomain));
if (pAppDomain != NULL)
{
return pAppDomain;
}
return CacheAppDomain(vmAppDomain);
}
CordbAppDomain * CordbProcess::GetSharedAppDomain()
{
if (m_sharedAppDomain == NULL)
{
CordbAppDomain *pAD = new CordbAppDomain(this, VMPTR_AppDomain::NullPtr());
if (InterlockedCompareExchangeT<CordbAppDomain*>(&m_sharedAppDomain, pAD, NULL) != NULL)
{
delete pAD;
}
m_sharedAppDomain->InternalAddRef();
}
return m_sharedAppDomain;
}
//---------------------------------------------------------------------------------------
//
// Add a new appdomain to the cache.
//
// Arguments:
// vmAppDomain - appdomain to add.
//
// Return Value:
// Pointer to newly created appdomain, which should be the normal case.
// Throws on failure. Never returns null.
//
// Assumptions:
// Caller ensure the appdomain is not already cached.
// Caller should have stop-go lock, which provides thread-safety.
//
// Notes:
// This sets unrecoverable error on failure.
//
//---------------------------------------------------------------------------------------
CordbAppDomain * CordbProcess::CacheAppDomain(VMPTR_AppDomain vmAppDomain)
{
INTERNAL_API_ENTRY(GetProcess());
_ASSERTE(GetProcessLock()->HasLock());
RSInitHolder<CordbAppDomain> pAppDomain;
pAppDomain.Assign(new CordbAppDomain(this, vmAppDomain)); // throws
// Add to the hash. This will addref the pAppDomain.
// Caller ensures we're not already cached.
// The cache will take ownership.
m_appDomains.AddBaseOrThrow(pAppDomain);
// If this assert fires, then it likely means the target is corrupted.
TargetConsistencyCheck(m_pDefaultAppDomain == NULL);
m_pDefaultAppDomain = pAppDomain;
CordbAppDomain * pReturn = pAppDomain;
pAppDomain.ClearAndMarkDontNeuter();
_ASSERTE(pReturn != NULL);
return pReturn;
}
//---------------------------------------------------------------------------------------
//
// Callback for Appdomain enumeration.
//
// Arguments:
// vmAppDomain - new appdomain to add to enumeration
// pUserData - data passed with callback (a 'this' ptr for CordbProcess)
//
//
// Assumptions:
// Invoked as callback from code:CordbProcess::PrepopulateAppDomains
//
//
//---------------------------------------------------------------------------------------
// static
void CordbProcess::AppDomainEnumerationCallback(VMPTR_AppDomain vmAppDomain, void * pUserData)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
CordbProcess * pProcess = static_cast<CordbProcess *> (pUserData);
INTERNAL_DAC_CALLBACK(pProcess);
pProcess->LookupOrCreateAppDomain(vmAppDomain);
}
//---------------------------------------------------------------------------------------
//
// Traverse appdomains in the target and build up our list.
//
// Arguments:
//
// Return Value:
// returns on success.
// Throws on error. AppDomain cache may be partially populated.
//
// Assumptions:
// This is an non-invasive inspection operation called when the debuggee is stopped.
//
// Notes:
// This can be called multiple times. If the list is non-empty, it will nop.
//---------------------------------------------------------------------------------------
void CordbProcess::PrepopulateAppDomainsOrThrow()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
INTERNAL_API_ENTRY(this);
if (!IsDacInitialized())
{
return;
}
// DD-primitive that invokes a callback. This may throw.
GetDAC()->EnumerateAppDomains(
CordbProcess::AppDomainEnumerationCallback,
this);
}
//---------------------------------------------------------------------------------------
//
// EnumerateAppDomains enumerates all app domains in the process.
//
// Arguments:
// ppAppDomains - get appdomain enumerator
//
// Return Value:
// S_OK on success.
//
// Assumptions:
//
//
// Notes:
// This operation is non-invasive target.
//
//---------------------------------------------------------------------------------------
HRESULT CordbProcess::EnumerateAppDomains(ICorDebugAppDomainEnum **ppAppDomains)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
ValidateOrThrow(ppAppDomains);
// Ensure list is populated.
PrepopulateAppDomainsOrThrow();
RSInitHolder<CordbHashTableEnum> pEnum;
CordbHashTableEnum::BuildOrThrow(
this,
GetContinueNeuterList(),
&m_appDomains,
IID_ICorDebugAppDomainEnum,
pEnum.GetAddr());
*ppAppDomains = static_cast<ICorDebugAppDomainEnum*> (pEnum);
pEnum->ExternalAddRef();
pEnum.ClearAndMarkDontNeuter();
}
PUBLIC_API_END(hr);
return hr;
}
/*
* GetObject returns the runtime process object.
* Note: This method is not yet implemented.
*/
HRESULT CordbProcess::GetObject(ICorDebugValue **ppObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppObject, ICorDebugObjectValue **);
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Given a taskid, finding the corresponding thread. The function can fail if we do not
// find any thread with the given taskid
//
// Arguments:
// taskId - The task ID to look for.
// ppThread - OUT: Space for storing the thread corresponding to the taskId given.
//
// Return Value:
// Typical HRESULT symantics, nothing abnormal.
//
HRESULT CordbProcess::GetThreadForTaskID(TASKID taskId, ICorDebugThread2 ** ppThread)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
if (ppThread == NULL)
{
ThrowHR(E_INVALIDARG);
}
// On initialization, the task ID of every thread is INVALID_TASK_ID, unless a host is present and
// the host calls IClrTask::SetTaskIdentifier(). So we need to explicitly check for INVALID_TASK_ID
// here and return NULL if necessary. We return S_FALSE because that's the return value for the case
// where we can't find a thread for the specified task ID.
if (taskId == INVALID_TASK_ID)
{
*ppThread = NULL;
hr = S_FALSE;
}
else
{
PrepopulateThreadsOrThrow();
// now find the ICorDebugThread corresponding to it
CordbThread * pThread;
HASHFIND hashFind;
for (pThread = m_userThreads.FindFirst(&hashFind);
pThread != NULL;
pThread = m_userThreads.FindNext(&hashFind))
{
if (pThread->GetTaskID() == taskId)
{
break;
}
}
if (pThread == NULL)
{
*ppThread = NULL;
hr = S_FALSE;
}
else
{
*ppThread = pThread;
pThread->ExternalAddRef();
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbProcess::GetThreadForTaskid
HRESULT
CordbProcess::GetVersion(COR_VERSION* pVersion)
{
if (NULL == pVersion)
{
return E_INVALIDARG;
}
//
// Because we require a matching version of mscordbi.dll to debug a certain version of the runtime,
// we can just use constants found in this particular mscordbi.dll to determine the version of the left side.
pVersion->dwMajor = RuntimeProductMajorVersion;
pVersion->dwMinor = RuntimeProductMinorVersion;
pVersion->dwBuild = RuntimeProductPatchVersion;
pVersion->dwSubBuild = 0;
return S_OK;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// Search for a native patch given the address. Return null if not found.
// Since we return an address, this is only valid until the table is disturbed.
//-----------------------------------------------------------------------------
NativePatch * CordbProcess::GetNativePatch(const void * pAddress)
{
_ASSERTE(ThreadHoldsProcessLock());
int cTotal = m_NativePatchList.Count();
NativePatch * pTable = m_NativePatchList.Table();
if (pTable == NULL)
{
return NULL;
}
for(int i = 0; i < cTotal; i++)
{
if (pTable[i].pAddress == pAddress)
{
return &pTable[i];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Is there an break-opcode (int3 on x86) at the address in the debuggee?
//-----------------------------------------------------------------------------
bool CordbProcess::IsBreakOpcodeAtAddress(const void * address)
{
// There should have been an int3 there already. Since we already put it in there,
// we should be able to safely read it out.
#if defined(TARGET_ARM) || defined(TARGET_ARM64)
PRD_TYPE opcodeTest = 0;
#elif defined(TARGET_AMD64) || defined(TARGET_X86)
BYTE opcodeTest = 0;
#else
PORTABILITY_ASSERT("NYI: Architecture specific opcode type to read");
#endif
HRESULT hr = SafeReadStruct(PTR_TO_CORDB_ADDRESS(address), &opcodeTest);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
return (opcodeTest == CORDbg_BREAK_INSTRUCTION);
}
#endif // FEATURE_INTEROP_DEBUGGING
//-----------------------------------------------------------------------------
// CordbProcess::SetUnmanagedBreakpoint
// Called by a native debugger to add breakpoints during Interop.
// address - remote address into the debuggee
// bufsize, buffer[] - initial size & buffer for the opcode that we're replacing.
// buflen - size of the buffer that we write to.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::SetUnmanagedBreakpoint(CORDB_ADDRESS address, ULONG32 bufsize, BYTE buffer[], ULONG32 * bufLen)
{
LOG((LF_CORDB, LL_INFO100, "CP::SetUnBP: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(!ThreadHoldsProcessLock());
Lock();
HRESULT hr = SetUnmanagedBreakpointInternal(address, bufsize, buffer, bufLen);
Unlock();
return hr;
#endif
}
//-----------------------------------------------------------------------------
// CordbProcess::SetUnmanagedBreakpointInternal
// The worker behind SetUnmanagedBreakpoint, this function can set both public
// breakpoints used by the debugger and internal breakpoints used for utility
// purposes in interop debugging.
// address - remote address into the debuggee
// bufsize, buffer[] - initial size & buffer for the opcode that we're replacing.
// buflen - size of the buffer that we write to.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::SetUnmanagedBreakpointInternal(CORDB_ADDRESS address, ULONG32 bufsize, BYTE buffer[], ULONG32 * bufLen)
{
LOG((LF_CORDB, LL_INFO100, "CP::SetUnBPI: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr = S_OK;
NativePatch * p = NULL;
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const BYTE patch = CORDbg_BREAK_INSTRUCTION;
BYTE opcode;
#elif defined(TARGET_ARM64)
const PRD_TYPE patch = CORDbg_BREAK_INSTRUCTION;
PRD_TYPE opcode;
#else
PORTABILITY_ASSERT("NYI: CordbProcess::SetUnmanagedBreakpoint, interop debugging NYI on this platform");
hr = E_NOTIMPL;
goto ErrExit;
#endif
// Make sure args are good
if ((buffer == NULL) || (bufsize < sizeof(patch)) || (bufLen == NULL))
{
hr = E_INVALIDARG;
goto ErrExit;
}
// Fail if there's already a patch at this address.
if (GetNativePatch(CORDB_ADDRESS_TO_PTR(address)) != NULL)
{
hr = CORDBG_E_NATIVE_PATCH_ALREADY_AT_ADDR;
goto ErrExit;
}
// Preallocate this now so that if are oom, we can fail before we get half-way through.
p = m_NativePatchList.Append();
if (p == NULL)
{
hr = E_OUTOFMEMORY;
goto ErrExit;
}
// Read out opcode. 1 byte on x86
hr = ApplyRemotePatch(this, CORDB_ADDRESS_TO_PTR(address), &p->opcode);
if (FAILED(hr))
goto ErrExit;
// It's all successful, so now update our out-params & internal bookkeaping.
#if defined(TARGET_X86) || defined(TARGET_AMD64)
opcode = (BYTE)p->opcode;
buffer[0] = opcode;
#elif defined(TARGET_ARM64)
opcode = p->opcode;
memcpy_s(buffer, bufsize, &opcode, sizeof(opcode));
#else
PORTABILITY_ASSERT("NYI: CordbProcess::SetUnmanagedBreakpoint, interop debugging NYI on this platform");
#endif
*bufLen = sizeof(opcode);
p->pAddress = CORDB_ADDRESS_TO_PTR(address);
p->opcode = opcode;
_ASSERTE(SUCCEEDED(hr));
ErrExit:
// If we failed, then free the patch
if (FAILED(hr) && (p != NULL))
{
m_NativePatchList.Delete(*p);
}
return hr;
#endif // FEATURE_INTEROP_DEBUGGING
}
//-----------------------------------------------------------------------------
// CordbProcess::ClearUnmanagedBreakpoint
// Called by a native debugger to remove breakpoints during Interop.
// The patch is deleted even if the function fails.
//-----------------------------------------------------------------------------
HRESULT
CordbProcess::ClearUnmanagedBreakpoint(CORDB_ADDRESS address)
{
LOG((LF_CORDB, LL_INFO100, "CP::ClearUnBP: pProcess=%x, address=%p.\n", this, CORDB_ADDRESS_TO_PTR(address)));
#ifndef FEATURE_INTEROP_DEBUGGING
return E_NOTIMPL;
#else
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
FAIL_IF_MANAGED_ONLY(this);
_ASSERTE(!ThreadHoldsProcessLock());
HRESULT hr = S_OK;
PRD_TYPE opcode;
Lock();
// Make sure this is a valid patch.
int cTotal = m_NativePatchList.Count();
NativePatch * pTable = m_NativePatchList.Table();
if (pTable == NULL)
{
hr = CORDBG_E_NO_NATIVE_PATCH_AT_ADDR;
goto ErrExit;
}
int i;
for(i = 0; i < cTotal; i++)
{
if (pTable[i].pAddress == CORDB_ADDRESS_TO_PTR(address))
break;
}
if (i >= cTotal)
{
hr = CORDBG_E_NO_NATIVE_PATCH_AT_ADDR;
goto ErrExit;
}
// Found it! Remove it from our table. Note that this may shuffle table contents
// around, so don't keep pointers into the table.
opcode = pTable[i].opcode;
m_NativePatchList.Delete(pTable[i]);
_ASSERTE(m_NativePatchList.Count() == cTotal - 1);
// Now remove the patch.
// Just call through to Write ProcessMemory
hr = RemoveRemotePatch(this, CORDB_ADDRESS_TO_PTR(address), opcode);
if (FAILED(hr))
goto ErrExit;
// Our internal bookeaping was already updated to remove the patch, so now we're done.
// If we had a failure, we should have already bailed.
_ASSERTE(SUCCEEDED(hr));
ErrExit:
Unlock();
return hr;
#endif // FEATURE_INTEROP_DEBUGGING
}
//------------------------------------------------------------------------------------
// StopCount, Sync, SyncReceived form our stop-status. This status is super-critical
// to most hangs, so we stress log it.
//------------------------------------------------------------------------------------
void CordbProcess::SetSynchronized(bool fSynch)
{
_ASSERTE(ThreadHoldsProcessLock() || !"Must have process lock to toggle SyncStatus");
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: set sync=%d\n", fSynch);
m_synchronized = fSynch;
}
bool CordbProcess::GetSynchronized()
{
// This can be accessed whether we're Locked or not. This means that the result
// may change underneath us.
return m_synchronized;
}
void CordbProcess::IncStopCount()
{
_ASSERTE(ThreadHoldsProcessLock());
m_stopCount++;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: Inc StopCount=%d\n", m_stopCount);
}
void CordbProcess::DecStopCount()
{
// We can inc w/ just the process lock (b/c we can dispatch events from the W32ET)
// But decrementing (eg, Continue), requires the stop-go lock.
// This if an operation takes the SG lock, it ensures we don't continue from underneath it.
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
_ASSERTE(ThreadHoldsProcessLock());
m_stopCount--;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: Dec StopCount=%d\n", m_stopCount);
}
// Just gets whether we're stopped or not (m_stopped > 0).
// You only need the StopGo lock for this.
bool CordbProcess::IsStopped()
{
// We don't require the process-lock, just the SG-lock.
// Holding the SG lock prevents another thread from continuing underneath you.
// (see DecStopCount()).
// But you could still be running free, and have another thread stop-underneath you.
// Thus IsStopped() leans towards returning false.
ASSERT_SINGLE_THREAD_ONLY(HoldsLock(&m_StopGoLock));
return (m_stopCount > 0);
}
int CordbProcess::GetStopCount()
{
_ASSERTE(ThreadHoldsProcessLock());
return m_stopCount;
}
bool CordbProcess::GetSyncCompleteRecv()
{
_ASSERTE(ThreadHoldsProcessLock());
return m_syncCompleteReceived;
}
void CordbProcess::SetSyncCompleteRecv(bool fSyncRecv)
{
_ASSERTE(ThreadHoldsProcessLock());
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CP:: set syncRecv=%d\n", fSyncRecv);
m_syncCompleteReceived = fSyncRecv;
}
// This can be used if we ever need the RS to emulate old behavior of previous versions.
// This can not be used in QIs to deny queries for new interfaces.
// QIs must be consistent across the lifetime of an object. Say CordbThread used this in a QI
// do deny returning a ICorDebugThread2 interface when emulating v1.1. Once that Thread is neutered,
// it no longer has a pointer to the process, and it no longer knows if it should be denying
// the v2.0 query. An object's QI can't start returning new interfaces onces its neutered.
bool CordbProcess::SupportsVersion(CorDebugInterfaceVersion featureVersion)
{
_ASSERTE(featureVersion == CorDebugVersion_2_0);
return true;
}
//---------------------------------------------------------------------------------------
// Add an object to the process's Left-Side resource cleanup list
//
// Arguments:
// pObject - non-null object to be added
//
// Notes:
// This list tracks objects with process-scope that hold left-side
// resources (like func-eval).
// See code:CordbAppDomain::GetSweepableExitNeuterList for per-appdomain
// objects with left-side resources.
void CordbProcess::AddToLeftSideResourceCleanupList(CordbBase * pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
m_LeftSideResourceCleanupList.Add(this, pObject);
}
// This list will get actively swept (looking for objects w/ external ref = 0) between continues.
void CordbProcess::AddToNeuterOnExitList(CordbBase *pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
HRESULT hr = S_OK;
EX_TRY
{
this->m_ExitNeuterList.Add(this, pObject);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
// Mark that this object should be neutered the next time we Continue the process.
void CordbProcess::AddToNeuterOnContinueList(CordbBase *pObject)
{
INTERNAL_API_ENTRY(this);
_ASSERTE(pObject != NULL);
m_ContinueNeuterList.Add(this, pObject); // throws
}
/* ------------------------------------------------------------------------- *
* Runtime Controller Event Thread class
* ------------------------------------------------------------------------- */
//
// Constructor
//
CordbRCEventThread::CordbRCEventThread(Cordb* cordb)
{
_ASSERTE(cordb != NULL);
m_cordb.Assign(cordb);
m_thread = NULL;
m_threadId = 0;
m_run = TRUE;
m_threadControlEvent = NULL;
m_processStateChanged = FALSE;
g_pRSDebuggingInfo->m_RCET = this;
}
//
// Destructor. Cleans up all of the open handles and such.
// This expects that the thread has been stopped and has terminated
// before being called.
//
CordbRCEventThread::~CordbRCEventThread()
{
if (m_threadControlEvent != NULL)
CloseHandle(m_threadControlEvent);
if (m_thread != NULL)
CloseHandle(m_thread);
g_pRSDebuggingInfo->m_RCET = NULL;
}
//
// Init sets up all the objects that the thread will need to run.
//
HRESULT CordbRCEventThread::Init()
{
if (m_cordb == NULL)
return E_INVALIDARG;
m_threadControlEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_threadControlEvent == NULL)
return HRESULT_FROM_GetLastError();
return S_OK;
}
#if defined(FEATURE_INTEROP_DEBUGGING)
//
// Helper to duplicate a handle or thorw
//
// Arguments:
// pLocalHandle - handle to duplicate into the remote process
// pRemoteHandle - RemoteHandle structure in IPC block to hold the remote handle.
// Return value:
// None. Throws on error.
//
void CordbProcess::DuplicateHandleToLocalProcess(HANDLE * pLocalHandle, RemoteHANDLE * pRemoteHandle)
{
_ASSERTE(m_pShim != NULL);
// Dup RSEA and RSER into this process if we don't already have them.
// On Launch, we don't have them yet, but on attach we do.
if (*pLocalHandle == NULL)
{
BOOL fSuccess = pRemoteHandle->DuplicateToLocalProcess(m_handle, pLocalHandle);
if (!fSuccess)
{
ThrowLastError();
}
}
}
#endif // FEATURE_INTEROP_DEBUGGING
// Public entry wrapper for code:CordbProcess::FinishInitializeIPCChannelWorker
void CordbProcess::FinishInitializeIPCChannel()
{
// This is called directly from a shim callback.
PUBLIC_API_ENTRY_FOR_SHIM(this);
FinishInitializeIPCChannelWorker();
}
//
// Initialize the IPC channel. After this, IPC events can flow in both ways.
//
// Return value:
// Returns S_OK on success.
//
// Notes:
// This will dispatch an UnrecoverableError callback if it fails.
// This will also initialize key state in the CordbProcess object.
//
// @dbgtodo remove helper-thread: this should eventually go away once we get rid of IPC events.
//
void CordbProcess::FinishInitializeIPCChannelWorker()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
_ASSERTE(m_pShim != NULL);
RSLockHolder lockHolder(&this->m_processMutex);
// If it's already initialized, then nothing left to do.
// this protects us if this function is called multiple times.
if (m_initialized)
{
_ASSERTE(GetDCB() != NULL);
return;
}
EX_TRY
{
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HFRCE: first event..., process %p\n", GetCurrentThreadId(), this));
BOOL fBlockExists;
GetEventBlock(&fBlockExists); // throws on error
LOG((LF_CORDB, LL_EVERYTHING, "Size of CdbP is %d\n", sizeof(CordbProcess)));
m_pEventChannel->Init(m_handle);
#if defined(FEATURE_INTEROP_DEBUGGING)
DuplicateHandleToLocalProcess(&m_leftSideUnmanagedWaitEvent, &GetDCB()->m_leftSideUnmanagedWaitEvent);
#endif // FEATURE_INTEROP_DEBUGGING
// Read the Runtime Offsets struct out of the debuggee.
hr = GetRuntimeOffsets();
IfFailThrow(hr);
// we need to be careful here. The LS will have a thread running free that may be initializing
// fields of the DCB (specifically it may be setting up the helper thread), so we need to make sure
// we don't overwrite any fields that the LS is writing. We need to be sure we only write to RS
// status fields.
m_initialized = true;
GetDCB()->m_rightSideIsWin32Debugger = IsInteropDebugging();
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
LOG((LF_CORDB, LL_INFO1000, "[%x] RCET::HFRCE: ...went fine\n", GetCurrentThreadId()));
_ASSERTE(SUCCEEDED(hr));
} EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
return;
}
// We only land here on failure cases.
// We must have jumped to this label. Maybe we didn't set HR, so check now.
STRESS_LOG1(LF_CORDB, LL_INFO1000, "HFCR: FAILED hr=0x%08x\n", hr);
CloseIPCHandles();
// Rethrow
ThrowHR(hr);
}
//---------------------------------------------------------------------------------------
// Marshals over a string buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_BaseBuffer::CopyLSDataToRSWorker(ICorDebugDataTarget * pTarget)
{
//
const DWORD cbCacheSize = m_cbSize;
// SHOULD not happen for more than once in well-behaved case.
if (m_pbRS != NULL)
{
SIMPLIFYING_ASSUMPTION(!"m_pbRS is non-null; is this a corrupted event?");
ThrowHR(E_INVALIDARG);
}
NewArrayHolder<BYTE> pData(new BYTE[cbCacheSize]);
ULONG32 cbRead;
HRESULT hrRead = pTarget->ReadVirtual(PTR_TO_CORDB_ADDRESS(m_pbLS), pData, cbCacheSize , &cbRead);
if(FAILED(hrRead))
{
hrRead = CORDBG_E_READVIRTUAL_FAILURE;
}
if (SUCCEEDED(hrRead) && (cbCacheSize != cbRead))
{
hrRead = HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY);
}
IfFailThrow(hrRead);
// Now do Transfer
m_pbRS = pData;
pData.SuppressRelease();
}
//---------------------------------------------------------------------------------------
// Marshals over a Byte buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_ByteBuffer::CopyLSDataToRS(ICorDebugDataTarget * pTarget)
{
CopyLSDataToRSWorker(pTarget);
}
//---------------------------------------------------------------------------------------
// Marshals over a string buffer in a managed event
//
// Arguments:
// pTarget - data-target for read the buffer from the LeftSide.
//
// Throws on error
void Ls_Rs_StringBuffer::CopyLSDataToRS(ICorDebugDataTarget * pTarget)
{
CopyLSDataToRSWorker(pTarget);
// Ensure we're a valid, well-formed string.
// @dbgtodo - this should only happen in corrupted scenarios. Perhaps a better HR here?
// - null terminated.
// - no embedded nulls.
const WCHAR * pString = GetString();
SIZE_T dwExpectedLenWithNull = m_cbSize / sizeof(WCHAR);
// Should at least have 1 character for the null-terminator.
if (dwExpectedLenWithNull == 0)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
// Ensure that there's a null where we expect it to be.
if (pString[dwExpectedLenWithNull-1] != 0)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
// Now we know it's safe to call wcslen. The buffer is local, so we know the pages are there.
// And we know there's a null capping the max length of the string.
SIZE_T dwActualLenWithNull = wcslen(pString) + 1;
if (dwActualLenWithNull != dwExpectedLenWithNull)
{
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
}
//---------------------------------------------------------------------------------------
// Marshals the arguments in a managed-debug event.
//
// Arguments:
// pManagedEvent - (IN/OUT) debug event to marshal. Events are not usable in the host process
// until they are marshalled. This will marshal the event in-place, and may convert
// some target addresses to host addresses.
//
// Return Value:
// S_OK on success. Else Error.
//
// Assumptions:
// Target is currently stopped and inspectable.
// After the event is marshalled, it has resources that must be cleaned up
// by calling code:DeleteIPCEventHelper.
//
// Notes:
// Call a Copy function (CopyManagedEventFromTarget, CopyRCEventFromIPCBlock)to
// get the event to marshal.
// This will marshal args from the target into the host.
// The debug event is fixed size. But since the debuggee is stopped, this can copy
// arbitrary-length buffers out of of the debuggee.
//
// This could be rolled into code:CordbProcess::RawDispatchEvent
//---------------------------------------------------------------------------------------
void CordbProcess::MarshalManagedEvent(DebuggerIPCEvent * pManagedEvent)
{
CONTRACTL
{
THROWS;
// Event has already been copied, now we do some quick Marshalling.
// Thsi should be a private local copy, and not the one in the IPC block or Target.
PRECONDITION(CheckPointer(pManagedEvent));
}
CONTRACTL_END;
IfFailThrow(pManagedEvent->hr);
// This may throw part way through marshalling. But that's ok because
// code:DeleteIPCEventHelper can cleanup a partially-marshalled event.
// Do a pre-processing on the event
switch (pManagedEvent->type & DB_IPCE_TYPE_MASK)
{
case DB_IPCE_MDA_NOTIFICATION:
{
pManagedEvent->MDANotification.szName.CopyLSDataToRS(this->m_pDACDataTarget);
pManagedEvent->MDANotification.szDescription.CopyLSDataToRS(this->m_pDACDataTarget);
pManagedEvent->MDANotification.szXml.CopyLSDataToRS(this->m_pDACDataTarget);
break;
}
case DB_IPCE_FIRST_LOG_MESSAGE:
{
pManagedEvent->FirstLogMessage.szContent.CopyLSDataToRS(this->m_pDACDataTarget);
break;
}
default:
break;
}
}
//---------------------------------------------------------------------------------------
// Copy a managed debug event from the target process into this local process
//
// Arguments:
// pRecord - native-debug event serving as the envelope for the managed event.
// pLocalManagedEvent - (dst) required local buffer to hold managed event.
//
// Return Value:
// * True if the event belongs to this runtime. This is very useful when multiple CLRs are
// loaded into the target and all sending events wit the same exception code.
// * False if this does not belong to this instance of ICorDebug. (perhaps it's an event
// intended for another instance of the CLR in the target, or some rogue user code happening
// to use our exception code).
// In either case, the event can still be cleaned up via code:DeleteIPCEventHelper.
//
// Throws on error. In the error case, the contents of pLocalManagedEvent are undefined.
// They may have been partially copied from the target. The local managed event does not own
// any resources until it's marshalled, so the buffer can be ignored if this function fails.
//
// Assumptions:
//
// Notes:
// The events are sent form the target via code:Debugger::SendRawEvent
// This just does a raw Byte copy, but does not do any Marshalling.
// This should always succeed in the well-behaved case. However, A bad debuggee can
// always send a poor-formed debug event.
// We don't distinguish between a badly formed event and an event that's not ours.
// The event still needs to be Marshaled before being used. (see code:CordbProcess::MarshalManagedEvent)
//
//---------------------------------------------------------------------------------------
#if defined(_MSC_VER) && defined(TARGET_ARM)
// This is a temporary workaround for an ARM specific MS C++ compiler bug (internal LKG build 18.1).
// Branch < if (ptrRemoteManagedEvent == NULL) > was always taken and the function always returned false.
// TODO: It should be removed once the bug is fixed.
#pragma optimize("", off)
#endif
bool CordbProcess::CopyManagedEventFromTarget(
const EXCEPTION_RECORD * pRecord,
DebuggerIPCEvent * pLocalManagedEvent)
{
_ASSERTE(pRecord != NULL);
_ASSERTE(pLocalManagedEvent != NULL);
// Initialize the event enough such backout code can call code:DeleteIPCEventHelper.
pLocalManagedEvent->type = DB_IPCE_DEBUGGER_INVALID;
// Ensure we have a CLR instance ID by now. Either we had one already, or we're in
// V2 mode and this is the startup event, and so we'll set it now.
HRESULT hr = EnsureClrInstanceIdSet();
IfFailThrow(hr);
_ASSERTE(m_clrInstanceId != 0);
// Determine if the event is really a debug event, and for our instance.
CORDB_ADDRESS ptrRemoteManagedEvent = IsEventDebuggerNotification(pRecord, m_clrInstanceId);
if (ptrRemoteManagedEvent == NULL)
{
return false;
}
// What we are doing on Windows here is dangerous. Any buffer for IPC events must be at least
// CorDBIPC_BUFFER_SIZE big, but here we are only copying sizeof(DebuggerIPCEvent). Fortunately, the
// only case where an IPC event is bigger than sizeof(DebuggerIPCEvent) is for the second category
// described in the comment for code:IEventChannel. In this case, we are just transferring the IPC
// event from the native pipeline to the event channel, and the event channel will read it directly from
// the send buffer on the LS. See code:CordbRCEventThread::WaitForIPCEventFromProcess.
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
hr = SafeReadStruct(ptrRemoteManagedEvent, pLocalManagedEvent);
#else
// For Mac remote debugging the address returned above is actually a local address.
// Also, we need to copy the entire buffer because once a debug event is read from the debugger
// transport, it won't be available afterwards.
memcpy(reinterpret_cast<BYTE *>(pLocalManagedEvent),
CORDB_ADDRESS_TO_PTR(ptrRemoteManagedEvent),
CorDBIPC_BUFFER_SIZE);
hr = S_OK;
#endif
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
IfFailThrow(hr);
return true;
}
#if defined(_MSC_VER) && defined(TARGET_ARM)
#pragma optimize("", on)
#endif
//---------------------------------------------------------------------------------------
// EnsureClrInstanceIdSet - Ensure we have a CLR Instance ID to debug
//
// In Arrowhead scenarios, the debugger is required to pass a valid CLR instance ID
// to us in OpenVirtualProcess. In V2 scenarios, for compatibility, we'll allow a
// CordbProcess object to exist for a process that doesn't yet have the CLR loaded.
// In this case the CLR instance ID will start off as 0, but be filled in when we see the
// startup exception indicating the CLR has been loaded.
//
// If we don't already have an instance ID, this function sets it to the only CLR in the
// target process. This requires that a CLR be loaded in the target process.
//
// Return Value:
// S_OK - if m_clrInstanceId was already set, or is now set to a valid CLR instance ID
// an error HRESULT - if m_clrInstanceId was 0, and cannot be set to a valid value
// (i.e. because we cannot find a CLR in the target process).
//
// Note that we need to probe for this on attach, and it's common to attach before the
// CLR has been loaded, so we avoid using exceptions for this common case.
//
HRESULT CordbProcess::EnsureClrInstanceIdSet()
{
// If we didn't expect a specific CLR, then attempt to attach to any.
if (m_clrInstanceId == 0)
{
// The only case in which we were allowed to request the "default" CLR instance
// ID is when we're running in V2 mode. In V3, the client is required to pass
// a non-zero value to OpenVirtualProcess. Since V2 is no longer supported we
// no longer attempt to find it.
if(m_cordb->GetTargetCLR() != 0)
{
m_clrInstanceId = PTR_TO_CORDB_ADDRESS(m_cordb->GetTargetCLR());
return S_OK;
}
// In V3, the client is required to pass a non-zero value to OpenVirtualProcess.
// In V2 mode we should be setting target CLR up front but return an error
// if we haven't.
_ASSERTE(m_pShim != NULL);
return E_UNEXPECTED;
}
// We've (now) got a valid CLR instance id
return S_OK;
}
//---------------------------------------------------------------------------------------
// // Copy event from IPC block into local.
//
// Arguments:
// pLocalManagedEvent - required local buffer to hold managed event.
//
// Return Value:
// None. Always succeeds.
//
// Assumptions:
// The IPC block has already been opened and filled in with an event.
//
// Notes:
// This is copying from a shared-memory block, which is treated as local memory.
// This just does a raw Byte copy, but does not do any Marshalling.
// This does no validation on the event.
// The event still needs to be Marshaled before being used. (see code:CordbProcess::MarshalManagedEvent)
//
//---------------------------------------------------------------------------------------
void inline CordbProcess::CopyRCEventFromIPCBlock(DebuggerIPCEvent * pLocalManagedEvent)
{
_ASSERTE(pLocalManagedEvent != NULL);
IfFailThrow(m_pEventChannel->GetEventFromLeftSide(pLocalManagedEvent));
}
// Return true if this is the RCEvent thread, else false.
bool CordbRCEventThread::IsRCEventThread()
{
return (m_threadId == GetCurrentThreadId());
}
//---------------------------------------------------------------------------------------
// Runtime assert, throws CORDBG_E_TARGET_INCONSISTENT if the expression is not true.
//
// Arguments:
// fExpression - assert parameter. If true, this function is a nop. If false,
// this will throw a CORDBG_E_TARGET_INCONSISTENT error.
//
// Notes:
// Use this for runtime checks to validate assumptions about the data-target.
// IcorDebug can't trust that data from the debugee is consistent (perhaps it's
// corrupted).
void CordbProcess::TargetConsistencyCheck(bool fExpression)
{
if (!fExpression)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "Target consistency check failed");
// When debugging possibly corrupt targets, this failure may be expected. For debugging purposes,
// assert if we're not expecting any target inconsistencies.
CONSISTENCY_CHECK_MSG( !m_fAssertOnTargetInconsistency, "Target consistency check failed unexpectedly");
ThrowHR(CORDBG_E_TARGET_INCONSISTENT);
}
}
//
// SendIPCEvent -- send an IPC event to the runtime controller. All this
// really does is copy the event into the process's send buffer and sets
// the RSEA then waits on RSER.
//
// Note: when sending a two-way event (replyRequired = true), the
// eventSize must be large enough for both the event sent and the
// result event.
//
// Returns whether the event was sent successfully. This is different than event->eventHr.
//
HRESULT CordbRCEventThread::SendIPCEvent(CordbProcess* process,
DebuggerIPCEvent* event,
SIZE_T eventSize)
{
_ASSERTE(process != NULL);
_ASSERTE(event != NULL);
_ASSERTE(process->GetShim() != NULL);
#ifdef _DEBUG
// We need to be synchronized whenever we're sending an IPC Event.
// This may require our callers' using a Stop-Continue holder.
// Attach + AsyncBreak are the only (obvious) exceptions.
// For continue, we set Sync-Status to false before sending, so we exclude that too.
// Everybody else should only be sending events when synced. We should never ever ever
// send an event from a CorbXYZ dtor (b/c that would be called at any random time). Instead,
// use a NeuterList.
switch (event->type)
{
case DB_IPCE_ATTACHING:
case DB_IPCE_ASYNC_BREAK:
case DB_IPCE_CONTINUE:
break;
default:
CONSISTENCY_CHECK_MSGF(process->GetSynchronized(), ("Must by synced while sending IPC event: %s (0x%x)",
IPCENames::GetName(event->type), event->type));
}
#endif
LOG((LF_CORDB, LL_EVERYTHING, "SendIPCEvent in CordbRCEventThread called\n"));
// For simplicity sake, we have the following conservative invariants when sending IPC events:
// - Always hold the Stop-Go lock.
// - never on the W32ET.
// - Never hold the Process-lock (this allows the w32et to take that lock to pump)
// Must have the stop-go lock to send an IPC event.
CONSISTENCY_CHECK_MSGF(process->GetStopGoLock()->HasLock(), ("Must have stop-go lock to send event. proc=%p, event=%s",
process, IPCENames::GetName(event->type)));
// The w32 ET will need to take the process lock. So if we're holding it here, then we'll
// deadlock (since W32 ET is blocked on lock, which we would hold; and we're blocked on W32 ET
// to keep pumping.
_ASSERTE(!process->ThreadHoldsProcessLock() || !"Can't hold P-lock while sending blocking IPC event");
// Can't be on the w32 ET, or we can't be pumping.
// Although we can trickle in here from public APIs, our caller should have validated
// that we weren't on the w32et, so the assert here is justified. But just in case there's something we missed,
// we have a runtime check (as a final backstop against a deadlock).
_ASSERTE(!process->IsWin32EventThread());
CORDBFailIfOnWin32EventThread(process);
// If this is an async event, then we expect it to be sent while the process is locked.
if (event->asyncSend)
{
// This may be on the w32et, so we can't hold the stop-go lock.
_ASSERTE(event->type == DB_IPCE_ATTACHING); // only async event should be attaching.
}
// This will catch us if we've detached or exited.
// Note if we exited, then we should have been neutered and so shouldn't even be sending an IPC event,
// but just in case, we'll check.
CORDBRequireProcessStateOK(process);
#ifdef _DEBUG
// We should never send an Async Break on the RCET. This will deadlock.
// - if we're on the RCET, we should be stopped, and thus Stop() should just bump up a stop count,
// and not actually send an AsyncBreak.
// - Delayed-Continues help enforce this.
// This is a special case of the deadlock check below.
if (IsRCEventThread())
{
_ASSERTE(event->type != DB_IPCE_ASYNC_BREAK);
}
#endif
#ifdef _DEBUG
// This assert protects us against a deadlock.
// 1) (RCET) blocked on (This function): If we're on the RCET, then the RCET is blocked until we return (duh).
// 2) (LS) blocked on (RCET): If the LS is not synchronized, then it may be sending an event to the RCET, and thus blocked on the RCET.
// 3) (Helper thread) blocked on (LS): That LS thread may be holding a lock that the helper thread needs, thus blocking the helper thread.
// 4) (This function) blocked on (Helper Thread): We block until the helper thread can process our IPC event.
// #4 is not true for async events.
//
// If we hit this assert, it means we may get the deadlock above and we're calling SendIPCEvent at a time we shouldn't.
// Note this race is as old as dirt.
if (IsRCEventThread() && !event->asyncSend)
{
// Note that w/ Continue & Attach, GetSynchronized() has a different meaning and the race above won't happen.
BOOL fPossibleDeadlock = process->GetSynchronized() || (event->type == DB_IPCE_CONTINUE) || (event->type == DB_IPCE_ATTACHING);
CONSISTENCY_CHECK_MSGF(fPossibleDeadlock, ("Possible deadlock while sending: '%s'\n", IPCENames::GetName(event->type)));
}
#endif
// Cache this process into the MRU so that we can find it if we're debugging in retail.
g_pRSDebuggingInfo->m_MRUprocess = process;
HRESULT hr = S_OK;
HRESULT hrEvent = S_OK;
_ASSERTE(event != NULL);
// NOTE: the eventSize parameter is only so you can specify an event size that is SMALLER than the process send
// buffer size!!
if (eventSize > CorDBIPC_BUFFER_SIZE)
return E_INVALIDARG;
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: sending %s to AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(event->type), VmPtrToCookie(event->vmAppDomain), process->m_id, process->m_id);
// For 2-way events, this check is unnecessary (since we already check for LS exit)
// But for async events, we need this.
// So just check it up here and make everyone's life easier.
if (process->m_terminated)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "CRCET::SIPCE: LS already terminated, shortcut exiting\n");
return CORDBG_E_PROCESS_TERMINATED;
}
// If the helper thread has died, we can't send an IPC event (and it's never coming back either).
// Although we do wait on the thread's handle, there are strange windows where the thread's handle
// is not yet signaled even though we've continued from the exit-thread event for the helper.
if (process->m_helperThreadDead)
{
STRESS_LOG0(LF_CORDB, LL_INFO10000, "CRCET::SIPCE: Helper-thread dead, shortcut exiting\n");
return CORDBG_E_PROCESS_TERMINATED;
}
BOOL fUnrecoverableError = TRUE;
EX_TRY
{
hr = process->GetEventChannel()->SendEventToLeftSide(event, eventSize);
fUnrecoverableError = FALSE;
}
EX_CATCH_HRESULT(hr);
// If we're sending a Continue() event, then after this, the LS may run free.
// If this is the last managed event before the LS exits, (which is the case
// if we're responding to either an Exit-Thread or if we respond to a Detach)
// the LS may exit at anytime from here on, so we need to be careful.
if (fUnrecoverableError)
{
_ASSERTE(FAILED(hr));
CORDBSetUnrecoverableError(process, hr, 0);
}
else
{
// Get a handle to the target process - this call always succeeds
HANDLE hLSProcess = NULL;
process->GetHandle(&hLSProcess);
// We take locks to ensure that the CordbProcess object is still alive,
// even if the OS process exited.
_ASSERTE(hLSProcess != NULL);
// Check if Sending the IPC event failed
if (FAILED(hr))
{
// The failure to send an event may be due to the target process terminating
// (especially, but not exclusively, in the case of async events).
// There is a race here - we can't rely on any check above SendEventToLeftSide
// to tell us whether the process has exited yet.
// Check for that case and return an accurate hresult.
DWORD ret = WaitForSingleObject(hLSProcess, 0);
if (ret == WAIT_OBJECT_0)
{
return CORDBG_E_PROCESS_TERMINATED;
}
// Some other failure sending the IPC event - just return it.
return hr;
}
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: sent...\n");
// If this is an async send, then don't wait for the left side to acknowledge that its read the event.
_ASSERTE(!event->asyncSend || !event->replyRequired);
if (process->GetEventChannel()->NeedToWaitForAck(event))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000,"CRCET::SIPCE: waiting for left side to read event. (on RSER)\n");
DWORD ret;
// Wait for either a reply (common case) or the left side to go away.
// We can't detach while waiting for a reply (because detach needs to send events).
// All of the outcomes from this wait are completely disjoint.
// It's possible for the LS to reply and then exit normally (Thread_Detach, Process_Detach)
// and so ExitProcess may have been called, but it doesn't matter.
enum {
ID_RSER = WAIT_OBJECT_0,
ID_LSPROCESS,
ID_HELPERTHREAD,
};
// Only wait on the helper thread for cases where the process is stopped (and thus we don't expect it do exit on us).
// If the process is running and we lose our helper thread, it ought to be during shutdown and we ough to
// follow up with an exit.
// This includes when we've dispatch Native events, and it includes the AsyncBreak sent to get us from a
// win32 frozen state to a synchronized state).
HANDLE hHelperThread = NULL;
if (process->IsStopped())
{
hHelperThread = process->GetHelperThreadHandle();
}
// Note that in case of a tie (multiple handles signaled), WaitForMultipleObjects gives
// priority to the handle earlier in the array.
HANDLE waitSet[] = { process->GetEventChannel()->GetRightSideEventAckHandle(), hLSProcess, hHelperThread};
DWORD cWaitSet = ARRAY_SIZE(waitSet);
if (hHelperThread == NULL)
{
cWaitSet--;
}
do
{
ret = WaitForMultipleObjectsEx(cWaitSet, waitSet, FALSE, CordbGetWaitTimeout(), FALSE);
// If we timeout because we're waiting for an uncontinued OOB event, we need to just keep waiting.
} while ((ret == WAIT_TIMEOUT) && process->IsWaitingForOOBEvent());
switch(ret)
{
case ID_RSER:
// Normal reply from LS.
// This is set iff the LS replied to our event. The LS may have exited since it replied
// but we don't care. We still have the reply and we'll pass it on.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side read the event.\n");
// If this was a two-way event, then the result is already ready for us. Simply copy the result back
// over the original event that was sent. Otherwise, the left side has simply read the event and is
// processing it...
if (event->replyRequired)
{
process->GetEventChannel()->GetReplyFromLeftSide(event, eventSize);
hrEvent = event->hr;
}
break;
case ID_LSPROCESS:
// Left side exited on us.
// ExitProcess may or may not have been called here (since it's on a different thread).
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side exiting while RS was waiting for reply.\n");
hr = CORDBG_E_PROCESS_TERMINATED;
break;
case ID_HELPERTHREAD:
// We can only send most IPC events while the LS is synchronized. We shouldn't lose our helper thread
// when synced under any sort of normal conditions.
// This won't fire if the process already exited, because LSPROCESS gets higher priority in the wait
// (since it was placed earlier).
// Thus the only "legitimate" window where this could happen would be in a shutdown scenario after
// the helper is dead but before the process has died. We shouldn't be synced in that scenario,
// so we shouldn't be sending IPC events during it.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: lost helper thread.\n");
// Assert because we want to know if we ever actually hit this in any detectable scenario.
// However, shutdown can occur in preemptive mode. Thus if the RS does an AsyncBreak late
// enough, then the LS will appear to be stopped but may still shutdown.
// Since the debuggee can exit asynchronously at any time (eg, suppose somebody forcefully
// kills it with taskman), this doesn't introduce a new case.
// That aside, it would be great to be able to assert this:
//_ASSERTE(!"Potential deadlock - Randomly Lost helper thread");
// We'll piggy back this on the terminated case.
hr = CORDBG_E_PROCESS_TERMINATED;
break;
default:
{
// If we timed out/failed, check the left side to see if it is in the unrecoverable error mode. If it is,
// return the HR from the left side that caused the error. Otherwise, return that we timed out and that
// we don't really know why.
HRESULT realHR = (ret == WAIT_FAILED) ? HRESULT_FROM_GetLastError() : ErrWrapper(CORDBG_E_TIMEOUT);
hr = process->CheckForUnrecoverableError();
if (hr == S_OK)
{
CORDBSetUnrecoverableError(process, realHR, 0);
hr = realHR;
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: left side timeout/fail while RS waiting for reply. hr = 0x%08x\n", hr);
}
break;
}
// If the LS picked up RSEA, it will be reset (since it's an auto event).
// But in the case that the wait failed or that the LS exited, we need to explicitly reset RSEA
if (hr != S_OK)
{
process->GetEventChannel()->ClearEventForLeftSide();
}
// Done waiting for reply.
}
}
process->ForceDacFlush();
// The hr and hrEvent are 2 very different things.
// hr tells us whether the event was sent successfully.
// hrEvent tells us how the LS responded to it.
// if FAILED(hr), then hrEvent is useless b/c the LS never got it.
// But if SUCCEEDED(hr), then hrEvent may still have failed and that could be
// valuable information.
return hr;
}
//---------------------------------------------------------------------------------------
// FlushQueuedEvents flushes a process's event queue.
//
// Arguments:
// pProcess - non-null process object whose queue will be drained
//
// Notes:
// @dbgtodo shim: this should be part of the shim.
// This dispatches events that are queued up. The queue is populated by
// the shim's proxy callback (see code:ShimProxyCallback). This will dispatch events
// to the 'real' callback supplied by the debugger. This will dispatch events
// as long as the debugger keeps calling continue.
//
// This requires that the process lock be held, although it will toggle the lock.
void CordbRCEventThread::FlushQueuedEvents(CordbProcess* process)
{
CONTRACTL
{
NOTHROW; // This is happening on the RCET thread, so there's no place to propagate an error back up.
}
CONTRACTL_END;
STRESS_LOG0(LF_CORDB,LL_INFO10000, "CRCET::FQE: Beginning to flush queue\n");
_ASSERTE(process->GetShim() != NULL);
// We should only call this is we already have queued events
_ASSERTE(!process->GetShim()->GetManagedEventQueue()->IsEmpty());
//
// Dispatch queued events so long as they keep calling Continue()
// before returning from their callback. If they call Continue(),
// process->m_synchronized will be false again and we know to
// loop around and dispatch the next event.
//
_ASSERTE(process->ThreadHoldsProcessLock());
// Give shim a chance to queue any faked attach events. Grab a pointer to the
// ShimProcess now, while we still hold the process lock. Once we release the lock,
// GetShim() may not work.
RSExtSmartPtr<ShimProcess> pShim(process->GetShim());
// Release lock before we call out to shim to Queue fake events.
{
RSInverseLockHolder inverseLockHolder(process->GetProcessLock());
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(pProcess);
// Because we've released the lock, at any point from here forward the
// CorDbProcess may suddenly get neutered if the user detaches the debugger.
pShim->QueueFakeAttachEventsIfNeeded(false);
}
}
// Now that we're holding the process lock again, we can safely check whether
// process has become neutered
if (process->IsNeutered())
{
return;
}
{
// Main dispatch loop here. DispatchRCEvent will take events out of the
// queue and invoke callbacks
do
{
// DispatchRCEvent will mark the process as stopped before dispatching.
process->DispatchRCEvent();
LOG((LF_CORDB,LL_INFO10000, "CRCET::FQE: Finished w/ "
"DispatchRCEvent\n"));
}
while (process->GetSyncCompleteRecv() &&
(process->GetSynchronized() == false) &&
(process->GetShim() != NULL) && // may have lost Shim if we detached while dispatch
(!process->GetShim()->GetManagedEventQueue()->IsEmpty()) &&
(process->m_unrecoverableError == false));
}
//
// If they returned from a callback without calling Continue() then
// the process is still synchronized, so let the rc event thread
// know that it need to update its process list and remove the
// process's event.
//
if (process->GetSynchronized())
{
ProcessStateChanged();
}
LOG((LF_CORDB,LL_INFO10000, "CRCET::FQE: finished\n"));
}
//---------------------------------------------------------------------------------------
// Preliminary Handle an Notification event from the target. This may queue the event,
// but does not actually dispatch the event.
//
// Arguments:
// pManagedEvent - local managed-event. On success, this function assumes ownership of the
// event and will delete its memory. Assumed that caller allocated via 'new'.
// pCallback - callback obecjt to dispatch events on.
//
// Return Value:
// None. Throws on error. On error, caller still owns the pManagedEvent and must free it.
//
// Assumptions:
// This should be called once a notification event is received from the target.
//
// Notes:
// HandleRCEvent -- handle an IPC event received from the runtime controller.
// This will update ICorDebug state and immediately dispatch the event.
//
//---------------------------------------------------------------------------------------
void CordbProcess::HandleRCEvent(
DebuggerIPCEvent * pManagedEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback)
{
CONTRACTL
{
THROWS;
PRECONDITION(CheckPointer(pManagedEvent));
PRECONDITION(CheckPointer(pCallback));
PRECONDITION(ThreadHoldsProcessLock());
}
CONTRACTL_END;
if (!this->IsSafeToSendEvents() || this->m_exiting)
{
return;
}
// Marshals over some standard data from event.
MarshalManagedEvent(pManagedEvent);
STRESS_LOG4(LF_CORDB, LL_INFO1000, "RCET::TP: Got %s for AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(pManagedEvent->type), VmPtrToCookie(pManagedEvent->vmAppDomain), this->m_id, this->m_id);
RSExtSmartPtr<ICorDebugManagedCallback2> pCallback2;
pCallback->QueryInterface(IID_ICorDebugManagedCallback2, reinterpret_cast<void **> (&pCallback2));
RSExtSmartPtr<ICorDebugManagedCallback3> pCallback3;
pCallback->QueryInterface(IID_ICorDebugManagedCallback3, reinterpret_cast<void **> (&pCallback3));
RSExtSmartPtr<ICorDebugManagedCallback4> pCallback4;
pCallback->QueryInterface(IID_ICorDebugManagedCallback4, reinterpret_cast<void **> (&pCallback4));
// Dispatch directly. May not necessarily dispatch an event.
// Toggles the lock to dispatch callbacks.
RawDispatchEvent(pManagedEvent, pLockHolder, pCallback, pCallback2, pCallback3, pCallback4);
}
//
// ProcessStateChanged -- tell the rc event thread that the ICorDebug's
// process list has changed by setting its flag and thread control event.
// This will cause the rc event thread to update its set of handles to wait
// on.
//
void CordbRCEventThread::ProcessStateChanged()
{
m_cordb->LockProcessList();
STRESS_LOG0(LF_CORDB, LL_INFO100000, "CRCET::ProcessStateChanged\n");
m_processStateChanged = TRUE;
SetEvent(m_threadControlEvent);
m_cordb->UnlockProcessList();
}
//---------------------------------------------------------------------------------------
// Primary loop of the Runtime Controller event thread. This routine loops during the
// debug session taking IPC events from the IPC block and calling out to process them.
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Notes:
// @dbgtodo shim: eventually hoist the entire RCET into the shim.
//---------------------------------------------------------------------------------------
void CordbRCEventThread::ThreadProc()
{
HANDLE waitSet[MAXIMUM_WAIT_OBJECTS];
CordbProcess * rgProcessSet[MAXIMUM_WAIT_OBJECTS];
unsigned int waitCount;
#ifdef _DEBUG
memset(&rgProcessSet, NULL, MAXIMUM_WAIT_OBJECTS * sizeof(CordbProcess *));
memset(&waitSet, NULL, MAXIMUM_WAIT_OBJECTS * sizeof(HANDLE));
#endif
// First event to wait on is always the thread control event.
waitSet[0] = m_threadControlEvent;
rgProcessSet[0] = NULL;
waitCount = 1;
while (m_run)
{
DWORD dwStatus = WaitForMultipleObjectsEx(waitCount, waitSet, FALSE, 2000, FALSE);
if (dwStatus == WAIT_FAILED)
{
STRESS_LOG1(LF_CORDB, LL_INFO10000, "CordbRCEventThread::ThreadProc WaitFor"
"MultipleObjects failed: 0x%x\n", GetLastError());
}
#ifdef _DEBUG
else if ((dwStatus >= WAIT_OBJECT_0) && (dwStatus < WAIT_OBJECT_0 + waitCount) && m_run)
{
// Got an event. Figure out which process it came from.
unsigned int procNumber = dwStatus - WAIT_OBJECT_0;
if (procNumber != 0)
{
// @dbgtodo shim: rip all of this out. Leave the assert in for now to verify that we're not accidentally
// going down this codepath. Once we rip this out, we can also simplify some of the code below.
// Notification events (including Sync-complete) should be coming from Win32 event thread via
// V3 pipeline.
_ASSERTE(!"Shouldn't be here");
}
}
#endif
// Empty any queued work items.
DrainWorkerQueue();
// Check a flag to see if we need to update our list of processes to wait on.
if (m_processStateChanged)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "RCET::TP: refreshing process list.\n");
unsigned int i;
//
// free the old wait list
//
for (i = 1; i < waitCount; i++)
{
rgProcessSet[i]->InternalRelease();
}
// Pass 1: iterate the hash of all processes and collect the unsynchronized ones into the wait list.
// Note that Stop / Continue can still be called on a different thread while we're doing this.
m_cordb->LockProcessList();
m_processStateChanged = FALSE;
waitCount = 1;
CordbSafeHashTable<CordbProcess> * pHashTable = m_cordb->GetProcessList();
HASHFIND hashFind;
CordbProcess * pProcess;
for (pProcess = pHashTable->FindFirst(&hashFind); pProcess != NULL; pProcess = pHashTable->FindNext(&hashFind))
{
_ASSERTE(waitCount < MAXIMUM_WAIT_OBJECTS);
if( waitCount >= MAXIMUM_WAIT_OBJECTS )
{
break;
}
// Only listen to unsynchronized processes. Processes that are synchronized will not send events without
// being asked by us first, so there is no need to async listen to them.
//
// Note: if a process is not synchronized then there is no way for it to transition to the syncrhonized
// state without this thread receiving an event and taking action. So there is no need to lock the
// per-process mutex when checking the process's synchronized flag here.
if (!pProcess->GetSynchronized() && pProcess->IsSafeToSendEvents())
{
STRESS_LOG2(LF_CORDB, LL_INFO1000, "RCET::TP: listening to process 0x%x(%d)\n",
pProcess->m_id, pProcess->m_id);
waitSet[waitCount] = pProcess->m_leftSideEventAvailable;
rgProcessSet[waitCount] = pProcess;
rgProcessSet[waitCount]->InternalAddRef();
waitCount++;
}
}
m_cordb->UnlockProcessList();
// Pass 2: for each process that we placed in the wait list, determine if there are any existing queued
// events that need to be flushed.
// Start i at 1 to skip the control event...
i = 1;
while(i < waitCount)
{
pProcess = rgProcessSet[i];
// Take the process lock so we can check the queue safely
pProcess->Lock();
// Now that we've just locked the processes, we can safely inspect it and dispatch events.
// The process may have changed since when we first added it to the process list in Pass 1,
// so we can't make any assumptions about whether it's sync, live, or exiting.
// Flush the queue if necessary. Note, we only do this if we've actually received a SyncComplete message
// from this process. If we haven't received a SyncComplete yet, then we don't attempt to drain any
// queued events yet. They'll be drained when the SyncComplete event is actually received.
if (pProcess->GetSyncCompleteRecv() &&
(pProcess->GetShim() != NULL) &&
!pProcess->GetSynchronized())
{
if (pProcess->GetShim()->GetManagedEventQueue()->IsEmpty())
{
// Effectively what we are doing here is to continue everything without actually
// handling an event. We can get here if the event raised by the LS is a duplicate
// creation event, which the shim discards without adding it to the event queue.
// See code:ShimProcess::IsDuplicateCreationEvent.
//
// To continue, we need to increment the stop count first. Also, we can't call
// Continue() while holding the process lock.
pProcess->SetSynchronized(true);
pProcess->IncStopCount();
pProcess->Unlock();
pProcess->ContinueInternal(FALSE);
pProcess->Lock();
}
else
{
// This may toggle the process-lock
FlushQueuedEvents(pProcess);
}
}
// Flushing could have left the process synchronized...
// Common case is if the callback didn't call Continue().
if (pProcess->GetSynchronized())
{
// remove the process from the wait list by moving all the other processes down one.
if ((i + 1) < waitCount)
{
memcpy(&rgProcessSet[i], &(rgProcessSet[i+1]), sizeof(rgProcessSet[0]) * (waitCount - i - 1));
memcpy(&waitSet[i], &waitSet[i+1], sizeof(waitSet[0]) * (waitCount - i - 1));
}
// drop the count of processes to wait on
waitCount--;
pProcess->Unlock();
// make sure to release the reference we added when the process was added to the wait list.
pProcess->InternalRelease();
// We don't have to increment i because we've copied the next element into
// the current value at i.
}
else
{
// Even after flushing, its still not syncd, so leave it in the wait list.
pProcess->Unlock();
// Increment i normally.
i++;
}
}
} // end ProcessStateChanged
} // while (m_run)
#ifdef _DEBUG_IMPL
// We intentionally return while leaking some CordbProcess objects inside
// rgProcessSet, in some cases (e.g., I've seen this happen when detaching from a
// debuggee almost immediately after attaching to it). In the future, we should
// really consider not leaking these anymore. However, I'm unsure how safe it is to just
// go and InternalRelease() those guys, as above we intentionally DON'T release them when
// they're not synchronized. So for now, to make debug builds happy, exclude those
// references when we run CheckMemLeaks() later on. In our next side-by-side release,
// consider actually doing InternalRelease() on the remaining CordbProcesses on
// retail, and then we can remove the following loop.
for (UINT i=1; i < waitCount; i++)
{
InterlockedDecrement(&Cordb::s_DbgMemTotalOutstandingInternalRefs);
}
#endif //_DEBUG_IMPL
}
//
// This is the thread's real thread proc. It simply calls to the
// thread proc on the given object.
//
/*static*/
DWORD WINAPI CordbRCEventThread::ThreadProc(LPVOID parameter)
{
CordbRCEventThread * pThread = (CordbRCEventThread *) parameter;
INTERNAL_THREAD_ENTRY(pThread);
pThread->ThreadProc();
return 0;
}
template<typename T>
InterlockedStack<T>::InterlockedStack()
{
m_pHead = NULL;
}
template<typename T>
InterlockedStack<T>::~InterlockedStack()
{
// This is an arbitrary choice. We expect the stacks be drained.
_ASSERTE(m_pHead == NULL);
}
// Thread safe pushes + pops.
// Many threads can push simultaneously.
// Only 1 thread can pop.
template<typename T>
void InterlockedStack<T>::Push(T * pItem)
{
// InterlockedCompareExchangePointer(&dest, ex, comp).
// Really behaves like:
// val = *dest;
// if (*dest == comp) { *dest = ex; }
// return val;
//
// We can do a thread-safe assign { comp = dest; dest = ex } via:
// do { comp = dest } while (ICExPtr(&dest, ex, comp) != comp));
do
{
pItem->m_next = m_pHead;
}
while(InterlockedCompareExchangeT(&m_pHead, pItem, pItem->m_next) != pItem->m_next);
}
// Returns NULL on empty,
// else returns the head of the list.
template<typename T>
T * InterlockedStack<T>::Pop()
{
if (m_pHead == NULL)
{
return NULL;
}
// This allows 1 thread to Pop() and race against N threads doing a Push().
T * pItem = NULL;
do
{
pItem = m_pHead;
} while(InterlockedCompareExchangeT(&m_pHead, pItem->m_next, pItem) != pItem);
return pItem;
}
// RCET will take ownership of this item and delete it.
// This can be done w/o taking any locks (thus it can be called from any lock context)
// This may race w/ the RCET draining the queue.
void CordbRCEventThread::QueueAsyncWorkItem(RCETWorkItem * pItem)
{
// @todo -
// Non-blocking insert into queue.
_ASSERTE(pItem != NULL);
m_WorkerStack.Push(pItem);
// Ping the RCET so that it drains the queue.
SetEvent(m_threadControlEvent);
}
// Execute & delete all workitems in the queue.
// This can be done w/o taking any locks. (though individual items may take locks).
void CordbRCEventThread::DrainWorkerQueue()
{
_ASSERTE(IsRCEventThread());
while(true)
{
RCETWorkItem* pCur = m_WorkerStack.Pop();
if (pCur == NULL)
{
break;
}
pCur->Do();
delete pCur;
}
}
//---------------------------------------------------------------------------------------
// Wait for an reply from the debuggee.
//
// Arguments:
// pProcess - process for debuggee.
// pAppDomain - not used.
// pEvent - caller-allocated event to be filled out.
// This is expected to be at least as big as CorDBIPC_BUFFER_SIZE.
//
// Return Value:
// S_OK on success. else failure.
//
// Assumptions:
// Caller allocates
//
// Notes:
// WaitForIPCEventFromProcess waits for an event from just the specified
// process. This should only be called when the process is in a synchronized
// state, which ensures that the RCEventThread isn't listening to the
// process's event, too, which would get confusing.
//
// @dbgtodo - this function should eventually be obsolete once everything
// is using DAC calls instead of helper-thread.
//
//---------------------------------------------------------------------------------------
HRESULT CordbRCEventThread::WaitForIPCEventFromProcess(CordbProcess * pProcess,
CordbAppDomain * pAppDomain,
DebuggerIPCEvent * pEvent)
{
CORDBRequireProcessStateOKAndSync(pProcess, pAppDomain);
DWORD dwStatus;
HRESULT hr = S_OK;
do
{
dwStatus = SafeWaitForSingleObject(pProcess,
pProcess->m_leftSideEventAvailable,
CordbGetWaitTimeout());
if (pProcess->m_terminated)
{
return CORDBG_E_PROCESS_TERMINATED;
}
// If we timeout because we're waiting for an uncontinued OOB event, we need to just keep waiting.
} while ((dwStatus == WAIT_TIMEOUT) && pProcess->IsWaitingForOOBEvent());
if (dwStatus == WAIT_OBJECT_0)
{
pProcess->CopyRCEventFromIPCBlock(pEvent);
EX_TRY
{
pProcess->MarshalManagedEvent(pEvent);
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CRCET::SIPCE: Got %s for AD 0x%x, proc 0x%x(%d)\n",
IPCENames::GetName(pEvent->type),
VmPtrToCookie(pEvent->vmAppDomain),
pProcess->m_id,
pProcess->m_id);
}
EX_CATCH_HRESULT(hr)
SetEvent(pProcess->m_leftSideEventRead);
return hr;
}
else if (dwStatus == WAIT_TIMEOUT)
{
//
// If we timed out, check the left side to see if it is in the
// unrecoverable error mode. If it is, return the HR from the
// left side that caused the error. Otherwise, return that we timed
// out and that we don't really know why.
//
HRESULT realHR = ErrWrapper(CORDBG_E_TIMEOUT);
hr = pProcess->CheckForUnrecoverableError();
if (hr == S_OK)
{
CORDBSetUnrecoverableError(pProcess, realHR, 0);
return realHR;
}
else
return hr;
}
else
{
_ASSERTE(dwStatus == WAIT_FAILED);
hr = HRESULT_FROM_GetLastError();
CORDBSetUnrecoverableError(pProcess, hr, 0);
return hr;
}
}
//
// Start actually creates and starts the thread.
//
HRESULT CordbRCEventThread::Start()
{
if (m_threadControlEvent == NULL)
{
return E_INVALIDARG;
}
m_thread = CreateThread(NULL,
0,
&CordbRCEventThread::ThreadProc,
(LPVOID) this,
0,
&m_threadId);
if (m_thread == NULL)
{
return HRESULT_FROM_GetLastError();
}
return S_OK;
}
//
// Stop causes the thread to stop receiving events and exit. It
// waits for it to exit before returning.
//
HRESULT CordbRCEventThread::Stop()
{
if (m_thread != NULL)
{
LOG((LF_CORDB, LL_INFO100000, "CRCET::Stop\n"));
m_run = FALSE;
SetEvent(m_threadControlEvent);
DWORD ret = WaitForSingleObject(m_thread, INFINITE);
if (ret != WAIT_OBJECT_0)
{
return HRESULT_FROM_GetLastError();
}
}
m_cordb.Clear();
return S_OK;
}
/* ------------------------------------------------------------------------- *
* Win32 Event Thread class
* ------------------------------------------------------------------------- */
enum
{
W32ETA_NONE = 0,
W32ETA_CREATE_PROCESS = 1,
W32ETA_ATTACH_PROCESS = 2,
W32ETA_CONTINUE = 3,
W32ETA_DETACH = 4
};
//---------------------------------------------------------------------------------------
// Constructor
//
// Arguments:
// pCordb - Pointer to the owning cordb object for this event thread.
// pShim - Pointer to the shim for supporting V2 debuggers on V3 architecture.
//
//---------------------------------------------------------------------------------------
CordbWin32EventThread::CordbWin32EventThread(
Cordb * pCordb,
ShimProcess * pShim
) :
m_thread(NULL), m_threadControlEvent(NULL),
m_actionTakenEvent(NULL), m_run(TRUE),
m_action(W32ETA_NONE)
{
m_cordb.Assign(pCordb);
_ASSERTE(pCordb != NULL);
m_pShim = pShim;
m_pNativePipeline = NULL;
}
//
// Destructor. Cleans up all of the open handles and such.
// This expects that the thread has been stopped and has terminated
// before being called.
//
CordbWin32EventThread::~CordbWin32EventThread()
{
if (m_thread != NULL)
CloseHandle(m_thread);
if (m_threadControlEvent != NULL)
CloseHandle(m_threadControlEvent);
if (m_actionTakenEvent != NULL)
CloseHandle(m_actionTakenEvent);
if (m_pNativePipeline != NULL)
{
m_pNativePipeline->Delete();
m_pNativePipeline = NULL;
}
m_sendToWin32EventThreadMutex.Destroy();
}
//
// Init sets up all the objects that the thread will need to run.
//
HRESULT CordbWin32EventThread::Init()
{
if (m_cordb == NULL)
return E_INVALIDARG;
m_sendToWin32EventThreadMutex.Init("Win32-Send lock", RSLock::cLockFlat, RSLock::LL_WIN32_SEND_LOCK);
m_threadControlEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_threadControlEvent == NULL)
return HRESULT_FROM_GetLastError();
m_actionTakenEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL);
if (m_actionTakenEvent == NULL)
return HRESULT_FROM_GetLastError();
m_pNativePipeline = NewPipelineWithDebugChecks();
if (m_pNativePipeline == NULL)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
//
// Main function of the Win32 Event Thread
//
void CordbWin32EventThread::ThreadProc()
{
#if defined(RSCONTRACTS)
DbgRSThread::GetThread()->SetThreadType(DbgRSThread::cW32ET);
// The win32 ET conceptually holds a lock (all threads do).
DbgRSThread::GetThread()->TakeVirtualLock(RSLock::LL_WIN32_EVENT_THREAD);
#endif
// In V2, the debuggee decides what to do if the debugger rudely exits / detaches. (This is
// handled by host policy). With the OS native-debuggging pipeline, the debugger by default
// kills the debuggee if it exits. To emulate V2 behavior, we need to override that default.
BOOL fOk = m_pNativePipeline->DebugSetProcessKillOnExit(FALSE);
(void)fOk; //prevent "unused variable" error from GCC
_ASSERTE(fOk);
// Run the top-level event loop.
Win32EventLoop();
#if defined(RSCONTRACTS)
// The win32 ET conceptually holds a lock (all threads do).
DbgRSThread::GetThread()->ReleaseVirtualLock(RSLock::LL_WIN32_EVENT_THREAD);
#endif
}
// Define a holder that calls code:DeleteIPCEventHelper
using DeleteIPCEventHolder = SpecializedWrapper<DebuggerIPCEvent, DeleteIPCEventHelper>;
//---------------------------------------------------------------------------------------
//
// Helper to clean up IPCEvent before deleting it.
// This must be called after an event is marshalled via code:CordbProcess::MarshalManagedEvent
//
// Arguments:
// pManagedEvent - managed event to delete.
//
// Notes:
// This can delete a partially marshalled event.
//
void DeleteIPCEventHelper(DebuggerIPCEvent *pManagedEvent)
{
CONTRACTL
{
// This is backout code that shouldn't need to throw.
NOTHROW;
}
CONTRACTL_END;
if (pManagedEvent == NULL)
{
return;
}
switch (pManagedEvent->type & DB_IPCE_TYPE_MASK)
{
// so far only this event need to cleanup.
case DB_IPCE_MDA_NOTIFICATION:
pManagedEvent->MDANotification.szName.CleanUp();
pManagedEvent->MDANotification.szDescription.CleanUp();
pManagedEvent->MDANotification.szXml.CleanUp();
break;
case DB_IPCE_FIRST_LOG_MESSAGE:
pManagedEvent->FirstLogMessage.szContent.CleanUp();
break;
default:
break;
}
delete [] (BYTE *)pManagedEvent;
}
//---------------------------------------------------------------------------------------
// Handle a CLR specific notification event.
//
// Arguments:
// pManagedEvent - non-null pointer to a managed event.
// pLockHolder - hold to process lock that gets toggled if this dispatches an event.
// pCallback - callback to dispatch potential managed events.
//
// Return Value:
// Throws on error.
//
// Assumptions:
// Target is stopped. Record was already determined to be a CLR event.
//
// Notes:
// This is called after caller does WaitForDebugEvent.
// Any exception this Filter does not recognize is treated as kNotClr.
// Currently, this includes both managed-exceptions and unmanaged ones.
// For interop-debugging, the interop logic will handle all kNotClr and triage if
// it's really a non-CLR exception.
//
//---------------------------------------------------------------------------------------
void CordbProcess::FilterClrNotification(
DebuggerIPCEvent * pManagedEvent,
RSLockHolder * pLockHolder,
ICorDebugManagedCallback * pCallback)
{
CONTRACTL
{
THROWS;
PRECONDITION(CheckPointer(pManagedEvent));
PRECONDITION(CheckPointer(pCallback));
PRECONDITION(ThreadHoldsProcessLock());
}
CONTRACTL_END;
// There are 3 types of events from the LS:
// 1) Replies (eg, corresponding to WaitForIPCEvent)
// we need to set LSEA/wait on LSER.
// 2) Sync-Complete (kind of like a special notification)
// Ping the helper
// 3) Notifications (eg, Module-load):
// these are dispatched immediately.
// 4) Left-side Startup event
// IF we're synced, then we must be getting a "Reply".
bool fReply = this->GetSynchronized();
LOG((LF_CORDB, LL_INFO10000, "CP::FCN - Received event %s; fReply: %d\n",
IPCENames::GetName(pManagedEvent->type),
fReply));
if (fReply)
{
//
_ASSERTE(m_pShim != NULL);
//
// Case 1: Reply
//
pLockHolder->Release();
_ASSERTE(!ThreadHoldsProcessLock());
// Save the IPC event and wake up the thread which is waiting for it from the LS.
GetEventChannel()->SaveEventFromLeftSide(pManagedEvent);
SetEvent(this->m_leftSideEventAvailable);
// Some other thread called code:CordbRCEventThread::WaitForIPCEventFromProcess, and
// that will respond here and set the event.
DWORD dwResult = WaitForSingleObject(this->m_leftSideEventRead, CordbGetWaitTimeout());
pLockHolder->Acquire();
if (dwResult != WAIT_OBJECT_0)
{
// The wait failed. This is probably WAIT_TIMEOUT which suggests a deadlock/assert on
// the RCEventThread.
CONSISTENCY_CHECK_MSGF(false, ("WaitForSingleObject failed: %d", dwResult));
ThrowHR(CORDBG_E_TIMEOUT);
}
}
else
{
if (pManagedEvent->type == DB_IPCE_LEFTSIDE_STARTUP)
{
//
// Case 4: Left-side startup event. We'll mark that we're attached from oop.
//
// Now that LS is started, we should definitely be able to instantiate DAC.
InitializeDac();
// @dbgtodo 'attach-bit': we don't want the debugger automatically invading the process.
GetDAC()->MarkDebuggerAttached(TRUE);
}
else if (pManagedEvent->type == DB_IPCE_SYNC_COMPLETE)
{
// Since V3 doesn't request syncs, it shouldn't get sync-complete.
// @dbgtodo sync: this changes when V3 can explicitly request an AsyncBreak.
_ASSERTE(m_pShim != NULL);
//
// Case 2: Sync Complete
//
HandleSyncCompleteReceived();
}
else
{
//
// Case 3: Notification. This will dispatch the event immediately.
//
// Toggles the process-lock if it dispatches callbacks.
HandleRCEvent(pManagedEvent, pLockHolder, pCallback);
} // end Notification
}
}
//
// If the thread has an unhandled managed exception, hijack it.
//
// Arguments:
// dwThreadId - OS Thread id.
//
// Returns:
// True if hijacked; false if not.
//
// Notes:
// This is called from shim to emulate being synchronized at an unhandled
// exception.
// Other ICorDebug operations could calls this (eg, func-eval at 2nd chance).
BOOL CordbProcess::HijackThreadForUnhandledExceptionIfNeeded(DWORD dwThreadId)
{
PUBLIC_API_ENTRY(this); // from Shim
BOOL fHijacked = FALSE;
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcessLock());
// OS will not execute the Unhandled Exception Filter under native debugger, so
// we need to hijack the thread to get it to execute the UEF, which will then do
// work for unhandled managed exceptions.
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
if (pThread != NULL)
{
// If the thread has a managed exception, then we should have a pThread object.
if (pThread->HasUnhandledNativeException())
{
_ASSERTE(pThread->IsThreadExceptionManaged()); // should have been marked earlier
pThread->HijackForUnhandledException();
fHijacked = TRUE;
}
}
}
EX_CATCH_HRESULT(hr);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return fHijacked;
}
//---------------------------------------------------------------------------------------
// Validate the given exception record or throw.
//
// Arguments:
// pRawRecord - non-null raw bytes of the exception
// countBytes - number of bytes in pRawRecord buffer.
// format - format of pRawRecord
//
// Returns:
// A type-safe exception record from the raw buffer.
//
// Notes:
// This is a helper for code:CordbProcess::Filter.
// This can do consistency checks on the incoming parameters such as:
// * verify countBytes matches the expected size for the given format.
// * verify the format is supported.
//
// If we let a given ICD understand multiple formats (eg, have x86 understand both Exr32 and
// Exr64), this would be the spot to allow the conversion.
//
const EXCEPTION_RECORD * CordbProcess::ValidateExceptionRecord(
const BYTE pRawRecord[],
DWORD countBytes,
CorDebugRecordFormat format)
{
ValidateOrThrow(pRawRecord);
//
// Check format against expected platform.
//
// @dbgtodo - , cross-plat: Once we do cross-plat, these should be based off target-architecture not host's.
#if defined(HOST_64BIT)
if (format != FORMAT_WINDOWS_EXCEPTIONRECORD64)
{
ThrowHR(E_INVALIDARG);
}
#else
if (format != FORMAT_WINDOWS_EXCEPTIONRECORD32)
{
ThrowHR(E_INVALIDARG);
}
#endif
// @dbgtodo cross-plat: once we do cross-plat, need to use correct EXCEPTION_RECORD variant.
if (countBytes != sizeof(EXCEPTION_RECORD))
{
ThrowHR(E_INVALIDARG);
}
const EXCEPTION_RECORD * pRecord = reinterpret_cast<const EXCEPTION_RECORD *> (pRawRecord);
return pRecord;
};
// Return value: S_OK or indication that no more room exists for enabled types
HRESULT CordbProcess::SetEnableCustomNotification(ICorDebugClass * pClass, BOOL fEnable)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this); // takes the lock
ValidateOrThrow(pClass);
((CordbClass *)pClass)->SetCustomNotifications(fEnable);
PUBLIC_API_END(hr);
return hr;
} // CordbProcess::SetEnableCustomNotification
//---------------------------------------------------------------------------------------
// Public implementation of ICDProcess4::Filter
//
// Arguments:
// pRawRecord - non-null raw bytes of the exception
// countBytes - number of bytes in pRawRecord buffer.
// format - format of pRawRecord
// dwFlags - flags providing auxillary info for exception record.
// dwThreadId - thread that exception occurred on.
// pCallback - callback to dispatch potential managed events on.
// pContinueStatus - Continuation status for exception. This dictates what
// to pass to kernel32!ContinueDebugEvent().
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// Target is stopped.
//
// Notes:
// The exception could be anything, including:
// - a CLR notification,
// - a random managed exception (both from managed code or the runtime),
// - a non-CLR exception
//
// This is cross-platform. The {pRawRecord, countBytes, format} describe events
// on an arbitrary target architecture. On windows, this will be an EXCEPTION_RECORD.
//
HRESULT CordbProcess::Filter(
const BYTE pRawRecord[],
DWORD countBytes,
CorDebugRecordFormat format,
DWORD dwFlags,
DWORD dwThreadId,
ICorDebugManagedCallback * pCallback,
DWORD * pContinueStatus
)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this); // takes the lock
{
//
// Validate parameters
//
// If we don't care about the continue status, we leave it untouched.
ValidateOrThrow(pContinueStatus);
ValidateOrThrow(pCallback);
const EXCEPTION_RECORD * pRecord = ValidateExceptionRecord(pRawRecord, countBytes, format);
DWORD dwFirstChance = (dwFlags & IS_FIRST_CHANCE);
//
// Deal with 2nd-chance exceptions. Don't actually hijack now (that's too invasive),
// but mark that we have the exception in case a future operation (eg, func-eval) needs to hijack.
//
if (!dwFirstChance)
{
CordbThread * pThread = TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
// If we don't have a managed-thread object, then it certainly can't have a throwable.
// It's possible this is still an exception from the native portion of the runtime,
// but that's ok, we'll just treat it as a native exception.
// This could be expensive, don't want to do it often... (definitely not on every Filter).
// OS will not execute the Unhandled Exception Filter under native debugger, so
// we need to hijack the thread to get it to execute the UEF, which will then do
// work for unhandled managed exceptions.
if ((pThread != NULL) && pThread->IsThreadExceptionManaged())
{
// Copy exception record for future use in case we decide to hijack.
pThread->SetUnhandledNativeException(pRecord);
}
// we don't care about 2nd-chance exceptions, unless we decide to hijack it later.
}
//
// Deal with CLR notifications
//
else if (pRecord->ExceptionCode == CLRDBG_NOTIFICATION_EXCEPTION_CODE) // Special event code
{
//
// This may not be for us, or we may not have a managed thread object:
// 1. Anybody can raise an exception with this exception code, so can't assume this belongs to us yet.
// 2. Notifications may come on unmanaged threads if they're coming from MDAs or CLR internal events
// fired before the thread is created.
//
BYTE * pManagedEventBuffer = new BYTE[CorDBIPC_BUFFER_SIZE];
DeleteIPCEventHolder pManagedEvent(reinterpret_cast<DebuggerIPCEvent *>(pManagedEventBuffer));
bool fOwner = CopyManagedEventFromTarget(pRecord, pManagedEvent);
if (fOwner)
{
// This toggles the lock if it dispatches callbacks
FilterClrNotification(pManagedEvent, GET_PUBLIC_LOCK_HOLDER(), pCallback);
// Cancel any notification events from target. These are just supposed to notify ICD and not
// actually be real exceptions in the target.
// Canceling here also prevents a VectoredExceptionHandler in the target from picking
// up exceptions for the CLR.
*pContinueStatus = DBG_CONTINUE;
}
// holder will invoke DeleteIPCEventHelper(pManagedEvent).
}
}
PUBLIC_API_END(hr);
// we may not find the correct mscordacwks so fail gracefully
_ASSERTE(SUCCEEDED(hr) || (hr != HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND)));
return hr;
}
//---------------------------------------------------------------------------------------
// Wrapper to invoke ICorDebugMutableDataTarget::ContinueStatusChanged
//
// Arguments:
// dwContinueStatus - new continue status
//
// Returns:
// None. Throw on error.
//
// Notes:
// Initial continue status is returned from code:CordbProcess::Filter.
// Some operations (mainly hijacking on a 2nd-chance exception), may need to
// override that continue status.
// ICorDebug operations invoke a callback on the data-target to notify the debugger
// of a change in status. Debugger may fail the request.
//
void CordbProcess::ContinueStatusChanged(DWORD dwThreadId, CORDB_CONTINUE_STATUS dwContinueStatus)
{
HRESULT hr = m_pMutableDataTarget->ContinueStatusChanged(dwThreadId, dwContinueStatus);
IfFailThrow(hr);
}
//---------------------------------------------------------------------------------------
// Request a synchronization to occur after a debug event is dispatched.
//
// Note:
// This is called in response to a managed debug event, and so we know that we have
// a worker thread in the process (the one that just sent the event!)
// This can not be called asynchronously.
//---------------------------------------------------------------------------------------
void CordbProcess::RequestSyncAtEvent()
{
GetDAC()->RequestSyncAtEvent();
}
//---------------------------------------------------------------------------------------
//
// Primary loop of the Win32 debug event thread.
//
//
// Arguments:
// None.
//
// Return Value:
// None.
//
// Notes:
// This is it, you've found it, the main guy. This function loops as long as the
// debugger is around calling the OS WaitForDebugEvent() API. It takes the OS Debug
// Event and filters it thru the right-side, continuing the process if not recognized.
//
// @dbgtodo shim: this will become part of the shim.
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::Win32EventLoop()
{
// This must be called from the win32 event thread.
_ASSERTE(IsWin32EventThread());
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: entered win32 event loop\n"));
DEBUG_EVENT event;
// Allow the timeout for WFDE to be adjustable. Default to 25 ms based off perf numbers (see issue VSWhidbey 132368).
DWORD dwWFDETimeout = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_DbgWFDETimeout);
while (m_run)
{
BOOL fEventAvailable = FALSE;
// We should not have any locks right now.
// Have to wait on 2 sources:
// WaitForMultipleObjects - ping for messages (create, attach, Continue, detach) and also
// process exits in the managed-only case.
// Native Debug Events - This is a huge perf hit so we want to avoid it whenever we can.
// Only wait on these if we're interop debugging and if the process is not frozen.
// A frozen process can't send any debug events, so don't bother looking for them.
unsigned int cWaitCount = 1;
HANDLE rghWaitSet[2];
rghWaitSet[0] = m_threadControlEvent;
DWORD dwWaitTimeout = INFINITE;
if (m_pProcess != NULL)
{
// Process is always built on Native debugging pipeline, so it needs to always be prepared to call WFDE
// As an optimization, if the target is stopped, then we can avoid calling WFDE.
{
#ifndef FEATURE_INTEROP_DEBUGGING
// Managed-only, never win32 stopped, so always check for an event.
dwWaitTimeout = 0;
fEventAvailable = m_pNativePipeline->WaitForDebugEvent(&event, dwWFDETimeout, m_pProcess);
#else
// Wait for a Win32 debug event from any processes that we may be attached to as the Win32 debugger.
const bool fIsWin32Stopped = (m_pProcess->m_state & CordbProcess::PS_WIN32_STOPPED) != 0;
const bool fSkipWFDE = fIsWin32Stopped;
const bool fIsInteropDebugging = m_pProcess->IsInteropDebugging();
(void)fIsInteropDebugging; //prevent "unused variable" error from GCC
// Assert checks
_ASSERTE(fIsInteropDebugging == m_pShim->IsInteropDebugging());
if (!fSkipWFDE)
{
dwWaitTimeout = 0;
fEventAvailable = m_pNativePipeline->WaitForDebugEvent(&event, dwWFDETimeout, m_pProcess);
}
else
{
// If we're managed-only debugging, then the process should always be running,
// which means we always need to be calling WFDE to pump potential debug events.
// If we're interop-debugging, then the process can be stopped at a native-debug event,
// in which case we don't have to call WFDE until we resume it again.
// So we can only skip the WFDE when we're interop-debugging.
_ASSERTE(fIsInteropDebugging);
}
#endif // FEATURE_INTEROP_DEBUGGING
}
} // end m_pProcess != NULL
#if defined(FEATURE_INTEROP_DEBUGGING)
// While interop-debugging, the process may get killed rudely underneath us, even if we haven't
// continued the last debug event. In such cases, The process object will get signalled normally.
// If we didn't just get a native-exitProcess event, then listen on the process handle for exit.
// (this includes all managed-only debugging)
// It's very important to establish this before we go into the WaitForMutlipleObjects below
// because the debuggee may exit while we're sitting in that loop (waiting for the debugger to call Continue).
bool fDidNotJustGetExitProcessEvent = !fEventAvailable || (event.dwDebugEventCode != EXIT_PROCESS_DEBUG_EVENT);
#else
// In non-interop scenarios, we'll never get any native debug events, let alone an ExitProcess native event.
bool fDidNotJustGetExitProcessEvent = true;
#endif // FEATURE_INTEROP_DEBUGGING
// The m_pProcess handle will get nulled out after we process the ExitProcess event, and
// that will ensure that we only wait for an Exit event once.
if ((m_pProcess != NULL) && fDidNotJustGetExitProcessEvent)
{
rghWaitSet[1] = m_pProcess->UnsafeGetProcessHandle();
cWaitCount = 2;
}
// See if any process that we aren't attached to as the Win32 debugger have exited. (Note: this is a
// polling action if we are also waiting for Win32 debugger events. We're also looking at the thread
// control event here, too, to see if we're supposed to do something, like attach.
DWORD dwStatus = WaitForMultipleObjectsEx(cWaitCount, rghWaitSet, FALSE, dwWaitTimeout, FALSE);
_ASSERTE((dwStatus == WAIT_TIMEOUT) || (dwStatus < cWaitCount));
if (!m_run)
{
_ASSERTE(m_action == W32ETA_NONE);
break;
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL - got event , ret=%d, has w32 dbg event=%d\n",
dwStatus, fEventAvailable));
// If we haven't timed out, or if it wasn't the thread control event
// that was set, then a process has
// exited...
if ((dwStatus != WAIT_TIMEOUT) && (dwStatus != WAIT_OBJECT_0))
{
// Grab the process that exited.
_ASSERTE((dwStatus - WAIT_OBJECT_0) == 1);
ExitProcess(false); // not detach
fEventAvailable = false;
}
// Should we create a process?
else if (m_action == W32ETA_CREATE_PROCESS)
{
CreateProcess();
}
// Should we attach to a process?
else if (m_action == W32ETA_ATTACH_PROCESS)
{
AttachProcess();
}
// Should we detach from a process?
else if (m_action == W32ETA_DETACH)
{
ExitProcess(true); // detach case
// Once we detach, we don't need to continue any outstanding event.
// So act like we never got the event.
fEventAvailable = false;
PREFIX_ASSUME(m_pProcess == NULL); // W32 cleared process pointer
}
#ifdef FEATURE_INTEROP_DEBUGGING
// Should we continue the process?
else if (m_action == W32ETA_CONTINUE)
{
HandleUnmanagedContinue();
}
#endif // FEATURE_INTEROP_DEBUGGING
// We don't need to sweep the FCH threads since we never hijack a thread in cooperative mode.
// Only process an event if one is available.
if (!fEventAvailable)
{
continue;
}
// The only ref we have is the one in the ProcessList hash;
// If we dispatch an ExitProcess event, we may even lose that.
// But since the CordbProcess is our parent object, we know it won't go away until
// it neuters us, so we can safely proceed.
// Find the process this event is for.
PREFIX_ASSUME(m_pProcess != NULL);
_ASSERTE(m_pProcess->m_id == GetProcessId(&event)); // should only get events for our proc
g_pRSDebuggingInfo->m_MRUprocess = m_pProcess;
// Must flush the dac cache since we were just running.
m_pProcess->ForceDacFlush();
// So we've filtered out CLR events.
// Let the shim handle the remaining events. This will call back into Filter() if appropriate.
// This will also ensure the debug event gets continued.
HRESULT hrShim = S_OK;
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(NULL);
hrShim = m_pShim->HandleWin32DebugEvent(&event);
}
// Any errors from the shim (eg. failure to load DAC) are unrecoverable
SetUnrecoverableIfFailed(m_pProcess, hrShim);
} // loop
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: exiting event loop\n"));
return;
}
//---------------------------------------------------------------------------------------
//
// Returns if the current thread is the win32 thread.
//
// Return Value:
// true iff this is the win32 event thread.
//
//---------------------------------------------------------------------------------------
bool CordbProcess::IsWin32EventThread()
{
_ASSERTE((m_pShim != NULL) || !"Don't check win32 event thread in V3 cases");
return m_pShim->IsWin32EventThread();
}
//---------------------------------------------------------------------------------------
// Call when the sync complete event is received and can be processed.
//
// Notes:
// This is called when the RS gets the sync-complete from the LS and can process it.
//
// This has a somewhat elaborate contract to fill between Interop-debugging, Async-Break, draining the
// managed event-queue, and coordinating with the dispatch thread (RCET).
//
// @dbgtodo - this should eventually get hoisted into the shim.
void CordbProcess::HandleSyncCompleteReceived()
{
_ASSERTE(ThreadHoldsProcessLock());
this->SetSyncCompleteRecv(true);
// If some thread is waiting for the process to sync, notify that it can go now.
if (this->m_stopRequested)
{
this->SetSynchronized(true);
SetEvent(this->m_stopWaitEvent);
}
else
{
// Note: we set the m_stopWaitEvent all the time and leave it high while we're stopped. This
// must be done after we've checked m_stopRequested.
SetEvent(this->m_stopWaitEvent);
// Otherwise, simply mark that the state of the process has changed and let the
// managed event dispatch logic take over.
//
// Note: process->m_synchronized remains false, which indicates to the RC event
// thread that it can dispatch the next managed event.
m_cordb->ProcessStateChanged();
}
}
#ifdef FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// Get (create if needed) the unmanaged thread for an unmanaged debug event.
//
// Arguments:
// event - native debug event.
//
// Return Value:
// Unmanaged thread corresponding to the native debug event.
//
//
// Notes:
// Thread may be newly allocated, or may be existing. CordbProcess holds
// list of all CordbUnmanagedThreads, and will handle freeing memory.
//
//---------------------------------------------------------------------------------------
CordbUnmanagedThread * CordbProcess::GetUnmanagedThreadFromEvent(const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr;
CordbUnmanagedThread * pUnmanagedThread = NULL;
// Remember newly created threads.
if (pEvent->dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT)
{
// We absolutely should have an unmanaged callback by this point.
// That means that the client debugger should have called ICorDebug::SetUnmanagedHandler by now.
// However, we can't actually enforce that (see comment in ICorDebug::SetUnmanagedHandler for details),
// so we do a runtime check to check this.
// This is an extremely gross API misuse and an issue in the client if the callback is not set yet.
// Without the unmanaged callback, we absolutely can't do interop-debugging. We assert (checked builds) and
// dispatch unrecoverable error (retail builds) to avoid an AV.
if (this->m_cordb->m_unmanagedCallback == NULL)
{
CONSISTENCY_CHECK_MSGF((this->m_cordb->m_unmanagedCallback != NULL),
("GROSS API misuse!!\nNo unmanaged callback set by the time we've received CreateProcess debug event for proces 0x%x.\n",
pEvent->dwProcessId));
CORDBSetUnrecoverableError(this, CORDBG_E_INTEROP_NOT_SUPPORTED, 0);
// Returning NULL will tell caller not to dispatch event to client. We have no callback object to dispatch upon.
return NULL;
}
pUnmanagedThread = this->HandleUnmanagedCreateThread(pEvent->dwThreadId,
pEvent->u.CreateProcessInfo.hThread,
pEvent->u.CreateProcessInfo.lpThreadLocalBase);
// Managed-attach won't start until after Cordbg continues from the loader-bp.
}
else if (pEvent->dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT)
{
pUnmanagedThread = this->HandleUnmanagedCreateThread(pEvent->dwThreadId,
pEvent->u.CreateThread.hThread,
pEvent->u.CreateThread.lpThreadLocalBase);
BOOL fBlockExists = FALSE;
hr = S_OK;
EX_TRY
{
// See if we have the debugger control block yet...
this->GetEventBlock(&fBlockExists);
// If we have the debugger control block, and if that control block has the address of the thread proc for
// the helper thread, then we're initialized enough on the Left Side to recgonize the helper thread based on
// its thread proc's address.
if (this->GetDCB() != NULL)
{
// get the latest LS DCB information
UpdateRightSideDCB();
if ((this->GetDCB()->m_helperThreadStartAddr != NULL) && (pUnmanagedThread != NULL))
{
void * pStartAddr = pEvent->u.CreateThread.lpStartAddress;
if (pStartAddr == this->GetDCB()->m_helperThreadStartAddr)
{
// Remember the ID of the helper thread.
this->m_helperThreadId = pEvent->dwThreadId;
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: Left Side Helper Thread is 0x%x\n", pEvent->dwThreadId));
}
}
}
}
EX_CATCH_HRESULT(hr)
{
if (fBlockExists && FAILED(hr))
{
_ASSERTE(IsLegalFatalError(hr));
// Send up the DebuggerError event
this->UnrecoverableError(hr, 0, NULL, 0);
// Kill the process.
// RS will pump events until we LS process exits.
TerminateProcess(this->m_handle, hr);
return pUnmanagedThread;
}
}
}
else
{
// Find the unmanaged thread that this event is for.
pUnmanagedThread = this->GetUnmanagedThread(pEvent->dwThreadId);
}
return pUnmanagedThread;
}
//---------------------------------------------------------------------------------------
//
// Handle a native-debug event representing a managed sync-complete event.
//
//
// Return Value:
// Reaction telling caller how to respond to the native-debug event.
//
// Assumptions:
// Called within the Triage process after receiving a native-debug event.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageSyncComplete()
{
_ASSERTE(ThreadHoldsProcessLock());
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TSC: received 'sync complete' flare.\n");
_ASSERTE(IsInteropDebugging());
// Note: we really don't need to be suspending Runtime threads that we know have tripped
// here. If we ever end up with a nice, quick way to know that about each unmanaged thread, then
// we should put that to good use here.
this->SuspendUnmanagedThreads();
this->HandleSyncCompleteReceived();
// Let the process run free.
return REACTION(cIgnore);
// At this point, all managed threads are stopped at safe places and all unmanaged
// threads are either suspended or hijacked. All stopped managed threads are also hard
// suspended (due to the call to SuspendUnmanagedThreads above) except for the thread
// that sent the sync complete flare.
// We've handled this exception, so skip all further processing.
UNREACHABLE();
}
//-----------------------------------------------------------------------------
// Triage a breakpoint (non-flare) on a "normal" thread.
//-----------------------------------------------------------------------------
Reaction CordbProcess::TriageBreakpoint(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
HRESULT hr = S_OK;
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
_ASSERTE(dwExCode == STATUS_BREAKPOINT);
// There are three cases here:
//
// 1. The breakpoint definetly belongs to the Runtime. (I.e., a BP in our patch table that
// is in managed code.) In this case, we continue the process with
// DBG_EXCEPTION_NOT_HANDLED, which lets the in-process exception logic kick in as if we
// weren't here.
//
// 2. The breakpoint is definetly not ours. (I.e., a BP that is not in our patch table.) We
// pass these up as regular exception events, doing the can't stop check as usual.
//
// 3. We're not sure. (I.e., a BP in our patch table, but set in unmangaed code.) In this
// case, we hijack as usual, also with can't stop check as usual.
bool fPatchFound = false;
bool fPatchIsUnmanaged = false;
hr = this->FindPatchByAddress(PTR_TO_CORDB_ADDRESS(pExAddress),
&fPatchFound,
&fPatchIsUnmanaged);
if (SUCCEEDED(hr))
{
if (fPatchFound)
{
#ifdef _DEBUG
// What if managed & native patch the same address? That could happen on a step out M --> U.
{
NativePatch * pNativePatch = GetNativePatch(pExAddress);
SIMPLIFYING_ASSUMPTION_MSGF(pNativePatch == NULL, ("Have Managed & native patch at 0x%p", pExAddress));
}
#endif
// BP could be ours... if its unmanaged, then we still need to hijack, so fall
// through to that logic. Otherwise, its ours.
if (!fPatchIsUnmanaged)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"belongs to runtime due to patch table match.\n"));
return REACTION(cCLR);
}
else
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"matched in patch table, but its unmanaged so might hijack anyway.\n"));
// If we're in cooperative mode, then we must have a inproc handler, and don't need to hijack
// One way this can happen is the patch placed for a func-eval complete is hit in coop-mode.
if (pUnmanagedThread->GetEEPGCDisabled())
{
LOG((LF_CORDB, LL_INFO10000, "Already in coop-mode, don't need to hijack\n"));
return REACTION(cCLR);
}
else
{
return REACTION(cBreakpointRequiringHijack);
}
}
UNREACHABLE();
}
else // Patch not found
{
// If we're here, then we have a BP that's not in the managed patch table, and not
// in the native patch list. This should be rare. Perhaps an int3 / DebugBreak() / Assert in
// the native code stream.
// Anyway, we don't know about this patch so we can't skip it. The only thing we can do
// is chuck it up to Cordbg and hope they can help us. Note that this is the same case
// we were in w. V1.
// BP doesn't belong to CLR ... so dispatch it to Cordbg as either make it IB or OOB.
// @todo - make the runtime 1 giant Can't stop region.
bool fCantStop = pUnmanagedThread->IsCantStop();
#ifdef _DEBUG
// We rarely expect a raw int3 here. Add a debug check that will assert.
// Tests that know they don't have raw int3 can enable this regkey to get
// extra coverage.
static DWORD s_fBreakOnRawInt3 = -1;
if (s_fBreakOnRawInt3 == -1)
s_fBreakOnRawInt3 = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgBreakOnRawInt3);
if (s_fBreakOnRawInt3)
{
CONSISTENCY_CHECK_MSGF(false, ("Unexpected Raw int3 at:%p on tid 0x%x (%d). CantStop=%d."
"This assert is used by specific tests to get extra checks."
"For normal cases it's ignorable and is enabled by setting DbgBreakOnRawInt3==1.",
pExAddress, pEvent->dwThreadId, pEvent->dwThreadId, fCantStop));
}
#endif
if (fCantStop)
{
// If we're in a can't stop region, then its OOB no matter what at this point.
return REACTION(cOOB);
}
else
{
// PGC must be enabled if we're going to stop for an IB event.
bool PGCDisabled = pUnmanagedThread->GetEEPGCDisabled();
_ASSERTE(!PGCDisabled);
// Bp is definitely not ours, and PGC is not disabled, so in-band exception.
LOG((LF_CORDB, LL_INFO1000, "W32ET::W32EL: breakpoint exception "
"does not belong to the runtime due to failed patch table match.\n"));
return REACTION(cInband);
}
UNREACHABLE();
}
UNREACHABLE();
}
else
{
// Patch table lookup failed? Only on OOM or if ReadProcessMemory fails...
_ASSERTE(!"Patch table lookup failed!");
CORDBSetUnrecoverableError(this, hr, 0);
return REACTION(cOOB);
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a "normal" 1st chance exception on a "normal" thread.
// Not hijacked, not the helper thread, not a flare, etc.. This is the common
// case for a native exception from native code.
//
// Arguments:
// pUnmanagedThread - Pointer to the CordbUnmanagedThread object that we want to hijack.
// pEvent - Pointer to the debug event which contains the exception code and address.
//
// Return Value:
// The Reaction tells if the event is in-band, out-of-band, CLR specific or ignorable.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::Triage1stChanceNonSpecial(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
HRESULT hr = S_OK;
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
// This had better not be a flare. If it is, that means we have some race that unmarked
// the hijacks.
_ASSERTE(!ExceptionIsFlare(dwExCode, pExAddress));
// Any first chance exception could belong to the Runtime, so long as the Runtime has actually been
// initialized. Here we'll setup a first-chance hijack for this thread so that it can give us the
// true answer that we need.
// But none of those exceptions could possibly be ours unless we have a managed thread to go with
// this unmanaged thread. A non-NULL EEThreadPtr tells us that there is indeed a managed thread for
// this unmanaged thread, even if the Right Side hasn't received a managed ThreadCreate message yet.
REMOTE_PTR pEEThread;
hr = pUnmanagedThread->GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
if (pEEThread == NULL)
{
// No managed thread, so it can't possibly belong to the runtime!
// But it may still be in a can't-stop region (think some goofy shutdown case).
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
// We have to be careful here. A Runtime thread may be in a place where we cannot let an
// unmanaged exception stop it. For instance, an unmanaged user breakpoint set on
// WaitForSingleObject will prevent Runtime threads from sending events to the Right Side. So at
// various points below, we check to see if this Runtime thread is in a place were we can't let
// it stop, and if so then we jump over to the out-of-band dispatch logic and treat this
// exception as out-of-band. The debugger is supposed to continue from the out-of-band event
// properly and help us avoid this problem altogether.
// Grab a few flags from the thread's state...
bool fThreadStepping = false;
bool fSpecialManagedException = false;
pUnmanagedThread->GetEEState(&fThreadStepping, &fSpecialManagedException);
// If we've got a single step exception, and if the Left Side has indicated that it was
// stepping the thread, then the exception is ours.
if (dwExCode == STATUS_SINGLE_STEP)
{
if (fThreadStepping)
{
// Yup, its the Left Side that was stepping the thread...
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: single step exception belongs to the runtime.\n");
return REACTION(cCLR);
}
// Any single step that is triggered when the thread's state doesn't indicate that
// we were stepping the thread automatically gets passed out as an unmanged event.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: single step exception "
"does not belong to the runtime.\n");
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
UNREACHABLE();
}
#ifdef CorDB_Short_Circuit_First_Chance_Ownership
// If the runtime indicates that this is a special exception being thrown within the runtime,
// then its ours no matter what.
else if (fSpecialManagedException)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: exception belongs to the runtime due to "
"special managed exception marking.\n");
return REACTION(cCLR);
}
else if ((dwExCode == EXCEPTION_COMPLUS) || (dwExCode == EXCEPTION_HIJACK))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000,
"W32ET::W32EL: exception belongs to Runtime due to match on built in exception code\n");
return REACTION(cCLR);
}
else if (dwExCode == EXCEPTION_MSVC)
{
// The runtime may use C++ exceptions internally. We can still report these
// to the debugger as long as we're outside of a can't-stop region.
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cCLR);
}
else
{
return REACTION(cInband);
}
}
else if (dwExCode == STATUS_BREAKPOINT)
{
return TriageBreakpoint(pUnmanagedThread, pEvent);
}// end BP case
#endif
// It's not a breakpoint or single-step. Now it just comes down to the address from where
// the exception is coming from. If it's managed, we give it back to the CLR. If it's
// from native, then we dispatch to Cordbg.
// We can use DAC to figure this out from Out-of-process.
_ASSERTE(dwExCode != STATUS_BREAKPOINT); // BP were already handled.
// Use DAC to decide if it's ours or not w/o going inproc.
CORDB_ADDRESS address = PTR_TO_CORDB_ADDRESS(pExAddress);
IDacDbiInterface::AddressType addrType;
addrType = GetDAC()->GetAddressType(address);
bool fIsCorCode =((addrType == IDacDbiInterface::kAddressManagedMethod) ||
(addrType == IDacDbiInterface::kAddressRuntimeManagedCode) ||
(addrType == IDacDbiInterface::kAddressRuntimeUnmanagedCode));
STRESS_LOG2(LF_CORDB, LL_INFO1000, "W32ET::W32EL: IsCorCode(0x%I64p)=%d\n", address, fIsCorCode);
if (fIsCorCode)
{
return REACTION(cCLR);
}
else
{
if (pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a 1st-chance exception when the CLR is initialized.
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// A 1st-chance event has a wide spectrum of possibility including:
// - It may be unmanaged or managed.
// - Or it may be an execution control exception for managed-exceution
// - thread skipping an OOB event.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageExcep1stChanceAndInit(CordbUnmanagedThread * pUnmanagedThread,
const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
_ASSERTE(m_runtimeOffsetsInitialized);
NativePatch * pNativePatch = NULL;
DebuggerIPCRuntimeOffsets * pIPCRuntimeOffsets = &(this->m_runtimeOffsets);
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
const void * pExAddress = pEvent->u.Exception.ExceptionRecord.ExceptionAddress;
LOG((LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Enter\n"));
#ifdef _DEBUG
// Some Interop bugs involve threads that land at a bad IP. Since we're interop-debugging, we can't
// attach a debugger to the LS. So we have some debug mode where we enable the SS flag and thus
// produce a trace of where a thread is going.
if (pUnmanagedThread->IsDEBUGTrace() && (dwExCode == STATUS_SINGLE_STEP))
{
pUnmanagedThread->ClearState(CUTS_DEBUG_SingleStep);
LOG((LF_CORDB, LL_INFO10000, "DEBUG TRACE, thread %4x at IP: 0x%p\n", pUnmanagedThread->m_id, pExAddress));
// Clear the exception and pretend this never happened.
return REACTION(cIgnore);
}
#endif
// If we were stepping for exception retrigger and got the single step and it should be hidden then just ignore it.
// Anything that isn't cInbandExceptionRetrigger will cause the debug event to be dequeued, stepping turned off, and
// it will count as not retriggering
// TODO: I don't think the IsSSFlagNeeded() check is needed here though it doesn't break anything
if (pUnmanagedThread->IsSSFlagNeeded() && pUnmanagedThread->IsSSFlagHidden() && (dwExCode == STATUS_SINGLE_STEP))
{
LOG((LF_CORDB, LL_INFO10000, "CP::TE1stCAI: ignoring hidden single step\n"));
return REACTION(cIgnore);
}
// Is this a breakpoint indicating that the Left Side is now synchronized?
if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_notifyRSOfSyncCompleteBPAddr))
{
return TriageSyncComplete();
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_excepForRuntimeHandoffCompleteBPAddr))
{
_ASSERTE(!"This should be unused now");
// This notification means that a thread that had been first-chance hijacked is now
// finally leaving the hijack.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'first chance hijack handoff complete' flare.\n");
// Let the process run.
return REACTION(cIgnore);
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == pIPCRuntimeOffsets->m_signalHijackCompleteBPAddr))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'hijack complete' flare.\n");
return REACTION(cInbandHijackComplete);
}
else if ((dwExCode == STATUS_BREAKPOINT) &&
(pExAddress == m_runtimeOffsets.m_signalHijackStartedBPAddr))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: received 'hijack started' flare.\n");
return REACTION(cFirstChanceHijackStarted);
}
else if ((dwExCode == STATUS_BREAKPOINT) && ((pNativePatch = GetNativePatch(pExAddress)) != NULL) )
{
// We hit a native BP placed by Cordbg. This could happen on any thread (including helper)
bool fCantStop = pUnmanagedThread->IsCantStop();
// REVISIT_TODO: if the user also set a breakpoint here then we should dispatch to the debugger
// and rely on the debugger to get us past this. Should be a rare case though.
if (fCantStop)
{
// Need to skip it completely; never dispatch.
pUnmanagedThread->SetupForSkipBreakpoint(pNativePatch);
// Debuggee will single step over the patch, and fire a SS exception.
// We'll then call FixupForSkipBreakpoint, and continue the process.
return REACTION(cIgnore);
}
else
{
// Native patch in native code. A very common scenario.
// Dispatch as an IB event to Cordbg.
STRESS_LOG1(LF_CORDB, LL_INFO10000, "Native patch in native code (at %p), dispatching as IB event.\n", pExAddress);
return REACTION(cInband);
}
UNREACHABLE();
}
else if ((dwExCode == STATUS_BREAKPOINT) && !IsBreakOpcodeAtAddress(pExAddress))
{
// If we got an int3 exception, but there's not actually an int3 at the address, then just reset the IP
// to the address. This can happen if the int 3 is cleared after the thread has dispatched it (in which case
// WFDE will pick it up) but before we realize it's one of ours.
STRESS_LOG2(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Phantom Int3: Tid=0x%x, addr=%p\n", pEvent->dwThreadId, pExAddress);
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
BOOL fSuccess = DbiGetThreadContext(pUnmanagedThread->m_handle, &context);
_ASSERTE(fSuccess);
if (fSuccess)
{
// Backup IP to point to the instruction we need to execute. Continuing from a breakpoint exception
// continues execution at the instruction after the breakpoint, but we need to continue where the
// breakpoint was.
CORDbgSetIP(&context, (LPVOID) pExAddress);
fSuccess = DbiSetThreadContext(pUnmanagedThread->m_handle, &context);
_ASSERTE(fSuccess);
}
return REACTION(cIgnore);
}
else if (pUnmanagedThread->IsSkippingNativePatch())
{
// If we Single-Step over an exception, then the OS never gives us the single-step event.
// Thus if we're skipping a native patch, we don't care what exception event we got.
LOG((LF_CORDB, LL_INFO100000, "Done skipping native patch. Ex=0x%x\n, IsSS=%d",
dwExCode,
(dwExCode == STATUS_SINGLE_STEP)));
// This is the 2nd half of skipping a native patch.
// This could happen on any thread (including helper)
// We've already removed the opcode and now we just finished a single-step over it.
// So put the patch back in, and continue the process.
pUnmanagedThread->FixupForSkipBreakpoint();
return REACTION(cIgnore);
}
else if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
// We should never ever get a single-step event from the helper thread.
CONSISTENCY_CHECK_MSGF(dwExCode != STATUS_SINGLE_STEP, (
"Single-Step exception on helper thread (tid=0x%x/%d) in debuggee process (pid=0x%x/%d).\n"
"For more information, attach a debuggee non-invasively to the LS to get the callstack.\n",
pUnmanagedThread->m_id,
pUnmanagedThread->m_id,
this->m_id,
this->m_id));
// We ignore any first chance exceptions from the helper thread. There are lots of places
// on the left side where we attempt to dereference bad object refs and such that will be
// handled by exception handlers already in place.
//
// Note: we check this after checking for the sync complete notification, since that can
// come from the helper thread.
//
// Note: we do let single step and breakpoint exceptions go through to the debugger for processing.
if ((dwExCode != STATUS_BREAKPOINT) && (dwExCode != STATUS_SINGLE_STEP))
{
return REACTION(cCLR);
}
else
{
// Since the helper thread is part of the "can't stop" region, we should have already
// skipped any BPs on it.
// However, any Assert on the helper thread will hit this case.
CONSISTENCY_CHECK_MSGF((dwExCode != STATUS_BREAKPOINT), (
"Assert on helper thread (tid=0x%x/%d) in debuggee process (pid=0x%x/%d).\n"
"For more information, attach a debuggee non-invasively to the LS to get the callstack.\n",
pUnmanagedThread->m_id,
pUnmanagedThread->m_id,
this->m_id,
this->m_id));
// These breakpoint and single step exceptions have to be dispatched to the debugger as
// out-of-band events. This tells the debugger that they must continue from these events
// immediatly, and that no interaction with the Left Side is allowed until they do so. This
// makes sense, since these events are on the helper thread.
return REACTION(cOOB);
}
UNREACHABLE();
}
else if (pUnmanagedThread->IsFirstChanceHijacked() && this->ExceptionIsFlare(dwExCode, pExAddress))
{
_ASSERTE(!"This should be unused now");
}
else if (pUnmanagedThread->IsGenericHijacked())
{
if (this->ExceptionIsFlare(dwExCode, pExAddress))
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TE1stCAI: fixing up from generic hijack.\n");
_ASSERTE(dwExCode == STATUS_BREAKPOINT);
// Fixup the thread from the generic hijack.
pUnmanagedThread->FixupFromGenericHijack();
// We force continue from this flare, since its only purpose was to notify us that we had to
// fixup the thread from a generic hijack.
return REACTION(cIgnore);
}
else
{
// We might reach here due to the stack overflow issue, due to target
// memory corruption, or even due to an exception thrown during hijacking
BOOL bStackOverflow = FALSE;
if (dwExCode == STATUS_ACCESS_VIOLATION || dwExCode == STATUS_STACK_OVERFLOW)
{
CORDB_ADDRESS stackLimit;
CORDB_ADDRESS stackBase;
if (pUnmanagedThread->GetStackRange(&stackBase, &stackLimit))
{
TADDR addr = pEvent->u.Exception.ExceptionRecord.ExceptionInformation[1];
if (stackLimit <= addr && addr < stackBase)
bStackOverflow = TRUE;
}
else
{
// to limit the impact of the change we'll consider failure to retrieve the stack
// bounds as stack overflow as well
bStackOverflow = TRUE;
}
}
if (!bStackOverflow)
{
// generic hijack means we're in CantStop, so return cOOB
return REACTION(cOOB);
}
// If generichijacked and its not a flare, and the address referenced is on the stack then we've
// got our special stack overflow case. Take off generic hijacked, mark that the helper thread
// is dead, throw this event on the floor, and pop anyone in SendIPCEvent out of their wait.
pUnmanagedThread->ClearState(CUTS_GenericHijacked);
this->m_helperThreadDead = true;
// This only works on Windows, not on Mac. We don't support interop-debugging on Mac anyway.
SetEvent(m_pEventChannel->GetRightSideEventAckHandle());
// Note: we remember that this was a second chance event from one of the special stack overflow
// cases with CUES_ExceptionUnclearable. This tells us to force the process to terminate when we
// continue from the event. Since for some odd reason the OS decides to re-raise this exception
// (first chance then second chance) infinitely.
_ASSERTE(pUnmanagedThread->HasIBEvent());
pUnmanagedThread->IBEvent()->SetState(CUES_ExceptionUnclearable);
//newEvent = false;
return REACTION(cInband_NotNewEvent);
}
}
else
{
LOG((LF_CORDB, LL_INFO1000, "CP::TE1stCAI: Triage1stChanceNonSpecial\n"));
Reaction r(REACTION(cOOB));
HRESULT hrCheck = S_OK;;
EX_TRY
{
r = Triage1stChanceNonSpecial(pUnmanagedThread, pEvent);
}
EX_CATCH_HRESULT(hrCheck);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hrCheck));
SetUnrecoverableIfFailed(this, hrCheck);
return r;
}
// At this point, any first-chance exceptions that could be special have been handled. Any
// first-chance exception that we're still processing at this point is destined to be
// dispatched as an unmanaged event.
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Triage a 2nd-chance exception when the CLR is initialized.
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// We already hijacked 2nd-chance managed exceptions, so this is just handling
// some V2 Interop corner cases.
// @dbgtodo interop: this should eventually completely go away with the V3 design.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageExcep2ndChanceAndInit(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
DWORD dwExCode = pEvent->u.Exception.ExceptionRecord.ExceptionCode;
#ifdef _DEBUG
// For debugging, add an extra knob that let us break on any 2nd chance exceptions.
// Most tests don't throw 2nd-chance, so we could have this enabled most of the time and
// catch bogus 2nd chance exceptions
static DWORD dwNo2ndChance = -1;
if (dwNo2ndChance == -1)
{
dwNo2ndChance = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgNo2ndChance);
}
if (dwNo2ndChance)
{
CONSISTENCY_CHECK_MSGF(false, ("2nd chance exception occurred on LS thread=0x%x, code=0x%08x, address=0x%p\n"
"This assert is firing b/c you explicitly requested it by having the 'DbgNo2ndChance' knob enabled.\n"
"Disable it to avoid asserts on 2nd chance.",
pUnmanagedThread->m_id,
dwExCode,
pEvent->u.Exception.ExceptionRecord.ExceptionAddress));
}
#endif
// Second chance exception, Runtime initialized. It could belong to the Runtime, so we'll check. If it
// does, then we'll hijack the thread. Otherwise, well just fall through and let it get
// dispatched. Note: we do this so that the CLR's unhandled exception logic gets a chance to run even
// though we've got a win32 debugger attached. But the unhandled exception logic never touches
// breakpoint or single step exceptions, so we ignore those here, too.
// There are strange cases with stack overflow exceptions. If a nieve application catches a stack
// overflow exception and handles it, without resetting the guard page, then the app will get an AV when
// it overflows the stack a second time. We will get the first chance AV, but when we continue from it the
// OS won't run any SEH handlers, so our FCH won't actually work. Instead, we'll get the AV back on
// second chance right away, and we'll end up right here.
if (this->IsSpecialStackOverflowCase(pUnmanagedThread, pEvent))
{
// IsSpecialStackOverflowCase will queue the event for us, so its no longer a "new event". Setting
// newEvent = false here basically prevents us from playing with the event anymore and we fall down
// to the dispatch logic below, which will get our already queued first chance AV dispatched for
// this thread.
//newEvent = false;
return REACTION(cInband_NotNewEvent);
}
else if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
// A second chance exception from the helper thread. This is pretty bad... we just force continue
// from them and hope for the best.
return REACTION(cCLR);
}
if(pUnmanagedThread->IsCantStop())
{
return REACTION(cOOB);
}
else
{
return REACTION(cInband);
}
}
//---------------------------------------------------------------------------------------
//
// Triage a win32 Debug event to get a reaction
//
// Arguments:
// pUnmanagedThread - thread that the event has occurred on.
// pEvent - native debug event for the exception that occurred that this is triaging.
//
// Return Value:
// Reaction for how to handle this event.
//
// Assumptions:
// Called when receiving a debug event when the process is stopped.
//
// Notes:
// This is the main triage routine for Win32 debug events, this delegates to the
// 1st and 2nd chance routines above appropriately.
//
//---------------------------------------------------------------------------------------
Reaction CordbProcess::TriageWin32DebugEvent(CordbUnmanagedThread * pUnmanagedThread, const DEBUG_EVENT * pEvent)
{
_ASSERTE(ThreadHoldsProcessLock());
// Lots of special cases for exception events. The vast majority of hybrid debugging work that takes
// place is in response to exception events. The work below will consider certian exception events
// special cases and rather than letting them be queued and dispatched, they will be handled right
// here.
if (pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
STRESS_LOG4(LF_CORDB, LL_INFO1000, "CP::TW32DE: unmanaged exception on "
"tid 0x%x, code 0x%08x, addr 0x%08x, chance %d\n",
pEvent->dwThreadId,
pEvent->u.Exception.ExceptionRecord.ExceptionCode,
pEvent->u.Exception.ExceptionRecord.ExceptionAddress,
2-pEvent->u.Exception.dwFirstChance);
#ifdef LOGGING
if (pEvent->u.Exception.ExceptionRecord.ExceptionCode == STATUS_ACCESS_VIOLATION)
{
LOG((LF_CORDB, LL_INFO1000, "\t<%s> address 0x%08x\n",
pEvent->u.Exception.ExceptionRecord.ExceptionInformation[0] ? "write to" : "read from",
pEvent->u.Exception.ExceptionRecord.ExceptionInformation[1]));
}
#endif
// Mark the loader bp for kicks. We won't start managed attach until native attach is finished.
if (!this->m_loaderBPReceived)
{
// If its a first chance breakpoint, and its the first one, then its the loader breakpoint.
if (pEvent->u.Exception.dwFirstChance &&
(pEvent->u.Exception.ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT))
{
LOG((LF_CORDB, LL_INFO1000, "CP::TW32DE: loader breakpoint received.\n"));
// Remember that we've received the loader BP event.
this->m_loaderBPReceived = true;
// We never hijack the loader BP anymore (CLR 2.0+).
// This is b/c w/ interop-attach, we don't start the managed-attach until _after_ Cordbg
// continues from the loader-bp.
}
} // end of loader bp.
// This event might be the retriggering of an event we already saw but previously had to hijack
if(pUnmanagedThread->HasIBEvent())
{
const EXCEPTION_RECORD* pRecord1 = &(pEvent->u.Exception.ExceptionRecord);
const EXCEPTION_RECORD* pRecord2 = &(pUnmanagedThread->IBEvent()->m_currentDebugEvent.u.Exception.ExceptionRecord);
if(pRecord1->ExceptionCode == pRecord2->ExceptionCode &&
pRecord1->ExceptionFlags == pRecord2->ExceptionFlags &&
pRecord1->ExceptionAddress == pRecord2->ExceptionAddress)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "CP::TW32DE: event is continuation of previously hijacked event.\n");
// if we continued from the hijack then we should have already dispatched this event
_ASSERTE(pUnmanagedThread->IBEvent()->IsDispatched());
return REACTION(cInbandExceptionRetrigger);
}
}
// We only care about exception events if they are first chance events and if the Runtime is
// initialized within the process. Otherwise, we don't do anything special with them.
if (pEvent->u.Exception.dwFirstChance && this->m_initialized)
{
return TriageExcep1stChanceAndInit(pUnmanagedThread, pEvent);
}
else if (!pEvent->u.Exception.dwFirstChance && this->m_initialized)
{
return TriageExcep2ndChanceAndInit(pUnmanagedThread, pEvent);
}
else
{
// An exception event, but the Runtime hasn't been initialize. I.e., its an exception event
// that we will never try to hijack.
return REACTION(cInband);
}
UNREACHABLE();
}
else
// OOB
{
return REACTION(cOOB);
}
}
//---------------------------------------------------------------------------------------
//
// Top-level handler for a win32 debug event during Interop-debugging.
//
// Arguments:
// event - native debug event to handle.
//
// Assumptions:
// The process just got a native debug event via WaitForDebugEvent
//
// Notes:
// The function will Triage the excpetion and then handle it based on the
// appropriate reaction (see: code:Reaction).
//
// @dbgtodo interop: this should all go into the shim.
//---------------------------------------------------------------------------------------
void CordbProcess::HandleDebugEventForInteropDebugging(const DEBUG_EVENT * pEvent)
{
PUBLIC_API_ENTRY_FOR_SHIM(this);
_ASSERTE(IsInteropDebugging() || !"Only do this in real interop handling path");
STRESS_LOG3(LF_CORDB, LL_INFO1000, "W32ET::W32EL: got unmanaged event %d on thread 0x%x, proc 0x%x\n",
pEvent->dwDebugEventCode, pEvent->dwThreadId, pEvent->dwProcessId);
// Get the Lock.
_ASSERTE(!this->ThreadHoldsProcessLock());
RSSmartPtr<CordbProcess> pRef(this); // make sure we're alive...
RSLockHolder processLockHolder(&this->m_processMutex);
// If we get a new Win32 Debug event, then we need to flush any cached oop data structures.
// This includes refreshing DAC and our patch table.
ForceDacFlush();
ClearPatchTable();
#ifdef _DEBUG
// We want to detect if we've deadlocked. Unfortunately, w/ interop debugging, there can be a lot of
// deadtime since we need to wait for a debug event. Thus the CPU usage may appear to be at 0%, but
// we're not deadlocked b/c we're still receiving debug events.
// So ping every X debug events.
static int s_cCount = 0;
static int s_iPingLevel = -1;
if (s_iPingLevel == -1)
{
s_iPingLevel = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgPingInterop);
}
if (s_iPingLevel != 0)
{
s_cCount++;
if (s_cCount >= s_iPingLevel)
{
s_cCount = 0;
::Beep(1000,100);
// Refresh so we can adjust ping level midstream.
s_iPingLevel = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgPingInterop);
}
}
#endif
bool fNewEvent = true;
// Mark the process as stopped.
this->m_state |= CordbProcess::PS_WIN32_STOPPED;
CordbUnmanagedThread * pUnmanagedThread = GetUnmanagedThreadFromEvent(pEvent);
// In retail, if there is no unmanaged thread then we just continue and loop back around. UnrecoverableError has
// already been set in this case. Note: there is an issue in the Win32 debugging API that can cause duplicate
// ExitThread events. We therefore must handle not finding an unmanaged thread gracefully.
_ASSERTE((pUnmanagedThread != NULL) || (pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT));
if (pUnmanagedThread == NULL)
{
// Note: we use ContinueDebugEvent directly here since our continue is very simple and all of our other
// continue mechanisms rely on having an UnmanagedThread object to play with ;)
STRESS_LOG2(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Continuing without thread on tid 0x%x, code=0x%x\n",
pEvent->dwThreadId,
pEvent->dwDebugEventCode);
this->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
BOOL fOk = ContinueDebugEvent(pEvent->dwProcessId, pEvent->dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
_ASSERTE(fOk || !"ContinueDebugEvent failed when he have no thread. Debuggee is likely hung");
return;
}
// There's an innate race such that we can get a Debug Event even after we've suspended a thread.
// This can happen if the thread has already dispatched the debug event but we haven't called WFDE to pick it up
// yet. This is sufficiently goofy that we want to stress log it.
if (pUnmanagedThread->IsSuspended())
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Thread 0x%x is suspended\n", pEvent->dwThreadId);
}
// For debugging races in retail, we'll keep a rolling queue of win32 debug events.
this->DebugRecordWin32Event(pEvent, pUnmanagedThread);
// Check to see if shutdown of the in-proc debugging services has begun. If it has, then we know we'll no longer
// be running any managed code, and we know that we can stop hijacking threads. We remember this by setting
// m_initialized to false, thus preventing most things from happening elsewhere.
// Don't even bother checking the DCB fields until it's been verified (m_initialized == true)
if (this->m_initialized && (this->GetDCB() != NULL))
{
UpdateRightSideDCB();
if (this->GetDCB()->m_shutdownBegun)
{
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: shutdown begun...\n");
this->m_initialized = false;
}
}
#ifdef _DEBUG
//Verify that GetThreadContext agrees with the exception address
if (pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
DT_CONTEXT tempDebugContext;
tempDebugContext.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(pUnmanagedThread->m_handle, &tempDebugContext);
CordbUnmanagedThread::LogContext(&tempDebugContext);
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const ULONG_PTR breakpointOpcodeSize = 1;
#elif defined(TARGET_ARM64)
const ULONG_PTR breakpointOpcodeSize = 4;
#else
const ULONG_PTR breakpointOpcodeSize = 1;
PORTABILITY_ASSERT("NYI: Breakpoint size offset for this platform");
#endif
_ASSERTE(CORDbgGetIP(&tempDebugContext) == pEvent->u.Exception.ExceptionRecord.ExceptionAddress ||
(DWORD)(size_t)CORDbgGetIP(&tempDebugContext) == ((DWORD)(size_t)pEvent->u.Exception.ExceptionRecord.ExceptionAddress)+breakpointOpcodeSize);
}
#endif
// This call will decide what to do w/ the the win32 event we just got. It does a lot of work.
Reaction reaction = TriageWin32DebugEvent(pUnmanagedThread, pEvent);
// Stress-log the reaction.
#ifdef _DEBUG
STRESS_LOG3(LF_CORDB, LL_INFO1000, "Reaction: %d (%s), line=%d\n",
reaction.GetType(),
reaction.GetReactionName(),
reaction.GetLine());
#else
STRESS_LOG1(LF_CORDB, LL_INFO1000, "Reaction: %d\n", reaction.GetType());
#endif
// Make sure the lock wasn't accidentally released.
_ASSERTE(ThreadHoldsProcessLock());
CordbWin32EventThread * pW32EventThread = this->m_pShim->GetWin32EventThread();
_ASSERTE(pW32EventThread != NULL);
// if we were waiting for a retriggered exception but received any other event then turn
// off the single stepping and dequeue the IB event. Right now we only use the SS flag internally
// for stepping during possible retrigger.
if(reaction.GetType() != Reaction::cInbandExceptionRetrigger && pUnmanagedThread->IsSSFlagNeeded())
{
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
_ASSERTE(pUnmanagedEvent->IsIBEvent());
_ASSERTE(pUnmanagedEvent->IsEventContinuedUnhijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
LOG((LF_CORDB, LL_INFO100000, "CP::HDEFID: IB event did not retrigger ue=0x%p\n", pUnmanagedEvent));
DequeueUnmanagedEvent(pUnmanagedThread);
pUnmanagedThread->EndStepping();
}
switch(reaction.GetType())
{
// Common for flares.
case Reaction::cIgnore:
// Shouldn't be suspending in the first place with outstanding flares.
_ASSERTE(!pUnmanagedThread->IsSuspended());
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
case Reaction::cCLR:
// Don't care if thread is suspended here. We'll just let the thread continue whatever it's doing.
this->m_DbgSupport.m_TotalCLR++;
// If this is for the CLR, then we just continue unhandled and know that the CLR has
// a handler inplace to deal w/ this exception.
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_EXCEPTION_NOT_HANDLED, false);
goto LDone;
case Reaction::cInband_NotNewEvent:
fNewEvent = false;
// fall through to Inband case...
case Reaction::cInband:
{
this->m_DbgSupport.m_TotalIB++;
// Hijack in-band events (exception events, exit threads) if there is already an event at the head
// of the queue or if the process is currently synchronized. Of course, we only do this if the
// process is initialized.
//
// Note: we also hijack these left over in-band events if we're actively trying to send the
// managed continue message to the Left Side. This is controlled by m_specialDeferment below.
// Only exceptions can be IB events - everything else is OOB.
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
// CLR internal exceptions should be sent back to the CLR and never treated as inband events.
// If this assert fires, the event was triaged wrong.
CONSISTENCY_CHECK_MSGF((pEvent->u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_COMPLUS),
("Attempting to dispatch a CLR internal exception as an Inband event. Reaction line=%d\n",
reaction.GetLine()));
_ASSERTE(!pUnmanagedThread->IsCantStop());
// We need to decide whether or not to dispatch this event immediately
// We defer it to enforce that we only dispatch 1 IB event at a time (managed events are
// considered IB here).
// This means if:
// 1) there's already an outstanding unmanaged inband event (an event the user has not continued from)
// 2) If the process is synchronized (since that means we've already dispatched a managed event).
// 3) If we've received a SyncComplete event, but aren't yet Sync. This will almost always be the same as
// whether we're synced, but has a distict quality. It's always set by the w32 event thread in Interop,
// and so it's guaranteed to be serialized against this check here (also on the w32et).
// 4) Special deferment - This covers the region where we're sending a Stop/Continue IPC event across.
// We defer it here to keep the Helper thread alive so that it can handle these IPC events.
// Queued events will be dispatched when continue is called.
BOOL fHasUserUncontinuedNativeEvents = HasUserUncontinuedNativeEvents();
bool fDeferInbandEvent = (fHasUserUncontinuedNativeEvents ||
GetSynchronized() ||
GetSyncCompleteRecv() ||
m_specialDeferment);
// If we've got a new event, queue it.
if (fNewEvent)
{
this->QueueUnmanagedEvent(pUnmanagedThread, pEvent);
}
if (fNewEvent && this->m_initialized && fDeferInbandEvent)
{
STRESS_LOG4(LF_CORDB, LL_INFO1000, "W32ET::W32EL: Needed to defer dispatching event: %d %d %d %d\n",
fHasUserUncontinuedNativeEvents,
GetSynchronized(),
GetSyncCompleteRecv(),
m_specialDeferment);
// this continues the IB debug event into the hijack
// the process is now running again
pW32EventThread->DoDbgContinue(this, pUnmanagedThread->IBEvent());
// Since we've hijacked this event, we don't need to do any further processing.
goto LDone;
}
else
{
// No need to defer the dispatch, do it now
this->DispatchUnmanagedInBandEvent();
goto LDone;
}
UNREACHABLE();
}
case Reaction::cFirstChanceHijackStarted:
{
// determine the logical event we are handling, if any
CordbUnmanagedEvent* pUnmanagedEvent = NULL;
if(pUnmanagedThread->HasIBEvent())
{
pUnmanagedEvent = pUnmanagedThread->IBEvent();
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB hijack starting, ue=0x%p\n", pUnmanagedEvent));
// fetch the LS memory set up for this hijack
REMOTE_PTR pDebuggerWord = NULL;
DebuggerIPCFirstChanceData fcd;
pUnmanagedThread->GetEEDebuggerWord(&pDebuggerWord);
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: old fcd DebugCounter=0x%x\n", fcd.debugCounter));
// determine what action the LS should take
if(pUnmanagedThread->IsBlockingForSync())
{
// there should be an event we hijacked in this case
_ASSERTE(pUnmanagedEvent != NULL);
// block that event
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: blocking\n"));
fcd.action = HIJACK_ACTION_WAIT;
fcd.debugCounter = 0x2;
SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
}
else
{
// we don't need to block. We want the vectored handler to just exit
// as if it wasn't there
_ASSERTE(fcd.action == HIJACK_ACTION_EXIT_UNHANDLED);
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: not blocking\n"));
}
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: continuing from flare\n"));
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
}
case Reaction::cInbandHijackComplete:
{
// We now execute the hijack worker even when not actually hijacked
// so can't assert this
//_ASSERTE(pUnmanagedThread->IsFirstChanceHijacked());
// we should not be stepping at the end of hijacks
_ASSERTE(!pUnmanagedThread->IsSSFlagHidden());
_ASSERTE(!pUnmanagedThread->IsSSFlagNeeded());
// if we were hijacked then clean up
if(pUnmanagedThread->IsFirstChanceHijacked())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: hijack complete will restore context...\n"));
DT_CONTEXT tempContext = { 0 };
tempContext.ContextFlags = DT_CONTEXT_FULL;
HRESULT hr = pUnmanagedThread->GetThreadContext(&tempContext);
_ASSERTE(SUCCEEDED(hr));
// The sync hijack returns normally but the m2uHandoff hijack needs to have the IP
// deliberately restored
if(!pUnmanagedThread->IsBlockingForSync())
{
// restore the context to the current un-hijacked context
BOOL succ = DbiSetThreadContext(pUnmanagedThread->m_handle, &tempContext);
_ASSERTE(succ);
// Because hijacks don't return normally they might have pushed handlers without poping them
// back off. To take care of that we explicitly restore the old SEH chain.
#ifdef TARGET_X86
hr = pUnmanagedThread->RestoreLeafSeh();
_ASSERTE(SUCCEEDED(hr));
#endif
}
else
{
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB hijack completing, continuing unhijacked ue=0x%p\n", pUnmanagedEvent));
_ASSERTE(pUnmanagedEvent->IsEventContinuedHijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
_ASSERTE(pUnmanagedEvent->IsEventUserContinued());
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
// fetch the LS memory set up for this hijack
REMOTE_PTR pDebuggerWord = NULL;
DebuggerIPCFirstChanceData fcd;
pUnmanagedThread->GetEEDebuggerWord(&pDebuggerWord);
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: pDebuggerWord is 0x%p\n", pDebuggerWord));
//set the correct continuation action based upon the user's selection
if(pUnmanagedEvent->IsExceptionCleared())
{
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: exception cleared\n"));
fcd.action = HIJACK_ACTION_EXIT_HANDLED;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: exception not cleared\n"));
fcd.action = HIJACK_ACTION_EXIT_UNHANDLED;
}
//
// LS context is restored here so that execution continues from next instruction that caused the hijack.
// We shouldn't always restore the LS context though.
// Consider the following case where this can cause issues:
// Debuggee process hits an exception and calls KERNELBASE!RaiseException, debugger gets the notification and
// prepares for first-chance hijack. Debugger(DBI) saves the current thread context (see SetupFirstChanceHijackForSync) which is restored
// later below (see SafeWriteThreadContext call) when the process is in VEH (CLRVectoredExceptionHandlerShim->FirstChanceSuspendHijackWorker).
// The thread context that got saved(by SetupFirstChanceHijackForSync) was for when the thread was executing RaiseException and when
// this context gets restored in VEH, the thread resumes after the exception handler with a context that is not same as one with which
// it entered. This inconsistency can lead to bad execution code-paths or even a debuggee crash.
//
// Example case where we should definitely update the LS context:
// After a DbgBreakPoint call, IP gets updated to point to the instruction after int 3 and this is the context saved by debugger.
// The IP in context passed to VEH still points to int 3 though and if we don't update the LS context in VEH, the breakpoint
// instruction will get executed again.
//
// Here's a list of cases when we update the LS context:
// * we know that context was explicitly updated during this hijack, OR
// * if single-stepping flag was set on it originally, OR
// * if this was a breakpoint event
// Note that above list is a heuristic and it is possible that we need to add more such cases in future.
//
BOOL isBreakPointEvent = (pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT &&
pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT);
if (pUnmanagedThread->IsContextSet() || IsSSFlagEnabled(&tempContext) || isBreakPointEvent)
{
_ASSERTE(fcd.pLeftSideContext != NULL);
LOG((LF_CORDB, LL_INFO10000, "W32ET::W32EL: updating LS context at 0x%p\n", fcd.pLeftSideContext));
// write the new context over the old one on the LS
SafeWriteThreadContext(fcd.pLeftSideContext, &tempContext);
}
// Write the new Fcd data to the LS
fcd.debugCounter = 0x1;
SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
fcd.debugCounter = 0;
SafeReadStruct(PTR_TO_CORDB_ADDRESS(pDebuggerWord), &fcd);
_ASSERTE(fcd.debugCounter == 1);
DequeueUnmanagedEvent(pUnmanagedThread);
}
_ASSERTE(m_cFirstChanceHijackedThreads > 0);
m_cFirstChanceHijackedThreads--;
if(m_cFirstChanceHijackedThreads == 0)
{
m_state &= ~PS_HIJACKS_IN_PLACE;
}
pUnmanagedThread->ClearState(CUTS_FirstChanceHijacked);
pUnmanagedThread->ClearState(CUTS_BlockingForSync);
// if the user set the context it either was already applied (m2uHandoff hijack)
// or is about to be applied when the hijack returns (sync hijack).
// There may still a small window where it won't appear accurate that
// we just have to live with
pUnmanagedThread->ClearState(CUTS_HasContextSet);
}
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
// We've handled this event. Skip further processing.
goto LDone;
}
case Reaction::cBreakpointRequiringHijack:
{
HRESULT hr = pUnmanagedThread->SetupFirstChanceHijack(EHijackReason::kM2UHandoff, &(pEvent->u.Exception.ExceptionRecord));
_ASSERTE(SUCCEEDED(hr));
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread, DBG_CONTINUE, false);
goto LDone;
}
case Reaction::cInbandExceptionRetrigger:
{
// this should be unused now
_ASSERTE(FALSE);
_ASSERTE(pUnmanagedThread->HasIBEvent());
CordbUnmanagedEvent* pUnmanagedEvent = pUnmanagedThread->IBEvent();
_ASSERTE(pUnmanagedEvent->IsIBEvent());
_ASSERTE(pUnmanagedEvent->IsEventContinuedUnhijacked());
_ASSERTE(pUnmanagedEvent->IsDispatched());
LOG((LF_CORDB, LL_INFO100000, "W32ET::W32EL: IB event completing, continuing ue=0x%p\n", pUnmanagedEvent));
DequeueUnmanagedEvent(pUnmanagedThread);
// If this event came from RaiseException then flush the context to ensure we won't use it until we re-enter
if(pUnmanagedEvent->m_owner->IsRaiseExceptionHijacked())
{
pUnmanagedEvent->m_owner->RestoreFromRaiseExceptionHijack();
pUnmanagedEvent->m_owner->ClearRaiseExceptionEntryContext();
}
else // otherwise we should have been stepping
{
pUnmanagedThread->EndStepping();
}
pW32EventThread->ForceDbgContinue(this, pUnmanagedThread,
pUnmanagedEvent->IsExceptionCleared() ? DBG_CONTINUE : DBG_EXCEPTION_NOT_HANDLED, false);
// We've handled this event. Skip further processing.
goto LDone;
}
case Reaction::cOOB:
{
// Don't care if this thread claimed to be suspended or not. Dispatch event anyways. After all,
// OOB events can come at *any* time.
// This thread may be suspended. We don't care.
this->m_DbgSupport.m_TotalOOB++;
// Not an inband event. This includes ALL non-exception events (including EXIT_THREAD) as
// well as any exception that can't be hijacked (ex, an exception on the helper thread).
// If this is an exit thread or exit process event, then we need to mark the unmanaged thread as
// exited for later.
if ((pEvent->dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) ||
(pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT))
{
pUnmanagedThread->SetState(CUTS_Deleted);
}
// If we get an exit process or exit thread event on the helper thread, then we know we're loosing
// the Left Side, so go ahead and remember that the helper thread has died.
if (this->IsHelperThreadWorked(pUnmanagedThread->GetOSTid()))
{
if ((pEvent->dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) ||
(pEvent->dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT))
{
this->m_helperThreadDead = true;
}
}
// Queue the current out-of-band event.
this->QueueOOBUnmanagedEvent(pUnmanagedThread, pEvent);
// Go ahead and dispatch the event if its the first one.
if (this->m_outOfBandEventQueue == pUnmanagedThread->OOBEvent())
{
// Set this to true to indicate to Continue() that we're in the unamnaged callback.
CordbUnmanagedEvent * pUnmanagedEvent = pUnmanagedThread->OOBEvent();
this->m_dispatchingOOBEvent = true;
pUnmanagedEvent->SetState(CUES_Dispatched);
this->Unlock();
// Handler should have been registered by now.
_ASSERTE(this->m_cordb->m_unmanagedCallback != NULL);
// Call the callback with fIsOutOfBand = TRUE.
{
PUBLIC_WIN32_CALLBACK_IN_THIS_SCOPE(this, pEvent, TRUE);
this->m_cordb->m_unmanagedCallback->DebugEvent(const_cast<DEBUG_EVENT*> (pEvent), TRUE);
}
this->Lock();
// If m_dispatchingOOBEvent is false, that means that the user called Continue() from within
// the callback. We know that we can go ahead and continue the process now.
if (this->m_dispatchingOOBEvent == false)
{
// Note: this call will dispatch more OOB events if necessary.
pW32EventThread->UnmanagedContinue(this, cOobUMContinue);
}
else
{
// We're not dispatching anymore, so set this back to false.
this->m_dispatchingOOBEvent = false;
}
}
// We've handled this event. Skip further processing.
goto LDone;
}
} // end Switch on Reaction
UNREACHABLE();
LDone:
// Process Lock implicitly released by holder.
STRESS_LOG0(LF_CORDB, LL_INFO1000, "W32ET::W32EL: done processing event.\n");
return;
}
//
// Returns true if the exception is a flare from the left side, false otherwise.
//
bool CordbProcess::ExceptionIsFlare(DWORD exceptionCode, const void *exceptionAddress)
{
_ASSERTE(m_runtimeOffsetsInitialized);
// Can't have a flare if the left side isn't initialized
if (m_initialized)
{
DebuggerIPCRuntimeOffsets *pRO = &m_runtimeOffsets;
// All flares are breakpoints...
if (exceptionCode == STATUS_BREAKPOINT)
{
// Does the breakpoint address match a flare address?
if ((exceptionAddress == pRO->m_signalHijackStartedBPAddr) ||
(exceptionAddress == pRO->m_excepForRuntimeHandoffStartBPAddr) ||
(exceptionAddress == pRO->m_excepForRuntimeHandoffCompleteBPAddr) ||
(exceptionAddress == pRO->m_signalHijackCompleteBPAddr) ||
(exceptionAddress == pRO->m_excepNotForRuntimeBPAddr) ||
(exceptionAddress == pRO->m_notifyRSOfSyncCompleteBPAddr))
return true;
}
}
return false;
}
#endif // FEATURE_INTEROP_DEBUGGING
// Allocate a buffer in the target and copy data into it.
//
// Arguments:
// pDomain - an appdomain associated with the allocation request.
// bufferSize - size of the buffer in bytes
// bufferFrom - local buffer of data (bufferSize bytes) to copy data from.
// ppRes - address into target of allocated buffer
//
// Returns:
// S_OK on success, else error.
HRESULT CordbProcess::GetAndWriteRemoteBuffer(CordbAppDomain *pDomain, unsigned int bufferSize, const void *bufferFrom, void **ppRes)
{
_ASSERTE(ppRes != NULL);
*ppRes = NULL;
HRESULT hr = S_OK;
EX_TRY
{
TargetBuffer tbTarget = GetRemoteBuffer(bufferSize); // throws
SafeWriteBuffer(tbTarget, (const BYTE*) bufferFrom); // throws
// Succeeded.
*ppRes = CORDB_ADDRESS_TO_PTR(tbTarget.pAddress);
}
EX_CATCH_HRESULT(hr);
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//
// Checks to see if the given second chance exception event actually signifies the death of the process due to a second
// stack overflow special case.
//
// There are strange cases with stack overflow exceptions. If a nieve application catches a stack overflow exception and
// handles it, without resetting the guard page, then the app will get an AV when it overflows the stack a second time. We
// will get the first chance AV, but when we continue from it the OS won't run any SEH handlers, so our FCH won't
// actually work. Instead, we'll get the AV back on second chance right away.
//
bool CordbProcess::IsSpecialStackOverflowCase(CordbUnmanagedThread *pUThread, const DEBUG_EVENT *pEvent)
{
_ASSERTE(pEvent->dwDebugEventCode == EXCEPTION_DEBUG_EVENT);
_ASSERTE(pEvent->u.Exception.dwFirstChance == 0);
// If this is not an AV, it can't be our special case.
if (pEvent->u.Exception.ExceptionRecord.ExceptionCode != STATUS_ACCESS_VIOLATION)
return false;
// If the thread isn't already first chance hijacked, it can't be our special case.
if (!pUThread->IsFirstChanceHijacked())
return false;
// The first chance hijack didn't take, so we're not FCH anymore and we're not waiting for an answer
// anymore... Note: by leaving this thread completely unhijacked, we'll report its true context, which is correct.
pUThread->ClearState(CUTS_FirstChanceHijacked);
// The process is techincally dead as a door nail here, so we'll mark that the helper thread is dead so our managed
// API bails nicely.
m_helperThreadDead = true;
// Remember we're in our special case.
pUThread->SetState(CUTS_HasSpecialStackOverflowCase);
// Now, remember the second chance AV event in the second IB event slot for this thread and add it to the end of the
// IB event queue.
QueueUnmanagedEvent(pUThread, pEvent);
// Note: returning true will ensure that the queued first chance AV for this thread is dispatched.
return true;
}
//-----------------------------------------------------------------------------
// Longhorn broke ContinueDebugEvent.
// In previous OS releases, DBG_CONTINUE would continue a non-continuable exception.
// In longhorn, we need to pass the DBG_FORCE_CONTINUE flag to do that.
// Note that all CLR exceptions are non-continuable.
// Now instead of DBG_CONTINUE, we need to pass DBG_FORCE_CONTINUE.
//-----------------------------------------------------------------------------
// Currently we don't have headers for the longhorn winnt.h. So we need to privately declare
// this here. We have a check such that if we do get headers, the value won't change underneath us.
#define MY_DBG_FORCE_CONTINUE ((DWORD )0x00010003L)
#ifndef DBG_FORCE_CONTINUE
#define DBG_FORCE_CONTINUE MY_DBG_FORCE_CONTINUE
#else
static_assert_no_msg(DBG_FORCE_CONTINUE == MY_DBG_FORCE_CONTINUE);
#endif
DWORD GetDbgContinueFlag()
{
// Currently, default to not using the new DBG_FORCE_CONTINUE flag.
static ConfigDWORD fNoFlagKey;
bool fNoFlag = fNoFlagKey.val(CLRConfig::UNSUPPORTED_DbgNoForceContinue) != 0;
if (!fNoFlag)
{
return DBG_FORCE_CONTINUE;
}
else
{
return DBG_CONTINUE;
}
}
// Some Interop bugs involve threads that land at a bad IP. Since we're interop-debugging, we can't
// attach a debugger to the LS. So we have some debug mode where we enable the SS flag and thus
// produce a trace of where a thread is going.
#ifdef _DEBUG
void EnableDebugTrace(CordbUnmanagedThread *ut)
{
// To enable, attach w/ a debugger and either set fTrace==true, or setip.
static bool fTrace = false;
if (!fTrace)
return;
// Give us a nop so that we can setip in the optimized case.
#ifdef TARGET_X86
__asm {
nop
}
#endif
fTrace = true;
CordbProcess *pProcess = ut->GetProcess();
// Get the context
HRESULT hr = S_OK;
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
hr = pProcess->GetThreadContext((DWORD) ut->m_id, sizeof(context), (BYTE*)&context);
if (FAILED(hr))
return;
// If the flag is already set, then don't set it again - that will just get confusing.
if (IsSSFlagEnabled(&context))
{
return;
}
_ASSERTE(CORDbgGetIP(&context) != 0);
SetSSFlag(&context);
// If SS flag not set, enable it. And remeber that it's us so we know how to handle
// it when we get the debug event.
hr = pProcess->SetThreadContext((DWORD)ut->m_id, sizeof(context), (BYTE*)&context);
ut->SetState(CUTS_DEBUG_SingleStep);
}
#endif // _DEBUG
//-----------------------------------------------------------------------------
// DoDbgContinue
//
// Continues from a specific Win32 DEBUG_EVENT.
//
// Arguments:
// pProcess - The process to continue.
// pUnmanagedEvent - The event to continue.
//
//-----------------------------------------------------------------------------
void CordbWin32EventThread::DoDbgContinue(CordbProcess *pProcess,
CordbUnmanagedEvent *pUnmanagedEvent)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
_ASSERTE(pUnmanagedEvent != NULL);
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
STRESS_LOG3(LF_CORDB, LL_INFO1000,
"W32ET::DDC: continue with ue=0x%p, thread=0x%p, tid=0x%x\n",
pUnmanagedEvent,
pUnmanagedEvent->m_owner,
pUnmanagedEvent->m_owner->m_id);
#ifdef _DEBUG
EnableDebugTrace(pUnmanagedEvent->m_owner);
#endif
if (pUnmanagedEvent->IsEventContinuedHijacked())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Skiping DoDbgContinue because event was already"
" continued hijacked, ue=0x%p\n", pUnmanagedEvent));
return;
}
BOOL threadIsHijacked = (pUnmanagedEvent->m_owner->IsFirstChanceHijacked() ||
pUnmanagedEvent->m_owner->IsGenericHijacked());
BOOL eventIsIB = (pUnmanagedEvent->m_owner->HasIBEvent() &&
pUnmanagedEvent->m_owner->IBEvent() == pUnmanagedEvent);
_ASSERTE((DWORD) pProcess->m_id == pUnmanagedEvent->m_currentDebugEvent.dwProcessId);
_ASSERTE(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED);
DWORD dwContType;
if(eventIsIB)
{
// 3 cases here...
// event was already hijacked
if(threadIsHijacked)
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, already hijacked, ue=0x%p\n", pUnmanagedEvent));
pUnmanagedEvent->SetState(CUES_EventContinuedHijacked);
dwContType = !pUnmanagedEvent->m_owner->IsBlockingForSync() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
// event was not hijacked but has been dispatched
else if(!threadIsHijacked && pUnmanagedEvent->IsDispatched())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, not hijacked, ue=0x%p\n", pUnmanagedEvent));
_ASSERTE(pUnmanagedEvent->IsDispatched());
_ASSERTE(pUnmanagedEvent->IsEventUserContinued());
_ASSERTE(!pUnmanagedEvent->IsEventContinuedUnhijacked());
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
dwContType = pUnmanagedEvent->IsExceptionCleared() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
// The event was never hijacked and so will never need to retrigger, get rid
// of it right now. If it had been hijacked then we would dequeue it either after the
// hijack complete flare or one instruction after that when it has had a chance to retrigger
pProcess->DequeueUnmanagedEvent(pUnmanagedEvent->m_owner);
}
// event was not hijacked nor dispatched
else // if(!threadIsHijacked && !pUnmanagedEvent->IsDispatched())
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing IB, now hijacked, ue=0x%p\n", pUnmanagedEvent));
HRESULT hr = pProcess->HijackIBEvent(pUnmanagedEvent);
_ASSERTE(SUCCEEDED(hr));
pUnmanagedEvent->SetState(CUES_EventContinuedHijacked);
dwContType = !pUnmanagedEvent->m_owner->IsBlockingForSync() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
}
else
{
LOG((LF_CORDB, LL_INFO100000, "W32ET::DDC: Continuing OB, ue=0x%p\n", pUnmanagedEvent));
// we might actually be hijacked here, but if we are it should be for a previous IB event
// we just mark all OB events as continued unhijacked
pUnmanagedEvent->SetState(CUES_EventContinuedUnhijacked);
dwContType = pUnmanagedEvent->IsExceptionCleared() ? GetDbgContinueFlag() : DBG_EXCEPTION_NOT_HANDLED;
}
// If the exception is marked as unclearable, then make sure the continue type is correct and force the process
// to terminate.
if (pUnmanagedEvent->IsExceptionUnclearable())
{
TerminateProcess(pProcess->UnsafeGetProcessHandle(), pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode);
dwContType = DBG_EXCEPTION_NOT_HANDLED;
}
// If we're continuing from the loader-bp, then send the managed attach here.
// (Note this will only be set if the runtime was loaded when we first tried to attach).
// We assume that the loader-bp is the 1st BP exception. This is naive,
// since it's not 100% accurate (someone could CreateThread w/ a threadproc of DebugBreak).
// But it's the best we can do.
// Note that it's critical we do this BEFORE continuing the process. If this is mixed-mode, we've already
// told VS about this breakpoint, and so it's set the attach-complete event. As soon as we continue this debug
// event the process can start moving again, so the CLR needs to know to wait for a managed attach.
DWORD dwEventCode = pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode;
if (dwEventCode == EXCEPTION_DEBUG_EVENT)
{
EXCEPTION_DEBUG_INFO * pDebugInfo = &pUnmanagedEvent->m_currentDebugEvent.u.Exception;
if (pDebugInfo->dwFirstChance && pDebugInfo->ExceptionRecord.ExceptionCode == STATUS_BREAKPOINT)
{
HRESULT hrIgnore = S_OK;
EX_TRY
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::DDC: Continuing from LdrBp, doing managed attach.\n"));
pProcess->QueueManagedAttachIfNeededWorker();
}
EX_CATCH_HRESULT(hrIgnore);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hrIgnore));
}
}
STRESS_LOG4(LF_CORDB, LL_INFO1000,
"W32ET::DDC: calling ContinueDebugEvent(0x%x, 0x%x, 0x%x), process state=0x%x\n",
pProcess->m_id, pUnmanagedEvent->m_owner->m_id, dwContType, pProcess->m_state);
// Actually continue the debug event
pProcess->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
BOOL fSuccess = m_pNativePipeline->ContinueDebugEvent((DWORD)pProcess->m_id, (DWORD)pUnmanagedEvent->m_owner->m_id, dwContType);
// ContinueDebugEvent may 'fail' if we force kill the debuggee while stopped at the exit-process event.
if (!fSuccess && (dwEventCode != EXIT_PROCESS_DEBUG_EVENT))
{
_ASSERTE(!"ContinueDebugEvent failed!");
CORDBSetUnrecoverableError(pProcess, HRESULT_FROM_GetLastError(), 0);
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::DDC: Last error after ContinueDebugEvent is %d\n", GetLastError());
}
// If this thread is marked for deletion (exit thread or exit process event on it), then we need to delete the
// unmanaged thread object.
if ((dwEventCode == EXIT_PROCESS_DEBUG_EVENT) || (dwEventCode == EXIT_THREAD_DEBUG_EVENT))
{
CordbUnmanagedThread * pUnmanagedThread = pUnmanagedEvent->m_owner;
_ASSERTE(pUnmanagedThread->IsDeleted());
// Thread may have a hijacked inband event on it. Thus it's actually running free from the OS perspective,
// and fair game to be terminated. In that case, we need to auto-dequeue the event.
// This will just prevent the RS from making the underlying call to ContinueDebugEvent on this thread
// for the inband event. Since we've already lost the thread, that's actually exactly what we want.
if (pUnmanagedThread->HasIBEvent())
{
pProcess->DequeueUnmanagedEvent(pUnmanagedThread);
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "Removing thread 0x%x (%d) from process list\n", pUnmanagedThread->m_id);
pProcess->m_unmanagedThreads.RemoveBase((ULONG_PTR)pUnmanagedThread->m_id);
}
// If we just continued from an exit process event, then its time to do the exit processing.
if (dwEventCode == EXIT_PROCESS_DEBUG_EVENT)
{
pProcess->Unlock();
ExitProcess(false); // not detach case
pProcess->Lock();
}
}
//---------------------------------------------------------------------------------------
//
// ForceDbgContinue continues from the last Win32 DEBUG_EVENT on the given thread, no matter what it was.
//
// Arguments:
// pProcess - process object to continue
// pUnmanagedThread - unmanaged thread object (maybe null if we're doing a raw cotninue)
// contType - continuation status (DBG_CONTINUE or DBG_EXCEPTION_NOT_HANDLED)
// fContinueProcess - do we resume hijacks?
//
void CordbWin32EventThread::ForceDbgContinue(CordbProcess *pProcess, CordbUnmanagedThread *pUnmanagedThread, DWORD contType,
bool fContinueProcess)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(pUnmanagedThread != NULL);
STRESS_LOG4(LF_CORDB, LL_INFO1000,
"W32ET::FDC: force continue with 0x%x (%s), contProcess=%d, tid=0x%x\n",
contType,
(contType == DBG_CONTINUE) ? "DBG_CONTINUE" : "DBG_EXCEPTION_NOT_HANDLED",
fContinueProcess,
pUnmanagedThread->m_id);
if (fContinueProcess)
{
pProcess->ResumeHijackedThreads();
}
if (contType == DBG_CONTINUE)
{
contType = GetDbgContinueFlag();
}
_ASSERTE(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED);
// Remove the Win32 stopped flag so long as the OOB event queue is empty. We're forcing a continue here, so by
// definition this should be the case...
_ASSERTE(pProcess->m_outOfBandEventQueue == NULL);
pProcess->m_state &= ~CordbProcess::PS_WIN32_STOPPED;
STRESS_LOG4(LF_CORDB, LL_INFO1000, "W32ET::FDC: calling ContinueDebugEvent(0x%x, 0x%x, 0x%x), process state=0x%x\n",
pProcess->m_id, pUnmanagedThread->m_id, contType, pProcess->m_state);
#ifdef _DEBUG
EnableDebugTrace(pUnmanagedThread);
#endif
BOOL ret = m_pNativePipeline->ContinueDebugEvent((DWORD)pProcess->m_id, (DWORD)pUnmanagedThread->m_id, contType);
if (!ret)
{
// This could in theory fail from Process exit, but that really would only be on the DoDbgContinue path.
_ASSERTE(!"ContinueDebugEvent failed #2!");
STRESS_LOG1(LF_CORDB, LL_INFO1000, "W32ET::DDC: Last error after ContinueDebugEvent is %d\n", GetLastError());
}
}
#endif // FEATURE_INTEROP_DEBUGGING
//
// This is the thread's real thread proc. It simply calls to the
// thread proc on the given object.
//
/*static*/ DWORD WINAPI CordbWin32EventThread::ThreadProc(LPVOID parameter)
{
CordbWin32EventThread* t = (CordbWin32EventThread*) parameter;
INTERNAL_THREAD_ENTRY(t);
t->ThreadProc();
return 0;
}
//
// Send a CreateProcess event to the Win32 thread to have it create us
// a new process.
//
HRESULT CordbWin32EventThread::SendCreateProcessEvent(
MachineInfo machineInfo,
LPCWSTR programName,
_In_z_ LPWSTR programArgs,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
PVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
CorDebugCreateProcessFlags corDebugFlags)
{
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
LOG((LF_CORDB, LL_EVERYTHING, "CordbWin32EventThread::SCPE Called\n"));
m_actionData.createData.machineInfo = machineInfo;
m_actionData.createData.programName = programName;
m_actionData.createData.programArgs = programArgs;
m_actionData.createData.lpProcessAttributes = lpProcessAttributes;
m_actionData.createData.lpThreadAttributes = lpThreadAttributes;
m_actionData.createData.bInheritHandles = bInheritHandles;
m_actionData.createData.dwCreationFlags = dwCreationFlags;
m_actionData.createData.lpEnvironment = lpEnvironment;
m_actionData.createData.lpCurrentDirectory = lpCurrentDirectory;
m_actionData.createData.lpStartupInfo = lpStartupInfo;
m_actionData.createData.lpProcessInformation = lpProcessInformation;
m_actionData.createData.corDebugFlags = corDebugFlags;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_CREATE_PROCESS;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
LOG((LF_CORDB, LL_EVERYTHING, "Process Handle is: %x, m_threadControlEvent is %x\n",
(UINT_PTR)m_actionData.createData.lpProcessInformation->hProcess, (UINT_PTR)m_threadControlEvent));
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//---------------------------------------------------------------------------------------
//
// Create a process
//
// Assumptions:
// This occurs on the win32 event thread. It is invokved via
// a message sent from code:CordbWin32EventThread::SendCreateProcessEvent
//
// Notes:
// Create a new process. This is called in the context of the Win32
// event thread to ensure that if we're Win32 debugging the process
// that the same thread that waits for debugging events will be the
// thread that creates the process.
//
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::CreateProcess()
{
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
DWORD dwCreationFlags = m_actionData.createData.dwCreationFlags;
// If the creation flags has DEBUG_PROCESS in them, then we're
// Win32 debugging this process. Otherwise, we have to create
// suspended to give us time to setup up our side of the IPC
// channel.
BOOL fInteropDebugging =
#if defined(FEATURE_INTEROP_DEBUGGING)
(dwCreationFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS));
#else
false; // Interop not supported.
#endif
// Have Win32 create the process...
hr = m_pNativePipeline->CreateProcessUnderDebugger(
m_actionData.createData.machineInfo,
m_actionData.createData.programName,
m_actionData.createData.programArgs,
m_actionData.createData.lpProcessAttributes,
m_actionData.createData.lpThreadAttributes,
m_actionData.createData.bInheritHandles,
dwCreationFlags,
m_actionData.createData.lpEnvironment,
m_actionData.createData.lpCurrentDirectory,
m_actionData.createData.lpStartupInfo,
m_actionData.createData.lpProcessInformation);
if (SUCCEEDED(hr))
{
// Process ID is filled in after process is succesfully created.
DWORD dwProcessId = m_actionData.createData.lpProcessInformation->dwProcessId;
ProcessDescriptor pd = ProcessDescriptor::FromPid(dwProcessId);
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
hr = m_pShim->InitializeDataTarget(&pd);
if (SUCCEEDED(hr))
{
// To emulate V2 semantics, we pass 0 for the clrInstanceID into
// OpenVirtualProcess. This will then connect to the first CLR
// loaded.
const ULONG64 cFirstClrLoaded = 0;
hr = CordbProcess::OpenVirtualProcess(cFirstClrLoaded, m_pShim->GetDataTarget(), NULL, m_cordb, &pd, m_pShim, &pProcess);
}
// Shouldn't happen on a create, only an attach
_ASSERTE(hr != CORDBG_E_DEBUGGER_ALREADY_ATTACHED);
// Remember the process in the global list of processes.
if (SUCCEEDED(hr))
{
EX_TRY
{
// Mark if we're interop-debugging
if (fInteropDebugging)
{
pProcess->EnableInteropDebugging();
}
m_cordb->AddProcess(pProcess); // will take ref if it succeeds
}
EX_CATCH_HRESULT(hr);
}
// If we're Win32 attached to this process, then increment the
// proper count, otherwise add this process to the wait set
// and resume the process's main thread.
if (SUCCEEDED(hr))
{
_ASSERTE(m_pProcess == NULL);
m_pProcess.Assign(pProcess);
}
}
//
// Signal the hr to the caller.
//
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
//
// Send a DebugActiveProcess event to the Win32 thread to have it attach to
// a new process.
//
HRESULT CordbWin32EventThread::SendDebugActiveProcessEvent(
MachineInfo machineInfo,
const ProcessDescriptor *pProcessDescriptor,
bool fWin32Attach,
CordbProcess *pProcess)
{
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
m_actionData.attachData.machineInfo = machineInfo;
m_actionData.attachData.processDescriptor = *pProcessDescriptor;
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
m_actionData.attachData.fWin32Attach = fWin32Attach;
#endif
m_actionData.attachData.pProcess = pProcess;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_ATTACH_PROCESS;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//-----------------------------------------------------------------------------
// Is the given thread id a helper thread (real or worker?)
//-----------------------------------------------------------------------------
bool CordbProcess::IsHelperThreadWorked(DWORD tid)
{
// Check against the id gained by sniffing Thread-Create events.
if (tid == this->m_helperThreadId)
{
return true;
}
// Now check for potential datate in the IPC block. If not there,
// then we know it can't be the helper.
DebuggerIPCControlBlock * pDCB = this->GetDCB();
if (pDCB == NULL)
{
return false;
}
// get the latest information from the LS DCB
UpdateRightSideDCB();
return
(tid == pDCB->m_realHelperThreadId) ||
(tid == pDCB->m_temporaryHelperThreadId);
}
//---------------------------------------------------------------------------------------
//
// Cleans up the Left Side's DCB after a failed attach attempt.
//
// Assumptions:
// Called when the left-site failed initialization
//
// Notes:
// This can be called multiple times.
//---------------------------------------------------------------------------------------
void CordbProcess::CleanupHalfBakedLeftSide()
{
if (GetDCB() != NULL)
{
EX_TRY
{
GetDCB()->m_rightSideIsWin32Debugger = false;
UpdateLeftSideDCBField(&(GetDCB()->m_rightSideIsWin32Debugger), sizeof(GetDCB()->m_rightSideIsWin32Debugger));
if (m_pEventChannel != NULL)
{
m_pEventChannel->Delete();
m_pEventChannel = NULL;
}
}
EX_CATCH
{
_ASSERTE(!"Writing process memory failed, perhaps due to an unexpected disconnection from the target.");
}
EX_END_CATCH(SwallowAllExceptions);
}
// Close and null out the various handles and events, including our process handle m_handle.
CloseIPCHandles();
m_cordb.Clear();
// This process object is Dead-On-Arrival, so it doesn't really have anything to neuter.
// But for safekeeping, we'll mark it as neutered.
UnsafeNeuterDeadObject();
}
//---------------------------------------------------------------------------------------
//
// Attach to an existing process.
//
//
// Assumptions:
// Called on W32Event Thread, in response to event sent by
// code:CordbWin32EventThread::SendDebugActiveProcessEvent
//
// Notes:
// Attach to a process. This is called in the context of the Win32
// event thread to ensure that if we're Win32 debugging the process
// that the same thread that waits for debugging events will be the
// thread that attaches the process.
//
// @dbgtodo shim: this will be part of the shim
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::AttachProcess()
{
_ASSERTE(IsWin32EventThread());
RSUnsafeExternalSmartPtr<CordbProcess> pProcess;
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
ProcessDescriptor processDescriptor = m_actionData.attachData.processDescriptor;
bool fNativeAttachSucceeded = false;
// Always do OS attach to the target.
// By this point, the pid should be valid (because OpenProcess above), pending some race where the process just exited.
// The OS will enforce that only 1 debugger is attached.
// Common failure paths here would be: access denied, double-attach
{
hr = m_pNativePipeline->DebugActiveProcess(m_actionData.attachData.machineInfo,
processDescriptor);
if (FAILED(hr))
{
goto LExit;
}
fNativeAttachSucceeded = true;
}
hr = m_pShim->InitializeDataTarget(&processDescriptor);
if (FAILED(hr))
{
goto LExit;
}
// To emulate V2 semantics, we pass 0 for the clrInstanceID into
// OpenVirtualProcess. This will then connect to the first CLR
// loaded.
{
const ULONG64 cFirstClrLoaded = 0;
hr = CordbProcess::OpenVirtualProcess(cFirstClrLoaded, m_pShim->GetDataTarget(), NULL, m_cordb, &processDescriptor, m_pShim, &pProcess);
if (FAILED(hr))
{
goto LExit;
}
}
// Remember the process in the global list of processes.
// The caller back in code:Cordb::DebugActiveProcess will then get this by fetching it from the list.
EX_TRY
{
// Don't allow attach if any metadata/IL updates have been applied
if (pProcess->GetDAC()->MetadataUpdatesApplied())
{
hr = CORDBG_E_ASSEMBLY_UPDATES_APPLIED;
goto LExit;
}
// Mark interop-debugging
if (m_actionData.attachData.IsInteropDebugging())
{
pProcess->EnableInteropDebugging(); // Throwing
}
m_cordb->AddProcess(pProcess); // will take ref if it succeeds
// Queue fake Attach event for CreateProcess
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(pProcess);
m_pShim->BeginQueueFakeAttachEvents();
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
goto LExit;
}
_ASSERTE(m_pProcess == NULL);
m_pProcess.Assign(pProcess);
pProcess.Clear(); // ownership transfered to m_pProcess
// Should have succeeded if we got to this point.
_ASSERTE(SUCCEEDED(hr));
LExit:
if (FAILED(hr))
{
// If we succeed to do a native-attach, but then failed elsewhere, try to native-detach.
if (fNativeAttachSucceeded)
{
m_pNativePipeline->DebugActiveProcessStop(processDescriptor.m_Pid);
}
if (pProcess != NULL)
{
// Safe to call this even if the process wasn't added.
m_cordb->RemoveProcess(pProcess);
pProcess->CleanupHalfBakedLeftSide();
pProcess.Clear();
}
m_pProcess.Clear();
}
//
// Signal the hr to the caller.
//
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
// Note that the actual 'DetachProcess' method is really ExitProcess with CW32ET_UNKNOWN_PROCESS_SLOT ==
// processSlot
HRESULT CordbWin32EventThread::SendDetachProcessEvent(CordbProcess *pProcess)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::SDPE\n"));
HRESULT hr = S_OK;
LockSendToWin32EventThreadMutex();
m_actionData.detachData.pProcess = pProcess;
// m_action is set last so that the win32 event thread can inspect it and take action without actually
// having to take any locks. The lock around this here is simply to prevent multiple threads from making
// requests at the same time.
m_action = W32ETA_DETACH;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
//
// Send a UnmanagedContinue event to the Win32 thread to have it
// continue from an unmanged debug event.
//
HRESULT CordbWin32EventThread::SendUnmanagedContinue(CordbProcess *pProcess,
EUMContinueType eContType)
{
HRESULT hr = S_OK;
// If this were being called on the win32 EventThread, we'd deadlock.
_ASSERTE(!IsWin32EventThread());
// This can't hold the process lock, b/c we're making a cross-thread call,
// and our target will need the process lock.
_ASSERTE(!pProcess->ThreadHoldsProcessLock());
LockSendToWin32EventThreadMutex();
m_actionData.continueData.process = pProcess;
m_actionData.continueData.eContType = eContType;
// m_action is set last so that the win32 event thread can inspect
// it and take action without actually having to take any
// locks. The lock around this here is simply to prevent multiple
// threads from making requests at the same time.
m_action = W32ETA_CONTINUE;
BOOL succ = SetEvent(m_threadControlEvent);
if (succ)
{
DWORD ret = WaitForSingleObject(m_actionTakenEvent, INFINITE);
if (ret == WAIT_OBJECT_0)
hr = m_actionResult;
else
hr = HRESULT_FROM_GetLastError();
}
else
hr = HRESULT_FROM_GetLastError();
UnlockSendToWin32EventThreadMutex();
return hr;
}
//
// Handle unmanaged continue. Continue an unmanaged debug
// event. Deferes to UnmanagedContinue. This is called in the context
// of the Win32 event thread to ensure that if we're Win32 debugging
// the process that the same thread that waits for debugging events
// will be the thread that continues the process.
//
void CordbWin32EventThread::HandleUnmanagedContinue()
{
_ASSERTE(IsWin32EventThread());
m_action = W32ETA_NONE;
HRESULT hr = S_OK;
// Continue the process
CordbProcess *pProcess = m_actionData.continueData.process;
// If we lost the process object, we must have exited.
if (m_pProcess != NULL)
{
_ASSERTE(m_pProcess != NULL);
_ASSERTE(pProcess == m_pProcess);
_ASSERTE(!pProcess->ThreadHoldsProcessLock());
RSSmartPtr<CordbProcess> proc(pProcess);
RSLockHolder ch(&pProcess->m_processMutex);
hr = UnmanagedContinue(pProcess, m_actionData.continueData.eContType);
}
// Signal the hr to the caller.
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
}
//
// Continue an unmanaged debug event. This is called in the context of the Win32 Event thread to ensure that the same
// thread that waits for debug events will be the thread that continues the process.
//
HRESULT CordbWin32EventThread::UnmanagedContinue(CordbProcess *pProcess,
EUMContinueType eContType)
{
_ASSERTE(pProcess->ThreadHoldsProcessLock());
_ASSERTE(IsWin32EventThread());
_ASSERTE(m_pShim != NULL);
HRESULT hr = S_OK;
STRESS_LOG1(LF_CORDB, LL_INFO1000, "UM Continue. type=%d\n", eContType);
if (eContType == cOobUMContinue)
{
_ASSERTE(pProcess->m_outOfBandEventQueue != NULL);
// Dequeue the OOB event.
CordbUnmanagedEvent *ue = pProcess->m_outOfBandEventQueue;
CordbUnmanagedThread *ut = ue->m_owner;
pProcess->DequeueOOBUnmanagedEvent(ut);
// Do a little extra work if that was an OOB exception event...
hr = ue->m_owner->FixupAfterOOBException(ue);
_ASSERTE(SUCCEEDED(hr));
// Continue from the event.
DoDbgContinue(pProcess, ue);
// If there are more queued OOB events, dispatch them now.
if (pProcess->m_outOfBandEventQueue != NULL)
pProcess->DispatchUnmanagedOOBEvent();
// Note: if we previously skipped letting the entire process go on an IB continue due to a blocking OOB event,
// and if the OOB event queue is now empty, then go ahead and let the process continue now...
if ((pProcess->m_doRealContinueAfterOOBBlock == true) &&
(pProcess->m_outOfBandEventQueue == NULL))
goto doRealContinue;
}
else if (eContType == cInternalUMContinue)
{
// We're trying to get into a synced state which means we need the process running (potentially
// with some threads hijacked) in order to have the helper thread do the sync.
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue.\n"));
if (!pProcess->GetSynchronized())
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, !sync'd.\n"));
pProcess->ResumeUnmanagedThreads();
// the event we may need to hijack and continue;
CordbUnmanagedEvent* pEvent = pProcess->m_lastQueuedUnmanagedEvent;
// It is possible to be stopped at either an IB or an OOB event here. We only want to
// continue from an IB event here though
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED && pEvent != NULL &&
pEvent->IsEventWaitingForContinue())
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, frozen on IB event.\n"));
// There should be a uncontinued IB event at the head of the queue
_ASSERTE(pEvent->IsIBEvent());
_ASSERTE(!pEvent->IsEventContinuedUnhijacked());
_ASSERTE(!pEvent->IsEventContinuedHijacked());
// Ensure that the event is hijacked now (it may not have been before) so that the
// thread does not slip forward during the sync process. After that we can safely continue
// it.
pProcess->HijackIBEvent(pEvent);
m_pShim->GetWin32EventThread()->DoDbgContinue(pProcess, pEvent);
}
}
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: internal continue, done.\n"));
}
else
{
// If we're here, then we know 100% for sure that we've successfully gotten the managed continue event to the
// Left Side, so we can stop force hijacking left over in-band events now. Note: if we had hijacked any such
// events, they'll be dispatched below since they're properly queued.
pProcess->m_specialDeferment = false;
// We don't actually do any work if there is an outstanding out-of-band event. When we do continue from the
// out-of-band event, we'll do this work, too.
if (pProcess->m_outOfBandEventQueue != NULL)
{
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: ignoring real continue due to block by out-of-band event(s).\n"));
_ASSERTE(pProcess->m_doRealContinueAfterOOBBlock == false);
pProcess->m_doRealContinueAfterOOBBlock = true;
}
else
{
doRealContinue:
// This is either the Frozen -> Running transition or a
// Synced -> Running transition
_ASSERTE(pProcess->m_outOfBandEventQueue == NULL);
pProcess->m_doRealContinueAfterOOBBlock = false;
LOG((LF_CORDB, LL_INFO1000, "W32ET::UC: continuing the process.\n"));
// Dispatch any more queued in-band events, or if there are none then just continue the process.
//
// Note: don't dispatch more events if we've already sent up the ExitProcess event... those events are just
// lost.
if ((pProcess->HasUndispatchedNativeEvents()) && (pProcess->m_exiting == false))
{
pProcess->DispatchUnmanagedInBandEvent();
}
else
{
// If the unmanaged event queue is empty now, and the process is synchronized, and there are queued
// managed events, then go ahead and get more managed events dispatched.
//
// Note: don't dispatch more events if we've already sent up the ExitProcess event... those events are
// just lost.
if (pProcess->GetSynchronized() && (!m_pShim->GetManagedEventQueue()->IsEmpty()) && (pProcess->m_exiting == false))
{
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED)
{
DoDbgContinue(pProcess, pProcess->m_lastDispatchedIBEvent);
// This if should not be necessary, I am just being extra careful because this
// fix is going in late - see issue 818301
_ASSERTE(pProcess->m_lastDispatchedIBEvent != NULL);
if(pProcess->m_lastDispatchedIBEvent != NULL)
{
pProcess->m_lastDispatchedIBEvent->m_owner->InternalRelease();
pProcess->m_lastDispatchedIBEvent = NULL;
}
}
// Now, get more managed events dispatched.
pProcess->SetSynchronized(false);
pProcess->MarkAllThreadsDirty();
m_cordb->ProcessStateChanged();
}
else
{
// free all the hijacked threads that hit native debug events
pProcess->ResumeHijackedThreads();
// after continuing the here the process should be running completely
// free... no hijacks, no suspended threads, and of course not frozen
if(pProcess->m_state & CordbProcess::PS_WIN32_STOPPED)
{
DoDbgContinue(pProcess, pProcess->m_lastDispatchedIBEvent);
// This if should not be necessary, I am just being extra careful because this
// fix is going in late - see issue 818301
_ASSERTE(pProcess->m_lastDispatchedIBEvent != NULL);
if(pProcess->m_lastDispatchedIBEvent != NULL)
{
pProcess->m_lastDispatchedIBEvent->m_owner->InternalRelease();
pProcess->m_lastDispatchedIBEvent = NULL;
}
}
}
}
// Implicit Release on UT
}
}
return hr;
}
#endif // FEATURE_INTEROP_DEBUGGING
void ExitProcessWorkItem::Do()
{
STRESS_LOG1(LF_CORDB, LL_INFO1000, "ExitProcessWorkItem proc=%p\n", GetProcess());
// This is being called on the RCET.
// That's the thread that dispatches managed events. Since it's calling us now, we know
// it can't be dispatching a managed event, and so we don't need to both waiting for it
{
// Get the SG lock here to coordinate against any other continues.
RSLockHolder ch(GetProcess()->GetStopGoLock());
RSLockHolder ch2(&(GetProcess()->m_processMutex));
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: ExitProcess callback\n"));
// We're synchronized now, so mark the process as such.
GetProcess()->SetSynchronized(true);
GetProcess()->IncStopCount();
// By the time we release the SG + Process locks here, the process object has been
// marked as exiting + terminated (by the w32et which queued us). Future attemps to
// continue should fail, and thus we should remain synchronized.
}
// Just to be safe, neuter any children before the exit process callback.
{
RSLockHolder ch(GetProcess()->GetProcessLock());
// Release the process.
GetProcess()->NeuterChildren();
}
RSSmartPtr<Cordb> pCordb(NULL);
// There is a race condition here where the debuggee process is killed while we are processing a process
// detach. We queue the process exit event for the Win32 event thread before queueing the process detach
// event. By the time this function is executed, we may have neutered the CordbProcess already as a
// result of code:CordbProcess::Detach. Detect that case here under the SG lock.
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
if (!GetProcess()->IsNeutered())
{
_ASSERTE(GetProcess()->m_cordb != NULL);
pCordb.Assign(GetProcess()->m_cordb);
}
}
// Move this into Shim?
// Invoke the ExitProcess callback. This is very important since the a shell
// may rely on it for proper shutdown and may hang if they don't get it.
// We don't expect Cordbg to continue from this (we're certainly not going to wait for it).
if ((pCordb != NULL) && (pCordb->m_managedCallback != NULL))
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0_NO_LOCK(GetProcess());
pCordb->m_managedCallback->ExitProcess(GetProcess());
}
// This CordbProcess object now has no reservations against a client calling ICorDebug::Terminate.
// That call may race against the CordbProcess::Neuter below, but since we already neutered the children,
// that neuter call will not do anything interesting that will conflict with Terminate.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: returned from ExitProcess callback\n"));
{
RSLockHolder ch(GetProcess()->GetStopGoLock());
// Release the process.
GetProcess()->Neuter();
}
// Our dtor will release the Process object.
// This may be the final release on the process.
}
//---------------------------------------------------------------------------------------
//
// Handles process exiting and detach cases
//
// Arguments:
// fDetach - true if detaching, false if process is exiting.
//
// Return Value:
// The type of the next argument in the signature,
// normalized.
//
// Assumptions:
// On exit, the process has already exited and we detected this by either an EXIT_PROCESS
// native debug event, or by waiting on the process handle.
// On detach, the process is stil live.
//
// Notes:
// ExitProcess is called when a process exits or detaches.
// This does our final cleanup and removes the process from our wait sets.
// We're either here because we're detaching (fDetach == TRUE), or because the process has really exited,
// and we're doing shutdown logic.
//
//---------------------------------------------------------------------------------------
void CordbWin32EventThread::ExitProcess(bool fDetach)
{
INTERNAL_API_ENTRY(this);
// Consider the following when you're modifying this function:
// - The OS can kill the debuggee at any time.
// - ExitProcess can race with detach.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: begin ExitProcess, detach=%d\n", fDetach));
// For the Mac remote debugging transport, DebugActiveProcessStop() is a nop. The transport will be
// shut down later when we neuter the CordbProcess.
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
// @dbgtodo shim: this is a primitive workaround for interop-detach
// Eventually, the Debugger owns the detach pipeline, so this won't be necessary.
if (fDetach && (m_pProcess != NULL))
{
HRESULT hr = m_pNativePipeline->DebugActiveProcessStop(m_pProcess->GetProcessDescriptor()->m_Pid);
// We don't expect detach to fail (we check earlier for common conditions that
// may cause it to fail)
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
if( FAILED(hr) )
{
m_actionResult = hr;
SetEvent(m_actionTakenEvent);
return;
}
}
#endif // !FEATURE_DBGIPC_TRANSPORT_DI
// We don't really care if we're on the Win32 thread or not here. We just want to be sure that
// the LS Exit case and the Detach case both occur on the same thread. This makes it much easier
// to assert that if we exit while detaching, EP is only called once.
// If we ever decide to make the RCET listen on the LS process handle for EP(exit), then we should also
// make the EP(detach) handled on the RCET (via DoFavor() ).
_ASSERTE(IsWin32EventThread());
// So either the Exit case or Detach case must happen first.
// 1) If Detach first, then LS process is removed from wait set and so EP(Exit) will never happen
// because we check wait set after returning from EP(Detach).
// 2) If Exit is first, m_pProcess gets set=NULL. EP(detach) will still get called, so explicitly check that.
if (fDetach && ((m_pProcess == NULL) || m_pProcess->m_terminated))
{
// m_terminated is only set after the LS exits.
// So the only way (fDetach && m_terminated) is true is if the LS exited while detaching. In that case
// we already called EP(exit) and we don't want to call it again for EP(detach). So return here.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: In EP(detach), but EP(exit) already called. Early failure\n"));
m_actionResult = CORDBG_E_PROCESS_TERMINATED;
SetEvent(m_actionTakenEvent);
return;
}
// We null m_pProcess at the end here, so
// Only way we could get here w/ null process is if we're called twice. We can only be called
// by detach or exit. Can't detach twice, can't exit twice, so must have been one of each.
// If exit is first, we got removed from the wait set, so 2nd call must be detach and we'd catch
// that above. If detach is first, we'd get removed from the wait set and so exit would never happen.
_ASSERTE(m_pProcess != NULL);
_ASSERTE(!m_pProcess->ThreadHoldsProcessLock());
// Mark the process teminated. After this, the RCET will never call FlushQueuedEvents. It will
// ignore all events it receives (including a SyncComplete) and the RCET also does not listen
// to terminated processes (so ProcessStateChange() won't cause a FQE either).
m_pProcess->Terminating(fDetach);
// Take care of the race where the process exits right after the user calls Continue() from the last
// managed event but before the handler has actually returned.
//
// Also, To get through this lock means that either:
// 1. FlushQueuedEvents is not currently executing and no one will call FQE.
// 2. FQE is exiting but is in the middle of a callback (so AreDispatchingEvent = true)
//
m_pProcess->Lock();
m_pProcess->m_exiting = true;
if (fDetach)
{
m_pProcess->SetSynchronized(false);
}
// If we are exiting, we *must* dispatch the ExitProcess callback, but we will delete all the events
// in the queue and not bother dispatching anything else. If (and only if) we are currently dispatching
// an event, then we will wait while that event is finished before invoking ExitProcess.
// (Note that a dispatched event has already been removed from the queue)
// Remove the process from the global list of processes.
m_cordb->RemoveProcess(m_pProcess);
if (fDetach)
{
// Signal the hr to the caller.
LOG((LF_CORDB, LL_INFO1000,"W32ET::EP: Detach: send result back!\n"));
m_actionResult = S_OK;
SetEvent(m_actionTakenEvent);
}
m_pProcess->Unlock();
// Delete all queued events
m_pProcess->DeleteQueuedEvents();
// If we're detaching, then the Detach already neutered everybody, so nothing here.
// If we're exiting, then we still need to neuter things, but we can't do that on this thread,
// so we queue it. We also need to dispatch an exit process callback. We'll queue that onto the RCET
// and dispatch it inband w/the other callbacks.
if (!fDetach)
{
#ifdef TARGET_UNIX
// Cleanup the transport pipe and semaphore files that might be left by the target (LS) process.
m_pNativePipeline->CleanupTargetProcess();
#endif
ExitProcessWorkItem * pItem = new (nothrow) ExitProcessWorkItem(m_pProcess);
if (pItem != NULL)
{
m_cordb->m_rcEventThread->QueueAsyncWorkItem(pItem);
}
}
// This will remove the process from our wait lists (so that we don't send multiple ExitProcess events).
m_pProcess.Clear();
}
//
// Start actually creates and starts the thread.
//
HRESULT CordbWin32EventThread::Start()
{
HRESULT hr = S_OK;
if (m_threadControlEvent == NULL)
return E_INVALIDARG;
// Create the thread suspended to make sure that m_threadId is set
// before CordbWin32EventThread::ThreadProc runs
// Stack size = 0x80000 = 512KB
m_thread = CreateThread(NULL, 0x80000, &CordbWin32EventThread::ThreadProc,
(LPVOID) this, CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, &m_threadId);
if (m_thread == NULL)
return HRESULT_FROM_GetLastError();
DWORD succ = ResumeThread(m_thread);
if (succ == (DWORD)-1)
return HRESULT_FROM_GetLastError();
return hr;
}
//
// Stop causes the thread to stop receiving events and exit. It
// waits for it to exit before returning.
//
HRESULT CordbWin32EventThread::Stop()
{
HRESULT hr = S_OK;
// m_pProcess may be NULL from CordbWin32EventThread::ExitProcess
// Can't block on W32ET while holding the process-lock since the W32ET may need that to exit.
// But since m_pProcess may be null, we can't enforce that.
if (m_thread != NULL)
{
LockSendToWin32EventThreadMutex();
m_action = W32ETA_NONE;
m_run = FALSE;
SetEvent(m_threadControlEvent);
UnlockSendToWin32EventThreadMutex();
DWORD ret = WaitForSingleObject(m_thread, INFINITE);
if (ret != WAIT_OBJECT_0)
hr = HRESULT_FROM_GetLastError();
}
m_pProcess.Clear();
m_cordb.Clear();
return hr;
}
// Allocate a buffer of cbBuffer bytes in the target.
//
// Arguments:
// cbBuffer - count of bytes for the buffer.
//
// Returns:
// a TargetBuffer describing the new memory region in the target.
// Throws on error.
TargetBuffer CordbProcess::GetRemoteBuffer(ULONG cbBuffer)
{
INTERNAL_SYNC_API_ENTRY(this); //
// Create and initialize the event as synchronous
DebuggerIPCEvent event;
InitIPCEvent(&event,
DB_IPCE_GET_BUFFER,
true,
VMPTR_AppDomain::NullPtr());
// Indicate the buffer size wanted
event.GetBuffer.bufSize = cbBuffer;
// Make the request, which is synchronous
HRESULT hr = SendIPCEvent(&event, sizeof(event));
IfFailThrow(hr);
_ASSERTE(event.type == DB_IPCE_GET_BUFFER_RESULT);
IfFailThrow(event.GetBufferResult.hr);
// The request succeeded. Return the newly allocated range.
return TargetBuffer(event.GetBufferResult.pBuffer, cbBuffer);
}
/*
* This will release a previously allocated left side buffer.
*/
HRESULT CordbProcess::ReleaseRemoteBuffer(void **ppBuffer)
{
INTERNAL_SYNC_API_ENTRY(this); //
_ASSERTE(m_pShim != NULL);
// Create and initialize the event as synchronous
DebuggerIPCEvent event;
InitIPCEvent(&event,
DB_IPCE_RELEASE_BUFFER,
true,
VMPTR_AppDomain::NullPtr());
// Indicate the buffer to release
event.ReleaseBuffer.pBuffer = (*ppBuffer);
// Make the request, which is synchronous
HRESULT hr = SendIPCEvent(&event, sizeof(event));
TESTANDRETURNHR(hr);
(*ppBuffer) = NULL;
// Indicate success
return event.ReleaseBufferResult.hr;
}
HRESULT CordbProcess::SetDesiredNGENCompilerFlags(DWORD dwFlags)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return CORDBG_E_NGEN_NOT_SUPPORTED;
}
HRESULT CordbProcess::GetDesiredNGENCompilerFlags(DWORD *pdwFlags )
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pdwFlags, DWORD*);
*pdwFlags = 0;
CordbProcess *pProcess = GetProcess();
ATT_REQUIRE_STOPPED_MAY_FAIL(pProcess);
HRESULT hr = S_OK;
EX_TRY
{
hr = pProcess->GetDAC()->GetNGENCompilerFlags(pdwFlags);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//-----------------------------------------------------------------------------
// Get an ICorDebugReference Value for the GC handle.
// handle - raw bits for the GC handle.
// pOutHandle
//-----------------------------------------------------------------------------
HRESULT CordbProcess::GetReferenceValueFromGCHandle(
UINT_PTR gcHandle,
ICorDebugReferenceValue **pOutValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(this);
VALIDATE_POINTER_TO_OBJECT(pOutValue, ICorDebugReferenceValue*);
*pOutValue = NULL;
HRESULT hr = S_OK;
EX_TRY
{
if (gcHandle == NULL)
{
ThrowHR(CORDBG_E_BAD_REFERENCE_VALUE);
}
IDacDbiInterface* pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetVmObjectHandle(gcHandle);
if(!pDAC->IsVmObjectHandleValid(vmObjHandle))
{
ThrowHR(CORDBG_E_BAD_REFERENCE_VALUE);
}
ULONG appDomainId = pDAC->GetAppDomainIdFromVmObjectHandle(vmObjHandle);
VMPTR_AppDomain vmAppDomain = pDAC->GetAppDomainFromId(appDomainId);
RSLockHolder lockHolder(GetProcessLock());
CordbAppDomain * pAppDomain = LookupOrCreateAppDomain(vmAppDomain);
lockHolder.Release();
// Now that we finally have the AppDomain, we can go ahead and get a ReferenceValue
// from the ObjectHandle.
hr = CordbReferenceValue::BuildFromGCHandle(pAppDomain, vmObjHandle, pOutValue);
_ASSERTE(SUCCEEDED(hr) == (*pOutValue != NULL));
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//-----------------------------------------------------------------------------
// Return count of outstanding GC handles held by CordbHandleValue objects
LONG CordbProcess::OutstandingHandles()
{
return m_cOutstandingHandles;
}
//-----------------------------------------------------------------------------
// Increment the outstanding handle count for code:CordbProces::OutstandingHandles
// This is the inverse of code:CordbProces::DecrementOutstandingHandles
void CordbProcess::IncrementOutstandingHandles()
{
_ASSERTE(ThreadHoldsProcessLock());
m_cOutstandingHandles++;
}
//-----------------------------------------------------------------------------
// Decrement the outstanding handle count for code:CordbProces::OutstandingHandles
// This is the inverse of code:CordbProces::IncrementOutstandingHandles
void CordbProcess::DecrementOutstandingHandles()
{
_ASSERTE(ThreadHoldsProcessLock());
m_cOutstandingHandles--;
}
/*
* IsReadyForDetach
*
* This method encapsulates all logic for deciding if it is ok for a debugger to
* detach from the process at this time.
*
* Parameters: None.
*
* Returns: S_OK if it is ok to detach, else a specific HRESULT describing why it
* is not ok to detach.
*
*/
HRESULT CordbProcess::IsReadyForDetach()
{
INTERNAL_API_ENTRY(this);
// Always safe to detach in V3 case.
if (m_pShim == NULL)
{
return S_OK;
}
// If not initialized yet, then there are no detach liabilities.
if (!m_initialized)
{
return S_OK;
}
RSLockHolder lockHolder(&this->m_processMutex);
//
// If there are any outstanding func-evals then fail the detach.
//
if (OutstandingEvalCount() != 0)
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_EVALS;
}
// V2 didn't check outstanding handles (code:CordbProcess::OutstandingHandles)
// because it could automatically clean those up on detach.
//
// If there are any outstanding steppers then fail the detach.
//
if (m_steppers.IsInitialized() && (m_steppers.GetCount() > 0))
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_STEPPERS;
}
//
// If there are any outstanding breakpoints then fail the detach.
//
HASHFIND foundAppDomain;
CordbAppDomain *pAppDomain = m_appDomains.FindFirst(&foundAppDomain);
while (pAppDomain != NULL)
{
if (pAppDomain->m_breakpoints.IsInitialized() && (pAppDomain->m_breakpoints.GetCount() > 0))
{
return CORDBG_E_DETACH_FAILED_OUTSTANDING_BREAKPOINTS;
}
// Check for any outstanding EnC modules.
HASHFIND foundModule;
CordbModule * pModule = pAppDomain->m_modules.FindFirst(&foundModule);
while (pModule != NULL)
{
if (pModule->m_EnCCount > 0)
{
return CORDBG_E_DETACH_FAILED_ON_ENC;
}
pModule = pAppDomain->m_modules.FindNext(&foundModule);
}
pAppDomain = m_appDomains.FindNext(&foundAppDomain);
}
return S_OK;
}
/*
* Look for any thread which was last seen in the specified AppDomain.
* The CordbAppDomain object is about to be neutered due to an AD Unload
* So the thread must no longer be considered to be in that domain.
* Note that this is a workaround due to the existance of the (possibly incorrect)
* cached AppDomain value. Ideally we would remove the cached value entirely
* and there would be no need for this.
*
* @dbgtodo: , appdomain: We should remove CordbThread::m_pAppDomain in the V3 architecture.
* If we need the thread's current domain, we should get it accurately with DAC.
*/
void CordbProcess::UpdateThreadsForAdUnload(CordbAppDomain * pAppDomain)
{
INTERNAL_API_ENTRY(this);
// If we're doing an AD unload then we should have already seen the ATTACH
// notification for the default domain.
//_ASSERTE( m_pDefaultAppDomain != NULL );
// @dbgtodo appdomain: fix Default domain invariants with DAC-izing Appdomain work.
RSLockHolder lockHolder(GetProcessLock());
CordbThread* t;
HASHFIND find;
// We don't need to prepopulate here (to collect LS state) because we're just updating RS state.
for (t = m_userThreads.FindFirst(&find);
t != NULL;
t = m_userThreads.FindNext(&find))
{
if( t->GetAppDomain() == pAppDomain )
{
// This thread cannot actually be in this AppDomain anymore (since it's being
// unloaded). Reset it to point to the default AppDomain
t->m_pAppDomain = m_pDefaultAppDomain;
}
}
}
// CordbProcess::LookupClass
// Looks up a previously constructed CordbClass instance without creating. May return NULL if the
// CordbClass instance doesn't exist.
// Argument: (in) vmDomainAssembly - pointer to the domain assembly for the module
// (in) mdTypeDef - metadata token for the class
// Return value: pointer to a previously created CordbClass instance or NULL in none exists
CordbClass * CordbProcess::LookupClass(ICorDebugAppDomain * pAppDomain, VMPTR_DomainAssembly vmDomainAssembly, mdTypeDef classToken)
{
_ASSERTE(ThreadHoldsProcessLock());
if (pAppDomain != NULL)
{
CordbModule * pModule = ((CordbAppDomain *)pAppDomain)->m_modules.GetBase(VmPtrToCookie(vmDomainAssembly));
if (pModule != NULL)
{
return pModule->LookupClass(classToken);
}
}
return NULL;
} // CordbProcess::LookupClass
//---------------------------------------------------------------------------------------
// Look for a specific module in the process.
//
// Arguments:
// vmDomainAssembly - non-null module to lookup
//
// Returns:
// a CordbModule object for the given cookie. Object may be from the cache, or created
// lazily.
// Never returns null. Throws on error.
//
// Notes:
// A VMPTR_DomainAssembly has appdomain affinity, but is ultimately scoped to a process.
// So if we get a raw VMPTR_DomainAssembly (eg, from the stackwalker or from some other
// lookup function), then we need to do a process wide lookup since we don't know which
// appdomain it's in. If you know the appdomain, you can use code:CordbAppDomain::LookupOrCreateModule.
//
CordbModule * CordbProcess::LookupOrCreateModule(VMPTR_DomainAssembly vmDomainAssembly)
{
INTERNAL_API_ENTRY(this);
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
_ASSERTE(!vmDomainAssembly.IsNull());
DomainAssemblyInfo data;
GetDAC()->GetDomainAssemblyData(vmDomainAssembly, &data); // throws
CordbAppDomain * pAppDomain = LookupOrCreateAppDomain(data.vmAppDomain);
return pAppDomain->LookupOrCreateModule(vmDomainAssembly);
}
//---------------------------------------------------------------------------------------
// Determine if the process has any in-band queued events which have not been dispatched
//
// Returns:
// TRUE iff there are undispatched IB events
//
#ifdef FEATURE_INTEROP_DEBUGGING
BOOL CordbProcess::HasUndispatchedNativeEvents()
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedEvent* pEvent = m_unmanagedEventQueue;
while(pEvent != NULL && pEvent->IsDispatched())
{
pEvent = pEvent->m_next;
}
return pEvent != NULL;
}
#endif
//---------------------------------------------------------------------------------------
// Determine if the process has any in-band queued events which have not been user continued
//
// Returns:
// TRUE iff there are user uncontinued IB events
//
#ifdef FEATURE_INTEROP_DEBUGGING
BOOL CordbProcess::HasUserUncontinuedNativeEvents()
{
INTERNAL_API_ENTRY(this);
CordbUnmanagedEvent* pEvent = m_unmanagedEventQueue;
while(pEvent != NULL && pEvent->IsEventUserContinued())
{
pEvent = pEvent->m_next;
}
return pEvent != NULL;
}
#endif
//---------------------------------------------------------------------------------------
// Hijack the thread which had this event. If the thread is already hijacked this method
// has no effect.
//
// Arguments:
// pUnmanagedEvent - the debug event which requires us to hijack
//
// Returns:
// S_OK on success, failing HRESULT if the hijack could not be set up
//
#ifdef FEATURE_INTEROP_DEBUGGING
HRESULT CordbProcess::HijackIBEvent(CordbUnmanagedEvent * pUnmanagedEvent)
{
// Can't hijack after the event has already been continued hijacked
_ASSERTE(!pUnmanagedEvent->IsEventContinuedHijacked());
// Can only hijack IB events
_ASSERTE(pUnmanagedEvent->IsIBEvent());
// If we already hijacked the event then there is nothing left to do
if(pUnmanagedEvent->m_owner->IsFirstChanceHijacked() ||
pUnmanagedEvent->m_owner->IsGenericHijacked())
{
return S_OK;
}
ResetEvent(this->m_leftSideUnmanagedWaitEvent);
if (pUnmanagedEvent->m_currentDebugEvent.u.Exception.dwFirstChance)
{
HRESULT hr = pUnmanagedEvent->m_owner->SetupFirstChanceHijackForSync();
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return hr;
}
else // Second chance exceptions must be generic hijacked.
{
HRESULT hr = pUnmanagedEvent->m_owner->SetupGenericHijack(pUnmanagedEvent->m_currentDebugEvent.dwDebugEventCode, &pUnmanagedEvent->m_currentDebugEvent.u.Exception.ExceptionRecord);
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
return hr;
}
}
#endif
// Sets a bitfield reflecting the managed debugging state at the time of
// the jit attach.
HRESULT CordbProcess::GetAttachStateFlags(CLR_DEBUGGING_PROCESS_FLAGS *pFlags)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
if(pFlags == NULL)
hr = E_POINTER;
else
*pFlags = GetDAC()->GetAttachStateFlags();
}
PUBLIC_API_END(hr);
return hr;
}
// Determine if this version of ICorDebug is compatibile with the ICorDebug in the specified major CLR version
bool CordbProcess::IsCompatibleWith(DWORD clrMajorVersion)
{
// The debugger versioning policy is that debuggers generally need to opt-in to supporting major new
// versions of the CLR. Often new versions of the CLR violate some invariant that previous debuggers assume
// (eg. hot/cold splitting in Whidbey, multiple CLRs in a process in CLR v4), and neither VS or the CLR
// teams generally want the support burden of forward compatibility.
//
// If this assert is firing for you, its probably because the major version
// number of the clr.dll has changed. This assert is here to remind you to do a bit of other
// work you may not have realized you needed to do so that our versioning works smoothly
// for debugging. You probably want to contact the CLR DST team if you are a
// non-debugger person hitting this. DON'T JUST DELETE THIS ASSERT!!!
//
// 1) You should ensure new versions of all ICorDebug users in DevDiv (VS Debugger, MDbg, etc.)
// are using a creation path that explicitly specifies that they support this new major
// version of the CLR.
// 2) You should file an issue to track blocking earlier debuggers from targetting this
// version of the CLR (i.e. update requiredVersion to the new CLR major
// version). To enable a smooth internal transition, this often isn't done until absolutely
// necessary (sometimes as late as Beta2).
// 3) You can consider updating the CLR_ID guid used by the shim to recognize a CLR, but only
// if it's important to completely hide newer CLRs from the shim. The expectation now
// is that we won't need to do this (i.e. we'd like VS to give a nice error message about
// needed a newer version of the debugger, rather than just acting as if a process has no CLR).
// 4) Update this assert so that it no longer fires for your new CLR version or any of
// the previous versions, but don't delete the assert...
// the next CLR version after yours will probably need the same reminder
_ASSERTE_MSG(clrMajorVersion <= 4,
"Found major CLR version greater than 4 in mscordbi.dll from CLRv4 - contact CLRDST");
// This knob lets us enable forward compatibility for internal scenarios, and also simulate new
// versions of the runtime for testing the failure user-experience in a version of the debugger
// before it is shipped.
// We don't want to risk customers getting this, so for RTM builds this must be CHK-only.
// To aid in internal transition, we may temporarily enable this in RET builds, but when
// doing so must file a bug to track making it CHK only again before RTM.
// For example, Dev10 Beta2 shipped with this knob, but it was made CHK-only at the start of RC.
// In theory we might have a point release someday where we break debugger compat, but
// it seems unlikely and since this knob is unsupported anyway we can always extend it
// then (support reading a string value, etc.). So for now we just map the number
// to the major CLR version number.
DWORD requiredVersion = 0;
#ifdef _DEBUG
requiredVersion = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_Debugging_RequiredVersion);
#endif
// If unset (the only supported configuration), then we require a debugger designed for CLRv4
// for desktop, where we do not allow forward compat.
// For SL, we allow forward compat. Right now, that means SLv2+ debugger requests can be
// honored for SLv4.
if (requiredVersion <= 0)
{
requiredVersion = 2;
}
// Compare the version we were created for against the minimum required
return (clrMajorVersion >= requiredVersion);
}
bool CordbProcess::IsThreadSuspendedOrHijacked(ICorDebugThread * pICorDebugThread)
{
// An RS lock can be held while this is called. Specifically,
// CordbThread::EnumerateChains may be on the stack, and it uses
// ATT_REQUIRE_STOPPED_MAY_FAIL, which holds the CordbProcess::m_StopGoLock lock for
// its entire duration. As a result, this needs to be considered a reentrant API. See
// comments above code:PrivateShimCallbackHolder for more info.
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(this);
CordbThread * pCordbThread = static_cast<CordbThread *> (pICorDebugThread);
return GetDAC()->IsThreadSuspendedOrHijacked(pCordbThread->m_vmThreadToken);
}
void CordbProcess::HandleControlCTrapResult(HRESULT result)
{
RSLockHolder ch(GetStopGoLock());
DebuggerIPCEvent eventControlCResult;
InitIPCEvent(&eventControlCResult,
DB_IPCE_CONTROL_C_EVENT_RESULT,
false,
VMPTR_AppDomain::NullPtr());
// Indicate whether the debugger has handled the event.
eventControlCResult.hr = result;
// Send the reply to the LS.
SendIPCEvent(&eventControlCResult, sizeof(eventControlCResult));
}
| -1 |
dotnet/runtime
| 66,432 |
Overhaul how regex generated code is structured
|
Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
stephentoub
| 2022-03-10T04:10:24Z | 2022-03-10T23:42:20Z |
458524aa752f6841db44bd4443ccc3f3863e0a4e
|
3fc949bc10a83c8b62c8938ba2ae09b6ceb8169d
|
Overhaul how regex generated code is structured. Fixes https://github.com/dotnet/runtime/issues/63502
Fixes https://github.com/dotnet/runtime/issues/63512
For every regex, we currently emit a private type next to the partial member we're implementing, and that private type contains all the code for the regex, including all the helpers it needs. There are multiple issues with this:
- We're emitting a lot of duplicated code into an assembly that has multiple/many uses of [RegexGenerator(...)]. System.Private.Xml has ~10 uses of it now and it has ~1000 lines of unnecessarily duplicative code being generated.
- We have to global::-qualify all uses of types we rely on in the implementation, because C# binding rules would otherwise bind to things declared inside the user's partial type we're generating into. This is particularly bad for extension methods, which we then can't use as extensions, and we make heavy use of MemoryExtensions throughout the generated code for all of our interactions with spans.
- We could avoid the code duplication by putting all the helpers into a shared utilities type, but then that type would need to be internal and would effectively be shipping surface area we don't want to ship.
- Code inside that user's type can see the private type we're emitting, and EditorBrowsable doesn't currently help (https://github.com/dotnet/roslyn/issues/60080).
With this PR, we instead move all of the types into a separate namespace and parent class, which then enables a) having usings inside the namespace declaration so that we can avoid fully-qualifying everything and b) separating out all of the helper methods into a class that's then private to the parent wrapper class, shielding it from the rest of the assembly.
Hopefully C# 11 will see a solution to https://github.com/dotnet/csharplang/issues/5529, at which point we can use that to hide all of the separated out generated code other than the partial method definitions (with the changes in this PR, doing so should involve minimal tweaks to the code generation). Until then, we still have a similar problem as we do today for the generated Regex-derived types being visible to other code in the assembly, but at least the shared helpers aren't.
cc: @joperezr, @chsienki
|
./src/tests/JIT/IL_Conformance/Old/Base/br_s.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.class _br_s {
.method public static int32 main(class [mscorlib]System.String[]) {
.entrypoint
.maxstack 10
br.s PASS
FAIL:
ldc.i4 0x0
ret
PASS:
ldc.i4 100
ret
}
}
.assembly br_s {}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.class _br_s {
.method public static int32 main(class [mscorlib]System.String[]) {
.entrypoint
.maxstack 10
br.s PASS
FAIL:
ldc.i4 0x0
ret
PASS:
ldc.i4 100
ret
}
}
.assembly br_s {}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/CMakeLists.txt
|
cmake_minimum_required(VERSION 3.6.2)
if (CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15)
cmake_policy(SET CMP0091 NEW)
endif()
project(corehost)
include(../../../eng/native/configurepaths.cmake)
include(${CLR_ENG_NATIVE_DIR}/configurecompiler.cmake)
if (MSVC)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4996>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4267>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4018>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4200>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4244>)
# Host components don't try to handle asynchronous exceptions
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/EHsc>)
elseif (CMAKE_CXX_COMPILER_ID MATCHES GNU)
# Prevents libc from calling pthread_cond_destroy on static objects in
# dlopen()'ed library which we dlclose() in pal::unload_library.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-use-cxa-atexit>)
endif()
add_subdirectory(hostcommon)
add_subdirectory(fxr)
add_subdirectory(hostpolicy)
add_subdirectory(apphost)
add_subdirectory(dotnet)
add_subdirectory(nethost)
add_subdirectory(test)
if (NOT RUNTIME_FLAVOR STREQUAL Mono)
if(CLR_CMAKE_TARGET_WIN32)
add_subdirectory(comhost)
add_subdirectory(ijwhost)
endif()
endif()
|
cmake_minimum_required(VERSION 3.6.2)
if (CMAKE_VERSION VERSION_GREATER 3.15 OR CMAKE_VERSION VERSION_EQUAL 3.15)
cmake_policy(SET CMP0091 NEW)
endif()
project(corehost)
include(../../../eng/native/configurepaths.cmake)
include(${CLR_ENG_NATIVE_DIR}/configurecompiler.cmake)
if (MSVC)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4267>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4018>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4200>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4244>)
# Host components don't try to handle asynchronous exceptions
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:/EHsc>)
elseif (CMAKE_CXX_COMPILER_ID MATCHES GNU)
# Prevents libc from calling pthread_cond_destroy on static objects in
# dlopen()'ed library which we dlclose() in pal::unload_library.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-use-cxa-atexit>)
endif()
add_subdirectory(hostcommon)
add_subdirectory(fxr)
add_subdirectory(hostpolicy)
add_subdirectory(apphost)
add_subdirectory(dotnet)
add_subdirectory(nethost)
add_subdirectory(test)
if (NOT RUNTIME_FLAVOR STREQUAL Mono)
if(CLR_CMAKE_TARGET_WIN32)
add_subdirectory(comhost)
add_subdirectory(ijwhost)
endif()
endif()
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/apphost/static/CMakeLists.txt
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
project(singlefilehost)
set(DOTNET_PROJECT_NAME "singlefilehost")
# Add RPATH to the apphost binary that allows using local copies of shared libraries
# dotnet core depends on for special scenarios when system wide installation of such
# dependencies is not possible for some reason.
# This cannot be enabled for MacOS (Darwin) since its RPATH works in a different way,
# doesn't apply to libraries loaded via dlopen and most importantly, it is not transitive.
if (NOT CLR_CMAKE_TARGET_OSX)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH "\$ORIGIN/netcoredeps")
endif()
set(SKIP_VERSIONING 1)
include_directories(..)
include_directories(../../json)
include_directories(${CLR_SRC_NATIVE_DIR}/libs/System.IO.Compression.Native)
include_directories(${CLR_SRC_NATIVE_DIR}/libs/Common)
set(SOURCES
../bundle_marker.cpp
./hostfxr_resolver.cpp
./hostpolicy_resolver.cpp
../../hostpolicy/static/coreclr_resolver.cpp
)
set(HEADERS
../bundle_marker.h
../../hostfxr_resolver.h
)
add_definitions(-D_NO_ASYNCRTIMP)
add_definitions(-D_NO_PPLXIMP)
remove_definitions(-DEXPORT_SHARED_API)
add_definitions(-DHOSTPOLICY_EMBEDDED)
add_definitions(-DNATIVE_LIBS_EMBEDDED)
include(../../fxr/files.cmake)
include(../../hostpolicy/files.cmake)
include(../../hostcommon/files.cmake)
if(MSVC)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4996>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4267>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4018>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4200>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4244>)
# Host components don't try to handle asynchronous exceptions
add_compile_options(/EHsc)
elseif (CMAKE_CXX_COMPILER_ID MATCHES GNU)
# Prevents libc from calling pthread_cond_destroy on static objects in
# dlopen()'ed library which we dlclose() in pal::unload_library.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-use-cxa-atexit>)
endif()
if(CLR_CMAKE_TARGET_WIN32)
list(APPEND SOURCES
../apphost.windows.cpp)
list(APPEND HEADERS
../apphost.windows.h)
endif()
if(CLR_CMAKE_TARGET_WIN32)
add_linker_flag("/DEF:${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost.def")
else()
if(CLR_CMAKE_TARGET_OSX)
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_OSXexports.src)
else()
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_unixexports.src)
endif()
set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/singlefilehost.exports)
generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE})
set_exports_linker_option(${EXPORTS_FILE})
endif()
if (CLR_SINGLE_FILE_HOST_ONLY)
set(ADDITIONAL_INSTALL_ARGUMENTS COMPONENT runtime)
endif()
include(../../exe.cmake)
include(configure.cmake)
if(CLR_CMAKE_HOST_UNIX)
add_custom_target(singlefilehost_exports DEPENDS ${EXPORTS_FILE})
add_dependencies(singlefilehost singlefilehost_exports)
set_property(TARGET singlefilehost APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION})
set_property(TARGET singlefilehost APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE})
endif()
add_definitions(-DFEATURE_APPHOST=1)
add_definitions(-DFEATURE_STATIC_HOST=1)
if(CLR_CMAKE_TARGET_WIN32)
# Disable manifest generation into the file .exe on Windows
add_linker_flag("/MANIFEST:NO")
# Incremental linking results in the linker inserting extra padding and routing function calls via thunks that can break the
# invariants (e.g. size of region between Jit_PatchedCodeLast-Jit_PatchCodeStart needs to fit in a page).
add_linker_flag("/INCREMENTAL:NO")
# Delay load libraries required for WinRT as that is not supported on all platforms
add_linker_flag("/DELAYLOAD:api-ms-win-core-winrt-l1-1-0.dll")
endif()
if(CLR_CMAKE_TARGET_WIN32)
set(NATIVE_LIBS
coreclr_static
System.Globalization.Native-Static
System.IO.Compression.Native-Static
kernel32.lib
advapi32.lib
ole32.lib
oleaut32.lib
uuid.lib
user32.lib
version.lib
shlwapi.lib
shell32.lib
bcrypt.lib
RuntimeObject.lib
delayimp.lib
)
set(RUNTIMEINFO_LIB runtimeinfo)
else()
set(NATIVE_LIBS
coreclr_static
System.Globalization.Native-Static
System.IO.Compression.Native-Static
System.Net.Security.Native-Static
System.Native-Static
System.Security.Cryptography.Native.OpenSsl-Static
palrt
coreclrpal
eventprovider
nativeresourcestring
)
# additional requirements for System.IO.Compression.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.IO.Compression.Native/extra_libs.cmake)
append_extra_compression_libs(NATIVE_LIBS)
# Additional requirements for System.Net.Security.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.Net.Security.Native/extra_libs.cmake)
append_extra_security_libs(NATIVE_LIBS)
# Additional requirements for System.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.Native/extra_libs.cmake)
append_extra_system_libs(NATIVE_LIBS)
# Additional requirements for System.Security.Cryptography.Native.OpenSsl
include(${CLR_SRC_NATIVE_DIR}/libs/System.Security.Cryptography.Native/extra_libs.cmake)
append_extra_cryptography_libs(NATIVE_LIBS)
set(RUNTIMEINFO_LIB runtimeinfo)
endif()
if(CLR_CMAKE_TARGET_OSX)
LIST(APPEND NATIVE_LIBS
System.Security.Cryptography.Native.Apple-Static
)
# Additional requirements for System.Security.Cryptography.Native.Apple
include(${CLR_SRC_NATIVE_DIR}/libs/System.Security.Cryptography.Native.Apple/extra_libs.cmake)
append_extra_cryptography_apple_libs(NATIVE_LIBS)
endif()
#
# Additional requirements for coreclr
#
if(CLR_CMAKE_TARGET_OSX)
find_library(COREFOUNDATION CoreFoundation)
find_library(CORESERVICES CoreServices)
find_library(SECURITY Security)
find_library(SYSTEM System)
LIST(APPEND NATIVE_LIBS
${COREFOUNDATION}
${CORESERVICES}
${SECURITY}
${SYSTEM}
)
elseif(CLR_CMAKE_TARGET_NETBSD)
find_library(KVM kvm)
LIST(APPEND NATIVE_LIBS
${KVM}
)
elseif (CLR_CMAKE_TARGET_SUNOS)
LIST(APPEND NATIVE_LIBS
socket
)
endif(CLR_CMAKE_TARGET_OSX)
# On *BSD, we always use the libunwind that's part of the OS
if(CLR_CMAKE_TARGET_FREEBSD)
set(CLR_CMAKE_USE_SYSTEM_LIBUNWIND 1)
endif()
if(CLR_CMAKE_USE_SYSTEM_LIBUNWIND)
find_unwind_libs(UNWIND_LIBS)
LIST(APPEND NATIVE_LIBS
${UNWIND_LIBS}
)
endif()
if(CLR_CMAKE_TARGET_LINUX OR CLR_CMAKE_TARGET_FREEBSD OR CLR_CMAKE_TARGET_NETBSD OR CLR_CMAKE_TARGET_SUNOS)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -Wl,--whole-archive)
set(END_WHOLE_ARCHIVE -Wl,--no-whole-archive)
endif(CLR_CMAKE_TARGET_LINUX OR CLR_CMAKE_TARGET_FREEBSD OR CLR_CMAKE_TARGET_NETBSD OR CLR_CMAKE_TARGET_SUNOS)
if(CLR_CMAKE_TARGET_OSX)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -force_load)
set(END_WHOLE_ARCHIVE )
endif(CLR_CMAKE_TARGET_OSX)
set_property(TARGET singlefilehost PROPERTY ENABLE_EXPORTS 1)
target_link_libraries(
singlefilehost
${NATIVE_LIBS}
${START_WHOLE_ARCHIVE}
${RUNTIMEINFO_LIB}
${END_WHOLE_ARCHIVE}
)
|
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
project(singlefilehost)
set(DOTNET_PROJECT_NAME "singlefilehost")
# Add RPATH to the apphost binary that allows using local copies of shared libraries
# dotnet core depends on for special scenarios when system wide installation of such
# dependencies is not possible for some reason.
# This cannot be enabled for MacOS (Darwin) since its RPATH works in a different way,
# doesn't apply to libraries loaded via dlopen and most importantly, it is not transitive.
if (NOT CLR_CMAKE_TARGET_OSX)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH "\$ORIGIN/netcoredeps")
endif()
set(SKIP_VERSIONING 1)
include_directories(..)
include_directories(../../json)
include_directories(${CLR_SRC_NATIVE_DIR}/libs/System.IO.Compression.Native)
include_directories(${CLR_SRC_NATIVE_DIR}/libs/Common)
set(SOURCES
../bundle_marker.cpp
./hostfxr_resolver.cpp
./hostpolicy_resolver.cpp
../../hostpolicy/static/coreclr_resolver.cpp
)
set(HEADERS
../bundle_marker.h
../../hostfxr_resolver.h
)
add_definitions(-D_NO_ASYNCRTIMP)
add_definitions(-D_NO_PPLXIMP)
remove_definitions(-DEXPORT_SHARED_API)
add_definitions(-DHOSTPOLICY_EMBEDDED)
add_definitions(-DNATIVE_LIBS_EMBEDDED)
include(../../fxr/files.cmake)
include(../../hostpolicy/files.cmake)
include(../../hostcommon/files.cmake)
if(MSVC)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4267>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4018>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4200>)
add_compile_options($<$<COMPILE_LANGUAGE:C,CXX>:/wd4244>)
# Host components don't try to handle asynchronous exceptions
add_compile_options(/EHsc)
elseif (CMAKE_CXX_COMPILER_ID MATCHES GNU)
# Prevents libc from calling pthread_cond_destroy on static objects in
# dlopen()'ed library which we dlclose() in pal::unload_library.
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fno-use-cxa-atexit>)
endif()
if(CLR_CMAKE_TARGET_WIN32)
list(APPEND SOURCES
../apphost.windows.cpp)
list(APPEND HEADERS
../apphost.windows.h)
endif()
if(CLR_CMAKE_TARGET_WIN32)
add_linker_flag("/DEF:${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost.def")
else()
if(CLR_CMAKE_TARGET_OSX)
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_OSXexports.src)
else()
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/singlefilehost_unixexports.src)
endif()
set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/singlefilehost.exports)
generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE})
set_exports_linker_option(${EXPORTS_FILE})
endif()
if (CLR_SINGLE_FILE_HOST_ONLY)
set(ADDITIONAL_INSTALL_ARGUMENTS COMPONENT runtime)
endif()
include(../../exe.cmake)
include(configure.cmake)
if(CLR_CMAKE_HOST_UNIX)
add_custom_target(singlefilehost_exports DEPENDS ${EXPORTS_FILE})
add_dependencies(singlefilehost singlefilehost_exports)
set_property(TARGET singlefilehost APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION})
set_property(TARGET singlefilehost APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE})
endif()
add_definitions(-DFEATURE_APPHOST=1)
add_definitions(-DFEATURE_STATIC_HOST=1)
if(CLR_CMAKE_TARGET_WIN32)
# Disable manifest generation into the file .exe on Windows
add_linker_flag("/MANIFEST:NO")
# Incremental linking results in the linker inserting extra padding and routing function calls via thunks that can break the
# invariants (e.g. size of region between Jit_PatchedCodeLast-Jit_PatchCodeStart needs to fit in a page).
add_linker_flag("/INCREMENTAL:NO")
# Delay load libraries required for WinRT as that is not supported on all platforms
add_linker_flag("/DELAYLOAD:api-ms-win-core-winrt-l1-1-0.dll")
endif()
if(CLR_CMAKE_TARGET_WIN32)
set(NATIVE_LIBS
coreclr_static
System.Globalization.Native-Static
System.IO.Compression.Native-Static
kernel32.lib
advapi32.lib
ole32.lib
oleaut32.lib
uuid.lib
user32.lib
version.lib
shlwapi.lib
shell32.lib
bcrypt.lib
RuntimeObject.lib
delayimp.lib
)
set(RUNTIMEINFO_LIB runtimeinfo)
else()
set(NATIVE_LIBS
coreclr_static
System.Globalization.Native-Static
System.IO.Compression.Native-Static
System.Net.Security.Native-Static
System.Native-Static
System.Security.Cryptography.Native.OpenSsl-Static
palrt
coreclrpal
eventprovider
nativeresourcestring
)
# additional requirements for System.IO.Compression.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.IO.Compression.Native/extra_libs.cmake)
append_extra_compression_libs(NATIVE_LIBS)
# Additional requirements for System.Net.Security.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.Net.Security.Native/extra_libs.cmake)
append_extra_security_libs(NATIVE_LIBS)
# Additional requirements for System.Native
include(${CLR_SRC_NATIVE_DIR}/libs/System.Native/extra_libs.cmake)
append_extra_system_libs(NATIVE_LIBS)
# Additional requirements for System.Security.Cryptography.Native.OpenSsl
include(${CLR_SRC_NATIVE_DIR}/libs/System.Security.Cryptography.Native/extra_libs.cmake)
append_extra_cryptography_libs(NATIVE_LIBS)
set(RUNTIMEINFO_LIB runtimeinfo)
endif()
if(CLR_CMAKE_TARGET_OSX)
LIST(APPEND NATIVE_LIBS
System.Security.Cryptography.Native.Apple-Static
)
# Additional requirements for System.Security.Cryptography.Native.Apple
include(${CLR_SRC_NATIVE_DIR}/libs/System.Security.Cryptography.Native.Apple/extra_libs.cmake)
append_extra_cryptography_apple_libs(NATIVE_LIBS)
endif()
#
# Additional requirements for coreclr
#
if(CLR_CMAKE_TARGET_OSX)
find_library(COREFOUNDATION CoreFoundation)
find_library(CORESERVICES CoreServices)
find_library(SECURITY Security)
find_library(SYSTEM System)
LIST(APPEND NATIVE_LIBS
${COREFOUNDATION}
${CORESERVICES}
${SECURITY}
${SYSTEM}
)
elseif(CLR_CMAKE_TARGET_NETBSD)
find_library(KVM kvm)
LIST(APPEND NATIVE_LIBS
${KVM}
)
elseif (CLR_CMAKE_TARGET_SUNOS)
LIST(APPEND NATIVE_LIBS
socket
)
endif(CLR_CMAKE_TARGET_OSX)
# On *BSD, we always use the libunwind that's part of the OS
if(CLR_CMAKE_TARGET_FREEBSD)
set(CLR_CMAKE_USE_SYSTEM_LIBUNWIND 1)
endif()
if(CLR_CMAKE_USE_SYSTEM_LIBUNWIND)
find_unwind_libs(UNWIND_LIBS)
LIST(APPEND NATIVE_LIBS
${UNWIND_LIBS}
)
endif()
if(CLR_CMAKE_TARGET_LINUX OR CLR_CMAKE_TARGET_FREEBSD OR CLR_CMAKE_TARGET_NETBSD OR CLR_CMAKE_TARGET_SUNOS)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -Wl,--whole-archive)
set(END_WHOLE_ARCHIVE -Wl,--no-whole-archive)
endif(CLR_CMAKE_TARGET_LINUX OR CLR_CMAKE_TARGET_FREEBSD OR CLR_CMAKE_TARGET_NETBSD OR CLR_CMAKE_TARGET_SUNOS)
if(CLR_CMAKE_TARGET_OSX)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -force_load)
set(END_WHOLE_ARCHIVE )
endif(CLR_CMAKE_TARGET_OSX)
set_property(TARGET singlefilehost PROPERTY ENABLE_EXPORTS 1)
target_link_libraries(
singlefilehost
${NATIVE_LIBS}
${START_WHOLE_ARCHIVE}
${RUNTIMEINFO_LIB}
${END_WHOLE_ARCHIVE}
)
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/hostmisc/pal.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef PAL_H
#define PAL_H
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <cstdarg>
#include <cstdint>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <algorithm>
#include <cassert>
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#define xerr std::wcerr
#define xout std::wcout
#define DIR_SEPARATOR L'\\'
#define PATH_SEPARATOR L';'
#define PATH_MAX MAX_PATH
#define _X(s) L ## s
#else
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <mutex>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#define xerr std::cerr
#define xout std::cout
#define DIR_SEPARATOR '/'
#define PATH_SEPARATOR ':'
#undef _X
#define _X(s) s
#define S_OK 0x00000000
#define E_NOTIMPL 0x80004001
#define E_FAIL 0x80004005
#define SUCCEEDED(Status) ((Status) >= 0)
#endif
// When running on a platform that is not supported in RID fallback graph (because it was unknown
// at the time the SharedFX in question was built), we need to use a reasonable fallback RID to allow
// consuming the native assets.
//
// For Windows and OSX, we will maintain the last highest RID-Platform we are known to support for them as the
// degree of compat across their respective releases is usually high.
//
// We cannot maintain the same (compat) invariant for linux and thus, we will fallback to using lowest RID-Plaform.
#if defined(TARGET_WINDOWS)
#define LIB_PREFIX
#define MAKE_LIBNAME(NAME) (_X(NAME) _X(".dll"))
#define FALLBACK_HOST_RID _X("win10")
#elif defined(TARGET_OSX)
#define LIB_PREFIX _X("lib")
#define MAKE_LIBNAME(NAME) (LIB_PREFIX _X(NAME) _X(".dylib"))
#define FALLBACK_HOST_RID _X("osx.10.12")
#else
#define LIB_PREFIX _X("lib")
#define MAKE_LIBNAME(NAME) (LIB_PREFIX _X(NAME) _X(".so"))
#if defined(TARGET_FREEBSD)
#define FALLBACK_HOST_RID _X("freebsd")
#elif defined(TARGET_ILLUMOS)
#define FALLBACK_HOST_RID _X("illumos")
#elif defined(TARGET_SUNOS)
#define FALLBACK_HOST_RID _X("solaris")
#elif defined(TARGET_LINUX_MUSL)
#define FALLBACK_HOST_RID _X("linux-musl")
#else
#define FALLBACK_HOST_RID _X("linux")
#endif
#endif
#define LIBCORECLR_FILENAME (LIB_PREFIX _X("coreclr"))
#define LIBCORECLR_NAME MAKE_LIBNAME("coreclr")
#define CORELIB_NAME _X("System.Private.CoreLib.dll")
#define LIBHOSTPOLICY_FILENAME (LIB_PREFIX _X("hostpolicy"))
#define LIBHOSTPOLICY_NAME MAKE_LIBNAME("hostpolicy")
#define LIBFXR_NAME MAKE_LIBNAME("hostfxr")
#if !defined(PATH_MAX) && !defined(_WIN32)
#define PATH_MAX 4096
#endif
namespace pal
{
#if defined(_WIN32)
#ifdef EXPORT_SHARED_API
#define SHARED_API extern "C" __declspec(dllexport)
#else
#define SHARED_API extern "C"
#endif
#define STDMETHODCALLTYPE __stdcall
typedef wchar_t char_t;
typedef std::wstring string_t;
typedef std::wstringstream stringstream_t;
// TODO: Agree on the correct encoding of the files: The PoR for now is to
// temporarily wchar for Windows and char for Unix. Current implementation
// implicitly expects the contents on both Windows and Unix as char and
// converts them to wchar in code for Windows. This line should become:
// typedef std::basic_ifstream<char_t> ifstream_t.
typedef std::basic_ifstream<char> ifstream_t;
typedef std::istreambuf_iterator<ifstream_t::char_type> istreambuf_iterator_t;
typedef std::basic_istream<char> istream_t;
typedef HRESULT hresult_t;
typedef HMODULE dll_t;
typedef FARPROC proc_t;
// Lockable object backed by CRITICAL_SECTION such that it does not pull in ConcRT.
class mutex_t
{
public:
mutex_t();
~mutex_t();
mutex_t(const mutex_t&) = delete;
mutex_t& operator=(const mutex_t&) = delete;
void lock();
void unlock();
private:
CRITICAL_SECTION _impl;
};
inline string_t exe_suffix() { return _X(".exe"); }
inline int cstrcasecmp(const char* str1, const char* str2) { return ::_stricmp(str1, str2); }
inline int strcmp(const char_t* str1, const char_t* str2) { return ::wcscmp(str1, str2); }
inline int strcasecmp(const char_t* str1, const char_t* str2) { return ::_wcsicmp(str1, str2); }
inline int strncmp(const char_t* str1, const char_t* str2, size_t len) { return ::wcsncmp(str1, str2, len); }
inline int strncasecmp(const char_t* str1, const char_t* str2, size_t len) { return ::_wcsnicmp(str1, str2, len); }
inline int pathcmp(const pal::string_t& path1, const pal::string_t& path2) { return strcasecmp(path1.c_str(), path2.c_str()); }
inline string_t to_string(int value) { return std::to_wstring(value); }
inline size_t strlen(const char_t* str) { return ::wcslen(str); }
#pragma warning(suppress : 4996) // error C4996: '_wfopen': This function or variable may be unsafe.
inline FILE* file_open(const string_t& path, const char_t* mode) { return ::_wfopen(path.c_str(), mode); }
inline void file_vprintf(FILE* f, const char_t* format, va_list vl) { ::vfwprintf(f, format, vl); ::fputwc(_X('\n'), f); }
inline void err_fputs(const char_t* message) { ::fputws(message, stderr); ::fputwc(_X('\n'), stderr); }
inline void out_vprintf(const char_t* format, va_list vl) { ::vfwprintf(stdout, format, vl); ::fputwc(_X('\n'), stdout); }
// This API is being used correctly and querying for needed size first.
#pragma warning(suppress : 4996) // error C4996: '_vsnwprintf': This function or variable may be unsafe.
inline int str_vprintf(char_t* buffer, size_t count, const char_t* format, va_list vl) { return ::_vsnwprintf(buffer, count, format, vl); }
// Suppressing warning since the 'safe' version requires an input buffer that is unnecessary for
// uses of this function.
#pragma warning(suppress : 4996) // error C4996: '_wcserror': This function or variable may be unsafe.
inline const char_t* strerror(int errnum) { return ::_wcserror(errnum); }
bool pal_utf8string(const string_t& str, std::vector<char>* out);
bool pal_clrstring(const string_t& str, std::vector<char>* out);
bool clr_palstring(const char* cstr, string_t* out);
inline bool mkdir(const char_t* dir, int mode) { return CreateDirectoryW(dir, NULL) != 0; }
inline bool rmdir(const char_t* path) { return RemoveDirectoryW(path) != 0; }
inline int rename(const char_t* old_name, const char_t* new_name) { return ::_wrename(old_name, new_name); }
inline int remove(const char_t* path) { return ::_wremove(path); }
inline bool munmap(void* addr, size_t length) { return UnmapViewOfFile(addr) != 0; }
inline int get_pid() { return GetCurrentProcessId(); }
inline void sleep(uint32_t milliseconds) { Sleep(milliseconds); }
#else
#ifdef EXPORT_SHARED_API
#define SHARED_API extern "C" __attribute__((__visibility__("default")))
#else
#define SHARED_API extern "C"
#endif
#define __cdecl /* nothing */
#define __stdcall /* nothing */
#if !defined(TARGET_FREEBSD)
#define __fastcall /* nothing */
#endif
#define STDMETHODCALLTYPE __stdcall
typedef char char_t;
typedef std::string string_t;
typedef std::stringstream stringstream_t;
typedef std::basic_ifstream<char> ifstream_t;
typedef std::istreambuf_iterator<ifstream_t::char_type> istreambuf_iterator_t;
typedef std::basic_istream<char> istream_t;
typedef int hresult_t;
typedef void* dll_t;
typedef void* proc_t;
typedef std::mutex mutex_t;
inline string_t exe_suffix() { return _X(""); }
inline int cstrcasecmp(const char* str1, const char* str2) { return ::strcasecmp(str1, str2); }
inline int strcmp(const char_t* str1, const char_t* str2) { return ::strcmp(str1, str2); }
inline int strcasecmp(const char_t* str1, const char_t* str2) { return ::strcasecmp(str1, str2); }
inline int strncmp(const char_t* str1, const char_t* str2, int len) { return ::strncmp(str1, str2, len); }
inline int strncasecmp(const char_t* str1, const char_t* str2, int len) { return ::strncasecmp(str1, str2, len); }
inline int pathcmp(const pal::string_t& path1, const pal::string_t& path2) { return strcmp(path1.c_str(), path2.c_str()); }
inline string_t to_string(int value) { return std::to_string(value); }
inline size_t strlen(const char_t* str) { return ::strlen(str); }
inline FILE* file_open(const string_t& path, const char_t* mode) { return fopen(path.c_str(), mode); }
inline void file_vprintf(FILE* f, const char_t* format, va_list vl) { ::vfprintf(f, format, vl); ::fputc('\n', f); }
inline void err_fputs(const char_t* message) { ::fputs(message, stderr); ::fputc(_X('\n'), stderr); }
inline void out_vprintf(const char_t* format, va_list vl) { ::vfprintf(stdout, format, vl); ::fputc('\n', stdout); }
inline int str_vprintf(char_t* str, size_t size, const char_t* format, va_list vl) { return ::vsnprintf(str, size, format, vl); }
inline const char_t* strerror(int errnum) { return ::strerror(errnum); }
inline bool pal_utf8string(const string_t& str, std::vector<char>* out) { out->assign(str.begin(), str.end()); out->push_back('\0'); return true; }
inline bool pal_clrstring(const string_t& str, std::vector<char>* out) { return pal_utf8string(str, out); }
inline bool clr_palstring(const char* cstr, string_t* out) { out->assign(cstr); return true; }
inline bool mkdir(const char_t* dir, int mode) { return ::mkdir(dir, mode) == 0; }
inline bool rmdir(const char_t* path) { return ::rmdir(path) == 0; }
inline int rename(const char_t* old_name, const char_t* new_name) { return ::rename(old_name, new_name); }
inline int remove(const char_t* path) { return ::remove(path); }
inline bool munmap(void* addr, size_t length) { return ::munmap(addr, length) == 0; }
inline int get_pid() { return getpid(); }
inline void sleep(uint32_t milliseconds) { usleep(milliseconds * 1000); }
#endif
inline int snwprintf(char_t* buffer, size_t count, const char_t* format, ...)
{
va_list args;
va_start(args, format);
int ret = str_vprintf(buffer, count, format, args);
va_end(args);
return ret;
}
string_t get_timestamp();
bool getcwd(string_t* recv);
inline void file_flush(FILE* f) { std::fflush(f); }
inline void err_flush() { std::fflush(stderr); }
inline void out_flush() { std::fflush(stdout); }
string_t get_current_os_rid_platform();
inline string_t get_current_os_fallback_rid()
{
string_t fallbackRid(FALLBACK_HOST_RID);
return fallbackRid;
}
const void* mmap_read(const string_t& path, size_t* length = nullptr);
void* mmap_copy_on_write(const string_t& path, size_t* length = nullptr);
bool touch_file(const string_t& path);
bool realpath(string_t* path, bool skip_error_logging = false);
bool file_exists(const string_t& path);
inline bool directory_exists(const string_t& path) { return file_exists(path); }
void readdir(const string_t& path, const string_t& pattern, std::vector<string_t>* list);
void readdir(const string_t& path, std::vector<string_t>* list);
void readdir_onlydirectories(const string_t& path, const string_t& pattern, std::vector<string_t>* list);
void readdir_onlydirectories(const string_t& path, std::vector<string_t>* list);
bool get_own_executable_path(string_t* recv);
bool get_own_module_path(string_t* recv);
bool get_method_module_path(string_t* recv, void* method);
bool get_module_path(dll_t mod, string_t* recv);
bool get_current_module(dll_t* mod);
bool getenv(const char_t* name, string_t* recv);
bool get_default_servicing_directory(string_t* recv);
// Returns the globally registered install location (if any)
bool get_dotnet_self_registered_dir(string_t* recv);
// Returns name of the global registry location (for error messages)
string_t get_dotnet_self_registered_config_location();
// Returns the default install location for a given platform
bool get_default_installation_dir(string_t* recv);
// Returns the global locations to search for SDK/Frameworks - used when multi-level lookup is enabled
bool get_global_dotnet_dirs(std::vector<string_t>* recv);
bool get_default_breadcrumb_store(string_t* recv);
bool is_path_rooted(const string_t& path);
// Returns a platform-specific, user-private directory
// that can be used for extracting out components of a single-file app.
bool get_default_bundle_extraction_base_dir(string_t& extraction_dir);
int xtoi(const char_t* input);
bool get_loaded_library(const char_t* library_name, const char* symbol_name, /*out*/ dll_t* dll, /*out*/ string_t* path);
bool load_library(const string_t* path, dll_t* dll);
proc_t get_symbol(dll_t library, const char* name);
void unload_library(dll_t library);
bool is_running_in_wow64();
bool is_emulating_x64();
bool are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2);
}
#endif // PAL_H
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef PAL_H
#define PAL_H
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstring>
#include <cstdarg>
#include <cstdint>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <memory>
#include <algorithm>
#include <cassert>
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#define xerr std::wcerr
#define xout std::wcout
#define DIR_SEPARATOR L'\\'
#define PATH_SEPARATOR L';'
#define PATH_MAX MAX_PATH
#define _X(s) L ## s
#else
#include <cstdlib>
#include <unistd.h>
#include <libgen.h>
#include <mutex>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#define xerr std::cerr
#define xout std::cout
#define DIR_SEPARATOR '/'
#define PATH_SEPARATOR ':'
#undef _X
#define _X(s) s
#define S_OK 0x00000000
#define E_NOTIMPL 0x80004001
#define E_FAIL 0x80004005
#define SUCCEEDED(Status) ((Status) >= 0)
#endif
// When running on a platform that is not supported in RID fallback graph (because it was unknown
// at the time the SharedFX in question was built), we need to use a reasonable fallback RID to allow
// consuming the native assets.
//
// For Windows and OSX, we will maintain the last highest RID-Platform we are known to support for them as the
// degree of compat across their respective releases is usually high.
//
// We cannot maintain the same (compat) invariant for linux and thus, we will fallback to using lowest RID-Plaform.
#if defined(TARGET_WINDOWS)
#define LIB_PREFIX
#define MAKE_LIBNAME(NAME) (_X(NAME) _X(".dll"))
#define FALLBACK_HOST_RID _X("win10")
#elif defined(TARGET_OSX)
#define LIB_PREFIX _X("lib")
#define MAKE_LIBNAME(NAME) (LIB_PREFIX _X(NAME) _X(".dylib"))
#define FALLBACK_HOST_RID _X("osx.10.12")
#else
#define LIB_PREFIX _X("lib")
#define MAKE_LIBNAME(NAME) (LIB_PREFIX _X(NAME) _X(".so"))
#if defined(TARGET_FREEBSD)
#define FALLBACK_HOST_RID _X("freebsd")
#elif defined(TARGET_ILLUMOS)
#define FALLBACK_HOST_RID _X("illumos")
#elif defined(TARGET_SUNOS)
#define FALLBACK_HOST_RID _X("solaris")
#elif defined(TARGET_LINUX_MUSL)
#define FALLBACK_HOST_RID _X("linux-musl")
#else
#define FALLBACK_HOST_RID _X("linux")
#endif
#endif
#define LIBCORECLR_FILENAME (LIB_PREFIX _X("coreclr"))
#define LIBCORECLR_NAME MAKE_LIBNAME("coreclr")
#define CORELIB_NAME _X("System.Private.CoreLib.dll")
#define LIBHOSTPOLICY_FILENAME (LIB_PREFIX _X("hostpolicy"))
#define LIBHOSTPOLICY_NAME MAKE_LIBNAME("hostpolicy")
#define LIBFXR_NAME MAKE_LIBNAME("hostfxr")
#if !defined(PATH_MAX) && !defined(_WIN32)
#define PATH_MAX 4096
#endif
namespace pal
{
#if defined(_WIN32)
#ifdef EXPORT_SHARED_API
#define SHARED_API extern "C" __declspec(dllexport)
#else
#define SHARED_API extern "C"
#endif
#define STDMETHODCALLTYPE __stdcall
typedef wchar_t char_t;
typedef std::wstring string_t;
typedef std::wstringstream stringstream_t;
// TODO: Agree on the correct encoding of the files: The PoR for now is to
// temporarily wchar for Windows and char for Unix. Current implementation
// implicitly expects the contents on both Windows and Unix as char and
// converts them to wchar in code for Windows. This line should become:
// typedef std::basic_ifstream<char_t> ifstream_t.
typedef std::basic_ifstream<char> ifstream_t;
typedef std::istreambuf_iterator<ifstream_t::char_type> istreambuf_iterator_t;
typedef std::basic_istream<char> istream_t;
typedef HRESULT hresult_t;
typedef HMODULE dll_t;
typedef FARPROC proc_t;
// Lockable object backed by CRITICAL_SECTION such that it does not pull in ConcRT.
class mutex_t
{
public:
mutex_t();
~mutex_t();
mutex_t(const mutex_t&) = delete;
mutex_t& operator=(const mutex_t&) = delete;
void lock();
void unlock();
private:
CRITICAL_SECTION _impl;
};
inline string_t exe_suffix() { return _X(".exe"); }
inline int cstrcasecmp(const char* str1, const char* str2) { return ::_stricmp(str1, str2); }
inline int strcmp(const char_t* str1, const char_t* str2) { return ::wcscmp(str1, str2); }
inline int strcasecmp(const char_t* str1, const char_t* str2) { return ::_wcsicmp(str1, str2); }
inline int strncmp(const char_t* str1, const char_t* str2, size_t len) { return ::wcsncmp(str1, str2, len); }
inline int strncasecmp(const char_t* str1, const char_t* str2, size_t len) { return ::_wcsnicmp(str1, str2, len); }
inline int pathcmp(const pal::string_t& path1, const pal::string_t& path2) { return strcasecmp(path1.c_str(), path2.c_str()); }
inline string_t to_string(int value) { return std::to_wstring(value); }
inline size_t strlen(const char_t* str) { return ::wcslen(str); }
inline FILE* file_open(const string_t& path, const char_t* mode) { return ::_wfsopen(path.c_str(), mode, _SH_DENYNO); }
inline void file_vprintf(FILE* f, const char_t* format, va_list vl) { ::vfwprintf(f, format, vl); ::fputwc(_X('\n'), f); }
inline void err_fputs(const char_t* message) { ::fputws(message, stderr); ::fputwc(_X('\n'), stderr); }
inline void out_vprintf(const char_t* format, va_list vl) { ::vfwprintf(stdout, format, vl); ::fputwc(_X('\n'), stdout); }
inline int str_vprintf(char_t* buffer, size_t count, const char_t* format, va_list vl) { return ::_vsnwprintf_s(buffer, count, _TRUNCATE, format, vl); }
inline int strlen_vprintf(const char_t* format, va_list vl) { return ::_vscwprintf(format, vl); }
inline const string_t strerror(int errnum)
{
// Windows does not provide strerrorlen to get the actual error length.
// Use 1024 as the buffer size based on the buffer size used by glibc.
// _wcserror_s truncates (and null-terminates) if the buffer is too small
char_t buffer[1024];
::_wcserror_s(buffer, sizeof(buffer) / sizeof(char_t), errnum);
return buffer;
}
bool pal_utf8string(const string_t& str, std::vector<char>* out);
bool pal_clrstring(const string_t& str, std::vector<char>* out);
bool clr_palstring(const char* cstr, string_t* out);
inline bool mkdir(const char_t* dir, int mode) { return CreateDirectoryW(dir, NULL) != 0; }
inline bool rmdir(const char_t* path) { return RemoveDirectoryW(path) != 0; }
inline int rename(const char_t* old_name, const char_t* new_name) { return ::_wrename(old_name, new_name); }
inline int remove(const char_t* path) { return ::_wremove(path); }
inline bool munmap(void* addr, size_t length) { return UnmapViewOfFile(addr) != 0; }
inline int get_pid() { return GetCurrentProcessId(); }
inline void sleep(uint32_t milliseconds) { Sleep(milliseconds); }
#else
#ifdef EXPORT_SHARED_API
#define SHARED_API extern "C" __attribute__((__visibility__("default")))
#else
#define SHARED_API extern "C"
#endif
#define __cdecl /* nothing */
#define __stdcall /* nothing */
#if !defined(TARGET_FREEBSD)
#define __fastcall /* nothing */
#endif
#define STDMETHODCALLTYPE __stdcall
typedef char char_t;
typedef std::string string_t;
typedef std::stringstream stringstream_t;
typedef std::basic_ifstream<char> ifstream_t;
typedef std::istreambuf_iterator<ifstream_t::char_type> istreambuf_iterator_t;
typedef std::basic_istream<char> istream_t;
typedef int hresult_t;
typedef void* dll_t;
typedef void* proc_t;
typedef std::mutex mutex_t;
inline string_t exe_suffix() { return _X(""); }
inline int cstrcasecmp(const char* str1, const char* str2) { return ::strcasecmp(str1, str2); }
inline int strcmp(const char_t* str1, const char_t* str2) { return ::strcmp(str1, str2); }
inline int strcasecmp(const char_t* str1, const char_t* str2) { return ::strcasecmp(str1, str2); }
inline int strncmp(const char_t* str1, const char_t* str2, int len) { return ::strncmp(str1, str2, len); }
inline int strncasecmp(const char_t* str1, const char_t* str2, int len) { return ::strncasecmp(str1, str2, len); }
inline int pathcmp(const pal::string_t& path1, const pal::string_t& path2) { return strcmp(path1.c_str(), path2.c_str()); }
inline string_t to_string(int value) { return std::to_string(value); }
inline size_t strlen(const char_t* str) { return ::strlen(str); }
inline FILE* file_open(const string_t& path, const char_t* mode) { return fopen(path.c_str(), mode); }
inline void file_vprintf(FILE* f, const char_t* format, va_list vl) { ::vfprintf(f, format, vl); ::fputc('\n', f); }
inline void err_fputs(const char_t* message) { ::fputs(message, stderr); ::fputc(_X('\n'), stderr); }
inline void out_vprintf(const char_t* format, va_list vl) { ::vfprintf(stdout, format, vl); ::fputc('\n', stdout); }
inline int str_vprintf(char_t* str, size_t size, const char_t* format, va_list vl) { return ::vsnprintf(str, size, format, vl); }
inline int strlen_vprintf(const char_t* format, va_list vl) { return ::vsnprintf(nullptr, 0, format, vl); }
inline const string_t strerror(int errnum) { return ::strerror(errnum); }
inline bool pal_utf8string(const string_t& str, std::vector<char>* out) { out->assign(str.begin(), str.end()); out->push_back('\0'); return true; }
inline bool pal_clrstring(const string_t& str, std::vector<char>* out) { return pal_utf8string(str, out); }
inline bool clr_palstring(const char* cstr, string_t* out) { out->assign(cstr); return true; }
inline bool mkdir(const char_t* dir, int mode) { return ::mkdir(dir, mode) == 0; }
inline bool rmdir(const char_t* path) { return ::rmdir(path) == 0; }
inline int rename(const char_t* old_name, const char_t* new_name) { return ::rename(old_name, new_name); }
inline int remove(const char_t* path) { return ::remove(path); }
inline bool munmap(void* addr, size_t length) { return ::munmap(addr, length) == 0; }
inline int get_pid() { return getpid(); }
inline void sleep(uint32_t milliseconds) { usleep(milliseconds * 1000); }
#endif
inline int snwprintf(char_t* buffer, size_t count, const char_t* format, ...)
{
va_list args;
va_start(args, format);
int ret = str_vprintf(buffer, count, format, args);
va_end(args);
return ret;
}
string_t get_timestamp();
bool getcwd(string_t* recv);
inline void file_flush(FILE* f) { std::fflush(f); }
inline void err_flush() { std::fflush(stderr); }
inline void out_flush() { std::fflush(stdout); }
string_t get_current_os_rid_platform();
inline string_t get_current_os_fallback_rid()
{
string_t fallbackRid(FALLBACK_HOST_RID);
return fallbackRid;
}
const void* mmap_read(const string_t& path, size_t* length = nullptr);
void* mmap_copy_on_write(const string_t& path, size_t* length = nullptr);
bool touch_file(const string_t& path);
bool realpath(string_t* path, bool skip_error_logging = false);
bool file_exists(const string_t& path);
inline bool directory_exists(const string_t& path) { return file_exists(path); }
void readdir(const string_t& path, const string_t& pattern, std::vector<string_t>* list);
void readdir(const string_t& path, std::vector<string_t>* list);
void readdir_onlydirectories(const string_t& path, const string_t& pattern, std::vector<string_t>* list);
void readdir_onlydirectories(const string_t& path, std::vector<string_t>* list);
bool get_own_executable_path(string_t* recv);
bool get_own_module_path(string_t* recv);
bool get_method_module_path(string_t* recv, void* method);
bool get_module_path(dll_t mod, string_t* recv);
bool get_current_module(dll_t* mod);
bool getenv(const char_t* name, string_t* recv);
bool get_default_servicing_directory(string_t* recv);
// Returns the globally registered install location (if any)
bool get_dotnet_self_registered_dir(string_t* recv);
// Returns name of the global registry location (for error messages)
string_t get_dotnet_self_registered_config_location();
// Returns the default install location for a given platform
bool get_default_installation_dir(string_t* recv);
// Returns the global locations to search for SDK/Frameworks - used when multi-level lookup is enabled
bool get_global_dotnet_dirs(std::vector<string_t>* recv);
bool get_default_breadcrumb_store(string_t* recv);
bool is_path_rooted(const string_t& path);
// Returns a platform-specific, user-private directory
// that can be used for extracting out components of a single-file app.
bool get_default_bundle_extraction_base_dir(string_t& extraction_dir);
int xtoi(const char_t* input);
bool get_loaded_library(const char_t* library_name, const char* symbol_name, /*out*/ dll_t* dll, /*out*/ string_t* path);
bool load_library(const string_t* path, dll_t* dll);
proc_t get_symbol(dll_t library, const char* name);
void unload_library(dll_t library);
bool is_running_in_wow64();
bool is_emulating_x64();
bool are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2);
}
#endif // PAL_H
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/hostmisc/pal.unix.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if defined(TARGET_FREEBSD)
#define _WITH_GETLINE
#endif
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <cassert>
#include <dlfcn.h>
#include <dirent.h>
#include <pwd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <ctime>
#include <locale>
#include <pwd.h>
#include "config.h"
#include <minipal/getexepath.h>
#if defined(TARGET_OSX)
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#elif defined(__sun)
#include <sys/utsname.h>
#elif defined(TARGET_FREEBSD)
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#endif
#if !HAVE_DIRENT_D_TYPE
#define DT_UNKNOWN 0
#define DT_DIR 4
#define DT_REG 8
#define DT_LNK 10
#endif
#ifdef __linux__
#define PAL_CWD_SIZE 0
#elif defined(MAXPATHLEN)
#define PAL_CWD_SIZE MAXPATHLEN
#elif defined(PATH_MAX)
#define PAL_CWD_SIZE PATH_MAX
#else
#error "Don't know how to obtain max path on this platform"
#endif
pal::string_t pal::get_timestamp()
{
std::time_t t = std::time(nullptr);
const std::size_t elems = 100;
char_t buf[elems];
std::strftime(buf, elems, _X("%c %Z"), std::gmtime(&t));
return pal::string_t(buf);
}
bool pal::touch_file(const pal::string_t& path)
{
int fd = open(path.c_str(), (O_CREAT | O_EXCL), (S_IRUSR | S_IRGRP | S_IROTH));
if (fd == -1)
{
trace::warning(_X("open(%s) failed in %s"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
(void)close(fd);
return true;
}
static void* map_file(const pal::string_t& path, size_t* length, int prot, int flags)
{
int fd = open(path.c_str(), O_RDONLY);
if (fd == -1)
{
trace::error(_X("Failed to map file. open(%s) failed with error %d"), path.c_str(), errno);
return nullptr;
}
struct stat buf;
if (fstat(fd, &buf) != 0)
{
trace::error(_X("Failed to map file. fstat(%s) failed with error %d"), path.c_str(), errno);
close(fd);
return nullptr;
}
size_t size = buf.st_size;
if (length != nullptr)
{
*length = size;
}
void* address = mmap(nullptr, size, prot, flags, fd, 0);
if (address == MAP_FAILED)
{
trace::error(_X("Failed to map file. mmap(%s) failed with error %d"), path.c_str(), errno);
address = nullptr;
}
close(fd);
return address;
}
const void* pal::mmap_read(const string_t& path, size_t* length)
{
return map_file(path, length, PROT_READ, MAP_SHARED);
}
void* pal::mmap_copy_on_write(const string_t& path, size_t* length)
{
return map_file(path, length, PROT_READ | PROT_WRITE, MAP_PRIVATE);
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t* buf = ::getcwd(nullptr, PAL_CWD_SIZE);
if (buf == nullptr)
{
if (errno == ENOENT)
{
return false;
}
trace::error(_X("getcwd() failed: %s"), strerror(errno));
return false;
}
recv->assign(buf);
::free(buf);
return true;
}
namespace
{
bool get_loaded_library_from_proc_maps(const pal::char_t* library_name, pal::dll_t* dll, pal::string_t* path)
{
char* line = nullptr;
size_t lineLen = 0;
ssize_t read;
FILE* file = pal::file_open(_X("/proc/self/maps"), _X("r"));
if (file == nullptr)
return false;
// Read maps file line by line to check fo the library
bool found = false;
pal::string_t path_local;
while ((read = getline(&line, &lineLen, file)) != -1)
{
char buf[PATH_MAX];
if (sscanf(line, "%*p-%*p %*[-rwxsp] %*p %*[:0-9a-f] %*d %s\n", buf) == 1)
{
path_local = buf;
size_t pos = path_local.rfind(DIR_SEPARATOR);
if (pos == std::string::npos)
continue;
pos = path_local.find(library_name, pos);
if (pos != std::string::npos)
{
found = true;
break;
}
}
}
fclose(file);
if (!found)
return false;
pal::dll_t dll_maybe = dlopen(path_local.c_str(), RTLD_LAZY | RTLD_NOLOAD);
if (dll_maybe == nullptr)
return false;
*dll = dll_maybe;
path->assign(path_local);
return true;
}
}
bool pal::get_loaded_library(
const char_t* library_name,
const char* symbol_name,
/*out*/ dll_t* dll,
/*out*/ pal::string_t* path)
{
pal::string_t library_name_local;
#if defined(TARGET_OSX)
if (!pal::is_path_rooted(library_name))
library_name_local.append("@rpath/");
#endif
library_name_local.append(library_name);
dll_t dll_maybe = dlopen(library_name_local.c_str(), RTLD_LAZY | RTLD_NOLOAD);
if (dll_maybe == nullptr)
{
if (pal::is_path_rooted(library_name))
return false;
// dlopen on some systems only finds loaded libraries when given the full path
// Check proc maps as a fallback
return get_loaded_library_from_proc_maps(library_name, dll, path);
}
// Not all systems support getting the path from just the handle (e.g. dlinfo),
// so we rely on the caller passing in a symbol name so that we get (any) address
// in the library
assert(symbol_name != nullptr);
pal::proc_t proc = pal::get_symbol(dll_maybe, symbol_name);
Dl_info info;
if (dladdr(proc, &info) == 0)
{
dlclose(dll_maybe);
return false;
}
*dll = dll_maybe;
path->assign(info.dli_fname);
return true;
}
bool pal::load_library(const string_t* path, dll_t* dll)
{
*dll = dlopen(path->c_str(), RTLD_LAZY);
if (*dll == nullptr)
{
trace::error(_X("Failed to load %s, error: %s"), path->c_str(), dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::info(_X("Probed for and did not find library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("Failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_BREADCRUMBS"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_BREADCRUMBS [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core breadcrumbs [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("corebreadcrumbs"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core breadcrumbs at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), (R_OK | W_OK)) != 0)
{
trace::info(_X("Breadcrumb store [%s] is not ACL-ed with rw-"), ext.c_str());
}
recv->assign(ext);
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_SERVICING"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_SERVICING [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core servicing at [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("coreservicing"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core servicing at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), R_OK) != 0)
{
trace::info(_X("Directory core servicing at [%s] was not ACL-ed properly"), ext.c_str());
}
recv->assign(ext);
trace::info(_X("Using core servicing at [%s]"), ext.c_str());
return true;
}
bool is_read_write_able_directory(pal::string_t& dir)
{
return pal::realpath(&dir) &&
(access(dir.c_str(), R_OK | W_OK | X_OK) == 0);
}
bool get_extraction_base_parent_directory(pal::string_t& directory)
{
// check for the POSIX standard environment variable
if (pal::getenv(_X("HOME"), &directory))
{
if (is_read_write_able_directory(directory))
{
return true;
}
else
{
trace::error(_X("Default extraction directory [%s] either doesn't exist or is not accessible for read/write."), directory.c_str());
}
}
else
{
// fallback to the POSIX standard getpwuid() library function
struct passwd* pwuid = NULL;
errno = 0;
do
{
pwuid = getpwuid(getuid());
} while (pwuid == NULL && errno == EINTR);
if (pwuid != NULL)
{
directory.assign(pwuid->pw_dir);
if (is_read_write_able_directory(directory))
{
return true;
}
else
{
trace::error(_X("Failed to determine default extraction location. Environment variable '$HOME' is not defined and directory reported by getpwuid() [%s] either doesn't exist or is not accessible for read/write."), pwuid->pw_dir);
}
}
else
{
trace::error(_X("Failed to determine default extraction location. Environment variable '$HOME' is not defined and getpwuid() returned NULL."));
}
}
return false;
}
bool pal::get_default_bundle_extraction_base_dir(pal::string_t& extraction_dir)
{
if (!get_extraction_base_parent_directory(extraction_dir))
{
return false;
}
append_path(&extraction_dir, _X(".net"));
if (is_read_write_able_directory(extraction_dir))
{
return true;
}
// Create $HOME/.net with rwx access to the owner
if (::mkdir(extraction_dir.c_str(), S_IRWXU) == 0)
{
return true;
}
else if (errno != EEXIST)
{
trace::error(_X("Failed to create default extraction directory [%s]. %s"), extraction_dir.c_str(), pal::strerror(errno));
return false;
}
return is_read_write_able_directory(extraction_dir);
}
bool pal::get_global_dotnet_dirs(std::vector<pal::string_t>* recv)
{
// No support for global directories in Unix.
return false;
}
pal::string_t pal::get_dotnet_self_registered_config_location()
{
// ***Used only for testing***
pal::string_t environment_install_location_override;
if (test_only_getenv(_X("_DOTNET_TEST_INSTALL_LOCATION_PATH"), &environment_install_location_override))
{
return environment_install_location_override;
}
return _X("/etc/dotnet");
}
namespace
{
bool get_line_from_file(FILE* pFile, pal::string_t& line)
{
line = pal::string_t();
char buffer[256];
while (fgets(buffer, sizeof(buffer), pFile))
{
line += (pal::char_t*)buffer;
size_t len = line.length();
// fgets includes the newline character in the string - so remove it.
if (len > 0 && line[len - 1] == '\n')
{
line.pop_back();
break;
}
}
return !line.empty();
}
}
bool get_install_location_from_file(const pal::string_t& file_path, bool& file_found, pal::string_t& install_location)
{
file_found = true;
bool install_location_found = false;
FILE* install_location_file = pal::file_open(file_path, "r");
if (install_location_file != nullptr)
{
if (!get_line_from_file(install_location_file, install_location))
{
trace::warning(_X("Did not find any install location in '%s'."), file_path.c_str());
}
else
{
install_location_found = true;
}
fclose(install_location_file);
if (install_location_found)
return true;
}
else
{
if (errno == ENOENT)
{
trace::verbose(_X("The install_location file ['%s'] does not exist - skipping."), file_path.c_str());
file_found = false;
}
else
{
trace::error(_X("The install_location file ['%s'] failed to open: %s."), file_path.c_str(), pal::strerror(errno));
}
}
return false;
}
bool pal::get_dotnet_self_registered_dir(pal::string_t* recv)
{
recv->clear();
// ***Used only for testing***
pal::string_t environment_override;
if (test_only_getenv(_X("_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"), &environment_override))
{
recv->assign(environment_override);
return true;
}
// ***************************
pal::string_t install_location_path = get_dotnet_self_registered_config_location();
pal::string_t arch_specific_install_location_file_path = install_location_path;
append_path(&arch_specific_install_location_file_path, (_X("install_location_") + to_lower(get_arch())).c_str());
trace::verbose(_X("Looking for architecture specific install_location file in '%s'."), arch_specific_install_location_file_path.c_str());
pal::string_t install_location;
bool file_found = false;
if (!get_install_location_from_file(arch_specific_install_location_file_path, file_found, install_location))
{
if (file_found)
{
return false;
}
pal::string_t legacy_install_location_file_path = install_location_path;
append_path(&legacy_install_location_file_path, _X("install_location"));
trace::verbose(_X("Looking for install_location file in '%s'."), legacy_install_location_file_path.c_str());
if (!get_install_location_from_file(legacy_install_location_file_path, file_found, install_location))
{
return false;
}
}
recv->assign(install_location);
trace::verbose(_X("Using install location '%s'."), recv->c_str());
return true;
}
bool pal::get_default_installation_dir(pal::string_t* recv)
{
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_DEFAULT_INSTALL_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
#if defined(TARGET_OSX)
recv->assign(_X("/usr/local/share/dotnet"));
if (pal::is_emulating_x64())
{
append_path(recv, _X("x64"));
}
#else
recv->assign(_X("/usr/share/dotnet"));
#endif
return true;
}
pal::string_t trim_quotes(pal::string_t stringToCleanup)
{
pal::char_t quote_array[2] = { '\"', '\'' };
for (size_t index = 0; index < sizeof(quote_array) / sizeof(quote_array[0]); index++)
{
size_t pos = stringToCleanup.find(quote_array[index]);
while (pos != std::string::npos)
{
stringToCleanup = stringToCleanup.erase(pos, 1);
pos = stringToCleanup.find(quote_array[index]);
}
}
return stringToCleanup;
}
#if defined(TARGET_OSX)
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
size_t size = sizeof(str);
// returns something like 10.5.2 or 11.6
int ret = sysctlbyname("kern.osproductversion", str, &size, nullptr, 0);
if (ret == 0)
{
// the value _should_ be null terminated but let's make sure
str[size - 1] = 0;
char* pos = strchr(str, '.');
if (pos != NULL)
{
int major = atoi(str);
if (major > 11)
{
// starting with 12.0 we track only major release
*pos = 0;
}
else if (major == 11)
{
// for 11.x we publish RID as 11.0
// if we return anything else, it would break the RID graph processing
strcpy(str, "11.0");
}
else
{
// for 10.x the significant releases are actually the second digit
pos = strchr(pos + 1, '.');
if (pos != NULL)
{
// strip anything after second dot and return something like 10.5
*pos = 0;
}
}
}
std::string release(str, strlen(str));
ridOS.append(_X("osx."));
ridOS.append(release);
}
return ridOS;
}
#elif defined(TARGET_FREEBSD)
// On FreeBSD get major verion. Minors should be compatible
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
if (ret == 0)
{
char* pos = strchr(str, '.');
if (pos)
{
ridOS.append(_X("freebsd."))
.append(str, pos - str);
}
}
return ridOS;
}
#elif defined(TARGET_ILLUMOS)
pal::string_t pal::get_current_os_rid_platform()
{
// Code:
// struct utsname u;
// if (uname(&u) != -1)
// printf("sysname: %s, release: %s, version: %s, machine: %s\n", u.sysname, u.release, u.version, u.machine);
//
// Output examples:
// on OmniOS
// sysname: SunOS, release: 5.11, version: omnios-r151018-95eaa7e, machine: i86pc
// on OpenIndiana Hipster:
// sysname: SunOS, release: 5.11, version: illumos-63878f749f, machine: i86pc
// on SmartOS:
// sysname: SunOS, release: 5.11, version: joyent_20200408T231825Z, machine: i86pc
pal::string_t ridOS;
struct utsname utsname_obj;
if (uname(&utsname_obj) < 0)
{
return ridOS;
}
if (strncmp(utsname_obj.version, "omnios", strlen("omnios")) == 0)
{
ridOS.append(_X("omnios."))
.append(utsname_obj.version, strlen("omnios-r"), 2); // e.g. omnios.15
}
else if (strncmp(utsname_obj.version, "illumos-", strlen("illumos-")) == 0)
{
ridOS.append(_X("openindiana")); // version-less
}
else if (strncmp(utsname_obj.version, "joyent_", strlen("joyent_")) == 0)
{
ridOS.append(_X("smartos."))
.append(utsname_obj.version, strlen("joyent_"), 4); // e.g. smartos.2020
}
return ridOS;
}
#elif defined(__sun)
pal::string_t pal::get_current_os_rid_platform()
{
// Code:
// struct utsname u;
// if (uname(&u) != -1)
// printf("sysname: %s, release: %s, version: %s, machine: %s\n", u.sysname, u.release, u.version, u.machine);
//
// Output example on Solaris 11:
// sysname: SunOS, release: 5.11, version: 11.3, machine: i86pc
pal::string_t ridOS;
struct utsname utsname_obj;
if (uname(&utsname_obj) < 0)
{
return ridOS;
}
char* pos = strchr(utsname_obj.version, '.');
if (pos)
{
ridOS.append(_X("solaris."))
.append(utsname_obj.version, pos - utsname_obj.version); // e.g. solaris.11
}
return ridOS;
}
#else
// For some distros, we don't want to use the full version from VERSION_ID. One example is
// Red Hat Enterprise Linux, which includes a minor version in their VERSION_ID but minor
// versions are backwards compatable.
//
// In this case, we'll normalized RIDs like 'rhel.7.2' and 'rhel.7.3' to a generic
// 'rhel.7'. This brings RHEL in line with other distros like CentOS or Debian which
// don't put minor version numbers in their VERSION_ID fields because all minor versions
// are backwards compatible.
static
pal::string_t normalize_linux_rid(pal::string_t rid)
{
pal::string_t rhelPrefix(_X("rhel."));
pal::string_t alpinePrefix(_X("alpine."));
pal::string_t rockyPrefix(_X("rocky."));
size_t lastVersionSeparatorIndex = std::string::npos;
if (rid.compare(0, rhelPrefix.length(), rhelPrefix) == 0)
{
lastVersionSeparatorIndex = rid.find(_X("."), rhelPrefix.length());
}
else if (rid.compare(0, alpinePrefix.length(), alpinePrefix) == 0)
{
size_t secondVersionSeparatorIndex = rid.find(_X("."), alpinePrefix.length());
if (secondVersionSeparatorIndex != std::string::npos)
{
lastVersionSeparatorIndex = rid.find(_X("."), secondVersionSeparatorIndex + 1);
}
}
else if (rid.compare(0, rockyPrefix.length(), rockyPrefix) == 0)
{
lastVersionSeparatorIndex = rid.find(_X("."), rockyPrefix.length());
}
if (lastVersionSeparatorIndex != std::string::npos)
{
rid.erase(lastVersionSeparatorIndex, rid.length() - lastVersionSeparatorIndex);
}
return rid;
}
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
pal::string_t versionFile(_X("/etc/os-release"));
if (pal::file_exists(versionFile))
{
// Read the file to get ID and VERSION_ID data that will be used
// to construct the RID.
std::fstream fsVersionFile;
fsVersionFile.open(versionFile, std::fstream::in);
// Proceed only if we were able to open the file
if (fsVersionFile.good())
{
pal::string_t line;
pal::string_t strID(_X("ID="));
pal::string_t valID;
pal::string_t strVersionID(_X("VERSION_ID="));
pal::string_t valVersionID;
bool fFoundID = false, fFoundVersion = false;
// Read the first line
std::getline(fsVersionFile, line);
// Loop until we are at the end of file
while (!fsVersionFile.eof())
{
// Look for ID if we have not found it already
if (!fFoundID)
{
size_t pos = line.find(strID);
if ((pos != std::string::npos) && (pos == 0))
{
valID.append(line.substr(3));
fFoundID = true;
}
}
// Look for VersionID if we have not found it already
if (!fFoundVersion)
{
size_t pos = line.find(strVersionID);
if ((pos != std::string::npos) && (pos == 0))
{
valVersionID.append(line.substr(11));
fFoundVersion = true;
}
}
if (fFoundID && fFoundVersion)
{
// We have everything we need to form the RID - break out of the loop.
break;
}
// Read the next line
std::getline(fsVersionFile, line);
}
// Close the file now that we are done with it.
fsVersionFile.close();
if (fFoundID)
{
ridOS.append(valID);
}
if (fFoundVersion)
{
ridOS.append(_X("."));
ridOS.append(valVersionID);
}
if (fFoundID || fFoundVersion)
{
// Remove any double-quotes
ridOS = trim_quotes(ridOS);
}
}
}
return normalize_linux_rid(ridOS);
}
#endif
bool pal::get_own_executable_path(pal::string_t* recv)
{
char* path = minipal_getexepath();
if (!path)
{
return false;
}
recv->assign(path);
free(path);
return true;
}
bool pal::get_own_module_path(string_t* recv)
{
Dl_info info;
if (dladdr((void*)&pal::get_own_module_path, &info) == 0)
return false;
recv->assign(info.dli_fname);
return true;
}
bool pal::get_method_module_path(string_t* recv, void* method)
{
Dl_info info;
if (dladdr(method, &info) == 0)
return false;
recv->assign(info.dli_fname);
return true;
}
bool pal::get_module_path(dll_t module, string_t* recv)
{
return false;
}
bool pal::get_current_module(dll_t* mod)
{
return false;
}
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const pal::char_t* name, pal::string_t* recv)
{
recv->clear();
auto result = ::getenv(name);
if (result != nullptr)
{
recv->assign(result);
}
return (recv->length() > 0);
}
bool pal::realpath(pal::string_t* path, bool skip_error_logging)
{
auto resolved = ::realpath(path->c_str(), nullptr);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
if (!skip_error_logging)
{
trace::error(_X("realpath(%s) failed: %s"), path->c_str(), strerror(errno));
}
return false;
}
path->assign(resolved);
::free(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
return (::access(path.c_str(), F_OK) == 0);
}
static void readdir(const pal::string_t& path, const pal::string_t& pattern, bool onlydirectories, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while ((entry = readdir(dir)) != nullptr)
{
if (fnmatch(pattern.c_str(), entry->d_name, FNM_PATHNAME) != 0)
{
continue;
}
#if HAVE_DIRENT_D_TYPE
int dirEntryType = entry->d_type;
#else
int dirEntryType = DT_UNKNOWN;
#endif
// We are interested in files only
switch (dirEntryType)
{
case DT_DIR:
break;
case DT_REG:
if (onlydirectories)
{
continue;
}
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
struct stat sb;
if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == -1)
{
continue;
}
if (onlydirectories)
{
if (!S_ISDIR(sb.st_mode))
{
continue;
}
break;
}
else if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
{
continue;
}
files.emplace_back(entry->d_name);
}
closedir(dir);
}
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, false, list);
}
void pal::readdir(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), false, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, true, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), true, list);
}
bool pal::is_running_in_wow64()
{
return false;
}
bool pal::is_emulating_x64()
{
int is_translated_process = 0;
#if defined(TARGET_OSX)
size_t size = sizeof(is_translated_process);
if (sysctlbyname("sysctl.proc_translated", &is_translated_process, &size, NULL, 0) == -1)
{
trace::info(_X("Could not determine whether the current process is running under Rosetta."));
if (errno != ENOENT)
{
trace::info(_X("Call to sysctlbyname failed: %s"), strerror(errno));
}
return false;
}
#endif
return is_translated_process == 1;
}
bool pal::are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2)
{
#if defined(TARGET_OSX)
// On Mac, paths are case-insensitive
return (strcasecmp(path1.c_str(), path2.c_str()) == 0);
#else
// On Linux, paths are case-sensitive
return path1 == path2;
#endif
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if defined(TARGET_FREEBSD)
#define _WITH_GETLINE
#endif
#include "pal.h"
#include "utils.h"
#include "trace.h"
#include <cassert>
#include <dlfcn.h>
#include <dirent.h>
#include <pwd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <ctime>
#include <locale>
#include <pwd.h>
#include "config.h"
#include <minipal/getexepath.h>
#if defined(TARGET_OSX)
#include <mach-o/dyld.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#elif defined(__sun)
#include <sys/utsname.h>
#elif defined(TARGET_FREEBSD)
#include <sys/types.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#endif
#if !HAVE_DIRENT_D_TYPE
#define DT_UNKNOWN 0
#define DT_DIR 4
#define DT_REG 8
#define DT_LNK 10
#endif
#ifdef __linux__
#define PAL_CWD_SIZE 0
#elif defined(MAXPATHLEN)
#define PAL_CWD_SIZE MAXPATHLEN
#elif defined(PATH_MAX)
#define PAL_CWD_SIZE PATH_MAX
#else
#error "Don't know how to obtain max path on this platform"
#endif
pal::string_t pal::get_timestamp()
{
std::time_t t = std::time(nullptr);
const std::size_t elems = 100;
char_t buf[elems];
std::strftime(buf, elems, _X("%c %Z"), std::gmtime(&t));
return pal::string_t(buf);
}
bool pal::touch_file(const pal::string_t& path)
{
int fd = open(path.c_str(), (O_CREAT | O_EXCL), (S_IRUSR | S_IRGRP | S_IROTH));
if (fd == -1)
{
trace::warning(_X("open(%s) failed in %s"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
(void)close(fd);
return true;
}
static void* map_file(const pal::string_t& path, size_t* length, int prot, int flags)
{
int fd = open(path.c_str(), O_RDONLY);
if (fd == -1)
{
trace::error(_X("Failed to map file. open(%s) failed with error %d"), path.c_str(), errno);
return nullptr;
}
struct stat buf;
if (fstat(fd, &buf) != 0)
{
trace::error(_X("Failed to map file. fstat(%s) failed with error %d"), path.c_str(), errno);
close(fd);
return nullptr;
}
size_t size = buf.st_size;
if (length != nullptr)
{
*length = size;
}
void* address = mmap(nullptr, size, prot, flags, fd, 0);
if (address == MAP_FAILED)
{
trace::error(_X("Failed to map file. mmap(%s) failed with error %d"), path.c_str(), errno);
address = nullptr;
}
close(fd);
return address;
}
const void* pal::mmap_read(const string_t& path, size_t* length)
{
return map_file(path, length, PROT_READ, MAP_SHARED);
}
void* pal::mmap_copy_on_write(const string_t& path, size_t* length)
{
return map_file(path, length, PROT_READ | PROT_WRITE, MAP_PRIVATE);
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t* buf = ::getcwd(nullptr, PAL_CWD_SIZE);
if (buf == nullptr)
{
if (errno == ENOENT)
{
return false;
}
trace::error(_X("getcwd() failed: %s"), strerror(errno).c_str());
return false;
}
recv->assign(buf);
::free(buf);
return true;
}
namespace
{
bool get_loaded_library_from_proc_maps(const pal::char_t* library_name, pal::dll_t* dll, pal::string_t* path)
{
char* line = nullptr;
size_t lineLen = 0;
ssize_t read;
FILE* file = pal::file_open(_X("/proc/self/maps"), _X("r"));
if (file == nullptr)
return false;
// Read maps file line by line to check fo the library
bool found = false;
pal::string_t path_local;
while ((read = getline(&line, &lineLen, file)) != -1)
{
char buf[PATH_MAX];
if (sscanf(line, "%*p-%*p %*[-rwxsp] %*p %*[:0-9a-f] %*d %s\n", buf) == 1)
{
path_local = buf;
size_t pos = path_local.rfind(DIR_SEPARATOR);
if (pos == std::string::npos)
continue;
pos = path_local.find(library_name, pos);
if (pos != std::string::npos)
{
found = true;
break;
}
}
}
fclose(file);
if (!found)
return false;
pal::dll_t dll_maybe = dlopen(path_local.c_str(), RTLD_LAZY | RTLD_NOLOAD);
if (dll_maybe == nullptr)
return false;
*dll = dll_maybe;
path->assign(path_local);
return true;
}
}
bool pal::get_loaded_library(
const char_t* library_name,
const char* symbol_name,
/*out*/ dll_t* dll,
/*out*/ pal::string_t* path)
{
pal::string_t library_name_local;
#if defined(TARGET_OSX)
if (!pal::is_path_rooted(library_name))
library_name_local.append("@rpath/");
#endif
library_name_local.append(library_name);
dll_t dll_maybe = dlopen(library_name_local.c_str(), RTLD_LAZY | RTLD_NOLOAD);
if (dll_maybe == nullptr)
{
if (pal::is_path_rooted(library_name))
return false;
// dlopen on some systems only finds loaded libraries when given the full path
// Check proc maps as a fallback
return get_loaded_library_from_proc_maps(library_name, dll, path);
}
// Not all systems support getting the path from just the handle (e.g. dlinfo),
// so we rely on the caller passing in a symbol name so that we get (any) address
// in the library
assert(symbol_name != nullptr);
pal::proc_t proc = pal::get_symbol(dll_maybe, symbol_name);
Dl_info info;
if (dladdr(proc, &info) == 0)
{
dlclose(dll_maybe);
return false;
}
*dll = dll_maybe;
path->assign(info.dli_fname);
return true;
}
bool pal::load_library(const string_t* path, dll_t* dll)
{
*dll = dlopen(path->c_str(), RTLD_LAZY);
if (*dll == nullptr)
{
trace::error(_X("Failed to load %s, error: %s"), path->c_str(), dlerror());
return false;
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = dlsym(library, name);
if (result == nullptr)
{
trace::info(_X("Probed for and did not find library symbol %s, error: %s"), name, dlerror());
}
return result;
}
void pal::unload_library(dll_t library)
{
if (dlclose(library) != 0)
{
trace::warning(_X("Failed to unload library, error: %s"), dlerror());
}
}
int pal::xtoi(const char_t* input)
{
return atoi(input);
}
bool pal::is_path_rooted(const pal::string_t& path)
{
return path.front() == '/';
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_BREADCRUMBS"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_BREADCRUMBS [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core breadcrumbs [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("corebreadcrumbs"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core breadcrumbs at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), (R_OK | W_OK)) != 0)
{
trace::info(_X("Breadcrumb store [%s] is not ACL-ed with rw-"), ext.c_str());
}
recv->assign(ext);
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
recv->clear();
pal::string_t ext;
if (pal::getenv(_X("CORE_SERVICING"), &ext) && pal::realpath(&ext))
{
// We should have the path in ext.
trace::info(_X("Realpath CORE_SERVICING [%s]"), ext.c_str());
}
if (!pal::directory_exists(ext))
{
trace::info(_X("Directory core servicing at [%s] was not specified or found"), ext.c_str());
ext.clear();
append_path(&ext, _X("opt"));
append_path(&ext, _X("coreservicing"));
if (!pal::directory_exists(ext))
{
trace::info(_X("Fallback directory core servicing at [%s] was not found"), ext.c_str());
return false;
}
}
if (access(ext.c_str(), R_OK) != 0)
{
trace::info(_X("Directory core servicing at [%s] was not ACL-ed properly"), ext.c_str());
}
recv->assign(ext);
trace::info(_X("Using core servicing at [%s]"), ext.c_str());
return true;
}
bool is_read_write_able_directory(pal::string_t& dir)
{
return pal::realpath(&dir) &&
(access(dir.c_str(), R_OK | W_OK | X_OK) == 0);
}
bool get_extraction_base_parent_directory(pal::string_t& directory)
{
// check for the POSIX standard environment variable
if (pal::getenv(_X("HOME"), &directory))
{
if (is_read_write_able_directory(directory))
{
return true;
}
else
{
trace::error(_X("Default extraction directory [%s] either doesn't exist or is not accessible for read/write."), directory.c_str());
}
}
else
{
// fallback to the POSIX standard getpwuid() library function
struct passwd* pwuid = NULL;
errno = 0;
do
{
pwuid = getpwuid(getuid());
} while (pwuid == NULL && errno == EINTR);
if (pwuid != NULL)
{
directory.assign(pwuid->pw_dir);
if (is_read_write_able_directory(directory))
{
return true;
}
else
{
trace::error(_X("Failed to determine default extraction location. Environment variable '$HOME' is not defined and directory reported by getpwuid() [%s] either doesn't exist or is not accessible for read/write."), pwuid->pw_dir);
}
}
else
{
trace::error(_X("Failed to determine default extraction location. Environment variable '$HOME' is not defined and getpwuid() returned NULL."));
}
}
return false;
}
bool pal::get_default_bundle_extraction_base_dir(pal::string_t& extraction_dir)
{
if (!get_extraction_base_parent_directory(extraction_dir))
{
return false;
}
append_path(&extraction_dir, _X(".net"));
if (is_read_write_able_directory(extraction_dir))
{
return true;
}
// Create $HOME/.net with rwx access to the owner
if (::mkdir(extraction_dir.c_str(), S_IRWXU) == 0)
{
return true;
}
else if (errno != EEXIST)
{
trace::error(_X("Failed to create default extraction directory [%s]. %s"), extraction_dir.c_str(), pal::strerror(errno).c_str());
return false;
}
return is_read_write_able_directory(extraction_dir);
}
bool pal::get_global_dotnet_dirs(std::vector<pal::string_t>* recv)
{
// No support for global directories in Unix.
return false;
}
pal::string_t pal::get_dotnet_self_registered_config_location()
{
// ***Used only for testing***
pal::string_t environment_install_location_override;
if (test_only_getenv(_X("_DOTNET_TEST_INSTALL_LOCATION_PATH"), &environment_install_location_override))
{
return environment_install_location_override;
}
return _X("/etc/dotnet");
}
namespace
{
bool get_line_from_file(FILE* pFile, pal::string_t& line)
{
line = pal::string_t();
char buffer[256];
while (fgets(buffer, sizeof(buffer), pFile))
{
line += (pal::char_t*)buffer;
size_t len = line.length();
// fgets includes the newline character in the string - so remove it.
if (len > 0 && line[len - 1] == '\n')
{
line.pop_back();
break;
}
}
return !line.empty();
}
}
bool get_install_location_from_file(const pal::string_t& file_path, bool& file_found, pal::string_t& install_location)
{
file_found = true;
bool install_location_found = false;
FILE* install_location_file = pal::file_open(file_path, "r");
if (install_location_file != nullptr)
{
if (!get_line_from_file(install_location_file, install_location))
{
trace::warning(_X("Did not find any install location in '%s'."), file_path.c_str());
}
else
{
install_location_found = true;
}
fclose(install_location_file);
if (install_location_found)
return true;
}
else
{
if (errno == ENOENT)
{
trace::verbose(_X("The install_location file ['%s'] does not exist - skipping."), file_path.c_str());
file_found = false;
}
else
{
trace::error(_X("The install_location file ['%s'] failed to open: %s."), file_path.c_str(), pal::strerror(errno).c_str());
}
}
return false;
}
bool pal::get_dotnet_self_registered_dir(pal::string_t* recv)
{
recv->clear();
// ***Used only for testing***
pal::string_t environment_override;
if (test_only_getenv(_X("_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"), &environment_override))
{
recv->assign(environment_override);
return true;
}
// ***************************
pal::string_t install_location_path = get_dotnet_self_registered_config_location();
pal::string_t arch_specific_install_location_file_path = install_location_path;
append_path(&arch_specific_install_location_file_path, (_X("install_location_") + to_lower(get_arch())).c_str());
trace::verbose(_X("Looking for architecture specific install_location file in '%s'."), arch_specific_install_location_file_path.c_str());
pal::string_t install_location;
bool file_found = false;
if (!get_install_location_from_file(arch_specific_install_location_file_path, file_found, install_location))
{
if (file_found)
{
return false;
}
pal::string_t legacy_install_location_file_path = install_location_path;
append_path(&legacy_install_location_file_path, _X("install_location"));
trace::verbose(_X("Looking for install_location file in '%s'."), legacy_install_location_file_path.c_str());
if (!get_install_location_from_file(legacy_install_location_file_path, file_found, install_location))
{
return false;
}
}
recv->assign(install_location);
trace::verbose(_X("Using install location '%s'."), recv->c_str());
return true;
}
bool pal::get_default_installation_dir(pal::string_t* recv)
{
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_DEFAULT_INSTALL_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
#if defined(TARGET_OSX)
recv->assign(_X("/usr/local/share/dotnet"));
if (pal::is_emulating_x64())
{
append_path(recv, _X("x64"));
}
#else
recv->assign(_X("/usr/share/dotnet"));
#endif
return true;
}
pal::string_t trim_quotes(pal::string_t stringToCleanup)
{
pal::char_t quote_array[2] = { '\"', '\'' };
for (size_t index = 0; index < sizeof(quote_array) / sizeof(quote_array[0]); index++)
{
size_t pos = stringToCleanup.find(quote_array[index]);
while (pos != std::string::npos)
{
stringToCleanup = stringToCleanup.erase(pos, 1);
pos = stringToCleanup.find(quote_array[index]);
}
}
return stringToCleanup;
}
#if defined(TARGET_OSX)
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
size_t size = sizeof(str);
// returns something like 10.5.2 or 11.6
int ret = sysctlbyname("kern.osproductversion", str, &size, nullptr, 0);
if (ret == 0)
{
// the value _should_ be null terminated but let's make sure
str[size - 1] = 0;
char* pos = strchr(str, '.');
if (pos != NULL)
{
int major = atoi(str);
if (major > 11)
{
// starting with 12.0 we track only major release
*pos = 0;
}
else if (major == 11)
{
// for 11.x we publish RID as 11.0
// if we return anything else, it would break the RID graph processing
strcpy(str, "11.0");
}
else
{
// for 10.x the significant releases are actually the second digit
pos = strchr(pos + 1, '.');
if (pos != NULL)
{
// strip anything after second dot and return something like 10.5
*pos = 0;
}
}
}
std::string release(str, strlen(str));
ridOS.append(_X("osx."));
ridOS.append(release);
}
return ridOS;
}
#elif defined(TARGET_FREEBSD)
// On FreeBSD get major verion. Minors should be compatible
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
if (ret == 0)
{
char* pos = strchr(str, '.');
if (pos)
{
ridOS.append(_X("freebsd."))
.append(str, pos - str);
}
}
return ridOS;
}
#elif defined(TARGET_ILLUMOS)
pal::string_t pal::get_current_os_rid_platform()
{
// Code:
// struct utsname u;
// if (uname(&u) != -1)
// printf("sysname: %s, release: %s, version: %s, machine: %s\n", u.sysname, u.release, u.version, u.machine);
//
// Output examples:
// on OmniOS
// sysname: SunOS, release: 5.11, version: omnios-r151018-95eaa7e, machine: i86pc
// on OpenIndiana Hipster:
// sysname: SunOS, release: 5.11, version: illumos-63878f749f, machine: i86pc
// on SmartOS:
// sysname: SunOS, release: 5.11, version: joyent_20200408T231825Z, machine: i86pc
pal::string_t ridOS;
struct utsname utsname_obj;
if (uname(&utsname_obj) < 0)
{
return ridOS;
}
if (strncmp(utsname_obj.version, "omnios", strlen("omnios")) == 0)
{
ridOS.append(_X("omnios."))
.append(utsname_obj.version, strlen("omnios-r"), 2); // e.g. omnios.15
}
else if (strncmp(utsname_obj.version, "illumos-", strlen("illumos-")) == 0)
{
ridOS.append(_X("openindiana")); // version-less
}
else if (strncmp(utsname_obj.version, "joyent_", strlen("joyent_")) == 0)
{
ridOS.append(_X("smartos."))
.append(utsname_obj.version, strlen("joyent_"), 4); // e.g. smartos.2020
}
return ridOS;
}
#elif defined(__sun)
pal::string_t pal::get_current_os_rid_platform()
{
// Code:
// struct utsname u;
// if (uname(&u) != -1)
// printf("sysname: %s, release: %s, version: %s, machine: %s\n", u.sysname, u.release, u.version, u.machine);
//
// Output example on Solaris 11:
// sysname: SunOS, release: 5.11, version: 11.3, machine: i86pc
pal::string_t ridOS;
struct utsname utsname_obj;
if (uname(&utsname_obj) < 0)
{
return ridOS;
}
char* pos = strchr(utsname_obj.version, '.');
if (pos)
{
ridOS.append(_X("solaris."))
.append(utsname_obj.version, pos - utsname_obj.version); // e.g. solaris.11
}
return ridOS;
}
#else
// For some distros, we don't want to use the full version from VERSION_ID. One example is
// Red Hat Enterprise Linux, which includes a minor version in their VERSION_ID but minor
// versions are backwards compatable.
//
// In this case, we'll normalized RIDs like 'rhel.7.2' and 'rhel.7.3' to a generic
// 'rhel.7'. This brings RHEL in line with other distros like CentOS or Debian which
// don't put minor version numbers in their VERSION_ID fields because all minor versions
// are backwards compatible.
static
pal::string_t normalize_linux_rid(pal::string_t rid)
{
pal::string_t rhelPrefix(_X("rhel."));
pal::string_t alpinePrefix(_X("alpine."));
pal::string_t rockyPrefix(_X("rocky."));
size_t lastVersionSeparatorIndex = std::string::npos;
if (rid.compare(0, rhelPrefix.length(), rhelPrefix) == 0)
{
lastVersionSeparatorIndex = rid.find(_X("."), rhelPrefix.length());
}
else if (rid.compare(0, alpinePrefix.length(), alpinePrefix) == 0)
{
size_t secondVersionSeparatorIndex = rid.find(_X("."), alpinePrefix.length());
if (secondVersionSeparatorIndex != std::string::npos)
{
lastVersionSeparatorIndex = rid.find(_X("."), secondVersionSeparatorIndex + 1);
}
}
else if (rid.compare(0, rockyPrefix.length(), rockyPrefix) == 0)
{
lastVersionSeparatorIndex = rid.find(_X("."), rockyPrefix.length());
}
if (lastVersionSeparatorIndex != std::string::npos)
{
rid.erase(lastVersionSeparatorIndex, rid.length() - lastVersionSeparatorIndex);
}
return rid;
}
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
pal::string_t versionFile(_X("/etc/os-release"));
if (pal::file_exists(versionFile))
{
// Read the file to get ID and VERSION_ID data that will be used
// to construct the RID.
std::fstream fsVersionFile;
fsVersionFile.open(versionFile, std::fstream::in);
// Proceed only if we were able to open the file
if (fsVersionFile.good())
{
pal::string_t line;
pal::string_t strID(_X("ID="));
pal::string_t valID;
pal::string_t strVersionID(_X("VERSION_ID="));
pal::string_t valVersionID;
bool fFoundID = false, fFoundVersion = false;
// Read the first line
std::getline(fsVersionFile, line);
// Loop until we are at the end of file
while (!fsVersionFile.eof())
{
// Look for ID if we have not found it already
if (!fFoundID)
{
size_t pos = line.find(strID);
if ((pos != std::string::npos) && (pos == 0))
{
valID.append(line.substr(3));
fFoundID = true;
}
}
// Look for VersionID if we have not found it already
if (!fFoundVersion)
{
size_t pos = line.find(strVersionID);
if ((pos != std::string::npos) && (pos == 0))
{
valVersionID.append(line.substr(11));
fFoundVersion = true;
}
}
if (fFoundID && fFoundVersion)
{
// We have everything we need to form the RID - break out of the loop.
break;
}
// Read the next line
std::getline(fsVersionFile, line);
}
// Close the file now that we are done with it.
fsVersionFile.close();
if (fFoundID)
{
ridOS.append(valID);
}
if (fFoundVersion)
{
ridOS.append(_X("."));
ridOS.append(valVersionID);
}
if (fFoundID || fFoundVersion)
{
// Remove any double-quotes
ridOS = trim_quotes(ridOS);
}
}
}
return normalize_linux_rid(ridOS);
}
#endif
bool pal::get_own_executable_path(pal::string_t* recv)
{
char* path = minipal_getexepath();
if (!path)
{
return false;
}
recv->assign(path);
free(path);
return true;
}
bool pal::get_own_module_path(string_t* recv)
{
Dl_info info;
if (dladdr((void*)&pal::get_own_module_path, &info) == 0)
return false;
recv->assign(info.dli_fname);
return true;
}
bool pal::get_method_module_path(string_t* recv, void* method)
{
Dl_info info;
if (dladdr(method, &info) == 0)
return false;
recv->assign(info.dli_fname);
return true;
}
bool pal::get_module_path(dll_t module, string_t* recv)
{
return false;
}
bool pal::get_current_module(dll_t* mod)
{
return false;
}
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const pal::char_t* name, pal::string_t* recv)
{
recv->clear();
auto result = ::getenv(name);
if (result != nullptr)
{
recv->assign(result);
}
return (recv->length() > 0);
}
bool pal::realpath(pal::string_t* path, bool skip_error_logging)
{
auto resolved = ::realpath(path->c_str(), nullptr);
if (resolved == nullptr)
{
if (errno == ENOENT)
{
return false;
}
if (!skip_error_logging)
{
trace::error(_X("realpath(%s) failed: %s"), path->c_str(), strerror(errno).c_str());
}
return false;
}
path->assign(resolved);
::free(resolved);
return true;
}
bool pal::file_exists(const pal::string_t& path)
{
return (::access(path.c_str(), F_OK) == 0);
}
static void readdir(const pal::string_t& path, const pal::string_t& pattern, bool onlydirectories, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
auto dir = opendir(path.c_str());
if (dir != nullptr)
{
struct dirent* entry = nullptr;
while ((entry = readdir(dir)) != nullptr)
{
if (fnmatch(pattern.c_str(), entry->d_name, FNM_PATHNAME) != 0)
{
continue;
}
#if HAVE_DIRENT_D_TYPE
int dirEntryType = entry->d_type;
#else
int dirEntryType = DT_UNKNOWN;
#endif
// We are interested in files only
switch (dirEntryType)
{
case DT_DIR:
break;
case DT_REG:
if (onlydirectories)
{
continue;
}
break;
// Handle symlinks and file systems that do not support d_type
case DT_LNK:
case DT_UNKNOWN:
{
struct stat sb;
if (fstatat(dirfd(dir), entry->d_name, &sb, 0) == -1)
{
continue;
}
if (onlydirectories)
{
if (!S_ISDIR(sb.st_mode))
{
continue;
}
break;
}
else if (!S_ISREG(sb.st_mode) && !S_ISDIR(sb.st_mode))
{
continue;
}
}
break;
default:
continue;
}
if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
{
continue;
}
files.emplace_back(entry->d_name);
}
closedir(dir);
}
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, false, list);
}
void pal::readdir(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), false, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, true, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), true, list);
}
bool pal::is_running_in_wow64()
{
return false;
}
bool pal::is_emulating_x64()
{
int is_translated_process = 0;
#if defined(TARGET_OSX)
size_t size = sizeof(is_translated_process);
if (sysctlbyname("sysctl.proc_translated", &is_translated_process, &size, NULL, 0) == -1)
{
trace::info(_X("Could not determine whether the current process is running under Rosetta."));
if (errno != ENOENT)
{
trace::info(_X("Call to sysctlbyname failed: %s"), strerror(errno).c_str());
}
return false;
}
#endif
return is_translated_process == 1;
}
bool pal::are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2)
{
#if defined(TARGET_OSX)
// On Mac, paths are case-insensitive
return (strcasecmp(path1.c_str(), path2.c_str()) == 0);
#else
// On Linux, paths are case-sensitive
return path1 == path2;
#endif
}
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/hostmisc/pal.windows.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal.h"
#include "trace.h"
#include "utils.h"
#include "longfile.h"
#include <cassert>
#include <locale>
#include <ShlObj.h>
#include <ctime>
bool GetModuleFileNameWrapper(HMODULE hModule, pal::string_t* recv)
{
pal::string_t path;
size_t dwModuleFileName = MAX_PATH / 2;
do
{
path.resize(dwModuleFileName * 2);
dwModuleFileName = GetModuleFileNameW(hModule, (LPWSTR)path.data(), static_cast<DWORD>(path.size()));
} while (dwModuleFileName == path.size());
if (dwModuleFileName == 0)
return false;
path.resize(dwModuleFileName);
recv->assign(path);
return true;
}
bool GetModuleHandleFromAddress(void *addr, HMODULE *hModule)
{
BOOL res = ::GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(addr),
hModule);
return (res != FALSE);
}
pal::string_t pal::get_timestamp()
{
std::time_t t = std::time(nullptr);
const std::size_t elems = 100;
char_t buf[elems];
tm tm_l{};
::gmtime_s(&tm_l, &t);
std::wcsftime(buf, elems, _X("%c GMT"), &tm_l);
return pal::string_t(buf);
}
bool pal::touch_file(const pal::string_t& path)
{
HANDLE hnd = ::CreateFileW(path.c_str(), 0, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hnd == INVALID_HANDLE_VALUE)
{
trace::verbose(_X("Failed to leave breadcrumb, HRESULT: 0x%X"), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
::CloseHandle(hnd);
return true;
}
static void* map_file(const pal::string_t& path, size_t *length, DWORD mapping_protect, DWORD view_desired_access)
{
HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
{
trace::error(_X("Failed to map file. CreateFileW(%s) failed with error %d"), path.c_str(), GetLastError());
return nullptr;
}
if (length != nullptr)
{
LARGE_INTEGER fileSize;
if (GetFileSizeEx(file, &fileSize) == 0)
{
trace::error(_X("Failed to map file. GetFileSizeEx(%s) failed with error %d"), path.c_str(), GetLastError());
CloseHandle(file);
return nullptr;
}
*length = (size_t)fileSize.QuadPart;
}
HANDLE map = CreateFileMappingW(file, NULL, mapping_protect, 0, 0, NULL);
if (map == NULL)
{
trace::error(_X("Failed to map file. CreateFileMappingW(%s) failed with error %d"), path.c_str(), GetLastError());
CloseHandle(file);
return nullptr;
}
void *address = MapViewOfFile(map, view_desired_access, 0, 0, 0);
if (address == NULL)
{
trace::error(_X("Failed to map file. MapViewOfFile(%s) failed with error %d"), path.c_str(), GetLastError());
}
// The file-handle (file) and mapping object handle (map) can be safely closed
// once the file is mapped. The OS keeps the file open if there is an open mapping into the file.
CloseHandle(map);
CloseHandle(file);
return address;
}
const void* pal::mmap_read(const string_t& path, size_t* length)
{
return map_file(path, length, PAGE_READONLY, FILE_MAP_READ);
}
void* pal::mmap_copy_on_write(const string_t& path, size_t* length)
{
return map_file(path, length, PAGE_WRITECOPY, FILE_MAP_READ | FILE_MAP_COPY);
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t buf[MAX_PATH];
DWORD result = GetCurrentDirectoryW(MAX_PATH, buf);
if (result < MAX_PATH)
{
recv->assign(buf);
return true;
}
else if (result != 0)
{
std::vector<pal::char_t> str;
str.resize(result);
result = GetCurrentDirectoryW(static_cast<uint32_t>(str.size()), str.data());
assert(result <= str.size());
if (result != 0)
{
recv->assign(str.data());
return true;
}
}
assert(result == 0);
trace::error(_X("Failed to obtain working directory, HRESULT: 0x%X"), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
bool pal::get_loaded_library(
const char_t *library_name,
const char *symbol_name,
/*out*/ dll_t *dll,
/*out*/ pal::string_t *path)
{
dll_t dll_maybe = ::GetModuleHandleW(library_name);
if (dll_maybe == nullptr)
return false;
*dll = dll_maybe;
return pal::get_module_path(*dll, path);
}
bool pal::load_library(const string_t* in_path, dll_t* dll)
{
string_t path = *in_path;
// LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR:
// In framework-dependent apps, coreclr would come from another directory than the host,
// so make sure coreclr dependencies can be resolved from coreclr.dll load dir.
if (LongFile::IsPathNotFullyQualified(path))
{
if (!pal::realpath(&path))
{
trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
}
//Adding the assert to ensure relative paths which are not just filenames are not used for LoadLibrary Calls
assert(!LongFile::IsPathNotFullyQualified(path) || !LongFile::ContainsDirectorySeparator(path));
*dll = ::LoadLibraryExW(path.c_str(), NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
if (*dll == nullptr)
{
trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
// Pin the module
HMODULE dummy_module;
if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, path.c_str(), &dummy_module))
{
trace::error(_X("Failed to pin library [%s] in [%s]"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
if (trace::is_enabled())
{
string_t buf;
GetModuleFileNameWrapper(*dll, &buf);
trace::info(_X("Loaded library from %s"), buf.c_str());
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = ::GetProcAddress(library, name);
if (result == nullptr)
{
trace::info(_X("Probed for and did not resolve library symbol %S"), name);
}
return result;
}
void pal::unload_library(dll_t library)
{
// No-op. On windows, we pin the library, so it can't be unloaded.
}
static
bool get_wow_mode_program_files(pal::string_t* recv)
{
#if defined(TARGET_AMD64)
const pal::char_t* env_key = _X("ProgramFiles(x86)");
#else
const pal::char_t* env_key = _X("ProgramFiles");
#endif
return get_file_path_from_env(env_key,recv);
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t prog_dat;
if (!get_file_path_from_env(_X("ProgramData"), &prog_dat))
{
// We should have the path in prog_dat.
trace::verbose(_X("Failed to read default breadcrumb store [%s]"), prog_dat.c_str());
return false;
}
recv->assign(prog_dat);
append_path(recv, _X("Microsoft"));
append_path(recv, _X("NetFramework"));
append_path(recv, _X("BreadcrumbStore"));
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
if (!get_wow_mode_program_files(recv))
{
return false;
}
append_path(recv, _X("coreservicing"));
return true;
}
bool pal::get_default_installation_dir(pal::string_t* recv)
{
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_DEFAULT_INSTALL_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
const pal::char_t* program_files_dir;
if (pal::is_running_in_wow64())
{
program_files_dir = _X("ProgramFiles(x86)");
}
else
{
program_files_dir = _X("ProgramFiles");
}
if (!get_file_path_from_env(program_files_dir, recv))
{
return false;
}
append_path(recv, _X("dotnet"));
if (pal::is_emulating_x64())
{
// Install location for emulated x64 should be %ProgramFiles%\dotnet\x64.
append_path(recv, _X("x64"));
}
return true;
}
namespace
{
void get_dotnet_install_location_registry_path(HKEY * key_hive, pal::string_t * sub_key, const pal::char_t ** value)
{
*key_hive = HKEY_LOCAL_MACHINE;
// The registry search occurs in the 32-bit registry in all cases.
pal::string_t dotnet_key_path = pal::string_t(_X("SOFTWARE\\dotnet"));
pal::string_t environmentRegistryPathOverride;
if (test_only_getenv(_X("_DOTNET_TEST_REGISTRY_PATH"), &environmentRegistryPathOverride))
{
pal::string_t hkcuPrefix = _X("HKEY_CURRENT_USER\\");
if (environmentRegistryPathOverride.substr(0, hkcuPrefix.length()) == hkcuPrefix)
{
*key_hive = HKEY_CURRENT_USER;
environmentRegistryPathOverride = environmentRegistryPathOverride.substr(hkcuPrefix.length());
}
dotnet_key_path = environmentRegistryPathOverride;
}
*sub_key = dotnet_key_path + pal::string_t(_X("\\Setup\\InstalledVersions\\")) + get_arch();
*value = _X("InstallLocation");
}
}
pal::string_t pal::get_dotnet_self_registered_config_location()
{
HKEY key_hive;
pal::string_t sub_key;
const pal::char_t* value;
get_dotnet_install_location_registry_path(&key_hive, &sub_key, &value);
return (key_hive == HKEY_CURRENT_USER ? _X("HKCU\\") : _X("HKLM\\")) + sub_key + _X("\\") + value;
}
bool pal::get_dotnet_self_registered_dir(pal::string_t* recv)
{
recv->clear();
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
HKEY hkeyHive;
pal::string_t sub_key;
const pal::char_t* value;
get_dotnet_install_location_registry_path(&hkeyHive, &sub_key, &value);
// Must use RegOpenKeyEx to be able to specify KEY_WOW64_32KEY to access the 32-bit registry in all cases.
// The RegGetValue has this option available only on Win10.
HKEY hkey = NULL;
LSTATUS result = ::RegOpenKeyExW(hkeyHive, sub_key.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &hkey);
if (result != ERROR_SUCCESS)
{
trace::verbose(_X("Can't open the SDK installed location registry key, result: 0x%X"), result);
return false;
}
// Determine the size of the buffer
DWORD size = 0;
result = ::RegGetValueW(hkey, nullptr, value, RRF_RT_REG_SZ, nullptr, nullptr, &size);
if (result != ERROR_SUCCESS || size == 0)
{
trace::verbose(_X("Can't get the size of the SDK location registry value or it's empty, result: 0x%X"), result);
::RegCloseKey(hkey);
return false;
}
// Get the key's value
std::vector<pal::char_t> buffer(size/sizeof(pal::char_t));
result = ::RegGetValueW(hkey, nullptr, value, RRF_RT_REG_SZ, nullptr, &buffer[0], &size);
if (result != ERROR_SUCCESS)
{
trace::verbose(_X("Can't get the value of the SDK location registry value, result: 0x%X"), result);
::RegCloseKey(hkey);
return false;
}
recv->assign(buffer.data());
::RegCloseKey(hkey);
return true;
}
bool pal::get_global_dotnet_dirs(std::vector<pal::string_t>* dirs)
{
pal::string_t default_dir;
pal::string_t custom_dir;
bool dir_found = false;
if (pal::get_dotnet_self_registered_dir(&custom_dir))
{
remove_trailing_dir_seperator(&custom_dir);
dirs->push_back(custom_dir);
dir_found = true;
}
if (get_default_installation_dir(&default_dir))
{
remove_trailing_dir_seperator(&default_dir);
// Avoid duplicate global dirs.
if (!dir_found || !are_paths_equal_with_normalized_casing(custom_dir, default_dir))
{
dirs->push_back(default_dir);
dir_found = true;
}
}
return dir_found;
}
// To determine the OS version, we are going to use RtlGetVersion API
// since GetVersion call can be shimmed on Win8.1+.
typedef LONG (WINAPI *pFuncRtlGetVersion)(RTL_OSVERSIONINFOW *);
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
RTL_OSVERSIONINFOW osinfo;
// Init the buffer
ZeroMemory(&osinfo, sizeof(osinfo));
osinfo.dwOSVersionInfoSize = sizeof(osinfo);
HMODULE hmodNtdll = LoadLibraryA("ntdll.dll");
if (hmodNtdll != NULL)
{
pFuncRtlGetVersion pRtlGetVersion = (pFuncRtlGetVersion)GetProcAddress(hmodNtdll, "RtlGetVersion");
if (pRtlGetVersion)
{
if ((*pRtlGetVersion)(&osinfo) == 0)
{
// Win7 RID is the minimum supported version.
uint32_t majorVer = 6;
uint32_t minorVer = 1;
if (osinfo.dwMajorVersion > majorVer)
{
majorVer = osinfo.dwMajorVersion;
// Reset the minor version since we picked a different major version.
minorVer = 0;
}
if (osinfo.dwMinorVersion > minorVer)
{
minorVer = osinfo.dwMinorVersion;
}
if (majorVer == 6)
{
switch(minorVer)
{
case 1:
ridOS.append(_X("win7"));
break;
case 2:
ridOS.append(_X("win8"));
break;
case 3:
default:
// For unknown version, we will support the highest RID that we know for this major version.
ridOS.append(_X("win81"));
break;
}
}
else if (majorVer >= 10)
{
// Return the major version for use in RID computation without applying any cap.
ridOS.append(_X("win"));
ridOS.append(pal::to_string(majorVer));
}
}
}
}
return ridOS;
}
bool pal::is_path_rooted(const string_t& path)
{
return path.length() >= 2 && path[1] == L':';
}
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const char_t* name, string_t* recv)
{
recv->clear();
auto length = ::GetEnvironmentVariableW(name, nullptr, 0);
if (length == 0)
{
auto err = GetLastError();
if (err != ERROR_ENVVAR_NOT_FOUND)
{
trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError()));
}
return false;
}
auto buf = new char_t[length];
if (::GetEnvironmentVariableW(name, buf, length) == 0)
{
trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError()));
return false;
}
recv->assign(buf);
delete[] buf;
return true;
}
int pal::xtoi(const char_t* input)
{
return ::_wtoi(input);
}
bool pal::get_own_executable_path(string_t* recv)
{
return GetModuleFileNameWrapper(NULL, recv);
}
bool pal::get_current_module(dll_t *mod)
{
HMODULE hmod = nullptr;
if (!GetModuleHandleFromAddress(&get_current_module, &hmod))
return false;
*mod = (pal::dll_t)hmod;
return true;
}
bool pal::get_own_module_path(string_t* recv)
{
HMODULE hmod;
if (!GetModuleHandleFromAddress(&get_own_module_path, &hmod))
return false;
return GetModuleFileNameWrapper(hmod, recv);
}
bool pal::get_method_module_path(string_t* recv, void* method)
{
HMODULE hmod;
if (!GetModuleHandleFromAddress(method, &hmod))
return false;
return GetModuleFileNameWrapper(hmod, recv);
}
bool pal::get_module_path(dll_t mod, string_t* recv)
{
return GetModuleFileNameWrapper(mod, recv);
}
bool get_extraction_base_parent_directory(pal::string_t& directory)
{
const size_t max_len = MAX_PATH + 1;
pal::char_t temp_path[max_len];
size_t len = GetTempPathW(max_len, temp_path);
if (len == 0)
{
return false;
}
assert(len < max_len);
directory.assign(temp_path);
return pal::realpath(&directory);
}
bool pal::get_default_bundle_extraction_base_dir(pal::string_t& extraction_dir)
{
if (!get_extraction_base_parent_directory(extraction_dir))
{
trace::error(_X("Failed to determine default extraction location. Check if 'TMP' or 'TEMP' points to existing path."));
return false;
}
append_path(&extraction_dir, _X(".net"));
// Windows Temp-Path is already user-private.
if (realpath(&extraction_dir))
{
return true;
}
// Create the %TEMP%\.net directory
if (CreateDirectoryW(extraction_dir.c_str(), NULL) == 0 &&
GetLastError() != ERROR_ALREADY_EXISTS)
{
trace::error(_X("Failed to create default extraction directory [%s]. %s, error code: %d"), extraction_dir.c_str(), pal::strerror(errno), GetLastError());
return false;
}
return realpath(&extraction_dir);
}
static bool wchar_convert_helper(DWORD code_page, const char* cstr, size_t len, pal::string_t* out)
{
out->clear();
// No need of explicit null termination, so pass in the actual length.
size_t size = ::MultiByteToWideChar(code_page, 0, cstr, static_cast<uint32_t>(len), nullptr, 0);
if (size == 0)
{
return false;
}
out->resize(size, '\0');
return ::MultiByteToWideChar(code_page, 0, cstr, static_cast<uint32_t>(len), &(*out)[0], static_cast<uint32_t>(out->size())) != 0;
}
bool pal::pal_utf8string(const pal::string_t& str, std::vector<char>* out)
{
out->clear();
// Pass -1 as we want explicit null termination in the char buffer.
size_t size = ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (size == 0)
{
return false;
}
out->resize(size, '\0');
return ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, out->data(), static_cast<uint32_t>(out->size()), nullptr, nullptr) != 0;
}
bool pal::pal_clrstring(const pal::string_t& str, std::vector<char>* out)
{
return pal_utf8string(str, out);
}
bool pal::clr_palstring(const char* cstr, pal::string_t* out)
{
return wchar_convert_helper(CP_UTF8, cstr, ::strlen(cstr), out);
}
// Return if path is valid and file exists, return true and adjust path as appropriate.
bool pal::realpath(string_t* path, bool skip_error_logging)
{
if (path->empty())
{
return false;
}
if (LongFile::IsNormalized(*path))
{
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(path->c_str(), GetFileExInfoStandard, &data) != 0)
{
return true;
}
}
char_t buf[MAX_PATH];
size_t size = ::GetFullPathNameW(path->c_str(), MAX_PATH, buf, nullptr);
if (size == 0)
{
if (!skip_error_logging)
{
trace::error(_X("Error resolving full path [%s]"), path->c_str());
}
return false;
}
string_t str;
if (size < MAX_PATH)
{
str.assign(buf);
}
else
{
str.resize(size + LongFile::UNCExtendedPathPrefix.length(), 0);
size = ::GetFullPathNameW(path->c_str(), static_cast<uint32_t>(size), (LPWSTR)str.data(), nullptr);
assert(size <= str.size());
if (size == 0)
{
if (!skip_error_logging)
{
trace::error(_X("Error resolving full path [%s]"), path->c_str());
}
return false;
}
const string_t* prefix = &LongFile::ExtendedPrefix;
//Check if the resolved path is a UNC. By default we assume relative path to resolve to disk
if (str.compare(0, LongFile::UNCPathPrefix.length(), LongFile::UNCPathPrefix) == 0)
{
prefix = &LongFile::UNCExtendedPathPrefix;
str.erase(0, LongFile::UNCPathPrefix.length());
size = size - LongFile::UNCPathPrefix.length();
}
str.insert(0, *prefix);
str.resize(size + prefix->length());
str.shrink_to_fit();
}
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(str.c_str(), GetFileExInfoStandard, &data) != 0)
{
*path = str;
return true;
}
return false;
}
bool pal::file_exists(const string_t& path)
{
string_t tmp(path);
return pal::realpath(&tmp, true);
}
static void readdir(const pal::string_t& path, const pal::string_t& pattern, bool onlydirectories, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
pal::string_t normalized_path(path);
if (LongFile::ShouldNormalize(normalized_path))
{
if (!pal::realpath(&normalized_path))
{
return;
}
}
pal::string_t search_string(normalized_path);
append_path(&search_string, pattern.c_str());
WIN32_FIND_DATAW data = { 0 };
auto handle = ::FindFirstFileExW(search_string.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, NULL, 0);
if (handle == INVALID_HANDLE_VALUE)
{
return;
}
do
{
if (!onlydirectories || (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
pal::string_t filepath(data.cFileName);
if (filepath != _X(".") && filepath != _X(".."))
{
files.push_back(filepath);
}
}
} while (::FindNextFileW(handle, &data));
::FindClose(handle);
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, false, list);
}
void pal::readdir(const string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), false, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, true, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), true, list);
}
bool pal::is_running_in_wow64()
{
BOOL fWow64Process = FALSE;
if (!IsWow64Process(GetCurrentProcess(), &fWow64Process))
{
return false;
}
return (fWow64Process != FALSE);
}
typedef BOOL (WINAPI* is_wow64_process2)(
HANDLE hProcess,
USHORT *pProcessMachine,
USHORT *pNativeMachine
);
bool pal::is_emulating_x64()
{
USHORT pProcessMachine, pNativeMachine;
auto kernel32 = LoadLibraryExW(L"kernel32.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (kernel32)
{
is_wow64_process2 isWow64Process2Func = (is_wow64_process2)GetProcAddress(kernel32, "IsWow64Process2");
if (!isWow64Process2Func)
{
// Could not find IsWow64Process2.
return false;
}
if (!isWow64Process2Func(GetCurrentProcess(), &pProcessMachine, &pNativeMachine))
{
// IsWow64Process2 failed. Log the error and continue.
trace::info(_X("Call to IsWow64Process2 failed: %s"), GetLastError());
return false;
}
// Check if we are running an x64 process on a non-x64 windows machine.
return pProcessMachine != pNativeMachine && pProcessMachine == IMAGE_FILE_MACHINE_AMD64;
}
// Loading kernel32.dll failed, log the error and continue.
trace::info(_X("Could not load 'kernel32.dll': %s"), GetLastError());
return false;
}
bool pal::are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2)
{
// On Windows, paths are case-insensitive
return (strcasecmp(path1.c_str(), path2.c_str()) == 0);
}
pal::mutex_t::mutex_t()
: _impl{ }
{
::InitializeCriticalSection(&_impl);
}
pal::mutex_t::~mutex_t()
{
::DeleteCriticalSection(&_impl);
}
void pal::mutex_t::lock()
{
::EnterCriticalSection(&_impl);
}
void pal::mutex_t::unlock()
{
::LeaveCriticalSection(&_impl);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal.h"
#include "trace.h"
#include "utils.h"
#include "longfile.h"
#include <cassert>
#include <locale>
#include <ShlObj.h>
#include <ctime>
bool GetModuleFileNameWrapper(HMODULE hModule, pal::string_t* recv)
{
pal::string_t path;
size_t dwModuleFileName = MAX_PATH / 2;
do
{
path.resize(dwModuleFileName * 2);
dwModuleFileName = GetModuleFileNameW(hModule, (LPWSTR)path.data(), static_cast<DWORD>(path.size()));
} while (dwModuleFileName == path.size());
if (dwModuleFileName == 0)
return false;
path.resize(dwModuleFileName);
recv->assign(path);
return true;
}
bool GetModuleHandleFromAddress(void *addr, HMODULE *hModule)
{
BOOL res = ::GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(addr),
hModule);
return (res != FALSE);
}
pal::string_t pal::get_timestamp()
{
std::time_t t = std::time(nullptr);
const std::size_t elems = 100;
char_t buf[elems];
tm tm_l{};
::gmtime_s(&tm_l, &t);
std::wcsftime(buf, elems, _X("%c GMT"), &tm_l);
return pal::string_t(buf);
}
bool pal::touch_file(const pal::string_t& path)
{
HANDLE hnd = ::CreateFileW(path.c_str(), 0, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hnd == INVALID_HANDLE_VALUE)
{
trace::verbose(_X("Failed to leave breadcrumb, HRESULT: 0x%X"), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
::CloseHandle(hnd);
return true;
}
static void* map_file(const pal::string_t& path, size_t *length, DWORD mapping_protect, DWORD view_desired_access)
{
HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file == INVALID_HANDLE_VALUE)
{
trace::error(_X("Failed to map file. CreateFileW(%s) failed with error %d"), path.c_str(), GetLastError());
return nullptr;
}
if (length != nullptr)
{
LARGE_INTEGER fileSize;
if (GetFileSizeEx(file, &fileSize) == 0)
{
trace::error(_X("Failed to map file. GetFileSizeEx(%s) failed with error %d"), path.c_str(), GetLastError());
CloseHandle(file);
return nullptr;
}
*length = (size_t)fileSize.QuadPart;
}
HANDLE map = CreateFileMappingW(file, NULL, mapping_protect, 0, 0, NULL);
if (map == NULL)
{
trace::error(_X("Failed to map file. CreateFileMappingW(%s) failed with error %d"), path.c_str(), GetLastError());
CloseHandle(file);
return nullptr;
}
void *address = MapViewOfFile(map, view_desired_access, 0, 0, 0);
if (address == NULL)
{
trace::error(_X("Failed to map file. MapViewOfFile(%s) failed with error %d"), path.c_str(), GetLastError());
}
// The file-handle (file) and mapping object handle (map) can be safely closed
// once the file is mapped. The OS keeps the file open if there is an open mapping into the file.
CloseHandle(map);
CloseHandle(file);
return address;
}
const void* pal::mmap_read(const string_t& path, size_t* length)
{
return map_file(path, length, PAGE_READONLY, FILE_MAP_READ);
}
void* pal::mmap_copy_on_write(const string_t& path, size_t* length)
{
return map_file(path, length, PAGE_WRITECOPY, FILE_MAP_READ | FILE_MAP_COPY);
}
bool pal::getcwd(pal::string_t* recv)
{
recv->clear();
pal::char_t buf[MAX_PATH];
DWORD result = GetCurrentDirectoryW(MAX_PATH, buf);
if (result < MAX_PATH)
{
recv->assign(buf);
return true;
}
else if (result != 0)
{
std::vector<pal::char_t> str;
str.resize(result);
result = GetCurrentDirectoryW(static_cast<uint32_t>(str.size()), str.data());
assert(result <= str.size());
if (result != 0)
{
recv->assign(str.data());
return true;
}
}
assert(result == 0);
trace::error(_X("Failed to obtain working directory, HRESULT: 0x%X"), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
bool pal::get_loaded_library(
const char_t *library_name,
const char *symbol_name,
/*out*/ dll_t *dll,
/*out*/ pal::string_t *path)
{
dll_t dll_maybe = ::GetModuleHandleW(library_name);
if (dll_maybe == nullptr)
return false;
*dll = dll_maybe;
return pal::get_module_path(*dll, path);
}
bool pal::load_library(const string_t* in_path, dll_t* dll)
{
string_t path = *in_path;
// LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR:
// In framework-dependent apps, coreclr would come from another directory than the host,
// so make sure coreclr dependencies can be resolved from coreclr.dll load dir.
if (LongFile::IsPathNotFullyQualified(path))
{
if (!pal::realpath(&path))
{
trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
}
//Adding the assert to ensure relative paths which are not just filenames are not used for LoadLibrary Calls
assert(!LongFile::IsPathNotFullyQualified(path) || !LongFile::ContainsDirectorySeparator(path));
*dll = ::LoadLibraryExW(path.c_str(), NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
if (*dll == nullptr)
{
trace::error(_X("Failed to load the dll from [%s], HRESULT: 0x%X"), path.c_str(), HRESULT_FROM_WIN32(GetLastError()));
return false;
}
// Pin the module
HMODULE dummy_module;
if (!::GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, path.c_str(), &dummy_module))
{
trace::error(_X("Failed to pin library [%s] in [%s]"), path.c_str(), _STRINGIFY(__FUNCTION__));
return false;
}
if (trace::is_enabled())
{
string_t buf;
GetModuleFileNameWrapper(*dll, &buf);
trace::info(_X("Loaded library from %s"), buf.c_str());
}
return true;
}
pal::proc_t pal::get_symbol(dll_t library, const char* name)
{
auto result = ::GetProcAddress(library, name);
if (result == nullptr)
{
trace::info(_X("Probed for and did not resolve library symbol %S"), name);
}
return result;
}
void pal::unload_library(dll_t library)
{
// No-op. On windows, we pin the library, so it can't be unloaded.
}
static
bool get_wow_mode_program_files(pal::string_t* recv)
{
#if defined(TARGET_AMD64)
const pal::char_t* env_key = _X("ProgramFiles(x86)");
#else
const pal::char_t* env_key = _X("ProgramFiles");
#endif
return get_file_path_from_env(env_key,recv);
}
bool pal::get_default_breadcrumb_store(string_t* recv)
{
recv->clear();
pal::string_t prog_dat;
if (!get_file_path_from_env(_X("ProgramData"), &prog_dat))
{
// We should have the path in prog_dat.
trace::verbose(_X("Failed to read default breadcrumb store [%s]"), prog_dat.c_str());
return false;
}
recv->assign(prog_dat);
append_path(recv, _X("Microsoft"));
append_path(recv, _X("NetFramework"));
append_path(recv, _X("BreadcrumbStore"));
return true;
}
bool pal::get_default_servicing_directory(string_t* recv)
{
if (!get_wow_mode_program_files(recv))
{
return false;
}
append_path(recv, _X("coreservicing"));
return true;
}
bool pal::get_default_installation_dir(pal::string_t* recv)
{
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_DEFAULT_INSTALL_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
const pal::char_t* program_files_dir;
if (pal::is_running_in_wow64())
{
program_files_dir = _X("ProgramFiles(x86)");
}
else
{
program_files_dir = _X("ProgramFiles");
}
if (!get_file_path_from_env(program_files_dir, recv))
{
return false;
}
append_path(recv, _X("dotnet"));
if (pal::is_emulating_x64())
{
// Install location for emulated x64 should be %ProgramFiles%\dotnet\x64.
append_path(recv, _X("x64"));
}
return true;
}
namespace
{
void get_dotnet_install_location_registry_path(HKEY * key_hive, pal::string_t * sub_key, const pal::char_t ** value)
{
*key_hive = HKEY_LOCAL_MACHINE;
// The registry search occurs in the 32-bit registry in all cases.
pal::string_t dotnet_key_path = pal::string_t(_X("SOFTWARE\\dotnet"));
pal::string_t environmentRegistryPathOverride;
if (test_only_getenv(_X("_DOTNET_TEST_REGISTRY_PATH"), &environmentRegistryPathOverride))
{
pal::string_t hkcuPrefix = _X("HKEY_CURRENT_USER\\");
if (environmentRegistryPathOverride.substr(0, hkcuPrefix.length()) == hkcuPrefix)
{
*key_hive = HKEY_CURRENT_USER;
environmentRegistryPathOverride = environmentRegistryPathOverride.substr(hkcuPrefix.length());
}
dotnet_key_path = environmentRegistryPathOverride;
}
*sub_key = dotnet_key_path + pal::string_t(_X("\\Setup\\InstalledVersions\\")) + get_arch();
*value = _X("InstallLocation");
}
}
pal::string_t pal::get_dotnet_self_registered_config_location()
{
HKEY key_hive;
pal::string_t sub_key;
const pal::char_t* value;
get_dotnet_install_location_registry_path(&key_hive, &sub_key, &value);
return (key_hive == HKEY_CURRENT_USER ? _X("HKCU\\") : _X("HKLM\\")) + sub_key + _X("\\") + value;
}
bool pal::get_dotnet_self_registered_dir(pal::string_t* recv)
{
recv->clear();
// ***Used only for testing***
pal::string_t environmentOverride;
if (test_only_getenv(_X("_DOTNET_TEST_GLOBALLY_REGISTERED_PATH"), &environmentOverride))
{
recv->assign(environmentOverride);
return true;
}
// ***************************
HKEY hkeyHive;
pal::string_t sub_key;
const pal::char_t* value;
get_dotnet_install_location_registry_path(&hkeyHive, &sub_key, &value);
// Must use RegOpenKeyEx to be able to specify KEY_WOW64_32KEY to access the 32-bit registry in all cases.
// The RegGetValue has this option available only on Win10.
HKEY hkey = NULL;
LSTATUS result = ::RegOpenKeyExW(hkeyHive, sub_key.c_str(), 0, KEY_READ | KEY_WOW64_32KEY, &hkey);
if (result != ERROR_SUCCESS)
{
trace::verbose(_X("Can't open the SDK installed location registry key, result: 0x%X"), result);
return false;
}
// Determine the size of the buffer
DWORD size = 0;
result = ::RegGetValueW(hkey, nullptr, value, RRF_RT_REG_SZ, nullptr, nullptr, &size);
if (result != ERROR_SUCCESS || size == 0)
{
trace::verbose(_X("Can't get the size of the SDK location registry value or it's empty, result: 0x%X"), result);
::RegCloseKey(hkey);
return false;
}
// Get the key's value
std::vector<pal::char_t> buffer(size/sizeof(pal::char_t));
result = ::RegGetValueW(hkey, nullptr, value, RRF_RT_REG_SZ, nullptr, &buffer[0], &size);
if (result != ERROR_SUCCESS)
{
trace::verbose(_X("Can't get the value of the SDK location registry value, result: 0x%X"), result);
::RegCloseKey(hkey);
return false;
}
recv->assign(buffer.data());
::RegCloseKey(hkey);
return true;
}
bool pal::get_global_dotnet_dirs(std::vector<pal::string_t>* dirs)
{
pal::string_t default_dir;
pal::string_t custom_dir;
bool dir_found = false;
if (pal::get_dotnet_self_registered_dir(&custom_dir))
{
remove_trailing_dir_seperator(&custom_dir);
dirs->push_back(custom_dir);
dir_found = true;
}
if (get_default_installation_dir(&default_dir))
{
remove_trailing_dir_seperator(&default_dir);
// Avoid duplicate global dirs.
if (!dir_found || !are_paths_equal_with_normalized_casing(custom_dir, default_dir))
{
dirs->push_back(default_dir);
dir_found = true;
}
}
return dir_found;
}
// To determine the OS version, we are going to use RtlGetVersion API
// since GetVersion call can be shimmed on Win8.1+.
typedef LONG (WINAPI *pFuncRtlGetVersion)(RTL_OSVERSIONINFOW *);
pal::string_t pal::get_current_os_rid_platform()
{
pal::string_t ridOS;
RTL_OSVERSIONINFOW osinfo;
// Init the buffer
ZeroMemory(&osinfo, sizeof(osinfo));
osinfo.dwOSVersionInfoSize = sizeof(osinfo);
HMODULE hmodNtdll = LoadLibraryA("ntdll.dll");
if (hmodNtdll != NULL)
{
pFuncRtlGetVersion pRtlGetVersion = (pFuncRtlGetVersion)GetProcAddress(hmodNtdll, "RtlGetVersion");
if (pRtlGetVersion)
{
if ((*pRtlGetVersion)(&osinfo) == 0)
{
// Win7 RID is the minimum supported version.
uint32_t majorVer = 6;
uint32_t minorVer = 1;
if (osinfo.dwMajorVersion > majorVer)
{
majorVer = osinfo.dwMajorVersion;
// Reset the minor version since we picked a different major version.
minorVer = 0;
}
if (osinfo.dwMinorVersion > minorVer)
{
minorVer = osinfo.dwMinorVersion;
}
if (majorVer == 6)
{
switch(minorVer)
{
case 1:
ridOS.append(_X("win7"));
break;
case 2:
ridOS.append(_X("win8"));
break;
case 3:
default:
// For unknown version, we will support the highest RID that we know for this major version.
ridOS.append(_X("win81"));
break;
}
}
else if (majorVer >= 10)
{
// Return the major version for use in RID computation without applying any cap.
ridOS.append(_X("win"));
ridOS.append(pal::to_string(majorVer));
}
}
}
}
return ridOS;
}
bool pal::is_path_rooted(const string_t& path)
{
return path.length() >= 2 && path[1] == L':';
}
// Returns true only if an env variable can be read successfully to be non-empty.
bool pal::getenv(const char_t* name, string_t* recv)
{
recv->clear();
auto length = ::GetEnvironmentVariableW(name, nullptr, 0);
if (length == 0)
{
auto err = GetLastError();
if (err != ERROR_ENVVAR_NOT_FOUND)
{
trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError()));
}
return false;
}
auto buf = new char_t[length];
if (::GetEnvironmentVariableW(name, buf, length) == 0)
{
trace::error(_X("Failed to read environment variable [%s], HRESULT: 0x%X"), name, HRESULT_FROM_WIN32(GetLastError()));
return false;
}
recv->assign(buf);
delete[] buf;
return true;
}
int pal::xtoi(const char_t* input)
{
return ::_wtoi(input);
}
bool pal::get_own_executable_path(string_t* recv)
{
return GetModuleFileNameWrapper(NULL, recv);
}
bool pal::get_current_module(dll_t *mod)
{
HMODULE hmod = nullptr;
if (!GetModuleHandleFromAddress(&get_current_module, &hmod))
return false;
*mod = (pal::dll_t)hmod;
return true;
}
bool pal::get_own_module_path(string_t* recv)
{
HMODULE hmod;
if (!GetModuleHandleFromAddress(&get_own_module_path, &hmod))
return false;
return GetModuleFileNameWrapper(hmod, recv);
}
bool pal::get_method_module_path(string_t* recv, void* method)
{
HMODULE hmod;
if (!GetModuleHandleFromAddress(method, &hmod))
return false;
return GetModuleFileNameWrapper(hmod, recv);
}
bool pal::get_module_path(dll_t mod, string_t* recv)
{
return GetModuleFileNameWrapper(mod, recv);
}
bool get_extraction_base_parent_directory(pal::string_t& directory)
{
const size_t max_len = MAX_PATH + 1;
pal::char_t temp_path[max_len];
size_t len = GetTempPathW(max_len, temp_path);
if (len == 0)
{
return false;
}
assert(len < max_len);
directory.assign(temp_path);
return pal::realpath(&directory);
}
bool pal::get_default_bundle_extraction_base_dir(pal::string_t& extraction_dir)
{
if (!get_extraction_base_parent_directory(extraction_dir))
{
trace::error(_X("Failed to determine default extraction location. Check if 'TMP' or 'TEMP' points to existing path."));
return false;
}
append_path(&extraction_dir, _X(".net"));
// Windows Temp-Path is already user-private.
if (realpath(&extraction_dir))
{
return true;
}
// Create the %TEMP%\.net directory
if (CreateDirectoryW(extraction_dir.c_str(), NULL) == 0 &&
GetLastError() != ERROR_ALREADY_EXISTS)
{
trace::error(_X("Failed to create default extraction directory [%s]. %s, error code: %d"), extraction_dir.c_str(), pal::strerror(errno).c_str(), GetLastError());
return false;
}
return realpath(&extraction_dir);
}
static bool wchar_convert_helper(DWORD code_page, const char* cstr, size_t len, pal::string_t* out)
{
out->clear();
// No need of explicit null termination, so pass in the actual length.
size_t size = ::MultiByteToWideChar(code_page, 0, cstr, static_cast<uint32_t>(len), nullptr, 0);
if (size == 0)
{
return false;
}
out->resize(size, '\0');
return ::MultiByteToWideChar(code_page, 0, cstr, static_cast<uint32_t>(len), &(*out)[0], static_cast<uint32_t>(out->size())) != 0;
}
bool pal::pal_utf8string(const pal::string_t& str, std::vector<char>* out)
{
out->clear();
// Pass -1 as we want explicit null termination in the char buffer.
size_t size = ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr);
if (size == 0)
{
return false;
}
out->resize(size, '\0');
return ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, out->data(), static_cast<uint32_t>(out->size()), nullptr, nullptr) != 0;
}
bool pal::pal_clrstring(const pal::string_t& str, std::vector<char>* out)
{
return pal_utf8string(str, out);
}
bool pal::clr_palstring(const char* cstr, pal::string_t* out)
{
return wchar_convert_helper(CP_UTF8, cstr, ::strlen(cstr), out);
}
// Return if path is valid and file exists, return true and adjust path as appropriate.
bool pal::realpath(string_t* path, bool skip_error_logging)
{
if (path->empty())
{
return false;
}
if (LongFile::IsNormalized(*path))
{
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(path->c_str(), GetFileExInfoStandard, &data) != 0)
{
return true;
}
}
char_t buf[MAX_PATH];
size_t size = ::GetFullPathNameW(path->c_str(), MAX_PATH, buf, nullptr);
if (size == 0)
{
if (!skip_error_logging)
{
trace::error(_X("Error resolving full path [%s]"), path->c_str());
}
return false;
}
string_t str;
if (size < MAX_PATH)
{
str.assign(buf);
}
else
{
str.resize(size + LongFile::UNCExtendedPathPrefix.length(), 0);
size = ::GetFullPathNameW(path->c_str(), static_cast<uint32_t>(size), (LPWSTR)str.data(), nullptr);
assert(size <= str.size());
if (size == 0)
{
if (!skip_error_logging)
{
trace::error(_X("Error resolving full path [%s]"), path->c_str());
}
return false;
}
const string_t* prefix = &LongFile::ExtendedPrefix;
//Check if the resolved path is a UNC. By default we assume relative path to resolve to disk
if (str.compare(0, LongFile::UNCPathPrefix.length(), LongFile::UNCPathPrefix) == 0)
{
prefix = &LongFile::UNCExtendedPathPrefix;
str.erase(0, LongFile::UNCPathPrefix.length());
size = size - LongFile::UNCPathPrefix.length();
}
str.insert(0, *prefix);
str.resize(size + prefix->length());
str.shrink_to_fit();
}
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesExW(str.c_str(), GetFileExInfoStandard, &data) != 0)
{
*path = str;
return true;
}
return false;
}
bool pal::file_exists(const string_t& path)
{
string_t tmp(path);
return pal::realpath(&tmp, true);
}
static void readdir(const pal::string_t& path, const pal::string_t& pattern, bool onlydirectories, std::vector<pal::string_t>* list)
{
assert(list != nullptr);
std::vector<pal::string_t>& files = *list;
pal::string_t normalized_path(path);
if (LongFile::ShouldNormalize(normalized_path))
{
if (!pal::realpath(&normalized_path))
{
return;
}
}
pal::string_t search_string(normalized_path);
append_path(&search_string, pattern.c_str());
WIN32_FIND_DATAW data = { 0 };
auto handle = ::FindFirstFileExW(search_string.c_str(), FindExInfoStandard, &data, FindExSearchNameMatch, NULL, 0);
if (handle == INVALID_HANDLE_VALUE)
{
return;
}
do
{
if (!onlydirectories || (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
pal::string_t filepath(data.cFileName);
if (filepath != _X(".") && filepath != _X(".."))
{
files.push_back(filepath);
}
}
} while (::FindNextFileW(handle, &data));
::FindClose(handle);
}
void pal::readdir(const string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, false, list);
}
void pal::readdir(const string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), false, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, const string_t& pattern, std::vector<pal::string_t>* list)
{
::readdir(path, pattern, true, list);
}
void pal::readdir_onlydirectories(const pal::string_t& path, std::vector<pal::string_t>* list)
{
::readdir(path, _X("*"), true, list);
}
bool pal::is_running_in_wow64()
{
BOOL fWow64Process = FALSE;
if (!IsWow64Process(GetCurrentProcess(), &fWow64Process))
{
return false;
}
return (fWow64Process != FALSE);
}
typedef BOOL (WINAPI* is_wow64_process2)(
HANDLE hProcess,
USHORT *pProcessMachine,
USHORT *pNativeMachine
);
bool pal::is_emulating_x64()
{
USHORT pProcessMachine, pNativeMachine;
auto kernel32 = LoadLibraryExW(L"kernel32.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
if (kernel32)
{
is_wow64_process2 isWow64Process2Func = (is_wow64_process2)GetProcAddress(kernel32, "IsWow64Process2");
if (!isWow64Process2Func)
{
// Could not find IsWow64Process2.
return false;
}
if (!isWow64Process2Func(GetCurrentProcess(), &pProcessMachine, &pNativeMachine))
{
// IsWow64Process2 failed. Log the error and continue.
trace::info(_X("Call to IsWow64Process2 failed: %s"), GetLastError());
return false;
}
// Check if we are running an x64 process on a non-x64 windows machine.
return pProcessMachine != pNativeMachine && pProcessMachine == IMAGE_FILE_MACHINE_AMD64;
}
// Loading kernel32.dll failed, log the error and continue.
trace::info(_X("Could not load 'kernel32.dll': %s"), GetLastError());
return false;
}
bool pal::are_paths_equal_with_normalized_casing(const string_t& path1, const string_t& path2)
{
// On Windows, paths are case-insensitive
return (strcasecmp(path1.c_str(), path2.c_str()) == 0);
}
pal::mutex_t::mutex_t()
: _impl{ }
{
::InitializeCriticalSection(&_impl);
}
pal::mutex_t::~mutex_t()
{
::DeleteCriticalSection(&_impl);
}
void pal::mutex_t::lock()
{
::EnterCriticalSection(&_impl);
}
void pal::mutex_t::unlock()
{
::LeaveCriticalSection(&_impl);
}
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/hostmisc/trace.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "trace.h"
#include <mutex>
// g_trace_verbosity is used to encode COREHOST_TRACE and COREHOST_TRACE_VERBOSITY to selectively control output of
// trace::warn(), trace::info(), and trace::verbose()
// COREHOST_TRACE=0 COREHOST_TRACE_VERBOSITY=N/A implies g_trace_verbosity = 0. // Trace "disabled". error() messages will be produced.
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=4 or unset implies g_trace_verbosity = 4. // Trace "enabled". verbose(), info(), warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=3 implies g_trace_verbosity = 3. // Trace "enabled". info(), warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=2 implies g_trace_verbosity = 2. // Trace "enabled". warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=1 implies g_trace_verbosity = 1. // Trace "enabled". error() messages will be produced
static int g_trace_verbosity = 0;
static FILE * g_trace_file = stderr;
static pal::mutex_t g_trace_mutex;
thread_local static trace::error_writer_fn g_error_writer = nullptr;
//
// Turn on tracing for the corehost based on "COREHOST_TRACE" & "COREHOST_TRACEFILE" env.
//
void trace::setup()
{
// Read trace environment variable
pal::string_t trace_str;
if (!pal::getenv(_X("COREHOST_TRACE"), &trace_str))
{
return;
}
auto trace_val = pal::xtoi(trace_str.c_str());
if (trace_val > 0)
{
if (trace::enable())
{
auto ts = pal::get_timestamp();
trace::info(_X("Tracing enabled @ %s"), ts.c_str());
}
}
}
bool trace::enable()
{
bool file_open_error = false;
pal::string_t tracefile_str;
if (g_trace_verbosity)
{
return false;
}
else
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
g_trace_file = stderr;
if (pal::getenv(_X("COREHOST_TRACEFILE"), &tracefile_str))
{
FILE *tracefile = pal::file_open(tracefile_str, _X("a"));
if (tracefile)
{
setvbuf(tracefile, nullptr, _IONBF, 0);
g_trace_file = tracefile;
}
else
{
file_open_error = true;
}
}
pal::string_t trace_str;
if (!pal::getenv(_X("COREHOST_TRACE_VERBOSITY"), &trace_str))
{
g_trace_verbosity = 4; // Verbose trace by default
}
else
{
g_trace_verbosity = pal::xtoi(trace_str.c_str());
}
}
if (file_open_error)
{
trace::error(_X("Unable to open COREHOST_TRACEFILE=%s for writing"), tracefile_str.c_str());
}
return true;
}
bool trace::is_enabled()
{
return g_trace_verbosity;
}
void trace::verbose(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 3)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::info(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 2)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::error(const pal::char_t* format, ...)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
// Always print errors
va_list args;
va_start(args, format);
va_list trace_args;
va_copy(trace_args, args);
va_list dup_args;
va_copy(dup_args, args);
int count = pal::str_vprintf(nullptr, 0, format, args) + 1;
std::vector<pal::char_t> buffer(count);
pal::str_vprintf(&buffer[0], count, format, dup_args);
if (g_error_writer == nullptr)
{
pal::err_fputs(buffer.data());
}
else
{
g_error_writer(buffer.data());
}
#if defined(_WIN32)
::OutputDebugStringW(buffer.data());
#endif
if (g_trace_verbosity && ((g_trace_file != stderr) || g_error_writer != nullptr))
{
pal::file_vprintf(g_trace_file, format, trace_args);
}
va_end(args);
}
void trace::println(const pal::char_t* format, ...)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::out_vprintf(format, args);
va_end(args);
}
void trace::println()
{
println(_X(""));
}
void trace::warning(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 1)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::flush()
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
pal::file_flush(g_trace_file);
pal::err_flush();
pal::out_flush();
}
trace::error_writer_fn trace::set_error_writer(trace::error_writer_fn error_writer)
{
// No need for locking since g_error_writer is thread local.
error_writer_fn previous_writer = g_error_writer;
g_error_writer = error_writer;
return previous_writer;
}
trace::error_writer_fn trace::get_error_writer()
{
// No need for locking since g_error_writer is thread local.
return g_error_writer;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "trace.h"
#include <mutex>
// g_trace_verbosity is used to encode COREHOST_TRACE and COREHOST_TRACE_VERBOSITY to selectively control output of
// trace::warn(), trace::info(), and trace::verbose()
// COREHOST_TRACE=0 COREHOST_TRACE_VERBOSITY=N/A implies g_trace_verbosity = 0. // Trace "disabled". error() messages will be produced.
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=4 or unset implies g_trace_verbosity = 4. // Trace "enabled". verbose(), info(), warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=3 implies g_trace_verbosity = 3. // Trace "enabled". info(), warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=2 implies g_trace_verbosity = 2. // Trace "enabled". warn() and error() messages will be produced
// COREHOST_TRACE=1 COREHOST_TRACE_VERBOSITY=1 implies g_trace_verbosity = 1. // Trace "enabled". error() messages will be produced
static int g_trace_verbosity = 0;
static FILE * g_trace_file = stderr;
static pal::mutex_t g_trace_mutex;
thread_local static trace::error_writer_fn g_error_writer = nullptr;
//
// Turn on tracing for the corehost based on "COREHOST_TRACE" & "COREHOST_TRACEFILE" env.
//
void trace::setup()
{
// Read trace environment variable
pal::string_t trace_str;
if (!pal::getenv(_X("COREHOST_TRACE"), &trace_str))
{
return;
}
auto trace_val = pal::xtoi(trace_str.c_str());
if (trace_val > 0)
{
if (trace::enable())
{
auto ts = pal::get_timestamp();
trace::info(_X("Tracing enabled @ %s"), ts.c_str());
}
}
}
bool trace::enable()
{
bool file_open_error = false;
pal::string_t tracefile_str;
if (g_trace_verbosity)
{
return false;
}
else
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
g_trace_file = stderr;
if (pal::getenv(_X("COREHOST_TRACEFILE"), &tracefile_str))
{
FILE *tracefile = pal::file_open(tracefile_str, _X("a"));
if (tracefile)
{
setvbuf(tracefile, nullptr, _IONBF, 0);
g_trace_file = tracefile;
}
else
{
file_open_error = true;
}
}
pal::string_t trace_str;
if (!pal::getenv(_X("COREHOST_TRACE_VERBOSITY"), &trace_str))
{
g_trace_verbosity = 4; // Verbose trace by default
}
else
{
g_trace_verbosity = pal::xtoi(trace_str.c_str());
}
}
if (file_open_error)
{
trace::error(_X("Unable to open COREHOST_TRACEFILE=%s for writing"), tracefile_str.c_str());
}
return true;
}
bool trace::is_enabled()
{
return g_trace_verbosity;
}
void trace::verbose(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 3)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::info(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 2)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::error(const pal::char_t* format, ...)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
// Always print errors
va_list args;
va_start(args, format);
va_list trace_args;
va_copy(trace_args, args);
va_list dup_args;
va_copy(dup_args, args);
int count = pal::strlen_vprintf(format, args) + 1;
std::vector<pal::char_t> buffer(count);
pal::str_vprintf(&buffer[0], count, format, dup_args);
if (g_error_writer == nullptr)
{
pal::err_fputs(buffer.data());
}
else
{
g_error_writer(buffer.data());
}
#if defined(_WIN32)
::OutputDebugStringW(buffer.data());
#endif
if (g_trace_verbosity && ((g_trace_file != stderr) || g_error_writer != nullptr))
{
pal::file_vprintf(g_trace_file, format, trace_args);
}
va_end(args);
}
void trace::println(const pal::char_t* format, ...)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::out_vprintf(format, args);
va_end(args);
}
void trace::println()
{
println(_X(""));
}
void trace::warning(const pal::char_t* format, ...)
{
if (g_trace_verbosity > 1)
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
va_list args;
va_start(args, format);
pal::file_vprintf(g_trace_file, format, args);
va_end(args);
}
}
void trace::flush()
{
std::lock_guard<pal::mutex_t> lock(g_trace_mutex);
pal::file_flush(g_trace_file);
pal::err_flush();
pal::out_flush();
}
trace::error_writer_fn trace::set_error_writer(trace::error_writer_fn error_writer)
{
// No need for locking since g_error_writer is thread local.
error_writer_fn previous_writer = g_error_writer;
g_error_writer = error_writer;
return previous_writer;
}
trace::error_writer_fn trace::get_error_writer()
{
// No need for locking since g_error_writer is thread local.
return g_error_writer;
}
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/json_parser.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// These are only used by rapidjson/error/en.h to declare the error messages,
// and have to be set to these values before any files are included. They're
// defined here because it's the only place that calls GetParseError().
#undef RAPIDJSON_ERROR_CHARTYPE
#undef RAPIDJSON_ERROR_STRING
#define RAPIDJSON_ERROR_CHARTYPE pal::char_t
#define RAPIDJSON_ERROR_STRING(x) _X(x)
#include <json_parser.h>
#include <external/rapidjson/error/en.h>
#include "utils.h"
#include <cassert>
#include <cstdint>
namespace {
// Try to match 0xEF 0xBB 0xBF byte sequence (no endianness here.)
std::streampos get_utf8_bom_length(pal::istream_t& stream)
{
if (stream.eof())
{
return 0;
}
auto peeked = stream.peek();
if (peeked == EOF || ((peeked & 0xFF) != 0xEF))
{
return 0;
}
unsigned char bytes[3];
stream.read(reinterpret_cast<char*>(bytes), 3);
if ((stream.gcount() < 3) || (bytes[1] != 0xBB) || (bytes[2] != 0xBF))
{
return 0;
}
return 3;
}
void get_line_column_from_offset(const char* data, uint64_t size, size_t offset, int *line, int *column)
{
assert(offset < size);
*line = *column = 1;
for (size_t i = 0; i < offset; i++)
{
(*column)++;
if (data[i] == '\n')
{
(*line)++;
*column = 1;
}
else if (data[i] == '\r' && data[i + 1] == '\n')
{
(*line)++;
*column = 1;
i++; // Discard carriage return
}
}
}
} // empty namespace
void json_parser_t::realloc_buffer(size_t size)
{
m_json.resize(size + 1);
m_json[size] = '\0';
}
bool json_parser_t::parse_raw_data(char* data, int64_t size, const pal::string_t& context)
{
assert(data != nullptr);
constexpr auto flags = rapidjson::ParseFlag::kParseStopWhenDoneFlag | rapidjson::ParseFlag::kParseCommentsFlag;
#ifdef _WIN32
// Can't use in-situ parsing on Windows, as JSON data is encoded in
// UTF-8 and the host expects wide strings. m_document will store
// data in UTF-16 (with pal::char_t as the character type), but it
// has to know that data is encoded in UTF-8 to convert during parsing.
m_document.Parse<flags, rapidjson::UTF8<>>(data);
#else // _WIN32
m_document.ParseInsitu<flags>(data);
#endif // _WIN32
if (m_document.HasParseError())
{
int line, column;
size_t offset = m_document.GetErrorOffset();
get_line_column_from_offset(data, size, offset, &line, &column);
trace::error(_X("A JSON parsing exception occurred in [%s], offset %zu (line %d, column %d): %s"),
context.c_str(), offset, line, column,
rapidjson::GetParseError_En(m_document.GetParseError()));
return false;
}
if (!m_document.IsObject())
{
trace::error(_X("Expected a JSON object in [%s]"), context.c_str());
return false;
}
return true;
}
bool json_parser_t::parse_file(const pal::string_t& path)
{
// This code assumes that the caller has checked that the file `path` exists
// either within the bundle, or as a real file on disk.
assert(m_bundle_data == nullptr);
assert(m_bundle_location == nullptr);
if (bundle::info_t::is_single_file_bundle())
{
// Due to in-situ parsing on Linux,
// * The json file is mapped as copy-on-write.
// * The mapping cannot be immediately released, and will be unmapped by the json_parser destructor.
m_bundle_data = bundle::info_t::config_t::map(path, m_bundle_location);
if (m_bundle_data != nullptr)
{
bool result = parse_raw_data(m_bundle_data, m_bundle_location->size, path);
return result;
}
}
pal::ifstream_t file{ path };
if (!file.good())
{
trace::error(_X("Cannot use file stream for [%s]: %s"), path.c_str(), pal::strerror(errno));
return false;
}
auto current_pos = ::get_utf8_bom_length(file);
file.seekg(0, file.end);
auto stream_size = file.tellg();
if (stream_size == -1)
{
trace::error(_X("Failed to get size of file [%s]"), path.c_str());
return false;
}
file.seekg(current_pos, file.beg);
realloc_buffer(static_cast<size_t>(stream_size - current_pos));
file.read(m_json.data(), stream_size - current_pos);
return parse_raw_data(m_json.data(), m_json.size(), path);
}
json_parser_t::~json_parser_t()
{
if (m_bundle_data != nullptr)
{
bundle::info_t::config_t::unmap(m_bundle_data, m_bundle_location);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// These are only used by rapidjson/error/en.h to declare the error messages,
// and have to be set to these values before any files are included. They're
// defined here because it's the only place that calls GetParseError().
#undef RAPIDJSON_ERROR_CHARTYPE
#undef RAPIDJSON_ERROR_STRING
#define RAPIDJSON_ERROR_CHARTYPE pal::char_t
#define RAPIDJSON_ERROR_STRING(x) _X(x)
#include <json_parser.h>
#include <external/rapidjson/error/en.h>
#include "utils.h"
#include <cassert>
#include <cstdint>
namespace {
// Try to match 0xEF 0xBB 0xBF byte sequence (no endianness here.)
std::streampos get_utf8_bom_length(pal::istream_t& stream)
{
if (stream.eof())
{
return 0;
}
auto peeked = stream.peek();
if (peeked == EOF || ((peeked & 0xFF) != 0xEF))
{
return 0;
}
unsigned char bytes[3];
stream.read(reinterpret_cast<char*>(bytes), 3);
if ((stream.gcount() < 3) || (bytes[1] != 0xBB) || (bytes[2] != 0xBF))
{
return 0;
}
return 3;
}
void get_line_column_from_offset(const char* data, uint64_t size, size_t offset, int *line, int *column)
{
assert(offset < size);
*line = *column = 1;
for (size_t i = 0; i < offset; i++)
{
(*column)++;
if (data[i] == '\n')
{
(*line)++;
*column = 1;
}
else if (data[i] == '\r' && data[i + 1] == '\n')
{
(*line)++;
*column = 1;
i++; // Discard carriage return
}
}
}
} // empty namespace
void json_parser_t::realloc_buffer(size_t size)
{
m_json.resize(size + 1);
m_json[size] = '\0';
}
bool json_parser_t::parse_raw_data(char* data, int64_t size, const pal::string_t& context)
{
assert(data != nullptr);
constexpr auto flags = rapidjson::ParseFlag::kParseStopWhenDoneFlag | rapidjson::ParseFlag::kParseCommentsFlag;
#ifdef _WIN32
// Can't use in-situ parsing on Windows, as JSON data is encoded in
// UTF-8 and the host expects wide strings. m_document will store
// data in UTF-16 (with pal::char_t as the character type), but it
// has to know that data is encoded in UTF-8 to convert during parsing.
m_document.Parse<flags, rapidjson::UTF8<>>(data);
#else // _WIN32
m_document.ParseInsitu<flags>(data);
#endif // _WIN32
if (m_document.HasParseError())
{
int line, column;
size_t offset = m_document.GetErrorOffset();
get_line_column_from_offset(data, size, offset, &line, &column);
trace::error(_X("A JSON parsing exception occurred in [%s], offset %zu (line %d, column %d): %s"),
context.c_str(), offset, line, column,
rapidjson::GetParseError_En(m_document.GetParseError()));
return false;
}
if (!m_document.IsObject())
{
trace::error(_X("Expected a JSON object in [%s]"), context.c_str());
return false;
}
return true;
}
bool json_parser_t::parse_file(const pal::string_t& path)
{
// This code assumes that the caller has checked that the file `path` exists
// either within the bundle, or as a real file on disk.
assert(m_bundle_data == nullptr);
assert(m_bundle_location == nullptr);
if (bundle::info_t::is_single_file_bundle())
{
// Due to in-situ parsing on Linux,
// * The json file is mapped as copy-on-write.
// * The mapping cannot be immediately released, and will be unmapped by the json_parser destructor.
m_bundle_data = bundle::info_t::config_t::map(path, m_bundle_location);
if (m_bundle_data != nullptr)
{
bool result = parse_raw_data(m_bundle_data, m_bundle_location->size, path);
return result;
}
}
pal::ifstream_t file{ path };
if (!file.good())
{
trace::error(_X("Cannot use file stream for [%s]: %s"), path.c_str(), pal::strerror(errno).c_str());
return false;
}
auto current_pos = ::get_utf8_bom_length(file);
file.seekg(0, file.end);
auto stream_size = file.tellg();
if (stream_size == -1)
{
trace::error(_X("Failed to get size of file [%s]"), path.c_str());
return false;
}
file.seekg(current_pos, file.beg);
realloc_buffer(static_cast<size_t>(stream_size - current_pos));
file.read(m_json.data(), stream_size - current_pos);
return parse_raw_data(m_json.data(), m_json.size(), path);
}
json_parser_t::~json_parser_t()
{
if (m_bundle_data != nullptr)
{
bundle::info_t::config_t::unmap(m_bundle_data, m_bundle_location);
}
}
| 1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/Interop/PInvoke/Delegate/DelegateAsInterfaceTestNative.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
namespace
{
HRESULT InvokeDelegate(IDispatch* dele, VARIANT* pResult)
{
HRESULT hr;
BSTR bstrName = SysAllocString(L"DynamicInvoke");
DISPID dispid = 0;
hr = dele->GetIDsOfNames(
IID_NULL,
&bstrName,
1,
GetUserDefaultLCID(),
&dispid);
SysFreeString(bstrName);
if (FAILED(hr))
{
printf("\nERROR: Invoke failed: 0x%x\n", (unsigned int)hr);
return hr;
}
DISPPARAMS params = { NULL, NULL, 0, 0 };
VariantInit(pResult);
hr = dele->Invoke(
dispid,
IID_NULL,
GetUserDefaultLCID(),
DISPATCH_METHOD,
¶ms,
pResult,
NULL,
NULL);
return hr;
}
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpected(int i, IDispatch* delegate)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(delegate, &pRetVal);
return SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpectedAndClear(int i, IDispatch** delegate)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(*delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
(*delegate)->Release();
*delegate = nullptr;
return result;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE DuplicateDelegate(int i, IDispatch* delegateIn, IDispatch** delegateOut)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(delegateIn, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
delegateIn->AddRef();
*delegateOut = delegateIn;
return result;
}
extern "C" DLL_EXPORT IDispatch* STDMETHODCALLTYPE DuplicateDelegateReturned(IDispatch* delegateIn)
{
delegateIn->AddRef();
return delegateIn;
}
struct DispatchDelegateWithExpectedValue
{
int expected;
IDispatch* delegate;
};
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateStructDelegateValueMatchesExpected(DispatchDelegateWithExpectedValue dispatch)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatch.delegate, &pRetVal);
return SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatch.expected ? TRUE : FALSE;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpectedAndClearStruct(DispatchDelegateWithExpectedValue* dispatch)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatch->delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatch->expected ? TRUE : FALSE;
dispatch->delegate->Release();
dispatch->delegate = nullptr;
return result;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE DuplicateStruct(DispatchDelegateWithExpectedValue dispatchIn, DispatchDelegateWithExpectedValue* dispatchOut)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatchIn.delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatchIn.expected ? TRUE : FALSE;
dispatchIn.delegate->AddRef();
dispatchOut->delegate = dispatchIn.delegate;
dispatchOut->expected = dispatchIn.expected;
return result;
}
extern "C" DLL_EXPORT void* Invalid(...)
{
return nullptr;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
namespace
{
HRESULT InvokeDelegate(IDispatch* dele, VARIANT* pResult)
{
HRESULT hr;
BSTR bstrName = SysAllocString(L"DynamicInvoke");
DISPID dispid = 0;
hr = dele->GetIDsOfNames(
IID_NULL,
&bstrName,
1,
GetUserDefaultLCID(),
&dispid);
SysFreeString(bstrName);
if (FAILED(hr))
{
printf("\nERROR: Invoke failed: 0x%x\n", (unsigned int)hr);
return hr;
}
DISPPARAMS params = { NULL, NULL, 0, 0 };
VariantInit(pResult);
hr = dele->Invoke(
dispid,
IID_NULL,
GetUserDefaultLCID(),
DISPATCH_METHOD,
¶ms,
pResult,
NULL,
NULL);
return hr;
}
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpected(int i, IDispatch* delegate)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(delegate, &pRetVal);
return SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpectedAndClear(int i, IDispatch** delegate)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(*delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
(*delegate)->Release();
*delegate = nullptr;
return result;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE DuplicateDelegate(int i, IDispatch* delegateIn, IDispatch** delegateOut)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(delegateIn, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == i ? TRUE : FALSE;
delegateIn->AddRef();
*delegateOut = delegateIn;
return result;
}
extern "C" DLL_EXPORT IDispatch* STDMETHODCALLTYPE DuplicateDelegateReturned(IDispatch* delegateIn)
{
delegateIn->AddRef();
return delegateIn;
}
struct DispatchDelegateWithExpectedValue
{
int expected;
IDispatch* delegate;
};
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateStructDelegateValueMatchesExpected(DispatchDelegateWithExpectedValue dispatch)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatch.delegate, &pRetVal);
return SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatch.expected ? TRUE : FALSE;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE ValidateDelegateValueMatchesExpectedAndClearStruct(DispatchDelegateWithExpectedValue* dispatch)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatch->delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatch->expected ? TRUE : FALSE;
dispatch->delegate->Release();
dispatch->delegate = nullptr;
return result;
}
extern "C" DLL_EXPORT BOOL STDMETHODCALLTYPE DuplicateStruct(DispatchDelegateWithExpectedValue dispatchIn, DispatchDelegateWithExpectedValue* dispatchOut)
{
VARIANT pRetVal;
HRESULT hr = InvokeDelegate(dispatchIn.delegate, &pRetVal);
BOOL result = SUCCEEDED(hr) && V_VT(&pRetVal) == VT_I4 && V_I4(&pRetVal) == dispatchIn.expected ? TRUE : FALSE;
dispatchIn.delegate->AddRef();
dispatchOut->delegate = dispatchIn.delegate;
dispatchOut->expected = dispatchIn.expected;
return result;
}
extern "C" DLL_EXPORT void* Invalid(...)
{
return nullptr;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/md/runtime/mdinternalro.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// MDInternalRO.h
//
//
// Contains utility code for MD directory
//
//*****************************************************************************
#ifndef __MDInternalRO__h__
#define __MDInternalRO__h__
#include "metamodel.h"
#ifdef FEATURE_METADATA_INTERNAL_APIS
class MDInternalRO : public IMDInternalImport, IMDCommon
{
public:
MDInternalRO();
virtual ~MDInternalRO();
__checkReturn
HRESULT Init(LPVOID pData, ULONG cbData);
// *** IUnknown methods ***
__checkReturn
STDMETHODIMP QueryInterface(REFIID riid, void** ppv);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
__checkReturn
STDMETHODIMP TranslateSigWithScope(
IMDInternalImport *pAssemImport, // [IN] import assembly scope.
const void *pbHashValue, // [IN] hash value for the import assembly.
ULONG cbHashValue, // [IN] count of bytes in the hash value.
PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope
ULONG cbSigBlob, // [IN] count of bytes of signature
IMetaDataAssemblyEmit *pAssemEmit, // [IN] assembly emit scope.
IMetaDataEmit *emit, // [IN] emit interface
CQuickBytes *pqkSigEmit, // [OUT] buffer to hold translated signature
ULONG *pcbSig) // [OUT] count of bytes in the translated signature
DAC_UNEXPECTED();
__checkReturn
STDMETHODIMP GetTypeDefRefTokenInTypeSpec(// return S_FALSE if enclosing type does not have a token
mdTypeSpec tkTypeSpec, // [IN] TypeSpec token to look at
mdToken *tkEnclosedToken); // [OUT] The enclosed type token
STDMETHODIMP_(IMetaModelCommon*) GetMetaModelCommon()
{
return static_cast<IMetaModelCommon*>(&m_LiteWeightStgdb.m_MiniMd);
}
STDMETHODIMP_(IMetaModelCommonRO*) GetMetaModelCommonRO()
{
if (m_LiteWeightStgdb.m_MiniMd.IsWritable())
{
_ASSERTE(!"IMetaModelCommonRO methods cannot be used because this importer is writable.");
return NULL;
}
return static_cast<IMetaModelCommonRO*>(&m_LiteWeightStgdb.m_MiniMd);
}
__checkReturn
STDMETHODIMP SetOptimizeAccessForSpeed(
BOOL fOptSpeed)
{
return S_OK;
}
//*****************************************************************************
// return the count of entries of a given kind in a scope
// For example, pass in mdtMethodDef will tell you how many MethodDef
// contained in a scope
//*****************************************************************************
STDMETHODIMP_(ULONG) GetCountWithTokenKind(// return hresult
DWORD tkKind) // [IN] pass in the kind of token.
DAC_UNEXPECTED();
//*****************************************************************************
// enumerator for typedef
//*****************************************************************************
__checkReturn
STDMETHODIMP EnumTypeDefInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
//*****************************************************************************
// enumerator for MethodImpl
//*****************************************************************************
__checkReturn
STDMETHODIMP EnumMethodImplInit( // return hresult
mdTypeDef td, // [IN] TypeDef over which to scope the enumeration.
HENUMInternal *phEnumBody, // [OUT] buffer to fill for enumerator data for MethodBody tokens.
HENUMInternal *phEnumDecl); // [OUT] buffer to fill for enumerator data for MethodDecl tokens.
STDMETHODIMP_(ULONG) EnumMethodImplGetCount(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
STDMETHODIMP_(void) EnumMethodImplReset(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
__checkReturn
STDMETHODIMP EnumMethodImplNext( // return hresult
HENUMInternal *phEnumBody, // [IN] input enum for MethodBody
HENUMInternal *phEnumDecl, // [IN] input enum for MethodDecl
mdToken *ptkBody, // [OUT] return token for MethodBody
mdToken *ptkDecl); // [OUT] return token for MethodDecl
STDMETHODIMP_(void) EnumMethodImplClose(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
//*****************************************
// Enumerator helpers for memberdef, memberref, interfaceimp,
// event, property, param, methodimpl
//*****************************************
__checkReturn
STDMETHODIMP EnumGlobalFunctionsInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
__checkReturn
STDMETHODIMP EnumGlobalFieldsInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
__checkReturn
STDMETHODIMP EnumInit( // return S_FALSE if record not found
DWORD tkKind, // [IN] which table to work on
mdToken tkParent, // [IN] token to scope the search
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP EnumAllInit( // return S_FALSE if record not found
DWORD tkKind, // [IN] which table to work on
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP EnumCustomAttributeByNameInit(// return S_FALSE if record not found
mdToken tkParent, // [IN] token to scope the search
LPCSTR szName, // [IN] CustomAttribute's name to scope the search
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP GetParentToken(
mdToken tkChild, // [IN] given child token
mdToken *ptkParent); // [OUT] returning parent
__checkReturn
STDMETHODIMP GetCustomAttributeProps(
mdCustomAttribute at, // [IN] The attribute.
mdToken *ptkType); // [OUT] Put attribute type here.
__checkReturn
STDMETHODIMP GetCustomAttributeAsBlob(
mdCustomAttribute cv, // [IN] given custom attribute token
void const **ppBlob, // [OUT] return the pointer to internal blob
ULONG *pcbSize); // [OUT] return the size of the blob
__checkReturn
STDMETHODIMP GetCustomAttributeByName( // S_OK or error.
mdToken tkObj, // [IN] Object with Custom Attribute.
LPCUTF8 szName, // [IN] Name of desired Custom Attribute.
const void **ppData, // [OUT] Put pointer to data here.
ULONG *pcbData); // [OUT] Put size of data here.
__checkReturn
STDMETHODIMP GetNameOfCustomAttribute( // S_OK or error.
mdCustomAttribute mdAttribute, // [IN] The Custom Attribute
LPCUTF8 *pszNamespace, // [OUT] Namespace of Custom Attribute.
LPCUTF8 *pszName); // [OUT] Name of Custom Attribute.
__checkReturn
STDMETHODIMP GetScopeProps(
LPCSTR *pszName, // [OUT] scope name
GUID *pmvid); // [OUT] version id
// finding a particular method
__checkReturn
STDMETHODIMP FindMethodDef(
mdTypeDef classdef, // [IN] given typedef
LPCSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of COM+ signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdMethodDef *pmd); // [OUT] matching memberdef
// return a iSeq's param given a MethodDef
__checkReturn
STDMETHODIMP FindParamOfMethod( // S_OK or error.
mdMethodDef md, // [IN] The owning method of the param.
ULONG iSeq, // [IN] The sequence # of the param.
mdParamDef *pparamdef); // [OUT] Put ParamDef token here.
//*****************************************
//
// GetName* functions
//
//*****************************************
// return the name and namespace of typedef
__checkReturn
STDMETHODIMP GetNameOfTypeDef(
mdTypeDef classdef, // given classdef
LPCSTR *pszname, // return class name(unqualified)
LPCSTR *psznamespace); // return the name space name
__checkReturn
STDMETHODIMP GetIsDualOfTypeDef(
mdTypeDef classdef, // [IN] given classdef.
ULONG *pDual); // [OUT] return dual flag here.
__checkReturn
STDMETHODIMP GetIfaceTypeOfTypeDef(
mdTypeDef classdef, // [IN] given classdef.
ULONG *pIface); // [OUT] 0=dual, 1=vtable, 2=dispinterface
// get the name of either methoddef
__checkReturn
STDMETHODIMP GetNameOfMethodDef( // return the name of the memberdef in UTF8
mdMethodDef md, // given memberdef
LPCSTR *pszName);
__checkReturn
STDMETHODIMP GetNameAndSigOfMethodDef(
mdMethodDef methoddef, // [IN] given memberdef
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of COM+ signature
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
LPCSTR *pszName);
// return the name of a FieldDef
__checkReturn
STDMETHODIMP GetNameOfFieldDef(
mdFieldDef fd, // given memberdef
LPCSTR *pszName);
// return the name of typeref
__checkReturn
STDMETHODIMP GetNameOfTypeRef(
mdTypeRef classref, // [IN] given typeref
LPCSTR *psznamespace, // [OUT] return typeref name
LPCSTR *pszname); // [OUT] return typeref namespace
// return the resolutionscope of typeref
__checkReturn
STDMETHODIMP GetResolutionScopeOfTypeRef(
mdTypeRef classref, // given classref
mdToken *ptkResolutionScope);
// return the typeref token given the name.
__checkReturn
STDMETHODIMP FindTypeRefByName(
LPCSTR szNamespace, // [IN] Namespace for the TypeRef.
LPCSTR szName, // [IN] Name of the TypeRef.
mdToken tkResolutionScope, // [IN] Resolution Scope fo the TypeRef.
mdTypeRef *ptk); // [OUT] TypeRef token returned.
// return the TypeDef properties
__checkReturn
STDMETHODIMP GetTypeDefProps( // return hresult
mdTypeDef classdef, // given classdef
DWORD *pdwAttr, // return flags on class, tdPublic, tdAbstract
mdToken *ptkExtends); // [OUT] Put base class TypeDef/TypeRef here.
// return the item's guid
__checkReturn
STDMETHODIMP GetItemGuid( // return hresult
mdToken tkObj, // [IN] given item.
CLSID *pGuid); // [OUT] Put guid here.
// get enclosing class of NestedClass.
__checkReturn
STDMETHODIMP GetNestedClassProps( // S_OK or error
mdTypeDef tkNestedClass, // [IN] NestedClass token.
mdTypeDef *ptkEnclosingClass); // [OUT] EnclosingClass token.
// Get count of Nested classes given the enclosing class.
__checkReturn
STDMETHODIMP GetCountNestedClasses( // return count of Nested classes.
mdTypeDef tkEnclosingClass, // [IN]Enclosing class.
ULONG *pcNestedClassesCount);
// Return array of Nested classes given the enclosing class.
__checkReturn
STDMETHODIMP GetNestedClasses( // Return actual count.
mdTypeDef tkEnclosingClass, // [IN] Enclosing class.
mdTypeDef *rNestedClasses, // [OUT] Array of nested class tokens.
ULONG ulNestedClasses, // [IN] Size of array.
ULONG *pcNestedClasses);
// return the ModuleRef properties
__checkReturn
STDMETHODIMP GetModuleRefProps(
mdModuleRef mur, // [IN] moduleref token
LPCSTR *pszName); // [OUT] buffer to fill with the moduleref name
//*****************************************
//
// GetSig* functions
//
//*****************************************
__checkReturn
STDMETHODIMP GetSigOfMethodDef(
mdMethodDef methoddef, // [IN] given memberdef
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
PCCOR_SIGNATURE *ppSig);
__checkReturn
STDMETHODIMP GetSigOfFieldDef(
mdMethodDef methoddef, // [IN] given memberdef
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
PCCOR_SIGNATURE *ppSig);
__checkReturn
STDMETHODIMP GetSigFromToken(
mdToken tk, // FieldDef, MethodDef, Signature or TypeSpec token
ULONG * pcbSig,
PCCOR_SIGNATURE * ppSig);
//*****************************************
// get method property
//*****************************************
__checkReturn
STDMETHODIMP GetMethodDefProps(
mdMethodDef md, // The method for which to get props.
DWORD *pdwFlags);
__checkReturn
STDMETHODIMP_(ULONG) GetMethodDefSlot(
mdMethodDef mb); // The method for which to get props.
//*****************************************
// return method implementation informaiton, like RVA and implflags
//*****************************************
__checkReturn
STDMETHODIMP GetMethodImplProps(
mdMethodDef tk, // [IN] MethodDef
ULONG *pulCodeRVA, // [OUT] CodeRVA
DWORD *pdwImplFlags); // [OUT] Impl. Flags
//*****************************************************************************
// return the field RVA
//*****************************************************************************
__checkReturn
STDMETHODIMP GetFieldRVA(
mdToken fd, // [IN] FieldDef
ULONG *pulCodeRVA); // [OUT] CodeRVA
//*****************************************************************************
// return the field offset for a given field
//*****************************************************************************
__checkReturn
STDMETHODIMP GetFieldOffset(
mdFieldDef fd, // [IN] fielddef
ULONG *pulOffset); // [OUT] FieldOffset
//*****************************************
// get field property
//*****************************************
__checkReturn
STDMETHODIMP GetFieldDefProps(
mdFieldDef fd, // [IN] given fielddef
DWORD *pdwFlags); // [OUT] return fdPublic, fdPrive, etc flags
//*****************************************************************************
// return default value of a token (could be paramdef, fielddef, or property)
//*****************************************************************************
__checkReturn
STDMETHODIMP GetDefaultValue(
mdToken tk, // [IN] given FieldDef, ParamDef, or Property
MDDefaultValue *pDefaultValue); // [OUT] default value to fill
//*****************************************
// get dispid of a MethodDef or a FieldDef
//*****************************************
__checkReturn
STDMETHODIMP GetDispIdOfMemberDef( // return hresult
mdToken tk, // [IN] given methoddef or fielddef
ULONG *pDispid); // [OUT] Put the dispid here.
//*****************************************
// return TypeRef/TypeDef given an InterfaceImpl token
//*****************************************
__checkReturn
STDMETHODIMP GetTypeOfInterfaceImpl( // return the TypeRef/typedef token for the interfaceimpl
mdInterfaceImpl iiImpl, // given a interfaceimpl
mdToken *ptkType);
//*****************************************
// return information about a generic method instantiation
//*****************************************
__checkReturn
STDMETHODIMP GetMethodSpecProps(
mdMethodSpec mi, // [IN] The method instantiation
mdToken *tkParent, // [OUT] MethodDef or MemberRef
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob); // [OUT] actual size of signature blob
//*****************************************
// look up function for TypeDef
//*****************************************
__checkReturn
STDMETHODIMP FindTypeDef(
LPCSTR szNamespace, // [IN] Namespace for the TypeDef.
LPCSTR szName, // [IN] Name of the TypeDef.
mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef of enclosing class.
mdTypeDef *ptypedef); // [OUT] return typedef
__checkReturn
STDMETHODIMP FindTypeDefByGUID(
REFGUID guid, // guid to look up
mdTypeDef *ptypedef); // return typedef
//*****************************************
// return name and sig of a memberref
//*****************************************
__checkReturn
STDMETHODIMP GetNameAndSigOfMemberRef( // return name here
mdMemberRef memberref, // given memberref
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of COM+ signature
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
LPCSTR *pszName);
//*****************************************************************************
// Given memberref, return the parent. It can be TypeRef, ModuleRef, MethodDef
//*****************************************************************************
__checkReturn
STDMETHODIMP GetParentOfMemberRef(
mdMemberRef memberref, // given memberref
mdToken *ptkParent); // return the parent token
__checkReturn
STDMETHODIMP GetParamDefProps(
mdParamDef paramdef, // given a paramdef
USHORT *pusSequence, // [OUT] slot number for this parameter
DWORD *pdwAttr, // [OUT] flags
LPCSTR *pszName); // [OUT] return the name of the parameter
//******************************************
// property info for method.
//******************************************
__checkReturn
STDMETHODIMP GetPropertyInfoForMethodDef( // Result.
mdMethodDef md, // [IN] memberdef
mdProperty *ppd, // [OUT] put property token here
LPCSTR *pName, // [OUT] put pointer to name here
ULONG *pSemantic) // [OUT] put semantic here
DAC_UNEXPECTED();
//*****************************************
// class layout/sequence information
//*****************************************
__checkReturn
STDMETHODIMP GetClassPackSize( // [OUT] return error if a class doesn't have packsize info
mdTypeDef td, // [IN] give typedef
ULONG *pdwPackSize); // [OUT] return the pack size of the class. 1, 2, 4, 8 or 16
__checkReturn
STDMETHODIMP GetClassTotalSize( // [OUT] return error if a class doesn't have total size info
mdTypeDef td, // [IN] give typedef
ULONG *pdwClassSize); // [OUT] return the total size of the class
__checkReturn
STDMETHODIMP GetClassLayoutInit(
mdTypeDef td, // [IN] give typedef
MD_CLASS_LAYOUT *pLayout); // [OUT] set up the status of query here
__checkReturn
STDMETHODIMP GetClassLayoutNext(
MD_CLASS_LAYOUT *pLayout, // [IN|OUT] set up the status of query here
mdFieldDef *pfd, // [OUT] return the fielddef
ULONG *pulOffset); // [OUT] return the offset/ulSequence associate with it
//*****************************************
// marshal information of a field
//*****************************************
__checkReturn
STDMETHODIMP GetFieldMarshal( // return error if no native type associate with the token
mdFieldDef fd, // [IN] given fielddef
PCCOR_SIGNATURE *pSigNativeType, // [OUT] the native type signature
ULONG *pcbNativeType); // [OUT] the count of bytes of *ppvNativeType
//*****************************************
// property APIs
//*****************************************
// find a property by name
__checkReturn
STDMETHODIMP FindProperty(
mdTypeDef td, // [IN] given a typdef
LPCSTR szPropName, // [IN] property name
mdProperty *pProp); // [OUT] return property token
__checkReturn
STDMETHODIMP GetPropertyProps(
mdProperty prop, // [IN] property token
LPCSTR *szProperty, // [OUT] property name
DWORD *pdwPropFlags, // [OUT] property flags.
PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob
ULONG *pcbSig); // [OUT] count of bytes in *ppvSig
//**********************************
// Event APIs
//**********************************
__checkReturn
STDMETHODIMP FindEvent(
mdTypeDef td, // [IN] given a typdef
LPCSTR szEventName, // [IN] event name
mdEvent *pEvent); // [OUT] return event token
__checkReturn
STDMETHODIMP GetEventProps( // S_OK, S_FALSE, or error.
mdEvent ev, // [IN] event token
LPCSTR *pszEvent, // [OUT] Event name
DWORD *pdwEventFlags, // [OUT] Event flags.
mdToken *ptkEventType); // [OUT] EventType class
//**********************************
// Generics APIs
//**********************************
__checkReturn
STDMETHODIMP GetGenericParamProps( // S_OK or error.
mdGenericParam rd, // [IN] The type parameter
ULONG* pulSequence, // [OUT] Parameter sequence number
DWORD* pdwAttr, // [OUT] Type parameter flags (for future use)
mdToken *ptOwner, // [OUT] The owner (TypeDef or MethodDef)
DWORD *reserved, // [OUT] The kind (TypeDef/Ref/Spec, for future use)
LPCSTR *szName); // [OUT] The name
__checkReturn
STDMETHODIMP GetGenericParamConstraintProps( // S_OK or error.
mdGenericParamConstraint rd, // [IN] The constraint token
mdGenericParam *ptGenericParam, // [OUT] GenericParam that is constrained
mdToken *ptkConstraintType); // [OUT] TypeDef/Ref/Spec constraint
//**********************************
// find a particular associate of a property or an event
//**********************************
__checkReturn
STDMETHODIMP FindAssociate(
mdToken evprop, // [IN] given a property or event token
DWORD associate, // [IN] given a associate semantics(setter, getter, testdefault, reset, AddOn, RemoveOn, Fire)
mdMethodDef *pmd); // [OUT] return method def token
__checkReturn
STDMETHODIMP EnumAssociateInit(
mdToken evprop, // [IN] given a property or an event token
HENUMInternal *phEnum); // [OUT] cursor to hold the query result
__checkReturn
STDMETHODIMP GetAllAssociates(
HENUMInternal *phEnum, // [IN] query result form GetPropertyAssociateCounts
ASSOCIATE_RECORD *pAssociateRec, // [OUT] struct to fill for output
ULONG cAssociateRec); // [IN] size of the buffer
//**********************************
// Get info about a PermissionSet.
//**********************************
__checkReturn
STDMETHODIMP GetPermissionSetProps(
mdPermission pm, // [IN] the permission token.
DWORD *pdwAction, // [OUT] CorDeclSecurity.
void const **ppvPermission, // [OUT] permission blob.
ULONG *pcbPermission); // [OUT] count of bytes of pvPermission.
//****************************************
// Get the String given the String token.
// Returns a pointer to the string, or NULL in case of error.
//****************************************
__checkReturn
STDMETHODIMP GetUserString(
mdString stk, // [IN] the string token.
ULONG *pchString, // [OUT] count of characters in the string.
BOOL *pbIs80Plus, // [OUT] specifies where there are extended characters >= 0x80.
LPCWSTR *pwszUserString);
//*****************************************************************************
// p-invoke APIs.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetPinvokeMap(
mdMethodDef tk, // [IN] FieldDef or MethodDef.
DWORD *pdwMappingFlags, // [OUT] Flags used for mapping.
LPCSTR *pszImportName, // [OUT] Import name.
mdModuleRef *pmrImportDLL); // [OUT] ModuleRef token for the target DLL.
//*****************************************************************************
// Assembly MetaData APIs.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetAssemblyProps(
mdAssembly mda, // [IN] The Assembly for which to get the properties.
const void **ppbPublicKey, // [OUT] Pointer to the public key.
ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key.
ULONG *pulHashAlgId, // [OUT] Hash Algorithm.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData.
DWORD *pdwAssemblyFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetAssemblyRefProps(
mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties.
const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token.
ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData.
const void **ppbHashValue, // [OUT] Hash blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob.
DWORD *pdwAssemblyRefFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetFileProps(
mdFile mdf, // [IN] The File for which to get the properties.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob.
DWORD *pdwFileFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetExportedTypeProps(
mdExportedType mdct, // [IN] The ExportedType for which to get the properties.
LPCSTR *pszNamespace, // [OUT] Buffer to fill with namespace.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file.
DWORD *pdwExportedTypeFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetManifestResourceProps(
mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file.
DWORD *pdwResourceFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP FindExportedTypeByName( // S_OK or error
LPCSTR szNamespace, // [IN] Namespace of the ExportedType.
LPCSTR szName, // [IN] Name of the ExportedType.
mdExportedType tkEnclosingType, // [IN] Enclosing ExportedType.
mdExportedType *pmct); // [OUT] Put ExportedType token here.
__checkReturn
STDMETHODIMP FindManifestResourceByName(// S_OK or error
LPCSTR szName, // [IN] Name of the resource.
mdManifestResource *pmmr); // [OUT] Put ManifestResource token here.
__checkReturn
STDMETHODIMP GetAssemblyFromScope( // S_OK or error
mdAssembly *ptkAssembly); // [OUT] Put token here.
//***************************************************************************
// return properties regarding a TypeSpec
//***************************************************************************
__checkReturn
STDMETHODIMP GetTypeSpecFromToken( // S_OK or error.
mdTypeSpec typespec, // [IN] Signature token.
PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token.
ULONG *pcbSig); // [OUT] return size of signature.
//*****************************************************************************
// This function gets the "built for" version of a metadata scope.
// NOTE: if the scope has never been saved, it will not have a built-for
// version, and an empty string will be returned.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetVersionString( // S_OK or error.
LPCSTR *pVer); // [OUT] Put version string here.
//*****************************************************************************
// helpers to convert a text signature to a com format
//*****************************************************************************
__checkReturn
STDMETHODIMP ConvertTextSigToComSig( // Return hresult.
BOOL fCreateTrIfNotFound, // [IN] create typeref if not found
LPCSTR pSignature, // [IN] class file format signature
CQuickBytes *pqbNewSig, // [OUT] place holder for COM+ signature
ULONG *pcbCount); // [OUT] the result size of signature
__checkReturn
STDMETHODIMP SetUserContextData( // S_OK or E_NOTIMPL
IUnknown *pIUnk) // The user context.
{ return E_NOTIMPL; }
STDMETHODIMP_(BOOL) IsValidToken( // True or False.
mdToken tk); // [IN] Given token.
STDMETHODIMP_(IUnknown *) GetCachedPublicInterface(BOOL fWithLock) { return NULL;} // return the cached public interface
__checkReturn
STDMETHODIMP SetCachedPublicInterface(IUnknown *pUnk) { return E_FAIL;} ;// return hresult
STDMETHODIMP_(UTSemReadWrite*) GetReaderWriterLock() {return NULL;} // return the reader writer lock
__checkReturn
STDMETHODIMP SetReaderWriterLock(UTSemReadWrite *pSem) { return NOERROR; }
STDMETHODIMP_(mdModule) GetModuleFromScope(void);
// Find a paticular method and pass in the signature comparison routine. Very
// helpful when the passed in signature does not come from the same scope.
__checkReturn
STDMETHODIMP FindMethodDefUsingCompare(
mdTypeDef classdef, // [IN] given typedef
LPCSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of COM+ signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
PSIGCOMPARE pSignatureCompare, // [IN] Routine to compare signatures
void* pSignatureArgs, // [IN] Additional info to supply the compare function
mdMethodDef *pmd); // [OUT] matching memberdef
//*****************************************************************************
// return the table pointer and size for a given table index
//*****************************************************************************
__checkReturn
STDMETHODIMP GetTableInfoWithIndex(
ULONG index, // [IN] pass in the index
void **pTable, // [OUT] pointer to table at index
void **pTableSize); // [OUT] size of table at index
__checkReturn
STDMETHODIMP ApplyEditAndContinue(
void *pData, // [IN] the delta metadata
ULONG cbData, // [IN] length of pData
IMDInternalImport **ppv); // [OUT] the resulting metadata interface
STDMETHODIMP GetRvaOffsetData(
DWORD *pFirstMethodRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in MethodDef table.
DWORD *pMethodDefRecordSize, // [OUT] Size of each record in MethodDef table.
DWORD *pMethodDefCount, // [OUT] Number of records in MethodDef table.
DWORD *pFirstFieldRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in FieldRVA table.
DWORD *pFieldRvaRecordSize, // [OUT] Size of each record in FieldRVA table.
DWORD *pFieldRvaCount // [OUT] Number of records in FieldRVA table.
);
CLiteWeightStgdb<CMiniMd> m_LiteWeightStgdb;
private:
struct CMethodSemanticsMap
{
mdToken m_mdMethod; // Method token.
RID m_ridSemantics; // RID of semantics record.
};
CMethodSemanticsMap *m_pMethodSemanticsMap; // Possible array of method semantics pointers, ordered by method token.
#ifndef DACCESS_COMPILE
class CMethodSemanticsMapSorter : public CQuickSort<CMethodSemanticsMap>
{
public:
CMethodSemanticsMapSorter(CMethodSemanticsMap *pBase, int iCount) : CQuickSort<CMethodSemanticsMap>(pBase, iCount) {}
virtual int Compare(CMethodSemanticsMap *psFirst, CMethodSemanticsMap *psSecond);
};
#endif //!DACCESS_COMPILE
class CMethodSemanticsMapSearcher : public CBinarySearch<CMethodSemanticsMap>
{
public:
CMethodSemanticsMapSearcher(const CMethodSemanticsMap *pBase, int iCount) : CBinarySearch<CMethodSemanticsMap>(pBase, iCount) {}
virtual int Compare(const CMethodSemanticsMap *psFirst, const CMethodSemanticsMap *psSecond);
};
static BOOL CompareSignatures(PCCOR_SIGNATURE pvFirstSigBlob, DWORD cbFirstSigBlob,
PCCOR_SIGNATURE pvSecondSigBlob, DWORD cbSecondSigBlob,
void* SigARguments);
mdTypeDef m_tdModule; // <Module> typedef value.
LONG m_cRefs; // Ref count.
public:
STDMETHODIMP_(DWORD) GetMetadataStreamVersion()
{
return (DWORD)m_LiteWeightStgdb.m_MiniMd.m_Schema.m_minor |
((DWORD)m_LiteWeightStgdb.m_MiniMd.m_Schema.m_major << 16);
};
STDMETHODIMP SetVerifiedByTrustedSource(// return hresult
BOOL fVerified)
{
m_LiteWeightStgdb.m_MiniMd.SetVerifiedByTrustedSource(fVerified);
return S_OK;
}
}; // class MDInternalRO
#endif //FEATURE_METADATA_INTERNAL_APIS
#endif // __MDInternalRO__h__
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// MDInternalRO.h
//
//
// Contains utility code for MD directory
//
//*****************************************************************************
#ifndef __MDInternalRO__h__
#define __MDInternalRO__h__
#include "metamodel.h"
#ifdef FEATURE_METADATA_INTERNAL_APIS
class MDInternalRO : public IMDInternalImport, IMDCommon
{
public:
MDInternalRO();
virtual ~MDInternalRO();
__checkReturn
HRESULT Init(LPVOID pData, ULONG cbData);
// *** IUnknown methods ***
__checkReturn
STDMETHODIMP QueryInterface(REFIID riid, void** ppv);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
__checkReturn
STDMETHODIMP TranslateSigWithScope(
IMDInternalImport *pAssemImport, // [IN] import assembly scope.
const void *pbHashValue, // [IN] hash value for the import assembly.
ULONG cbHashValue, // [IN] count of bytes in the hash value.
PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope
ULONG cbSigBlob, // [IN] count of bytes of signature
IMetaDataAssemblyEmit *pAssemEmit, // [IN] assembly emit scope.
IMetaDataEmit *emit, // [IN] emit interface
CQuickBytes *pqkSigEmit, // [OUT] buffer to hold translated signature
ULONG *pcbSig) // [OUT] count of bytes in the translated signature
DAC_UNEXPECTED();
__checkReturn
STDMETHODIMP GetTypeDefRefTokenInTypeSpec(// return S_FALSE if enclosing type does not have a token
mdTypeSpec tkTypeSpec, // [IN] TypeSpec token to look at
mdToken *tkEnclosedToken); // [OUT] The enclosed type token
STDMETHODIMP_(IMetaModelCommon*) GetMetaModelCommon()
{
return static_cast<IMetaModelCommon*>(&m_LiteWeightStgdb.m_MiniMd);
}
STDMETHODIMP_(IMetaModelCommonRO*) GetMetaModelCommonRO()
{
if (m_LiteWeightStgdb.m_MiniMd.IsWritable())
{
_ASSERTE(!"IMetaModelCommonRO methods cannot be used because this importer is writable.");
return NULL;
}
return static_cast<IMetaModelCommonRO*>(&m_LiteWeightStgdb.m_MiniMd);
}
__checkReturn
STDMETHODIMP SetOptimizeAccessForSpeed(
BOOL fOptSpeed)
{
return S_OK;
}
//*****************************************************************************
// return the count of entries of a given kind in a scope
// For example, pass in mdtMethodDef will tell you how many MethodDef
// contained in a scope
//*****************************************************************************
STDMETHODIMP_(ULONG) GetCountWithTokenKind(// return hresult
DWORD tkKind) // [IN] pass in the kind of token.
DAC_UNEXPECTED();
//*****************************************************************************
// enumerator for typedef
//*****************************************************************************
__checkReturn
STDMETHODIMP EnumTypeDefInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
//*****************************************************************************
// enumerator for MethodImpl
//*****************************************************************************
__checkReturn
STDMETHODIMP EnumMethodImplInit( // return hresult
mdTypeDef td, // [IN] TypeDef over which to scope the enumeration.
HENUMInternal *phEnumBody, // [OUT] buffer to fill for enumerator data for MethodBody tokens.
HENUMInternal *phEnumDecl); // [OUT] buffer to fill for enumerator data for MethodDecl tokens.
STDMETHODIMP_(ULONG) EnumMethodImplGetCount(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
STDMETHODIMP_(void) EnumMethodImplReset(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
__checkReturn
STDMETHODIMP EnumMethodImplNext( // return hresult
HENUMInternal *phEnumBody, // [IN] input enum for MethodBody
HENUMInternal *phEnumDecl, // [IN] input enum for MethodDecl
mdToken *ptkBody, // [OUT] return token for MethodBody
mdToken *ptkDecl); // [OUT] return token for MethodDecl
STDMETHODIMP_(void) EnumMethodImplClose(
HENUMInternal *phEnumBody, // [IN] MethodBody enumerator.
HENUMInternal *phEnumDecl); // [IN] MethodDecl enumerator.
//*****************************************
// Enumerator helpers for memberdef, memberref, interfaceimp,
// event, property, param, methodimpl
//*****************************************
__checkReturn
STDMETHODIMP EnumGlobalFunctionsInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
__checkReturn
STDMETHODIMP EnumGlobalFieldsInit( // return hresult
HENUMInternal *phEnum); // [OUT] buffer to fill for enumerator data
__checkReturn
STDMETHODIMP EnumInit( // return S_FALSE if record not found
DWORD tkKind, // [IN] which table to work on
mdToken tkParent, // [IN] token to scope the search
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP EnumAllInit( // return S_FALSE if record not found
DWORD tkKind, // [IN] which table to work on
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP EnumCustomAttributeByNameInit(// return S_FALSE if record not found
mdToken tkParent, // [IN] token to scope the search
LPCSTR szName, // [IN] CustomAttribute's name to scope the search
HENUMInternal *phEnum); // [OUT] the enumerator to fill
__checkReturn
STDMETHODIMP GetParentToken(
mdToken tkChild, // [IN] given child token
mdToken *ptkParent); // [OUT] returning parent
__checkReturn
STDMETHODIMP GetCustomAttributeProps(
mdCustomAttribute at, // [IN] The attribute.
mdToken *ptkType); // [OUT] Put attribute type here.
__checkReturn
STDMETHODIMP GetCustomAttributeAsBlob(
mdCustomAttribute cv, // [IN] given custom attribute token
void const **ppBlob, // [OUT] return the pointer to internal blob
ULONG *pcbSize); // [OUT] return the size of the blob
__checkReturn
STDMETHODIMP GetCustomAttributeByName( // S_OK or error.
mdToken tkObj, // [IN] Object with Custom Attribute.
LPCUTF8 szName, // [IN] Name of desired Custom Attribute.
const void **ppData, // [OUT] Put pointer to data here.
ULONG *pcbData); // [OUT] Put size of data here.
__checkReturn
STDMETHODIMP GetNameOfCustomAttribute( // S_OK or error.
mdCustomAttribute mdAttribute, // [IN] The Custom Attribute
LPCUTF8 *pszNamespace, // [OUT] Namespace of Custom Attribute.
LPCUTF8 *pszName); // [OUT] Name of Custom Attribute.
__checkReturn
STDMETHODIMP GetScopeProps(
LPCSTR *pszName, // [OUT] scope name
GUID *pmvid); // [OUT] version id
// finding a particular method
__checkReturn
STDMETHODIMP FindMethodDef(
mdTypeDef classdef, // [IN] given typedef
LPCSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of COM+ signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
mdMethodDef *pmd); // [OUT] matching memberdef
// return a iSeq's param given a MethodDef
__checkReturn
STDMETHODIMP FindParamOfMethod( // S_OK or error.
mdMethodDef md, // [IN] The owning method of the param.
ULONG iSeq, // [IN] The sequence # of the param.
mdParamDef *pparamdef); // [OUT] Put ParamDef token here.
//*****************************************
//
// GetName* functions
//
//*****************************************
// return the name and namespace of typedef
__checkReturn
STDMETHODIMP GetNameOfTypeDef(
mdTypeDef classdef, // given classdef
LPCSTR *pszname, // return class name(unqualified)
LPCSTR *psznamespace); // return the name space name
__checkReturn
STDMETHODIMP GetIsDualOfTypeDef(
mdTypeDef classdef, // [IN] given classdef.
ULONG *pDual); // [OUT] return dual flag here.
__checkReturn
STDMETHODIMP GetIfaceTypeOfTypeDef(
mdTypeDef classdef, // [IN] given classdef.
ULONG *pIface); // [OUT] 0=dual, 1=vtable, 2=dispinterface
// get the name of either methoddef
__checkReturn
STDMETHODIMP GetNameOfMethodDef( // return the name of the memberdef in UTF8
mdMethodDef md, // given memberdef
LPCSTR *pszName);
__checkReturn
STDMETHODIMP GetNameAndSigOfMethodDef(
mdMethodDef methoddef, // [IN] given memberdef
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of COM+ signature
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
LPCSTR *pszName);
// return the name of a FieldDef
__checkReturn
STDMETHODIMP GetNameOfFieldDef(
mdFieldDef fd, // given memberdef
LPCSTR *pszName);
// return the name of typeref
__checkReturn
STDMETHODIMP GetNameOfTypeRef(
mdTypeRef classref, // [IN] given typeref
LPCSTR *psznamespace, // [OUT] return typeref name
LPCSTR *pszname); // [OUT] return typeref namespace
// return the resolutionscope of typeref
__checkReturn
STDMETHODIMP GetResolutionScopeOfTypeRef(
mdTypeRef classref, // given classref
mdToken *ptkResolutionScope);
// return the typeref token given the name.
__checkReturn
STDMETHODIMP FindTypeRefByName(
LPCSTR szNamespace, // [IN] Namespace for the TypeRef.
LPCSTR szName, // [IN] Name of the TypeRef.
mdToken tkResolutionScope, // [IN] Resolution Scope fo the TypeRef.
mdTypeRef *ptk); // [OUT] TypeRef token returned.
// return the TypeDef properties
__checkReturn
STDMETHODIMP GetTypeDefProps( // return hresult
mdTypeDef classdef, // given classdef
DWORD *pdwAttr, // return flags on class, tdPublic, tdAbstract
mdToken *ptkExtends); // [OUT] Put base class TypeDef/TypeRef here.
// return the item's guid
__checkReturn
STDMETHODIMP GetItemGuid( // return hresult
mdToken tkObj, // [IN] given item.
CLSID *pGuid); // [OUT] Put guid here.
// get enclosing class of NestedClass.
__checkReturn
STDMETHODIMP GetNestedClassProps( // S_OK or error
mdTypeDef tkNestedClass, // [IN] NestedClass token.
mdTypeDef *ptkEnclosingClass); // [OUT] EnclosingClass token.
// Get count of Nested classes given the enclosing class.
__checkReturn
STDMETHODIMP GetCountNestedClasses( // return count of Nested classes.
mdTypeDef tkEnclosingClass, // [IN]Enclosing class.
ULONG *pcNestedClassesCount);
// Return array of Nested classes given the enclosing class.
__checkReturn
STDMETHODIMP GetNestedClasses( // Return actual count.
mdTypeDef tkEnclosingClass, // [IN] Enclosing class.
mdTypeDef *rNestedClasses, // [OUT] Array of nested class tokens.
ULONG ulNestedClasses, // [IN] Size of array.
ULONG *pcNestedClasses);
// return the ModuleRef properties
__checkReturn
STDMETHODIMP GetModuleRefProps(
mdModuleRef mur, // [IN] moduleref token
LPCSTR *pszName); // [OUT] buffer to fill with the moduleref name
//*****************************************
//
// GetSig* functions
//
//*****************************************
__checkReturn
STDMETHODIMP GetSigOfMethodDef(
mdMethodDef methoddef, // [IN] given memberdef
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
PCCOR_SIGNATURE *ppSig);
__checkReturn
STDMETHODIMP GetSigOfFieldDef(
mdMethodDef methoddef, // [IN] given memberdef
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
PCCOR_SIGNATURE *ppSig);
__checkReturn
STDMETHODIMP GetSigFromToken(
mdToken tk, // FieldDef, MethodDef, Signature or TypeSpec token
ULONG * pcbSig,
PCCOR_SIGNATURE * ppSig);
//*****************************************
// get method property
//*****************************************
__checkReturn
STDMETHODIMP GetMethodDefProps(
mdMethodDef md, // The method for which to get props.
DWORD *pdwFlags);
__checkReturn
STDMETHODIMP_(ULONG) GetMethodDefSlot(
mdMethodDef mb); // The method for which to get props.
//*****************************************
// return method implementation informaiton, like RVA and implflags
//*****************************************
__checkReturn
STDMETHODIMP GetMethodImplProps(
mdMethodDef tk, // [IN] MethodDef
ULONG *pulCodeRVA, // [OUT] CodeRVA
DWORD *pdwImplFlags); // [OUT] Impl. Flags
//*****************************************************************************
// return the field RVA
//*****************************************************************************
__checkReturn
STDMETHODIMP GetFieldRVA(
mdToken fd, // [IN] FieldDef
ULONG *pulCodeRVA); // [OUT] CodeRVA
//*****************************************************************************
// return the field offset for a given field
//*****************************************************************************
__checkReturn
STDMETHODIMP GetFieldOffset(
mdFieldDef fd, // [IN] fielddef
ULONG *pulOffset); // [OUT] FieldOffset
//*****************************************
// get field property
//*****************************************
__checkReturn
STDMETHODIMP GetFieldDefProps(
mdFieldDef fd, // [IN] given fielddef
DWORD *pdwFlags); // [OUT] return fdPublic, fdPrive, etc flags
//*****************************************************************************
// return default value of a token (could be paramdef, fielddef, or property)
//*****************************************************************************
__checkReturn
STDMETHODIMP GetDefaultValue(
mdToken tk, // [IN] given FieldDef, ParamDef, or Property
MDDefaultValue *pDefaultValue); // [OUT] default value to fill
//*****************************************
// get dispid of a MethodDef or a FieldDef
//*****************************************
__checkReturn
STDMETHODIMP GetDispIdOfMemberDef( // return hresult
mdToken tk, // [IN] given methoddef or fielddef
ULONG *pDispid); // [OUT] Put the dispid here.
//*****************************************
// return TypeRef/TypeDef given an InterfaceImpl token
//*****************************************
__checkReturn
STDMETHODIMP GetTypeOfInterfaceImpl( // return the TypeRef/typedef token for the interfaceimpl
mdInterfaceImpl iiImpl, // given a interfaceimpl
mdToken *ptkType);
//*****************************************
// return information about a generic method instantiation
//*****************************************
__checkReturn
STDMETHODIMP GetMethodSpecProps(
mdMethodSpec mi, // [IN] The method instantiation
mdToken *tkParent, // [OUT] MethodDef or MemberRef
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to the blob value of meta data
ULONG *pcbSigBlob); // [OUT] actual size of signature blob
//*****************************************
// look up function for TypeDef
//*****************************************
__checkReturn
STDMETHODIMP FindTypeDef(
LPCSTR szNamespace, // [IN] Namespace for the TypeDef.
LPCSTR szName, // [IN] Name of the TypeDef.
mdToken tkEnclosingClass, // [IN] TypeDef/TypeRef of enclosing class.
mdTypeDef *ptypedef); // [OUT] return typedef
__checkReturn
STDMETHODIMP FindTypeDefByGUID(
REFGUID guid, // guid to look up
mdTypeDef *ptypedef); // return typedef
//*****************************************
// return name and sig of a memberref
//*****************************************
__checkReturn
STDMETHODIMP GetNameAndSigOfMemberRef( // return name here
mdMemberRef memberref, // given memberref
PCCOR_SIGNATURE *ppvSigBlob, // [OUT] point to a blob value of COM+ signature
ULONG *pcbSigBlob, // [OUT] count of bytes in the signature blob
LPCSTR *pszName);
//*****************************************************************************
// Given memberref, return the parent. It can be TypeRef, ModuleRef, MethodDef
//*****************************************************************************
__checkReturn
STDMETHODIMP GetParentOfMemberRef(
mdMemberRef memberref, // given memberref
mdToken *ptkParent); // return the parent token
__checkReturn
STDMETHODIMP GetParamDefProps(
mdParamDef paramdef, // given a paramdef
USHORT *pusSequence, // [OUT] slot number for this parameter
DWORD *pdwAttr, // [OUT] flags
LPCSTR *pszName); // [OUT] return the name of the parameter
//******************************************
// property info for method.
//******************************************
__checkReturn
STDMETHODIMP GetPropertyInfoForMethodDef( // Result.
mdMethodDef md, // [IN] memberdef
mdProperty *ppd, // [OUT] put property token here
LPCSTR *pName, // [OUT] put pointer to name here
ULONG *pSemantic) // [OUT] put semantic here
DAC_UNEXPECTED();
//*****************************************
// class layout/sequence information
//*****************************************
__checkReturn
STDMETHODIMP GetClassPackSize( // [OUT] return error if a class doesn't have packsize info
mdTypeDef td, // [IN] give typedef
ULONG *pdwPackSize); // [OUT] return the pack size of the class. 1, 2, 4, 8 or 16
__checkReturn
STDMETHODIMP GetClassTotalSize( // [OUT] return error if a class doesn't have total size info
mdTypeDef td, // [IN] give typedef
ULONG *pdwClassSize); // [OUT] return the total size of the class
__checkReturn
STDMETHODIMP GetClassLayoutInit(
mdTypeDef td, // [IN] give typedef
MD_CLASS_LAYOUT *pLayout); // [OUT] set up the status of query here
__checkReturn
STDMETHODIMP GetClassLayoutNext(
MD_CLASS_LAYOUT *pLayout, // [IN|OUT] set up the status of query here
mdFieldDef *pfd, // [OUT] return the fielddef
ULONG *pulOffset); // [OUT] return the offset/ulSequence associate with it
//*****************************************
// marshal information of a field
//*****************************************
__checkReturn
STDMETHODIMP GetFieldMarshal( // return error if no native type associate with the token
mdFieldDef fd, // [IN] given fielddef
PCCOR_SIGNATURE *pSigNativeType, // [OUT] the native type signature
ULONG *pcbNativeType); // [OUT] the count of bytes of *ppvNativeType
//*****************************************
// property APIs
//*****************************************
// find a property by name
__checkReturn
STDMETHODIMP FindProperty(
mdTypeDef td, // [IN] given a typdef
LPCSTR szPropName, // [IN] property name
mdProperty *pProp); // [OUT] return property token
__checkReturn
STDMETHODIMP GetPropertyProps(
mdProperty prop, // [IN] property token
LPCSTR *szProperty, // [OUT] property name
DWORD *pdwPropFlags, // [OUT] property flags.
PCCOR_SIGNATURE *ppvSig, // [OUT] property type. pointing to meta data internal blob
ULONG *pcbSig); // [OUT] count of bytes in *ppvSig
//**********************************
// Event APIs
//**********************************
__checkReturn
STDMETHODIMP FindEvent(
mdTypeDef td, // [IN] given a typdef
LPCSTR szEventName, // [IN] event name
mdEvent *pEvent); // [OUT] return event token
__checkReturn
STDMETHODIMP GetEventProps( // S_OK, S_FALSE, or error.
mdEvent ev, // [IN] event token
LPCSTR *pszEvent, // [OUT] Event name
DWORD *pdwEventFlags, // [OUT] Event flags.
mdToken *ptkEventType); // [OUT] EventType class
//**********************************
// Generics APIs
//**********************************
__checkReturn
STDMETHODIMP GetGenericParamProps( // S_OK or error.
mdGenericParam rd, // [IN] The type parameter
ULONG* pulSequence, // [OUT] Parameter sequence number
DWORD* pdwAttr, // [OUT] Type parameter flags (for future use)
mdToken *ptOwner, // [OUT] The owner (TypeDef or MethodDef)
DWORD *reserved, // [OUT] The kind (TypeDef/Ref/Spec, for future use)
LPCSTR *szName); // [OUT] The name
__checkReturn
STDMETHODIMP GetGenericParamConstraintProps( // S_OK or error.
mdGenericParamConstraint rd, // [IN] The constraint token
mdGenericParam *ptGenericParam, // [OUT] GenericParam that is constrained
mdToken *ptkConstraintType); // [OUT] TypeDef/Ref/Spec constraint
//**********************************
// find a particular associate of a property or an event
//**********************************
__checkReturn
STDMETHODIMP FindAssociate(
mdToken evprop, // [IN] given a property or event token
DWORD associate, // [IN] given a associate semantics(setter, getter, testdefault, reset, AddOn, RemoveOn, Fire)
mdMethodDef *pmd); // [OUT] return method def token
__checkReturn
STDMETHODIMP EnumAssociateInit(
mdToken evprop, // [IN] given a property or an event token
HENUMInternal *phEnum); // [OUT] cursor to hold the query result
__checkReturn
STDMETHODIMP GetAllAssociates(
HENUMInternal *phEnum, // [IN] query result form GetPropertyAssociateCounts
ASSOCIATE_RECORD *pAssociateRec, // [OUT] struct to fill for output
ULONG cAssociateRec); // [IN] size of the buffer
//**********************************
// Get info about a PermissionSet.
//**********************************
__checkReturn
STDMETHODIMP GetPermissionSetProps(
mdPermission pm, // [IN] the permission token.
DWORD *pdwAction, // [OUT] CorDeclSecurity.
void const **ppvPermission, // [OUT] permission blob.
ULONG *pcbPermission); // [OUT] count of bytes of pvPermission.
//****************************************
// Get the String given the String token.
// Returns a pointer to the string, or NULL in case of error.
//****************************************
__checkReturn
STDMETHODIMP GetUserString(
mdString stk, // [IN] the string token.
ULONG *pchString, // [OUT] count of characters in the string.
BOOL *pbIs80Plus, // [OUT] specifies where there are extended characters >= 0x80.
LPCWSTR *pwszUserString);
//*****************************************************************************
// p-invoke APIs.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetPinvokeMap(
mdMethodDef tk, // [IN] FieldDef or MethodDef.
DWORD *pdwMappingFlags, // [OUT] Flags used for mapping.
LPCSTR *pszImportName, // [OUT] Import name.
mdModuleRef *pmrImportDLL); // [OUT] ModuleRef token for the target DLL.
//*****************************************************************************
// Assembly MetaData APIs.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetAssemblyProps(
mdAssembly mda, // [IN] The Assembly for which to get the properties.
const void **ppbPublicKey, // [OUT] Pointer to the public key.
ULONG *pcbPublicKey, // [OUT] Count of bytes in the public key.
ULONG *pulHashAlgId, // [OUT] Hash Algorithm.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData.
DWORD *pdwAssemblyFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetAssemblyRefProps(
mdAssemblyRef mdar, // [IN] The AssemblyRef for which to get the properties.
const void **ppbPublicKeyOrToken, // [OUT] Pointer to the public key or token.
ULONG *pcbPublicKeyOrToken, // [OUT] Count of bytes in the public key or token.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
AssemblyMetaDataInternal *pMetaData,// [OUT] Assembly MetaData.
const void **ppbHashValue, // [OUT] Hash blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the hash blob.
DWORD *pdwAssemblyRefFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetFileProps(
mdFile mdf, // [IN] The File for which to get the properties.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
const void **ppbHashValue, // [OUT] Pointer to the Hash Value Blob.
ULONG *pcbHashValue, // [OUT] Count of bytes in the Hash Value Blob.
DWORD *pdwFileFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetExportedTypeProps(
mdExportedType mdct, // [IN] The ExportedType for which to get the properties.
LPCSTR *pszNamespace, // [OUT] Buffer to fill with namespace.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
mdTypeDef *ptkTypeDef, // [OUT] TypeDef token within the file.
DWORD *pdwExportedTypeFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP GetManifestResourceProps(
mdManifestResource mdmr, // [IN] The ManifestResource for which to get the properties.
LPCSTR *pszName, // [OUT] Buffer to fill with name.
mdToken *ptkImplementation, // [OUT] mdFile or mdAssemblyRef that provides the ExportedType.
DWORD *pdwOffset, // [OUT] Offset to the beginning of the resource within the file.
DWORD *pdwResourceFlags); // [OUT] Flags.
__checkReturn
STDMETHODIMP FindExportedTypeByName( // S_OK or error
LPCSTR szNamespace, // [IN] Namespace of the ExportedType.
LPCSTR szName, // [IN] Name of the ExportedType.
mdExportedType tkEnclosingType, // [IN] Enclosing ExportedType.
mdExportedType *pmct); // [OUT] Put ExportedType token here.
__checkReturn
STDMETHODIMP FindManifestResourceByName(// S_OK or error
LPCSTR szName, // [IN] Name of the resource.
mdManifestResource *pmmr); // [OUT] Put ManifestResource token here.
__checkReturn
STDMETHODIMP GetAssemblyFromScope( // S_OK or error
mdAssembly *ptkAssembly); // [OUT] Put token here.
//***************************************************************************
// return properties regarding a TypeSpec
//***************************************************************************
__checkReturn
STDMETHODIMP GetTypeSpecFromToken( // S_OK or error.
mdTypeSpec typespec, // [IN] Signature token.
PCCOR_SIGNATURE *ppvSig, // [OUT] return pointer to token.
ULONG *pcbSig); // [OUT] return size of signature.
//*****************************************************************************
// This function gets the "built for" version of a metadata scope.
// NOTE: if the scope has never been saved, it will not have a built-for
// version, and an empty string will be returned.
//*****************************************************************************
__checkReturn
STDMETHODIMP GetVersionString( // S_OK or error.
LPCSTR *pVer); // [OUT] Put version string here.
//*****************************************************************************
// helpers to convert a text signature to a com format
//*****************************************************************************
__checkReturn
STDMETHODIMP ConvertTextSigToComSig( // Return hresult.
BOOL fCreateTrIfNotFound, // [IN] create typeref if not found
LPCSTR pSignature, // [IN] class file format signature
CQuickBytes *pqbNewSig, // [OUT] place holder for COM+ signature
ULONG *pcbCount); // [OUT] the result size of signature
__checkReturn
STDMETHODIMP SetUserContextData( // S_OK or E_NOTIMPL
IUnknown *pIUnk) // The user context.
{ return E_NOTIMPL; }
STDMETHODIMP_(BOOL) IsValidToken( // True or False.
mdToken tk); // [IN] Given token.
STDMETHODIMP_(IUnknown *) GetCachedPublicInterface(BOOL fWithLock) { return NULL;} // return the cached public interface
__checkReturn
STDMETHODIMP SetCachedPublicInterface(IUnknown *pUnk) { return E_FAIL;} ;// return hresult
STDMETHODIMP_(UTSemReadWrite*) GetReaderWriterLock() {return NULL;} // return the reader writer lock
__checkReturn
STDMETHODIMP SetReaderWriterLock(UTSemReadWrite *pSem) { return NOERROR; }
STDMETHODIMP_(mdModule) GetModuleFromScope(void);
// Find a paticular method and pass in the signature comparison routine. Very
// helpful when the passed in signature does not come from the same scope.
__checkReturn
STDMETHODIMP FindMethodDefUsingCompare(
mdTypeDef classdef, // [IN] given typedef
LPCSTR szName, // [IN] member name
PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of COM+ signature
ULONG cbSigBlob, // [IN] count of bytes in the signature blob
PSIGCOMPARE pSignatureCompare, // [IN] Routine to compare signatures
void* pSignatureArgs, // [IN] Additional info to supply the compare function
mdMethodDef *pmd); // [OUT] matching memberdef
//*****************************************************************************
// return the table pointer and size for a given table index
//*****************************************************************************
__checkReturn
STDMETHODIMP GetTableInfoWithIndex(
ULONG index, // [IN] pass in the index
void **pTable, // [OUT] pointer to table at index
void **pTableSize); // [OUT] size of table at index
__checkReturn
STDMETHODIMP ApplyEditAndContinue(
void *pData, // [IN] the delta metadata
ULONG cbData, // [IN] length of pData
IMDInternalImport **ppv); // [OUT] the resulting metadata interface
STDMETHODIMP GetRvaOffsetData(
DWORD *pFirstMethodRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in MethodDef table.
DWORD *pMethodDefRecordSize, // [OUT] Size of each record in MethodDef table.
DWORD *pMethodDefCount, // [OUT] Number of records in MethodDef table.
DWORD *pFirstFieldRvaOffset, // [OUT] Offset (from start of metadata) to the first RVA field in FieldRVA table.
DWORD *pFieldRvaRecordSize, // [OUT] Size of each record in FieldRVA table.
DWORD *pFieldRvaCount // [OUT] Number of records in FieldRVA table.
);
CLiteWeightStgdb<CMiniMd> m_LiteWeightStgdb;
private:
struct CMethodSemanticsMap
{
mdToken m_mdMethod; // Method token.
RID m_ridSemantics; // RID of semantics record.
};
CMethodSemanticsMap *m_pMethodSemanticsMap; // Possible array of method semantics pointers, ordered by method token.
#ifndef DACCESS_COMPILE
class CMethodSemanticsMapSorter : public CQuickSort<CMethodSemanticsMap>
{
public:
CMethodSemanticsMapSorter(CMethodSemanticsMap *pBase, int iCount) : CQuickSort<CMethodSemanticsMap>(pBase, iCount) {}
virtual int Compare(CMethodSemanticsMap *psFirst, CMethodSemanticsMap *psSecond);
};
#endif //!DACCESS_COMPILE
class CMethodSemanticsMapSearcher : public CBinarySearch<CMethodSemanticsMap>
{
public:
CMethodSemanticsMapSearcher(const CMethodSemanticsMap *pBase, int iCount) : CBinarySearch<CMethodSemanticsMap>(pBase, iCount) {}
virtual int Compare(const CMethodSemanticsMap *psFirst, const CMethodSemanticsMap *psSecond);
};
static BOOL CompareSignatures(PCCOR_SIGNATURE pvFirstSigBlob, DWORD cbFirstSigBlob,
PCCOR_SIGNATURE pvSecondSigBlob, DWORD cbSecondSigBlob,
void* SigARguments);
mdTypeDef m_tdModule; // <Module> typedef value.
LONG m_cRefs; // Ref count.
public:
STDMETHODIMP_(DWORD) GetMetadataStreamVersion()
{
return (DWORD)m_LiteWeightStgdb.m_MiniMd.m_Schema.m_minor |
((DWORD)m_LiteWeightStgdb.m_MiniMd.m_Schema.m_major << 16);
};
STDMETHODIMP SetVerifiedByTrustedSource(// return hresult
BOOL fVerified)
{
m_LiteWeightStgdb.m_MiniMd.SetVerifiedByTrustedSource(fVerified);
return S_OK;
}
}; // class MDInternalRO
#endif //FEATURE_METADATA_INTERNAL_APIS
#endif // __MDInternalRO__h__
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/nativeaot/Runtime/AsmOffsetsVerify.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "common.h"
#include "gcenv.h"
#include "gcheaputilities.h"
#include "rhassert.h"
#include "RedhawkWarnings.h"
#include "slist.h"
#include "gcrhinterface.h"
#include "varint.h"
#include "regdisplay.h"
#include "StackFrameIterator.h"
#include "thread.h"
#include "TargetPtrs.h"
#include "rhbinder.h"
#include "RWLock.h"
#include "RuntimeInstance.h"
#include "CachedInterfaceDispatch.h"
#include "shash.h"
#include "CallDescr.h"
class AsmOffsets
{
static_assert(sizeof(Thread::m_rgbAllocContextBuffer) >= sizeof(gc_alloc_context), "Thread::m_rgbAllocContextBuffer is not big enough to hold a gc_alloc_context");
// Some assembly helpers for arrays and strings are shared and use the fact that arrays and strings have similar layouts)
static_assert(offsetof(Array, m_Length) == offsetof(String, m_Length), "The length field of String and Array have different offsets");
static_assert(sizeof(((Array*)0)->m_Length) == sizeof(((String*)0)->m_Length), "The length field of String and Array have different sizes");
#define PLAT_ASM_OFFSET(offset, cls, member) \
static_assert((offsetof(cls, member) == 0x##offset) || (offsetof(cls, member) > 0x##offset), "Bad asm offset for '" #cls "." #member "', the actual offset is smaller than 0x" #offset "."); \
static_assert((offsetof(cls, member) == 0x##offset) || (offsetof(cls, member) < 0x##offset), "Bad asm offset for '" #cls "." #member "', the actual offset is larger than 0x" #offset ".");
#define PLAT_ASM_SIZEOF(size, cls ) \
static_assert((sizeof(cls) == 0x##size) || (sizeof(cls) > 0x##size), "Bad asm size for '" #cls "', the actual size is smaller than 0x" #size "."); \
static_assert((sizeof(cls) == 0x##size) || (sizeof(cls) < 0x##size), "Bad asm size for '" #cls "', the actual size is larger than 0x" #size ".");
#define PLAT_ASM_CONST(constant, expr) \
static_assert(((expr) == 0x##constant) || ((expr) > 0x##constant), "Bad asm constant for '" #expr "', the actual value is smaller than 0x" #constant "."); \
static_assert(((expr) == 0x##constant) || ((expr) < 0x##constant), "Bad asm constant for '" #expr "', the actual value is larger than 0x" #constant ".");
#include "AsmOffsets.h"
};
#ifdef _MSC_VER
namespace { char WorkaroundLNK4221Warning; };
#endif
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "common.h"
#include "gcenv.h"
#include "gcheaputilities.h"
#include "rhassert.h"
#include "RedhawkWarnings.h"
#include "slist.h"
#include "gcrhinterface.h"
#include "varint.h"
#include "regdisplay.h"
#include "StackFrameIterator.h"
#include "thread.h"
#include "TargetPtrs.h"
#include "rhbinder.h"
#include "RWLock.h"
#include "RuntimeInstance.h"
#include "CachedInterfaceDispatch.h"
#include "shash.h"
#include "CallDescr.h"
class AsmOffsets
{
static_assert(sizeof(Thread::m_rgbAllocContextBuffer) >= sizeof(gc_alloc_context), "Thread::m_rgbAllocContextBuffer is not big enough to hold a gc_alloc_context");
// Some assembly helpers for arrays and strings are shared and use the fact that arrays and strings have similar layouts)
static_assert(offsetof(Array, m_Length) == offsetof(String, m_Length), "The length field of String and Array have different offsets");
static_assert(sizeof(((Array*)0)->m_Length) == sizeof(((String*)0)->m_Length), "The length field of String and Array have different sizes");
#define PLAT_ASM_OFFSET(offset, cls, member) \
static_assert((offsetof(cls, member) == 0x##offset) || (offsetof(cls, member) > 0x##offset), "Bad asm offset for '" #cls "." #member "', the actual offset is smaller than 0x" #offset "."); \
static_assert((offsetof(cls, member) == 0x##offset) || (offsetof(cls, member) < 0x##offset), "Bad asm offset for '" #cls "." #member "', the actual offset is larger than 0x" #offset ".");
#define PLAT_ASM_SIZEOF(size, cls ) \
static_assert((sizeof(cls) == 0x##size) || (sizeof(cls) > 0x##size), "Bad asm size for '" #cls "', the actual size is smaller than 0x" #size "."); \
static_assert((sizeof(cls) == 0x##size) || (sizeof(cls) < 0x##size), "Bad asm size for '" #cls "', the actual size is larger than 0x" #size ".");
#define PLAT_ASM_CONST(constant, expr) \
static_assert(((expr) == 0x##constant) || ((expr) > 0x##constant), "Bad asm constant for '" #expr "', the actual value is smaller than 0x" #constant "."); \
static_assert(((expr) == 0x##constant) || ((expr) < 0x##constant), "Bad asm constant for '" #expr "', the actual value is larger than 0x" #constant ".");
#include "AsmOffsets.h"
};
#ifdef _MSC_VER
namespace { char WorkaroundLNK4221Warning; };
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/vm/clrtocomcall.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: CLRtoCOMCall.h
//
//
// Used to handle stub creation for managed to unmanaged transitions.
//
#ifndef __COMPLUSCALL_H__
#define __COMPLUSCALL_H__
#ifndef FEATURE_COMINTEROP
#error FEATURE_COMINTEROP is required for this file
#endif // FEATURE_COMINTEROP
#include "util.hpp"
class ComPlusCall
{
public:
//---------------------------------------------------------
// Debugger helper function
//---------------------------------------------------------
static TADDR GetFrameCallIP(FramedMethodFrame *frame);
static MethodDesc* GetILStubMethodDesc(MethodDesc* pMD, DWORD dwStubFlags);
static PCODE GetStubForILStub(MethodDesc* pMD, MethodDesc** ppStubMD);
static ComPlusCallInfo *PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWORD* pdwStubFlags);
#ifdef TARGET_X86
static void Init();
static LPVOID GetRetThunk(UINT numStackBytes);
#endif // TARGET_X86
private:
ComPlusCall(); // prevent "new"'s on this class
#ifdef TARGET_X86
struct RetThunkCacheElement
{
RetThunkCacheElement()
{
LIMITED_METHOD_CONTRACT;
m_cbStack = 0;
m_pRetThunk = NULL;
}
UINT m_cbStack;
LPVOID m_pRetThunk;
};
class RetThunkSHashTraits : public NoRemoveSHashTraits< DefaultSHashTraits<RetThunkCacheElement> >
{
public:
typedef UINT key_t;
static key_t GetKey(element_t e) { LIMITED_METHOD_CONTRACT; return e.m_cbStack; }
static BOOL Equals(key_t k1, key_t k2) { LIMITED_METHOD_CONTRACT; return (k1 == k2); }
static count_t Hash(key_t k) { LIMITED_METHOD_CONTRACT; return (count_t)(size_t)k; }
static const element_t Null() { LIMITED_METHOD_CONTRACT; return RetThunkCacheElement(); }
static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return (e.m_pRetThunk == NULL); }
};
static SHash<RetThunkSHashTraits> *s_pRetThunkCache;
static CrstStatic s_RetThunkCacheCrst;
#endif // TARGET_X86
};
#endif // __COMPLUSCALL_H__
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// File: CLRtoCOMCall.h
//
//
// Used to handle stub creation for managed to unmanaged transitions.
//
#ifndef __COMPLUSCALL_H__
#define __COMPLUSCALL_H__
#ifndef FEATURE_COMINTEROP
#error FEATURE_COMINTEROP is required for this file
#endif // FEATURE_COMINTEROP
#include "util.hpp"
class ComPlusCall
{
public:
//---------------------------------------------------------
// Debugger helper function
//---------------------------------------------------------
static TADDR GetFrameCallIP(FramedMethodFrame *frame);
static MethodDesc* GetILStubMethodDesc(MethodDesc* pMD, DWORD dwStubFlags);
static PCODE GetStubForILStub(MethodDesc* pMD, MethodDesc** ppStubMD);
static ComPlusCallInfo *PopulateComPlusCallMethodDesc(MethodDesc* pMD, DWORD* pdwStubFlags);
#ifdef TARGET_X86
static void Init();
static LPVOID GetRetThunk(UINT numStackBytes);
#endif // TARGET_X86
private:
ComPlusCall(); // prevent "new"'s on this class
#ifdef TARGET_X86
struct RetThunkCacheElement
{
RetThunkCacheElement()
{
LIMITED_METHOD_CONTRACT;
m_cbStack = 0;
m_pRetThunk = NULL;
}
UINT m_cbStack;
LPVOID m_pRetThunk;
};
class RetThunkSHashTraits : public NoRemoveSHashTraits< DefaultSHashTraits<RetThunkCacheElement> >
{
public:
typedef UINT key_t;
static key_t GetKey(element_t e) { LIMITED_METHOD_CONTRACT; return e.m_cbStack; }
static BOOL Equals(key_t k1, key_t k2) { LIMITED_METHOD_CONTRACT; return (k1 == k2); }
static count_t Hash(key_t k) { LIMITED_METHOD_CONTRACT; return (count_t)(size_t)k; }
static const element_t Null() { LIMITED_METHOD_CONTRACT; return RetThunkCacheElement(); }
static bool IsNull(const element_t &e) { LIMITED_METHOD_CONTRACT; return (e.m_pRetThunk == NULL); }
};
static SHash<RetThunkSHashTraits> *s_pRetThunkCache;
static CrstStatic s_RetThunkCacheCrst;
#endif // TARGET_X86
};
#endif // __COMPLUSCALL_H__
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/arch/i386/signalhandlerhelper.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/palinternal.h"
#include "pal/context.h"
#include "pal/signal.hpp"
#include "pal/utils.h"
#include <sys/ucontext.h>
/*++
Function :
ExecuteHandlerOnCustomStack
Execute signal handler on a custom stack, the current stack pointer is specified by the customSp
If the customSp is 0, then the handler is executed on the original stack where the signal was fired.
It installs a fake stack frame to enable stack unwinding to the signal source location.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
void ExecuteHandlerOnCustomStack(int code, siginfo_t *siginfo, void *context, size_t customSp, SignalHandlerWorkerReturnPoint* returnPoint)
{
ucontext_t *ucontext = (ucontext_t *)context;
size_t faultSp = (size_t)MCREG_Esp(ucontext->uc_mcontext);
_ASSERTE(IS_ALIGNED(faultSp, 4));
if (customSp == 0)
{
customSp = ALIGN_DOWN(faultSp, 16);
}
size_t fakeFrameReturnAddress;
switch (faultSp & 0xc)
{
case 0x0:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0;
break;
case 0x4:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset4 + (size_t)CallSignalHandlerWrapper4;
break;
case 0x8:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset8 + (size_t)CallSignalHandlerWrapper8;
break;
case 0xc:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset12 + (size_t)CallSignalHandlerWrapper12;
break;
}
size_t* sp = (size_t*)customSp;
// Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction
*--sp = (size_t)MCREG_Eip(ucontext->uc_mcontext);
*--sp = (size_t)MCREG_Ebp(ucontext->uc_mcontext);
size_t fp = (size_t)sp;
// Align stack
sp -= 2;
*--sp = (size_t)returnPoint;
*--sp = (size_t)context;
*--sp = (size_t)siginfo;
*--sp = code;
*--sp = fakeFrameReturnAddress;
// Switch the current context to the signal_handler_worker and the original stack
CONTEXT context2;
RtlCaptureContext(&context2);
// We don't care about the other registers state since the stack unwinding restores
// them for the target frame directly from the signal context.
context2.Esp = (size_t)sp;
context2.Ebp = (size_t)fp;
context2.Eip = (size_t)signal_handler_worker;
RtlRestoreContext(&context2, NULL);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/palinternal.h"
#include "pal/context.h"
#include "pal/signal.hpp"
#include "pal/utils.h"
#include <sys/ucontext.h>
/*++
Function :
ExecuteHandlerOnCustomStack
Execute signal handler on a custom stack, the current stack pointer is specified by the customSp
If the customSp is 0, then the handler is executed on the original stack where the signal was fired.
It installs a fake stack frame to enable stack unwinding to the signal source location.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
void ExecuteHandlerOnCustomStack(int code, siginfo_t *siginfo, void *context, size_t customSp, SignalHandlerWorkerReturnPoint* returnPoint)
{
ucontext_t *ucontext = (ucontext_t *)context;
size_t faultSp = (size_t)MCREG_Esp(ucontext->uc_mcontext);
_ASSERTE(IS_ALIGNED(faultSp, 4));
if (customSp == 0)
{
customSp = ALIGN_DOWN(faultSp, 16);
}
size_t fakeFrameReturnAddress;
switch (faultSp & 0xc)
{
case 0x0:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset0 + (size_t)CallSignalHandlerWrapper0;
break;
case 0x4:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset4 + (size_t)CallSignalHandlerWrapper4;
break;
case 0x8:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset8 + (size_t)CallSignalHandlerWrapper8;
break;
case 0xc:
fakeFrameReturnAddress = (size_t)SignalHandlerWorkerReturnOffset12 + (size_t)CallSignalHandlerWrapper12;
break;
}
size_t* sp = (size_t*)customSp;
// Build fake stack frame to enable the stack unwinder to unwind from signal_handler_worker to the faulting instruction
*--sp = (size_t)MCREG_Eip(ucontext->uc_mcontext);
*--sp = (size_t)MCREG_Ebp(ucontext->uc_mcontext);
size_t fp = (size_t)sp;
// Align stack
sp -= 2;
*--sp = (size_t)returnPoint;
*--sp = (size_t)context;
*--sp = (size_t)siginfo;
*--sp = code;
*--sp = fakeFrameReturnAddress;
// Switch the current context to the signal_handler_worker and the original stack
CONTEXT context2;
RtlCaptureContext(&context2);
// We don't care about the other registers state since the stack unwinding restores
// them for the target frame directly from the signal context.
context2.Esp = (size_t)sp;
context2.Ebp = (size_t)fp;
context2.Eip = (size_t)signal_handler_worker;
RtlRestoreContext(&context2, NULL);
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/vm/gchelpers.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
* GCHELPERS.H
*
* GC Allocation and Write Barrier Helpers
*
*
*/
#ifndef _GCHELPERS_H_
#define _GCHELPERS_H_
//========================================================================
//
// ALLOCATION HELPERS
//
//========================================================================
// Allocate single-dimensional array given array type
OBJECTREF AllocateSzArray(MethodTable *pArrayMT, INT32 length, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
OBJECTREF AllocateSzArray(TypeHandle arrayType, INT32 length, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
// The main Array allocation routine, can do multi-dimensional
OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
OBJECTREF AllocateArrayEx(TypeHandle arrayType, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
// Create a SD array of primitive types given an element type
OBJECTREF AllocatePrimitiveArray(CorElementType type, DWORD cElements);
// Allocate SD array of object types given an element type
OBJECTREF AllocateObjectArray(DWORD cElements, TypeHandle ElementType, BOOL bAllocateInPinnedHeap = FALSE);
// Allocate a string
STRINGREF AllocateString( DWORD cchStringLength );
OBJECTREF DupArrayForCloning(BASEARRAYREF pRef);
// The JIT requests the EE to specify an allocation helper to use at each new-site.
// The EE makes this choice based on whether context boundaries may be involved,
// whether the type is a COM object, whether it is a large object,
// whether the object requires finalization.
// These functions will throw OutOfMemoryException so don't need to check
// for NULL return value from them.
OBJECTREF AllocateObject(MethodTable *pMT
#ifdef FEATURE_COMINTEROP
, bool fHandleCom = true
#endif
);
extern int StompWriteBarrierEphemeral(bool isRuntimeSuspended);
extern int StompWriteBarrierResize(bool isRuntimeSuspended, bool bReqUpperBoundsCheck);
extern int SwitchToWriteWatchBarrier(bool isRuntimeSuspended);
extern int SwitchToNonWriteWatchBarrier(bool isRuntimeSuspended);
extern void FlushWriteBarrierInstructionCache();
extern void ThrowOutOfMemoryDimensionsExceeded();
//========================================================================
//
// WRITE BARRIER HELPERS
//
//========================================================================
void ErectWriteBarrier(OBJECTREF* dst, OBJECTREF ref);
void SetCardsAfterBulkCopy(Object **start, size_t len);
#endif // _GCHELPERS_H_
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
* GCHELPERS.H
*
* GC Allocation and Write Barrier Helpers
*
*
*/
#ifndef _GCHELPERS_H_
#define _GCHELPERS_H_
//========================================================================
//
// ALLOCATION HELPERS
//
//========================================================================
// Allocate single-dimensional array given array type
OBJECTREF AllocateSzArray(MethodTable *pArrayMT, INT32 length, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
OBJECTREF AllocateSzArray(TypeHandle arrayType, INT32 length, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
// The main Array allocation routine, can do multi-dimensional
OBJECTREF AllocateArrayEx(MethodTable *pArrayMT, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
OBJECTREF AllocateArrayEx(TypeHandle arrayType, INT32 *pArgs, DWORD dwNumArgs, GC_ALLOC_FLAGS flags = GC_ALLOC_NO_FLAGS);
// Create a SD array of primitive types given an element type
OBJECTREF AllocatePrimitiveArray(CorElementType type, DWORD cElements);
// Allocate SD array of object types given an element type
OBJECTREF AllocateObjectArray(DWORD cElements, TypeHandle ElementType, BOOL bAllocateInPinnedHeap = FALSE);
// Allocate a string
STRINGREF AllocateString( DWORD cchStringLength );
OBJECTREF DupArrayForCloning(BASEARRAYREF pRef);
// The JIT requests the EE to specify an allocation helper to use at each new-site.
// The EE makes this choice based on whether context boundaries may be involved,
// whether the type is a COM object, whether it is a large object,
// whether the object requires finalization.
// These functions will throw OutOfMemoryException so don't need to check
// for NULL return value from them.
OBJECTREF AllocateObject(MethodTable *pMT
#ifdef FEATURE_COMINTEROP
, bool fHandleCom = true
#endif
);
extern int StompWriteBarrierEphemeral(bool isRuntimeSuspended);
extern int StompWriteBarrierResize(bool isRuntimeSuspended, bool bReqUpperBoundsCheck);
extern int SwitchToWriteWatchBarrier(bool isRuntimeSuspended);
extern int SwitchToNonWriteWatchBarrier(bool isRuntimeSuspended);
extern void FlushWriteBarrierInstructionCache();
extern void ThrowOutOfMemoryDimensionsExceeded();
//========================================================================
//
// WRITE BARRIER HELPERS
//
//========================================================================
void ErectWriteBarrier(OBJECTREF* dst, OBJECTREF ref);
void SetCardsAfterBulkCopy(Object **start, size_t len);
#endif // _GCHELPERS_H_
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApiV2/baseline/Bug78587a.txt
|
<out xmlns:id="id" xmlns:cap="capitalizer">
<id>first</id>
<ID>FIRST</ID>
</out>
|
<out xmlns:id="id" xmlns:cap="capitalizer">
<id>first</id>
<ID>FIRST</ID>
</out>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/libunwind/src/oop/_OOP_internal.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _OOP_internal_h
#define _OOP_internal_h
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "libunwind_i.h"
#include "dwarf-eh.h"
#include "dwarf_i.h"
#endif /* _OOP_internal_h */
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _OOP_internal_h
#define _OOP_internal_h
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include "libunwind_i.h"
#include "dwarf-eh.h"
#include "dwarf_i.h"
#endif /* _OOP_internal_h */
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/exception/signal.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
exception/signal.cpp
Abstract:
Signal handler implementation (map signals to exceptions)
--*/
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/corunix.hpp"
#include "pal/handleapi.hpp"
#include "pal/process.h"
#include "pal/thread.hpp"
#include "pal/threadinfo.hpp"
#include "pal/threadsusp.hpp"
#include "pal/seh.hpp"
#include "pal/signal.hpp"
#include "pal/palinternal.h"
#include <clrconfignocache.h>
#include <errno.h>
#include <signal.h>
#if !HAVE_MACH_EXCEPTIONS
#include "pal/init.h"
#include "pal/debug.h"
#include "pal/virtual.h"
#include "pal/utils.h"
#include <string.h>
#include <sys/ucontext.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <sys/mman.h>
#endif // !HAVE_MACH_EXCEPTIONS
#include "pal/context.h"
#ifdef SIGRTMIN
#define INJECT_ACTIVATION_SIGNAL SIGRTMIN
#else
#define INJECT_ACTIVATION_SIGNAL SIGUSR1
#endif
#if !defined(INJECT_ACTIVATION_SIGNAL) && defined(FEATURE_HIJACK)
#error FEATURE_HIJACK requires INJECT_ACTIVATION_SIGNAL to be defined
#endif
using namespace CorUnix;
/* local type definitions *****************************************************/
typedef void (*SIGFUNC)(int, siginfo_t *, void *);
/* internal function declarations *********************************************/
static void sigterm_handler(int code, siginfo_t *siginfo, void *context);
#ifdef INJECT_ACTIVATION_SIGNAL
static void inject_activation_handler(int code, siginfo_t *siginfo, void *context);
#endif
static void sigill_handler(int code, siginfo_t *siginfo, void *context);
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context);
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context);
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context);
static void sigbus_handler(int code, siginfo_t *siginfo, void *context);
static void sigint_handler(int code, siginfo_t *siginfo, void *context);
static void sigquit_handler(int code, siginfo_t *siginfo, void *context);
static void sigabrt_handler(int code, siginfo_t *siginfo, void *context);
static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...);
static void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags = 0, bool skipIgnored = false);
static void restore_signal(int signal_id, struct sigaction *previousAction);
static void restore_signal_and_resend(int code, struct sigaction* action);
/* internal data declarations *********************************************/
bool g_registered_signal_handlers = false;
#if !HAVE_MACH_EXCEPTIONS
bool g_enable_alternate_stack_check = false;
#endif // !HAVE_MACH_EXCEPTIONS
static bool g_registered_sigterm_handler = false;
static bool g_registered_activation_handler = false;
struct sigaction g_previous_sigterm;
#ifdef INJECT_ACTIVATION_SIGNAL
struct sigaction g_previous_activation;
#endif
struct sigaction g_previous_sigill;
struct sigaction g_previous_sigtrap;
struct sigaction g_previous_sigfpe;
struct sigaction g_previous_sigbus;
struct sigaction g_previous_sigsegv;
struct sigaction g_previous_sigint;
struct sigaction g_previous_sigquit;
struct sigaction g_previous_sigabrt;
#if !HAVE_MACH_EXCEPTIONS
// TOP of special stack for handling stack overflow
volatile void* g_stackOverflowHandlerStack = NULL;
// Flag that is or-ed with SIGSEGV to indicate that the SIGSEGV was a stack overflow
const int StackOverflowFlag = 0x40000000;
#endif // !HAVE_MACH_EXCEPTIONS
/* public function definitions ************************************************/
/*++
Function :
SEHInitializeSignals
Set up signal handlers to catch signals and translate them to exceptions
Parameters :
None
Return :
TRUE in case of a success, FALSE otherwise
--*/
BOOL SEHInitializeSignals(CorUnix::CPalThread *pthrCurrent, DWORD flags)
{
TRACE("Initializing signal handlers %04x\n", flags);
#if !HAVE_MACH_EXCEPTIONS
g_enable_alternate_stack_check = false;
CLRConfigNoCache stackCheck = CLRConfigNoCache::Get("EnableAlternateStackCheck", /*noprefix*/ false, &getenv);
if (stackCheck.IsSet())
{
DWORD value;
if (stackCheck.TryAsInteger(10, value))
g_enable_alternate_stack_check = (value != 0);
}
#endif
if (flags & PAL_INITIALIZE_REGISTER_SIGNALS)
{
g_registered_signal_handlers = true;
/* we call handle_signal for every possible signal, even
if we don't provide a signal handler.
handle_signal will set SA_RESTART flag for specified signal.
Therefore, all signals will have SA_RESTART flag set, preventing
slow Unix system calls from being interrupted. On systems without
siginfo_t, SIGKILL and SIGSTOP can't be restarted, so we don't
handle those signals. Both the Darwin and FreeBSD man pages say
that SIGKILL and SIGSTOP can't be handled, but FreeBSD allows us
to register a handler for them anyway. We don't do that.
see sigaction man page for more details
*/
handle_signal(SIGILL, sigill_handler, &g_previous_sigill);
handle_signal(SIGFPE, sigfpe_handler, &g_previous_sigfpe);
handle_signal(SIGBUS, sigbus_handler, &g_previous_sigbus);
handle_signal(SIGABRT, sigabrt_handler, &g_previous_sigabrt);
// We don't setup a handler for SIGINT/SIGQUIT when those signals are ignored.
// Otherwise our child processes would reset to the default on exec causing them
// to terminate on these signals.
handle_signal(SIGINT, sigint_handler, &g_previous_sigint, 0 /* additionalFlags */, true /* skipIgnored */);
handle_signal(SIGQUIT, sigquit_handler, &g_previous_sigquit, 0 /* additionalFlags */, true /* skipIgnored */);
#if HAVE_MACH_EXCEPTIONS
handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv);
#else
handle_signal(SIGTRAP, sigtrap_handler, &g_previous_sigtrap);
// SIGSEGV handler runs on a separate stack so that we can handle stack overflow
handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv, SA_ONSTACK);
if (!pthrCurrent->EnsureSignalAlternateStack())
{
return FALSE;
}
// Allocate the minimal stack necessary for handling stack overflow
int stackOverflowStackSize = ALIGN_UP(sizeof(SignalHandlerWorkerReturnPoint), 16) + 7 * 4096;
// Align the size to virtual page size and add one virtual page as a stack guard
stackOverflowStackSize = ALIGN_UP(stackOverflowStackSize, GetVirtualPageSize()) + GetVirtualPageSize();
int flags = MAP_ANONYMOUS | MAP_PRIVATE;
#ifdef MAP_STACK
flags |= MAP_STACK;
#endif
g_stackOverflowHandlerStack = mmap(NULL, stackOverflowStackSize, PROT_READ | PROT_WRITE, flags, -1, 0);
if (g_stackOverflowHandlerStack == MAP_FAILED)
{
return FALSE;
}
// create a guard page for the alternate stack
int st = mprotect((void*)g_stackOverflowHandlerStack, GetVirtualPageSize(), PROT_NONE);
if (st != 0)
{
munmap((void*)g_stackOverflowHandlerStack, stackOverflowStackSize);
return FALSE;
}
g_stackOverflowHandlerStack = (void*)((size_t)g_stackOverflowHandlerStack + stackOverflowStackSize);
#endif // HAVE_MACH_EXCEPTIONS
}
/* The default action for SIGPIPE is process termination.
Since SIGPIPE can be signaled when trying to write on a socket for which
the connection has been dropped, we need to tell the system we want
to ignore this signal.
Instead of terminating the process, the system call which would had
issued a SIGPIPE will, instead, report an error and set errno to EPIPE.
*/
signal(SIGPIPE, SIG_IGN);
if (flags & PAL_INITIALIZE_REGISTER_SIGTERM_HANDLER)
{
g_registered_sigterm_handler = true;
handle_signal(SIGTERM, sigterm_handler, &g_previous_sigterm);
}
#ifdef INJECT_ACTIVATION_SIGNAL
if (flags & PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL)
{
handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation);
g_registered_activation_handler = true;
}
#endif
return TRUE;
}
/*++
Function :
SEHCleanupSignals
Restore default signal handlers
Parameters :
None
(no return value)
note :
reason for this function is that during PAL_Terminate, we reach a point where
SEH isn't possible anymore (handle manager is off, etc). Past that point,
we can't avoid crashing on a signal.
--*/
void SEHCleanupSignals()
{
TRACE("Restoring default signal handlers\n");
if (g_registered_signal_handlers)
{
restore_signal(SIGILL, &g_previous_sigill);
#if !HAVE_MACH_EXCEPTIONS
restore_signal(SIGTRAP, &g_previous_sigtrap);
#endif
restore_signal(SIGFPE, &g_previous_sigfpe);
restore_signal(SIGBUS, &g_previous_sigbus);
restore_signal(SIGABRT, &g_previous_sigabrt);
restore_signal(SIGSEGV, &g_previous_sigsegv);
restore_signal(SIGINT, &g_previous_sigint);
restore_signal(SIGQUIT, &g_previous_sigquit);
}
#ifdef INJECT_ACTIVATION_SIGNAL
if (g_registered_activation_handler)
{
restore_signal(INJECT_ACTIVATION_SIGNAL, &g_previous_activation);
}
#endif
if (g_registered_sigterm_handler)
{
restore_signal(SIGTERM, &g_previous_sigterm);
}
}
/*++
Function :
SEHCleanupAbort()
Restore default SIGABORT signal handlers
(no parameters, no return value)
--*/
void SEHCleanupAbort()
{
if (g_registered_signal_handlers)
{
restore_signal(SIGABRT, &g_previous_sigabrt);
}
}
/* internal function definitions **********************************************/
/*++
Function :
IsRunningOnAlternateStack
Detects if the current signal handlers is running on an alternate stack
Parameters :
The context of the signal
Return :
true if we are running on an alternate stack
--*/
bool IsRunningOnAlternateStack(void *context)
{
#if HAVE_MACH_EXCEPTIONS
return false;
#else
bool isRunningOnAlternateStack;
if (g_enable_alternate_stack_check)
{
// Note: WSL doesn't return the alternate signal ranges in the uc_stack (the whole structure is zeroed no
// matter whether the code is running on an alternate stack or not). So the check would always fail on WSL.
stack_t *signalStack = &((native_context_t *)context)->uc_stack;
// Check if the signalStack local variable address is within the alternate stack range. If it is not,
// then either the alternate stack was not installed at all or the current method is not running on it.
void* alternateStackEnd = (char *)signalStack->ss_sp + signalStack->ss_size;
isRunningOnAlternateStack = ((signalStack->ss_flags & SS_DISABLE) == 0) && (signalStack->ss_sp <= &signalStack) && (&signalStack < alternateStackEnd);
}
else
{
// If alternate stack check is disabled, consider always that we are running on an alternate
// signal handler stack.
isRunningOnAlternateStack = true;
}
return isRunningOnAlternateStack;
#endif // HAVE_MACH_EXCEPTIONS
}
static bool IsSaSigInfo(struct sigaction* action)
{
return (action->sa_flags & SA_SIGINFO) != 0;
}
static bool IsSigDfl(struct sigaction* action)
{
// macOS can return sigaction with SIG_DFL and SA_SIGINFO.
// SA_SIGINFO means we should use sa_sigaction, but here we want to check sa_handler.
// So we ignore SA_SIGINFO when sa_sigaction and sa_handler are at the same address.
return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) &&
action->sa_handler == SIG_DFL;
}
static bool IsSigIgn(struct sigaction* action)
{
return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) &&
action->sa_handler == SIG_IGN;
}
/*++
Function :
invoke_previous_action
synchronously invokes the previous action or aborts when that is not possible
Parameters :
action : previous sigaction struct
code : signal code
siginfo : signal siginfo
context : signal context
signalRestarts: BOOL state : TRUE if the process will be signalled again
(no return value)
--*/
static void invoke_previous_action(struct sigaction* action, int code, siginfo_t *siginfo, void *context, bool signalRestarts = true)
{
_ASSERTE(action != NULL);
if (IsSigIgn(action))
{
if (signalRestarts)
{
// This signal mustn't be ignored because it will be restarted.
PROCAbort(code);
}
return;
}
else if (IsSigDfl(action))
{
if (signalRestarts)
{
// Restore the original and restart h/w exception.
restore_signal(code, action);
}
else
{
// We can't invoke the original handler because returning from the
// handler doesn't restart the exception.
PROCAbort(code);
}
}
else if (IsSaSigInfo(action))
{
// Directly call the previous handler.
_ASSERTE(action->sa_sigaction != NULL);
action->sa_sigaction(code, siginfo, context);
}
else
{
// Directly call the previous handler.
_ASSERTE(action->sa_handler != NULL);
action->sa_handler(code);
}
PROCNotifyProcessShutdown(IsRunningOnAlternateStack(context));
PROCCreateCrashDumpIfEnabled(code);
}
/*++
Function :
sigill_handler
handle SIGILL signal (EXCEPTION_ILLEGAL_INSTRUCTION, others?)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigill_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
invoke_previous_action(&g_previous_sigill, code, siginfo, context);
}
/*++
Function :
sigfpe_handler
handle SIGFPE signal (division by zero, floating point exception)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
invoke_previous_action(&g_previous_sigfpe, code, siginfo, context);
}
#if !HAVE_MACH_EXCEPTIONS
/*++
Function :
signal_handler_worker
Handles signal on the original stack where the signal occured.
Invoked via setcontext.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
extern "C" void signal_handler_worker(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint)
{
// TODO: First variable parameter says whether a read (0) or write (non-0) caused the
// fault. We must disassemble the instruction at record.ExceptionAddress
// to correctly fill in this value.
// Unmask the activation signal now that we are running on the original stack of the thread
sigset_t signal_set;
sigemptyset(&signal_set);
sigaddset(&signal_set, INJECT_ACTIVATION_SIGNAL);
int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
returnPoint->returnFromHandler = common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr);
// We are going to return to the alternate stack, so block the activation signal again
sigmaskRet = pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
RtlRestoreContext(&returnPoint->context, NULL);
}
/*++
Function :
SwitchStackAndExecuteHandler
Switch to the stack specified by the sp argument
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
sp - stack pointer of the stack to execute the handler on.
If sp == 0, execute it on the original stack where the signal has occured.
Return :
The return value from the signal handler
--*/
static bool SwitchStackAndExecuteHandler(int code, siginfo_t *siginfo, void *context, size_t sp)
{
// Establish a return point in case the common_signal_handler returns
volatile bool contextInitialization = true;
void *ptr = alloca(sizeof(SignalHandlerWorkerReturnPoint) + alignof(SignalHandlerWorkerReturnPoint) - 1);
SignalHandlerWorkerReturnPoint *pReturnPoint = (SignalHandlerWorkerReturnPoint *)ALIGN_UP(ptr, alignof(SignalHandlerWorkerReturnPoint));
RtlCaptureContext(&pReturnPoint->context);
// When the signal handler worker completes, it uses setcontext to return to this point
if (contextInitialization)
{
contextInitialization = false;
ExecuteHandlerOnCustomStack(code, siginfo, context, sp, pReturnPoint);
_ASSERTE(FALSE); // The ExecuteHandlerOnCustomStack should never return
}
return pReturnPoint->returnFromHandler;
}
#endif // !HAVE_MACH_EXCEPTIONS
/*++
Function :
sigsegv_handler
handle SIGSEGV signal (EXCEPTION_ACCESS_VIOLATION, others)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context)
{
#if !HAVE_MACH_EXCEPTIONS
if (PALIsInitialized())
{
// First check if we have a stack overflow
size_t sp = (size_t)GetNativeContextSP((native_context_t *)context);
size_t failureAddress = (size_t)siginfo->si_addr;
// If the failure address is at most one page above or below the stack pointer,
// we have a stack overflow.
if ((failureAddress - (sp - GetVirtualPageSize())) < 2 * GetVirtualPageSize())
{
if (GetCurrentPalThread())
{
size_t handlerStackTop = __sync_val_compare_and_swap((size_t*)&g_stackOverflowHandlerStack, (size_t)g_stackOverflowHandlerStack, 0);
if (handlerStackTop == 0)
{
// We have only one stack for handling stack overflow preallocated. We let only the first thread that hits stack overflow to
// run the exception handling code on that stack (which ends up just dumping the stack trace and aborting the process).
// Other threads are held spinning and sleeping here until the process exits.
while (true)
{
sleep(1);
}
}
if (SwitchStackAndExecuteHandler(code | StackOverflowFlag, siginfo, context, (size_t)handlerStackTop))
{
PROCAbort(SIGSEGV);
}
}
else
{
(void)!write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1);
PROCAbort(SIGSEGV);
}
}
// Now that we know the SIGSEGV didn't happen due to a stack overflow, execute the common
// hardware signal handler on the original stack.
if (GetCurrentPalThread() && IsRunningOnAlternateStack(context))
{
if (SwitchStackAndExecuteHandler(code, siginfo, context, 0 /* sp */)) // sp == 0 indicates execution on the original stack
{
return;
}
}
else
{
// The code flow gets here when the signal handler is not running on an alternate stack or when it wasn't created
// by coreclr. In both cases, we execute the common_signal_handler directly.
// If thread isn't created by coreclr and has alternate signal stack GetCurrentPalThread() will return NULL too.
// But since in this case we don't handle hardware exceptions (IsSafeToHandleHardwareException returns false)
// we can call common_signal_handler on the alternate stack.
if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr))
{
return;
}
}
}
#endif // !HAVE_MACH_EXCEPTIONS
invoke_previous_action(&g_previous_sigsegv, code, siginfo, context);
}
/*++
Function :
sigtrap_handler
handle SIGTRAP signal (EXCEPTION_SINGLE_STEP, EXCEPTION_BREAKPOINT)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
// The signal doesn't restart, returning from a SIGTRAP handler continues execution past the trap.
invoke_previous_action(&g_previous_sigtrap, code, siginfo, context, /* signalRestarts */ false);
}
/*++
Function :
sigbus_handler
handle SIGBUS signal (EXCEPTION_ACCESS_VIOLATION?)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigbus_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
// TODO: First variable parameter says whether a read (0) or write (non-0) caused the
// fault. We must disassemble the instruction at record.ExceptionAddress
// to correctly fill in this value.
if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr))
{
return;
}
}
invoke_previous_action(&g_previous_sigbus, code, siginfo, context);
}
/*++
Function :
sigabrt_handler
handle SIGABRT signal - abort() API
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigabrt_handler(int code, siginfo_t *siginfo, void *context)
{
invoke_previous_action(&g_previous_sigabrt, code, siginfo, context);
}
/*++
Function :
sigint_handler
handle SIGINT signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigint_handler(int code, siginfo_t *siginfo, void *context)
{
PROCNotifyProcessShutdown();
restore_signal_and_resend(code, &g_previous_sigint);
}
/*++
Function :
sigquit_handler
handle SIGQUIT signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigquit_handler(int code, siginfo_t *siginfo, void *context)
{
PROCNotifyProcessShutdown();
restore_signal_and_resend(code, &g_previous_sigquit);
}
/*++
Function :
sigterm_handler
handle SIGTERM signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigterm_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
// g_pSynchronizationManager shouldn't be null if PAL is initialized.
_ASSERTE(g_pSynchronizationManager != nullptr);
g_pSynchronizationManager->SendTerminationRequestToWorkerThread();
}
else
{
restore_signal_and_resend(SIGTERM, &g_previous_sigterm);
}
}
#ifdef INJECT_ACTIVATION_SIGNAL
/*++
Function :
inject_activation_handler
Handle the INJECT_ACTIVATION_SIGNAL signal. This signal interrupts a running thread
so it can call the activation function that was specified when sending the signal.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void inject_activation_handler(int code, siginfo_t *siginfo, void *context)
{
// Only accept activations from the current process
if (g_activationFunction != NULL && (siginfo->si_pid == getpid()
#ifdef HOST_OSX
// On OSX si_pid is sometimes 0. It was confirmed by Apple to be expected, as the si_pid is tracked at the process level. So when multiple
// signals are in flight in the same process at the same time, it may be overwritten / zeroed.
|| siginfo->si_pid == 0
#endif
))
{
_ASSERTE(g_safeActivationCheckFunction != NULL);
native_context_t *ucontext = (native_context_t *)context;
CONTEXT winContext;
CONTEXTFromNativeContext(
ucontext,
&winContext,
CONTEXT_CONTROL | CONTEXT_INTEGER);
if (g_safeActivationCheckFunction(CONTEXTGetPC(&winContext), /* checkingCurrentThread */ TRUE))
{
int savedErrNo = errno; // Make sure that errno is not modified
g_activationFunction(&winContext);
errno = savedErrNo;
// Activation function may have modified the context, so update it.
CONTEXTToNativeContext(&winContext, ucontext);
}
}
else
{
// Call the original handler when it is not ignored or default (terminate).
if (g_previous_activation.sa_flags & SA_SIGINFO)
{
_ASSERTE(g_previous_activation.sa_sigaction != NULL);
g_previous_activation.sa_sigaction(code, siginfo, context);
}
else
{
if (g_previous_activation.sa_handler != SIG_IGN &&
g_previous_activation.sa_handler != SIG_DFL)
{
_ASSERTE(g_previous_activation.sa_handler != NULL);
g_previous_activation.sa_handler(code);
}
}
}
}
#endif
/*++
Function :
InjectActivationInternal
Interrupt the specified thread and have it call the activationFunction passed in
Parameters :
pThread - target PAL thread
activationFunction - function to call
(no return value)
--*/
PAL_ERROR InjectActivationInternal(CorUnix::CPalThread* pThread)
{
#ifdef INJECT_ACTIVATION_SIGNAL
int status = pthread_kill(pThread->GetPThreadSelf(), INJECT_ACTIVATION_SIGNAL);
// We can get EAGAIN when printing stack overflow stack trace and when other threads hit
// stack overflow too. Those are held in the sigsegv_handler with blocked signals until
// the process exits.
#ifdef __APPLE__
// On Apple, pthread_kill is not allowed to be sent to dispatch queue threads
if (status == ENOTSUP)
{
return ERROR_NOT_SUPPORTED;
}
#endif
if ((status != 0) && (status != EAGAIN))
{
// Failure to send the signal is fatal. There are only two cases when sending
// the signal can fail. First, if the signal ID is invalid and second,
// if the thread doesn't exist anymore.
PROCAbort();
}
return NO_ERROR;
#else
return ERROR_CANCELLED;
#endif
}
#if !HAVE_MACH_EXCEPTIONS
/*++
Function :
signal_ignore_handler
Simple signal handler which does nothing
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void signal_ignore_handler(int code, siginfo_t *siginfo, void *context)
{
}
#endif // !HAVE_MACH_EXCEPTIONS
void PAL_IgnoreProfileSignal(int signalNum)
{
#if !HAVE_MACH_EXCEPTIONS
// Add a signal handler which will ignore signals
// This will allow signal to be used as a marker in perf recording.
// This will be used as an aid to synchronize recorded profile with
// test cases
//
// signal(signalNum, SGN_IGN) can not be used here. It will ignore
// the signal in kernel space and therefore generate no recordable
// event for profiling. Preventing it being used for profile
// synchronization
//
// Since this is only used in rare circumstances no attempt to
// restore the old handler will be made
handle_signal(signalNum, signal_ignore_handler, 0);
#endif
}
/*++
Function :
common_signal_handler
common code for all signal handlers
Parameters :
int code : signal received
siginfo_t *siginfo : siginfo passed to the signal handler
void *context : context structure passed to the signal handler
int numParams : number of variable parameters of the exception
... : variable parameters of the exception (each of size_t type)
Returns true if the execution should continue or false if the exception was unhandled
Note:
the "pointers" parameter should contain a valid exception record pointer,
but the ContextRecord pointer will be overwritten.
--*/
__attribute__((noinline))
static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...)
{
#if !HAVE_MACH_EXCEPTIONS
sigset_t signal_set;
CONTEXT signalContextRecord;
CONTEXT* signalContextRecordPtr = &signalContextRecord;
EXCEPTION_RECORD exceptionRecord;
native_context_t *ucontext;
ucontext = (native_context_t *)sigcontext;
g_hardware_exception_context_locvar_offset = (int)((char*)&signalContextRecordPtr - (char*)__builtin_frame_address(0));
if (code == (SIGSEGV | StackOverflowFlag))
{
exceptionRecord.ExceptionCode = EXCEPTION_STACK_OVERFLOW;
code &= ~StackOverflowFlag;
}
else
{
exceptionRecord.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
}
exceptionRecord.ExceptionFlags = EXCEPTION_IS_SIGNAL;
exceptionRecord.ExceptionRecord = NULL;
exceptionRecord.ExceptionAddress = GetNativeContextPC(ucontext);
exceptionRecord.NumberParameters = numParams;
va_list params;
va_start(params, numParams);
for (int i = 0; i < numParams; i++)
{
exceptionRecord.ExceptionInformation[i] = va_arg(params, size_t);
}
// Pre-populate context with data from current frame, because ucontext doesn't have some data (e.g. SS register)
// which is required for restoring context
RtlCaptureContext(&signalContextRecord);
ULONG contextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT;
#if defined(HOST_AMD64)
contextFlags |= CONTEXT_XSTATE;
#endif
// Fill context record with required information. from pal.h:
// On non-Win32 platforms, the CONTEXT pointer in the
// PEXCEPTION_POINTERS will contain at least the CONTEXT_CONTROL registers.
CONTEXTFromNativeContext(ucontext, &signalContextRecord, contextFlags);
/* Unmask signal so we can receive it again */
sigemptyset(&signal_set);
sigaddset(&signal_set, code);
int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
signalContextRecord.ContextFlags |= CONTEXT_EXCEPTION_ACTIVE;
// The exception object takes ownership of the exceptionRecord and contextRecord
PAL_SEHException exception(&exceptionRecord, &signalContextRecord, true);
if (SEHProcessException(&exception))
{
// Exception handling may have modified the context, so update it.
CONTEXTToNativeContext(exception.ExceptionPointers.ContextRecord, ucontext);
return true;
}
#endif // !HAVE_MACH_EXCEPTIONS
return false;
}
/*++
Function :
handle_signal
register handler for specified signal
Parameters :
int signal_id : signal to handle
SIGFUNC sigfunc : signal handler
previousAction : previous sigaction struct
(no return value)
note : if sigfunc is NULL, the default signal handler is restored
--*/
void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags, bool skipIgnored)
{
struct sigaction newAction;
newAction.sa_flags = SA_RESTART | additionalFlags;
newAction.sa_handler = NULL;
newAction.sa_sigaction = sigfunc;
newAction.sa_flags |= SA_SIGINFO;
sigemptyset(&newAction.sa_mask);
#ifdef INJECT_ACTIVATION_SIGNAL
if ((additionalFlags & SA_ONSTACK) != 0)
{
// A handler that runs on a separate stack should not be interrupted by the activation signal
// until it switches back to the regular stack, since that signal's handler would run on the
// limited separate stack and likely run into a stack overflow.
sigaddset(&newAction.sa_mask, INJECT_ACTIVATION_SIGNAL);
}
#endif
if (skipIgnored)
{
if (-1 == sigaction(signal_id, NULL, previousAction))
{
ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
else if (previousAction->sa_handler == SIG_IGN)
{
return;
}
}
if (-1 == sigaction(signal_id, &newAction, previousAction))
{
ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
}
/*++
Function :
restore_signal
restore handler for specified signal
Parameters :
int signal_id : signal to handle
previousAction : previous sigaction struct to restore
(no return value)
--*/
void restore_signal(int signal_id, struct sigaction *previousAction)
{
if (-1 == sigaction(signal_id, previousAction, NULL))
{
ASSERT("restore_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
}
/*++
Function :
restore_signal_and_resend
restore handler for specified signal and signal the process
Parameters :
int signal_id : signal to handle
previousAction : previous sigaction struct to restore
(no return value)
--*/
void restore_signal_and_resend(int signal_id, struct sigaction* previousAction)
{
restore_signal(signal_id, previousAction);
kill(gPID, signal_id);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
exception/signal.cpp
Abstract:
Signal handler implementation (map signals to exceptions)
--*/
#include "pal/dbgmsg.h"
SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do this first
#include "pal/corunix.hpp"
#include "pal/handleapi.hpp"
#include "pal/process.h"
#include "pal/thread.hpp"
#include "pal/threadinfo.hpp"
#include "pal/threadsusp.hpp"
#include "pal/seh.hpp"
#include "pal/signal.hpp"
#include "pal/palinternal.h"
#include <clrconfignocache.h>
#include <errno.h>
#include <signal.h>
#if !HAVE_MACH_EXCEPTIONS
#include "pal/init.h"
#include "pal/debug.h"
#include "pal/virtual.h"
#include "pal/utils.h"
#include <string.h>
#include <sys/ucontext.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <sys/mman.h>
#endif // !HAVE_MACH_EXCEPTIONS
#include "pal/context.h"
#ifdef SIGRTMIN
#define INJECT_ACTIVATION_SIGNAL SIGRTMIN
#else
#define INJECT_ACTIVATION_SIGNAL SIGUSR1
#endif
#if !defined(INJECT_ACTIVATION_SIGNAL) && defined(FEATURE_HIJACK)
#error FEATURE_HIJACK requires INJECT_ACTIVATION_SIGNAL to be defined
#endif
using namespace CorUnix;
/* local type definitions *****************************************************/
typedef void (*SIGFUNC)(int, siginfo_t *, void *);
/* internal function declarations *********************************************/
static void sigterm_handler(int code, siginfo_t *siginfo, void *context);
#ifdef INJECT_ACTIVATION_SIGNAL
static void inject_activation_handler(int code, siginfo_t *siginfo, void *context);
#endif
static void sigill_handler(int code, siginfo_t *siginfo, void *context);
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context);
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context);
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context);
static void sigbus_handler(int code, siginfo_t *siginfo, void *context);
static void sigint_handler(int code, siginfo_t *siginfo, void *context);
static void sigquit_handler(int code, siginfo_t *siginfo, void *context);
static void sigabrt_handler(int code, siginfo_t *siginfo, void *context);
static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...);
static void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags = 0, bool skipIgnored = false);
static void restore_signal(int signal_id, struct sigaction *previousAction);
static void restore_signal_and_resend(int code, struct sigaction* action);
/* internal data declarations *********************************************/
bool g_registered_signal_handlers = false;
#if !HAVE_MACH_EXCEPTIONS
bool g_enable_alternate_stack_check = false;
#endif // !HAVE_MACH_EXCEPTIONS
static bool g_registered_sigterm_handler = false;
static bool g_registered_activation_handler = false;
struct sigaction g_previous_sigterm;
#ifdef INJECT_ACTIVATION_SIGNAL
struct sigaction g_previous_activation;
#endif
struct sigaction g_previous_sigill;
struct sigaction g_previous_sigtrap;
struct sigaction g_previous_sigfpe;
struct sigaction g_previous_sigbus;
struct sigaction g_previous_sigsegv;
struct sigaction g_previous_sigint;
struct sigaction g_previous_sigquit;
struct sigaction g_previous_sigabrt;
#if !HAVE_MACH_EXCEPTIONS
// TOP of special stack for handling stack overflow
volatile void* g_stackOverflowHandlerStack = NULL;
// Flag that is or-ed with SIGSEGV to indicate that the SIGSEGV was a stack overflow
const int StackOverflowFlag = 0x40000000;
#endif // !HAVE_MACH_EXCEPTIONS
/* public function definitions ************************************************/
/*++
Function :
SEHInitializeSignals
Set up signal handlers to catch signals and translate them to exceptions
Parameters :
None
Return :
TRUE in case of a success, FALSE otherwise
--*/
BOOL SEHInitializeSignals(CorUnix::CPalThread *pthrCurrent, DWORD flags)
{
TRACE("Initializing signal handlers %04x\n", flags);
#if !HAVE_MACH_EXCEPTIONS
g_enable_alternate_stack_check = false;
CLRConfigNoCache stackCheck = CLRConfigNoCache::Get("EnableAlternateStackCheck", /*noprefix*/ false, &getenv);
if (stackCheck.IsSet())
{
DWORD value;
if (stackCheck.TryAsInteger(10, value))
g_enable_alternate_stack_check = (value != 0);
}
#endif
if (flags & PAL_INITIALIZE_REGISTER_SIGNALS)
{
g_registered_signal_handlers = true;
/* we call handle_signal for every possible signal, even
if we don't provide a signal handler.
handle_signal will set SA_RESTART flag for specified signal.
Therefore, all signals will have SA_RESTART flag set, preventing
slow Unix system calls from being interrupted. On systems without
siginfo_t, SIGKILL and SIGSTOP can't be restarted, so we don't
handle those signals. Both the Darwin and FreeBSD man pages say
that SIGKILL and SIGSTOP can't be handled, but FreeBSD allows us
to register a handler for them anyway. We don't do that.
see sigaction man page for more details
*/
handle_signal(SIGILL, sigill_handler, &g_previous_sigill);
handle_signal(SIGFPE, sigfpe_handler, &g_previous_sigfpe);
handle_signal(SIGBUS, sigbus_handler, &g_previous_sigbus);
handle_signal(SIGABRT, sigabrt_handler, &g_previous_sigabrt);
// We don't setup a handler for SIGINT/SIGQUIT when those signals are ignored.
// Otherwise our child processes would reset to the default on exec causing them
// to terminate on these signals.
handle_signal(SIGINT, sigint_handler, &g_previous_sigint, 0 /* additionalFlags */, true /* skipIgnored */);
handle_signal(SIGQUIT, sigquit_handler, &g_previous_sigquit, 0 /* additionalFlags */, true /* skipIgnored */);
#if HAVE_MACH_EXCEPTIONS
handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv);
#else
handle_signal(SIGTRAP, sigtrap_handler, &g_previous_sigtrap);
// SIGSEGV handler runs on a separate stack so that we can handle stack overflow
handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv, SA_ONSTACK);
if (!pthrCurrent->EnsureSignalAlternateStack())
{
return FALSE;
}
// Allocate the minimal stack necessary for handling stack overflow
int stackOverflowStackSize = ALIGN_UP(sizeof(SignalHandlerWorkerReturnPoint), 16) + 7 * 4096;
// Align the size to virtual page size and add one virtual page as a stack guard
stackOverflowStackSize = ALIGN_UP(stackOverflowStackSize, GetVirtualPageSize()) + GetVirtualPageSize();
int flags = MAP_ANONYMOUS | MAP_PRIVATE;
#ifdef MAP_STACK
flags |= MAP_STACK;
#endif
g_stackOverflowHandlerStack = mmap(NULL, stackOverflowStackSize, PROT_READ | PROT_WRITE, flags, -1, 0);
if (g_stackOverflowHandlerStack == MAP_FAILED)
{
return FALSE;
}
// create a guard page for the alternate stack
int st = mprotect((void*)g_stackOverflowHandlerStack, GetVirtualPageSize(), PROT_NONE);
if (st != 0)
{
munmap((void*)g_stackOverflowHandlerStack, stackOverflowStackSize);
return FALSE;
}
g_stackOverflowHandlerStack = (void*)((size_t)g_stackOverflowHandlerStack + stackOverflowStackSize);
#endif // HAVE_MACH_EXCEPTIONS
}
/* The default action for SIGPIPE is process termination.
Since SIGPIPE can be signaled when trying to write on a socket for which
the connection has been dropped, we need to tell the system we want
to ignore this signal.
Instead of terminating the process, the system call which would had
issued a SIGPIPE will, instead, report an error and set errno to EPIPE.
*/
signal(SIGPIPE, SIG_IGN);
if (flags & PAL_INITIALIZE_REGISTER_SIGTERM_HANDLER)
{
g_registered_sigterm_handler = true;
handle_signal(SIGTERM, sigterm_handler, &g_previous_sigterm);
}
#ifdef INJECT_ACTIVATION_SIGNAL
if (flags & PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL)
{
handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation);
g_registered_activation_handler = true;
}
#endif
return TRUE;
}
/*++
Function :
SEHCleanupSignals
Restore default signal handlers
Parameters :
None
(no return value)
note :
reason for this function is that during PAL_Terminate, we reach a point where
SEH isn't possible anymore (handle manager is off, etc). Past that point,
we can't avoid crashing on a signal.
--*/
void SEHCleanupSignals()
{
TRACE("Restoring default signal handlers\n");
if (g_registered_signal_handlers)
{
restore_signal(SIGILL, &g_previous_sigill);
#if !HAVE_MACH_EXCEPTIONS
restore_signal(SIGTRAP, &g_previous_sigtrap);
#endif
restore_signal(SIGFPE, &g_previous_sigfpe);
restore_signal(SIGBUS, &g_previous_sigbus);
restore_signal(SIGABRT, &g_previous_sigabrt);
restore_signal(SIGSEGV, &g_previous_sigsegv);
restore_signal(SIGINT, &g_previous_sigint);
restore_signal(SIGQUIT, &g_previous_sigquit);
}
#ifdef INJECT_ACTIVATION_SIGNAL
if (g_registered_activation_handler)
{
restore_signal(INJECT_ACTIVATION_SIGNAL, &g_previous_activation);
}
#endif
if (g_registered_sigterm_handler)
{
restore_signal(SIGTERM, &g_previous_sigterm);
}
}
/*++
Function :
SEHCleanupAbort()
Restore default SIGABORT signal handlers
(no parameters, no return value)
--*/
void SEHCleanupAbort()
{
if (g_registered_signal_handlers)
{
restore_signal(SIGABRT, &g_previous_sigabrt);
}
}
/* internal function definitions **********************************************/
/*++
Function :
IsRunningOnAlternateStack
Detects if the current signal handlers is running on an alternate stack
Parameters :
The context of the signal
Return :
true if we are running on an alternate stack
--*/
bool IsRunningOnAlternateStack(void *context)
{
#if HAVE_MACH_EXCEPTIONS
return false;
#else
bool isRunningOnAlternateStack;
if (g_enable_alternate_stack_check)
{
// Note: WSL doesn't return the alternate signal ranges in the uc_stack (the whole structure is zeroed no
// matter whether the code is running on an alternate stack or not). So the check would always fail on WSL.
stack_t *signalStack = &((native_context_t *)context)->uc_stack;
// Check if the signalStack local variable address is within the alternate stack range. If it is not,
// then either the alternate stack was not installed at all or the current method is not running on it.
void* alternateStackEnd = (char *)signalStack->ss_sp + signalStack->ss_size;
isRunningOnAlternateStack = ((signalStack->ss_flags & SS_DISABLE) == 0) && (signalStack->ss_sp <= &signalStack) && (&signalStack < alternateStackEnd);
}
else
{
// If alternate stack check is disabled, consider always that we are running on an alternate
// signal handler stack.
isRunningOnAlternateStack = true;
}
return isRunningOnAlternateStack;
#endif // HAVE_MACH_EXCEPTIONS
}
static bool IsSaSigInfo(struct sigaction* action)
{
return (action->sa_flags & SA_SIGINFO) != 0;
}
static bool IsSigDfl(struct sigaction* action)
{
// macOS can return sigaction with SIG_DFL and SA_SIGINFO.
// SA_SIGINFO means we should use sa_sigaction, but here we want to check sa_handler.
// So we ignore SA_SIGINFO when sa_sigaction and sa_handler are at the same address.
return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) &&
action->sa_handler == SIG_DFL;
}
static bool IsSigIgn(struct sigaction* action)
{
return (&action->sa_handler == (void*)&action->sa_sigaction || !IsSaSigInfo(action)) &&
action->sa_handler == SIG_IGN;
}
/*++
Function :
invoke_previous_action
synchronously invokes the previous action or aborts when that is not possible
Parameters :
action : previous sigaction struct
code : signal code
siginfo : signal siginfo
context : signal context
signalRestarts: BOOL state : TRUE if the process will be signalled again
(no return value)
--*/
static void invoke_previous_action(struct sigaction* action, int code, siginfo_t *siginfo, void *context, bool signalRestarts = true)
{
_ASSERTE(action != NULL);
if (IsSigIgn(action))
{
if (signalRestarts)
{
// This signal mustn't be ignored because it will be restarted.
PROCAbort(code);
}
return;
}
else if (IsSigDfl(action))
{
if (signalRestarts)
{
// Restore the original and restart h/w exception.
restore_signal(code, action);
}
else
{
// We can't invoke the original handler because returning from the
// handler doesn't restart the exception.
PROCAbort(code);
}
}
else if (IsSaSigInfo(action))
{
// Directly call the previous handler.
_ASSERTE(action->sa_sigaction != NULL);
action->sa_sigaction(code, siginfo, context);
}
else
{
// Directly call the previous handler.
_ASSERTE(action->sa_handler != NULL);
action->sa_handler(code);
}
PROCNotifyProcessShutdown(IsRunningOnAlternateStack(context));
PROCCreateCrashDumpIfEnabled(code);
}
/*++
Function :
sigill_handler
handle SIGILL signal (EXCEPTION_ILLEGAL_INSTRUCTION, others?)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigill_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
invoke_previous_action(&g_previous_sigill, code, siginfo, context);
}
/*++
Function :
sigfpe_handler
handle SIGFPE signal (division by zero, floating point exception)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
invoke_previous_action(&g_previous_sigfpe, code, siginfo, context);
}
#if !HAVE_MACH_EXCEPTIONS
/*++
Function :
signal_handler_worker
Handles signal on the original stack where the signal occured.
Invoked via setcontext.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
returnPoint - context to which the function returns if the common_signal_handler returns
(no return value)
--*/
extern "C" void signal_handler_worker(int code, siginfo_t *siginfo, void *context, SignalHandlerWorkerReturnPoint* returnPoint)
{
// TODO: First variable parameter says whether a read (0) or write (non-0) caused the
// fault. We must disassemble the instruction at record.ExceptionAddress
// to correctly fill in this value.
// Unmask the activation signal now that we are running on the original stack of the thread
sigset_t signal_set;
sigemptyset(&signal_set);
sigaddset(&signal_set, INJECT_ACTIVATION_SIGNAL);
int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
returnPoint->returnFromHandler = common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr);
// We are going to return to the alternate stack, so block the activation signal again
sigmaskRet = pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
RtlRestoreContext(&returnPoint->context, NULL);
}
/*++
Function :
SwitchStackAndExecuteHandler
Switch to the stack specified by the sp argument
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
sp - stack pointer of the stack to execute the handler on.
If sp == 0, execute it on the original stack where the signal has occured.
Return :
The return value from the signal handler
--*/
static bool SwitchStackAndExecuteHandler(int code, siginfo_t *siginfo, void *context, size_t sp)
{
// Establish a return point in case the common_signal_handler returns
volatile bool contextInitialization = true;
void *ptr = alloca(sizeof(SignalHandlerWorkerReturnPoint) + alignof(SignalHandlerWorkerReturnPoint) - 1);
SignalHandlerWorkerReturnPoint *pReturnPoint = (SignalHandlerWorkerReturnPoint *)ALIGN_UP(ptr, alignof(SignalHandlerWorkerReturnPoint));
RtlCaptureContext(&pReturnPoint->context);
// When the signal handler worker completes, it uses setcontext to return to this point
if (contextInitialization)
{
contextInitialization = false;
ExecuteHandlerOnCustomStack(code, siginfo, context, sp, pReturnPoint);
_ASSERTE(FALSE); // The ExecuteHandlerOnCustomStack should never return
}
return pReturnPoint->returnFromHandler;
}
#endif // !HAVE_MACH_EXCEPTIONS
/*++
Function :
sigsegv_handler
handle SIGSEGV signal (EXCEPTION_ACCESS_VIOLATION, others)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context)
{
#if !HAVE_MACH_EXCEPTIONS
if (PALIsInitialized())
{
// First check if we have a stack overflow
size_t sp = (size_t)GetNativeContextSP((native_context_t *)context);
size_t failureAddress = (size_t)siginfo->si_addr;
// If the failure address is at most one page above or below the stack pointer,
// we have a stack overflow.
if ((failureAddress - (sp - GetVirtualPageSize())) < 2 * GetVirtualPageSize())
{
if (GetCurrentPalThread())
{
size_t handlerStackTop = __sync_val_compare_and_swap((size_t*)&g_stackOverflowHandlerStack, (size_t)g_stackOverflowHandlerStack, 0);
if (handlerStackTop == 0)
{
// We have only one stack for handling stack overflow preallocated. We let only the first thread that hits stack overflow to
// run the exception handling code on that stack (which ends up just dumping the stack trace and aborting the process).
// Other threads are held spinning and sleeping here until the process exits.
while (true)
{
sleep(1);
}
}
if (SwitchStackAndExecuteHandler(code | StackOverflowFlag, siginfo, context, (size_t)handlerStackTop))
{
PROCAbort(SIGSEGV);
}
}
else
{
(void)!write(STDERR_FILENO, StackOverflowMessage, sizeof(StackOverflowMessage) - 1);
PROCAbort(SIGSEGV);
}
}
// Now that we know the SIGSEGV didn't happen due to a stack overflow, execute the common
// hardware signal handler on the original stack.
if (GetCurrentPalThread() && IsRunningOnAlternateStack(context))
{
if (SwitchStackAndExecuteHandler(code, siginfo, context, 0 /* sp */)) // sp == 0 indicates execution on the original stack
{
return;
}
}
else
{
// The code flow gets here when the signal handler is not running on an alternate stack or when it wasn't created
// by coreclr. In both cases, we execute the common_signal_handler directly.
// If thread isn't created by coreclr and has alternate signal stack GetCurrentPalThread() will return NULL too.
// But since in this case we don't handle hardware exceptions (IsSafeToHandleHardwareException returns false)
// we can call common_signal_handler on the alternate stack.
if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr))
{
return;
}
}
}
#endif // !HAVE_MACH_EXCEPTIONS
invoke_previous_action(&g_previous_sigsegv, code, siginfo, context);
}
/*++
Function :
sigtrap_handler
handle SIGTRAP signal (EXCEPTION_SINGLE_STEP, EXCEPTION_BREAKPOINT)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
if (common_signal_handler(code, siginfo, context, 0))
{
return;
}
}
// The signal doesn't restart, returning from a SIGTRAP handler continues execution past the trap.
invoke_previous_action(&g_previous_sigtrap, code, siginfo, context, /* signalRestarts */ false);
}
/*++
Function :
sigbus_handler
handle SIGBUS signal (EXCEPTION_ACCESS_VIOLATION?)
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigbus_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
// TODO: First variable parameter says whether a read (0) or write (non-0) caused the
// fault. We must disassemble the instruction at record.ExceptionAddress
// to correctly fill in this value.
if (common_signal_handler(code, siginfo, context, 2, (size_t)0, (size_t)siginfo->si_addr))
{
return;
}
}
invoke_previous_action(&g_previous_sigbus, code, siginfo, context);
}
/*++
Function :
sigabrt_handler
handle SIGABRT signal - abort() API
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigabrt_handler(int code, siginfo_t *siginfo, void *context)
{
invoke_previous_action(&g_previous_sigabrt, code, siginfo, context);
}
/*++
Function :
sigint_handler
handle SIGINT signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigint_handler(int code, siginfo_t *siginfo, void *context)
{
PROCNotifyProcessShutdown();
restore_signal_and_resend(code, &g_previous_sigint);
}
/*++
Function :
sigquit_handler
handle SIGQUIT signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigquit_handler(int code, siginfo_t *siginfo, void *context)
{
PROCNotifyProcessShutdown();
restore_signal_and_resend(code, &g_previous_sigquit);
}
/*++
Function :
sigterm_handler
handle SIGTERM signal
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void sigterm_handler(int code, siginfo_t *siginfo, void *context)
{
if (PALIsInitialized())
{
// g_pSynchronizationManager shouldn't be null if PAL is initialized.
_ASSERTE(g_pSynchronizationManager != nullptr);
g_pSynchronizationManager->SendTerminationRequestToWorkerThread();
}
else
{
restore_signal_and_resend(SIGTERM, &g_previous_sigterm);
}
}
#ifdef INJECT_ACTIVATION_SIGNAL
/*++
Function :
inject_activation_handler
Handle the INJECT_ACTIVATION_SIGNAL signal. This signal interrupts a running thread
so it can call the activation function that was specified when sending the signal.
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void inject_activation_handler(int code, siginfo_t *siginfo, void *context)
{
// Only accept activations from the current process
if (g_activationFunction != NULL && (siginfo->si_pid == getpid()
#ifdef HOST_OSX
// On OSX si_pid is sometimes 0. It was confirmed by Apple to be expected, as the si_pid is tracked at the process level. So when multiple
// signals are in flight in the same process at the same time, it may be overwritten / zeroed.
|| siginfo->si_pid == 0
#endif
))
{
_ASSERTE(g_safeActivationCheckFunction != NULL);
native_context_t *ucontext = (native_context_t *)context;
CONTEXT winContext;
CONTEXTFromNativeContext(
ucontext,
&winContext,
CONTEXT_CONTROL | CONTEXT_INTEGER);
if (g_safeActivationCheckFunction(CONTEXTGetPC(&winContext), /* checkingCurrentThread */ TRUE))
{
int savedErrNo = errno; // Make sure that errno is not modified
g_activationFunction(&winContext);
errno = savedErrNo;
// Activation function may have modified the context, so update it.
CONTEXTToNativeContext(&winContext, ucontext);
}
}
else
{
// Call the original handler when it is not ignored or default (terminate).
if (g_previous_activation.sa_flags & SA_SIGINFO)
{
_ASSERTE(g_previous_activation.sa_sigaction != NULL);
g_previous_activation.sa_sigaction(code, siginfo, context);
}
else
{
if (g_previous_activation.sa_handler != SIG_IGN &&
g_previous_activation.sa_handler != SIG_DFL)
{
_ASSERTE(g_previous_activation.sa_handler != NULL);
g_previous_activation.sa_handler(code);
}
}
}
}
#endif
/*++
Function :
InjectActivationInternal
Interrupt the specified thread and have it call the activationFunction passed in
Parameters :
pThread - target PAL thread
activationFunction - function to call
(no return value)
--*/
PAL_ERROR InjectActivationInternal(CorUnix::CPalThread* pThread)
{
#ifdef INJECT_ACTIVATION_SIGNAL
int status = pthread_kill(pThread->GetPThreadSelf(), INJECT_ACTIVATION_SIGNAL);
// We can get EAGAIN when printing stack overflow stack trace and when other threads hit
// stack overflow too. Those are held in the sigsegv_handler with blocked signals until
// the process exits.
#ifdef __APPLE__
// On Apple, pthread_kill is not allowed to be sent to dispatch queue threads
if (status == ENOTSUP)
{
return ERROR_NOT_SUPPORTED;
}
#endif
if ((status != 0) && (status != EAGAIN))
{
// Failure to send the signal is fatal. There are only two cases when sending
// the signal can fail. First, if the signal ID is invalid and second,
// if the thread doesn't exist anymore.
PROCAbort();
}
return NO_ERROR;
#else
return ERROR_CANCELLED;
#endif
}
#if !HAVE_MACH_EXCEPTIONS
/*++
Function :
signal_ignore_handler
Simple signal handler which does nothing
Parameters :
POSIX signal handler parameter list ("man sigaction" for details)
(no return value)
--*/
static void signal_ignore_handler(int code, siginfo_t *siginfo, void *context)
{
}
#endif // !HAVE_MACH_EXCEPTIONS
void PAL_IgnoreProfileSignal(int signalNum)
{
#if !HAVE_MACH_EXCEPTIONS
// Add a signal handler which will ignore signals
// This will allow signal to be used as a marker in perf recording.
// This will be used as an aid to synchronize recorded profile with
// test cases
//
// signal(signalNum, SGN_IGN) can not be used here. It will ignore
// the signal in kernel space and therefore generate no recordable
// event for profiling. Preventing it being used for profile
// synchronization
//
// Since this is only used in rare circumstances no attempt to
// restore the old handler will be made
handle_signal(signalNum, signal_ignore_handler, 0);
#endif
}
/*++
Function :
common_signal_handler
common code for all signal handlers
Parameters :
int code : signal received
siginfo_t *siginfo : siginfo passed to the signal handler
void *context : context structure passed to the signal handler
int numParams : number of variable parameters of the exception
... : variable parameters of the exception (each of size_t type)
Returns true if the execution should continue or false if the exception was unhandled
Note:
the "pointers" parameter should contain a valid exception record pointer,
but the ContextRecord pointer will be overwritten.
--*/
__attribute__((noinline))
static bool common_signal_handler(int code, siginfo_t *siginfo, void *sigcontext, int numParams, ...)
{
#if !HAVE_MACH_EXCEPTIONS
sigset_t signal_set;
CONTEXT signalContextRecord;
CONTEXT* signalContextRecordPtr = &signalContextRecord;
EXCEPTION_RECORD exceptionRecord;
native_context_t *ucontext;
ucontext = (native_context_t *)sigcontext;
g_hardware_exception_context_locvar_offset = (int)((char*)&signalContextRecordPtr - (char*)__builtin_frame_address(0));
if (code == (SIGSEGV | StackOverflowFlag))
{
exceptionRecord.ExceptionCode = EXCEPTION_STACK_OVERFLOW;
code &= ~StackOverflowFlag;
}
else
{
exceptionRecord.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
}
exceptionRecord.ExceptionFlags = EXCEPTION_IS_SIGNAL;
exceptionRecord.ExceptionRecord = NULL;
exceptionRecord.ExceptionAddress = GetNativeContextPC(ucontext);
exceptionRecord.NumberParameters = numParams;
va_list params;
va_start(params, numParams);
for (int i = 0; i < numParams; i++)
{
exceptionRecord.ExceptionInformation[i] = va_arg(params, size_t);
}
// Pre-populate context with data from current frame, because ucontext doesn't have some data (e.g. SS register)
// which is required for restoring context
RtlCaptureContext(&signalContextRecord);
ULONG contextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT;
#if defined(HOST_AMD64)
contextFlags |= CONTEXT_XSTATE;
#endif
// Fill context record with required information. from pal.h:
// On non-Win32 platforms, the CONTEXT pointer in the
// PEXCEPTION_POINTERS will contain at least the CONTEXT_CONTROL registers.
CONTEXTFromNativeContext(ucontext, &signalContextRecord, contextFlags);
/* Unmask signal so we can receive it again */
sigemptyset(&signal_set);
sigaddset(&signal_set, code);
int sigmaskRet = pthread_sigmask(SIG_UNBLOCK, &signal_set, NULL);
if (sigmaskRet != 0)
{
ASSERT("pthread_sigmask failed; error number is %d\n", sigmaskRet);
}
signalContextRecord.ContextFlags |= CONTEXT_EXCEPTION_ACTIVE;
// The exception object takes ownership of the exceptionRecord and contextRecord
PAL_SEHException exception(&exceptionRecord, &signalContextRecord, true);
if (SEHProcessException(&exception))
{
// Exception handling may have modified the context, so update it.
CONTEXTToNativeContext(exception.ExceptionPointers.ContextRecord, ucontext);
return true;
}
#endif // !HAVE_MACH_EXCEPTIONS
return false;
}
/*++
Function :
handle_signal
register handler for specified signal
Parameters :
int signal_id : signal to handle
SIGFUNC sigfunc : signal handler
previousAction : previous sigaction struct
(no return value)
note : if sigfunc is NULL, the default signal handler is restored
--*/
void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction, int additionalFlags, bool skipIgnored)
{
struct sigaction newAction;
newAction.sa_flags = SA_RESTART | additionalFlags;
newAction.sa_handler = NULL;
newAction.sa_sigaction = sigfunc;
newAction.sa_flags |= SA_SIGINFO;
sigemptyset(&newAction.sa_mask);
#ifdef INJECT_ACTIVATION_SIGNAL
if ((additionalFlags & SA_ONSTACK) != 0)
{
// A handler that runs on a separate stack should not be interrupted by the activation signal
// until it switches back to the regular stack, since that signal's handler would run on the
// limited separate stack and likely run into a stack overflow.
sigaddset(&newAction.sa_mask, INJECT_ACTIVATION_SIGNAL);
}
#endif
if (skipIgnored)
{
if (-1 == sigaction(signal_id, NULL, previousAction))
{
ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
else if (previousAction->sa_handler == SIG_IGN)
{
return;
}
}
if (-1 == sigaction(signal_id, &newAction, previousAction))
{
ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
}
/*++
Function :
restore_signal
restore handler for specified signal
Parameters :
int signal_id : signal to handle
previousAction : previous sigaction struct to restore
(no return value)
--*/
void restore_signal(int signal_id, struct sigaction *previousAction)
{
if (-1 == sigaction(signal_id, previousAction, NULL))
{
ASSERT("restore_signal: sigaction() call failed with error code %d (%s)\n",
errno, strerror(errno));
}
}
/*++
Function :
restore_signal_and_resend
restore handler for specified signal and signal the process
Parameters :
int signal_id : signal to handle
previousAction : previous sigaction struct to restore
(no return value)
--*/
void restore_signal_and_resend(int signal_id, struct sigaction* previousAction)
{
restore_signal(signal_id, previousAction);
kill(gPID, signal_id);
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/Interop/ICustomMarshaler/ConflictingNames/CMakeLists.txt
|
project (CustomMarshalersConflictingNames)
include_directories(${INC_PLATFORM_DIR})
set(SOURCES CustomMarshalerNative.cpp )
# add the executable
add_library (CustomMarshalerNative SHARED ${SOURCES})
target_link_libraries(CustomMarshalerNative ${LINK_LIBRARIES_ADDITIONAL})
# add the install targets
install (TARGETS CustomMarshalerNative DESTINATION bin)
|
project (CustomMarshalersConflictingNames)
include_directories(${INC_PLATFORM_DIR})
set(SOURCES CustomMarshalerNative.cpp )
# add the executable
add_library (CustomMarshalerNative SHARED ${SOURCES})
target_link_libraries(CustomMarshalerNative ${LINK_LIBRARIES_ADDITIONAL})
# add the install targets
install (TARGETS CustomMarshalerNative DESTINATION bin)
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/binder/applicationcontext.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ============================================================
//
// ApplicationContext.cpp
//
//
// Implements the ApplicationContext class
//
// ============================================================
#include "applicationcontext.hpp"
#include "stringarraylist.h"
#include "loadcontext.hpp"
#include "failurecache.hpp"
#include "assemblyidentitycache.hpp"
#include "utils.hpp"
#include "ex.h"
#include "clr/fs/path.h"
using namespace clr::fs;
namespace BINDER_SPACE
{
ApplicationContext::ApplicationContext()
{
m_pExecutionContext = NULL;
m_pFailureCache = NULL;
m_contextCS = NULL;
m_pTrustedPlatformAssemblyMap = nullptr;
}
ApplicationContext::~ApplicationContext()
{
SAFE_DELETE(m_pExecutionContext);
SAFE_DELETE(m_pFailureCache);
if (m_contextCS != NULL)
{
ClrDeleteCriticalSection(m_contextCS);
}
if (m_pTrustedPlatformAssemblyMap != nullptr)
{
delete m_pTrustedPlatformAssemblyMap;
}
}
HRESULT ApplicationContext::Init()
{
HRESULT hr = S_OK;
NewHolder<ExecutionContext> pExecutionContext;
FailureCache *pFailureCache = NULL;
// Allocate context objects
SAFE_NEW(pExecutionContext, ExecutionContext);
SAFE_NEW(pFailureCache, FailureCache);
m_contextCS = ClrCreateCriticalSection(
CrstFusionAppCtx,
CRST_REENTRANCY);
if (!m_contextCS)
{
SAFE_DELETE(pFailureCache);
hr = E_OUTOFMEMORY;
}
else
{
m_pExecutionContext = pExecutionContext.Extract();
m_pFailureCache = pFailureCache;
}
Exit:
return hr;
}
HRESULT ApplicationContext::SetupBindingPaths(SString &sTrustedPlatformAssemblies,
SString &sPlatformResourceRoots,
SString &sAppPaths,
BOOL fAcquireLock)
{
HRESULT hr = S_OK;
CRITSEC_Holder contextLock(fAcquireLock ? GetCriticalSectionCookie() : NULL);
if (m_pTrustedPlatformAssemblyMap != nullptr)
{
GO_WITH_HRESULT(S_OK);
}
//
// Parse TrustedPlatformAssemblies
//
m_pTrustedPlatformAssemblyMap = new SimpleNameToFileNameMap();
sTrustedPlatformAssemblies.Normalize();
for (SString::Iterator i = sTrustedPlatformAssemblies.Begin(); i != sTrustedPlatformAssemblies.End(); )
{
SString fileName;
SString simpleName;
bool isNativeImage = false;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextTPAPath(sTrustedPlatformAssemblies, i, /*dllOnly*/ false, fileName, simpleName, isNativeImage));
if (pathResult == S_FALSE)
{
break;
}
const SimpleNameToFileNameMapEntry *pExistingEntry = m_pTrustedPlatformAssemblyMap->LookupPtr(simpleName.GetUnicode());
if (pExistingEntry != nullptr)
{
//
// We want to store only the first entry matching a simple name we encounter.
// The exception is if we first store an IL reference and later in the string
// we encounter a native image. Since we don't touch IL in the presence of
// native images, we replace the IL entry with the NI.
//
if ((pExistingEntry->m_wszILFileName != nullptr && !isNativeImage) ||
(pExistingEntry->m_wszNIFileName != nullptr && isNativeImage))
{
continue;
}
}
LPWSTR wszSimpleName = nullptr;
if (pExistingEntry == nullptr)
{
wszSimpleName = new WCHAR[simpleName.GetCount() + 1];
if (wszSimpleName == nullptr)
{
GO_WITH_HRESULT(E_OUTOFMEMORY);
}
wcscpy_s(wszSimpleName, simpleName.GetCount() + 1, simpleName.GetUnicode());
}
else
{
wszSimpleName = pExistingEntry->m_wszSimpleName;
}
LPWSTR wszFileName = new WCHAR[fileName.GetCount() + 1];
if (wszFileName == nullptr)
{
GO_WITH_HRESULT(E_OUTOFMEMORY);
}
wcscpy_s(wszFileName, fileName.GetCount() + 1, fileName.GetUnicode());
SimpleNameToFileNameMapEntry mapEntry;
mapEntry.m_wszSimpleName = wszSimpleName;
if (isNativeImage)
{
mapEntry.m_wszNIFileName = wszFileName;
mapEntry.m_wszILFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszILFileName;
}
else
{
mapEntry.m_wszILFileName = wszFileName;
mapEntry.m_wszNIFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszNIFileName;
}
m_pTrustedPlatformAssemblyMap->AddOrReplace(mapEntry);
}
//
// Parse PlatformResourceRoots
//
sPlatformResourceRoots.Normalize();
for (SString::Iterator i = sPlatformResourceRoots.Begin(); i != sPlatformResourceRoots.End(); )
{
SString pathName;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextPath(sPlatformResourceRoots, i, pathName));
if (pathResult == S_FALSE)
{
break;
}
if (Path::IsRelative(pathName))
{
GO_WITH_HRESULT(E_INVALIDARG);
}
m_platformResourceRoots.Append(pathName);
}
//
// Parse AppPaths
//
sAppPaths.Normalize();
for (SString::Iterator i = sAppPaths.Begin(); i != sAppPaths.End(); )
{
SString pathName;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextPath(sAppPaths, i, pathName));
if (pathResult == S_FALSE)
{
break;
}
if (Path::IsRelative(pathName))
{
GO_WITH_HRESULT(E_INVALIDARG);
}
m_appPaths.Append(pathName);
}
Exit:
return hr;
}
HRESULT ApplicationContext::GetAssemblyIdentity(LPCSTR szTextualIdentity,
AssemblyIdentityUTF8 **ppAssemblyIdentity)
{
HRESULT hr = S_OK;
_ASSERTE(szTextualIdentity != NULL);
_ASSERTE(ppAssemblyIdentity != NULL);
CRITSEC_Holder contextLock(GetCriticalSectionCookie());
AssemblyIdentityUTF8 *pAssemblyIdentity = m_assemblyIdentityCache.Lookup(szTextualIdentity);
if (pAssemblyIdentity == NULL)
{
NewHolder<AssemblyIdentityUTF8> pNewAssemblyIdentity;
SString sTextualIdentity;
SAFE_NEW(pNewAssemblyIdentity, AssemblyIdentityUTF8);
sTextualIdentity.SetUTF8(szTextualIdentity);
IF_FAIL_GO(TextualIdentityParser::Parse(sTextualIdentity, pNewAssemblyIdentity));
IF_FAIL_GO(m_assemblyIdentityCache.Add(szTextualIdentity, pNewAssemblyIdentity));
pNewAssemblyIdentity->PopulateUTF8Fields();
pAssemblyIdentity = pNewAssemblyIdentity.Extract();
}
*ppAssemblyIdentity = pAssemblyIdentity;
Exit:
return hr;
}
bool ApplicationContext::IsTpaListProvided()
{
return m_pTrustedPlatformAssemblyMap != nullptr;
}
};
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ============================================================
//
// ApplicationContext.cpp
//
//
// Implements the ApplicationContext class
//
// ============================================================
#include "applicationcontext.hpp"
#include "stringarraylist.h"
#include "loadcontext.hpp"
#include "failurecache.hpp"
#include "assemblyidentitycache.hpp"
#include "utils.hpp"
#include "ex.h"
#include "clr/fs/path.h"
using namespace clr::fs;
namespace BINDER_SPACE
{
ApplicationContext::ApplicationContext()
{
m_pExecutionContext = NULL;
m_pFailureCache = NULL;
m_contextCS = NULL;
m_pTrustedPlatformAssemblyMap = nullptr;
}
ApplicationContext::~ApplicationContext()
{
SAFE_DELETE(m_pExecutionContext);
SAFE_DELETE(m_pFailureCache);
if (m_contextCS != NULL)
{
ClrDeleteCriticalSection(m_contextCS);
}
if (m_pTrustedPlatformAssemblyMap != nullptr)
{
delete m_pTrustedPlatformAssemblyMap;
}
}
HRESULT ApplicationContext::Init()
{
HRESULT hr = S_OK;
NewHolder<ExecutionContext> pExecutionContext;
FailureCache *pFailureCache = NULL;
// Allocate context objects
SAFE_NEW(pExecutionContext, ExecutionContext);
SAFE_NEW(pFailureCache, FailureCache);
m_contextCS = ClrCreateCriticalSection(
CrstFusionAppCtx,
CRST_REENTRANCY);
if (!m_contextCS)
{
SAFE_DELETE(pFailureCache);
hr = E_OUTOFMEMORY;
}
else
{
m_pExecutionContext = pExecutionContext.Extract();
m_pFailureCache = pFailureCache;
}
Exit:
return hr;
}
HRESULT ApplicationContext::SetupBindingPaths(SString &sTrustedPlatformAssemblies,
SString &sPlatformResourceRoots,
SString &sAppPaths,
BOOL fAcquireLock)
{
HRESULT hr = S_OK;
CRITSEC_Holder contextLock(fAcquireLock ? GetCriticalSectionCookie() : NULL);
if (m_pTrustedPlatformAssemblyMap != nullptr)
{
GO_WITH_HRESULT(S_OK);
}
//
// Parse TrustedPlatformAssemblies
//
m_pTrustedPlatformAssemblyMap = new SimpleNameToFileNameMap();
sTrustedPlatformAssemblies.Normalize();
for (SString::Iterator i = sTrustedPlatformAssemblies.Begin(); i != sTrustedPlatformAssemblies.End(); )
{
SString fileName;
SString simpleName;
bool isNativeImage = false;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextTPAPath(sTrustedPlatformAssemblies, i, /*dllOnly*/ false, fileName, simpleName, isNativeImage));
if (pathResult == S_FALSE)
{
break;
}
const SimpleNameToFileNameMapEntry *pExistingEntry = m_pTrustedPlatformAssemblyMap->LookupPtr(simpleName.GetUnicode());
if (pExistingEntry != nullptr)
{
//
// We want to store only the first entry matching a simple name we encounter.
// The exception is if we first store an IL reference and later in the string
// we encounter a native image. Since we don't touch IL in the presence of
// native images, we replace the IL entry with the NI.
//
if ((pExistingEntry->m_wszILFileName != nullptr && !isNativeImage) ||
(pExistingEntry->m_wszNIFileName != nullptr && isNativeImage))
{
continue;
}
}
LPWSTR wszSimpleName = nullptr;
if (pExistingEntry == nullptr)
{
wszSimpleName = new WCHAR[simpleName.GetCount() + 1];
if (wszSimpleName == nullptr)
{
GO_WITH_HRESULT(E_OUTOFMEMORY);
}
wcscpy_s(wszSimpleName, simpleName.GetCount() + 1, simpleName.GetUnicode());
}
else
{
wszSimpleName = pExistingEntry->m_wszSimpleName;
}
LPWSTR wszFileName = new WCHAR[fileName.GetCount() + 1];
if (wszFileName == nullptr)
{
GO_WITH_HRESULT(E_OUTOFMEMORY);
}
wcscpy_s(wszFileName, fileName.GetCount() + 1, fileName.GetUnicode());
SimpleNameToFileNameMapEntry mapEntry;
mapEntry.m_wszSimpleName = wszSimpleName;
if (isNativeImage)
{
mapEntry.m_wszNIFileName = wszFileName;
mapEntry.m_wszILFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszILFileName;
}
else
{
mapEntry.m_wszILFileName = wszFileName;
mapEntry.m_wszNIFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszNIFileName;
}
m_pTrustedPlatformAssemblyMap->AddOrReplace(mapEntry);
}
//
// Parse PlatformResourceRoots
//
sPlatformResourceRoots.Normalize();
for (SString::Iterator i = sPlatformResourceRoots.Begin(); i != sPlatformResourceRoots.End(); )
{
SString pathName;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextPath(sPlatformResourceRoots, i, pathName));
if (pathResult == S_FALSE)
{
break;
}
if (Path::IsRelative(pathName))
{
GO_WITH_HRESULT(E_INVALIDARG);
}
m_platformResourceRoots.Append(pathName);
}
//
// Parse AppPaths
//
sAppPaths.Normalize();
for (SString::Iterator i = sAppPaths.Begin(); i != sAppPaths.End(); )
{
SString pathName;
HRESULT pathResult = S_OK;
IF_FAIL_GO(pathResult = GetNextPath(sAppPaths, i, pathName));
if (pathResult == S_FALSE)
{
break;
}
if (Path::IsRelative(pathName))
{
GO_WITH_HRESULT(E_INVALIDARG);
}
m_appPaths.Append(pathName);
}
Exit:
return hr;
}
HRESULT ApplicationContext::GetAssemblyIdentity(LPCSTR szTextualIdentity,
AssemblyIdentityUTF8 **ppAssemblyIdentity)
{
HRESULT hr = S_OK;
_ASSERTE(szTextualIdentity != NULL);
_ASSERTE(ppAssemblyIdentity != NULL);
CRITSEC_Holder contextLock(GetCriticalSectionCookie());
AssemblyIdentityUTF8 *pAssemblyIdentity = m_assemblyIdentityCache.Lookup(szTextualIdentity);
if (pAssemblyIdentity == NULL)
{
NewHolder<AssemblyIdentityUTF8> pNewAssemblyIdentity;
SString sTextualIdentity;
SAFE_NEW(pNewAssemblyIdentity, AssemblyIdentityUTF8);
sTextualIdentity.SetUTF8(szTextualIdentity);
IF_FAIL_GO(TextualIdentityParser::Parse(sTextualIdentity, pNewAssemblyIdentity));
IF_FAIL_GO(m_assemblyIdentityCache.Add(szTextualIdentity, pNewAssemblyIdentity));
pNewAssemblyIdentity->PopulateUTF8Fields();
pAssemblyIdentity = pNewAssemblyIdentity.Extract();
}
*ppAssemblyIdentity = pAssemblyIdentity;
Exit:
return hr;
}
bool ApplicationContext::IsTpaListProvided()
{
return m_pTrustedPlatformAssemblyMap != nullptr;
}
};
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/mono/mono/utils/mono-stack-unwinding.h
|
/**
* \file
* Copyright 2008-2010 Novell, Inc.
* Copyright 2011 Xamarin Inc.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_MONO_STACK_UNWINDING_H__
#define __MONO_MONO_STACK_UNWINDING_H__
#include <mono/metadata/appdomain.h>
#include <mono/metadata/metadata.h>
#include <mono/utils/mono-context.h>
/*
* Possible frame types returned by the stack walker.
*/
typedef enum {
/* Normal managed frames */
FRAME_TYPE_MANAGED = 0,
/* Pseudo frame marking the start of a method invocation done by the soft debugger */
FRAME_TYPE_DEBUGGER_INVOKE = 1,
/* Frame for transitioning to native code */
FRAME_TYPE_MANAGED_TO_NATIVE = 2,
FRAME_TYPE_TRAMPOLINE = 3,
/* Interpreter frame */
FRAME_TYPE_INTERP = 4,
/* Frame for transitioning from interpreter to managed code */
FRAME_TYPE_INTERP_TO_MANAGED = 5,
/* same, but with MonoContext */
FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX = 6,
/* Frame for transitioning to interpreted code */
FRAME_TYPE_INTERP_ENTRY = 7,
/* Frame marking transition to native JIT compiler */
FRAME_TYPE_JIT_ENTRY = 8,
/* Compiled method with IL state */
FRAME_TYPE_IL_STATE = 9,
FRAME_TYPE_NUM = 10
} MonoStackFrameType;
typedef enum {
MONO_UNWIND_NONE = 0x0,
MONO_UNWIND_LOOKUP_IL_OFFSET = 0x1,
/* NOT signal safe */
MONO_UNWIND_LOOKUP_ACTUAL_METHOD = 0x2,
/*
* Store the locations where caller-saved registers are saved on the stack in
* frame->reg_locations. The pointer is only valid during the call to the unwind
* callback.
*/
MONO_UNWIND_REG_LOCATIONS = 0x4,
MONO_UNWIND_DEFAULT = MONO_UNWIND_LOOKUP_ACTUAL_METHOD,
MONO_UNWIND_SIGNAL_SAFE = MONO_UNWIND_NONE,
MONO_UNWIND_LOOKUP_ALL = MONO_UNWIND_LOOKUP_IL_OFFSET | MONO_UNWIND_LOOKUP_ACTUAL_METHOD,
} MonoUnwindOptions;
typedef struct {
MonoStackFrameType type;
/*
* For FRAME_TYPE_MANAGED, otherwise NULL.
*/
MonoJitInfo *ji;
/*
* Same as ji->method.
* Not valid if ASYNC_CONTEXT is true.
*/
MonoMethod *method;
/*
* If ji->method is a gshared method, this is the actual method instance.
* This is only filled if lookup for actual method was requested (MONO_UNWIND_LOOKUP_ACTUAL_METHOD)
* Not valid if ASYNC_CONTEXT is true.
*/
MonoMethod *actual_method;
/* Whenever method is a user level method */
gboolean managed;
/*
* Whenever this frame was loaded in async context.
*/
gboolean async_context;
int native_offset;
/*
* IL offset of this frame.
* Only available if the runtime have debugging enabled (--debug switch) and
* il offset resultion was requested (MONO_UNWIND_LOOKUP_IL_OFFSET)
*/
int il_offset;
/* For FRAME_TYPE_INTERP_EXIT */
gpointer interp_exit_data;
/* For FRAME_TYPE_INTERP */
gpointer interp_frame;
/*
* A stack address associated with the frame which can be used
* to compare frames.
* This is needed because ctx is not changed when unwinding through
* interpreter frames, it still refers to the last native interpreter
* frame.
*/
gpointer frame_addr;
/* The next fields are only useful for the jit */
gpointer lmf;
guint32 unwind_info_len;
guint8 *unwind_info;
host_mgreg_t **reg_locations;
/* For FRAME_TYPE_IL_STATE */
gpointer il_state; /* MonoMethodILState */
} MonoStackFrameInfo;
/*Index into MonoThreadState::unwind_data. */
enum {
MONO_UNWIND_DATA_DOMAIN,
MONO_UNWIND_DATA_LMF,
MONO_UNWIND_DATA_JIT_TLS,
};
/*
* This structs holds all information needed to unwind the stack
* of a thread.
*/
typedef struct {
MonoContext ctx;
gpointer unwind_data [3]; /*right now: domain, lmf and jit_tls*/
gboolean valid;
void *gc_stackdata;
int gc_stackdata_size;
} MonoThreadUnwindState;
#endif
|
/**
* \file
* Copyright 2008-2010 Novell, Inc.
* Copyright 2011 Xamarin Inc.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_MONO_STACK_UNWINDING_H__
#define __MONO_MONO_STACK_UNWINDING_H__
#include <mono/metadata/appdomain.h>
#include <mono/metadata/metadata.h>
#include <mono/utils/mono-context.h>
/*
* Possible frame types returned by the stack walker.
*/
typedef enum {
/* Normal managed frames */
FRAME_TYPE_MANAGED = 0,
/* Pseudo frame marking the start of a method invocation done by the soft debugger */
FRAME_TYPE_DEBUGGER_INVOKE = 1,
/* Frame for transitioning to native code */
FRAME_TYPE_MANAGED_TO_NATIVE = 2,
FRAME_TYPE_TRAMPOLINE = 3,
/* Interpreter frame */
FRAME_TYPE_INTERP = 4,
/* Frame for transitioning from interpreter to managed code */
FRAME_TYPE_INTERP_TO_MANAGED = 5,
/* same, but with MonoContext */
FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX = 6,
/* Frame for transitioning to interpreted code */
FRAME_TYPE_INTERP_ENTRY = 7,
/* Frame marking transition to native JIT compiler */
FRAME_TYPE_JIT_ENTRY = 8,
/* Compiled method with IL state */
FRAME_TYPE_IL_STATE = 9,
FRAME_TYPE_NUM = 10
} MonoStackFrameType;
typedef enum {
MONO_UNWIND_NONE = 0x0,
MONO_UNWIND_LOOKUP_IL_OFFSET = 0x1,
/* NOT signal safe */
MONO_UNWIND_LOOKUP_ACTUAL_METHOD = 0x2,
/*
* Store the locations where caller-saved registers are saved on the stack in
* frame->reg_locations. The pointer is only valid during the call to the unwind
* callback.
*/
MONO_UNWIND_REG_LOCATIONS = 0x4,
MONO_UNWIND_DEFAULT = MONO_UNWIND_LOOKUP_ACTUAL_METHOD,
MONO_UNWIND_SIGNAL_SAFE = MONO_UNWIND_NONE,
MONO_UNWIND_LOOKUP_ALL = MONO_UNWIND_LOOKUP_IL_OFFSET | MONO_UNWIND_LOOKUP_ACTUAL_METHOD,
} MonoUnwindOptions;
typedef struct {
MonoStackFrameType type;
/*
* For FRAME_TYPE_MANAGED, otherwise NULL.
*/
MonoJitInfo *ji;
/*
* Same as ji->method.
* Not valid if ASYNC_CONTEXT is true.
*/
MonoMethod *method;
/*
* If ji->method is a gshared method, this is the actual method instance.
* This is only filled if lookup for actual method was requested (MONO_UNWIND_LOOKUP_ACTUAL_METHOD)
* Not valid if ASYNC_CONTEXT is true.
*/
MonoMethod *actual_method;
/* Whenever method is a user level method */
gboolean managed;
/*
* Whenever this frame was loaded in async context.
*/
gboolean async_context;
int native_offset;
/*
* IL offset of this frame.
* Only available if the runtime have debugging enabled (--debug switch) and
* il offset resultion was requested (MONO_UNWIND_LOOKUP_IL_OFFSET)
*/
int il_offset;
/* For FRAME_TYPE_INTERP_EXIT */
gpointer interp_exit_data;
/* For FRAME_TYPE_INTERP */
gpointer interp_frame;
/*
* A stack address associated with the frame which can be used
* to compare frames.
* This is needed because ctx is not changed when unwinding through
* interpreter frames, it still refers to the last native interpreter
* frame.
*/
gpointer frame_addr;
/* The next fields are only useful for the jit */
gpointer lmf;
guint32 unwind_info_len;
guint8 *unwind_info;
host_mgreg_t **reg_locations;
/* For FRAME_TYPE_IL_STATE */
gpointer il_state; /* MonoMethodILState */
} MonoStackFrameInfo;
/*Index into MonoThreadState::unwind_data. */
enum {
MONO_UNWIND_DATA_DOMAIN,
MONO_UNWIND_DATA_LMF,
MONO_UNWIND_DATA_JIT_TLS,
};
/*
* This structs holds all information needed to unwind the stack
* of a thread.
*/
typedef struct {
MonoContext ctx;
gpointer unwind_data [3]; /*right now: domain, lmf and jit_tls*/
gboolean valid;
void *gc_stackdata;
int gc_stackdata_size;
} MonoThreadUnwindState;
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/vm/encee.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===========================================================================
// File: EnC.CPP
//
//
// Handles EditAndContinue support in the EE
// ===========================================================================
#include "common.h"
#include "dbginterface.h"
#include "dllimport.h"
#include "eeconfig.h"
#include "excep.h"
#include "stackwalk.h"
#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE
#ifdef EnC_SUPPORTED
// can't get this on the helper thread at runtime in ResolveField, so make it static and get when add a field.
#ifdef _DEBUG
static int g_BreakOnEnCResolveField = -1;
#endif
#ifndef DACCESS_COMPILE
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
EditAndContinueModule::EditAndContinueModule(Assembly *pAssembly, mdToken moduleRef, PEAssembly *pPEAssembly)
: Module(pAssembly, moduleRef, pPEAssembly)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
LOG((LF_ENC,LL_INFO100,"EACM::ctor %p\n", this));
m_applyChangesCount = CorDB_DEFAULT_ENC_FUNCTION_VERSION;
}
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
/*virtual*/
void EditAndContinueModule::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LOG((LF_ENC,LL_INFO100,"EACM::Initialize %p\n", this));
Module::Initialize(pamTracker, szName);
}
// Called when the module is being destroyed (eg. AD unload time)
void EditAndContinueModule::Destruct()
{
LIMITED_METHOD_CONTRACT;
LOG((LF_ENC,LL_EVERYTHING,"EACM::Destruct %p\n", this));
// Call the superclass's Destruct method...
Module::Destruct();
}
//---------------------------------------------------------------------------------------
//
// ApplyEditAndContinue - updates this module for an EnC
//
// Arguments:
// cbDeltaMD - number of bytes pointed to by pDeltaMD
// pDeltaMD - pointer to buffer holding the delta metadata
// cbDeltaIL - number of bytes pointed to by pDeltaIL
// pDeltaIL - pointer to buffer holding the delta IL
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
HRESULT EditAndContinueModule::ApplyEditAndContinue(
DWORD cbDeltaMD,
BYTE *pDeltaMD,
DWORD cbDeltaIL,
BYTE *pDeltaIL)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Update the module's EnC version number
++m_applyChangesCount;
LOG((LF_ENC, LL_INFO100, "EACM::AEAC:\n"));
#ifdef _DEBUG
// Debugging hook to optionally break when this method is called
static BOOL shouldBreak = -1;
if (shouldBreak == -1)
shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncApplyChanges);
if (shouldBreak > 0) {
_ASSERTE(!"EncApplyChanges");
}
// Debugging hook to dump out all edits to dmeta and dil files
static BOOL dumpChanges = -1;
if (dumpChanges == -1)
dumpChanges = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncDumpApplyChanges);
if (dumpChanges> 0) {
SString fn;
int ec;
fn.Printf(W("ApplyChanges.%d.dmeta"), m_applyChangesCount);
FILE *fp;
ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
_ASSERTE(SUCCEEDED(ec));
fwrite(pDeltaMD, 1, cbDeltaMD, fp);
fclose(fp);
fn.Printf(W("ApplyChanges.%d.dil"), m_applyChangesCount);
ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
_ASSERTE(SUCCEEDED(ec));
fwrite(pDeltaIL, 1, cbDeltaIL, fp);
fclose(fp);
}
#endif
HRESULT hr = S_OK;
HENUMInternal enumENC;
BYTE *pLocalILMemory = NULL;
IMDInternalImport *pMDImport = NULL;
IMDInternalImport *pNewMDImport = NULL;
CONTRACT_VIOLATION(GCViolation); // SafeComHolder goes to preemptive mode, which will trigger a GC
SafeComHolder<IMDInternalImportENC> pIMDInternalImportENC;
SafeComHolder<IMetaDataEmit> pEmitter;
// Apply the changes. Note that ApplyEditAndContinue() requires read/write metadata. If the metadata is
// not already RW, then ApplyEditAndContinue() will perform the conversion, invalidate the current
// metadata importer, and return us a new one. We can't let that happen. Other parts of the system are
// already using the current metadata importer, some possibly in preemptive GC mode at this very moment.
// Instead, we ensure that the metadata is RW by calling ConvertMDInternalToReadWrite(), which will make
// a new importer if necessary and ensure that new accesses to the metadata use that while still managing
// the lifetime of the old importer. Therefore, we can be sure that ApplyEditAndContinue() won't need to
// make a new importer.
// Ensure the metadata is RW.
EX_TRY
{
// ConvertMDInternalToReadWrite should only ever be called on EnC capable files.
_ASSERTE(IsEditAndContinueCapable()); // this also checks that the file is EnC capable
GetPEAssembly()->ConvertMDInternalToReadWrite();
}
EX_CATCH_HRESULT(hr);
IfFailGo(hr);
// Grab the current importer.
pMDImport = GetMDImport();
// Apply the EnC delta to this module's metadata.
IfFailGo(pMDImport->ApplyEditAndContinue(pDeltaMD, cbDeltaMD, &pNewMDImport));
// The importer should not have changed! We assert that, and back-stop in a retail build just to be sure.
if (pNewMDImport != pMDImport)
{
_ASSERTE( !"ApplyEditAndContinue should not have needed to create a new metadata importer!" );
IfFailGo(CORDBG_E_ENC_INTERNAL_ERROR);
}
// get the delta interface
IfFailGo(pMDImport->QueryInterface(IID_IMDInternalImportENC, (void **)&pIMDInternalImportENC));
// get an emitter interface
IfFailGo(GetMetaDataPublicInterfaceFromInternal(pMDImport, IID_IMetaDataEmit, (void **)&pEmitter));
// Copy the deltaIL into our RVAable IL memory
pLocalILMemory = new BYTE[cbDeltaIL];
memcpy(pLocalILMemory, pDeltaIL, cbDeltaIL);
// Enumerate all of the EnC delta tokens
HENUMInternal::ZeroEnum(&enumENC);
IfFailGo(pIMDInternalImportENC->EnumDeltaTokensInit(&enumENC));
mdToken token;
while (pIMDInternalImportENC->EnumNext(&enumENC, &token))
{
STRESS_LOG3(LF_ENC, LL_INFO100, "EACM::AEAC: updated token %08x; type %08x; rid %08x\n", token, TypeFromToken(token), RidFromToken(token));
switch (TypeFromToken(token))
{
case mdtMethodDef:
// MethodDef token - update/add a method
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found method %08x\n", token));
ULONG dwMethodRVA;
DWORD dwMethodFlags;
IfFailGo(pMDImport->GetMethodImplProps(token, &dwMethodRVA, &dwMethodFlags));
if (dwMethodRVA >= cbDeltaIL)
{
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Failure RVA of %d with cbDeltaIl %d\n", dwMethodRVA, cbDeltaIL));
IfFailGo(E_INVALIDARG);
}
SetDynamicIL(token, (TADDR)(pLocalILMemory + dwMethodRVA), FALSE);
// use module to resolve to method
MethodDesc *pMethod;
pMethod = LookupMethodDef(token);
if (pMethod)
{
// Method exists already - update it
IfFailGo(UpdateMethod(pMethod));
}
else
{
// This is a new method token - create a new method
IfFailGo(AddMethod(token));
}
break;
case mdtFieldDef:
// FieldDef token - add a new field
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found field %08x\n", token));
if (LookupFieldDef(token))
{
// Field already exists - just ignore for now
continue;
}
// Field is new - add it
IfFailGo(AddField(token));
break;
}
}
// Update the AvailableClassHash for reflection, etc. ensure that the new TypeRefs, AssemblyRefs and MethodDefs can be stored.
ApplyMetaData();
ErrExit:
if (pIMDInternalImportENC)
pIMDInternalImportENC->EnumClose(&enumENC);
return hr;
}
//---------------------------------------------------------------------------------------
//
// UpdateMethod - called when a method has been updated by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update, and swap the new IL in as the current
// version of the method.
//
// Arguments:
// pMethod - the method being updated
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::UpdateMethod(MethodDesc *pMethod)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Notify the debugger of the update
if (CORDebuggerAttached())
{
HRESULT hr = g_pDebugInterface->UpdateFunction(pMethod, m_applyChangesCount);
if (FAILED(hr))
{
return hr;
}
}
// Notify the JIT that we've got new IL for this method
// This will ensure that all new calls to the method will go to the new version.
// The runtime does this by never backpatching the methodtable slots in EnC-enabled modules.
LOG((LF_ENC, LL_INFO100000, "EACM::UM: Updating function %s to version %d\n", pMethod->m_pszDebugMethodName, m_applyChangesCount));
// Reset any flags relevant to the old code
//
// Note that this only works since we've very carefullly made sure that _all_ references
// to the Method's code must be to the call/jmp blob immediately in front of the
// MethodDesc itself. See MethodDesc::IsEnCMethod()
//
pMethod->ResetCodeEntryPointForEnC();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// AddMethod - called when a new method is added by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update, and create and add a new MethodDesc to the class.
//
// Arguments:
// token - methodDef token for the method being added
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddMethod(mdMethodDef token)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
mdTypeDef parentTypeDef;
HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AM can't find parent token for method token %08x\n", token));
return E_FAIL;
}
// see if the class is loaded yet.
MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
if (pParentType == NULL)
{
// Class isn't loaded yet, don't have to modify any existing EE data structures beyond the metadata.
// Just notify debugger and return.
LOG((LF_ENC, LL_INFO100, "EnCModule::AM class %08x not loaded (method %08x), our work is done\n", parentTypeDef, token));
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->UpdateNotYetLoadedFunction(token, this, m_applyChangesCount);
}
return hr;
}
// Add the method to the runtime's Class data structures
LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding function %08x to type %08x\n", token, parentTypeDef));
MethodDesc *pMethod = NULL;
hr = EEClass::AddMethod(pParentType, token, 0, &pMethod);
if (FAILED(hr))
{
_ASSERTE(!"Failed to add function");
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AM: Failed to add function %08x with hr %08x\n", token, hr));
return hr;
}
// Tell the debugger about the new method so it gets the version number properly
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->AddFunction(pMethod, m_applyChangesCount);
if (FAILED(hr))
{
_ASSERTE(!"Failed to add function");
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add method %08x to debugger with hr %08x\n", token, hr));
}
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// AddField - called when a new field is added by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update,
//
// Arguments:
// token - fieldDef for the field being added
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddField(mdFieldDef token)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
mdTypeDef parentTypeDef;
HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AF can't find parent token for field token %08x\n", token));
return E_FAIL;
}
// see if the class is loaded yet. If not we don't need to do anything. When this class is
// loaded (with the updated metadata), it will have this field like any other normal field.
// If the class hasn't been loaded, than the debugger shouldn't know anything about it
// so there shouldn't be any harm in not notifying it of the update. For completeness,
// we may want to consider changing this to notify the debugger here as well.
MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
if (pParentType == NULL)
{
LOG((LF_ENC, LL_INFO100, "EnCModule::AF class %08x not loaded (field %08x), our work is done\n", parentTypeDef, token));
return S_OK;
}
// Create a new EnCFieldDesc for the field and add it to the class
LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding field %08x to type %08x\n", token, parentTypeDef));
EnCFieldDesc *pField;
hr = EEClass::AddField(pParentType, token, &pField);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %08x to EE with hr %08x\n", token, hr));
return hr;
}
// Tell the debugger about the new field
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->AddField(pField, m_applyChangesCount);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %08x to debugger with hr %08x\n", token, hr));
}
}
#ifdef _DEBUG
if (g_BreakOnEnCResolveField == -1)
{
g_BreakOnEnCResolveField = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCResolveField);
}
#endif
return hr;
}
//---------------------------------------------------------------------------------------
//
// JitUpdatedFunction - Jit the new version of a function for EnC.
//
// Arguments:
// pMD - the MethodDesc for the method we want to JIT
// pOrigContext - context of thread pointing into original version of the function
//
// Return value:
// Return the address of the newly jitted code or NULL on failure.
//
PCODE EditAndContinueModule::JitUpdatedFunction( MethodDesc *pMD,
CONTEXT *pOrigContext)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_ENC, LL_INFO100, "EnCModule::JitUpdatedFunction for %s\n",
pMD->m_pszDebugMethodName));
PCODE jittedCode = NULL;
GCX_COOP();
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(
CLRConfig::INTERNAL_EncJitUpdatedFunction);
if (shouldBreak > 0) {
_ASSERTE(!"EncJitUpdatedFunction");
}
#endif
// Setup a frame so that has context for the exception
// so that gc can crawl the stack and do the right thing.
_ASSERTE(pOrigContext);
Thread *pCurThread = GetThread();
FrameWithCookie<ResumableFrame> resFrame(pOrigContext);
resFrame.Push(pCurThread);
CONTEXT *pCtxTemp = NULL;
// We need to zero out the filter context so a multi-threaded GC doesn't result
// in somebody else tracing this thread & concluding that we're in JITted code.
// We need to remove the filter context so that if we're in preemptive GC
// mode, we'll either have the filter context, or the ResumableFrame,
// but not both, set.
// Since we're in cooperative mode here, we can swap the two non-atomically here.
pCtxTemp = pCurThread->GetFilterContext();
_ASSERTE(pCtxTemp != NULL); // currently called from within a filter context, protects us during GC-toggle.
pCurThread->SetFilterContext(NULL);
// get the code address (may jit the fcn if not already jitted)
EX_TRY {
if (!pMD->IsPointingToNativeCode())
{
GCX_PREEMP();
pMD->DoPrestub(NULL);
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction JIT successful\n"));
}
else
{
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction function already JITed\n"));
}
jittedCode = pMD->GetNativeCode();
} EX_CATCH {
#ifdef _DEBUG
{
// This is debug-only code to print out the error string, but SString can throw.
// This function is no-throw, and we can't put an EX_TRY inside an EX_CATCH block, so
// we just have the violation.
CONTRACT_VIOLATION(ThrowsViolation);
StackSString exceptionMessage;
SString errorMessage;
GetExceptionMessage(GET_THROWABLE(), exceptionMessage);
errorMessage.AppendASCII("**Error: Probable rude edit.**\n\n"
"EnCModule::JITUpdatedFunction JIT failed with the following exception:\n\n");
errorMessage.Append(exceptionMessage);
StackScratchBuffer buffer;
DbgAssertDialog(__FILE__, __LINE__, errorMessage.GetANSI(buffer));
LOG((LF_ENC, LL_INFO100, errorMessage.GetANSI(buffer)));
}
#endif
} EX_END_CATCH(SwallowAllExceptions)
resFrame.Pop(pCurThread);
// Restore the filter context here (see comment above)
pCurThread->SetFilterContext(pCtxTemp);
return jittedCode;
}
//-----------------------------------------------------------------------------
// Called by EnC to resume the code in a new version of the function.
// This will:
// 1) jit the new function
// 2) set the IP to newILOffset within that new function
// 3) adjust local variables (particularly enregistered vars) to the new func.
// It will not return.
//
// Params:
// pMD - method desc for method being updated. This is not enc-version aware.
// oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
// This is enc-version aware.
// newILOffset - the IL offset to resume execution at within the new function.
// pOrigContext - context of thread pointing into original version of the function.
//
// This function must be called on the thread that's executing the old function.
// This function does not return. Instead, it will remap this thread directly
// to be executing the new function.
//-----------------------------------------------------------------------------
HRESULT EditAndContinueModule::ResumeInUpdatedFunction(
MethodDesc *pMD,
void *oldDebuggerFuncHandle,
SIZE_T newILOffset,
CONTEXT *pOrigContext)
{
#if defined(TARGET_ARM64) || defined(TARGET_ARM)
return E_NOTIMPL;
#else
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction for %s at IL offset 0x%x, ",
pMD->m_pszDebugMethodName, newILOffset));
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(
CLRConfig::INTERNAL_EncResumeInUpdatedFunction);
if (shouldBreak > 0) {
_ASSERTE(!"EncResumeInUpdatedFunction");
}
#endif
HRESULT hr = E_FAIL;
// JIT-compile the updated version of the method
PCODE jittedCode = JitUpdatedFunction(pMD, pOrigContext);
if ( jittedCode == NULL )
return CORDBG_E_ENC_JIT_CANT_UPDATE;
GCX_COOP();
// This will create a new frame and copy old vars to it
// need pointer to old & new code, old & new info
EECodeInfo oldCodeInfo(GetIP(pOrigContext));
_ASSERTE(oldCodeInfo.GetMethodDesc() == pMD);
// Get the new native offset & IP from the new IL offset
LOG((LF_ENC, LL_INFO10000, "EACM::RIUF: About to map IL forwards!\n"));
SIZE_T newNativeOffset = 0;
g_pDebugInterface->MapILInfoToCurrentNative(pMD,
newILOffset,
jittedCode,
&newNativeOffset);
EECodeInfo newCodeInfo(jittedCode + newNativeOffset);
_ASSERTE(newCodeInfo.GetMethodDesc() == pMD);
_ASSERTE(newCodeInfo.GetRelOffset() == newNativeOffset);
_ASSERTE(oldCodeInfo.GetCodeManager() == newCodeInfo.GetCodeManager());
DWORD oldFrameSize = oldCodeInfo.GetFixedStackSize();
DWORD newFrameSize = newCodeInfo.GetFixedStackSize();
// FixContextAndResume() will replace the old stack frame of the function with the new
// one and will initialize that new frame to null. Anything on the stack where that new
// frame sits will be wiped out. This could include anything on the stack right up to or beyond our
// current stack from in ResumeInUpdatedFunction. In order to prevent our current frame from being
// trashed we determine the maximum amount that the stack could grow by and allocate this as a buffer using
// alloca. Then we call FixContextAndResume which can safely rely on the stack because none of it's frames
// state or anything lower can be reached by the new frame.
if( newFrameSize > oldFrameSize)
{
DWORD frameIncrement = newFrameSize - oldFrameSize;
// alloca() has __attribute__((warn_unused_result)) in glibc, for which gcc 11+ issue `-Wunused-result` even with `(void)alloca(..)`,
// so we use additional NOT(!) operator to force unused-result suppression.
(void)!alloca(frameIncrement);
}
// Ask the EECodeManager to actually fill in the context and stack for the new frame so that
// values of locals etc. are preserved.
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction calling FixContextAndResume oldNativeOffset: 0x%x, newNativeOffset: 0x%x,"
"oldFrameSize: 0x%x, newFrameSize: 0x%x\n",
oldCodeInfo.GetRelOffset(), newCodeInfo.GetRelOffset(), oldFrameSize, newFrameSize));
FixContextAndResume(pMD,
oldDebuggerFuncHandle,
pOrigContext,
&oldCodeInfo,
&newCodeInfo);
// At this point we shouldn't have failed, so this is genuinely erroneous.
LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
_ASSERTE(!"Should not return from FixContextAndResume()");
hr = E_FAIL;
// If we fail for any reason we have already potentially trashed with new locals and we have also unwound any
// Win32 handlers on the stack so cannot ever return from this function.
EEPOLICY_HANDLE_FATAL_ERROR(CORDBG_E_ENC_INTERNAL_ERROR);
return hr;
#endif // #if define(TARGET_ARM64) || defined(TARGET_ARM)
}
//---------------------------------------------------------------------------------------
//
// FixContextAndResume - Modify the thread context for EnC remap and resume execution
//
// Arguments:
// pMD - MethodDesc for the method being remapped
// oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
// pContext - the thread's original CONTEXT when the remap opportunity was hit
// pOldCodeInfo - collection of various information about the current frame state
// pNewCodeInfo - information about how we want the frame state to be after the remap
//
// Return Value:
// Doesn't return
//
// Notes:
// WARNING: This method cannot access any stack-data below its frame on the stack
// (i.e. anything allocated in a caller frame), so all stack-based arguments must
// EXPLICITLY be copied by value and this method cannot be inlined. We may need to expand
// the stack frame to accomodate the new method, and so extra buffer space must have
// been allocated on the stack. Note that passing a struct by value (via C++) is not
// enough to ensure its data is really copied (on x64, large structs may internally be
// passed by reference). Thus we explicitly make copies of structs passed in, at the
// beginning.
//
NOINLINE void EditAndContinueModule::FixContextAndResume(
MethodDesc *pMD,
void *oldDebuggerFuncHandle,
T_CONTEXT *pContext,
EECodeInfo *pOldCodeInfo,
EECodeInfo *pNewCodeInfo)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_GC_TRIGGERS; // Sends IPC event
STATIC_CONTRACT_THROWS;
// Create local copies of all structs passed as arguments to prevent them from being overwritten
CONTEXT context;
memcpy(&context, pContext, sizeof(CONTEXT));
pContext = &context;
#if defined(TARGET_AMD64)
// Since we made a copy of the incoming CONTEXT in context, clear any new flags we
// don't understand (like XSAVE), since we'll eventually be passing a CONTEXT based
// on this copy to ClrRestoreNonvolatileContext, and this copy doesn't have the extra info
// required by the XSAVE or other flags.
//
// FUTURE: No reason to ifdef this for amd64-only, except to make this late fix as
// surgical as possible. Would be nice to enable this on x86 early in the next cycle.
pContext->ContextFlags &= CONTEXT_ALL;
#endif // defined(TARGET_AMD64)
EECodeInfo oldCodeInfo;
memcpy(&oldCodeInfo, pOldCodeInfo, sizeof(EECodeInfo));
pOldCodeInfo = &oldCodeInfo;
EECodeInfo newCodeInfo;
memcpy(&newCodeInfo, pNewCodeInfo, sizeof(EECodeInfo));
pNewCodeInfo = &newCodeInfo;
const ICorDebugInfo::NativeVarInfo *pOldVarInfo = NULL;
const ICorDebugInfo::NativeVarInfo *pNewVarInfo = NULL;
SIZE_T oldVarInfoCount = 0;
SIZE_T newVarInfoCount = 0;
// Get the var info which the codemanager will use for updating
// enregistered variables correctly, or variables whose lifetimes differ
// at the update point
g_pDebugInterface->GetVarInfo(pMD, oldDebuggerFuncHandle, &oldVarInfoCount, &pOldVarInfo);
g_pDebugInterface->GetVarInfo(pMD, NULL, &newVarInfoCount, &pNewVarInfo);
#ifdef TARGET_X86
// save the frame pointer as FixContextForEnC might step on it.
LPVOID oldSP = dac_cast<PTR_VOID>(GetSP(pContext));
// need to pop the SEH records before write over the stack in FixContextForEnC
PopSEHRecords(oldSP);
#endif
// Ask the EECodeManager to actually fill in the context and stack for the new frame so that
// values of locals etc. are preserved.
HRESULT hr = pNewCodeInfo->GetCodeManager()->FixContextForEnC(
pContext,
pOldCodeInfo,
pOldVarInfo, oldVarInfoCount,
pNewCodeInfo,
pNewVarInfo, newVarInfoCount);
// If FixContextForEnC succeeded, the stack is potentially trashed with any new locals and we have also unwound
// any Win32 handlers on the stack so cannot ever return from this function. If FixContextForEnC failed, can't
// assume that the stack is still intact so apply the proper policy for a fatal EE error to bring us down
// "gracefully" (it's all relative).
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::ResumeInUpdatedFunction for FixContextForEnC failed\n"));
EEPOLICY_HANDLE_FATAL_ERROR(hr);
}
// Set the new IP
// Note that all we're really doing here is setting the IP register. We unfortunately don't
// share any code with the implementation of debugger SetIP, despite the similarities.
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction: Resume at EIP=%p\n", pNewCodeInfo->GetCodeAddress()));
Thread *pCurThread = GetThread();
pCurThread->SetFilterContext(pContext);
SetIP(pContext, pNewCodeInfo->GetCodeAddress());
// Notify the debugger that we're about to resume execution in the new version of the method
HRESULT hrIgnore = g_pDebugInterface->RemapComplete(pMD, pNewCodeInfo->GetCodeAddress(), pNewCodeInfo->GetRelOffset());
// Now jump into the new version of the method. Note that we can't just setup the filter context
// and return because we are potentially writing new vars onto the stack.
pCurThread->SetFilterContext( NULL );
#if defined(TARGET_X86)
ResumeAtJit(pContext, oldSP);
#else
ClrRestoreNonvolatileContext(pContext);
#endif
// At this point we shouldn't have failed, so this is genuinely erroneous.
LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
_ASSERTE(!"Should not return from ResumeAtJit()");
}
#endif // #ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// ResolveField - get a pointer to the value of a field that was added by EnC
//
// Arguments:
// thisPointer - For instance fields, a pointer to the object instance of interest.
// For static fields this is unused and should be NULL.
// pFD - FieldDesc describing the field we're interested in
// fAllocateNew - If storage doesn't yet exist for this field and fAllocateNew is true
// then we will attempt to allocate the storage (throwing an exception
// if it fails). Otherwise, if fAllocateNew is false, then we will just
// return NULL when the storage is not yet available.
//
// Return Value:
// If storage doesn't yet exist for this field we return NULL, otherwise, we return a pointer
// to the contents of the field on success.
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveField(OBJECTREF thisPointer,
EnCFieldDesc * pFD)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifdef _DEBUG
if (g_BreakOnEnCResolveField == 1)
{
_ASSERTE( !"EditAndContinueModule::ResolveField");
}
#endif
// If it's static, we stash in the EnCFieldDesc
if (pFD->IsStatic())
{
_ASSERTE( thisPointer == NULL );
EnCAddedStaticField *pAddedStatic = pFD->GetStaticFieldData();
if (!pAddedStatic)
{
return NULL;
}
_ASSERTE( pAddedStatic->m_pFieldDesc == pFD );
return PTR_CBYTE(pAddedStatic->GetFieldData());
}
// not static so get it out of the syncblock
SyncBlock * pBlock = NULL;
// Get the SyncBlock, failing if not available
pBlock = thisPointer->PassiveGetSyncBlock();
if( pBlock == NULL )
{
return NULL;
}
EnCSyncBlockInfo * pEnCInfo = NULL;
// Attempt to get the EnC information from the sync block
pEnCInfo = pBlock->GetEnCInfo();
if (!pEnCInfo)
{
// No EnC info on this object yet, fail since we don't want to allocate it
return NULL;
}
// Lookup the actual field value from the EnCSyncBlockInfo
return pEnCInfo->ResolveField(thisPointer, pFD);
} // EditAndContinueModule::ResolveField
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// ResolveOrAllocateField - get a pointer to the value of a field that was added by EnC,
// allocating storage for it if necessary
//
// Arguments:
// thisPointer - For instance fields, a pointer to the object instance of interest.
// For static fields this is unused and should be NULL.
// pFD - FieldDesc describing the field we're interested in
// Return Value:
// Returns a pointer to the contents of the field on success. This should only fail due
// to out-of-memory and will therefore throw an OOM exception.
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveOrAllocateField(OBJECTREF thisPointer,
EnCFieldDesc * pFD)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
// first try getting a pre-existing field
PTR_CBYTE fieldAddr = ResolveField(thisPointer, pFD);
if (fieldAddr != NULL)
{
return fieldAddr;
}
// we didn't find the field already allocated
if (pFD->IsStatic())
{
_ASSERTE(thisPointer == NULL);
EnCAddedStaticField * pAddedStatic = pFD->GetOrAllocateStaticFieldData();
_ASSERTE(pAddedStatic->m_pFieldDesc == pFD);
return PTR_CBYTE(pAddedStatic->GetFieldData());
}
// not static so get it out of the syncblock
SyncBlock* pBlock = NULL;
// Get the SyncBlock, creating it if necessary
pBlock = thisPointer->GetSyncBlock();
EnCSyncBlockInfo * pEnCInfo = NULL;
// Attempt to get the EnC information from the sync block
pEnCInfo = pBlock->GetEnCInfo();
if (!pEnCInfo)
{
// Attach new EnC field info to this object.
pEnCInfo = new EnCSyncBlockInfo;
if (!pEnCInfo)
{
COMPlusThrowOM();
}
pBlock->SetEnCInfo(pEnCInfo);
}
// Lookup the actual field value from the EnCSyncBlockInfo
return pEnCInfo->ResolveOrAllocateField(thisPointer, pFD);
} // EditAndContinueModule::ResolveOrAllocateField
#endif // !DACCESS_COMPILE
//-----------------------------------------------------------------------------
// Get or optionally create an EnCEEClassData object for the specified
// EEClass in this module.
//
// Arguments:
// pClass - the EEClass of interest
// getOnly - if false (the default), we'll create a new entry of none exists yet
//
// Note: If called in a DAC build, GetOnly must be TRUE
//
PTR_EnCEEClassData EditAndContinueModule::GetEnCEEClassData(MethodTable * pMT, BOOL getOnly /*=FALSE*/ )
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef DACCESS_COMPILE
_ASSERTE(getOnly == TRUE);
#endif // DACCESS_COMPILE
DPTR(PTR_EnCEEClassData) ppData = m_ClassList.Table();
DPTR(PTR_EnCEEClassData) ppLast = ppData + m_ClassList.Count();
// Look for an existing entry for the specified class
while (ppData < ppLast)
{
PREFIX_ASSUME(ppLast != NULL);
if ((*ppData)->GetMethodTable() == pMT)
return *ppData;
++ppData;
}
// No match found. Return now if we don't want to create a new entry
if (getOnly)
{
return NULL;
}
#ifndef DACCESS_COMPILE
// Create a new entry and add it to the end our our table
EnCEEClassData *pNewData = (EnCEEClassData*)(void*)pMT->GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem_NoThrow(S_SIZE_T(sizeof(EnCEEClassData)));
pNewData->Init(pMT);
ppData = m_ClassList.Append();
if (!ppData)
return NULL;
*ppData = pNewData;
return pNewData;
#else
DacNotImpl();
return NULL;
#endif
}
// Computes the address of this field within the object "o"
void *EnCFieldDesc::GetAddress( void *o)
{
#ifndef DACCESS_COMPILE
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// can't throw through FieldDesc::GetInstanceField if FORBIDGC_LOADER_USE_ENABLED
_ASSERTE(! FORBIDGC_LOADER_USE_ENABLED());
EditAndContinueModule *pModule = (EditAndContinueModule*)GetModule();
_ASSERTE(pModule->IsEditAndContinueEnabled());
// EnC added fields aren't just at some static offset in the object like normal fields
// are. Get the EditAndContinueModule to compute the address for us.
return (void *)pModule->ResolveOrAllocateField(ObjectToOBJECTREF((Object *)o), this);
#else
DacNotImpl();
return NULL;
#endif
}
#ifndef DACCESS_COMPILE
// Do simple field initialization
// We do this when the process is suspended for debugging (in a GC_NOTRIGGER).
// Full initialization will be done in Fixup when the process is running.
void EnCFieldDesc::Init(mdFieldDef token, BOOL fIsStatic)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Clear out the FieldDesc incase someone attempts to use any of the fields
memset( this, 0, sizeof(EnCFieldDesc) );
// Initialize our members
m_pStaticFieldData = NULL;
m_bNeedsFixup = TRUE;
// Initialize the bare minimum of FieldDesc necessary for now
if (fIsStatic)
FieldDesc::m_isStatic = TRUE;
SetMemberDef(token);
SetEnCNew();
}
// Allocate a new EnCAddedField instance and hook it up to hold the value for an instance
// field which was added by EnC to the specified object. This effectively adds a reference from
// the object to the new field value so that the field's lifetime is managed properly.
//
// Arguments:
// pFD - description of the field being added
// thisPointer - object instance to attach the new field to
//
EnCAddedField *EnCAddedField::Allocate(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate for this %p, FD %p\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// Create a new EnCAddedField instance
EnCAddedField *pEntry = new EnCAddedField;
pEntry->m_pFieldDesc = pFD;
AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();
// We need to associate the contents of the new field with the object it is attached to
// in a way that mimics the lifetime behavior of a normal field reference. Specifically,
// when the object is collected, the field should also be collected (assuming there are no
// other references), but references to the field shouldn't keep the object alive.
// To achieve this, we have introduced the concept of a "dependent handle" which provides
// the appropriate semantics. The dependent handle has a weak reference to a "primary object"
// (the object getting a new field in this case), and a strong reference to a secondary object.
// When the primary object is collected, the reference to the secondary object is released.
// See the definition of code:HNDTYPE_DEPENDENT and code:Ref_ScanDependentHandles for more details.
//
// We create a helper object and store it as the secondary object in the dependant handle
// so that its liveliness can be maintained along with the primary object.
// The helper then contains an object reference to the real field value that we are adding.
// The reason for doing this is that we cannot hand out the handle address for
// the OBJECTREF address so we need to hand out something else that is hooked up to the handle.
GCPROTECT_BEGIN(thisPointer);
MethodTable *pHelperMT = CoreLibBinder::GetClass(CLASS__ENC_HELPER);
pEntry->m_FieldData = pDomain->CreateDependentHandle(thisPointer, AllocateObject(pHelperMT));
GCPROTECT_END();
LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate created dependent handle %p\n",pEntry->m_FieldData));
// The EnC helper object stores a reference to the actual field value. For fields which are
// reference types, this is simply a normal object reference so we don't need to do anything
// special here.
if (pFD->GetFieldType() != ELEMENT_TYPE_CLASS)
{
// The field is a value type so we need to create storage on the heap to hold a boxed
// copy of the value and have the helper's objectref point there.
OBJECTREF obj = NULL;
if (pFD->IsByValue())
{
// Create a boxed version of the value class. This allows the standard GC algorithm
// to take care of internal pointers into the value class.
obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
}
else
{
// In the case of primitive types, we use a reference to a 1-element array on the heap.
// I'm not sure why we bother treating primitives specially, it seems like we should be able
// to just box any value type including primitives.
obj = AllocatePrimitiveArray(ELEMENT_TYPE_I1, GetSizeForCorElementType(pFD->GetFieldType()));
}
GCPROTECT_BEGIN (obj);
// Get a FieldDesc for the object reference field in the EnC helper object (warning: triggers)
FieldDesc *pHelperField = CoreLibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
// store the empty boxed object into the helper object
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelperObj = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
OBJECTREF *pHelperRef = (OBJECTREF *)pHelperField->GetAddress( pHelperObj->GetAddress() );
SetObjectReference( pHelperRef, obj);
GCPROTECT_END ();
}
return pEntry;
}
#endif // !DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc
// Gets the address of an EnC field accounting for its type: valuetype, class or primitive
// Arguments:
// input: pHelperFieldDesc - FieldDesc for the enc helper object
// pHelper - EnC helper (points to list of added fields)
// pFD - fieldDesc describing the field of interest
// Return value: the address of the EnC added field
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc(FieldDesc * pHelperFieldDesc,
OBJECTREF pHelper,
EnCFieldDesc * pFD)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(pHelperFieldDesc != NULL);
_ASSERTE(pHelper != NULL);
// Get the address of the reference inside the helper object which points to
// the field contents
PTR_OBJECTREF pOR = dac_cast<PTR_OBJECTREF>(pHelperFieldDesc->GetAddress(pHelper->GetAddress()));
_ASSERTE(pOR != NULL);
PTR_CBYTE retAddr = NULL;
// Compute the address to the actual field contents based on the field type
// See the description above Allocate for details
if (pFD->IsByValue())
{
// field value is a value type, we store it boxed so get the pointer to the first field
retAddr = dac_cast<PTR_CBYTE>((*pOR)->UnBox());
}
else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS)
{
// field value is a reference type, we store the objref directly
retAddr = dac_cast<PTR_CBYTE>(pOR);
}
else
{
// field value is a primitive, we store it inside a 1-element array
OBJECTREF objRef = *pOR;
I1ARRAYREF primitiveArray = dac_cast<I1ARRAYREF>(objRef);
retAddr = dac_cast<PTR_CBYTE>(primitiveArray->GetDirectPointerToNonObjectElements());
}
LOG((LF_ENC, LL_INFO1000, "\tEnCSBI:RF address of %s type member is %p\n",
(pFD->IsByValue() ? "ByValue" : pFD->GetFieldType() == ELEMENT_TYPE_CLASS ? "Class" : "Other"), retAddr));
return retAddr;
} // EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveField
// Get the address of the data referenced by an instance field that was added with EnC
// Arguments:
// thisPointer - the object instance whose field to access
// pFD - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an EnC added instance field
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
// We should only be passed FieldDescs for instance fields
_ASSERTE(!pFD->IsStatic());
PTR_EnCAddedField pEntry = NULL;
LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %08x\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
// arise here.
// Look for an entry for the requested field in our linked list
pEntry = m_pList;
while (pEntry && pEntry->m_pFieldDesc != pFD)
{
pEntry = pEntry->m_pNext;
}
if (!pEntry)
{
// No existing entry - we have to return NULL
return NULL;
}
// we found a matching entry in the list of EnCAddedFields
// Get the EnC helper object (see the detailed description in Allocate above)
#ifdef DACCESS_COMPILE
OBJECTREF pHelper = GetDependentHandleSecondary(pEntry->m_FieldData);
#else // DACCESS_COMPILE
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelper = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
#endif // DACCESS_COMPILE
_ASSERTE(pHelper != NULL);
FieldDesc *pHelperFieldDesc = NULL;
// We _HAVE_ to call GetExistingField b/c (a) we can't throw exceptions, and
// (b) we _DON'T_ want to run class init code, either.
pHelperFieldDesc = CoreLibBinder::GetExistingField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
if (pHelperFieldDesc == NULL)
{
return NULL;
}
else
{
return GetEnCFieldAddrFromHelperFieldDesc(pHelperFieldDesc, pHelper, pFD);
}
} // EnCSyncBlockInfo::ResolveField
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveOrAllocateField
// get the address of an EnC added field, allocating it if it doesn't yet exist
// Arguments:
// thisPointer - the object instance whose field to access
// pFD - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an instance field that was added with EnC
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveOrAllocateField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
GC_TRIGGERS;
WRAPPER(THROWS);
}
CONTRACTL_END;
// We should only be passed FieldDescs for instance fields
_ASSERTE( !pFD->IsStatic() );
// first try to get the address of a pre-existing field (storage has already been allocated)
PTR_CBYTE retAddr = ResolveField(thisPointer, pFD);
if (retAddr != NULL)
{
return retAddr;
}
// if the field doesn't yet have available storage, we'll have to allocate it.
PTR_EnCAddedField pEntry = NULL;
LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %08x\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
// arise here.
// Because we may have additions to the head of m_pList at any time, we have to keep searching this
// until we either find a match or succeed in allocating a new entry and adding it to the list
do
{
// Look for an entry for the requested field in our linked list (maybe it was just added)
pEntry = m_pList;
while (pEntry && pEntry->m_pFieldDesc != pFD)
{
pEntry = pEntry->m_pNext;
}
if (pEntry)
{
// match found
break;
}
// Allocate an entry and tie it to the object instance
pEntry = EnCAddedField::Allocate(thisPointer, pFD);
// put at front of list so the list is in order of most recently added
pEntry->m_pNext = m_pList;
if (FastInterlockCompareExchangePointer(&m_pList, pEntry, pEntry->m_pNext) == pEntry->m_pNext)
break;
// There was a race and another thread modified the list here, so we need to try again
// We should do this so rarely, and EnC perf is of relatively little
// consequence, we should just be taking a lock here to simplify this code.
// @todo - We leak a GC handle here. Allocate() above alloced a GC handle in m_FieldData.
// There's no dtor for pEntry to free it.
delete pEntry;
} while (TRUE);
// we found a matching entry in the list of EnCAddedFields
// Get the EnC helper object (see the detailed description in Allocate above)
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelper = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
_ASSERTE(pHelper != NULL);
FieldDesc * pHelperField = NULL;
GCPROTECT_BEGIN (pHelper);
pHelperField = CoreLibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
GCPROTECT_END ();
return GetEnCFieldAddrFromHelperFieldDesc(pHelperField, pHelper, pFD);
} // EnCSyncBlockInfo::ResolveOrAllocateField
// Free all the resources associated with the fields added to this object instance
// This is invoked after the object instance has been collected, and the SyncBlock is
// being reclaimed.
//
// Note, this is not threadsafe, and so should only be called when we know no-one else
// maybe using this SyncBlockInfo.
void EnCSyncBlockInfo::Cleanup()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Walk our linked list of all the fields that were added
EnCAddedField *pEntry = m_pList;
while (pEntry)
{
// Clean up the handle we created in EnCAddedField::Allocate
DestroyDependentHandle(*(OBJECTHANDLE*)&pEntry->m_FieldData);
// Delete this list entry and move onto the next
EnCAddedField *next = pEntry->m_pNext;
delete pEntry;
pEntry = next;
}
// Finally, delete the sync block info itself
delete this;
}
// Allocate space to hold the value for the new static field
EnCAddedStaticField *EnCAddedStaticField::Allocate(EnCFieldDesc *pFD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();
// Compute the size of the fieldData entry
size_t fieldSize;
if (pFD->IsByValue() || pFD->GetFieldType() == ELEMENT_TYPE_CLASS) {
// We store references to reference types or boxed value types
fieldSize = sizeof(OBJECTREF*);
} else {
// We store primitives inline
fieldSize = GetSizeForCorElementType(pFD->GetFieldType());
}
// allocate an instance with space for the field data
EnCAddedStaticField *pEntry = (EnCAddedStaticField *)
(void*)pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(offsetof(EnCAddedStaticField, m_FieldData)) + S_SIZE_T(fieldSize));
pEntry->m_pFieldDesc = pFD;
// Create a static objectref to point to the field contents, except for primitives
// which will use the memory available in-line at m_FieldData for storage.
// We use static object refs for static fields as these fields won't go away
// unless the module is unloaded, and they can easily be found by GC.
if (pFD->IsByValue())
{
// create a boxed version of the value class. This allows the standard GC
// algorithm to take care of internal pointers in the value class.
OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
*pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
OBJECTREF obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
SetObjectReference( *pOR, obj);
}
else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS)
{
// references to reference-types are stored directly in the field data
OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
*pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
}
return pEntry;
}
#endif // !DACCESS_COMPILE
// GetFieldData - return the ADDRESS where the field data is located
PTR_CBYTE EnCAddedStaticField::GetFieldData()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
if ( (m_pFieldDesc->IsByValue()) || (m_pFieldDesc->GetFieldType() == ELEMENT_TYPE_CLASS) )
{
// It's indirect via an ObjRef at m_FieldData. This is a TADDR, so we need to make a PTR_CBYTE from
// the ObjRef
return *(PTR_CBYTE *)&m_FieldData;
}
else
{
// An elementry type. It's stored directly in m_FieldData. In this case, we need to get the target
// address of the m_FieldData data member and marshal it via the DAC.
return dac_cast<PTR_CBYTE>(PTR_HOST_MEMBER_TADDR(EnCAddedStaticField, this, m_FieldData));
}
}
// Gets a pointer to the field's contents (assuming this is a static field)
// We'll return NULL if we don't yet have a pointer to the data.
// Arguments: none
// Return value: address of the static field data if available or NULL otherwise
EnCAddedStaticField * EnCFieldDesc::GetStaticFieldData()
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
_ASSERTE(IsStatic());
return m_pStaticFieldData;
}
#ifndef DACCESS_COMPILE
// Gets a pointer to the field's contents (assuming this is a static field)
// Arguments: none
// Return value: address of the field data. If we don't yet have a pointer to the data,
// this will allocate space to store it.
// May throw OOM.
EnCAddedStaticField * EnCFieldDesc::GetOrAllocateStaticFieldData()
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
_ASSERTE(IsStatic());
// If necessary and requested, allocate space for the static field data
if (!m_pStaticFieldData)
{
m_pStaticFieldData = EnCAddedStaticField::Allocate(this);
}
return m_pStaticFieldData;
}
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// Adds the provided new field to the appropriate linked list and updates the appropriate count
void EnCEEClassData::AddField(EnCAddedFieldElement *pAddedField)
{
LIMITED_METHOD_CONTRACT;
// Determine the appropriate field list and update the field counter
EnCFieldDesc *pFD = &pAddedField->m_fieldDesc;
EnCAddedFieldElement **pList;
if (pFD->IsStatic())
{
++m_dwNumAddedStaticFields;
pList = &m_pAddedStaticFields;
}
else
{
++m_dwNumAddedInstanceFields;
pList = &m_pAddedInstanceFields;
}
// If the list is empty, just add this field as the only entry
if (*pList == NULL)
{
*pList = pAddedField;
return;
}
// Otherwise, add this field to the end of the field list
EnCAddedFieldElement *pCur = *pList;
while (pCur->m_next != NULL)
{
pCur = pCur->m_next;
}
pCur->m_next = pAddedField;
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
EnCEEClassData::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
if (m_pMT.IsValid())
{
m_pMT->EnumMemoryRegions(flags);
}
PTR_EnCAddedFieldElement elt = m_pAddedInstanceFields;
while (elt.IsValid())
{
elt.EnumMem();
elt = elt->m_next;
}
elt = m_pAddedStaticFields;
while (elt.IsValid())
{
elt.EnumMem();
elt = elt->m_next;
}
}
void
EditAndContinueModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis)
{
SUPPORTS_DAC;
if (enumThis)
{
DAC_ENUM_VTHIS();
}
Module::EnumMemoryRegions(flags, false);
m_ClassList.EnumMemoryRegions();
DPTR(PTR_EnCEEClassData) classData = m_ClassList.Table();
DPTR(PTR_EnCEEClassData) classLast = classData + m_ClassList.Count();
while (classData.IsValid() && classData < classLast)
{
if ((*classData).IsValid())
{
(*classData)->EnumMemoryRegions(flags);
}
classData++;
}
}
#endif // #ifdef DACCESS_COMPILE
// Create a field iterator which includes EnC fields in addition to the fields from an
// underlying ApproxFieldDescIterator.
//
// Arguments:
// pMT - MethodTable indicating the type of interest
// iteratorType - one of the ApproxFieldDescIterator::IteratorType values specifying which fields
// are of interest.
// fixupEnC - if true, then any partially-initialized EnC FieldDescs will be fixed up to be complete
// initialized FieldDescs as they are returned by Next(). This may load types and do
// other things to trigger a GC.
//
EncApproxFieldDescIterator::EncApproxFieldDescIterator(MethodTable *pMT, int iteratorType, BOOL fixupEnC) :
m_nonEnCIter( pMT, iteratorType )
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END
m_fixupEnC = fixupEnC;
#ifndef DACCESS_COMPILE
// can't fixup for EnC on the debugger thread
_ASSERTE((g_pDebugInterface->GetRCThreadId() != GetCurrentThreadId()) || fixupEnC == FALSE);
#endif
m_pCurrListElem = NULL;
m_encClassData = NULL;
m_encFieldsReturned = 0;
// If this is an EnC module, then grab a pointer to the EnC data
if( pMT->GetModule()->IsEditAndContinueEnabled() )
{
PTR_EditAndContinueModule encMod = PTR_EditAndContinueModule(pMT->GetModule());
m_encClassData = encMod->GetEnCEEClassData( pMT, TRUE);
}
}
// Iterates through all fields, returns NULL when done.
PTR_FieldDesc EncApproxFieldDescIterator::Next()
{
CONTRACTL
{
NOTHROW;
if (m_fixupEnC) {GC_TRIGGERS;} else {GC_NOTRIGGER;}
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
// If we still have non-EnC fields to look at, return one of them
if( m_nonEnCIter.CountRemaining() > 0 )
{
_ASSERTE( m_encFieldsReturned == 0 );
return m_nonEnCIter.Next();
}
// Get the next EnC field Desc if any
PTR_EnCFieldDesc pFD = NextEnC();
if( pFD == NULL )
{
// No more fields
return NULL;
}
#ifndef DACCESS_COMPILE
// Fixup the fieldDesc if requested and necessary
if ( m_fixupEnC && (pFD->NeedsFixup()) )
{
// if we get an OOM during fixup, the field will just not get fixed up
EX_TRY
{
FAULT_NOT_FATAL();
pFD->Fixup(pFD->GetMemberDef());
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
}
// Either it's been fixed up so we can use it, or we're the Debugger RC thread, we can't fix it up,
// but it's ok since our logic will check & make sure we don't try and use it. If haven't asked to
// have the field fixed up, should never be trying to get at non-fixed up field in
// this list. Can't simply fixup the field always because loading triggers GC and many
// code paths can't tolerate that.
_ASSERTE( !(pFD->NeedsFixup()) ||
( g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId() ) );
#endif
return dac_cast<PTR_FieldDesc>(pFD);
}
// Returns the number of fields plus the number of add EnC fields
int EncApproxFieldDescIterator::Count()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
int count = m_nonEnCIter.Count();
// If this module doesn't have any EnC data then there aren't any EnC fields
if (m_encClassData == NULL)
{
return count;
}
BOOL doInst = ( GetIteratorType() & (int)ApproxFieldDescIterator::INSTANCE_FIELDS);
BOOL doStatic = ( GetIteratorType() & (int)ApproxFieldDescIterator::STATIC_FIELDS);
int cNumAddedInst = doInst ? m_encClassData->GetAddedInstanceFields() : 0;
int cNumAddedStatics = doStatic ? m_encClassData->GetAddedStaticFields() : 0;
return count + cNumAddedInst + cNumAddedStatics;
}
// Iterate through EnC added fields.
// Returns NULL when done.
PTR_EnCFieldDesc EncApproxFieldDescIterator::NextEnC()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
// If this module doesn't have any EnC data then there aren't any EnC fields
if( m_encClassData == NULL )
{
return NULL;
}
BOOL doInst = ( GetIteratorType() & (int)ApproxFieldDescIterator::INSTANCE_FIELDS);
BOOL doStatic = ( GetIteratorType() & (int)ApproxFieldDescIterator::STATIC_FIELDS);
int cNumAddedInst = doInst ? m_encClassData->GetAddedInstanceFields() : 0;
int cNumAddedStatics = doStatic ? m_encClassData->GetAddedStaticFields() : 0;
// If we haven't returned anything yet
if ( m_encFieldsReturned == 0 )
{
_ASSERTE(m_pCurrListElem == NULL);
// We're at the start of the instance list.
if ( doInst )
{
m_pCurrListElem = m_encClassData->m_pAddedInstanceFields;
}
}
// If we've finished the instance fields (or never wanted to do any)
if ( m_encFieldsReturned == cNumAddedInst)
{
// We should be at the end of the instance list if doInst is true
_ASSERTE(m_pCurrListElem == NULL);
// We're at the start of the statics list.
if ( doStatic )
{
m_pCurrListElem = m_encClassData->m_pAddedStaticFields;
}
}
// If we don't have any elements to return, then we're done
if (m_pCurrListElem == NULL)
{
// Verify that we returned the number we expected to
_ASSERTE( m_encFieldsReturned == cNumAddedInst + cNumAddedStatics );
return NULL;
}
// Advance the list pointer and return the element
m_encFieldsReturned++;
PTR_EnCFieldDesc fd = PTR_EnCFieldDesc(PTR_HOST_MEMBER_TADDR(EnCAddedFieldElement, m_pCurrListElem, m_fieldDesc));
m_pCurrListElem = m_pCurrListElem->m_next;
return fd;
}
#endif // EnC_SUPPORTED
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===========================================================================
// File: EnC.CPP
//
//
// Handles EditAndContinue support in the EE
// ===========================================================================
#include "common.h"
#include "dbginterface.h"
#include "dllimport.h"
#include "eeconfig.h"
#include "excep.h"
#include "stackwalk.h"
#ifdef DACCESS_COMPILE
#include "../debug/daccess/gcinterface.dac.h"
#endif // DACCESS_COMPILE
#ifdef EnC_SUPPORTED
// can't get this on the helper thread at runtime in ResolveField, so make it static and get when add a field.
#ifdef _DEBUG
static int g_BreakOnEnCResolveField = -1;
#endif
#ifndef DACCESS_COMPILE
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The constructor phase initializes just enough so that Destruct() can be safely called.
// It cannot throw or fail.
//
EditAndContinueModule::EditAndContinueModule(Assembly *pAssembly, mdToken moduleRef, PEAssembly *pPEAssembly)
: Module(pAssembly, moduleRef, pPEAssembly)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
FORBID_FAULT;
}
CONTRACTL_END
LOG((LF_ENC,LL_INFO100,"EACM::ctor %p\n", this));
m_applyChangesCount = CorDB_DEFAULT_ENC_FUNCTION_VERSION;
}
// Module initialization occurs in two phases: the constructor phase and the Initialize phase.
//
// The Initialize() phase completes the initialization after the constructor has run.
// It can throw exceptions but whether it throws or succeeds, it must leave the Module
// in a state where Destruct() can be safely called.
//
/*virtual*/
void EditAndContinueModule::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM(););
}
CONTRACTL_END
LOG((LF_ENC,LL_INFO100,"EACM::Initialize %p\n", this));
Module::Initialize(pamTracker, szName);
}
// Called when the module is being destroyed (eg. AD unload time)
void EditAndContinueModule::Destruct()
{
LIMITED_METHOD_CONTRACT;
LOG((LF_ENC,LL_EVERYTHING,"EACM::Destruct %p\n", this));
// Call the superclass's Destruct method...
Module::Destruct();
}
//---------------------------------------------------------------------------------------
//
// ApplyEditAndContinue - updates this module for an EnC
//
// Arguments:
// cbDeltaMD - number of bytes pointed to by pDeltaMD
// pDeltaMD - pointer to buffer holding the delta metadata
// cbDeltaIL - number of bytes pointed to by pDeltaIL
// pDeltaIL - pointer to buffer holding the delta IL
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
HRESULT EditAndContinueModule::ApplyEditAndContinue(
DWORD cbDeltaMD,
BYTE *pDeltaMD,
DWORD cbDeltaIL,
BYTE *pDeltaIL)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Update the module's EnC version number
++m_applyChangesCount;
LOG((LF_ENC, LL_INFO100, "EACM::AEAC:\n"));
#ifdef _DEBUG
// Debugging hook to optionally break when this method is called
static BOOL shouldBreak = -1;
if (shouldBreak == -1)
shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncApplyChanges);
if (shouldBreak > 0) {
_ASSERTE(!"EncApplyChanges");
}
// Debugging hook to dump out all edits to dmeta and dil files
static BOOL dumpChanges = -1;
if (dumpChanges == -1)
dumpChanges = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EncDumpApplyChanges);
if (dumpChanges> 0) {
SString fn;
int ec;
fn.Printf(W("ApplyChanges.%d.dmeta"), m_applyChangesCount);
FILE *fp;
ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
_ASSERTE(SUCCEEDED(ec));
fwrite(pDeltaMD, 1, cbDeltaMD, fp);
fclose(fp);
fn.Printf(W("ApplyChanges.%d.dil"), m_applyChangesCount);
ec = _wfopen_s(&fp, fn.GetUnicode(), W("wb"));
_ASSERTE(SUCCEEDED(ec));
fwrite(pDeltaIL, 1, cbDeltaIL, fp);
fclose(fp);
}
#endif
HRESULT hr = S_OK;
HENUMInternal enumENC;
BYTE *pLocalILMemory = NULL;
IMDInternalImport *pMDImport = NULL;
IMDInternalImport *pNewMDImport = NULL;
CONTRACT_VIOLATION(GCViolation); // SafeComHolder goes to preemptive mode, which will trigger a GC
SafeComHolder<IMDInternalImportENC> pIMDInternalImportENC;
SafeComHolder<IMetaDataEmit> pEmitter;
// Apply the changes. Note that ApplyEditAndContinue() requires read/write metadata. If the metadata is
// not already RW, then ApplyEditAndContinue() will perform the conversion, invalidate the current
// metadata importer, and return us a new one. We can't let that happen. Other parts of the system are
// already using the current metadata importer, some possibly in preemptive GC mode at this very moment.
// Instead, we ensure that the metadata is RW by calling ConvertMDInternalToReadWrite(), which will make
// a new importer if necessary and ensure that new accesses to the metadata use that while still managing
// the lifetime of the old importer. Therefore, we can be sure that ApplyEditAndContinue() won't need to
// make a new importer.
// Ensure the metadata is RW.
EX_TRY
{
// ConvertMDInternalToReadWrite should only ever be called on EnC capable files.
_ASSERTE(IsEditAndContinueCapable()); // this also checks that the file is EnC capable
GetPEAssembly()->ConvertMDInternalToReadWrite();
}
EX_CATCH_HRESULT(hr);
IfFailGo(hr);
// Grab the current importer.
pMDImport = GetMDImport();
// Apply the EnC delta to this module's metadata.
IfFailGo(pMDImport->ApplyEditAndContinue(pDeltaMD, cbDeltaMD, &pNewMDImport));
// The importer should not have changed! We assert that, and back-stop in a retail build just to be sure.
if (pNewMDImport != pMDImport)
{
_ASSERTE( !"ApplyEditAndContinue should not have needed to create a new metadata importer!" );
IfFailGo(CORDBG_E_ENC_INTERNAL_ERROR);
}
// get the delta interface
IfFailGo(pMDImport->QueryInterface(IID_IMDInternalImportENC, (void **)&pIMDInternalImportENC));
// get an emitter interface
IfFailGo(GetMetaDataPublicInterfaceFromInternal(pMDImport, IID_IMetaDataEmit, (void **)&pEmitter));
// Copy the deltaIL into our RVAable IL memory
pLocalILMemory = new BYTE[cbDeltaIL];
memcpy(pLocalILMemory, pDeltaIL, cbDeltaIL);
// Enumerate all of the EnC delta tokens
HENUMInternal::ZeroEnum(&enumENC);
IfFailGo(pIMDInternalImportENC->EnumDeltaTokensInit(&enumENC));
mdToken token;
while (pIMDInternalImportENC->EnumNext(&enumENC, &token))
{
STRESS_LOG3(LF_ENC, LL_INFO100, "EACM::AEAC: updated token %08x; type %08x; rid %08x\n", token, TypeFromToken(token), RidFromToken(token));
switch (TypeFromToken(token))
{
case mdtMethodDef:
// MethodDef token - update/add a method
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found method %08x\n", token));
ULONG dwMethodRVA;
DWORD dwMethodFlags;
IfFailGo(pMDImport->GetMethodImplProps(token, &dwMethodRVA, &dwMethodFlags));
if (dwMethodRVA >= cbDeltaIL)
{
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Failure RVA of %d with cbDeltaIl %d\n", dwMethodRVA, cbDeltaIL));
IfFailGo(E_INVALIDARG);
}
SetDynamicIL(token, (TADDR)(pLocalILMemory + dwMethodRVA), FALSE);
// use module to resolve to method
MethodDesc *pMethod;
pMethod = LookupMethodDef(token);
if (pMethod)
{
// Method exists already - update it
IfFailGo(UpdateMethod(pMethod));
}
else
{
// This is a new method token - create a new method
IfFailGo(AddMethod(token));
}
break;
case mdtFieldDef:
// FieldDef token - add a new field
LOG((LF_ENC, LL_INFO10000, "EACM::AEAC: Found field %08x\n", token));
if (LookupFieldDef(token))
{
// Field already exists - just ignore for now
continue;
}
// Field is new - add it
IfFailGo(AddField(token));
break;
}
}
// Update the AvailableClassHash for reflection, etc. ensure that the new TypeRefs, AssemblyRefs and MethodDefs can be stored.
ApplyMetaData();
ErrExit:
if (pIMDInternalImportENC)
pIMDInternalImportENC->EnumClose(&enumENC);
return hr;
}
//---------------------------------------------------------------------------------------
//
// UpdateMethod - called when a method has been updated by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update, and swap the new IL in as the current
// version of the method.
//
// Arguments:
// pMethod - the method being updated
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::UpdateMethod(MethodDesc *pMethod)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Notify the debugger of the update
if (CORDebuggerAttached())
{
HRESULT hr = g_pDebugInterface->UpdateFunction(pMethod, m_applyChangesCount);
if (FAILED(hr))
{
return hr;
}
}
// Notify the JIT that we've got new IL for this method
// This will ensure that all new calls to the method will go to the new version.
// The runtime does this by never backpatching the methodtable slots in EnC-enabled modules.
LOG((LF_ENC, LL_INFO100000, "EACM::UM: Updating function %s to version %d\n", pMethod->m_pszDebugMethodName, m_applyChangesCount));
// Reset any flags relevant to the old code
//
// Note that this only works since we've very carefullly made sure that _all_ references
// to the Method's code must be to the call/jmp blob immediately in front of the
// MethodDesc itself. See MethodDesc::IsEnCMethod()
//
pMethod->ResetCodeEntryPointForEnC();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// AddMethod - called when a new method is added by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update, and create and add a new MethodDesc to the class.
//
// Arguments:
// token - methodDef token for the method being added
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddMethod(mdMethodDef token)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
mdTypeDef parentTypeDef;
HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AM can't find parent token for method token %08x\n", token));
return E_FAIL;
}
// see if the class is loaded yet.
MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
if (pParentType == NULL)
{
// Class isn't loaded yet, don't have to modify any existing EE data structures beyond the metadata.
// Just notify debugger and return.
LOG((LF_ENC, LL_INFO100, "EnCModule::AM class %08x not loaded (method %08x), our work is done\n", parentTypeDef, token));
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->UpdateNotYetLoadedFunction(token, this, m_applyChangesCount);
}
return hr;
}
// Add the method to the runtime's Class data structures
LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding function %08x to type %08x\n", token, parentTypeDef));
MethodDesc *pMethod = NULL;
hr = EEClass::AddMethod(pParentType, token, 0, &pMethod);
if (FAILED(hr))
{
_ASSERTE(!"Failed to add function");
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AM: Failed to add function %08x with hr %08x\n", token, hr));
return hr;
}
// Tell the debugger about the new method so it gets the version number properly
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->AddFunction(pMethod, m_applyChangesCount);
if (FAILED(hr))
{
_ASSERTE(!"Failed to add function");
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add method %08x to debugger with hr %08x\n", token, hr));
}
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// AddField - called when a new field is added by EnC.
//
// The module's metadata has already been updated. Here we notify the
// debugger of the update,
//
// Arguments:
// token - fieldDef for the field being added
//
// Return Value:
// S_OK on success.
// if the edit fails for any reason, at any point in this function,
// we are toasted, so return out and IDE will end debug session.
//
// Assumptions:
// The CLR must be suspended for debugging.
//
HRESULT EditAndContinueModule::AddField(mdFieldDef token)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
mdTypeDef parentTypeDef;
HRESULT hr = GetMDImport()->GetParentToken(token, &parentTypeDef);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::AF can't find parent token for field token %08x\n", token));
return E_FAIL;
}
// see if the class is loaded yet. If not we don't need to do anything. When this class is
// loaded (with the updated metadata), it will have this field like any other normal field.
// If the class hasn't been loaded, than the debugger shouldn't know anything about it
// so there shouldn't be any harm in not notifying it of the update. For completeness,
// we may want to consider changing this to notify the debugger here as well.
MethodTable * pParentType = LookupTypeDef(parentTypeDef).AsMethodTable();
if (pParentType == NULL)
{
LOG((LF_ENC, LL_INFO100, "EnCModule::AF class %08x not loaded (field %08x), our work is done\n", parentTypeDef, token));
return S_OK;
}
// Create a new EnCFieldDesc for the field and add it to the class
LOG((LF_ENC, LL_INFO100000, "EACM::AM: Adding field %08x to type %08x\n", token, parentTypeDef));
EnCFieldDesc *pField;
hr = EEClass::AddField(pParentType, token, &pField);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %08x to EE with hr %08x\n", token, hr));
return hr;
}
// Tell the debugger about the new field
if (CORDebuggerAttached())
{
hr = g_pDebugInterface->AddField(pField, m_applyChangesCount);
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100000, "**Error** EACM::AF: Failed to add field %08x to debugger with hr %08x\n", token, hr));
}
}
#ifdef _DEBUG
if (g_BreakOnEnCResolveField == -1)
{
g_BreakOnEnCResolveField = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCResolveField);
}
#endif
return hr;
}
//---------------------------------------------------------------------------------------
//
// JitUpdatedFunction - Jit the new version of a function for EnC.
//
// Arguments:
// pMD - the MethodDesc for the method we want to JIT
// pOrigContext - context of thread pointing into original version of the function
//
// Return value:
// Return the address of the newly jitted code or NULL on failure.
//
PCODE EditAndContinueModule::JitUpdatedFunction( MethodDesc *pMD,
CONTEXT *pOrigContext)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_ENC, LL_INFO100, "EnCModule::JitUpdatedFunction for %s\n",
pMD->m_pszDebugMethodName));
PCODE jittedCode = NULL;
GCX_COOP();
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(
CLRConfig::INTERNAL_EncJitUpdatedFunction);
if (shouldBreak > 0) {
_ASSERTE(!"EncJitUpdatedFunction");
}
#endif
// Setup a frame so that has context for the exception
// so that gc can crawl the stack and do the right thing.
_ASSERTE(pOrigContext);
Thread *pCurThread = GetThread();
FrameWithCookie<ResumableFrame> resFrame(pOrigContext);
resFrame.Push(pCurThread);
CONTEXT *pCtxTemp = NULL;
// We need to zero out the filter context so a multi-threaded GC doesn't result
// in somebody else tracing this thread & concluding that we're in JITted code.
// We need to remove the filter context so that if we're in preemptive GC
// mode, we'll either have the filter context, or the ResumableFrame,
// but not both, set.
// Since we're in cooperative mode here, we can swap the two non-atomically here.
pCtxTemp = pCurThread->GetFilterContext();
_ASSERTE(pCtxTemp != NULL); // currently called from within a filter context, protects us during GC-toggle.
pCurThread->SetFilterContext(NULL);
// get the code address (may jit the fcn if not already jitted)
EX_TRY {
if (!pMD->IsPointingToNativeCode())
{
GCX_PREEMP();
pMD->DoPrestub(NULL);
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction JIT successful\n"));
}
else
{
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction function already JITed\n"));
}
jittedCode = pMD->GetNativeCode();
} EX_CATCH {
#ifdef _DEBUG
{
// This is debug-only code to print out the error string, but SString can throw.
// This function is no-throw, and we can't put an EX_TRY inside an EX_CATCH block, so
// we just have the violation.
CONTRACT_VIOLATION(ThrowsViolation);
StackSString exceptionMessage;
SString errorMessage;
GetExceptionMessage(GET_THROWABLE(), exceptionMessage);
errorMessage.AppendASCII("**Error: Probable rude edit.**\n\n"
"EnCModule::JITUpdatedFunction JIT failed with the following exception:\n\n");
errorMessage.Append(exceptionMessage);
StackScratchBuffer buffer;
DbgAssertDialog(__FILE__, __LINE__, errorMessage.GetANSI(buffer));
LOG((LF_ENC, LL_INFO100, errorMessage.GetANSI(buffer)));
}
#endif
} EX_END_CATCH(SwallowAllExceptions)
resFrame.Pop(pCurThread);
// Restore the filter context here (see comment above)
pCurThread->SetFilterContext(pCtxTemp);
return jittedCode;
}
//-----------------------------------------------------------------------------
// Called by EnC to resume the code in a new version of the function.
// This will:
// 1) jit the new function
// 2) set the IP to newILOffset within that new function
// 3) adjust local variables (particularly enregistered vars) to the new func.
// It will not return.
//
// Params:
// pMD - method desc for method being updated. This is not enc-version aware.
// oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
// This is enc-version aware.
// newILOffset - the IL offset to resume execution at within the new function.
// pOrigContext - context of thread pointing into original version of the function.
//
// This function must be called on the thread that's executing the old function.
// This function does not return. Instead, it will remap this thread directly
// to be executing the new function.
//-----------------------------------------------------------------------------
HRESULT EditAndContinueModule::ResumeInUpdatedFunction(
MethodDesc *pMD,
void *oldDebuggerFuncHandle,
SIZE_T newILOffset,
CONTEXT *pOrigContext)
{
#if defined(TARGET_ARM64) || defined(TARGET_ARM)
return E_NOTIMPL;
#else
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction for %s at IL offset 0x%x, ",
pMD->m_pszDebugMethodName, newILOffset));
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(
CLRConfig::INTERNAL_EncResumeInUpdatedFunction);
if (shouldBreak > 0) {
_ASSERTE(!"EncResumeInUpdatedFunction");
}
#endif
HRESULT hr = E_FAIL;
// JIT-compile the updated version of the method
PCODE jittedCode = JitUpdatedFunction(pMD, pOrigContext);
if ( jittedCode == NULL )
return CORDBG_E_ENC_JIT_CANT_UPDATE;
GCX_COOP();
// This will create a new frame and copy old vars to it
// need pointer to old & new code, old & new info
EECodeInfo oldCodeInfo(GetIP(pOrigContext));
_ASSERTE(oldCodeInfo.GetMethodDesc() == pMD);
// Get the new native offset & IP from the new IL offset
LOG((LF_ENC, LL_INFO10000, "EACM::RIUF: About to map IL forwards!\n"));
SIZE_T newNativeOffset = 0;
g_pDebugInterface->MapILInfoToCurrentNative(pMD,
newILOffset,
jittedCode,
&newNativeOffset);
EECodeInfo newCodeInfo(jittedCode + newNativeOffset);
_ASSERTE(newCodeInfo.GetMethodDesc() == pMD);
_ASSERTE(newCodeInfo.GetRelOffset() == newNativeOffset);
_ASSERTE(oldCodeInfo.GetCodeManager() == newCodeInfo.GetCodeManager());
DWORD oldFrameSize = oldCodeInfo.GetFixedStackSize();
DWORD newFrameSize = newCodeInfo.GetFixedStackSize();
// FixContextAndResume() will replace the old stack frame of the function with the new
// one and will initialize that new frame to null. Anything on the stack where that new
// frame sits will be wiped out. This could include anything on the stack right up to or beyond our
// current stack from in ResumeInUpdatedFunction. In order to prevent our current frame from being
// trashed we determine the maximum amount that the stack could grow by and allocate this as a buffer using
// alloca. Then we call FixContextAndResume which can safely rely on the stack because none of it's frames
// state or anything lower can be reached by the new frame.
if( newFrameSize > oldFrameSize)
{
DWORD frameIncrement = newFrameSize - oldFrameSize;
// alloca() has __attribute__((warn_unused_result)) in glibc, for which gcc 11+ issue `-Wunused-result` even with `(void)alloca(..)`,
// so we use additional NOT(!) operator to force unused-result suppression.
(void)!alloca(frameIncrement);
}
// Ask the EECodeManager to actually fill in the context and stack for the new frame so that
// values of locals etc. are preserved.
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction calling FixContextAndResume oldNativeOffset: 0x%x, newNativeOffset: 0x%x,"
"oldFrameSize: 0x%x, newFrameSize: 0x%x\n",
oldCodeInfo.GetRelOffset(), newCodeInfo.GetRelOffset(), oldFrameSize, newFrameSize));
FixContextAndResume(pMD,
oldDebuggerFuncHandle,
pOrigContext,
&oldCodeInfo,
&newCodeInfo);
// At this point we shouldn't have failed, so this is genuinely erroneous.
LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
_ASSERTE(!"Should not return from FixContextAndResume()");
hr = E_FAIL;
// If we fail for any reason we have already potentially trashed with new locals and we have also unwound any
// Win32 handlers on the stack so cannot ever return from this function.
EEPOLICY_HANDLE_FATAL_ERROR(CORDBG_E_ENC_INTERNAL_ERROR);
return hr;
#endif // #if define(TARGET_ARM64) || defined(TARGET_ARM)
}
//---------------------------------------------------------------------------------------
//
// FixContextAndResume - Modify the thread context for EnC remap and resume execution
//
// Arguments:
// pMD - MethodDesc for the method being remapped
// oldDebuggerFuncHandle - Debugger DJI to uniquely identify old function.
// pContext - the thread's original CONTEXT when the remap opportunity was hit
// pOldCodeInfo - collection of various information about the current frame state
// pNewCodeInfo - information about how we want the frame state to be after the remap
//
// Return Value:
// Doesn't return
//
// Notes:
// WARNING: This method cannot access any stack-data below its frame on the stack
// (i.e. anything allocated in a caller frame), so all stack-based arguments must
// EXPLICITLY be copied by value and this method cannot be inlined. We may need to expand
// the stack frame to accomodate the new method, and so extra buffer space must have
// been allocated on the stack. Note that passing a struct by value (via C++) is not
// enough to ensure its data is really copied (on x64, large structs may internally be
// passed by reference). Thus we explicitly make copies of structs passed in, at the
// beginning.
//
NOINLINE void EditAndContinueModule::FixContextAndResume(
MethodDesc *pMD,
void *oldDebuggerFuncHandle,
T_CONTEXT *pContext,
EECodeInfo *pOldCodeInfo,
EECodeInfo *pNewCodeInfo)
{
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_GC_TRIGGERS; // Sends IPC event
STATIC_CONTRACT_THROWS;
// Create local copies of all structs passed as arguments to prevent them from being overwritten
CONTEXT context;
memcpy(&context, pContext, sizeof(CONTEXT));
pContext = &context;
#if defined(TARGET_AMD64)
// Since we made a copy of the incoming CONTEXT in context, clear any new flags we
// don't understand (like XSAVE), since we'll eventually be passing a CONTEXT based
// on this copy to ClrRestoreNonvolatileContext, and this copy doesn't have the extra info
// required by the XSAVE or other flags.
//
// FUTURE: No reason to ifdef this for amd64-only, except to make this late fix as
// surgical as possible. Would be nice to enable this on x86 early in the next cycle.
pContext->ContextFlags &= CONTEXT_ALL;
#endif // defined(TARGET_AMD64)
EECodeInfo oldCodeInfo;
memcpy(&oldCodeInfo, pOldCodeInfo, sizeof(EECodeInfo));
pOldCodeInfo = &oldCodeInfo;
EECodeInfo newCodeInfo;
memcpy(&newCodeInfo, pNewCodeInfo, sizeof(EECodeInfo));
pNewCodeInfo = &newCodeInfo;
const ICorDebugInfo::NativeVarInfo *pOldVarInfo = NULL;
const ICorDebugInfo::NativeVarInfo *pNewVarInfo = NULL;
SIZE_T oldVarInfoCount = 0;
SIZE_T newVarInfoCount = 0;
// Get the var info which the codemanager will use for updating
// enregistered variables correctly, or variables whose lifetimes differ
// at the update point
g_pDebugInterface->GetVarInfo(pMD, oldDebuggerFuncHandle, &oldVarInfoCount, &pOldVarInfo);
g_pDebugInterface->GetVarInfo(pMD, NULL, &newVarInfoCount, &pNewVarInfo);
#ifdef TARGET_X86
// save the frame pointer as FixContextForEnC might step on it.
LPVOID oldSP = dac_cast<PTR_VOID>(GetSP(pContext));
// need to pop the SEH records before write over the stack in FixContextForEnC
PopSEHRecords(oldSP);
#endif
// Ask the EECodeManager to actually fill in the context and stack for the new frame so that
// values of locals etc. are preserved.
HRESULT hr = pNewCodeInfo->GetCodeManager()->FixContextForEnC(
pContext,
pOldCodeInfo,
pOldVarInfo, oldVarInfoCount,
pNewCodeInfo,
pNewVarInfo, newVarInfoCount);
// If FixContextForEnC succeeded, the stack is potentially trashed with any new locals and we have also unwound
// any Win32 handlers on the stack so cannot ever return from this function. If FixContextForEnC failed, can't
// assume that the stack is still intact so apply the proper policy for a fatal EE error to bring us down
// "gracefully" (it's all relative).
if (FAILED(hr))
{
LOG((LF_ENC, LL_INFO100, "**Error** EnCModule::ResumeInUpdatedFunction for FixContextForEnC failed\n"));
EEPOLICY_HANDLE_FATAL_ERROR(hr);
}
// Set the new IP
// Note that all we're really doing here is setting the IP register. We unfortunately don't
// share any code with the implementation of debugger SetIP, despite the similarities.
LOG((LF_ENC, LL_INFO100, "EnCModule::ResumeInUpdatedFunction: Resume at EIP=%p\n", pNewCodeInfo->GetCodeAddress()));
Thread *pCurThread = GetThread();
pCurThread->SetFilterContext(pContext);
SetIP(pContext, pNewCodeInfo->GetCodeAddress());
// Notify the debugger that we're about to resume execution in the new version of the method
HRESULT hrIgnore = g_pDebugInterface->RemapComplete(pMD, pNewCodeInfo->GetCodeAddress(), pNewCodeInfo->GetRelOffset());
// Now jump into the new version of the method. Note that we can't just setup the filter context
// and return because we are potentially writing new vars onto the stack.
pCurThread->SetFilterContext( NULL );
#if defined(TARGET_X86)
ResumeAtJit(pContext, oldSP);
#else
ClrRestoreNonvolatileContext(pContext);
#endif
// At this point we shouldn't have failed, so this is genuinely erroneous.
LOG((LF_ENC, LL_ERROR, "**Error** EnCModule::ResumeInUpdatedFunction returned from ResumeAtJit"));
_ASSERTE(!"Should not return from ResumeAtJit()");
}
#endif // #ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// ResolveField - get a pointer to the value of a field that was added by EnC
//
// Arguments:
// thisPointer - For instance fields, a pointer to the object instance of interest.
// For static fields this is unused and should be NULL.
// pFD - FieldDesc describing the field we're interested in
// fAllocateNew - If storage doesn't yet exist for this field and fAllocateNew is true
// then we will attempt to allocate the storage (throwing an exception
// if it fails). Otherwise, if fAllocateNew is false, then we will just
// return NULL when the storage is not yet available.
//
// Return Value:
// If storage doesn't yet exist for this field we return NULL, otherwise, we return a pointer
// to the contents of the field on success.
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveField(OBJECTREF thisPointer,
EnCFieldDesc * pFD)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifdef _DEBUG
if (g_BreakOnEnCResolveField == 1)
{
_ASSERTE( !"EditAndContinueModule::ResolveField");
}
#endif
// If it's static, we stash in the EnCFieldDesc
if (pFD->IsStatic())
{
_ASSERTE( thisPointer == NULL );
EnCAddedStaticField *pAddedStatic = pFD->GetStaticFieldData();
if (!pAddedStatic)
{
return NULL;
}
_ASSERTE( pAddedStatic->m_pFieldDesc == pFD );
return PTR_CBYTE(pAddedStatic->GetFieldData());
}
// not static so get it out of the syncblock
SyncBlock * pBlock = NULL;
// Get the SyncBlock, failing if not available
pBlock = thisPointer->PassiveGetSyncBlock();
if( pBlock == NULL )
{
return NULL;
}
EnCSyncBlockInfo * pEnCInfo = NULL;
// Attempt to get the EnC information from the sync block
pEnCInfo = pBlock->GetEnCInfo();
if (!pEnCInfo)
{
// No EnC info on this object yet, fail since we don't want to allocate it
return NULL;
}
// Lookup the actual field value from the EnCSyncBlockInfo
return pEnCInfo->ResolveField(thisPointer, pFD);
} // EditAndContinueModule::ResolveField
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// ResolveOrAllocateField - get a pointer to the value of a field that was added by EnC,
// allocating storage for it if necessary
//
// Arguments:
// thisPointer - For instance fields, a pointer to the object instance of interest.
// For static fields this is unused and should be NULL.
// pFD - FieldDesc describing the field we're interested in
// Return Value:
// Returns a pointer to the contents of the field on success. This should only fail due
// to out-of-memory and will therefore throw an OOM exception.
//---------------------------------------------------------------------------------------
PTR_CBYTE EditAndContinueModule::ResolveOrAllocateField(OBJECTREF thisPointer,
EnCFieldDesc * pFD)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
// first try getting a pre-existing field
PTR_CBYTE fieldAddr = ResolveField(thisPointer, pFD);
if (fieldAddr != NULL)
{
return fieldAddr;
}
// we didn't find the field already allocated
if (pFD->IsStatic())
{
_ASSERTE(thisPointer == NULL);
EnCAddedStaticField * pAddedStatic = pFD->GetOrAllocateStaticFieldData();
_ASSERTE(pAddedStatic->m_pFieldDesc == pFD);
return PTR_CBYTE(pAddedStatic->GetFieldData());
}
// not static so get it out of the syncblock
SyncBlock* pBlock = NULL;
// Get the SyncBlock, creating it if necessary
pBlock = thisPointer->GetSyncBlock();
EnCSyncBlockInfo * pEnCInfo = NULL;
// Attempt to get the EnC information from the sync block
pEnCInfo = pBlock->GetEnCInfo();
if (!pEnCInfo)
{
// Attach new EnC field info to this object.
pEnCInfo = new EnCSyncBlockInfo;
if (!pEnCInfo)
{
COMPlusThrowOM();
}
pBlock->SetEnCInfo(pEnCInfo);
}
// Lookup the actual field value from the EnCSyncBlockInfo
return pEnCInfo->ResolveOrAllocateField(thisPointer, pFD);
} // EditAndContinueModule::ResolveOrAllocateField
#endif // !DACCESS_COMPILE
//-----------------------------------------------------------------------------
// Get or optionally create an EnCEEClassData object for the specified
// EEClass in this module.
//
// Arguments:
// pClass - the EEClass of interest
// getOnly - if false (the default), we'll create a new entry of none exists yet
//
// Note: If called in a DAC build, GetOnly must be TRUE
//
PTR_EnCEEClassData EditAndContinueModule::GetEnCEEClassData(MethodTable * pMT, BOOL getOnly /*=FALSE*/ )
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#ifdef DACCESS_COMPILE
_ASSERTE(getOnly == TRUE);
#endif // DACCESS_COMPILE
DPTR(PTR_EnCEEClassData) ppData = m_ClassList.Table();
DPTR(PTR_EnCEEClassData) ppLast = ppData + m_ClassList.Count();
// Look for an existing entry for the specified class
while (ppData < ppLast)
{
PREFIX_ASSUME(ppLast != NULL);
if ((*ppData)->GetMethodTable() == pMT)
return *ppData;
++ppData;
}
// No match found. Return now if we don't want to create a new entry
if (getOnly)
{
return NULL;
}
#ifndef DACCESS_COMPILE
// Create a new entry and add it to the end our our table
EnCEEClassData *pNewData = (EnCEEClassData*)(void*)pMT->GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem_NoThrow(S_SIZE_T(sizeof(EnCEEClassData)));
pNewData->Init(pMT);
ppData = m_ClassList.Append();
if (!ppData)
return NULL;
*ppData = pNewData;
return pNewData;
#else
DacNotImpl();
return NULL;
#endif
}
// Computes the address of this field within the object "o"
void *EnCFieldDesc::GetAddress( void *o)
{
#ifndef DACCESS_COMPILE
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
// can't throw through FieldDesc::GetInstanceField if FORBIDGC_LOADER_USE_ENABLED
_ASSERTE(! FORBIDGC_LOADER_USE_ENABLED());
EditAndContinueModule *pModule = (EditAndContinueModule*)GetModule();
_ASSERTE(pModule->IsEditAndContinueEnabled());
// EnC added fields aren't just at some static offset in the object like normal fields
// are. Get the EditAndContinueModule to compute the address for us.
return (void *)pModule->ResolveOrAllocateField(ObjectToOBJECTREF((Object *)o), this);
#else
DacNotImpl();
return NULL;
#endif
}
#ifndef DACCESS_COMPILE
// Do simple field initialization
// We do this when the process is suspended for debugging (in a GC_NOTRIGGER).
// Full initialization will be done in Fixup when the process is running.
void EnCFieldDesc::Init(mdFieldDef token, BOOL fIsStatic)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// Clear out the FieldDesc incase someone attempts to use any of the fields
memset( this, 0, sizeof(EnCFieldDesc) );
// Initialize our members
m_pStaticFieldData = NULL;
m_bNeedsFixup = TRUE;
// Initialize the bare minimum of FieldDesc necessary for now
if (fIsStatic)
FieldDesc::m_isStatic = TRUE;
SetMemberDef(token);
SetEnCNew();
}
// Allocate a new EnCAddedField instance and hook it up to hold the value for an instance
// field which was added by EnC to the specified object. This effectively adds a reference from
// the object to the new field value so that the field's lifetime is managed properly.
//
// Arguments:
// pFD - description of the field being added
// thisPointer - object instance to attach the new field to
//
EnCAddedField *EnCAddedField::Allocate(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate for this %p, FD %p\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// Create a new EnCAddedField instance
EnCAddedField *pEntry = new EnCAddedField;
pEntry->m_pFieldDesc = pFD;
AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();
// We need to associate the contents of the new field with the object it is attached to
// in a way that mimics the lifetime behavior of a normal field reference. Specifically,
// when the object is collected, the field should also be collected (assuming there are no
// other references), but references to the field shouldn't keep the object alive.
// To achieve this, we have introduced the concept of a "dependent handle" which provides
// the appropriate semantics. The dependent handle has a weak reference to a "primary object"
// (the object getting a new field in this case), and a strong reference to a secondary object.
// When the primary object is collected, the reference to the secondary object is released.
// See the definition of code:HNDTYPE_DEPENDENT and code:Ref_ScanDependentHandles for more details.
//
// We create a helper object and store it as the secondary object in the dependant handle
// so that its liveliness can be maintained along with the primary object.
// The helper then contains an object reference to the real field value that we are adding.
// The reason for doing this is that we cannot hand out the handle address for
// the OBJECTREF address so we need to hand out something else that is hooked up to the handle.
GCPROTECT_BEGIN(thisPointer);
MethodTable *pHelperMT = CoreLibBinder::GetClass(CLASS__ENC_HELPER);
pEntry->m_FieldData = pDomain->CreateDependentHandle(thisPointer, AllocateObject(pHelperMT));
GCPROTECT_END();
LOG((LF_ENC, LL_INFO1000, "\tEnCAF:Allocate created dependent handle %p\n",pEntry->m_FieldData));
// The EnC helper object stores a reference to the actual field value. For fields which are
// reference types, this is simply a normal object reference so we don't need to do anything
// special here.
if (pFD->GetFieldType() != ELEMENT_TYPE_CLASS)
{
// The field is a value type so we need to create storage on the heap to hold a boxed
// copy of the value and have the helper's objectref point there.
OBJECTREF obj = NULL;
if (pFD->IsByValue())
{
// Create a boxed version of the value class. This allows the standard GC algorithm
// to take care of internal pointers into the value class.
obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
}
else
{
// In the case of primitive types, we use a reference to a 1-element array on the heap.
// I'm not sure why we bother treating primitives specially, it seems like we should be able
// to just box any value type including primitives.
obj = AllocatePrimitiveArray(ELEMENT_TYPE_I1, GetSizeForCorElementType(pFD->GetFieldType()));
}
GCPROTECT_BEGIN (obj);
// Get a FieldDesc for the object reference field in the EnC helper object (warning: triggers)
FieldDesc *pHelperField = CoreLibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
// store the empty boxed object into the helper object
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelperObj = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
OBJECTREF *pHelperRef = (OBJECTREF *)pHelperField->GetAddress( pHelperObj->GetAddress() );
SetObjectReference( pHelperRef, obj);
GCPROTECT_END ();
}
return pEntry;
}
#endif // !DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc
// Gets the address of an EnC field accounting for its type: valuetype, class or primitive
// Arguments:
// input: pHelperFieldDesc - FieldDesc for the enc helper object
// pHelper - EnC helper (points to list of added fields)
// pFD - fieldDesc describing the field of interest
// Return value: the address of the EnC added field
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc(FieldDesc * pHelperFieldDesc,
OBJECTREF pHelper,
EnCFieldDesc * pFD)
{
WRAPPER_NO_CONTRACT;
SUPPORTS_DAC;
_ASSERTE(pHelperFieldDesc != NULL);
_ASSERTE(pHelper != NULL);
// Get the address of the reference inside the helper object which points to
// the field contents
PTR_OBJECTREF pOR = dac_cast<PTR_OBJECTREF>(pHelperFieldDesc->GetAddress(pHelper->GetAddress()));
_ASSERTE(pOR != NULL);
PTR_CBYTE retAddr = NULL;
// Compute the address to the actual field contents based on the field type
// See the description above Allocate for details
if (pFD->IsByValue())
{
// field value is a value type, we store it boxed so get the pointer to the first field
retAddr = dac_cast<PTR_CBYTE>((*pOR)->UnBox());
}
else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS)
{
// field value is a reference type, we store the objref directly
retAddr = dac_cast<PTR_CBYTE>(pOR);
}
else
{
// field value is a primitive, we store it inside a 1-element array
OBJECTREF objRef = *pOR;
I1ARRAYREF primitiveArray = dac_cast<I1ARRAYREF>(objRef);
retAddr = dac_cast<PTR_CBYTE>(primitiveArray->GetDirectPointerToNonObjectElements());
}
LOG((LF_ENC, LL_INFO1000, "\tEnCSBI:RF address of %s type member is %p\n",
(pFD->IsByValue() ? "ByValue" : pFD->GetFieldType() == ELEMENT_TYPE_CLASS ? "Class" : "Other"), retAddr));
return retAddr;
} // EnCSyncBlockInfo::GetEnCFieldAddrFromHelperFieldDesc
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveField
// Get the address of the data referenced by an instance field that was added with EnC
// Arguments:
// thisPointer - the object instance whose field to access
// pFD - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an EnC added instance field
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
// We should only be passed FieldDescs for instance fields
_ASSERTE(!pFD->IsStatic());
PTR_EnCAddedField pEntry = NULL;
LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %08x\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
// arise here.
// Look for an entry for the requested field in our linked list
pEntry = m_pList;
while (pEntry && pEntry->m_pFieldDesc != pFD)
{
pEntry = pEntry->m_pNext;
}
if (!pEntry)
{
// No existing entry - we have to return NULL
return NULL;
}
// we found a matching entry in the list of EnCAddedFields
// Get the EnC helper object (see the detailed description in Allocate above)
#ifdef DACCESS_COMPILE
OBJECTREF pHelper = GetDependentHandleSecondary(pEntry->m_FieldData);
#else // DACCESS_COMPILE
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelper = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
#endif // DACCESS_COMPILE
_ASSERTE(pHelper != NULL);
FieldDesc *pHelperFieldDesc = NULL;
// We _HAVE_ to call GetExistingField b/c (a) we can't throw exceptions, and
// (b) we _DON'T_ want to run class init code, either.
pHelperFieldDesc = CoreLibBinder::GetExistingField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
if (pHelperFieldDesc == NULL)
{
return NULL;
}
else
{
return GetEnCFieldAddrFromHelperFieldDesc(pHelperFieldDesc, pHelper, pFD);
}
} // EnCSyncBlockInfo::ResolveField
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
// EnCSyncBlockInfo::ResolveOrAllocateField
// get the address of an EnC added field, allocating it if it doesn't yet exist
// Arguments:
// thisPointer - the object instance whose field to access
// pFD - fieldDesc describing the field of interest
// Return value: Returns a pointer to the data referenced by an instance field that was added with EnC
//---------------------------------------------------------------------------------------
PTR_CBYTE EnCSyncBlockInfo::ResolveOrAllocateField(OBJECTREF thisPointer, EnCFieldDesc *pFD)
{
CONTRACTL
{
GC_TRIGGERS;
WRAPPER(THROWS);
}
CONTRACTL_END;
// We should only be passed FieldDescs for instance fields
_ASSERTE( !pFD->IsStatic() );
// first try to get the address of a pre-existing field (storage has already been allocated)
PTR_CBYTE retAddr = ResolveField(thisPointer, pFD);
if (retAddr != NULL)
{
return retAddr;
}
// if the field doesn't yet have available storage, we'll have to allocate it.
PTR_EnCAddedField pEntry = NULL;
LOG((LF_ENC, LL_INFO1000, "EnCSBI:RF for this %p, FD %08x\n", OBJECTREFToObject(thisPointer), pFD->GetMemberDef()));
// This list is not synchronized--it hasn't proved a problem, but we could conceivably see race conditions
// arise here.
// Because we may have additions to the head of m_pList at any time, we have to keep searching this
// until we either find a match or succeed in allocating a new entry and adding it to the list
do
{
// Look for an entry for the requested field in our linked list (maybe it was just added)
pEntry = m_pList;
while (pEntry && pEntry->m_pFieldDesc != pFD)
{
pEntry = pEntry->m_pNext;
}
if (pEntry)
{
// match found
break;
}
// Allocate an entry and tie it to the object instance
pEntry = EnCAddedField::Allocate(thisPointer, pFD);
// put at front of list so the list is in order of most recently added
pEntry->m_pNext = m_pList;
if (FastInterlockCompareExchangePointer(&m_pList, pEntry, pEntry->m_pNext) == pEntry->m_pNext)
break;
// There was a race and another thread modified the list here, so we need to try again
// We should do this so rarely, and EnC perf is of relatively little
// consequence, we should just be taking a lock here to simplify this code.
// @todo - We leak a GC handle here. Allocate() above alloced a GC handle in m_FieldData.
// There's no dtor for pEntry to free it.
delete pEntry;
} while (TRUE);
// we found a matching entry in the list of EnCAddedFields
// Get the EnC helper object (see the detailed description in Allocate above)
IGCHandleManager *mgr = GCHandleUtilities::GetGCHandleManager();
OBJECTREF pHelper = ObjectToOBJECTREF(mgr->GetDependentHandleSecondary(pEntry->m_FieldData));
_ASSERTE(pHelper != NULL);
FieldDesc * pHelperField = NULL;
GCPROTECT_BEGIN (pHelper);
pHelperField = CoreLibBinder::GetField(FIELD__ENC_HELPER__OBJECT_REFERENCE);
GCPROTECT_END ();
return GetEnCFieldAddrFromHelperFieldDesc(pHelperField, pHelper, pFD);
} // EnCSyncBlockInfo::ResolveOrAllocateField
// Free all the resources associated with the fields added to this object instance
// This is invoked after the object instance has been collected, and the SyncBlock is
// being reclaimed.
//
// Note, this is not threadsafe, and so should only be called when we know no-one else
// maybe using this SyncBlockInfo.
void EnCSyncBlockInfo::Cleanup()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Walk our linked list of all the fields that were added
EnCAddedField *pEntry = m_pList;
while (pEntry)
{
// Clean up the handle we created in EnCAddedField::Allocate
DestroyDependentHandle(*(OBJECTHANDLE*)&pEntry->m_FieldData);
// Delete this list entry and move onto the next
EnCAddedField *next = pEntry->m_pNext;
delete pEntry;
pEntry = next;
}
// Finally, delete the sync block info itself
delete this;
}
// Allocate space to hold the value for the new static field
EnCAddedStaticField *EnCAddedStaticField::Allocate(EnCFieldDesc *pFD)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
AppDomain *pDomain = (AppDomain*) pFD->GetApproxEnclosingMethodTable()->GetDomain();
// Compute the size of the fieldData entry
size_t fieldSize;
if (pFD->IsByValue() || pFD->GetFieldType() == ELEMENT_TYPE_CLASS) {
// We store references to reference types or boxed value types
fieldSize = sizeof(OBJECTREF*);
} else {
// We store primitives inline
fieldSize = GetSizeForCorElementType(pFD->GetFieldType());
}
// allocate an instance with space for the field data
EnCAddedStaticField *pEntry = (EnCAddedStaticField *)
(void*)pDomain->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(offsetof(EnCAddedStaticField, m_FieldData)) + S_SIZE_T(fieldSize));
pEntry->m_pFieldDesc = pFD;
// Create a static objectref to point to the field contents, except for primitives
// which will use the memory available in-line at m_FieldData for storage.
// We use static object refs for static fields as these fields won't go away
// unless the module is unloaded, and they can easily be found by GC.
if (pFD->IsByValue())
{
// create a boxed version of the value class. This allows the standard GC
// algorithm to take care of internal pointers in the value class.
OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
*pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
OBJECTREF obj = AllocateObject(pFD->GetFieldTypeHandleThrowing().GetMethodTable());
SetObjectReference( *pOR, obj);
}
else if (pFD->GetFieldType() == ELEMENT_TYPE_CLASS)
{
// references to reference-types are stored directly in the field data
OBJECTREF **pOR = (OBJECTREF**)&pEntry->m_FieldData;
*pOR = pDomain->AllocateStaticFieldObjRefPtrs(1);
}
return pEntry;
}
#endif // !DACCESS_COMPILE
// GetFieldData - return the ADDRESS where the field data is located
PTR_CBYTE EnCAddedStaticField::GetFieldData()
{
LIMITED_METHOD_CONTRACT;
SUPPORTS_DAC;
if ( (m_pFieldDesc->IsByValue()) || (m_pFieldDesc->GetFieldType() == ELEMENT_TYPE_CLASS) )
{
// It's indirect via an ObjRef at m_FieldData. This is a TADDR, so we need to make a PTR_CBYTE from
// the ObjRef
return *(PTR_CBYTE *)&m_FieldData;
}
else
{
// An elementry type. It's stored directly in m_FieldData. In this case, we need to get the target
// address of the m_FieldData data member and marshal it via the DAC.
return dac_cast<PTR_CBYTE>(PTR_HOST_MEMBER_TADDR(EnCAddedStaticField, this, m_FieldData));
}
}
// Gets a pointer to the field's contents (assuming this is a static field)
// We'll return NULL if we don't yet have a pointer to the data.
// Arguments: none
// Return value: address of the static field data if available or NULL otherwise
EnCAddedStaticField * EnCFieldDesc::GetStaticFieldData()
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SUPPORTS_DAC;
}
CONTRACTL_END;
_ASSERTE(IsStatic());
return m_pStaticFieldData;
}
#ifndef DACCESS_COMPILE
// Gets a pointer to the field's contents (assuming this is a static field)
// Arguments: none
// Return value: address of the field data. If we don't yet have a pointer to the data,
// this will allocate space to store it.
// May throw OOM.
EnCAddedStaticField * EnCFieldDesc::GetOrAllocateStaticFieldData()
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
}
CONTRACTL_END;
_ASSERTE(IsStatic());
// If necessary and requested, allocate space for the static field data
if (!m_pStaticFieldData)
{
m_pStaticFieldData = EnCAddedStaticField::Allocate(this);
}
return m_pStaticFieldData;
}
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
// Adds the provided new field to the appropriate linked list and updates the appropriate count
void EnCEEClassData::AddField(EnCAddedFieldElement *pAddedField)
{
LIMITED_METHOD_CONTRACT;
// Determine the appropriate field list and update the field counter
EnCFieldDesc *pFD = &pAddedField->m_fieldDesc;
EnCAddedFieldElement **pList;
if (pFD->IsStatic())
{
++m_dwNumAddedStaticFields;
pList = &m_pAddedStaticFields;
}
else
{
++m_dwNumAddedInstanceFields;
pList = &m_pAddedInstanceFields;
}
// If the list is empty, just add this field as the only entry
if (*pList == NULL)
{
*pList = pAddedField;
return;
}
// Otherwise, add this field to the end of the field list
EnCAddedFieldElement *pCur = *pList;
while (pCur->m_next != NULL)
{
pCur = pCur->m_next;
}
pCur->m_next = pAddedField;
}
#endif // #ifndef DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
EnCEEClassData::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
DAC_ENUM_DTHIS();
if (m_pMT.IsValid())
{
m_pMT->EnumMemoryRegions(flags);
}
PTR_EnCAddedFieldElement elt = m_pAddedInstanceFields;
while (elt.IsValid())
{
elt.EnumMem();
elt = elt->m_next;
}
elt = m_pAddedStaticFields;
while (elt.IsValid())
{
elt.EnumMem();
elt = elt->m_next;
}
}
void
EditAndContinueModule::EnumMemoryRegions(CLRDataEnumMemoryFlags flags,
bool enumThis)
{
SUPPORTS_DAC;
if (enumThis)
{
DAC_ENUM_VTHIS();
}
Module::EnumMemoryRegions(flags, false);
m_ClassList.EnumMemoryRegions();
DPTR(PTR_EnCEEClassData) classData = m_ClassList.Table();
DPTR(PTR_EnCEEClassData) classLast = classData + m_ClassList.Count();
while (classData.IsValid() && classData < classLast)
{
if ((*classData).IsValid())
{
(*classData)->EnumMemoryRegions(flags);
}
classData++;
}
}
#endif // #ifdef DACCESS_COMPILE
// Create a field iterator which includes EnC fields in addition to the fields from an
// underlying ApproxFieldDescIterator.
//
// Arguments:
// pMT - MethodTable indicating the type of interest
// iteratorType - one of the ApproxFieldDescIterator::IteratorType values specifying which fields
// are of interest.
// fixupEnC - if true, then any partially-initialized EnC FieldDescs will be fixed up to be complete
// initialized FieldDescs as they are returned by Next(). This may load types and do
// other things to trigger a GC.
//
EncApproxFieldDescIterator::EncApproxFieldDescIterator(MethodTable *pMT, int iteratorType, BOOL fixupEnC) :
m_nonEnCIter( pMT, iteratorType )
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
}
CONTRACTL_END
m_fixupEnC = fixupEnC;
#ifndef DACCESS_COMPILE
// can't fixup for EnC on the debugger thread
_ASSERTE((g_pDebugInterface->GetRCThreadId() != GetCurrentThreadId()) || fixupEnC == FALSE);
#endif
m_pCurrListElem = NULL;
m_encClassData = NULL;
m_encFieldsReturned = 0;
// If this is an EnC module, then grab a pointer to the EnC data
if( pMT->GetModule()->IsEditAndContinueEnabled() )
{
PTR_EditAndContinueModule encMod = PTR_EditAndContinueModule(pMT->GetModule());
m_encClassData = encMod->GetEnCEEClassData( pMT, TRUE);
}
}
// Iterates through all fields, returns NULL when done.
PTR_FieldDesc EncApproxFieldDescIterator::Next()
{
CONTRACTL
{
NOTHROW;
if (m_fixupEnC) {GC_TRIGGERS;} else {GC_NOTRIGGER;}
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
// If we still have non-EnC fields to look at, return one of them
if( m_nonEnCIter.CountRemaining() > 0 )
{
_ASSERTE( m_encFieldsReturned == 0 );
return m_nonEnCIter.Next();
}
// Get the next EnC field Desc if any
PTR_EnCFieldDesc pFD = NextEnC();
if( pFD == NULL )
{
// No more fields
return NULL;
}
#ifndef DACCESS_COMPILE
// Fixup the fieldDesc if requested and necessary
if ( m_fixupEnC && (pFD->NeedsFixup()) )
{
// if we get an OOM during fixup, the field will just not get fixed up
EX_TRY
{
FAULT_NOT_FATAL();
pFD->Fixup(pFD->GetMemberDef());
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions)
}
// Either it's been fixed up so we can use it, or we're the Debugger RC thread, we can't fix it up,
// but it's ok since our logic will check & make sure we don't try and use it. If haven't asked to
// have the field fixed up, should never be trying to get at non-fixed up field in
// this list. Can't simply fixup the field always because loading triggers GC and many
// code paths can't tolerate that.
_ASSERTE( !(pFD->NeedsFixup()) ||
( g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId() ) );
#endif
return dac_cast<PTR_FieldDesc>(pFD);
}
// Returns the number of fields plus the number of add EnC fields
int EncApproxFieldDescIterator::Count()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
int count = m_nonEnCIter.Count();
// If this module doesn't have any EnC data then there aren't any EnC fields
if (m_encClassData == NULL)
{
return count;
}
BOOL doInst = ( GetIteratorType() & (int)ApproxFieldDescIterator::INSTANCE_FIELDS);
BOOL doStatic = ( GetIteratorType() & (int)ApproxFieldDescIterator::STATIC_FIELDS);
int cNumAddedInst = doInst ? m_encClassData->GetAddedInstanceFields() : 0;
int cNumAddedStatics = doStatic ? m_encClassData->GetAddedStaticFields() : 0;
return count + cNumAddedInst + cNumAddedStatics;
}
// Iterate through EnC added fields.
// Returns NULL when done.
PTR_EnCFieldDesc EncApproxFieldDescIterator::NextEnC()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
SUPPORTS_DAC;
}
CONTRACTL_END
// If this module doesn't have any EnC data then there aren't any EnC fields
if( m_encClassData == NULL )
{
return NULL;
}
BOOL doInst = ( GetIteratorType() & (int)ApproxFieldDescIterator::INSTANCE_FIELDS);
BOOL doStatic = ( GetIteratorType() & (int)ApproxFieldDescIterator::STATIC_FIELDS);
int cNumAddedInst = doInst ? m_encClassData->GetAddedInstanceFields() : 0;
int cNumAddedStatics = doStatic ? m_encClassData->GetAddedStaticFields() : 0;
// If we haven't returned anything yet
if ( m_encFieldsReturned == 0 )
{
_ASSERTE(m_pCurrListElem == NULL);
// We're at the start of the instance list.
if ( doInst )
{
m_pCurrListElem = m_encClassData->m_pAddedInstanceFields;
}
}
// If we've finished the instance fields (or never wanted to do any)
if ( m_encFieldsReturned == cNumAddedInst)
{
// We should be at the end of the instance list if doInst is true
_ASSERTE(m_pCurrListElem == NULL);
// We're at the start of the statics list.
if ( doStatic )
{
m_pCurrListElem = m_encClassData->m_pAddedStaticFields;
}
}
// If we don't have any elements to return, then we're done
if (m_pCurrListElem == NULL)
{
// Verify that we returned the number we expected to
_ASSERTE( m_encFieldsReturned == cNumAddedInst + cNumAddedStatics );
return NULL;
}
// Advance the list pointer and return the element
m_encFieldsReturned++;
PTR_EnCFieldDesc fd = PTR_EnCFieldDesc(PTR_HOST_MEMBER_TADDR(EnCAddedFieldElement, m_pCurrListElem, m_fieldDesc));
m_pCurrListElem = m_pCurrListElem->m_next;
return fd;
}
#endif // EnC_SUPPORTED
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/profiler/native/releaseondetach/releaseondetach.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include "../profiler.h"
#include <atomic>
// This test class is very small and doesn't do much. A repeated problem we had was that
// if an ICorProfilerCallback* interface was added the developer would forget to add
// code to call release on the new interface. This test verifies that it is reclaimed
// after detach. It relies on the fact that the base Profiler class will be updated
// to the new ICorProfilerCallback* interface whenever the interface is added.
//
// If this test fails, it likely means you added an ICorProfilerCallback* interface
// and didn't add the corresponding Release call in ~EEToProfInterfaceImpl.
class ReleaseOnDetach : public Profiler
{
public:
ReleaseOnDetach();
virtual ~ReleaseOnDetach();
static GUID GetClsid();
virtual HRESULT STDMETHODCALLTYPE InitializeForAttach(IUnknown* pCorProfilerInfoUnk, void* pvClientData, UINT cbClientData);
virtual HRESULT STDMETHODCALLTYPE Shutdown();
virtual HRESULT STDMETHODCALLTYPE ProfilerAttachComplete();
virtual HRESULT STDMETHODCALLTYPE ProfilerDetachSucceeded();
void SetCallback(ProfilerCallback callback);
private:
HRESULT GetDispenser(IMetaDataDispenserEx **disp);
IMetaDataDispenserEx* _dispenser;
std::atomic<int> _failures;
bool _detachSucceeded;
};
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include "../profiler.h"
#include <atomic>
// This test class is very small and doesn't do much. A repeated problem we had was that
// if an ICorProfilerCallback* interface was added the developer would forget to add
// code to call release on the new interface. This test verifies that it is reclaimed
// after detach. It relies on the fact that the base Profiler class will be updated
// to the new ICorProfilerCallback* interface whenever the interface is added.
//
// If this test fails, it likely means you added an ICorProfilerCallback* interface
// and didn't add the corresponding Release call in ~EEToProfInterfaceImpl.
class ReleaseOnDetach : public Profiler
{
public:
ReleaseOnDetach();
virtual ~ReleaseOnDetach();
static GUID GetClsid();
virtual HRESULT STDMETHODCALLTYPE InitializeForAttach(IUnknown* pCorProfilerInfoUnk, void* pvClientData, UINT cbClientData);
virtual HRESULT STDMETHODCALLTYPE Shutdown();
virtual HRESULT STDMETHODCALLTYPE ProfilerAttachComplete();
virtual HRESULT STDMETHODCALLTYPE ProfilerDetachSucceeded();
void SetCallback(ProfilerCallback callback);
private:
HRESULT GetDispenser(IMetaDataDispenserEx **disp);
IMetaDataDispenserEx* _dispenser;
std::atomic<int> _failures;
bool _detachSucceeded;
};
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/jit/emitjmps.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// clang-format off
#ifndef JMP_SMALL
#error Must define JMP_SMALL macro before including this file
#endif
#if defined(TARGET_XARCH)
// jump reverse instruction
JMP_SMALL(jmp , jmp , jmp )
JMP_SMALL(jo , jno , jo )
JMP_SMALL(jno , jo , jno )
JMP_SMALL(jb , jae , jb )
JMP_SMALL(jae , jb , jae )
JMP_SMALL(je , jne , je )
JMP_SMALL(jne , je , jne )
JMP_SMALL(jbe , ja , jbe )
JMP_SMALL(ja , jbe , ja )
JMP_SMALL(js , jns , js )
JMP_SMALL(jns , js , jns )
JMP_SMALL(jp , jnp , jp )
JMP_SMALL(jnp , jp , jnp )
JMP_SMALL(jl , jge , jl )
JMP_SMALL(jge , jl , jge )
JMP_SMALL(jle , jg , jle )
JMP_SMALL(jg , jle , jg )
#elif defined(TARGET_ARMARCH)
// jump reverse instruction condcode
JMP_SMALL(jmp , jmp , b ) // AL always
JMP_SMALL(eq , ne , beq ) // EQ
JMP_SMALL(ne , eq , bne ) // NE
JMP_SMALL(hs , lo , bhs ) // HS also CS
JMP_SMALL(lo , hs , blo ) // LO also CC
JMP_SMALL(mi , pl , bmi ) // MI
JMP_SMALL(pl , mi , bpl ) // PL
JMP_SMALL(vs , vc , bvs ) // VS
JMP_SMALL(vc , vs , bvc ) // VC
JMP_SMALL(hi , ls , bhi ) // HI
JMP_SMALL(ls , hi , bls ) // LS
JMP_SMALL(ge , lt , bge ) // GE
JMP_SMALL(lt , ge , blt ) // LT
JMP_SMALL(gt , le , bgt ) // GT
JMP_SMALL(le , gt , ble ) // LE
#else
#error Unsupported or unset target architecture
#endif // target type
/*****************************************************************************/
#undef JMP_SMALL
/*****************************************************************************/
// clang-format on
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// clang-format off
#ifndef JMP_SMALL
#error Must define JMP_SMALL macro before including this file
#endif
#if defined(TARGET_XARCH)
// jump reverse instruction
JMP_SMALL(jmp , jmp , jmp )
JMP_SMALL(jo , jno , jo )
JMP_SMALL(jno , jo , jno )
JMP_SMALL(jb , jae , jb )
JMP_SMALL(jae , jb , jae )
JMP_SMALL(je , jne , je )
JMP_SMALL(jne , je , jne )
JMP_SMALL(jbe , ja , jbe )
JMP_SMALL(ja , jbe , ja )
JMP_SMALL(js , jns , js )
JMP_SMALL(jns , js , jns )
JMP_SMALL(jp , jnp , jp )
JMP_SMALL(jnp , jp , jnp )
JMP_SMALL(jl , jge , jl )
JMP_SMALL(jge , jl , jge )
JMP_SMALL(jle , jg , jle )
JMP_SMALL(jg , jle , jg )
#elif defined(TARGET_ARMARCH)
// jump reverse instruction condcode
JMP_SMALL(jmp , jmp , b ) // AL always
JMP_SMALL(eq , ne , beq ) // EQ
JMP_SMALL(ne , eq , bne ) // NE
JMP_SMALL(hs , lo , bhs ) // HS also CS
JMP_SMALL(lo , hs , blo ) // LO also CC
JMP_SMALL(mi , pl , bmi ) // MI
JMP_SMALL(pl , mi , bpl ) // PL
JMP_SMALL(vs , vc , bvs ) // VS
JMP_SMALL(vc , vs , bvc ) // VC
JMP_SMALL(hi , ls , bhi ) // HI
JMP_SMALL(ls , hi , bls ) // LS
JMP_SMALL(ge , lt , bge ) // GE
JMP_SMALL(lt , ge , blt ) // LT
JMP_SMALL(gt , le , bgt ) // GT
JMP_SMALL(le , gt , ble ) // LE
#else
#error Unsupported or unset target architecture
#endif // target type
/*****************************************************************************/
#undef JMP_SMALL
/*****************************************************************************/
// clang-format on
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/tools/aot/jitinterface/jitinterface.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include "dllexport.h"
#include "jitinterface.h"
static void NotImplemented()
{
abort();
}
int JitInterfaceWrapper::FilterException(struct _EXCEPTION_POINTERS* pExceptionPointers)
{
NotImplemented();
return 1; // EXCEPTION_EXECUTE_HANDLER
}
bool JitInterfaceWrapper::runWithErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter)
{
try
{
(*function)(parameter);
}
catch (CorInfoExceptionClass *)
{
return false;
}
return true;
}
bool JitInterfaceWrapper::runWithSPMIErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter)
{
try
{
(*function)(parameter);
}
catch (CorInfoExceptionClass *)
{
return false;
}
return true;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <stdarg.h>
#include <stdlib.h>
#include <stdint.h>
#include "dllexport.h"
#include "jitinterface.h"
static void NotImplemented()
{
abort();
}
int JitInterfaceWrapper::FilterException(struct _EXCEPTION_POINTERS* pExceptionPointers)
{
NotImplemented();
return 1; // EXCEPTION_EXECUTE_HANDLER
}
bool JitInterfaceWrapper::runWithErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter)
{
try
{
(*function)(parameter);
}
catch (CorInfoExceptionClass *)
{
return false;
}
return true;
}
bool JitInterfaceWrapper::runWithSPMIErrorTrap(ICorJitInfo::errorTrapFunction function, void* parameter)
{
try
{
(*function)(parameter);
}
catch (CorInfoExceptionClass *)
{
return false;
}
return true;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/inc/guidfromname.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef GUIDFROMNAME_H_
#define GUIDFROMNAME_H_
// GuidFromName.h - function prototype
void CorGuidFromNameW
(
GUID * pGuidResult, // resulting GUID
LPCWSTR wzName, // the unicode name from which to generate a GUID
SIZE_T cchName // name length in count of unicode character.
// -1 if lstrlen(wzName)+1 should be used
);
#endif // GUIDFROMNAME_H_
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef GUIDFROMNAME_H_
#define GUIDFROMNAME_H_
// GuidFromName.h - function prototype
void CorGuidFromNameW
(
GUID * pGuidResult, // resulting GUID
LPCWSTR wzName, // the unicode name from which to generate a GUID
SIZE_T cchName // name length in count of unicode character.
// -1 if lstrlen(wzName)+1 should be used
);
#endif // GUIDFROMNAME_H_
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/libunwind/src/elfxx.h
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003, 2005 Hewlett-Packard Co
Copyright (C) 2007 David Mosberger-Tang
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "libunwind_i.h"
#if UNW_ELF_CLASS == UNW_ELFCLASS32
# define ELF_W(x) ELF32_##x
# define Elf_W(x) Elf32_##x
# define elf_w(x) _Uelf32_##x
#else
# define ELF_W(x) ELF64_##x
# define Elf_W(x) Elf64_##x
# define elf_w(x) _Uelf64_##x
#endif
extern int elf_w (get_proc_name) (unw_addr_space_t as,
pid_t pid, unw_word_t ip,
char *buf, size_t len,
unw_word_t *offp);
extern int elf_w (get_proc_name_in_image) (unw_addr_space_t as,
struct elf_image *ei,
unsigned long segbase,
unsigned long mapoff,
unw_word_t ip,
char *buf, size_t buf_len, unw_word_t *offp);
extern Elf_W (Shdr)* elf_w (find_section) (struct elf_image *ei, const char* secname);
extern int elf_w (load_debuglink) (const char* file, struct elf_image *ei, int is_local);
static inline int
elf_w (valid_object) (struct elf_image *ei)
{
if (ei->size <= EI_VERSION)
return 0;
return (memcmp (ei->image, ELFMAG, SELFMAG) == 0
&& ((uint8_t *) ei->image)[EI_CLASS] == UNW_ELF_CLASS
&& ((uint8_t *) ei->image)[EI_VERSION] != EV_NONE
&& ((uint8_t *) ei->image)[EI_VERSION] <= EV_CURRENT);
}
static inline int
elf_map_image (struct elf_image *ei, const char *path)
{
struct stat stat;
int fd;
fd = open (path, O_RDONLY);
if (fd < 0)
return -1;
if (fstat (fd, &stat) < 0)
{
close (fd);
return -1;
}
ei->size = stat.st_size;
ei->image = mmap (NULL, ei->size, PROT_READ, MAP_PRIVATE, fd, 0);
close (fd);
if (ei->image == MAP_FAILED)
return -1;
if (!elf_w (valid_object) (ei))
{
munmap(ei->image, ei->size);
return -1;
}
return 0;
}
|
/* libunwind - a platform-independent unwind library
Copyright (C) 2003, 2005 Hewlett-Packard Co
Copyright (C) 2007 David Mosberger-Tang
Contributed by David Mosberger-Tang <[email protected]>
This file is part of libunwind.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "libunwind_i.h"
#if UNW_ELF_CLASS == UNW_ELFCLASS32
# define ELF_W(x) ELF32_##x
# define Elf_W(x) Elf32_##x
# define elf_w(x) _Uelf32_##x
#else
# define ELF_W(x) ELF64_##x
# define Elf_W(x) Elf64_##x
# define elf_w(x) _Uelf64_##x
#endif
extern int elf_w (get_proc_name) (unw_addr_space_t as,
pid_t pid, unw_word_t ip,
char *buf, size_t len,
unw_word_t *offp);
extern int elf_w (get_proc_name_in_image) (unw_addr_space_t as,
struct elf_image *ei,
unsigned long segbase,
unsigned long mapoff,
unw_word_t ip,
char *buf, size_t buf_len, unw_word_t *offp);
extern Elf_W (Shdr)* elf_w (find_section) (struct elf_image *ei, const char* secname);
extern int elf_w (load_debuglink) (const char* file, struct elf_image *ei, int is_local);
static inline int
elf_w (valid_object) (struct elf_image *ei)
{
if (ei->size <= EI_VERSION)
return 0;
return (memcmp (ei->image, ELFMAG, SELFMAG) == 0
&& ((uint8_t *) ei->image)[EI_CLASS] == UNW_ELF_CLASS
&& ((uint8_t *) ei->image)[EI_VERSION] != EV_NONE
&& ((uint8_t *) ei->image)[EI_VERSION] <= EV_CURRENT);
}
static inline int
elf_map_image (struct elf_image *ei, const char *path)
{
struct stat stat;
int fd;
fd = open (path, O_RDONLY);
if (fd < 0)
return -1;
if (fstat (fd, &stat) < 0)
{
close (fd);
return -1;
}
ei->size = stat.st_size;
ei->image = mmap (NULL, ei->size, PROT_READ, MAP_PRIVATE, fd, 0);
close (fd);
if (ei->image == MAP_FAILED)
return -1;
if (!elf_w (valid_object) (ei))
{
munmap(ei->image, ei->size);
return -1;
}
return 0;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/debug/di/shimlocaldatatarget.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
//
// File: ShimLocalDataTarget.cpp
//
//*****************************************************************************
#include "stdafx.h"
#include "safewrap.h"
#include "check.h"
#include <limits.h>
#include "shimpriv.h"
#include "shimdatatarget.h"
// The Shim's Live data-target is allowed to call OS APIs directly.
// see code:RSDebuggingInfo#UseDataTarget.
#undef ReadProcessMemory
#undef WriteProcessMemory
class ShimLocalDataTarget : public ShimDataTarget
{
public:
ShimLocalDataTarget(DWORD processId, HANDLE hProcess);
~ShimLocalDataTarget();
virtual void Dispose();
//
// ICorDebugMutableDataTarget.
//
virtual HRESULT STDMETHODCALLTYPE GetPlatform(
CorDebugPlatform *pPlatform);
virtual HRESULT STDMETHODCALLTYPE ReadVirtual(
CORDB_ADDRESS address,
BYTE * pBuffer,
ULONG32 request,
ULONG32 *pcbRead);
virtual HRESULT STDMETHODCALLTYPE WriteVirtual(
CORDB_ADDRESS address,
const BYTE * pBuffer,
ULONG32 request);
virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
DWORD dwThreadID,
ULONG32 contextFlags,
ULONG32 contextSize,
BYTE * context);
virtual HRESULT STDMETHODCALLTYPE SetThreadContext(
DWORD dwThreadID,
ULONG32 contextSize,
const BYTE * context);
virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged(
DWORD dwThreadId,
CORDB_CONTINUE_STATUS dwContinueStatus);
virtual HRESULT STDMETHODCALLTYPE VirtualUnwind(
DWORD threadId, ULONG32 contextSize, PBYTE context);
private:
// Handle to the process. We own this.
HANDLE m_hProcess;
};
// Determines whether the target and host are running on compatible platforms.
// Arguments:
// input: hTargetProcess - handle for the target process
// Return Value: TRUE iff both target and host are both Wow64 or neither is.
// Note: throws
BOOL CompatibleHostAndTargetPlatforms(HANDLE hTargetProcess)
{
#if defined(TARGET_UNIX)
return TRUE;
#else
// get the platform for the host process
BOOL fHostProcessIsWow64 = FALSE;
BOOL fSuccess = FALSE;
HANDLE hHostProcess = GetCurrentProcess();
fSuccess = IsWow64Process(hHostProcess, &fHostProcessIsWow64);
CloseHandle(hHostProcess);
hHostProcess = NULL;
if (!fSuccess)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
// get the platform for the target process
if (hTargetProcess == NULL)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
BOOL fTargetProcessIsWow64 = FALSE;
fSuccess = IsWow64Process(hTargetProcess, &fTargetProcessIsWow64);
if (!fSuccess)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
// We don't want to expose the IPC block if one process is x86 and
// the other is ia64 or amd64
if (fTargetProcessIsWow64 != fHostProcessIsWow64)
{
return FALSE;
}
else
{
return TRUE;
}
#endif
} // CompatibleHostAndTargetPlatforms
// Helper macro to check for failure conditions at the start of data-target methods.
#define ReturnFailureIfStateNotOk() \
if (m_hr != S_OK) \
{ \
return m_hr; \
}
//---------------------------------------------------------------------------------------
//
// ctor for ShimLocalDataTarget.
//
// Arguments:
// processId - pid of live process.
// hProcess - handle to kernel process object.
//
// Assumptions:
// Shim takes ownership of handle hProcess.
//
ShimLocalDataTarget::ShimLocalDataTarget(DWORD processId, HANDLE hProcess)
{
m_ref = 0;
m_processId = processId;
m_hProcess = hProcess;
m_hr = S_OK;
m_fpContinueStatusChanged = NULL;
m_pContinueStatusChangedUserData = NULL;
}
//---------------------------------------------------------------------------------------
//
// dctor for ShimLocalDataTarget.
//
ShimLocalDataTarget::~ShimLocalDataTarget()
{
Dispose();
}
//---------------------------------------------------------------------------------------
//
// Dispose all resources and neuter the object.
//
//
//
// Notes:
// Release all resources (such as the handle to the process we got in the ctor).
// May be called multiple times.
// All other non-trivial APIs (eg, not IUnknown) will fail after this.
//
void ShimLocalDataTarget::Dispose()
{
if (m_hProcess != NULL)
{
CloseHandle(m_hProcess);
m_hProcess = NULL;
}
m_hr = CORDBG_E_OBJECT_NEUTERED;
}
//---------------------------------------------------------------------------------------
//
// Construction method for data-target
//
// Arguments:
// processId - (input) live OS process ID to build a data-target for.
// ppDataTarget - (output) new data-target instance. This gets addreffed.
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// pid must be for local, same architecture, process.
// Caller must have security permissions for OpenProcess()
// Caller must release *ppDataTarget.
//
HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo,
const ProcessDescriptor * pProcessDescriptor,
ShimDataTarget ** ppDataTarget)
{
HRESULT hr = S_OK;
HANDLE hProcess = NULL;
ShimLocalDataTarget * pLocalDataTarget = NULL;
*ppDataTarget = NULL;
hProcess = OpenProcess(
PROCESS_DUP_HANDLE |
PROCESS_QUERY_INFORMATION |
PROCESS_TERMINATE |
PROCESS_VM_OPERATION |
PROCESS_VM_READ |
PROCESS_VM_WRITE |
SYNCHRONIZE,
FALSE,
pProcessDescriptor->m_Pid);
if (hProcess == NULL)
{
hr = HRESULT_FROM_GetLastError();
goto Label_Exit;
}
EX_TRY
{
if (!CompatibleHostAndTargetPlatforms(hProcess))
{
hr = CORDBG_E_UNCOMPATIBLE_PLATFORMS;
goto Label_Exit;
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
goto Label_Exit;
}
pLocalDataTarget = new (nothrow) ShimLocalDataTarget(pProcessDescriptor->m_Pid, hProcess);
if (pLocalDataTarget == NULL)
{
hr = E_OUTOFMEMORY;
goto Label_Exit;
}
// ShimLocalDataTarget now has ownership of Handle.
hProcess = NULL;
_ASSERTE(SUCCEEDED(hr));
*ppDataTarget = pLocalDataTarget;
pLocalDataTarget->AddRef(); // must addref out-parameters
Label_Exit:
if (FAILED(hr))
{
if (hProcess != NULL)
{
CloseHandle(hProcess);
}
delete pLocalDataTarget;
}
return hr;
}
// impl of interface method ICorDebugDataTarget::GetPlatform
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetPlatform(
CorDebugPlatform *pPlatform)
{
#ifdef TARGET_UNIX
#error ShimLocalDataTarget is not implemented on PAL systems yet
#endif
// Assume that we're running on Windows for now.
#if defined(TARGET_X86)
*pPlatform = CORDB_PLATFORM_WINDOWS_X86;
#elif defined(TARGET_AMD64)
*pPlatform = CORDB_PLATFORM_WINDOWS_AMD64;
#elif defined(TARGET_ARM)
*pPlatform = CORDB_PLATFORM_WINDOWS_ARM;
#elif defined(TARGET_ARM64)
*pPlatform = CORDB_PLATFORM_WINDOWS_ARM64;
#else
#error Unknown Processor.
#endif
return S_OK;
}
// impl of interface method ICorDebugDataTarget::ReadVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ReadVirtual(
CORDB_ADDRESS address,
PBYTE pBuffer,
ULONG32 cbRequestSize,
ULONG32 *pcbRead)
{
ReturnFailureIfStateNotOk();
// ReadProcessMemory will fail if any part of the
// region to read does not have read access. This
// routine attempts to read the largest valid prefix
// so it has to break up reads on page boundaries.
HRESULT hrStatus = S_OK;
ULONG32 totalDone = 0;
SIZE_T read;
ULONG32 readSize;
while (cbRequestSize > 0)
{
// Calculate bytes to read and don't let read cross
// a page boundary.
readSize = GetOsPageSize() - (ULONG32)(address & (GetOsPageSize() - 1));
readSize = min(cbRequestSize, readSize);
if (!ReadProcessMemory(m_hProcess, (PVOID)(ULONG_PTR)address,
pBuffer, readSize, &read))
{
if (totalDone == 0)
{
// If we haven't read anything indicate failure.
hrStatus = HRESULT_FROM_GetLastError();
}
break;
}
totalDone += (ULONG32)read;
address += read;
pBuffer += read;
cbRequestSize -= (ULONG32)read;
}
*pcbRead = totalDone;
return hrStatus;
}
// impl of interface method ICorDebugMutableDataTarget::WriteVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::WriteVirtual(
CORDB_ADDRESS pAddress,
const BYTE * pBuffer,
ULONG32 cbRequestSize)
{
ReturnFailureIfStateNotOk();
SIZE_T cbWritten;
BOOL fWriteOk = WriteProcessMemory(m_hProcess, CORDB_ADDRESS_TO_PTR(pAddress), pBuffer, cbRequestSize, &cbWritten);
if (fWriteOk)
{
_ASSERTE(cbWritten == cbRequestSize); // MSDN docs say this must always be true
return S_OK;
}
else
{
return HRESULT_FROM_GetLastError();
}
}
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetThreadContext(
DWORD dwThreadID,
ULONG32 contextFlags,
ULONG32 contextSize,
BYTE * pContext)
{
ReturnFailureIfStateNotOk();
// @dbgtodo - Ideally we should cache the thread handles so that we don't need to
// open and close the thread handles every time.
HRESULT hr = E_FAIL;
if (!CheckContextSizeForBuffer(contextSize, pContext))
{
return E_INVALIDARG;
}
HandleHolder hThread = OpenThread(
THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION ,
FALSE, // thread handle is not inheritable.
dwThreadID);
if (hThread != NULL)
{
DT_CONTEXT * pCtx = reinterpret_cast<DT_CONTEXT *>(pContext);
pCtx->ContextFlags = contextFlags;
if (DbiGetThreadContext(hThread, pCtx))
{
hr = S_OK;
}
}
// hThread destructed automatically
return hr;
}
// impl of interface method ICorDebugMutableDataTarget::SetThreadContext
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::SetThreadContext(
DWORD dwThreadID,
ULONG32 contextSize,
const BYTE * pContext)
{
ReturnFailureIfStateNotOk();
HRESULT hr = E_FAIL;
if (!CheckContextSizeForBuffer(contextSize, pContext))
{
return E_INVALIDARG;
}
HandleHolder hThread = OpenThread(
THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION,
FALSE, // thread handle is not inheritable.
dwThreadID);
if (hThread != NULL)
{
if (DbiSetThreadContext(hThread, reinterpret_cast<const DT_CONTEXT *>(pContext)))
{
hr = S_OK;
}
}
// hThread destructed automatically
return hr;
}
// Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ContinueStatusChanged(
DWORD dwThreadId,
CORDB_CONTINUE_STATUS dwContinueStatus)
{
ReturnFailureIfStateNotOk();
if (m_fpContinueStatusChanged != NULL)
{
return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus);
}
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Unwind the stack to the next frame.
//
// Return Value:
// context filled in with the next frame
//
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context)
{
#ifndef TARGET_UNIX
_ASSERTE(!"ShimLocalDataTarget::VirtualUnwind NOT IMPLEMENTED");
#endif
return E_NOTIMPL;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
//
// File: ShimLocalDataTarget.cpp
//
//*****************************************************************************
#include "stdafx.h"
#include "safewrap.h"
#include "check.h"
#include <limits.h>
#include "shimpriv.h"
#include "shimdatatarget.h"
// The Shim's Live data-target is allowed to call OS APIs directly.
// see code:RSDebuggingInfo#UseDataTarget.
#undef ReadProcessMemory
#undef WriteProcessMemory
class ShimLocalDataTarget : public ShimDataTarget
{
public:
ShimLocalDataTarget(DWORD processId, HANDLE hProcess);
~ShimLocalDataTarget();
virtual void Dispose();
//
// ICorDebugMutableDataTarget.
//
virtual HRESULT STDMETHODCALLTYPE GetPlatform(
CorDebugPlatform *pPlatform);
virtual HRESULT STDMETHODCALLTYPE ReadVirtual(
CORDB_ADDRESS address,
BYTE * pBuffer,
ULONG32 request,
ULONG32 *pcbRead);
virtual HRESULT STDMETHODCALLTYPE WriteVirtual(
CORDB_ADDRESS address,
const BYTE * pBuffer,
ULONG32 request);
virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
DWORD dwThreadID,
ULONG32 contextFlags,
ULONG32 contextSize,
BYTE * context);
virtual HRESULT STDMETHODCALLTYPE SetThreadContext(
DWORD dwThreadID,
ULONG32 contextSize,
const BYTE * context);
virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged(
DWORD dwThreadId,
CORDB_CONTINUE_STATUS dwContinueStatus);
virtual HRESULT STDMETHODCALLTYPE VirtualUnwind(
DWORD threadId, ULONG32 contextSize, PBYTE context);
private:
// Handle to the process. We own this.
HANDLE m_hProcess;
};
// Determines whether the target and host are running on compatible platforms.
// Arguments:
// input: hTargetProcess - handle for the target process
// Return Value: TRUE iff both target and host are both Wow64 or neither is.
// Note: throws
BOOL CompatibleHostAndTargetPlatforms(HANDLE hTargetProcess)
{
#if defined(TARGET_UNIX)
return TRUE;
#else
// get the platform for the host process
BOOL fHostProcessIsWow64 = FALSE;
BOOL fSuccess = FALSE;
HANDLE hHostProcess = GetCurrentProcess();
fSuccess = IsWow64Process(hHostProcess, &fHostProcessIsWow64);
CloseHandle(hHostProcess);
hHostProcess = NULL;
if (!fSuccess)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
// get the platform for the target process
if (hTargetProcess == NULL)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
BOOL fTargetProcessIsWow64 = FALSE;
fSuccess = IsWow64Process(hTargetProcess, &fTargetProcessIsWow64);
if (!fSuccess)
{
ThrowHR(HRESULT_FROM_GetLastError());
}
// We don't want to expose the IPC block if one process is x86 and
// the other is ia64 or amd64
if (fTargetProcessIsWow64 != fHostProcessIsWow64)
{
return FALSE;
}
else
{
return TRUE;
}
#endif
} // CompatibleHostAndTargetPlatforms
// Helper macro to check for failure conditions at the start of data-target methods.
#define ReturnFailureIfStateNotOk() \
if (m_hr != S_OK) \
{ \
return m_hr; \
}
//---------------------------------------------------------------------------------------
//
// ctor for ShimLocalDataTarget.
//
// Arguments:
// processId - pid of live process.
// hProcess - handle to kernel process object.
//
// Assumptions:
// Shim takes ownership of handle hProcess.
//
ShimLocalDataTarget::ShimLocalDataTarget(DWORD processId, HANDLE hProcess)
{
m_ref = 0;
m_processId = processId;
m_hProcess = hProcess;
m_hr = S_OK;
m_fpContinueStatusChanged = NULL;
m_pContinueStatusChangedUserData = NULL;
}
//---------------------------------------------------------------------------------------
//
// dctor for ShimLocalDataTarget.
//
ShimLocalDataTarget::~ShimLocalDataTarget()
{
Dispose();
}
//---------------------------------------------------------------------------------------
//
// Dispose all resources and neuter the object.
//
//
//
// Notes:
// Release all resources (such as the handle to the process we got in the ctor).
// May be called multiple times.
// All other non-trivial APIs (eg, not IUnknown) will fail after this.
//
void ShimLocalDataTarget::Dispose()
{
if (m_hProcess != NULL)
{
CloseHandle(m_hProcess);
m_hProcess = NULL;
}
m_hr = CORDBG_E_OBJECT_NEUTERED;
}
//---------------------------------------------------------------------------------------
//
// Construction method for data-target
//
// Arguments:
// processId - (input) live OS process ID to build a data-target for.
// ppDataTarget - (output) new data-target instance. This gets addreffed.
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// pid must be for local, same architecture, process.
// Caller must have security permissions for OpenProcess()
// Caller must release *ppDataTarget.
//
HRESULT BuildPlatformSpecificDataTarget(MachineInfo machineInfo,
const ProcessDescriptor * pProcessDescriptor,
ShimDataTarget ** ppDataTarget)
{
HRESULT hr = S_OK;
HANDLE hProcess = NULL;
ShimLocalDataTarget * pLocalDataTarget = NULL;
*ppDataTarget = NULL;
hProcess = OpenProcess(
PROCESS_DUP_HANDLE |
PROCESS_QUERY_INFORMATION |
PROCESS_TERMINATE |
PROCESS_VM_OPERATION |
PROCESS_VM_READ |
PROCESS_VM_WRITE |
SYNCHRONIZE,
FALSE,
pProcessDescriptor->m_Pid);
if (hProcess == NULL)
{
hr = HRESULT_FROM_GetLastError();
goto Label_Exit;
}
EX_TRY
{
if (!CompatibleHostAndTargetPlatforms(hProcess))
{
hr = CORDBG_E_UNCOMPATIBLE_PLATFORMS;
goto Label_Exit;
}
}
EX_CATCH_HRESULT(hr);
if (FAILED(hr))
{
goto Label_Exit;
}
pLocalDataTarget = new (nothrow) ShimLocalDataTarget(pProcessDescriptor->m_Pid, hProcess);
if (pLocalDataTarget == NULL)
{
hr = E_OUTOFMEMORY;
goto Label_Exit;
}
// ShimLocalDataTarget now has ownership of Handle.
hProcess = NULL;
_ASSERTE(SUCCEEDED(hr));
*ppDataTarget = pLocalDataTarget;
pLocalDataTarget->AddRef(); // must addref out-parameters
Label_Exit:
if (FAILED(hr))
{
if (hProcess != NULL)
{
CloseHandle(hProcess);
}
delete pLocalDataTarget;
}
return hr;
}
// impl of interface method ICorDebugDataTarget::GetPlatform
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetPlatform(
CorDebugPlatform *pPlatform)
{
#ifdef TARGET_UNIX
#error ShimLocalDataTarget is not implemented on PAL systems yet
#endif
// Assume that we're running on Windows for now.
#if defined(TARGET_X86)
*pPlatform = CORDB_PLATFORM_WINDOWS_X86;
#elif defined(TARGET_AMD64)
*pPlatform = CORDB_PLATFORM_WINDOWS_AMD64;
#elif defined(TARGET_ARM)
*pPlatform = CORDB_PLATFORM_WINDOWS_ARM;
#elif defined(TARGET_ARM64)
*pPlatform = CORDB_PLATFORM_WINDOWS_ARM64;
#else
#error Unknown Processor.
#endif
return S_OK;
}
// impl of interface method ICorDebugDataTarget::ReadVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ReadVirtual(
CORDB_ADDRESS address,
PBYTE pBuffer,
ULONG32 cbRequestSize,
ULONG32 *pcbRead)
{
ReturnFailureIfStateNotOk();
// ReadProcessMemory will fail if any part of the
// region to read does not have read access. This
// routine attempts to read the largest valid prefix
// so it has to break up reads on page boundaries.
HRESULT hrStatus = S_OK;
ULONG32 totalDone = 0;
SIZE_T read;
ULONG32 readSize;
while (cbRequestSize > 0)
{
// Calculate bytes to read and don't let read cross
// a page boundary.
readSize = GetOsPageSize() - (ULONG32)(address & (GetOsPageSize() - 1));
readSize = min(cbRequestSize, readSize);
if (!ReadProcessMemory(m_hProcess, (PVOID)(ULONG_PTR)address,
pBuffer, readSize, &read))
{
if (totalDone == 0)
{
// If we haven't read anything indicate failure.
hrStatus = HRESULT_FROM_GetLastError();
}
break;
}
totalDone += (ULONG32)read;
address += read;
pBuffer += read;
cbRequestSize -= (ULONG32)read;
}
*pcbRead = totalDone;
return hrStatus;
}
// impl of interface method ICorDebugMutableDataTarget::WriteVirtual
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::WriteVirtual(
CORDB_ADDRESS pAddress,
const BYTE * pBuffer,
ULONG32 cbRequestSize)
{
ReturnFailureIfStateNotOk();
SIZE_T cbWritten;
BOOL fWriteOk = WriteProcessMemory(m_hProcess, CORDB_ADDRESS_TO_PTR(pAddress), pBuffer, cbRequestSize, &cbWritten);
if (fWriteOk)
{
_ASSERTE(cbWritten == cbRequestSize); // MSDN docs say this must always be true
return S_OK;
}
else
{
return HRESULT_FROM_GetLastError();
}
}
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::GetThreadContext(
DWORD dwThreadID,
ULONG32 contextFlags,
ULONG32 contextSize,
BYTE * pContext)
{
ReturnFailureIfStateNotOk();
// @dbgtodo - Ideally we should cache the thread handles so that we don't need to
// open and close the thread handles every time.
HRESULT hr = E_FAIL;
if (!CheckContextSizeForBuffer(contextSize, pContext))
{
return E_INVALIDARG;
}
HandleHolder hThread = OpenThread(
THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION ,
FALSE, // thread handle is not inheritable.
dwThreadID);
if (hThread != NULL)
{
DT_CONTEXT * pCtx = reinterpret_cast<DT_CONTEXT *>(pContext);
pCtx->ContextFlags = contextFlags;
if (DbiGetThreadContext(hThread, pCtx))
{
hr = S_OK;
}
}
// hThread destructed automatically
return hr;
}
// impl of interface method ICorDebugMutableDataTarget::SetThreadContext
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::SetThreadContext(
DWORD dwThreadID,
ULONG32 contextSize,
const BYTE * pContext)
{
ReturnFailureIfStateNotOk();
HRESULT hr = E_FAIL;
if (!CheckContextSizeForBuffer(contextSize, pContext))
{
return E_INVALIDARG;
}
HandleHolder hThread = OpenThread(
THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_QUERY_INFORMATION,
FALSE, // thread handle is not inheritable.
dwThreadID);
if (hThread != NULL)
{
if (DbiSetThreadContext(hThread, reinterpret_cast<const DT_CONTEXT *>(pContext)))
{
hr = S_OK;
}
}
// hThread destructed automatically
return hr;
}
// Public implementation of ICorDebugMutableDataTarget::ContinueStatusChanged
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::ContinueStatusChanged(
DWORD dwThreadId,
CORDB_CONTINUE_STATUS dwContinueStatus)
{
ReturnFailureIfStateNotOk();
if (m_fpContinueStatusChanged != NULL)
{
return m_fpContinueStatusChanged(m_pContinueStatusChangedUserData, dwThreadId, dwContinueStatus);
}
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Unwind the stack to the next frame.
//
// Return Value:
// context filled in with the next frame
//
HRESULT STDMETHODCALLTYPE
ShimLocalDataTarget::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context)
{
#ifndef TARGET_UNIX
_ASSERTE(!"ShimLocalDataTarget::VirtualUnwind NOT IMPLEMENTED");
#endif
return E_NOTIMPL;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/include/pal/numa.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
include/pal/numa.h
Abstract:
Header file for the NUMA functions.
--*/
#ifndef _PAL_NUMA_H_
#define _PAL_NUMA_H_
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
BOOL
NUMASupportInitialize();
VOID
NUMASupportCleanup();
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* _PAL_CRITSECT_H_ */
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
include/pal/numa.h
Abstract:
Header file for the NUMA functions.
--*/
#ifndef _PAL_NUMA_H_
#define _PAL_NUMA_H_
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
BOOL
NUMASupportInitialize();
VOID
NUMASupportCleanup();
#ifdef __cplusplus
}
#endif // __cplusplus
#endif /* _PAL_CRITSECT_H_ */
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/c_runtime/exit/test2/test2.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test2.c
**
** Purpose: Calls exit on fail, and verifies that it actually
** stops program execution and return 1.
**
**==========================================================================*/
#include <palsuite.h>
PALTEST(c_runtime_exit_test2_paltest_exit_test2, "c_runtime/exit/test2/paltest_exit_test2")
{
/*
* Initialize the PAL and return FAIL if this fails
*/
if (0 != (PAL_Initialize(argc, argv)))
{
return FAIL;
}
/*should return 1*/
exit(1);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test2.c
**
** Purpose: Calls exit on fail, and verifies that it actually
** stops program execution and return 1.
**
**==========================================================================*/
#include <palsuite.h>
PALTEST(c_runtime_exit_test2_paltest_exit_test2, "c_runtime/exit/test2/paltest_exit_test2")
{
/*
* Initialize the PAL and return FAIL if this fails
*/
if (0 != (PAL_Initialize(argc, argv)))
{
return FAIL;
}
/*should return 1*/
exit(1);
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/mono/wasm/runtime/pinvoke.h
|
#ifndef __PINVOKE_H__
#define __PINVOKE_H__
typedef struct {
const char *name;
void *func;
} PinvokeImport;
typedef struct {
void *func;
void *arg;
} InterpFtnDesc;
void*
wasm_dl_lookup_pinvoke_table (const char *name);
int
wasm_dl_is_pinvoke_table (void *handle);
void*
wasm_dl_get_native_to_interp (const char *key, void *extra_arg);
void
mono_wasm_pinvoke_vararg_stub (void);
#endif
|
#ifndef __PINVOKE_H__
#define __PINVOKE_H__
typedef struct {
const char *name;
void *func;
} PinvokeImport;
typedef struct {
void *func;
void *arg;
} InterpFtnDesc;
void*
wasm_dl_lookup_pinvoke_table (const char *name);
int
wasm_dl_is_pinvoke_table (void *handle);
void*
wasm_dl_get_native_to_interp (const char *key, void *extra_arg);
void
mono_wasm_pinvoke_vararg_stub (void);
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/eventprovider/CMakeLists.txt
|
set(EVENT_MANIFEST ${VM_DIR}/ClrEtwAll.man)
if(CLR_CMAKE_HOST_LINUX)
add_subdirectory(lttngprovider)
else()
add_subdirectory(dummyprovider)
endif()
|
set(EVENT_MANIFEST ${VM_DIR}/ClrEtwAll.man)
if(CLR_CMAKE_HOST_LINUX)
add_subdirectory(lttngprovider)
else()
add_subdirectory(dummyprovider)
endif()
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/unwinder/i386/unwinder_i386.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
#include "stdafx.h"
#include "unwinder_i386.h"
#ifdef FEATURE_EH_FUNCLETS
BOOL OOPStackUnwinderX86::Unwind(T_CONTEXT* pContextRecord, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers)
{
REGDISPLAY rd;
FillRegDisplay(&rd, pContextRecord);
rd.SP = pContextRecord->Esp;
rd.PCTAddr = (UINT_PTR)&(pContextRecord->Eip);
if (pContextPointers)
{
rd.pCurrentContextPointers = pContextPointers;
}
CodeManState codeManState;
codeManState.dwIsSet = 0;
DWORD ControlPc = pContextRecord->Eip;
EECodeInfo codeInfo;
codeInfo.Init((PCODE) ControlPc);
if (!UnwindStackFrame(&rd, &codeInfo, UpdateAllRegs, &codeManState, NULL))
{
return FALSE;
}
pContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL;
#define ARGUMENT_AND_SCRATCH_REGISTER(reg) if (rd.pCurrentContextPointers->reg) pContextRecord->reg = *rd.pCurrentContextPointers->reg;
ENUM_ARGUMENT_AND_SCRATCH_REGISTERS();
#undef ARGUMENT_AND_SCRATCH_REGISTER
#define CALLEE_SAVED_REGISTER(reg) if (rd.pCurrentContextPointers->reg) pContextRecord->reg = *rd.pCurrentContextPointers->reg;
ENUM_CALLEE_SAVED_REGISTERS();
#undef CALLEE_SAVED_REGISTER
pContextRecord->Esp = rd.SP - codeInfo.GetCodeManager()->GetStackParameterSize(&codeInfo);
pContextRecord->Eip = rd.ControlPC;
return TRUE;
}
/*++
Routine Description:
This function virtually unwinds the specified function by executing its
prologue code backward or its epilogue code forward.
If a context pointers record is specified, then the address where each
nonvolatile registers is restored from is recorded in the appropriate
element of the context pointers record.
Arguments:
HandlerType - Supplies the handler type expected for the virtual unwind.
This may be either an exception or an unwind handler. A flag may
optionally be supplied to avoid epilogue detection if it is known
the specified control PC is not located inside a function epilogue.
ImageBase - Supplies the base address of the image that contains the
function being unwound.
ControlPc - Supplies the address where control left the specified
function.
FunctionEntry - Supplies the address of the function table entry for the
specified function.
ContextRecord - Supplies the address of a context record.
HandlerData - Supplies a pointer to a variable that receives a pointer
the the language handler data.
EstablisherFrame - Supplies a pointer to a variable that receives the
the establisher frame pointer value.
ContextPointers - Supplies an optional pointer to a context pointers
record.
HandlerRoutine - Supplies an optional pointer to a variable that receives
the handler routine address. If control did not leave the specified
function in either the prologue or an epilogue and a handler of the
proper type is associated with the function, then the address of the
language specific exception handler is returned. Otherwise, NULL is
returned.
--*/
HRESULT
OOPStackUnwinderX86::VirtualUnwind(
_In_ DWORD HandlerType,
_In_ DWORD ImageBase,
_In_ DWORD ControlPc,
_In_ _PIMAGE_RUNTIME_FUNCTION_ENTRY FunctionEntry,
__inout PCONTEXT ContextRecord,
_Out_ PVOID *HandlerData,
_Out_ PDWORD EstablisherFrame,
__inout_opt PKNONVOLATILE_CONTEXT_POINTERS ContextPointers,
_Outptr_opt_result_maybenull_ PEXCEPTION_ROUTINE *HandlerRoutine
)
{
if (HandlerRoutine != NULL)
{
*HandlerRoutine = NULL;
}
_ASSERTE(ContextRecord->Eip == ControlPc);
if (!OOPStackUnwinderX86::Unwind(ContextRecord, ContextPointers))
{
return HRESULT_FROM_WIN32(ERROR_READ_FAULT);
}
// For x86, the value of Establisher Frame Pointer is Caller SP
//
// (Please refers to CLR ABI for details)
*EstablisherFrame = ContextRecord->Esp;
return S_OK;
}
BOOL DacUnwindStackFrame(T_CONTEXT* pContextRecord, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers)
{
BOOL res = OOPStackUnwinderX86::Unwind(pContextRecord, NULL);
if (res && pContextPointers)
{
FillContextPointers(pContextPointers, pContextRecord);
}
return res;
}
//---------------------------------------------------------------------------------------
//
// This function behaves like the RtlVirtualUnwind in Windows.
// It virtually unwinds the specified function by executing its
// prologue code backward or its epilogue code forward.
//
// If a context pointers record is specified, then the address where each
// nonvolatile registers is restored from is recorded in the appropriate
// element of the context pointers record.
//
// Arguments:
//
// HandlerType - Supplies the handler type expected for the virtual unwind.
// This may be either an exception or an unwind handler. A flag may
// optionally be supplied to avoid epilogue detection if it is known
// the specified control PC is not located inside a function epilogue.
//
// ImageBase - Supplies the base address of the image that contains the
// function being unwound.
//
// ControlPc - Supplies the address where control left the specified
// function.
//
// FunctionEntry - Supplies the address of the function table entry for the
// specified function.
//
// ContextRecord - Supplies the address of a context record.
//
// HandlerData - Supplies a pointer to a variable that receives a pointer
// the the language handler data.
//
// EstablisherFrame - Supplies a pointer to a variable that receives the
// the establisher frame pointer value.
//
// ContextPointers - Supplies an optional pointer to a context pointers
// record.
//
// Return value:
//
// The handler routine address. If control did not leave the specified
// function in either the prologue or an epilogue and a handler of the
// proper type is associated with the function, then the address of the
// language specific exception handler is returned. Otherwise, NULL is
// returned.
//
EXTERN_C
NTSYSAPI
PEXCEPTION_ROUTINE
NTAPI
RtlVirtualUnwind (
_In_ DWORD HandlerType,
_In_ DWORD ImageBase,
_In_ DWORD ControlPc,
_In_ PRUNTIME_FUNCTION FunctionEntry,
__inout PT_CONTEXT ContextRecord,
_Out_ PVOID *HandlerData,
_Out_ PDWORD EstablisherFrame,
__inout_opt PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers
)
{
PEXCEPTION_ROUTINE handlerRoutine;
HRESULT res = OOPStackUnwinderX86::VirtualUnwind(
HandlerType,
ImageBase,
ControlPc,
(_PIMAGE_RUNTIME_FUNCTION_ENTRY)FunctionEntry,
ContextRecord,
HandlerData,
EstablisherFrame,
ContextPointers,
&handlerRoutine);
_ASSERTE(SUCCEEDED(res));
return handlerRoutine;
}
#endif // FEATURE_EH_FUNCLETS
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
#include "stdafx.h"
#include "unwinder_i386.h"
#ifdef FEATURE_EH_FUNCLETS
BOOL OOPStackUnwinderX86::Unwind(T_CONTEXT* pContextRecord, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers)
{
REGDISPLAY rd;
FillRegDisplay(&rd, pContextRecord);
rd.SP = pContextRecord->Esp;
rd.PCTAddr = (UINT_PTR)&(pContextRecord->Eip);
if (pContextPointers)
{
rd.pCurrentContextPointers = pContextPointers;
}
CodeManState codeManState;
codeManState.dwIsSet = 0;
DWORD ControlPc = pContextRecord->Eip;
EECodeInfo codeInfo;
codeInfo.Init((PCODE) ControlPc);
if (!UnwindStackFrame(&rd, &codeInfo, UpdateAllRegs, &codeManState, NULL))
{
return FALSE;
}
pContextRecord->ContextFlags |= CONTEXT_UNWOUND_TO_CALL;
#define ARGUMENT_AND_SCRATCH_REGISTER(reg) if (rd.pCurrentContextPointers->reg) pContextRecord->reg = *rd.pCurrentContextPointers->reg;
ENUM_ARGUMENT_AND_SCRATCH_REGISTERS();
#undef ARGUMENT_AND_SCRATCH_REGISTER
#define CALLEE_SAVED_REGISTER(reg) if (rd.pCurrentContextPointers->reg) pContextRecord->reg = *rd.pCurrentContextPointers->reg;
ENUM_CALLEE_SAVED_REGISTERS();
#undef CALLEE_SAVED_REGISTER
pContextRecord->Esp = rd.SP - codeInfo.GetCodeManager()->GetStackParameterSize(&codeInfo);
pContextRecord->Eip = rd.ControlPC;
return TRUE;
}
/*++
Routine Description:
This function virtually unwinds the specified function by executing its
prologue code backward or its epilogue code forward.
If a context pointers record is specified, then the address where each
nonvolatile registers is restored from is recorded in the appropriate
element of the context pointers record.
Arguments:
HandlerType - Supplies the handler type expected for the virtual unwind.
This may be either an exception or an unwind handler. A flag may
optionally be supplied to avoid epilogue detection if it is known
the specified control PC is not located inside a function epilogue.
ImageBase - Supplies the base address of the image that contains the
function being unwound.
ControlPc - Supplies the address where control left the specified
function.
FunctionEntry - Supplies the address of the function table entry for the
specified function.
ContextRecord - Supplies the address of a context record.
HandlerData - Supplies a pointer to a variable that receives a pointer
the the language handler data.
EstablisherFrame - Supplies a pointer to a variable that receives the
the establisher frame pointer value.
ContextPointers - Supplies an optional pointer to a context pointers
record.
HandlerRoutine - Supplies an optional pointer to a variable that receives
the handler routine address. If control did not leave the specified
function in either the prologue or an epilogue and a handler of the
proper type is associated with the function, then the address of the
language specific exception handler is returned. Otherwise, NULL is
returned.
--*/
HRESULT
OOPStackUnwinderX86::VirtualUnwind(
_In_ DWORD HandlerType,
_In_ DWORD ImageBase,
_In_ DWORD ControlPc,
_In_ _PIMAGE_RUNTIME_FUNCTION_ENTRY FunctionEntry,
__inout PCONTEXT ContextRecord,
_Out_ PVOID *HandlerData,
_Out_ PDWORD EstablisherFrame,
__inout_opt PKNONVOLATILE_CONTEXT_POINTERS ContextPointers,
_Outptr_opt_result_maybenull_ PEXCEPTION_ROUTINE *HandlerRoutine
)
{
if (HandlerRoutine != NULL)
{
*HandlerRoutine = NULL;
}
_ASSERTE(ContextRecord->Eip == ControlPc);
if (!OOPStackUnwinderX86::Unwind(ContextRecord, ContextPointers))
{
return HRESULT_FROM_WIN32(ERROR_READ_FAULT);
}
// For x86, the value of Establisher Frame Pointer is Caller SP
//
// (Please refers to CLR ABI for details)
*EstablisherFrame = ContextRecord->Esp;
return S_OK;
}
BOOL DacUnwindStackFrame(T_CONTEXT* pContextRecord, T_KNONVOLATILE_CONTEXT_POINTERS* pContextPointers)
{
BOOL res = OOPStackUnwinderX86::Unwind(pContextRecord, NULL);
if (res && pContextPointers)
{
FillContextPointers(pContextPointers, pContextRecord);
}
return res;
}
//---------------------------------------------------------------------------------------
//
// This function behaves like the RtlVirtualUnwind in Windows.
// It virtually unwinds the specified function by executing its
// prologue code backward or its epilogue code forward.
//
// If a context pointers record is specified, then the address where each
// nonvolatile registers is restored from is recorded in the appropriate
// element of the context pointers record.
//
// Arguments:
//
// HandlerType - Supplies the handler type expected for the virtual unwind.
// This may be either an exception or an unwind handler. A flag may
// optionally be supplied to avoid epilogue detection if it is known
// the specified control PC is not located inside a function epilogue.
//
// ImageBase - Supplies the base address of the image that contains the
// function being unwound.
//
// ControlPc - Supplies the address where control left the specified
// function.
//
// FunctionEntry - Supplies the address of the function table entry for the
// specified function.
//
// ContextRecord - Supplies the address of a context record.
//
// HandlerData - Supplies a pointer to a variable that receives a pointer
// the the language handler data.
//
// EstablisherFrame - Supplies a pointer to a variable that receives the
// the establisher frame pointer value.
//
// ContextPointers - Supplies an optional pointer to a context pointers
// record.
//
// Return value:
//
// The handler routine address. If control did not leave the specified
// function in either the prologue or an epilogue and a handler of the
// proper type is associated with the function, then the address of the
// language specific exception handler is returned. Otherwise, NULL is
// returned.
//
EXTERN_C
NTSYSAPI
PEXCEPTION_ROUTINE
NTAPI
RtlVirtualUnwind (
_In_ DWORD HandlerType,
_In_ DWORD ImageBase,
_In_ DWORD ControlPc,
_In_ PRUNTIME_FUNCTION FunctionEntry,
__inout PT_CONTEXT ContextRecord,
_Out_ PVOID *HandlerData,
_Out_ PDWORD EstablisherFrame,
__inout_opt PT_KNONVOLATILE_CONTEXT_POINTERS ContextPointers
)
{
PEXCEPTION_ROUTINE handlerRoutine;
HRESULT res = OOPStackUnwinderX86::VirtualUnwind(
HandlerType,
ImageBase,
ControlPc,
(_PIMAGE_RUNTIME_FUNCTION_ENTRY)FunctionEntry,
ContextRecord,
HandlerData,
EstablisherFrame,
ContextPointers,
&handlerRoutine);
_ASSERTE(SUCCEEDED(res));
return handlerRoutine;
}
#endif // FEATURE_EH_FUNCLETS
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/profiler/native/gcbasicprofiler/gcbasicprofiler.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include "../profiler.h"
class GCBasicProfiler : public Profiler
{
public:
GCBasicProfiler() : Profiler(),
_gcStarts(0),
_gcFinishes(0),
_failures(0)
{}
static GUID GetClsid();
virtual HRESULT STDMETHODCALLTYPE Initialize(IUnknown* pICorProfilerInfoUnk);
virtual HRESULT STDMETHODCALLTYPE Shutdown();
virtual HRESULT STDMETHODCALLTYPE GarbageCollectionStarted(int cGenerations, BOOL generationCollected[], COR_PRF_GC_REASON reason);
virtual HRESULT STDMETHODCALLTYPE GarbageCollectionFinished();
private:
std::atomic<int> _gcStarts;
std::atomic<int> _gcFinishes;
std::atomic<int> _failures;
};
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include "../profiler.h"
class GCBasicProfiler : public Profiler
{
public:
GCBasicProfiler() : Profiler(),
_gcStarts(0),
_gcFinishes(0),
_failures(0)
{}
static GUID GetClsid();
virtual HRESULT STDMETHODCALLTYPE Initialize(IUnknown* pICorProfilerInfoUnk);
virtual HRESULT STDMETHODCALLTYPE Shutdown();
virtual HRESULT STDMETHODCALLTYPE GarbageCollectionStarted(int cGenerations, BOOL generationCollected[], COR_PRF_GC_REASON reason);
virtual HRESULT STDMETHODCALLTYPE GarbageCollectionFinished();
private:
std::atomic<int> _gcStarts;
std::atomic<int> _gcFinishes;
std::atomic<int> _failures;
};
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/debug/debug-pal/win/twowaypipe.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <assert.h>
#include "twowaypipe.h"
#define _ASSERTE assert
// This file contains implementation of a simple IPC mechanism - bidirectional named pipe.
// It is implemented on top of two one-directional names pipes (fifos on UNIX)
// Creates a server side of the pipe.
// Id is used to create pipes names and uniquely identify the pipe on the machine.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::CreateServer(const ProcessDescriptor& pd)
{
_ASSERTE(m_state == NotInitialized);
if (m_state != NotInitialized)
return false;
m_inboundPipe = CreateOneWayPipe(pd.m_Pid, true);
if (m_inboundPipe == INVALID_HANDLE_VALUE)
{
return false;
}
m_outboundPipe = CreateOneWayPipe(pd.m_Pid, false);
if (m_outboundPipe == INVALID_HANDLE_VALUE)
{
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
return false;
}
m_state = Created;
return true;
}
// Connects to a previously opened server side of the pipe.
// Id is used to locate the pipe on the machine.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::Connect(const ProcessDescriptor& pd)
{
_ASSERTE(m_state == NotInitialized);
if (m_state != NotInitialized)
return false;
m_inboundPipe = OpenOneWayPipe(pd.m_Pid, true);
if (m_inboundPipe == INVALID_HANDLE_VALUE)
{
return false;
}
m_outboundPipe = OpenOneWayPipe(pd.m_Pid, false);
if (m_outboundPipe == INVALID_HANDLE_VALUE)
{
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
return false;
}
m_state = ClientConnected;
return true;
}
// Waits for incoming client connections, assumes GetState() == Created
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::WaitForConnection()
{
_ASSERTE(m_state == Created);
if (m_state != Created)
return false;
if (!ConnectNamedPipe(m_inboundPipe, NULL))
{
auto error = GetLastError();
if (error != ERROR_PIPE_CONNECTED)
return false;
}
if (!ConnectNamedPipe(m_outboundPipe, NULL))
{
auto error = GetLastError();
if (error != ERROR_PIPE_CONNECTED)
return false;
}
m_state = ServerConnected;
return true;
}
// Reads data from pipe. Returns number of bytes read or a negative number in case of an error.
// use GetLastError() for more details
int TwoWayPipe::Read(void *buffer, DWORD bufferSize)
{
_ASSERTE(m_state == ServerConnected || m_state == ClientConnected);
DWORD bytesRead;
BOOL ok = ReadFile(m_inboundPipe, buffer, bufferSize, &bytesRead, NULL);
if (ok)
{
return (int)bytesRead;
}
else
{
return -1;
}
}
// Writes data to pipe. Returns number of bytes written or a negative number in case of an error.
// use GetLastError() for more details
int TwoWayPipe::Write(const void *data, DWORD dataSize)
{
_ASSERTE(m_state == ServerConnected || m_state == ClientConnected);
DWORD bytesWritten;
BOOL ok = WriteFile(m_outboundPipe, data, dataSize, &bytesWritten, NULL);
if (ok)
{
FlushFileBuffers(m_outboundPipe);
return (int)bytesWritten;
}
else
{
return -1;
}
}
// Disconnect server or client side of the pipe.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::Disconnect()
{
if (m_state == ServerConnected)
{
DisconnectNamedPipe(m_outboundPipe);
DisconnectNamedPipe(m_inboundPipe);
CloseHandle(m_outboundPipe);
m_outboundPipe = INVALID_HANDLE_VALUE;
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
m_state = NotInitialized;
return true;
}
else if (m_state == ClientConnected)
{
CloseHandle(m_outboundPipe);
m_outboundPipe = INVALID_HANDLE_VALUE;
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
m_state = NotInitialized;
return true;
}
else
{
// nothign to do
return true;
}
}
#define PIPE_NAME_FORMAT_STR L"\\\\.\\pipe\\clr-debug-pipe-%d-%s"
// Connects to a one sided pipe previously created by CreateOneWayPipe.
// In order to successfully connect id and inbound flag should be the same.
HANDLE TwoWayPipe::OpenOneWayPipe(DWORD id, bool inbound)
{
WCHAR fullName[MAX_PATH];
// "in" and "out" are deliberately switched because we're opening a client side connection
int chars = swprintf_s(fullName, MAX_PATH, PIPE_NAME_FORMAT_STR, id, inbound ? L"out" : L"in");
_ASSERTE(chars > 0);
HANDLE handle = CreateFileW(
fullName,
inbound ? GENERIC_READ : GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
return handle;
}
// Creates a one way pipe, id and inboud flag are used for naming.
// Created pipe is supposed to be connected to by OpenOneWayPipe.
HANDLE TwoWayPipe::CreateOneWayPipe(DWORD id, bool inbound)
{
WCHAR fullName[MAX_PATH];
int chars = swprintf_s(fullName, MAX_PATH, PIPE_NAME_FORMAT_STR, id, inbound ? L"in" : L"out");
_ASSERTE(chars > 0);
HANDLE handle = CreateNamedPipeW(fullName,
(inbound ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND) | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
1, // max number of instances
4000, //in buffer size
4000, //out buffer size
0, // default timeout
NULL); // default security
return handle;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <windows.h>
#include <stdio.h>
#include <wchar.h>
#include <assert.h>
#include "twowaypipe.h"
#define _ASSERTE assert
// This file contains implementation of a simple IPC mechanism - bidirectional named pipe.
// It is implemented on top of two one-directional names pipes (fifos on UNIX)
// Creates a server side of the pipe.
// Id is used to create pipes names and uniquely identify the pipe on the machine.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::CreateServer(const ProcessDescriptor& pd)
{
_ASSERTE(m_state == NotInitialized);
if (m_state != NotInitialized)
return false;
m_inboundPipe = CreateOneWayPipe(pd.m_Pid, true);
if (m_inboundPipe == INVALID_HANDLE_VALUE)
{
return false;
}
m_outboundPipe = CreateOneWayPipe(pd.m_Pid, false);
if (m_outboundPipe == INVALID_HANDLE_VALUE)
{
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
return false;
}
m_state = Created;
return true;
}
// Connects to a previously opened server side of the pipe.
// Id is used to locate the pipe on the machine.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::Connect(const ProcessDescriptor& pd)
{
_ASSERTE(m_state == NotInitialized);
if (m_state != NotInitialized)
return false;
m_inboundPipe = OpenOneWayPipe(pd.m_Pid, true);
if (m_inboundPipe == INVALID_HANDLE_VALUE)
{
return false;
}
m_outboundPipe = OpenOneWayPipe(pd.m_Pid, false);
if (m_outboundPipe == INVALID_HANDLE_VALUE)
{
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
return false;
}
m_state = ClientConnected;
return true;
}
// Waits for incoming client connections, assumes GetState() == Created
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::WaitForConnection()
{
_ASSERTE(m_state == Created);
if (m_state != Created)
return false;
if (!ConnectNamedPipe(m_inboundPipe, NULL))
{
auto error = GetLastError();
if (error != ERROR_PIPE_CONNECTED)
return false;
}
if (!ConnectNamedPipe(m_outboundPipe, NULL))
{
auto error = GetLastError();
if (error != ERROR_PIPE_CONNECTED)
return false;
}
m_state = ServerConnected;
return true;
}
// Reads data from pipe. Returns number of bytes read or a negative number in case of an error.
// use GetLastError() for more details
int TwoWayPipe::Read(void *buffer, DWORD bufferSize)
{
_ASSERTE(m_state == ServerConnected || m_state == ClientConnected);
DWORD bytesRead;
BOOL ok = ReadFile(m_inboundPipe, buffer, bufferSize, &bytesRead, NULL);
if (ok)
{
return (int)bytesRead;
}
else
{
return -1;
}
}
// Writes data to pipe. Returns number of bytes written or a negative number in case of an error.
// use GetLastError() for more details
int TwoWayPipe::Write(const void *data, DWORD dataSize)
{
_ASSERTE(m_state == ServerConnected || m_state == ClientConnected);
DWORD bytesWritten;
BOOL ok = WriteFile(m_outboundPipe, data, dataSize, &bytesWritten, NULL);
if (ok)
{
FlushFileBuffers(m_outboundPipe);
return (int)bytesWritten;
}
else
{
return -1;
}
}
// Disconnect server or client side of the pipe.
// true - success, false - failure (use GetLastError() for more details)
bool TwoWayPipe::Disconnect()
{
if (m_state == ServerConnected)
{
DisconnectNamedPipe(m_outboundPipe);
DisconnectNamedPipe(m_inboundPipe);
CloseHandle(m_outboundPipe);
m_outboundPipe = INVALID_HANDLE_VALUE;
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
m_state = NotInitialized;
return true;
}
else if (m_state == ClientConnected)
{
CloseHandle(m_outboundPipe);
m_outboundPipe = INVALID_HANDLE_VALUE;
CloseHandle(m_inboundPipe);
m_inboundPipe = INVALID_HANDLE_VALUE;
m_state = NotInitialized;
return true;
}
else
{
// nothign to do
return true;
}
}
#define PIPE_NAME_FORMAT_STR L"\\\\.\\pipe\\clr-debug-pipe-%d-%s"
// Connects to a one sided pipe previously created by CreateOneWayPipe.
// In order to successfully connect id and inbound flag should be the same.
HANDLE TwoWayPipe::OpenOneWayPipe(DWORD id, bool inbound)
{
WCHAR fullName[MAX_PATH];
// "in" and "out" are deliberately switched because we're opening a client side connection
int chars = swprintf_s(fullName, MAX_PATH, PIPE_NAME_FORMAT_STR, id, inbound ? L"out" : L"in");
_ASSERTE(chars > 0);
HANDLE handle = CreateFileW(
fullName,
inbound ? GENERIC_READ : GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
return handle;
}
// Creates a one way pipe, id and inboud flag are used for naming.
// Created pipe is supposed to be connected to by OpenOneWayPipe.
HANDLE TwoWayPipe::CreateOneWayPipe(DWORD id, bool inbound)
{
WCHAR fullName[MAX_PATH];
int chars = swprintf_s(fullName, MAX_PATH, PIPE_NAME_FORMAT_STR, id, inbound ? L"in" : L"out");
_ASSERTE(chars > 0);
HANDLE handle = CreateNamedPipeW(fullName,
(inbound ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND) | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
1, // max number of instances
4000, //in buffer size
4000, //out buffer size
0, // default timeout
NULL); // default security
return handle;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/Interop/IJW/IjwNativeCallingManagedDll/IjwNativeCallingManagedDll.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "platformdefines.h"
#pragma managed
int ManagedCallee();
#pragma unmanaged
int NativeFunction()
{
return ManagedCallee();
}
extern "C" DLL_EXPORT int __cdecl NativeEntryPoint()
{
return NativeFunction();
}
#pragma managed
public ref class TestClass
{
private:
static int s_valueToReturn = 100;
public:
int ManagedEntryPoint()
{
return NativeFunction();
}
static void ChangeReturnedValue(int i)
{
s_valueToReturn = i;
}
static int GetReturnValue()
{
return s_valueToReturn;
}
};
int ManagedCallee()
{
return TestClass::GetReturnValue();
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "platformdefines.h"
#pragma managed
int ManagedCallee();
#pragma unmanaged
int NativeFunction()
{
return ManagedCallee();
}
extern "C" DLL_EXPORT int __cdecl NativeEntryPoint()
{
return NativeFunction();
}
#pragma managed
public ref class TestClass
{
private:
static int s_valueToReturn = 100;
public:
int ManagedEntryPoint()
{
return NativeFunction();
}
static void ChangeReturnedValue(int i)
{
s_valueToReturn = i;
}
static int GetReturnValue()
{
return s_valueToReturn;
}
};
int ManagedCallee()
{
return TestClass::GetReturnValue();
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/vm/argslot.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ============================================================================
// File: argslot.h
//
// ============================================================================
// Contains the ARG_SLOT type.
#ifndef __ARG_SLOT_H__
#define __ARG_SLOT_H__
// The ARG_SLOT must be big enough to represent all pointer and basic types (except for 80-bit fp values).
// So, it's guaranteed to be at least 64-bit.
typedef unsigned __int64 ARG_SLOT;
#define SIZEOF_ARG_SLOT 8
#if BIGENDIAN
// Returns the address of the payload inside the argslot
inline BYTE* ArgSlotEndianessFixup(ARG_SLOT* pArg, UINT cbSize) {
LIMITED_METHOD_CONTRACT;
BYTE* pBuf = (BYTE*)pArg;
switch (cbSize) {
case 1:
pBuf += 7;
break;
case 2:
pBuf += 6;
break;
case 4:
pBuf += 4;
break;
}
return pBuf;
}
#else
#define ArgSlotEndianessFixup(pArg, cbSize) ((BYTE *)(pArg))
#endif
#endif // __ARG_SLOT_H__
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ============================================================================
// File: argslot.h
//
// ============================================================================
// Contains the ARG_SLOT type.
#ifndef __ARG_SLOT_H__
#define __ARG_SLOT_H__
// The ARG_SLOT must be big enough to represent all pointer and basic types (except for 80-bit fp values).
// So, it's guaranteed to be at least 64-bit.
typedef unsigned __int64 ARG_SLOT;
#define SIZEOF_ARG_SLOT 8
#if BIGENDIAN
// Returns the address of the payload inside the argslot
inline BYTE* ArgSlotEndianessFixup(ARG_SLOT* pArg, UINT cbSize) {
LIMITED_METHOD_CONTRACT;
BYTE* pBuf = (BYTE*)pArg;
switch (cbSize) {
case 1:
pBuf += 7;
break;
case 2:
pBuf += 6;
break;
case 4:
pBuf += 4;
break;
}
return pBuf;
}
#else
#define ArgSlotEndianessFixup(pArg, cbSize) ((BYTE *)(pArg))
#endif
#endif // __ARG_SLOT_H__
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/c_runtime/wcstoul/test5/test5.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test5.c
**
** Purpose: Test #5 for the wcstoul function
**
**
**==========================================================================*/
#include <palsuite.h>
/*
* Notes: wcstoul should depend on the current locale's LC_NUMERIC category,
* this is not currently tested.
*/
PALTEST(c_runtime_wcstoul_test5_paltest_wcstoul_test5, "c_runtime/wcstoul/test5/paltest_wcstoul_test5")
{
WCHAR overstr[] = {'4','2','9','4','9','6','7','2','9','6',0};
WCHAR understr[] = {'-','1',0};
WCHAR *end;
ULONG l;
if (0 != PAL_Initialize(argc, argv))
{
return FAIL;
}
errno = 0;
l = wcstoul(overstr, &end, 10);
if (l != _UI32_MAX)
{
Fail("ERROR: Expected wcstoul to return %u, got %u\n", _UI32_MAX, l);
}
if (end != overstr + 10)
{
Fail("ERROR: Expected wcstoul to give an end value of %p, got %p\n",
overstr + 10, end);
}
if (errno != ERANGE)
{
Fail("ERROR: wcstoul did not set errno to ERANGE (%d)\n", errno);
}
errno = 0;
l = wcstoul(understr, &end, 10);
if (l != _UI32_MAX)
{
Fail("ERROR: Expected wcstoul to return %u, got %u\n", _UI32_MAX, l);
}
if (end != understr + 2)
{
Fail("ERROR: Expected wcstoul to give an end value of %p, got %p\n",
understr + 2, end);
}
if (errno != 0)
{
Fail("ERROR: wcstoul set errno to non-zero (%d)\n", errno);
}
PAL_Terminate();
return PASS;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test5.c
**
** Purpose: Test #5 for the wcstoul function
**
**
**==========================================================================*/
#include <palsuite.h>
/*
* Notes: wcstoul should depend on the current locale's LC_NUMERIC category,
* this is not currently tested.
*/
PALTEST(c_runtime_wcstoul_test5_paltest_wcstoul_test5, "c_runtime/wcstoul/test5/paltest_wcstoul_test5")
{
WCHAR overstr[] = {'4','2','9','4','9','6','7','2','9','6',0};
WCHAR understr[] = {'-','1',0};
WCHAR *end;
ULONG l;
if (0 != PAL_Initialize(argc, argv))
{
return FAIL;
}
errno = 0;
l = wcstoul(overstr, &end, 10);
if (l != _UI32_MAX)
{
Fail("ERROR: Expected wcstoul to return %u, got %u\n", _UI32_MAX, l);
}
if (end != overstr + 10)
{
Fail("ERROR: Expected wcstoul to give an end value of %p, got %p\n",
overstr + 10, end);
}
if (errno != ERANGE)
{
Fail("ERROR: wcstoul did not set errno to ERANGE (%d)\n", errno);
}
errno = 0;
l = wcstoul(understr, &end, 10);
if (l != _UI32_MAX)
{
Fail("ERROR: Expected wcstoul to return %u, got %u\n", _UI32_MAX, l);
}
if (end != understr + 2)
{
Fail("ERROR: Expected wcstoul to give an end value of %p, got %p\n",
understr + 2, end);
}
if (errno != 0)
{
Fail("ERROR: wcstoul set errno to non-zero (%d)\n", errno);
}
PAL_Terminate();
return PASS;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/threading/DisableThreadLibraryCalls/test1/testlib.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=====================================================================
**
** Source: testlib.c
**
** Purpose: Simple library that counts thread attach/detach notifications
**
**
**===================================================================*/
#include <palsuite.h>
static int Count;
BOOL PALAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
Count = 0;
}
else if (fdwReason == DLL_THREAD_ATTACH ||
fdwReason == DLL_THREAD_DETACH)
{
Count++;
}
return TRUE;
}
#ifdef WIN32
BOOL PALAPI _DllMainCRTStartup(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
return DllMain(hinstDLL, fdwReason, lpvReserved);
}
#endif
#ifdef WIN32
__declspec(dllexport)
#endif
int PALAPI GetCallCount()
{
return Count;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=====================================================================
**
** Source: testlib.c
**
** Purpose: Simple library that counts thread attach/detach notifications
**
**
**===================================================================*/
#include <palsuite.h>
static int Count;
BOOL PALAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
Count = 0;
}
else if (fdwReason == DLL_THREAD_ATTACH ||
fdwReason == DLL_THREAD_DETACH)
{
Count++;
}
return TRUE;
}
#ifdef WIN32
BOOL PALAPI _DllMainCRTStartup(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
return DllMain(hinstDLL, fdwReason, lpvReserved);
}
#endif
#ifdef WIN32
__declspec(dllexport)
#endif
int PALAPI GetCallCount()
{
return Count;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/native/corehost/test/nativehost/resolve_component_dependencies_test.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <pal.h>
namespace resolve_component_dependencies_test
{
bool run_app_and_resolve(
const pal::string_t& hostfxr_path,
const pal::string_t& app_path,
const pal::string_t& component_path,
pal::stringstream_t& test_output);
bool run_app_and_resolve_multithreaded(
const pal::string_t& hostfxr_path,
const pal::string_t& app_path,
const pal::string_t& component_path_a,
const pal::string_t& component_path_b,
pal::stringstream_t& test_output);
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <pal.h>
namespace resolve_component_dependencies_test
{
bool run_app_and_resolve(
const pal::string_t& hostfxr_path,
const pal::string_t& app_path,
const pal::string_t& component_path,
pal::stringstream_t& test_output);
bool run_app_and_resolve_multithreaded(
const pal::string_t& hostfxr_path,
const pal::string_t& app_path,
const pal::string_t& component_path_a,
const pal::string_t& component_path_b,
pal::stringstream_t& test_output);
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=====================================================================
**
** Source: GetFileSizeEx.c (test 1)
**
** Purpose: Tests the PAL implementation of the GetFileSizeEx function.
**
**
**===================================================================*/
#include <palsuite.h>
void CleanUp_GetFileSizeEx_test1(HANDLE hFile)
{
if (CloseHandle(hFile) != TRUE)
{
Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n"
" Error is %d\n",
szTextFile, GetLastError());
}
if (!DeleteFileA(szTextFile))
{
Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n"
" Error is %d\n",
szTextFile, GetLastError());
}
}
void CheckFileSize_GetFileSizeEx_test1(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder)
{
DWORD dwRc = 0;
DWORD dwError = 0;
LARGE_INTEGER qwFileSize;
dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN);
if (dwRc == INVALID_SET_FILE_POINTER)
{
Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
else
{
if (!SetEndOfFile(hFile))
{
dwError = GetLastError();
CleanUp_GetFileSizeEx_test1(hFile);
if (dwError == 112)
{
Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of "
"disk space\n");
}
else
{
Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed "
"with error %ld\n", dwError);
}
}
else
{
GetFileSizeEx(hFile, &qwFileSize);
if ((qwFileSize.u.LowPart != dwOffset) ||
(qwFileSize.u.HighPart != dwHighOrder))
{
CleanUp_GetFileSizeEx_test1(hFile);
Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n");
}
}
}
}
PALTEST(file_io_GetFileSizeEx_test1_paltest_getfilesizeex_test1, "file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1")
{
HANDLE hFile = NULL;
BOOL bRc = FALSE;
DWORD lpNumberOfBytesWritten;
LARGE_INTEGER qwFileSize;
LARGE_INTEGER qwFileSize2;
char * data = "1234567890";
qwFileSize.QuadPart = 0;
qwFileSize2.QuadPart = 0;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/* test on a null file */
bRc = GetFileSizeEx(NULL, &qwFileSize);
if (bRc != FALSE)
{
Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
"a null handle.\n");
}
/* test on an invalid file */
bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize);
if (bRc != FALSE)
{
Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
"an invalid handle.\n");
}
/* create a test file */
hFile = CreateFile(szTextFile,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n",
szTextFile);
}
/* give the file a size */
CheckFileSize_GetFileSizeEx_test1(hFile, 256, 0);
/* make the file large using the high order option */
CheckFileSize_GetFileSizeEx_test1(hFile, 256, 1);
/* set the file size to zero */
CheckFileSize_GetFileSizeEx_test1(hFile, 0, 0);
/* test if file size changes by writing to it. */
/* get file size */
GetFileSizeEx(hFile, &qwFileSize);
/* test writing to the file */
if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0)
{
Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
/* make sure the buffer flushed.*/
if(FlushFileBuffers(hFile)==0)
{
Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
/* get file size after writing some chars */
GetFileSizeEx(hFile, &qwFileSize2);
if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data))
{
CleanUp_GetFileSizeEx_test1(hFile);
Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n"
"writing %d chars\n", strlen(data));
}
CleanUp_GetFileSizeEx_test1(hFile);
PAL_Terminate();
return PASS;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=====================================================================
**
** Source: GetFileSizeEx.c (test 1)
**
** Purpose: Tests the PAL implementation of the GetFileSizeEx function.
**
**
**===================================================================*/
#include <palsuite.h>
void CleanUp_GetFileSizeEx_test1(HANDLE hFile)
{
if (CloseHandle(hFile) != TRUE)
{
Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n"
" Error is %d\n",
szTextFile, GetLastError());
}
if (!DeleteFileA(szTextFile))
{
Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n"
" Error is %d\n",
szTextFile, GetLastError());
}
}
void CheckFileSize_GetFileSizeEx_test1(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder)
{
DWORD dwRc = 0;
DWORD dwError = 0;
LARGE_INTEGER qwFileSize;
dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN);
if (dwRc == INVALID_SET_FILE_POINTER)
{
Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
else
{
if (!SetEndOfFile(hFile))
{
dwError = GetLastError();
CleanUp_GetFileSizeEx_test1(hFile);
if (dwError == 112)
{
Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of "
"disk space\n");
}
else
{
Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed "
"with error %ld\n", dwError);
}
}
else
{
GetFileSizeEx(hFile, &qwFileSize);
if ((qwFileSize.u.LowPart != dwOffset) ||
(qwFileSize.u.HighPart != dwHighOrder))
{
CleanUp_GetFileSizeEx_test1(hFile);
Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n");
}
}
}
}
PALTEST(file_io_GetFileSizeEx_test1_paltest_getfilesizeex_test1, "file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1")
{
HANDLE hFile = NULL;
BOOL bRc = FALSE;
DWORD lpNumberOfBytesWritten;
LARGE_INTEGER qwFileSize;
LARGE_INTEGER qwFileSize2;
char * data = "1234567890";
qwFileSize.QuadPart = 0;
qwFileSize2.QuadPart = 0;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/* test on a null file */
bRc = GetFileSizeEx(NULL, &qwFileSize);
if (bRc != FALSE)
{
Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
"a null handle.\n");
}
/* test on an invalid file */
bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize);
if (bRc != FALSE)
{
Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
"an invalid handle.\n");
}
/* create a test file */
hFile = CreateFile(szTextFile,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(hFile == INVALID_HANDLE_VALUE)
{
Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n",
szTextFile);
}
/* give the file a size */
CheckFileSize_GetFileSizeEx_test1(hFile, 256, 0);
/* make the file large using the high order option */
CheckFileSize_GetFileSizeEx_test1(hFile, 256, 1);
/* set the file size to zero */
CheckFileSize_GetFileSizeEx_test1(hFile, 0, 0);
/* test if file size changes by writing to it. */
/* get file size */
GetFileSizeEx(hFile, &qwFileSize);
/* test writing to the file */
if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0)
{
Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
/* make sure the buffer flushed.*/
if(FlushFileBuffers(hFile)==0)
{
Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n",
GetLastError());
CleanUp_GetFileSizeEx_test1(hFile);
Fail("");
}
/* get file size after writing some chars */
GetFileSizeEx(hFile, &qwFileSize2);
if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data))
{
CleanUp_GetFileSizeEx_test1(hFile);
Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n"
"writing %d chars\n", strlen(data));
}
CleanUp_GetFileSizeEx_test1(hFile);
PAL_Terminate();
return PASS;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/inc/llvm/Dwarf.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2015 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
// SOFTWARE.
//===----------------------------------------------------------------------===//
//
// \file
// \brief This file contains constants used for implementing Dwarf
// debug support.
//
// For details on the Dwarf specfication see the latest DWARF Debugging
// Information Format standard document on http://www.dwarfstd.org. This
// file often includes support for non-released standard features.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_DWARF_H
#define LLVM_SUPPORT_DWARF_H
//===----------------------------------------------------------------------===//
// Dwarf constants as gleaned from the DWARF Debugging Information Format V.4
// reference manual http://www.dwarfstd.org/.
//
// Do not mix the following two enumerations sets. DW_TAG_invalid changes the
// enumeration base type.
enum LLVMConstants : uint32_t {
// LLVM mock tags (see also llvm/Support/Dwarf.def).
DW_TAG_invalid = ~0U, // Tag for invalid results.
DW_VIRTUALITY_invalid = ~0U, // Virtuality for invalid results.
DW_MACINFO_invalid = ~0U, // Macinfo type for invalid results.
// Other constants.
DWARF_VERSION = 4, // Default dwarf version we output.
DW_PUBTYPES_VERSION = 2, // Section version number for .debug_pubtypes.
DW_PUBNAMES_VERSION = 2, // Section version number for .debug_pubnames.
DW_ARANGES_VERSION = 2 // Section version number for .debug_aranges.
};
// Special ID values that distinguish a CIE from a FDE in DWARF CFI.
// Not inside an enum because a 64-bit value is needed.
const uint32_t DW_CIE_ID = UINT32_MAX;
const uint64_t DW64_CIE_ID = UINT64_MAX;
enum Tag : uint16_t {
#define HANDLE_DW_TAG(ID, NAME) DW_TAG_##NAME = ID,
#include "Dwarf.def"
DW_TAG_lo_user = 0x4080,
DW_TAG_hi_user = 0xffff,
DW_TAG_user_base = 0x1000 // Recommended base for user tags.
};
inline bool isType(Tag T) {
switch (T) {
case DW_TAG_array_type:
case DW_TAG_class_type:
case DW_TAG_interface_type:
case DW_TAG_enumeration_type:
case DW_TAG_pointer_type:
case DW_TAG_reference_type:
case DW_TAG_rvalue_reference_type:
case DW_TAG_string_type:
case DW_TAG_structure_type:
case DW_TAG_subroutine_type:
case DW_TAG_union_type:
case DW_TAG_ptr_to_member_type:
case DW_TAG_set_type:
case DW_TAG_subrange_type:
case DW_TAG_base_type:
case DW_TAG_const_type:
case DW_TAG_file_type:
case DW_TAG_packed_type:
case DW_TAG_volatile_type:
case DW_TAG_typedef:
return true;
default:
return false;
}
}
enum Attribute : uint16_t {
// Attributes
DW_AT_sibling = 0x01,
DW_AT_location = 0x02,
DW_AT_name = 0x03,
DW_AT_ordering = 0x09,
DW_AT_byte_size = 0x0b,
DW_AT_bit_offset = 0x0c,
DW_AT_bit_size = 0x0d,
DW_AT_stmt_list = 0x10,
DW_AT_low_pc = 0x11,
DW_AT_high_pc = 0x12,
DW_AT_language = 0x13,
DW_AT_discr = 0x15,
DW_AT_discr_value = 0x16,
DW_AT_visibility = 0x17,
DW_AT_import = 0x18,
DW_AT_string_length = 0x19,
DW_AT_common_reference = 0x1a,
DW_AT_comp_dir = 0x1b,
DW_AT_const_value = 0x1c,
DW_AT_containing_type = 0x1d,
DW_AT_default_value = 0x1e,
DW_AT_inline = 0x20,
DW_AT_is_optional = 0x21,
DW_AT_lower_bound = 0x22,
DW_AT_producer = 0x25,
DW_AT_prototyped = 0x27,
DW_AT_return_addr = 0x2a,
DW_AT_start_scope = 0x2c,
DW_AT_bit_stride = 0x2e,
DW_AT_upper_bound = 0x2f,
DW_AT_abstract_origin = 0x31,
DW_AT_accessibility = 0x32,
DW_AT_address_class = 0x33,
DW_AT_artificial = 0x34,
DW_AT_base_types = 0x35,
DW_AT_calling_convention = 0x36,
DW_AT_count = 0x37,
DW_AT_data_member_location = 0x38,
DW_AT_decl_column = 0x39,
DW_AT_decl_file = 0x3a,
DW_AT_decl_line = 0x3b,
DW_AT_declaration = 0x3c,
DW_AT_discr_list = 0x3d,
DW_AT_encoding = 0x3e,
DW_AT_external = 0x3f,
DW_AT_frame_base = 0x40,
DW_AT_friend = 0x41,
DW_AT_identifier_case = 0x42,
DW_AT_macro_info = 0x43,
DW_AT_namelist_item = 0x44,
DW_AT_priority = 0x45,
DW_AT_segment = 0x46,
DW_AT_specification = 0x47,
DW_AT_static_link = 0x48,
DW_AT_type = 0x49,
DW_AT_use_location = 0x4a,
DW_AT_variable_parameter = 0x4b,
DW_AT_virtuality = 0x4c,
DW_AT_vtable_elem_location = 0x4d,
DW_AT_allocated = 0x4e,
DW_AT_associated = 0x4f,
DW_AT_data_location = 0x50,
DW_AT_byte_stride = 0x51,
DW_AT_entry_pc = 0x52,
DW_AT_use_UTF8 = 0x53,
DW_AT_extension = 0x54,
DW_AT_ranges = 0x55,
DW_AT_trampoline = 0x56,
DW_AT_call_column = 0x57,
DW_AT_call_file = 0x58,
DW_AT_call_line = 0x59,
DW_AT_description = 0x5a,
DW_AT_binary_scale = 0x5b,
DW_AT_decimal_scale = 0x5c,
DW_AT_small = 0x5d,
DW_AT_decimal_sign = 0x5e,
DW_AT_digit_count = 0x5f,
DW_AT_picture_string = 0x60,
DW_AT_mutable = 0x61,
DW_AT_threads_scaled = 0x62,
DW_AT_explicit = 0x63,
DW_AT_object_pointer = 0x64,
DW_AT_endianity = 0x65,
DW_AT_elemental = 0x66,
DW_AT_pure = 0x67,
DW_AT_recursive = 0x68,
DW_AT_signature = 0x69,
DW_AT_main_subprogram = 0x6a,
DW_AT_data_bit_offset = 0x6b,
DW_AT_const_expr = 0x6c,
DW_AT_enum_class = 0x6d,
DW_AT_linkage_name = 0x6e,
// New in DWARF 5:
DW_AT_string_length_bit_size = 0x6f,
DW_AT_string_length_byte_size = 0x70,
DW_AT_rank = 0x71,
DW_AT_str_offsets_base = 0x72,
DW_AT_addr_base = 0x73,
DW_AT_ranges_base = 0x74,
DW_AT_dwo_id = 0x75,
DW_AT_dwo_name = 0x76,
DW_AT_reference = 0x77,
DW_AT_rvalue_reference = 0x78,
DW_AT_macros = 0x79,
DW_AT_lo_user = 0x2000,
DW_AT_hi_user = 0x3fff,
DW_AT_MIPS_loop_begin = 0x2002,
DW_AT_MIPS_tail_loop_begin = 0x2003,
DW_AT_MIPS_epilog_begin = 0x2004,
DW_AT_MIPS_loop_unroll_factor = 0x2005,
DW_AT_MIPS_software_pipeline_depth = 0x2006,
DW_AT_MIPS_linkage_name = 0x2007,
DW_AT_MIPS_stride = 0x2008,
DW_AT_MIPS_abstract_name = 0x2009,
DW_AT_MIPS_clone_origin = 0x200a,
DW_AT_MIPS_has_inlines = 0x200b,
DW_AT_MIPS_stride_byte = 0x200c,
DW_AT_MIPS_stride_elem = 0x200d,
DW_AT_MIPS_ptr_dopetype = 0x200e,
DW_AT_MIPS_allocatable_dopetype = 0x200f,
DW_AT_MIPS_assumed_shape_dopetype = 0x2010,
// This one appears to have only been implemented by Open64 for
// fortran and may conflict with other extensions.
DW_AT_MIPS_assumed_size = 0x2011,
// GNU extensions
DW_AT_sf_names = 0x2101,
DW_AT_src_info = 0x2102,
DW_AT_mac_info = 0x2103,
DW_AT_src_coords = 0x2104,
DW_AT_body_begin = 0x2105,
DW_AT_body_end = 0x2106,
DW_AT_GNU_vector = 0x2107,
DW_AT_GNU_template_name = 0x2110,
DW_AT_GNU_odr_signature = 0x210f,
DW_AT_GNU_macros = 0x2119,
// Extensions for Fission proposal.
DW_AT_GNU_dwo_name = 0x2130,
DW_AT_GNU_dwo_id = 0x2131,
DW_AT_GNU_ranges_base = 0x2132,
DW_AT_GNU_addr_base = 0x2133,
DW_AT_GNU_pubnames = 0x2134,
DW_AT_GNU_pubtypes = 0x2135,
DW_AT_GNU_discriminator = 0x2136,
// Borland extensions.
DW_AT_BORLAND_property_read = 0x3b11,
DW_AT_BORLAND_property_write = 0x3b12,
DW_AT_BORLAND_property_implements = 0x3b13,
DW_AT_BORLAND_property_index = 0x3b14,
DW_AT_BORLAND_property_default = 0x3b15,
DW_AT_BORLAND_Delphi_unit = 0x3b20,
DW_AT_BORLAND_Delphi_class = 0x3b21,
DW_AT_BORLAND_Delphi_record = 0x3b22,
DW_AT_BORLAND_Delphi_metaclass = 0x3b23,
DW_AT_BORLAND_Delphi_constructor = 0x3b24,
DW_AT_BORLAND_Delphi_destructor = 0x3b25,
DW_AT_BORLAND_Delphi_anonymous_method = 0x3b26,
DW_AT_BORLAND_Delphi_interface = 0x3b27,
DW_AT_BORLAND_Delphi_ABI = 0x3b28,
DW_AT_BORLAND_Delphi_return = 0x3b29,
DW_AT_BORLAND_Delphi_frameptr = 0x3b30,
DW_AT_BORLAND_closure = 0x3b31,
// LLVM project extensions.
DW_AT_LLVM_include_path = 0x3e00,
DW_AT_LLVM_config_macros = 0x3e01,
DW_AT_LLVM_isysroot = 0x3e02,
// Apple extensions.
DW_AT_APPLE_optimized = 0x3fe1,
DW_AT_APPLE_flags = 0x3fe2,
DW_AT_APPLE_isa = 0x3fe3,
DW_AT_APPLE_block = 0x3fe4,
DW_AT_APPLE_major_runtime_vers = 0x3fe5,
DW_AT_APPLE_runtime_class = 0x3fe6,
DW_AT_APPLE_omit_frame_ptr = 0x3fe7,
DW_AT_APPLE_property_name = 0x3fe8,
DW_AT_APPLE_property_getter = 0x3fe9,
DW_AT_APPLE_property_setter = 0x3fea,
DW_AT_APPLE_property_attribute = 0x3feb,
DW_AT_APPLE_objc_complete_type = 0x3fec,
DW_AT_APPLE_property = 0x3fed
};
enum Form : uint16_t {
// Attribute form encodings
DW_FORM_addr = 0x01,
DW_FORM_block2 = 0x03,
DW_FORM_block4 = 0x04,
DW_FORM_data2 = 0x05,
DW_FORM_data4 = 0x06,
DW_FORM_data8 = 0x07,
DW_FORM_string = 0x08,
DW_FORM_block = 0x09,
DW_FORM_block1 = 0x0a,
DW_FORM_data1 = 0x0b,
DW_FORM_flag = 0x0c,
DW_FORM_sdata = 0x0d,
DW_FORM_strp = 0x0e,
DW_FORM_udata = 0x0f,
DW_FORM_ref_addr = 0x10,
DW_FORM_ref1 = 0x11,
DW_FORM_ref2 = 0x12,
DW_FORM_ref4 = 0x13,
DW_FORM_ref8 = 0x14,
DW_FORM_ref_udata = 0x15,
DW_FORM_indirect = 0x16,
DW_FORM_sec_offset = 0x17,
DW_FORM_exprloc = 0x18,
DW_FORM_flag_present = 0x19,
DW_FORM_ref_sig8 = 0x20,
// Extensions for Fission proposal
DW_FORM_GNU_addr_index = 0x1f01,
DW_FORM_GNU_str_index = 0x1f02,
// Alternate debug sections proposal (output of "dwz" tool).
DW_FORM_GNU_ref_alt = 0x1f20,
DW_FORM_GNU_strp_alt = 0x1f21
};
enum LocationAtom {
#define HANDLE_DW_OP(ID, NAME) DW_OP_##NAME = ID,
#include "Dwarf.def"
DW_OP_lo_user = 0xe0,
DW_OP_hi_user = 0xff
};
enum TypeKind {
#define HANDLE_DW_ATE(ID, NAME) DW_ATE_##NAME = ID,
#include "Dwarf.def"
DW_ATE_lo_user = 0x80,
DW_ATE_hi_user = 0xff
};
enum DecimalSignEncoding {
// Decimal sign attribute values
DW_DS_unsigned = 0x01,
DW_DS_leading_overpunch = 0x02,
DW_DS_trailing_overpunch = 0x03,
DW_DS_leading_separate = 0x04,
DW_DS_trailing_separate = 0x05
};
enum EndianityEncoding {
// Endianity attribute values
DW_END_default = 0x00,
DW_END_big = 0x01,
DW_END_little = 0x02,
DW_END_lo_user = 0x40,
DW_END_hi_user = 0xff
};
enum AccessAttribute {
// Accessibility codes
DW_ACCESS_public = 0x01,
DW_ACCESS_protected = 0x02,
DW_ACCESS_private = 0x03
};
enum VisibilityAttribute {
// Visibility codes
DW_VIS_local = 0x01,
DW_VIS_exported = 0x02,
DW_VIS_qualified = 0x03
};
enum VirtualityAttribute {
#define HANDLE_DW_VIRTUALITY(ID, NAME) DW_VIRTUALITY_##NAME = ID,
#include "Dwarf.def"
DW_VIRTUALITY_max = 0x02
};
enum SourceLanguage {
#define HANDLE_DW_LANG(ID, NAME) DW_LANG_##NAME = ID,
#include "Dwarf.def"
DW_LANG_lo_user = 0x8000,
DW_LANG_hi_user = 0xffff
};
enum CaseSensitivity {
// Identifier case codes
DW_ID_case_sensitive = 0x00,
DW_ID_up_case = 0x01,
DW_ID_down_case = 0x02,
DW_ID_case_insensitive = 0x03
};
enum CallingConvention {
// Calling convention codes
DW_CC_normal = 0x01,
DW_CC_program = 0x02,
DW_CC_nocall = 0x03,
DW_CC_lo_user = 0x40,
DW_CC_GNU_borland_fastcall_i386 = 0x41,
DW_CC_BORLAND_safecall = 0xb0,
DW_CC_BORLAND_stdcall = 0xb1,
DW_CC_BORLAND_pascal = 0xb2,
DW_CC_BORLAND_msfastcall = 0xb3,
DW_CC_BORLAND_msreturn = 0xb4,
DW_CC_BORLAND_thiscall = 0xb5,
DW_CC_BORLAND_fastcall = 0xb6,
DW_CC_hi_user = 0xff
};
enum InlineAttribute {
// Inline codes
DW_INL_not_inlined = 0x00,
DW_INL_inlined = 0x01,
DW_INL_declared_not_inlined = 0x02,
DW_INL_declared_inlined = 0x03
};
enum ArrayDimensionOrdering {
// Array ordering
DW_ORD_row_major = 0x00,
DW_ORD_col_major = 0x01
};
enum DiscriminantList {
// Discriminant descriptor values
DW_DSC_label = 0x00,
DW_DSC_range = 0x01
};
enum LineNumberOps {
// Line Number Standard Opcode Encodings
DW_LNS_extended_op = 0x00,
DW_LNS_copy = 0x01,
DW_LNS_advance_pc = 0x02,
DW_LNS_advance_line = 0x03,
DW_LNS_set_file = 0x04,
DW_LNS_set_column = 0x05,
DW_LNS_negate_stmt = 0x06,
DW_LNS_set_basic_block = 0x07,
DW_LNS_const_add_pc = 0x08,
DW_LNS_fixed_advance_pc = 0x09,
DW_LNS_set_prologue_end = 0x0a,
DW_LNS_set_epilogue_begin = 0x0b,
DW_LNS_set_isa = 0x0c
};
enum LineNumberExtendedOps {
// Line Number Extended Opcode Encodings
DW_LNE_end_sequence = 0x01,
DW_LNE_set_address = 0x02,
DW_LNE_define_file = 0x03,
DW_LNE_set_discriminator = 0x04,
DW_LNE_lo_user = 0x80,
DW_LNE_hi_user = 0xff
};
enum MacinfoRecordType {
// Macinfo Type Encodings
DW_MACINFO_define = 0x01,
DW_MACINFO_undef = 0x02,
DW_MACINFO_start_file = 0x03,
DW_MACINFO_end_file = 0x04,
DW_MACINFO_vendor_ext = 0xff
};
enum MacroEntryType {
// Macro Information Entry Type Encodings
DW_MACRO_define = 0x01,
DW_MACRO_undef = 0x02,
DW_MACRO_start_file = 0x03,
DW_MACRO_end_file = 0x04,
DW_MACRO_define_indirect = 0x05,
DW_MACRO_undef_indirect = 0x06,
DW_MACRO_transparent_include = 0x07,
DW_MACRO_define_indirect_sup = 0x08,
DW_MACRO_undef_indirect_sup = 0x09,
DW_MACRO_transparent_include_sup = 0x0a,
DW_MACRO_define_indirectx = 0x0b,
DW_MACRO_undef_indirectx = 0x0c,
DW_MACRO_lo_user = 0xe0,
DW_MACRO_hi_user = 0xff
};
enum CallFrameInfo {
// Call frame instruction encodings
DW_CFA_extended = 0x00,
DW_CFA_nop = 0x00,
DW_CFA_advance_loc = 0x40,
DW_CFA_offset = 0x80,
DW_CFA_restore = 0xc0,
DW_CFA_set_loc = 0x01,
DW_CFA_advance_loc1 = 0x02,
DW_CFA_advance_loc2 = 0x03,
DW_CFA_advance_loc4 = 0x04,
DW_CFA_offset_extended = 0x05,
DW_CFA_restore_extended = 0x06,
DW_CFA_undefined = 0x07,
DW_CFA_same_value = 0x08,
DW_CFA_register = 0x09,
DW_CFA_remember_state = 0x0a,
DW_CFA_restore_state = 0x0b,
DW_CFA_def_cfa = 0x0c,
DW_CFA_def_cfa_register = 0x0d,
DW_CFA_def_cfa_offset = 0x0e,
DW_CFA_def_cfa_expression = 0x0f,
DW_CFA_expression = 0x10,
DW_CFA_offset_extended_sf = 0x11,
DW_CFA_def_cfa_sf = 0x12,
DW_CFA_def_cfa_offset_sf = 0x13,
DW_CFA_val_offset = 0x14,
DW_CFA_val_offset_sf = 0x15,
DW_CFA_val_expression = 0x16,
DW_CFA_MIPS_advance_loc8 = 0x1d,
DW_CFA_GNU_window_save = 0x2d,
DW_CFA_GNU_args_size = 0x2e,
DW_CFA_lo_user = 0x1c,
DW_CFA_hi_user = 0x3f
};
enum Constants {
// Children flag
DW_CHILDREN_no = 0x00,
DW_CHILDREN_yes = 0x01,
DW_EH_PE_absptr = 0x00,
DW_EH_PE_omit = 0xff,
DW_EH_PE_uleb128 = 0x01,
DW_EH_PE_udata2 = 0x02,
DW_EH_PE_udata4 = 0x03,
DW_EH_PE_udata8 = 0x04,
DW_EH_PE_sleb128 = 0x09,
DW_EH_PE_sdata2 = 0x0A,
DW_EH_PE_sdata4 = 0x0B,
DW_EH_PE_sdata8 = 0x0C,
DW_EH_PE_signed = 0x08,
DW_EH_PE_pcrel = 0x10,
DW_EH_PE_textrel = 0x20,
DW_EH_PE_datarel = 0x30,
DW_EH_PE_funcrel = 0x40,
DW_EH_PE_aligned = 0x50,
DW_EH_PE_indirect = 0x80
};
// Constants for debug_loc.dwo in the DWARF5 Split Debug Info Proposal
enum LocationListEntry : unsigned char {
DW_LLE_end_of_list_entry,
DW_LLE_base_address_selection_entry,
DW_LLE_start_end_entry,
DW_LLE_start_length_entry,
DW_LLE_offset_pair_entry
};
/// Contstants for the DW_APPLE_PROPERTY_attributes attribute.
/// Keep this list in sync with clang's DeclSpec.h ObjCPropertyAttributeKind.
enum ApplePropertyAttributes {
// Apple Objective-C Property Attributes
DW_APPLE_PROPERTY_readonly = 0x01,
DW_APPLE_PROPERTY_getter = 0x02,
DW_APPLE_PROPERTY_assign = 0x04,
DW_APPLE_PROPERTY_readwrite = 0x08,
DW_APPLE_PROPERTY_retain = 0x10,
DW_APPLE_PROPERTY_copy = 0x20,
DW_APPLE_PROPERTY_nonatomic = 0x40,
DW_APPLE_PROPERTY_setter = 0x80,
DW_APPLE_PROPERTY_atomic = 0x100,
DW_APPLE_PROPERTY_weak = 0x200,
DW_APPLE_PROPERTY_strong = 0x400,
DW_APPLE_PROPERTY_unsafe_unretained = 0x800
};
// Constants for the DWARF5 Accelerator Table Proposal
enum AcceleratorTable {
// Data layout descriptors.
DW_ATOM_null = 0u, // Marker as the end of a list of atoms.
DW_ATOM_die_offset = 1u, // DIE offset in the debug_info section.
DW_ATOM_cu_offset = 2u, // Offset of the compile unit header that contains the
// item in question.
DW_ATOM_die_tag = 3u, // A tag entry.
DW_ATOM_type_flags = 4u, // Set of flags for a type.
// DW_ATOM_type_flags values.
// Always set for C++, only set for ObjC if this is the @implementation for a
// class.
DW_FLAG_type_implementation = 2u,
// Hash functions.
// Daniel J. Bernstein hash.
DW_hash_function_djb = 0u
};
// Constants for the GNU pubnames/pubtypes extensions supporting gdb index.
enum GDBIndexEntryKind {
GIEK_NONE,
GIEK_TYPE,
GIEK_VARIABLE,
GIEK_FUNCTION,
GIEK_OTHER,
GIEK_UNUSED5,
GIEK_UNUSED6,
GIEK_UNUSED7
};
enum GDBIndexEntryLinkage {
GIEL_EXTERNAL,
GIEL_STATIC
};
/// \defgroup DwarfConstantsDumping Dwarf constants dumping functions
///
/// All these functions map their argument's value back to the
/// corresponding enumerator name or return nullptr if the value isn't
/// known.
///
/// @{
const char *TagString(unsigned Tag);
const char *ChildrenString(unsigned Children);
const char *AttributeString(unsigned Attribute);
const char *FormEncodingString(unsigned Encoding);
const char *OperationEncodingString(unsigned Encoding);
const char *AttributeEncodingString(unsigned Encoding);
const char *DecimalSignString(unsigned Sign);
const char *EndianityString(unsigned Endian);
const char *AccessibilityString(unsigned Access);
const char *VisibilityString(unsigned Visibility);
const char *VirtualityString(unsigned Virtuality);
const char *LanguageString(unsigned Language);
const char *CaseString(unsigned Case);
const char *ConventionString(unsigned Convention);
const char *InlineCodeString(unsigned Code);
const char *ArrayOrderString(unsigned Order);
const char *DiscriminantString(unsigned Discriminant);
const char *LNStandardString(unsigned Standard);
const char *LNExtendedString(unsigned Encoding);
const char *MacinfoString(unsigned Encoding);
const char *CallFrameString(unsigned Encoding);
const char *ApplePropertyString(unsigned);
const char *AtomTypeString(unsigned Atom);
const char *GDBIndexEntryKindString(GDBIndexEntryKind Kind);
const char *GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage);
/// @}
/// \brief Returns the symbolic string representing Val when used as a value
/// for attribute Attr.
const char *AttributeValueString(uint16_t Attr, unsigned Val);
/// \brief Decsribes an entry of the various gnu_pub* debug sections.
///
/// The gnu_pub* kind looks like:
///
/// 0-3 reserved
/// 4-6 symbol kind
/// 7 0 == global, 1 == static
///
/// A gdb_index descriptor includes the above kind, shifted 24 bits up with the
/// offset of the cu within the debug_info section stored in those 24 bits.
struct PubIndexEntryDescriptor {
GDBIndexEntryKind Kind;
GDBIndexEntryLinkage Linkage;
PubIndexEntryDescriptor(GDBIndexEntryKind Kind, GDBIndexEntryLinkage Linkage)
: Kind(Kind), Linkage(Linkage) {}
/* implicit */ PubIndexEntryDescriptor(GDBIndexEntryKind Kind)
: Kind(Kind), Linkage(GIEL_EXTERNAL) {}
explicit PubIndexEntryDescriptor(uint8_t Value)
: Kind(static_cast<GDBIndexEntryKind>((Value & KIND_MASK) >>
KIND_OFFSET)),
Linkage(static_cast<GDBIndexEntryLinkage>((Value & LINKAGE_MASK) >>
LINKAGE_OFFSET)) {}
uint8_t toBits() { return Kind << KIND_OFFSET | Linkage << LINKAGE_OFFSET; }
private:
enum {
KIND_OFFSET = 4,
KIND_MASK = 7 << KIND_OFFSET,
LINKAGE_OFFSET = 7,
LINKAGE_MASK = 1 << LINKAGE_OFFSET
};
};
#endif
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ==============================================================================
// LLVM Release License
// ==============================================================================
// University of Illinois/NCSA
// Open Source License
//
// Copyright (c) 2003-2015 University of Illinois at Urbana-Champaign.
// All rights reserved.
//
// Developed by:
//
// LLVM Team
//
// University of Illinois at Urbana-Champaign
//
// http://llvm.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal with
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimers in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the names of the LLVM Team, University of Illinois at
// Urbana-Champaign, nor the names of its contributors may be used to
// endorse or promote products derived from this Software without specific
// prior written permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
// SOFTWARE.
//===----------------------------------------------------------------------===//
//
// \file
// \brief This file contains constants used for implementing Dwarf
// debug support.
//
// For details on the Dwarf specfication see the latest DWARF Debugging
// Information Format standard document on http://www.dwarfstd.org. This
// file often includes support for non-released standard features.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_DWARF_H
#define LLVM_SUPPORT_DWARF_H
//===----------------------------------------------------------------------===//
// Dwarf constants as gleaned from the DWARF Debugging Information Format V.4
// reference manual http://www.dwarfstd.org/.
//
// Do not mix the following two enumerations sets. DW_TAG_invalid changes the
// enumeration base type.
enum LLVMConstants : uint32_t {
// LLVM mock tags (see also llvm/Support/Dwarf.def).
DW_TAG_invalid = ~0U, // Tag for invalid results.
DW_VIRTUALITY_invalid = ~0U, // Virtuality for invalid results.
DW_MACINFO_invalid = ~0U, // Macinfo type for invalid results.
// Other constants.
DWARF_VERSION = 4, // Default dwarf version we output.
DW_PUBTYPES_VERSION = 2, // Section version number for .debug_pubtypes.
DW_PUBNAMES_VERSION = 2, // Section version number for .debug_pubnames.
DW_ARANGES_VERSION = 2 // Section version number for .debug_aranges.
};
// Special ID values that distinguish a CIE from a FDE in DWARF CFI.
// Not inside an enum because a 64-bit value is needed.
const uint32_t DW_CIE_ID = UINT32_MAX;
const uint64_t DW64_CIE_ID = UINT64_MAX;
enum Tag : uint16_t {
#define HANDLE_DW_TAG(ID, NAME) DW_TAG_##NAME = ID,
#include "Dwarf.def"
DW_TAG_lo_user = 0x4080,
DW_TAG_hi_user = 0xffff,
DW_TAG_user_base = 0x1000 // Recommended base for user tags.
};
inline bool isType(Tag T) {
switch (T) {
case DW_TAG_array_type:
case DW_TAG_class_type:
case DW_TAG_interface_type:
case DW_TAG_enumeration_type:
case DW_TAG_pointer_type:
case DW_TAG_reference_type:
case DW_TAG_rvalue_reference_type:
case DW_TAG_string_type:
case DW_TAG_structure_type:
case DW_TAG_subroutine_type:
case DW_TAG_union_type:
case DW_TAG_ptr_to_member_type:
case DW_TAG_set_type:
case DW_TAG_subrange_type:
case DW_TAG_base_type:
case DW_TAG_const_type:
case DW_TAG_file_type:
case DW_TAG_packed_type:
case DW_TAG_volatile_type:
case DW_TAG_typedef:
return true;
default:
return false;
}
}
enum Attribute : uint16_t {
// Attributes
DW_AT_sibling = 0x01,
DW_AT_location = 0x02,
DW_AT_name = 0x03,
DW_AT_ordering = 0x09,
DW_AT_byte_size = 0x0b,
DW_AT_bit_offset = 0x0c,
DW_AT_bit_size = 0x0d,
DW_AT_stmt_list = 0x10,
DW_AT_low_pc = 0x11,
DW_AT_high_pc = 0x12,
DW_AT_language = 0x13,
DW_AT_discr = 0x15,
DW_AT_discr_value = 0x16,
DW_AT_visibility = 0x17,
DW_AT_import = 0x18,
DW_AT_string_length = 0x19,
DW_AT_common_reference = 0x1a,
DW_AT_comp_dir = 0x1b,
DW_AT_const_value = 0x1c,
DW_AT_containing_type = 0x1d,
DW_AT_default_value = 0x1e,
DW_AT_inline = 0x20,
DW_AT_is_optional = 0x21,
DW_AT_lower_bound = 0x22,
DW_AT_producer = 0x25,
DW_AT_prototyped = 0x27,
DW_AT_return_addr = 0x2a,
DW_AT_start_scope = 0x2c,
DW_AT_bit_stride = 0x2e,
DW_AT_upper_bound = 0x2f,
DW_AT_abstract_origin = 0x31,
DW_AT_accessibility = 0x32,
DW_AT_address_class = 0x33,
DW_AT_artificial = 0x34,
DW_AT_base_types = 0x35,
DW_AT_calling_convention = 0x36,
DW_AT_count = 0x37,
DW_AT_data_member_location = 0x38,
DW_AT_decl_column = 0x39,
DW_AT_decl_file = 0x3a,
DW_AT_decl_line = 0x3b,
DW_AT_declaration = 0x3c,
DW_AT_discr_list = 0x3d,
DW_AT_encoding = 0x3e,
DW_AT_external = 0x3f,
DW_AT_frame_base = 0x40,
DW_AT_friend = 0x41,
DW_AT_identifier_case = 0x42,
DW_AT_macro_info = 0x43,
DW_AT_namelist_item = 0x44,
DW_AT_priority = 0x45,
DW_AT_segment = 0x46,
DW_AT_specification = 0x47,
DW_AT_static_link = 0x48,
DW_AT_type = 0x49,
DW_AT_use_location = 0x4a,
DW_AT_variable_parameter = 0x4b,
DW_AT_virtuality = 0x4c,
DW_AT_vtable_elem_location = 0x4d,
DW_AT_allocated = 0x4e,
DW_AT_associated = 0x4f,
DW_AT_data_location = 0x50,
DW_AT_byte_stride = 0x51,
DW_AT_entry_pc = 0x52,
DW_AT_use_UTF8 = 0x53,
DW_AT_extension = 0x54,
DW_AT_ranges = 0x55,
DW_AT_trampoline = 0x56,
DW_AT_call_column = 0x57,
DW_AT_call_file = 0x58,
DW_AT_call_line = 0x59,
DW_AT_description = 0x5a,
DW_AT_binary_scale = 0x5b,
DW_AT_decimal_scale = 0x5c,
DW_AT_small = 0x5d,
DW_AT_decimal_sign = 0x5e,
DW_AT_digit_count = 0x5f,
DW_AT_picture_string = 0x60,
DW_AT_mutable = 0x61,
DW_AT_threads_scaled = 0x62,
DW_AT_explicit = 0x63,
DW_AT_object_pointer = 0x64,
DW_AT_endianity = 0x65,
DW_AT_elemental = 0x66,
DW_AT_pure = 0x67,
DW_AT_recursive = 0x68,
DW_AT_signature = 0x69,
DW_AT_main_subprogram = 0x6a,
DW_AT_data_bit_offset = 0x6b,
DW_AT_const_expr = 0x6c,
DW_AT_enum_class = 0x6d,
DW_AT_linkage_name = 0x6e,
// New in DWARF 5:
DW_AT_string_length_bit_size = 0x6f,
DW_AT_string_length_byte_size = 0x70,
DW_AT_rank = 0x71,
DW_AT_str_offsets_base = 0x72,
DW_AT_addr_base = 0x73,
DW_AT_ranges_base = 0x74,
DW_AT_dwo_id = 0x75,
DW_AT_dwo_name = 0x76,
DW_AT_reference = 0x77,
DW_AT_rvalue_reference = 0x78,
DW_AT_macros = 0x79,
DW_AT_lo_user = 0x2000,
DW_AT_hi_user = 0x3fff,
DW_AT_MIPS_loop_begin = 0x2002,
DW_AT_MIPS_tail_loop_begin = 0x2003,
DW_AT_MIPS_epilog_begin = 0x2004,
DW_AT_MIPS_loop_unroll_factor = 0x2005,
DW_AT_MIPS_software_pipeline_depth = 0x2006,
DW_AT_MIPS_linkage_name = 0x2007,
DW_AT_MIPS_stride = 0x2008,
DW_AT_MIPS_abstract_name = 0x2009,
DW_AT_MIPS_clone_origin = 0x200a,
DW_AT_MIPS_has_inlines = 0x200b,
DW_AT_MIPS_stride_byte = 0x200c,
DW_AT_MIPS_stride_elem = 0x200d,
DW_AT_MIPS_ptr_dopetype = 0x200e,
DW_AT_MIPS_allocatable_dopetype = 0x200f,
DW_AT_MIPS_assumed_shape_dopetype = 0x2010,
// This one appears to have only been implemented by Open64 for
// fortran and may conflict with other extensions.
DW_AT_MIPS_assumed_size = 0x2011,
// GNU extensions
DW_AT_sf_names = 0x2101,
DW_AT_src_info = 0x2102,
DW_AT_mac_info = 0x2103,
DW_AT_src_coords = 0x2104,
DW_AT_body_begin = 0x2105,
DW_AT_body_end = 0x2106,
DW_AT_GNU_vector = 0x2107,
DW_AT_GNU_template_name = 0x2110,
DW_AT_GNU_odr_signature = 0x210f,
DW_AT_GNU_macros = 0x2119,
// Extensions for Fission proposal.
DW_AT_GNU_dwo_name = 0x2130,
DW_AT_GNU_dwo_id = 0x2131,
DW_AT_GNU_ranges_base = 0x2132,
DW_AT_GNU_addr_base = 0x2133,
DW_AT_GNU_pubnames = 0x2134,
DW_AT_GNU_pubtypes = 0x2135,
DW_AT_GNU_discriminator = 0x2136,
// Borland extensions.
DW_AT_BORLAND_property_read = 0x3b11,
DW_AT_BORLAND_property_write = 0x3b12,
DW_AT_BORLAND_property_implements = 0x3b13,
DW_AT_BORLAND_property_index = 0x3b14,
DW_AT_BORLAND_property_default = 0x3b15,
DW_AT_BORLAND_Delphi_unit = 0x3b20,
DW_AT_BORLAND_Delphi_class = 0x3b21,
DW_AT_BORLAND_Delphi_record = 0x3b22,
DW_AT_BORLAND_Delphi_metaclass = 0x3b23,
DW_AT_BORLAND_Delphi_constructor = 0x3b24,
DW_AT_BORLAND_Delphi_destructor = 0x3b25,
DW_AT_BORLAND_Delphi_anonymous_method = 0x3b26,
DW_AT_BORLAND_Delphi_interface = 0x3b27,
DW_AT_BORLAND_Delphi_ABI = 0x3b28,
DW_AT_BORLAND_Delphi_return = 0x3b29,
DW_AT_BORLAND_Delphi_frameptr = 0x3b30,
DW_AT_BORLAND_closure = 0x3b31,
// LLVM project extensions.
DW_AT_LLVM_include_path = 0x3e00,
DW_AT_LLVM_config_macros = 0x3e01,
DW_AT_LLVM_isysroot = 0x3e02,
// Apple extensions.
DW_AT_APPLE_optimized = 0x3fe1,
DW_AT_APPLE_flags = 0x3fe2,
DW_AT_APPLE_isa = 0x3fe3,
DW_AT_APPLE_block = 0x3fe4,
DW_AT_APPLE_major_runtime_vers = 0x3fe5,
DW_AT_APPLE_runtime_class = 0x3fe6,
DW_AT_APPLE_omit_frame_ptr = 0x3fe7,
DW_AT_APPLE_property_name = 0x3fe8,
DW_AT_APPLE_property_getter = 0x3fe9,
DW_AT_APPLE_property_setter = 0x3fea,
DW_AT_APPLE_property_attribute = 0x3feb,
DW_AT_APPLE_objc_complete_type = 0x3fec,
DW_AT_APPLE_property = 0x3fed
};
enum Form : uint16_t {
// Attribute form encodings
DW_FORM_addr = 0x01,
DW_FORM_block2 = 0x03,
DW_FORM_block4 = 0x04,
DW_FORM_data2 = 0x05,
DW_FORM_data4 = 0x06,
DW_FORM_data8 = 0x07,
DW_FORM_string = 0x08,
DW_FORM_block = 0x09,
DW_FORM_block1 = 0x0a,
DW_FORM_data1 = 0x0b,
DW_FORM_flag = 0x0c,
DW_FORM_sdata = 0x0d,
DW_FORM_strp = 0x0e,
DW_FORM_udata = 0x0f,
DW_FORM_ref_addr = 0x10,
DW_FORM_ref1 = 0x11,
DW_FORM_ref2 = 0x12,
DW_FORM_ref4 = 0x13,
DW_FORM_ref8 = 0x14,
DW_FORM_ref_udata = 0x15,
DW_FORM_indirect = 0x16,
DW_FORM_sec_offset = 0x17,
DW_FORM_exprloc = 0x18,
DW_FORM_flag_present = 0x19,
DW_FORM_ref_sig8 = 0x20,
// Extensions for Fission proposal
DW_FORM_GNU_addr_index = 0x1f01,
DW_FORM_GNU_str_index = 0x1f02,
// Alternate debug sections proposal (output of "dwz" tool).
DW_FORM_GNU_ref_alt = 0x1f20,
DW_FORM_GNU_strp_alt = 0x1f21
};
enum LocationAtom {
#define HANDLE_DW_OP(ID, NAME) DW_OP_##NAME = ID,
#include "Dwarf.def"
DW_OP_lo_user = 0xe0,
DW_OP_hi_user = 0xff
};
enum TypeKind {
#define HANDLE_DW_ATE(ID, NAME) DW_ATE_##NAME = ID,
#include "Dwarf.def"
DW_ATE_lo_user = 0x80,
DW_ATE_hi_user = 0xff
};
enum DecimalSignEncoding {
// Decimal sign attribute values
DW_DS_unsigned = 0x01,
DW_DS_leading_overpunch = 0x02,
DW_DS_trailing_overpunch = 0x03,
DW_DS_leading_separate = 0x04,
DW_DS_trailing_separate = 0x05
};
enum EndianityEncoding {
// Endianity attribute values
DW_END_default = 0x00,
DW_END_big = 0x01,
DW_END_little = 0x02,
DW_END_lo_user = 0x40,
DW_END_hi_user = 0xff
};
enum AccessAttribute {
// Accessibility codes
DW_ACCESS_public = 0x01,
DW_ACCESS_protected = 0x02,
DW_ACCESS_private = 0x03
};
enum VisibilityAttribute {
// Visibility codes
DW_VIS_local = 0x01,
DW_VIS_exported = 0x02,
DW_VIS_qualified = 0x03
};
enum VirtualityAttribute {
#define HANDLE_DW_VIRTUALITY(ID, NAME) DW_VIRTUALITY_##NAME = ID,
#include "Dwarf.def"
DW_VIRTUALITY_max = 0x02
};
enum SourceLanguage {
#define HANDLE_DW_LANG(ID, NAME) DW_LANG_##NAME = ID,
#include "Dwarf.def"
DW_LANG_lo_user = 0x8000,
DW_LANG_hi_user = 0xffff
};
enum CaseSensitivity {
// Identifier case codes
DW_ID_case_sensitive = 0x00,
DW_ID_up_case = 0x01,
DW_ID_down_case = 0x02,
DW_ID_case_insensitive = 0x03
};
enum CallingConvention {
// Calling convention codes
DW_CC_normal = 0x01,
DW_CC_program = 0x02,
DW_CC_nocall = 0x03,
DW_CC_lo_user = 0x40,
DW_CC_GNU_borland_fastcall_i386 = 0x41,
DW_CC_BORLAND_safecall = 0xb0,
DW_CC_BORLAND_stdcall = 0xb1,
DW_CC_BORLAND_pascal = 0xb2,
DW_CC_BORLAND_msfastcall = 0xb3,
DW_CC_BORLAND_msreturn = 0xb4,
DW_CC_BORLAND_thiscall = 0xb5,
DW_CC_BORLAND_fastcall = 0xb6,
DW_CC_hi_user = 0xff
};
enum InlineAttribute {
// Inline codes
DW_INL_not_inlined = 0x00,
DW_INL_inlined = 0x01,
DW_INL_declared_not_inlined = 0x02,
DW_INL_declared_inlined = 0x03
};
enum ArrayDimensionOrdering {
// Array ordering
DW_ORD_row_major = 0x00,
DW_ORD_col_major = 0x01
};
enum DiscriminantList {
// Discriminant descriptor values
DW_DSC_label = 0x00,
DW_DSC_range = 0x01
};
enum LineNumberOps {
// Line Number Standard Opcode Encodings
DW_LNS_extended_op = 0x00,
DW_LNS_copy = 0x01,
DW_LNS_advance_pc = 0x02,
DW_LNS_advance_line = 0x03,
DW_LNS_set_file = 0x04,
DW_LNS_set_column = 0x05,
DW_LNS_negate_stmt = 0x06,
DW_LNS_set_basic_block = 0x07,
DW_LNS_const_add_pc = 0x08,
DW_LNS_fixed_advance_pc = 0x09,
DW_LNS_set_prologue_end = 0x0a,
DW_LNS_set_epilogue_begin = 0x0b,
DW_LNS_set_isa = 0x0c
};
enum LineNumberExtendedOps {
// Line Number Extended Opcode Encodings
DW_LNE_end_sequence = 0x01,
DW_LNE_set_address = 0x02,
DW_LNE_define_file = 0x03,
DW_LNE_set_discriminator = 0x04,
DW_LNE_lo_user = 0x80,
DW_LNE_hi_user = 0xff
};
enum MacinfoRecordType {
// Macinfo Type Encodings
DW_MACINFO_define = 0x01,
DW_MACINFO_undef = 0x02,
DW_MACINFO_start_file = 0x03,
DW_MACINFO_end_file = 0x04,
DW_MACINFO_vendor_ext = 0xff
};
enum MacroEntryType {
// Macro Information Entry Type Encodings
DW_MACRO_define = 0x01,
DW_MACRO_undef = 0x02,
DW_MACRO_start_file = 0x03,
DW_MACRO_end_file = 0x04,
DW_MACRO_define_indirect = 0x05,
DW_MACRO_undef_indirect = 0x06,
DW_MACRO_transparent_include = 0x07,
DW_MACRO_define_indirect_sup = 0x08,
DW_MACRO_undef_indirect_sup = 0x09,
DW_MACRO_transparent_include_sup = 0x0a,
DW_MACRO_define_indirectx = 0x0b,
DW_MACRO_undef_indirectx = 0x0c,
DW_MACRO_lo_user = 0xe0,
DW_MACRO_hi_user = 0xff
};
enum CallFrameInfo {
// Call frame instruction encodings
DW_CFA_extended = 0x00,
DW_CFA_nop = 0x00,
DW_CFA_advance_loc = 0x40,
DW_CFA_offset = 0x80,
DW_CFA_restore = 0xc0,
DW_CFA_set_loc = 0x01,
DW_CFA_advance_loc1 = 0x02,
DW_CFA_advance_loc2 = 0x03,
DW_CFA_advance_loc4 = 0x04,
DW_CFA_offset_extended = 0x05,
DW_CFA_restore_extended = 0x06,
DW_CFA_undefined = 0x07,
DW_CFA_same_value = 0x08,
DW_CFA_register = 0x09,
DW_CFA_remember_state = 0x0a,
DW_CFA_restore_state = 0x0b,
DW_CFA_def_cfa = 0x0c,
DW_CFA_def_cfa_register = 0x0d,
DW_CFA_def_cfa_offset = 0x0e,
DW_CFA_def_cfa_expression = 0x0f,
DW_CFA_expression = 0x10,
DW_CFA_offset_extended_sf = 0x11,
DW_CFA_def_cfa_sf = 0x12,
DW_CFA_def_cfa_offset_sf = 0x13,
DW_CFA_val_offset = 0x14,
DW_CFA_val_offset_sf = 0x15,
DW_CFA_val_expression = 0x16,
DW_CFA_MIPS_advance_loc8 = 0x1d,
DW_CFA_GNU_window_save = 0x2d,
DW_CFA_GNU_args_size = 0x2e,
DW_CFA_lo_user = 0x1c,
DW_CFA_hi_user = 0x3f
};
enum Constants {
// Children flag
DW_CHILDREN_no = 0x00,
DW_CHILDREN_yes = 0x01,
DW_EH_PE_absptr = 0x00,
DW_EH_PE_omit = 0xff,
DW_EH_PE_uleb128 = 0x01,
DW_EH_PE_udata2 = 0x02,
DW_EH_PE_udata4 = 0x03,
DW_EH_PE_udata8 = 0x04,
DW_EH_PE_sleb128 = 0x09,
DW_EH_PE_sdata2 = 0x0A,
DW_EH_PE_sdata4 = 0x0B,
DW_EH_PE_sdata8 = 0x0C,
DW_EH_PE_signed = 0x08,
DW_EH_PE_pcrel = 0x10,
DW_EH_PE_textrel = 0x20,
DW_EH_PE_datarel = 0x30,
DW_EH_PE_funcrel = 0x40,
DW_EH_PE_aligned = 0x50,
DW_EH_PE_indirect = 0x80
};
// Constants for debug_loc.dwo in the DWARF5 Split Debug Info Proposal
enum LocationListEntry : unsigned char {
DW_LLE_end_of_list_entry,
DW_LLE_base_address_selection_entry,
DW_LLE_start_end_entry,
DW_LLE_start_length_entry,
DW_LLE_offset_pair_entry
};
/// Contstants for the DW_APPLE_PROPERTY_attributes attribute.
/// Keep this list in sync with clang's DeclSpec.h ObjCPropertyAttributeKind.
enum ApplePropertyAttributes {
// Apple Objective-C Property Attributes
DW_APPLE_PROPERTY_readonly = 0x01,
DW_APPLE_PROPERTY_getter = 0x02,
DW_APPLE_PROPERTY_assign = 0x04,
DW_APPLE_PROPERTY_readwrite = 0x08,
DW_APPLE_PROPERTY_retain = 0x10,
DW_APPLE_PROPERTY_copy = 0x20,
DW_APPLE_PROPERTY_nonatomic = 0x40,
DW_APPLE_PROPERTY_setter = 0x80,
DW_APPLE_PROPERTY_atomic = 0x100,
DW_APPLE_PROPERTY_weak = 0x200,
DW_APPLE_PROPERTY_strong = 0x400,
DW_APPLE_PROPERTY_unsafe_unretained = 0x800
};
// Constants for the DWARF5 Accelerator Table Proposal
enum AcceleratorTable {
// Data layout descriptors.
DW_ATOM_null = 0u, // Marker as the end of a list of atoms.
DW_ATOM_die_offset = 1u, // DIE offset in the debug_info section.
DW_ATOM_cu_offset = 2u, // Offset of the compile unit header that contains the
// item in question.
DW_ATOM_die_tag = 3u, // A tag entry.
DW_ATOM_type_flags = 4u, // Set of flags for a type.
// DW_ATOM_type_flags values.
// Always set for C++, only set for ObjC if this is the @implementation for a
// class.
DW_FLAG_type_implementation = 2u,
// Hash functions.
// Daniel J. Bernstein hash.
DW_hash_function_djb = 0u
};
// Constants for the GNU pubnames/pubtypes extensions supporting gdb index.
enum GDBIndexEntryKind {
GIEK_NONE,
GIEK_TYPE,
GIEK_VARIABLE,
GIEK_FUNCTION,
GIEK_OTHER,
GIEK_UNUSED5,
GIEK_UNUSED6,
GIEK_UNUSED7
};
enum GDBIndexEntryLinkage {
GIEL_EXTERNAL,
GIEL_STATIC
};
/// \defgroup DwarfConstantsDumping Dwarf constants dumping functions
///
/// All these functions map their argument's value back to the
/// corresponding enumerator name or return nullptr if the value isn't
/// known.
///
/// @{
const char *TagString(unsigned Tag);
const char *ChildrenString(unsigned Children);
const char *AttributeString(unsigned Attribute);
const char *FormEncodingString(unsigned Encoding);
const char *OperationEncodingString(unsigned Encoding);
const char *AttributeEncodingString(unsigned Encoding);
const char *DecimalSignString(unsigned Sign);
const char *EndianityString(unsigned Endian);
const char *AccessibilityString(unsigned Access);
const char *VisibilityString(unsigned Visibility);
const char *VirtualityString(unsigned Virtuality);
const char *LanguageString(unsigned Language);
const char *CaseString(unsigned Case);
const char *ConventionString(unsigned Convention);
const char *InlineCodeString(unsigned Code);
const char *ArrayOrderString(unsigned Order);
const char *DiscriminantString(unsigned Discriminant);
const char *LNStandardString(unsigned Standard);
const char *LNExtendedString(unsigned Encoding);
const char *MacinfoString(unsigned Encoding);
const char *CallFrameString(unsigned Encoding);
const char *ApplePropertyString(unsigned);
const char *AtomTypeString(unsigned Atom);
const char *GDBIndexEntryKindString(GDBIndexEntryKind Kind);
const char *GDBIndexEntryLinkageString(GDBIndexEntryLinkage Linkage);
/// @}
/// \brief Returns the symbolic string representing Val when used as a value
/// for attribute Attr.
const char *AttributeValueString(uint16_t Attr, unsigned Val);
/// \brief Decsribes an entry of the various gnu_pub* debug sections.
///
/// The gnu_pub* kind looks like:
///
/// 0-3 reserved
/// 4-6 symbol kind
/// 7 0 == global, 1 == static
///
/// A gdb_index descriptor includes the above kind, shifted 24 bits up with the
/// offset of the cu within the debug_info section stored in those 24 bits.
struct PubIndexEntryDescriptor {
GDBIndexEntryKind Kind;
GDBIndexEntryLinkage Linkage;
PubIndexEntryDescriptor(GDBIndexEntryKind Kind, GDBIndexEntryLinkage Linkage)
: Kind(Kind), Linkage(Linkage) {}
/* implicit */ PubIndexEntryDescriptor(GDBIndexEntryKind Kind)
: Kind(Kind), Linkage(GIEL_EXTERNAL) {}
explicit PubIndexEntryDescriptor(uint8_t Value)
: Kind(static_cast<GDBIndexEntryKind>((Value & KIND_MASK) >>
KIND_OFFSET)),
Linkage(static_cast<GDBIndexEntryLinkage>((Value & LINKAGE_MASK) >>
LINKAGE_OFFSET)) {}
uint8_t toBits() { return Kind << KIND_OFFSET | Linkage << LINKAGE_OFFSET; }
private:
enum {
KIND_OFFSET = 4,
KIND_MASK = 7 << KIND_OFFSET,
LINKAGE_OFFSET = 7,
LINKAGE_MASK = 1 << LINKAGE_OFFSET
};
};
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/threading/SwitchToThread/test1/test1.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
** Source: test1.c
**
** Purpose: Test to ensure SwitchToThread works, without
** causing test to hang
**
** Dependencies: PAL_Initialize
** Fail
** SwitchToThread
** WaitForMultipleObject
** CreateThread
** GetLastError
**
**
**===========================================================================*/
#include <palsuite.h>
#define THREAD_COUNT 10
#define REPEAT_COUNT 1000
#define TIMEOUT 60000
void PALAPI Run_Thread_switchtothread_test1(LPVOID lpParam);
/**
* main
*
* executable entry point
*/
PALTEST(threading_SwitchToThread_test1_paltest_switchtothread_test1, "threading/SwitchToThread/test1/paltest_switchtothread_test1")
{
DWORD dwParam;
HANDLE hThread[THREAD_COUNT];
DWORD threadId[THREAD_COUNT];
int i = 0;
int returnCode = 0;
/*PAL initialization */
if( (PAL_Initialize(argc, argv)) != 0 )
{
return FAIL;
}
for( i = 0; i < THREAD_COUNT; i++ )
{
dwParam = (int) i;
//Create thread
hThread[i] = CreateThread(
NULL, /* no security attributes */
0, /* use default stack size */
(LPTHREAD_START_ROUTINE)Run_Thread_switchtothread_test1,/* thread function */
(LPVOID)dwParam, /* argument to thread function */
0, /* use default creation flags */
&threadId[i] /* returns the thread identifier*/
);
if(hThread[i] == NULL)
{
Fail("Create Thread failed for iteration %d GetLastError value is %d\n", i, GetLastError());
}
}
returnCode = WaitForMultipleObjects(THREAD_COUNT, hThread, TRUE, TIMEOUT);
if( WAIT_OBJECT_0 != returnCode )
{
Trace("Wait for Object(s) returned %d, expected value is %d, and GetLastError value is %d\n", returnCode, WAIT_OBJECT_0, GetLastError());
}
PAL_Terminate();
return PASS;
}
void PALAPI Run_Thread_switchtothread_test1 (LPVOID lpParam)
{
int i = 0;
int Id=(int)(SIZE_T)lpParam;
for(i=0; i < REPEAT_COUNT; i++ )
{
// No Last Error is set..
if(!SwitchToThread())
{
Trace( "The operating system did not switch execution to another thread,"
"for thread id[%d], iteration [%d]\n", Id, i );
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=============================================================================
**
** Source: test1.c
**
** Purpose: Test to ensure SwitchToThread works, without
** causing test to hang
**
** Dependencies: PAL_Initialize
** Fail
** SwitchToThread
** WaitForMultipleObject
** CreateThread
** GetLastError
**
**
**===========================================================================*/
#include <palsuite.h>
#define THREAD_COUNT 10
#define REPEAT_COUNT 1000
#define TIMEOUT 60000
void PALAPI Run_Thread_switchtothread_test1(LPVOID lpParam);
/**
* main
*
* executable entry point
*/
PALTEST(threading_SwitchToThread_test1_paltest_switchtothread_test1, "threading/SwitchToThread/test1/paltest_switchtothread_test1")
{
DWORD dwParam;
HANDLE hThread[THREAD_COUNT];
DWORD threadId[THREAD_COUNT];
int i = 0;
int returnCode = 0;
/*PAL initialization */
if( (PAL_Initialize(argc, argv)) != 0 )
{
return FAIL;
}
for( i = 0; i < THREAD_COUNT; i++ )
{
dwParam = (int) i;
//Create thread
hThread[i] = CreateThread(
NULL, /* no security attributes */
0, /* use default stack size */
(LPTHREAD_START_ROUTINE)Run_Thread_switchtothread_test1,/* thread function */
(LPVOID)dwParam, /* argument to thread function */
0, /* use default creation flags */
&threadId[i] /* returns the thread identifier*/
);
if(hThread[i] == NULL)
{
Fail("Create Thread failed for iteration %d GetLastError value is %d\n", i, GetLastError());
}
}
returnCode = WaitForMultipleObjects(THREAD_COUNT, hThread, TRUE, TIMEOUT);
if( WAIT_OBJECT_0 != returnCode )
{
Trace("Wait for Object(s) returned %d, expected value is %d, and GetLastError value is %d\n", returnCode, WAIT_OBJECT_0, GetLastError());
}
PAL_Terminate();
return PASS;
}
void PALAPI Run_Thread_switchtothread_test1 (LPVOID lpParam)
{
int i = 0;
int Id=(int)(SIZE_T)lpParam;
for(i=0; i < REPEAT_COUNT; i++ )
{
// No Last Error is set..
if(!SwitchToThread())
{
Trace( "The operating system did not switch execution to another thread,"
"for thread id[%d], iteration [%d]\n", Id, i );
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/jit/jittelemetry.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*****************************************************************************/
// <OWNER>clrjit</OWNER>
//
// This class abstracts the telemetry information collected for the JIT.
//
// Goals:
// 1. Telemetry information should be a NO-op when JIT level telemetry is disabled.
// 2. Data collection should be actionable.
// 3. Data collection should comply to privacy rules.
// 4. Data collection cannot impact JIT/OS performance.
// 5. Data collection volume should be manageable by our remote services.
//
// DESIGN CONCERNS:
//
// > To collect data, we use the TraceLogging API provided by Windows.
//
// The brief workflow suggested is:
// #include <TraceLoggingProvider.h>
// TRACELOGGING_DEFINE_PROVIDER( // defines g_hProvider
// g_hProvider, // Name of the provider variable
// "MyProvider", // Human-readable name of the provider
// (0xb3864c38, 0x4273, 0x58c5, 0x54, 0x5b, 0x8b, 0x36, 0x08, 0x34, 0x34, 0x71)); // Provider GUID
// int main(int argc, char* argv[]) // or DriverEntry for kernel-mode.
// {
// TraceLoggingRegister(g_hProvider, NULL, NULL, NULL); // NULLs only needed for C. Please do not include the
// // NULLs in C++ code.
// TraceLoggingWrite(g_hProvider,
// "MyEvent1",
// TraceLoggingString(argv[0], "arg0"),
// TraceLoggingInt32(argc));
// TraceLoggingUnregister(g_hProvider);
// return 0;
// }
//
// In summary, this involves:
// 1. Creating a binary/DLL local provider using:
// TRACELOGGING_DEFINE_PROVIDER(g_hProvider, "ProviderName", providerId, [option])
// 2. Registering the provider instance
// TraceLoggingRegister(g_hProvider)
// 3. Perform TraceLoggingWrite operations to write out data.
// 4. Unregister the provider instance.
// TraceLoggingUnregister(g_hProvider)
//
// A. Determining where to create the provider instance?
// 1) We use the same provider name/GUID as the CLR and the CLR creates its own DLL local provider handle.
// For CLRJIT.dll, the question is, can the same provider name/GUIDs be shared across binaries?
//
// Answer:
// "For TraceLogging providers, it is okay to use the same provider GUID / name
// in different binaries. Do not share the same provider handle across DLLs.
// As long as you do not pass an hProvider from one DLL to another, TraceLogging
// will properly keep track of the events."
//
// 2) CoreCLR is linked into the CLR. CLR already creates an instance, so where do we create the JIT's instance?
// Answer:
// "Ideally you would have one provider per DLL, but if you're folding distinct sets
// of functionality into one DLL (like shell32.dll or similar sort of catch-all things)
// you can have perhaps a few more providers per binary."
//
// B. Determining where to register and unregister the provider instance?
// 1) For CLRJIT.dll we can register the provider instance during jitDllOnProcessAttach.
// Since one of our goals is to turn telemetry off, we need to be careful about
// referencing environment variables during the DLL load and unload path.
// Referencing environment variables through ConfigDWORD uses UtilCode.
// This roughly translates to InitUtilcode() being called before jitDllOnProcessAttach.
//
// For CLRJIT.dll, compStartup is called on jitOnDllProcessAttach().
//
// 2) For CLRJIT.dll and CoreCLR, compShutdown will be called during jitOnDllProcessDetach().
//
// C. Determining the data to collect:
//
// IMPORTANT: Since telemetry data can be collected at any time after DLL load,
// make sure you initialize the compiler state variables you access in telemetry
// data collection. For example, if you are transmitting method names, then
// make sure info.compMethodHnd is initialized at that point.
//
// 1) Tracking noway assert count:
// After a noway assert is hit, in both min-opts and non-min-opts, we collect
// info such as the JIT version, method hash being compiled, filename and
// line number etc.
//
// 2) Tracking baseline for the noway asserts:
// During DLL unload, we report the number of methods that were compiled by
// the JIT per process both under normal mode and during min-opts. NOTE that
// this is ON for all processes.
//
// 3) For the future, be aware of privacy, performance and actionability of the data.
//
#include "jitpch.h"
#include "compiler.h"
#ifdef FEATURE_TRACELOGGING
#include "TraceLoggingProvider.h"
#include "MicrosoftTelemetry.h"
#include "clrtraceloggingcommon.h"
#include "fxver.h"
// Since telemetry code could be called under a noway_assert, make sure,
// we don't call noway_assert again.
#undef noway_assert
#define BUILD_STR1(x) #x
#define BUILD_STR2(x) BUILD_STR1(x)
#define BUILD_MACHINE BUILD_STR2(__BUILDMACHINE__)
// A DLL local instance of the DotNet provider
TRACELOGGING_DEFINE_PROVIDER(g_hClrJitProvider,
CLRJIT_PROVIDER_NAME,
CLRJIT_PROVIDER_ID,
TraceLoggingOptionMicrosoftTelemetry());
// Threshold to detect if we are hitting too many bad (noway) methods
// over good methods per process to prevent logging too much data.
static const double NOWAY_NOISE_RATIO = 0.6; // Threshold of (bad / total) beyond which we'd stop
// logging. We'd restart if the pass rate improves.
static const unsigned NOWAY_SUFFICIENCY_THRESHOLD = 25; // Count of methods beyond which we'd apply percent
// threshold
// Initialize Telemetry State
volatile bool JitTelemetry::s_fProviderRegistered = false;
volatile UINT32 JitTelemetry::s_uMethodsCompiled = 0;
volatile UINT32 JitTelemetry::s_uMethodsHitNowayAssert = 0;
// Constructor for telemetry state per compiler instance
JitTelemetry::JitTelemetry()
{
Initialize(nullptr);
}
//------------------------------------------------------------------------
// Initialize: Initialize the object with the compiler instance
//
// Description:
// Compiler instance may not be fully initialized. If you are
// tracking object data for telemetry, make sure they are initialized
// in the compiler is ready.
//
void JitTelemetry::Initialize(Compiler* c)
{
comp = c;
m_pszAssemblyName = "";
m_pszScopeName = "";
m_pszMethodName = "";
m_uMethodHash = 0;
m_fMethodInfoCached = false;
}
//------------------------------------------------------------------------
// IsTelemetryEnabled: Can we perform JIT telemetry
//
// Return Value:
// Returns "true" if COMPlus_JitTelemetry environment flag is
// non-zero. Else returns "false".
//
//
/* static */
bool JitTelemetry::IsTelemetryEnabled()
{
return JitConfig.JitTelemetry() != 0;
}
//------------------------------------------------------------------------
// NotifyDllProcessAttach: Notification for DLL load and static initializations
//
// Description:
// Register telemetry provider with the OS.
//
// Note:
// This method can be called twice in NGEN scenario.
//
void JitTelemetry::NotifyDllProcessAttach()
{
if (!IsTelemetryEnabled())
{
return;
}
if (!s_fProviderRegistered)
{
// Register the provider.
TraceLoggingRegister(g_hClrJitProvider);
s_fProviderRegistered = true;
}
}
//------------------------------------------------------------------------
// NotifyDllProcessDetach: Notification for DLL unload and teardown
//
// Description:
// Log the methods compiled data if telemetry is enabled and
// Unregister telemetry provider with the OS.
//
void JitTelemetry::NotifyDllProcessDetach()
{
if (!IsTelemetryEnabled())
{
return;
}
assert(s_fProviderRegistered); // volatile read
// Unregister the provider.
TraceLoggingUnregister(g_hClrJitProvider);
}
//------------------------------------------------------------------------
// NotifyEndOfCompilation: Notification for end of current method
// compilation.
//
// Description:
// Increment static volatile counters for the current compiled method.
// This is slightly inaccurate due to lack of synchronization around
// the counters. Inaccuracy is the tradeoff for JITting cost.
//
// Note:
// 1. Must be called post fully successful compilation of the method.
// 2. This serves as an effective baseline as how many methods compiled
// successfully.
void JitTelemetry::NotifyEndOfCompilation()
{
if (!IsTelemetryEnabled())
{
return;
}
s_uMethodsCompiled++; // volatile increment
}
//------------------------------------------------------------------------
// NotifyNowayAssert: Notification that a noway handling is under-way.
//
// Arguments:
// filename - The JIT source file name's absolute path at the time of
// building the JIT.
// line - The line number where the noway assert was hit.
//
// Description:
// If telemetry is enabled, then obtain data to collect from the
// compiler or the VM and use the tracelogging APIs to write out.
//
void JitTelemetry::NotifyNowayAssert(const char* filename, unsigned line)
{
if (!IsTelemetryEnabled())
{
return;
}
s_uMethodsHitNowayAssert++;
// Check if our assumption that noways are rare is invalid for this
// process. If so, return early than logging too much data.
unsigned noways = s_uMethodsHitNowayAssert;
unsigned attempts = max(1, s_uMethodsCompiled + noways);
double ratio = (noways / ((double)attempts));
if (noways > NOWAY_SUFFICIENCY_THRESHOLD && ratio > NOWAY_NOISE_RATIO)
{
return;
}
assert(comp);
UINT32 nowayIndex = s_uMethodsHitNowayAssert;
UINT32 codeSize = 0;
INT32 minOpts = -1;
const char* lastPhase = "";
if (comp != nullptr)
{
codeSize = comp->info.compILCodeSize;
minOpts = comp->opts.IsMinOptsSet() ? comp->opts.MinOpts() : -1;
lastPhase = PhaseNames[comp->mostRecentlyActivePhase];
}
CacheCurrentMethodInfo();
TraceLoggingWrite(g_hClrJitProvider, "CLRJIT.NowayAssert",
TraceLoggingUInt32(codeSize, "IL_CODE_SIZE"), TraceLoggingInt32(minOpts, "MINOPTS_MODE"),
TraceLoggingString(lastPhase, "PREVIOUS_COMPLETED_PHASE"),
TraceLoggingString(m_pszAssemblyName, "ASSEMBLY_NAME"),
TraceLoggingString(m_pszMethodName, "METHOD_NAME"),
TraceLoggingString(m_pszScopeName, "METHOD_SCOPE"),
TraceLoggingUInt32(m_uMethodHash, "METHOD_HASH"),
TraceLoggingString(filename, "FILENAME"), TraceLoggingUInt32(line, "LINE"),
TraceLoggingUInt32(nowayIndex, "NOWAY_INDEX"),
TraceLoggingString(TARGET_READABLE_NAME, "ARCH"),
TraceLoggingString(VER_FILEVERSION_STR, "VERSION"), TraceLoggingString(BUILD_MACHINE, "BUILD"),
TraceLoggingString(VER_COMMENTS_STR, "FLAVOR"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES));
}
//------------------------------------------------------------------------
// CacheCurrentMethodInfo: Cache the method/assembly/scope name info.
//
// Description:
// Obtain the method information if not already cached, for the
// method under compilation from the compiler. This includes:
//
// Method name, assembly name, scope name, method hash.
//
void JitTelemetry::CacheCurrentMethodInfo()
{
if (m_fMethodInfoCached)
{
return;
}
assert(comp);
if (comp != nullptr)
{
comp->compGetTelemetryDefaults(&m_pszAssemblyName, &m_pszScopeName, &m_pszMethodName, &m_uMethodHash);
assert(m_pszAssemblyName);
assert(m_pszScopeName);
assert(m_pszMethodName);
}
// Set cached to prevent getting this twice.
m_fMethodInfoCached = true;
}
//------------------------------------------------------------------------
// compGetTelemetryDefaults: Obtain information specific to telemetry
// from the JIT-interface.
//
// Arguments:
// assemblyName - Pointer to hold assembly name upon return
// scopeName - Pointer to hold scope name upon return
// methodName - Pointer to hold method name upon return
// methodHash - Pointer to hold method hash upon return
//
// Description:
// Obtains from the JIT EE interface the information for the
// current method under compilation.
//
// Warning:
// The eeGetMethodName call could be expensive for generic
// methods, so call this method only when there is less impact
// to throughput.
//
void Compiler::compGetTelemetryDefaults(const char** assemblyName,
const char** scopeName,
const char** methodName,
unsigned* methodHash)
{
if (info.compMethodHnd != nullptr)
{
__try
{
// Expensive calls, call infrequently or in exceptional scenarios.
*methodHash = info.compCompHnd->getMethodHash(info.compMethodHnd);
*methodName = eeGetMethodName(info.compMethodHnd, scopeName);
// SuperPMI needs to implement record/replay of these method calls.
*assemblyName = info.compCompHnd->getAssemblyName(
info.compCompHnd->getModuleAssembly(info.compCompHnd->getClassModule(info.compClassHnd)));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
}
// If the JIT interface methods init-ed these values to nullptr,
// make sure they are set to empty string.
if (*methodName == nullptr)
{
*methodName = "";
}
if (*scopeName == nullptr)
{
*scopeName = "";
}
if (*assemblyName == nullptr)
{
*assemblyName = "";
}
}
#endif // FEATURE_TRACELOGGING
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*****************************************************************************/
// <OWNER>clrjit</OWNER>
//
// This class abstracts the telemetry information collected for the JIT.
//
// Goals:
// 1. Telemetry information should be a NO-op when JIT level telemetry is disabled.
// 2. Data collection should be actionable.
// 3. Data collection should comply to privacy rules.
// 4. Data collection cannot impact JIT/OS performance.
// 5. Data collection volume should be manageable by our remote services.
//
// DESIGN CONCERNS:
//
// > To collect data, we use the TraceLogging API provided by Windows.
//
// The brief workflow suggested is:
// #include <TraceLoggingProvider.h>
// TRACELOGGING_DEFINE_PROVIDER( // defines g_hProvider
// g_hProvider, // Name of the provider variable
// "MyProvider", // Human-readable name of the provider
// (0xb3864c38, 0x4273, 0x58c5, 0x54, 0x5b, 0x8b, 0x36, 0x08, 0x34, 0x34, 0x71)); // Provider GUID
// int main(int argc, char* argv[]) // or DriverEntry for kernel-mode.
// {
// TraceLoggingRegister(g_hProvider, NULL, NULL, NULL); // NULLs only needed for C. Please do not include the
// // NULLs in C++ code.
// TraceLoggingWrite(g_hProvider,
// "MyEvent1",
// TraceLoggingString(argv[0], "arg0"),
// TraceLoggingInt32(argc));
// TraceLoggingUnregister(g_hProvider);
// return 0;
// }
//
// In summary, this involves:
// 1. Creating a binary/DLL local provider using:
// TRACELOGGING_DEFINE_PROVIDER(g_hProvider, "ProviderName", providerId, [option])
// 2. Registering the provider instance
// TraceLoggingRegister(g_hProvider)
// 3. Perform TraceLoggingWrite operations to write out data.
// 4. Unregister the provider instance.
// TraceLoggingUnregister(g_hProvider)
//
// A. Determining where to create the provider instance?
// 1) We use the same provider name/GUID as the CLR and the CLR creates its own DLL local provider handle.
// For CLRJIT.dll, the question is, can the same provider name/GUIDs be shared across binaries?
//
// Answer:
// "For TraceLogging providers, it is okay to use the same provider GUID / name
// in different binaries. Do not share the same provider handle across DLLs.
// As long as you do not pass an hProvider from one DLL to another, TraceLogging
// will properly keep track of the events."
//
// 2) CoreCLR is linked into the CLR. CLR already creates an instance, so where do we create the JIT's instance?
// Answer:
// "Ideally you would have one provider per DLL, but if you're folding distinct sets
// of functionality into one DLL (like shell32.dll or similar sort of catch-all things)
// you can have perhaps a few more providers per binary."
//
// B. Determining where to register and unregister the provider instance?
// 1) For CLRJIT.dll we can register the provider instance during jitDllOnProcessAttach.
// Since one of our goals is to turn telemetry off, we need to be careful about
// referencing environment variables during the DLL load and unload path.
// Referencing environment variables through ConfigDWORD uses UtilCode.
// This roughly translates to InitUtilcode() being called before jitDllOnProcessAttach.
//
// For CLRJIT.dll, compStartup is called on jitOnDllProcessAttach().
//
// 2) For CLRJIT.dll and CoreCLR, compShutdown will be called during jitOnDllProcessDetach().
//
// C. Determining the data to collect:
//
// IMPORTANT: Since telemetry data can be collected at any time after DLL load,
// make sure you initialize the compiler state variables you access in telemetry
// data collection. For example, if you are transmitting method names, then
// make sure info.compMethodHnd is initialized at that point.
//
// 1) Tracking noway assert count:
// After a noway assert is hit, in both min-opts and non-min-opts, we collect
// info such as the JIT version, method hash being compiled, filename and
// line number etc.
//
// 2) Tracking baseline for the noway asserts:
// During DLL unload, we report the number of methods that were compiled by
// the JIT per process both under normal mode and during min-opts. NOTE that
// this is ON for all processes.
//
// 3) For the future, be aware of privacy, performance and actionability of the data.
//
#include "jitpch.h"
#include "compiler.h"
#ifdef FEATURE_TRACELOGGING
#include "TraceLoggingProvider.h"
#include "MicrosoftTelemetry.h"
#include "clrtraceloggingcommon.h"
#include "fxver.h"
// Since telemetry code could be called under a noway_assert, make sure,
// we don't call noway_assert again.
#undef noway_assert
#define BUILD_STR1(x) #x
#define BUILD_STR2(x) BUILD_STR1(x)
#define BUILD_MACHINE BUILD_STR2(__BUILDMACHINE__)
// A DLL local instance of the DotNet provider
TRACELOGGING_DEFINE_PROVIDER(g_hClrJitProvider,
CLRJIT_PROVIDER_NAME,
CLRJIT_PROVIDER_ID,
TraceLoggingOptionMicrosoftTelemetry());
// Threshold to detect if we are hitting too many bad (noway) methods
// over good methods per process to prevent logging too much data.
static const double NOWAY_NOISE_RATIO = 0.6; // Threshold of (bad / total) beyond which we'd stop
// logging. We'd restart if the pass rate improves.
static const unsigned NOWAY_SUFFICIENCY_THRESHOLD = 25; // Count of methods beyond which we'd apply percent
// threshold
// Initialize Telemetry State
volatile bool JitTelemetry::s_fProviderRegistered = false;
volatile UINT32 JitTelemetry::s_uMethodsCompiled = 0;
volatile UINT32 JitTelemetry::s_uMethodsHitNowayAssert = 0;
// Constructor for telemetry state per compiler instance
JitTelemetry::JitTelemetry()
{
Initialize(nullptr);
}
//------------------------------------------------------------------------
// Initialize: Initialize the object with the compiler instance
//
// Description:
// Compiler instance may not be fully initialized. If you are
// tracking object data for telemetry, make sure they are initialized
// in the compiler is ready.
//
void JitTelemetry::Initialize(Compiler* c)
{
comp = c;
m_pszAssemblyName = "";
m_pszScopeName = "";
m_pszMethodName = "";
m_uMethodHash = 0;
m_fMethodInfoCached = false;
}
//------------------------------------------------------------------------
// IsTelemetryEnabled: Can we perform JIT telemetry
//
// Return Value:
// Returns "true" if COMPlus_JitTelemetry environment flag is
// non-zero. Else returns "false".
//
//
/* static */
bool JitTelemetry::IsTelemetryEnabled()
{
return JitConfig.JitTelemetry() != 0;
}
//------------------------------------------------------------------------
// NotifyDllProcessAttach: Notification for DLL load and static initializations
//
// Description:
// Register telemetry provider with the OS.
//
// Note:
// This method can be called twice in NGEN scenario.
//
void JitTelemetry::NotifyDllProcessAttach()
{
if (!IsTelemetryEnabled())
{
return;
}
if (!s_fProviderRegistered)
{
// Register the provider.
TraceLoggingRegister(g_hClrJitProvider);
s_fProviderRegistered = true;
}
}
//------------------------------------------------------------------------
// NotifyDllProcessDetach: Notification for DLL unload and teardown
//
// Description:
// Log the methods compiled data if telemetry is enabled and
// Unregister telemetry provider with the OS.
//
void JitTelemetry::NotifyDllProcessDetach()
{
if (!IsTelemetryEnabled())
{
return;
}
assert(s_fProviderRegistered); // volatile read
// Unregister the provider.
TraceLoggingUnregister(g_hClrJitProvider);
}
//------------------------------------------------------------------------
// NotifyEndOfCompilation: Notification for end of current method
// compilation.
//
// Description:
// Increment static volatile counters for the current compiled method.
// This is slightly inaccurate due to lack of synchronization around
// the counters. Inaccuracy is the tradeoff for JITting cost.
//
// Note:
// 1. Must be called post fully successful compilation of the method.
// 2. This serves as an effective baseline as how many methods compiled
// successfully.
void JitTelemetry::NotifyEndOfCompilation()
{
if (!IsTelemetryEnabled())
{
return;
}
s_uMethodsCompiled++; // volatile increment
}
//------------------------------------------------------------------------
// NotifyNowayAssert: Notification that a noway handling is under-way.
//
// Arguments:
// filename - The JIT source file name's absolute path at the time of
// building the JIT.
// line - The line number where the noway assert was hit.
//
// Description:
// If telemetry is enabled, then obtain data to collect from the
// compiler or the VM and use the tracelogging APIs to write out.
//
void JitTelemetry::NotifyNowayAssert(const char* filename, unsigned line)
{
if (!IsTelemetryEnabled())
{
return;
}
s_uMethodsHitNowayAssert++;
// Check if our assumption that noways are rare is invalid for this
// process. If so, return early than logging too much data.
unsigned noways = s_uMethodsHitNowayAssert;
unsigned attempts = max(1, s_uMethodsCompiled + noways);
double ratio = (noways / ((double)attempts));
if (noways > NOWAY_SUFFICIENCY_THRESHOLD && ratio > NOWAY_NOISE_RATIO)
{
return;
}
assert(comp);
UINT32 nowayIndex = s_uMethodsHitNowayAssert;
UINT32 codeSize = 0;
INT32 minOpts = -1;
const char* lastPhase = "";
if (comp != nullptr)
{
codeSize = comp->info.compILCodeSize;
minOpts = comp->opts.IsMinOptsSet() ? comp->opts.MinOpts() : -1;
lastPhase = PhaseNames[comp->mostRecentlyActivePhase];
}
CacheCurrentMethodInfo();
TraceLoggingWrite(g_hClrJitProvider, "CLRJIT.NowayAssert",
TraceLoggingUInt32(codeSize, "IL_CODE_SIZE"), TraceLoggingInt32(minOpts, "MINOPTS_MODE"),
TraceLoggingString(lastPhase, "PREVIOUS_COMPLETED_PHASE"),
TraceLoggingString(m_pszAssemblyName, "ASSEMBLY_NAME"),
TraceLoggingString(m_pszMethodName, "METHOD_NAME"),
TraceLoggingString(m_pszScopeName, "METHOD_SCOPE"),
TraceLoggingUInt32(m_uMethodHash, "METHOD_HASH"),
TraceLoggingString(filename, "FILENAME"), TraceLoggingUInt32(line, "LINE"),
TraceLoggingUInt32(nowayIndex, "NOWAY_INDEX"),
TraceLoggingString(TARGET_READABLE_NAME, "ARCH"),
TraceLoggingString(VER_FILEVERSION_STR, "VERSION"), TraceLoggingString(BUILD_MACHINE, "BUILD"),
TraceLoggingString(VER_COMMENTS_STR, "FLAVOR"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES));
}
//------------------------------------------------------------------------
// CacheCurrentMethodInfo: Cache the method/assembly/scope name info.
//
// Description:
// Obtain the method information if not already cached, for the
// method under compilation from the compiler. This includes:
//
// Method name, assembly name, scope name, method hash.
//
void JitTelemetry::CacheCurrentMethodInfo()
{
if (m_fMethodInfoCached)
{
return;
}
assert(comp);
if (comp != nullptr)
{
comp->compGetTelemetryDefaults(&m_pszAssemblyName, &m_pszScopeName, &m_pszMethodName, &m_uMethodHash);
assert(m_pszAssemblyName);
assert(m_pszScopeName);
assert(m_pszMethodName);
}
// Set cached to prevent getting this twice.
m_fMethodInfoCached = true;
}
//------------------------------------------------------------------------
// compGetTelemetryDefaults: Obtain information specific to telemetry
// from the JIT-interface.
//
// Arguments:
// assemblyName - Pointer to hold assembly name upon return
// scopeName - Pointer to hold scope name upon return
// methodName - Pointer to hold method name upon return
// methodHash - Pointer to hold method hash upon return
//
// Description:
// Obtains from the JIT EE interface the information for the
// current method under compilation.
//
// Warning:
// The eeGetMethodName call could be expensive for generic
// methods, so call this method only when there is less impact
// to throughput.
//
void Compiler::compGetTelemetryDefaults(const char** assemblyName,
const char** scopeName,
const char** methodName,
unsigned* methodHash)
{
if (info.compMethodHnd != nullptr)
{
__try
{
// Expensive calls, call infrequently or in exceptional scenarios.
*methodHash = info.compCompHnd->getMethodHash(info.compMethodHnd);
*methodName = eeGetMethodName(info.compMethodHnd, scopeName);
// SuperPMI needs to implement record/replay of these method calls.
*assemblyName = info.compCompHnd->getAssemblyName(
info.compCompHnd->getModuleAssembly(info.compCompHnd->getClassModule(info.compClassHnd)));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
}
}
// If the JIT interface methods init-ed these values to nullptr,
// make sure they are set to empty string.
if (*methodName == nullptr)
{
*methodName = "";
}
if (*scopeName == nullptr)
{
*scopeName = "";
}
if (*assemblyName == nullptr)
{
*assemblyName = "";
}
}
#endif // FEATURE_TRACELOGGING
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/mono/mono/utils/linux_magic.h
|
/**
* \file
*/
#ifndef __LINUX_MAGIC_H
#define __LINUX_MAGIC_H
#if __linux__
#if HAVE_LINUX_MAGIC_H
#include <linux/magic.h>
#endif
#ifndef ADFS_SUPER_MAGIC
#define ADFS_SUPER_MAGIC 0xadf5
#endif
#ifndef AFFS_SUPER_MAGIC
#define AFFS_SUPER_MAGIC 0xadff
#endif
#ifndef AFS_SUPER_MAGIC
#define AFS_SUPER_MAGIC 0x5346414F
#endif
#ifndef AUTOFS_SUPER_MAGIC
#define AUTOFS_SUPER_MAGIC 0x0187
#endif
#ifndef AUTOFS_SBI_MAGIC
#define AUTOFS_SBI_MAGIC 0x6d4a556d
#endif
#ifndef CODA_SUPER_MAGIC
#define CODA_SUPER_MAGIC 0x73757245
#endif
#ifndef CRAMFS_MAGIC
#define CRAMFS_MAGIC 0x28cd3d45
#endif
#ifndef CRAMFS_MAGIC_WEND
#define CRAMFS_MAGIC_WEND 0x453dcd28
#endif
#ifndef DEBUGFS_MAGIC
#define DEBUGFS_MAGIC 0x64626720
#endif
#ifndef SYSFS_MAGIC
#define SYSFS_MAGIC 0x62656572
#endif
#ifndef SECURITYFS_MAGIC
#define SECURITYFS_MAGIC 0x73636673
#endif
#ifndef SELINUX_MAGIC
#define SELINUX_MAGIC 0xf97cff8c
#endif
#ifndef RAMFS_MAGIC
#define RAMFS_MAGIC 0x858458f6
#endif
#ifndef TMPFS_MAGIC
#define TMPFS_MAGIC 0x01021994
#endif
#ifndef HUGETLBFS_MAGIC
#define HUGETLBFS_MAGIC 0x958458f6
#endif
#ifndef SQUASHFS_MAGIC
#define SQUASHFS_MAGIC 0x73717368
#endif
#ifndef EFS_SUPER_MAGIC
#define EFS_SUPER_MAGIC 0x414A53
#endif
#ifndef EXT2_SUPER_MAGIC
#define EXT2_SUPER_MAGIC 0xEF53
#endif
#ifndef EXT3_SUPER_MAGIC
#define EXT3_SUPER_MAGIC 0xEF53
#endif
#ifndef XENFS_SUPER_MAGIC
#define XENFS_SUPER_MAGIC 0xabba1974
#endif
#ifndef EXT4_SUPER_MAGIC
#define EXT4_SUPER_MAGIC 0xEF53
#endif
#ifndef BTRFS_SUPER_MAGIC
#define BTRFS_SUPER_MAGIC 0x9123683E
#endif
#ifndef HPFS_SUPER_MAGIC
#define HPFS_SUPER_MAGIC 0xf995e849
#endif
#ifndef ISOFS_SUPER_MAGIC
#define ISOFS_SUPER_MAGIC 0x9660
#endif
#ifndef JFFS2_SUPER_MAGIC
#define JFFS2_SUPER_MAGIC 0x72b6
#endif
#ifndef JFS_SUPER_MAGIC
#define JFS_SUPER_MAGIC 0x3153464a
#endif
#ifndef ANON_INODE_FS_MAGIC
#define ANON_INODE_FS_MAGIC 0x09041934
#endif
#ifndef MINIX_SUPER_MAGIC
#define MINIX_SUPER_MAGIC 0x137F
#endif
#ifndef MINIX_SUPER_MAGIC2
#define MINIX_SUPER_MAGIC2 0x138F
#endif
#ifndef MINIX2_SUPER_MAGIC
#define MINIX2_SUPER_MAGIC 0x2468
#endif
#ifndef MINIX2_SUPER_MAGIC2
#define MINIX2_SUPER_MAGIC2 0x2478
#endif
#ifndef MINIX3_SUPER_MAGIC
#define MINIX3_SUPER_MAGIC 0x4d5a
#endif
#ifndef MSDOS_SUPER_MAGIC
#define MSDOS_SUPER_MAGIC 0x4d44
#endif
#ifndef NCP_SUPER_MAGIC
#define NCP_SUPER_MAGIC 0x564c
#endif
#ifndef NFS_SUPER_MAGIC
#define NFS_SUPER_MAGIC 0x6969
#endif
#ifndef OPENPROM_SUPER_MAGIC
#define OPENPROM_SUPER_MAGIC 0x9fa1
#endif
#ifndef PROC_SUPER_MAGIC
#define PROC_SUPER_MAGIC 0x9fa0
#endif
#ifndef QNX4_SUPER_MAGIC
#define QNX4_SUPER_MAGIC 0x002f
#endif
#ifndef REISERFS_SUPER_MAGIC
#define REISERFS_SUPER_MAGIC 0x52654973
#endif
#ifndef SMB_SUPER_MAGIC
#define SMB_SUPER_MAGIC 0x517B
#endif
#ifndef USBDEVICE_SUPER_MAGIC
#define USBDEVICE_SUPER_MAGIC 0x9fa2
#endif
#ifndef CGROUP_SUPER_MAGIC
#define CGROUP_SUPER_MAGIC 0x27e0eb
#endif
#ifndef FUTEXFS_SUPER_MAGIC
#define FUTEXFS_SUPER_MAGIC 0xBAD1DEA
#endif
#ifndef DEVPTS_SUPER_MAGIC
#define DEVPTS_SUPER_MAGIC 0x1cd1
#endif
#ifndef CIFS_MAGIC_NUMBER
#define CIFS_MAGIC_NUMBER 0xFF534D42
#endif
#ifndef BEFS_SUPER_MAGIC1
#define BEFS_SUPER_MAGIC1 0x42465331
#endif
#ifndef BEFS_SUPER_MAGIC2
#define BEFS_SUPER_MAGIC2 0xdd121031
#endif
#ifndef BEFS_SUPER_MAGIC3
#define BEFS_SUPER_MAGIC3 0x15b6830e
#endif
#ifndef BFS_MAGIC
#define BFS_MAGIC 0x1BADFACE
#endif
#ifndef NTFS_SB_MAGIC
#define NTFS_SB_MAGIC 0x5346544e
#endif
enum {
MONO_SYSV_FSTYPE_NONE = 0,
MONO_SYSV_FSTYPE_XENIX,
MONO_SYSV_FSTYPE_SYSV4,
MONO_SYSV_FSTYPE_SYSV2,
MONO_SYSV_FSTYPE_COH,
};
#ifndef SYSV_MAGIC_BASE
#define SYSV_MAGIC_BASE 0x012FF7B3
#endif
#ifndef XENIX_SUPER_MAGIC
#define XENIX_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_XENIX)
#endif
#ifndef SYSV4_SUPER_MAGIC
#define SYSV4_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_SYSV4)
#endif
#ifndef SYSV2_SUPER_MAGIC
#define SYSV2_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_SYSV2)
#endif
#ifndef COH_SUPER_MAGIC
#define COH_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_COH)
#endif
#ifndef UFS_MAGIC
#define UFS_MAGIC 0x00011954
#endif
#ifndef UFS_MAGIC_BW
#define UFS_MAGIC_BW 0x0f242697
#endif
#ifndef UFS2_MAGIC
#define UFS2_MAGIC 0x19540119
#endif
#ifndef UFS_CIGAM
#define UFS_CIGAM 0x54190100
#endif
#ifndef UDF_SUPER_MAGIC
#define UDF_SUPER_MAGIC 0x15013346
#endif
#ifndef XFS_SB_MAGIC
#define XFS_SB_MAGIC 0x58465342
#endif
#ifndef FUSE_SUPER_MAGIC
#define FUSE_SUPER_MAGIC 0x65735546
#endif
#ifndef V9FS_MAGIC
#define V9FS_MAGIC 0x01021997
#endif
#ifndef CEPH_SUPER_MAGIC
#define CEPH_SUPER_MAGIC 0x00c36400
#endif
#ifndef CONFIGFS_MAGIC
#define CONFIGFS_MAGIC 0x62656570
#endif
#ifndef ECRYPTFS_SUPER_MAGIC
#define ECRYPTFS_SUPER_MAGIC 0xf15f
#endif
#ifndef EXOFS_SUPER_MAGIC
#define EXOFS_SUPER_MAGIC 0x5df5
#endif
#ifndef VXFS_SUPER_MAGIC
#define VXFS_SUPER_MAGIC 0xa501fcf5
#endif
#ifndef VXFS_OLT_MAGIC
#define VXFS_OLT_MAGIC 0xa504fcf5
#endif
#ifndef GFS2_MAGIC
#define GFS2_MAGIC 0x01161970
#endif
#ifndef HFS_SUPER_MAGIC
#define HFS_SUPER_MAGIC 0x4244
#endif
#ifndef HFSPLUS_SUPER_MAGIC
#define HFSPLUS_SUPER_MAGIC 0x482b
#endif
#ifndef LOGFS_MAGIC_U32
#define LOGFS_MAGIC_U32 0xc97e8168
#endif
#ifndef OCFS2_SUPER_MAGIC
#define OCFS2_SUPER_MAGIC 0x7461636f
#endif
#ifndef OMFS_MAGIC
#define OMFS_MAGIC 0xc2993d87
#endif
#ifndef UBIFS_SUPER_MAGIC
#define UBIFS_SUPER_MAGIC 0x24051905
#endif
#ifndef ROMFS_MAGIC
#define ROMFS_MAGIC 0x7275
#endif
#endif
#endif
|
/**
* \file
*/
#ifndef __LINUX_MAGIC_H
#define __LINUX_MAGIC_H
#if __linux__
#if HAVE_LINUX_MAGIC_H
#include <linux/magic.h>
#endif
#ifndef ADFS_SUPER_MAGIC
#define ADFS_SUPER_MAGIC 0xadf5
#endif
#ifndef AFFS_SUPER_MAGIC
#define AFFS_SUPER_MAGIC 0xadff
#endif
#ifndef AFS_SUPER_MAGIC
#define AFS_SUPER_MAGIC 0x5346414F
#endif
#ifndef AUTOFS_SUPER_MAGIC
#define AUTOFS_SUPER_MAGIC 0x0187
#endif
#ifndef AUTOFS_SBI_MAGIC
#define AUTOFS_SBI_MAGIC 0x6d4a556d
#endif
#ifndef CODA_SUPER_MAGIC
#define CODA_SUPER_MAGIC 0x73757245
#endif
#ifndef CRAMFS_MAGIC
#define CRAMFS_MAGIC 0x28cd3d45
#endif
#ifndef CRAMFS_MAGIC_WEND
#define CRAMFS_MAGIC_WEND 0x453dcd28
#endif
#ifndef DEBUGFS_MAGIC
#define DEBUGFS_MAGIC 0x64626720
#endif
#ifndef SYSFS_MAGIC
#define SYSFS_MAGIC 0x62656572
#endif
#ifndef SECURITYFS_MAGIC
#define SECURITYFS_MAGIC 0x73636673
#endif
#ifndef SELINUX_MAGIC
#define SELINUX_MAGIC 0xf97cff8c
#endif
#ifndef RAMFS_MAGIC
#define RAMFS_MAGIC 0x858458f6
#endif
#ifndef TMPFS_MAGIC
#define TMPFS_MAGIC 0x01021994
#endif
#ifndef HUGETLBFS_MAGIC
#define HUGETLBFS_MAGIC 0x958458f6
#endif
#ifndef SQUASHFS_MAGIC
#define SQUASHFS_MAGIC 0x73717368
#endif
#ifndef EFS_SUPER_MAGIC
#define EFS_SUPER_MAGIC 0x414A53
#endif
#ifndef EXT2_SUPER_MAGIC
#define EXT2_SUPER_MAGIC 0xEF53
#endif
#ifndef EXT3_SUPER_MAGIC
#define EXT3_SUPER_MAGIC 0xEF53
#endif
#ifndef XENFS_SUPER_MAGIC
#define XENFS_SUPER_MAGIC 0xabba1974
#endif
#ifndef EXT4_SUPER_MAGIC
#define EXT4_SUPER_MAGIC 0xEF53
#endif
#ifndef BTRFS_SUPER_MAGIC
#define BTRFS_SUPER_MAGIC 0x9123683E
#endif
#ifndef HPFS_SUPER_MAGIC
#define HPFS_SUPER_MAGIC 0xf995e849
#endif
#ifndef ISOFS_SUPER_MAGIC
#define ISOFS_SUPER_MAGIC 0x9660
#endif
#ifndef JFFS2_SUPER_MAGIC
#define JFFS2_SUPER_MAGIC 0x72b6
#endif
#ifndef JFS_SUPER_MAGIC
#define JFS_SUPER_MAGIC 0x3153464a
#endif
#ifndef ANON_INODE_FS_MAGIC
#define ANON_INODE_FS_MAGIC 0x09041934
#endif
#ifndef MINIX_SUPER_MAGIC
#define MINIX_SUPER_MAGIC 0x137F
#endif
#ifndef MINIX_SUPER_MAGIC2
#define MINIX_SUPER_MAGIC2 0x138F
#endif
#ifndef MINIX2_SUPER_MAGIC
#define MINIX2_SUPER_MAGIC 0x2468
#endif
#ifndef MINIX2_SUPER_MAGIC2
#define MINIX2_SUPER_MAGIC2 0x2478
#endif
#ifndef MINIX3_SUPER_MAGIC
#define MINIX3_SUPER_MAGIC 0x4d5a
#endif
#ifndef MSDOS_SUPER_MAGIC
#define MSDOS_SUPER_MAGIC 0x4d44
#endif
#ifndef NCP_SUPER_MAGIC
#define NCP_SUPER_MAGIC 0x564c
#endif
#ifndef NFS_SUPER_MAGIC
#define NFS_SUPER_MAGIC 0x6969
#endif
#ifndef OPENPROM_SUPER_MAGIC
#define OPENPROM_SUPER_MAGIC 0x9fa1
#endif
#ifndef PROC_SUPER_MAGIC
#define PROC_SUPER_MAGIC 0x9fa0
#endif
#ifndef QNX4_SUPER_MAGIC
#define QNX4_SUPER_MAGIC 0x002f
#endif
#ifndef REISERFS_SUPER_MAGIC
#define REISERFS_SUPER_MAGIC 0x52654973
#endif
#ifndef SMB_SUPER_MAGIC
#define SMB_SUPER_MAGIC 0x517B
#endif
#ifndef USBDEVICE_SUPER_MAGIC
#define USBDEVICE_SUPER_MAGIC 0x9fa2
#endif
#ifndef CGROUP_SUPER_MAGIC
#define CGROUP_SUPER_MAGIC 0x27e0eb
#endif
#ifndef FUTEXFS_SUPER_MAGIC
#define FUTEXFS_SUPER_MAGIC 0xBAD1DEA
#endif
#ifndef DEVPTS_SUPER_MAGIC
#define DEVPTS_SUPER_MAGIC 0x1cd1
#endif
#ifndef CIFS_MAGIC_NUMBER
#define CIFS_MAGIC_NUMBER 0xFF534D42
#endif
#ifndef BEFS_SUPER_MAGIC1
#define BEFS_SUPER_MAGIC1 0x42465331
#endif
#ifndef BEFS_SUPER_MAGIC2
#define BEFS_SUPER_MAGIC2 0xdd121031
#endif
#ifndef BEFS_SUPER_MAGIC3
#define BEFS_SUPER_MAGIC3 0x15b6830e
#endif
#ifndef BFS_MAGIC
#define BFS_MAGIC 0x1BADFACE
#endif
#ifndef NTFS_SB_MAGIC
#define NTFS_SB_MAGIC 0x5346544e
#endif
enum {
MONO_SYSV_FSTYPE_NONE = 0,
MONO_SYSV_FSTYPE_XENIX,
MONO_SYSV_FSTYPE_SYSV4,
MONO_SYSV_FSTYPE_SYSV2,
MONO_SYSV_FSTYPE_COH,
};
#ifndef SYSV_MAGIC_BASE
#define SYSV_MAGIC_BASE 0x012FF7B3
#endif
#ifndef XENIX_SUPER_MAGIC
#define XENIX_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_XENIX)
#endif
#ifndef SYSV4_SUPER_MAGIC
#define SYSV4_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_SYSV4)
#endif
#ifndef SYSV2_SUPER_MAGIC
#define SYSV2_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_SYSV2)
#endif
#ifndef COH_SUPER_MAGIC
#define COH_SUPER_MAGIC (SYSV_MAGIC_BASE+MONO_SYSV_FSTYPE_COH)
#endif
#ifndef UFS_MAGIC
#define UFS_MAGIC 0x00011954
#endif
#ifndef UFS_MAGIC_BW
#define UFS_MAGIC_BW 0x0f242697
#endif
#ifndef UFS2_MAGIC
#define UFS2_MAGIC 0x19540119
#endif
#ifndef UFS_CIGAM
#define UFS_CIGAM 0x54190100
#endif
#ifndef UDF_SUPER_MAGIC
#define UDF_SUPER_MAGIC 0x15013346
#endif
#ifndef XFS_SB_MAGIC
#define XFS_SB_MAGIC 0x58465342
#endif
#ifndef FUSE_SUPER_MAGIC
#define FUSE_SUPER_MAGIC 0x65735546
#endif
#ifndef V9FS_MAGIC
#define V9FS_MAGIC 0x01021997
#endif
#ifndef CEPH_SUPER_MAGIC
#define CEPH_SUPER_MAGIC 0x00c36400
#endif
#ifndef CONFIGFS_MAGIC
#define CONFIGFS_MAGIC 0x62656570
#endif
#ifndef ECRYPTFS_SUPER_MAGIC
#define ECRYPTFS_SUPER_MAGIC 0xf15f
#endif
#ifndef EXOFS_SUPER_MAGIC
#define EXOFS_SUPER_MAGIC 0x5df5
#endif
#ifndef VXFS_SUPER_MAGIC
#define VXFS_SUPER_MAGIC 0xa501fcf5
#endif
#ifndef VXFS_OLT_MAGIC
#define VXFS_OLT_MAGIC 0xa504fcf5
#endif
#ifndef GFS2_MAGIC
#define GFS2_MAGIC 0x01161970
#endif
#ifndef HFS_SUPER_MAGIC
#define HFS_SUPER_MAGIC 0x4244
#endif
#ifndef HFSPLUS_SUPER_MAGIC
#define HFSPLUS_SUPER_MAGIC 0x482b
#endif
#ifndef LOGFS_MAGIC_U32
#define LOGFS_MAGIC_U32 0xc97e8168
#endif
#ifndef OCFS2_SUPER_MAGIC
#define OCFS2_SUPER_MAGIC 0x7461636f
#endif
#ifndef OMFS_MAGIC
#define OMFS_MAGIC 0xc2993d87
#endif
#ifndef UBIFS_SUPER_MAGIC
#define UBIFS_SUPER_MAGIC 0x24051905
#endif
#ifndef ROMFS_MAGIC
#define ROMFS_MAGIC 0x7275
#endif
#endif
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/debug/di/rsthread.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
//
// File: rsthread.cpp
//
//*****************************************************************************
#include "stdafx.h"
#include "primitives.h"
#include <float.h>
#include <tls.h>
// Stack-based holder for RSPTRs that we allocated to give to the LS.
// If LS successfully takes ownership of them, then call SuppressRelease().
// Else, dtor will free them up.
// This is using a table protected by the ProcessLock().
template <class T>
class RsPtrHolder
{
T * m_pObject;
RsPointer<T> m_ptr;
public:
RsPtrHolder(T* pObject)
{
_ASSERTE(pObject != NULL);
m_ptr.AllocHandle(pObject->GetProcess(), pObject);
m_pObject = pObject;
}
// If owner didn't call SuppressRelease() to take ownership, then have dtor free it.
~RsPtrHolder()
{
if (!m_ptr.IsNull())
{
// @dbgtodo synchronization - push this up. Note that since this is in a dtor;
// need to order it well against RSLockHolder.
RSLockHolder lockHolder(m_pObject->GetProcess()->GetProcessLock());
T* pObjTest = m_ptr.UnWrapAndRemove(m_pObject->GetProcess());
(void)pObjTest; //prevent "unused variable" error from GCC
_ASSERTE(pObjTest == m_pObject);
}
}
RsPointer<T> Ptr()
{
return m_ptr;
}
void SuppressRelease()
{
m_ptr = RsPointer<T>::NullPtr();
}
};
/* ------------------------------------------------------------------------- *
* Managed Thread classes
* ------------------------------------------------------------------------- */
//---------------------------------------------------------------------------------------
//
// Instantiate a CordbThread object, which represents a managed thread.
//
// Arguments:
// process - non-null process object that this thread lives in.
// id - OS thread id of this thread.
// handle - OS Handle to the native thread in the debuggee.
//
//---------------------------------------------------------------------------------------
CordbThread::CordbThread(CordbProcess * pProcess, VMPTR_Thread vmThread) :
CordbBase(pProcess,
VmPtrToCookie(vmThread),
enumCordbThread),
m_pContext(NULL),
m_fContextFresh(false),
m_pAppDomain(NULL),
m_debugState(THREAD_RUN),
m_fFramesFresh(false),
m_fFloatStateValid(false),
m_floatStackTop(0),
m_fException(false),
m_EnCRemapFunctionIP(NULL),
m_userState(kInvalidUserState),
m_hCachedThread(INVALID_HANDLE_VALUE),
m_hCachedOutOfProcThread(INVALID_HANDLE_VALUE)
{
m_fHasUnhandledException = FALSE;
m_pExceptionRecord = NULL;
// Thread id may be a "fake" OS id for a CLRHosted thread.
m_vmThreadToken = vmThread;
// This id must be unique for the thread. V2 uses the current OS thread id.
// If we ever support fibers, then we need to use something more unique than that.
m_dwUniqueID = pProcess->GetDAC()->GetUniqueThreadID(vmThread); // may throw
LOG((LF_CORDB, LL_INFO1000, "CT::CT new thread 0x%p vmptr=0x%p id=0x%x\n",
this, m_vmThreadToken, m_dwUniqueID));
// Unique ID should never be 0.
_ASSERTE(m_dwUniqueID != 0);
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr();
m_vmExcepObjHandle = VMPTR_OBJECTHANDLE::NullPtr();
#if defined(_DEBUG)
for (unsigned int i = 0;
i < (sizeof(m_floatValues) / sizeof(m_floatValues[0]));
i++)
{
m_floatValues[i] = 0;
}
#endif
// Set AppDomain
VMPTR_AppDomain vmAppDomain = pProcess->GetDAC()->GetCurrentAppDomain(vmThread);
m_pAppDomain = pProcess->LookupOrCreateAppDomain(vmAppDomain);
_ASSERTE(m_pAppDomain != NULL);
}
CordbThread::~CordbThread()
{
// We've already been neutered, thus we don't need to call CleanupStack().
// That will have neutered + cleared frames + chains.
_ASSERTE(IsNeutered());
// Cleared in neuter
_ASSERTE(m_pContext == NULL);
_ASSERTE(m_hCachedThread == INVALID_HANDLE_VALUE);
_ASSERTE(m_pExceptionRecord == NULL);
}
// Neutered by the CordbProcess
void CordbThread::Neuter()
{
if (IsNeutered())
{
return;
}
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
delete m_pExceptionRecord;
m_pExceptionRecord = NULL;
// Neuter frames & Chains.
CleanupStack();
if (m_hCachedThread != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hCachedThread);
m_hCachedThread = INVALID_HANDLE_VALUE;
}
if( m_pContext != NULL )
{
delete [] m_pContext;
m_pContext = NULL;
}
ClearStackFrameCache();
CordbBase::Neuter();
}
HRESULT CordbThread::QueryInterface(REFIID id, void ** ppInterface)
{
if (id == IID_ICorDebugThread)
{
*ppInterface = static_cast<ICorDebugThread *>(this);
}
else if (id == IID_ICorDebugThread2)
{
*ppInterface = static_cast<ICorDebugThread2 *>(this);
}
else if (id == IID_ICorDebugThread3)
{
*ppInterface = static_cast<ICorDebugThread3*>(this);
}
else if (id == IID_ICorDebugThread4)
{
*ppInterface = static_cast<ICorDebugThread4*>(this);
}
else if (id == IID_ICorDebugThread5)
{
*ppInterface = static_cast<ICorDebugThread5*>(this);
}
else if (id == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown *>(static_cast<ICorDebugThread *>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
#ifdef _DEBUG
// Callback helper for code:CordbThread::DbgAssertThreadDeleted
//
// Arguments:
// vmThread - thread from enumeration of threads in the target.
// pUserData - the CordbThread for the thread that's deleted
//
// static
void CordbThread::DbgAssertThreadDeletedCallback(VMPTR_Thread vmThread, void * pUserData)
{
CordbThread * pThis = reinterpret_cast<CordbThread *>(pUserData);
INTERNAL_DAC_CALLBACK(pThis->GetProcess());
VMPTR_Thread vmThreadDelete = pThis->m_vmThreadToken;
CONSISTENCY_CHECK_MSGF((vmThread != vmThreadDelete),
("A Thread Exit event was sent, but it still shows up in the enumeration.\n vmThreadDelete=%p\n",
VmPtrToCookie(vmThreadDelete)));
}
// Debug-only helper to Assert that this thread is no longer discoverable in DacDbi enumerations
// This is designed to enforce the code:IDacDbiInterface#Enumeration rules for enumerations.
void CordbThread::DbgAssertThreadDeleted()
{
// Enumerate through all threads and ensure the deleted threads don't show up.
GetProcess()->GetDAC()->EnumerateThreads(
DbgAssertThreadDeletedCallback,
this);
}
#endif // _DEBUG
//---------------------------------------------------------------------------------------
// Mark that this thread has an unhandled native exception on it.
//
// Arguments
// pRecord - exception record of 2nd-chance exception that we're hijacking at. This will
// get deep copied into the CordbThread object in case it's needed for hijacking later.
//
// Notes:
// This bit is cleared in code:CordbThread::HijackForUnhandledException
void CordbThread::SetUnhandledNativeException(const EXCEPTION_RECORD * pExceptionRecord)
{
m_fHasUnhandledException = true;
if (m_pExceptionRecord == NULL)
{
m_pExceptionRecord = new EXCEPTION_RECORD(); // throws
}
memcpy(m_pExceptionRecord, pExceptionRecord, sizeof(EXCEPTION_RECORD));
}
//-----------------------------------------------------------------------------
// Returns true if the thread has an unhandled exception
// This is during the window after code:CordbThread::SetUnhandledNativeException is called,
// but before code:CordbThread::HijackForUnhandledException
bool CordbThread::HasUnhandledNativeException()
{
return m_fHasUnhandledException;
}
//---------------------------------------------------------------------------------------
// Determine if the thread's latest exception is a managed exception
//
// Notes:
// The CLR's UnhandledExceptionFilter has to make this same determination.
//
BOOL CordbThread::IsThreadExceptionManaged()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// A Thread's latest exception is managed if the VM Thread object has a managed object
// for the thread's Current Exception property. The CLR's Exception system is very diligent
// about tracking and clearing the thread's managed exception property. The runtime will clear
// the object if the exception is caught by unmanaged code (it can do this in the 2nd-pass).
// It's the presence of a throwable that makes the difference between a managed
// exception event and an unmanaged exception event.
VMPTR_OBJECTHANDLE vmObject = GetProcess()->GetDAC()->GetCurrentException(m_vmThreadToken);
bool fHasThrowable = !vmObject.IsNull();
return fHasThrowable;
}
// ----------------------------------------------------------------------------
// CordbThread::CreateCordbRegisterSet
//
// Description:
// This is a private hook for the shim to create a CordbRegisterSet for a ShimChain.
//
// Arguments:
// * pContext - the CONTEXT to be converted; this must be the leaf CONTEXT of a chain
// * fLeaf - whether the chain is the leaf chain or not
// * reason - the chain reason; this is needed for legacy reasons (see below)
// * ppRegSet - out parameter; return the newly created ICDRegisterSet
//
// Notes:
// * Note that the fQuickUnwind argument of the ctor of CordbRegisterSet is only true
// for an enter-managed chain. We need to keep the same behaviour here. That's why we need the
// chain reason.
//
void CordbThread::CreateCordbRegisterSet(DT_CONTEXT * pContext,
BOOL fLeaf,
CorDebugChainReason reason,
ICorDebugRegisterSet ** ppRegSet)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(GetProcess());
IfFailThrow(EnsureThreadIsAlive());
// The CordbRegisterSet is responsible for freeing this memory.
NewHolder<DebuggerREGDISPLAY> pDRD(new DebuggerREGDISPLAY());
// convert the CONTEXT to a DebuggerREGDISPLAY
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->ConvertContextToDebuggerRegDisplay(pContext, pDRD, fLeaf);
// create the CordbRegisterSet
RSInitHolder<CordbRegisterSet> pRS(new CordbRegisterSet(pDRD,
this,
(fLeaf == TRUE),
(reason == CHAIN_ENTER_MANAGED),
true));
pDRD.SuppressRelease();
pRS.TransferOwnershipExternal(ppRegSet);
}
// ----------------------------------------------------------------------------
// CordbThread::ConvertFrameForILMethodWithoutMetadata
//
// Description:
// This is a private hook for the shim to convert an ICDFrame into an ICDInternalFrame for a dynamic
// method. There are two cases where we need this:
// 1) In Arrowhead, dynamic methods are exposed as first-class stack frames, not internal frames. Thus,
// the shim needs a way to convert an ICDNativeFrame for a dynamic method in Arrowhead to an
// ICDInternalFrame of type STUBFRAME_LIGHTWEIGHT_FUNCTION in V2. Furthermore, IL stubs,
// which are also considered as a type of dynamic methods, are not exposed in V2 at all.
//
// 2) In V2, PrestubMethodFrames (PMFs) can be exposed as one of two things: a chain of type
// CHAIN_CLASS_INIT in most cases, or an internal frame of type STUBFRAME_LIGHTWEIGHT_FUNCTION if
// the method being jitted is a dynamic method. There is no way to make this distinction at the
// public ICD level.
//
// Arguments:
// * pNativeFrame - the native frame to be converted
// * ppInternalFrame - out parameter; the converted internal frame; could be NULL (see Notes below)
//
// Returns:
// Return TRUE if conversion has occurred. Note that even if the return value is TRUE, ppInternalFrame
// could be NULL. See Notes below.
//
// Notes:
// * There are two main types of dynamic methods: ones which are generated by the runtime itself for
// internal purposes (i.e. IL stubs), and ones which are generated by the user. ppInternalFrame
// is NULL for IL stubs. We need this functionality because IL stubs are not exposed at all in V2.
//
BOOL CordbThread::ConvertFrameForILMethodWithoutMetadata(ICorDebugFrame * pFrame,
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(GetProcess());
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
HRESULT hr = E_FAIL;
CordbFrame * pRealFrame = CordbFrame::GetCordbFrameFromInterface(pFrame);
CordbInternalFrame * pInternalFrame = pRealFrame->GetAsInternalFrame();
if (pInternalFrame != NULL)
{
// The input is an internal frame.
// Check its frame type.
CorDebugInternalFrameType type;
hr = pInternalFrame->GetFrameType(&type);
IfFailThrow(hr);
if (type != STUBFRAME_JIT_COMPILATION)
{
// No conversion is necessary.
return FALSE;
}
else
{
// We are indeed dealing with a PrestubMethodFrame.
return pInternalFrame->ConvertInternalFrameForILMethodWithoutMetadata(ppInternalFrame2);
}
}
else
{
// The input is a native frame.
CordbNativeFrame * pNativeFrame = pRealFrame->GetAsNativeFrame();
_ASSERTE(pNativeFrame != NULL);
return pNativeFrame->ConvertNativeFrameForILMethodWithoutMetadata(ppInternalFrame2);
}
}
//-----------------------------------------------------------------------------
// Hijack a thread at an unhandled exception. This lets it execute the
// CLR's Unhandled Exception Filter (which will send the managed 2nd-chance exception event)
//
// Notes:
// OS will not execute Unhandled Exception Filter (UEF) when debugger is attached.
// The CLR's UEF does useful work, like dispatching 2nd-chance managed exception event
// and allowing Func-eval and Continuable Exceptions for unhandled exceptions.
// So hijack the thread, and the hijack will then execute the CLR's UEF just
// like the OS would.
void CordbThread::HijackForUnhandledException()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
_ASSERTE(m_pExceptionRecord != NULL);
_ASSERTE(m_fHasUnhandledException);
m_fHasUnhandledException = false;
ULONG32 dwThreadId = GetVolatileOSThreadID();
// Note that the data-target is not atomic, and we have no rollback mechanism.
// We have to do several writes. If the data-target fails the writes half-way through the
// target will be inconsistent.
// We don't bother remembering the original context. LS hijack will have the
// context on its stack and will pass it to RS just like it does for filter-context.
GetProcess()->GetDAC()->Hijack(
m_vmThreadToken,
dwThreadId,
m_pExceptionRecord,
NULL, // LS will have the context.
0, // size of context
EHijackReason::kUnhandledException,
NULL,
NULL);
// Notify debugger to clear the exception.
// This will invoke the data-target.
GetProcess()->ContinueStatusChanged(dwThreadId, DBG_CONTINUE);
}
HRESULT CordbThread::GetProcess(ICorDebugProcess ** ppProcess)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppProcess, ICorDebugProcess **);
FAIL_IF_NEUTERED(this);
*ppProcess = GetProcess();
GetProcess()->ExternalAddRef();
return S_OK;
}
// Public implementation of ICorDebugThread::GetID
// Back in V1.0, GetID originally meant the OS thread ID that this managed thread was running on.
// In theory, that can change (fibers, logical thread scheduling, etc). However, in practice, in V1.0, it would
// not. Thus debuggers took a depedency on GetID being constant.
// In V2, this returns an opaque handle that is unique to this thread and stable for this thread's lifetime.
//
// Compare to code:CordbThread::GetVolatileOSThreadID, which returns the actual OS thread Id (which may change).
HRESULT CordbThread::GetID(DWORD * pdwThreadId)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(pdwThreadId, DWORD *);
FAIL_IF_NEUTERED(this);
*pdwThreadId = GetUniqueId();
return S_OK;
}
// Returns a unique ID that's stable for the life of this thread.
// In a non-hosted scenarios, this can be the OS thread id.
DWORD CordbThread::GetUniqueId()
{
return m_dwUniqueID;
}
// Implementation of public API, ICorDebugThread::GetHandle
// @dbgtodo ICDThread - deprecate in V3, offload to Shim
HRESULT CordbThread::GetHandle(HANDLE * phThreadHandle)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(phThreadHandle, HANDLE *);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (GetProcess()->GetShim() == NULL)
{
_ASSERTE(!"CordbThread::GetHandle() should be not be called on the new architecture");
*phThreadHandle = NULL;
return E_NOTIMPL;
}
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
HRESULT hr = S_OK;
EX_TRY
{
HANDLE hThread;
InternalGetHandle(&hThread); // throws on error
*phThreadHandle = hThread;
}
EX_CATCH_HRESULT(hr);
#else // FEATURE_DBGIPC_TRANSPORT_DI
// In the old SL implementation of Mac debugging, we return a thread handle faked up by the PAL on the Mac.
// The returned handle is meaningless. Here we explicitly return E_NOTIMPL. We plan to deprecate this
// function in Dev10 anyway.
//
// @dbgtodo Mac - Check with VS to see if they need the thread handle, e.g. for waiting on thread
// termination.
HRESULT hr = E_NOTIMPL;
#endif // !FEATURE_DBGIPC_TRANSPORT_DI
return hr;
}
// Note that we can return invalid handle
void CordbThread::InternalGetHandle(HANDLE * phThread)
{
INTERNAL_SYNC_API_ENTRY(GetProcess());
RefreshHandle(phThread);
}
//---------------------------------------------------------------------------------------
//
// This is a simple helper to check if a frame lives on the stack of the current thread.
//
// Arguments:
// pFrame - the stack frame to check
//
// Return Value:
// whether the frame lives on the stack of the current thread
//
// Assumption:
// This function assumes that the stack frames are valid, i.e. the stack frames have not been
// made dirty since the last stackwalk.
//
bool CordbThread::OwnsFrame(CordbFrame * pFrame)
{
// preliminary checking
if ( (pFrame != NULL) &&
(!pFrame->IsNeutered()) &&
(pFrame->m_pThread == this)
)
{
//
// Note that this is one of the two remaining places where we need to use the cached stack frames.
// Theoretically, since this is not an exact check anyway, we could just use the thread's stack
// range instead of looping through all the individual frames. However, since we need to maintain
// the stack frame cache for code:CordbThread::GetActiveFunctions, we might as well use the cache here.
//
// make sure this thread actually have frames to check
if (m_stackFrames.Count() != 0)
{
// get the stack range of this thread
FramePointer fpLeaf = (*(m_stackFrames.Get(0)))->GetFramePointer();
FramePointer fpRoot = (*(m_stackFrames.Get(m_stackFrames.Count() - 1)))->GetFramePointer();
FramePointer fpCurrent = pFrame->GetFramePointer();
// compare the stack range against the frame pointer of the specified frame
if (IsEqualOrCloserToLeaf(fpLeaf, fpCurrent) && IsEqualOrCloserToRoot(fpRoot, fpCurrent))
{
return true;
}
}
}
return false;
}
//---------------------------------------------------------------------------------------
//
// This routine is a internal helper function for ICorDebugThread2::GetTaskId.
//
// Arguments:
// pHandle - return thread handle here after fetching from the left side.
//
// Return Value:
// hr - It can fail with CORDBG_E_THREAD_NOT_SCHEDULED.
//
// Notes:
// This method will most likely be deprecated in V3.0. We can't always return the thread handle.
// For example, what does it mean to return a thread handle in remote debugging scenarios?
//
void CordbThread::RefreshHandle(HANDLE * phThread)
{
// here is where we will put code in to fetch the thread handle from the left side.
// This should only happen when CLRTask is hosted.
// Make sure that we are setting the right HR when thread is being switched out.
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
if (phThread == NULL)
{
ThrowHR(E_INVALIDARG);
}
*phThread = INVALID_HANDLE_VALUE;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
HANDLE hThread = pDAC->GetThreadHandle(m_vmThreadToken);
_ASSERTE(hThread != INVALID_HANDLE_VALUE);
PREFAST_ASSUME(hThread != NULL);
// need to dup handle here
if (hThread == m_hCachedOutOfProcThread)
{
*phThread = m_hCachedThread;
}
else
{
BOOL fSuccess = TRUE;
if (m_hCachedThread != INVALID_HANDLE_VALUE)
{
// clear the previous cache
CloseHandle(m_hCachedThread);
m_hCachedOutOfProcThread = INVALID_HANDLE_VALUE;
m_hCachedThread = INVALID_HANDLE_VALUE;
}
// now duplicate the out-of-proc handle
fSuccess = DuplicateHandle(GetProcess()->UnsafeGetProcessHandle(),
hThread,
GetCurrentProcess(),
&m_hCachedThread,
NULL,
FALSE,
DUPLICATE_SAME_ACCESS);
*phThread = m_hCachedThread;
if (fSuccess)
{
m_hCachedOutOfProcThread = hThread;
}
else
{
ThrowLastError();
}
}
} // CordbThread::RefreshHandle
//---------------------------------------------------------------------------------------
//
// This routine sets the debug state of a thread.
//
// Arguments:
// state - The debug state to set to.
//
// Return Value:
// Normal HRESULT semantics.
//
HRESULT CordbThread::SetDebugState(CorDebugThreadState state)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
LOG((LF_CORDB, LL_INFO1000, "CT::SDS: thread=0x%08x 0x%x, state=%d\n", this, m_id, state));
// @dbgtodo- , sync - decide on how to suspend a thread. V2 leverages synchronization
// (see below). For V3, do we just hard suspend the thread?
if (GetProcess()->GetShim() == NULL)
{
return E_NOTIMPL;
}
HRESULT hr = S_OK;
EX_TRY
{
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
// This lets the debugger suspend / resume threads. This is only called when when the
// target is already synchronized. That means all the threads are already suspended. So
// setting the suspend bit here just means that the debugger's continue logic won't resume
// this thread when we do a Continue.
if ((state != THREAD_SUSPEND) && (state != THREAD_RUN))
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->SetDebugState(m_vmThreadToken, state);
m_debugState = state;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::GetDebugState(CorDebugThreadState * pState)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(pState, CorDebugThreadState *);
*pState = m_debugState;
return S_OK;
}
// Public implementation of ICorDebugThread::GetUserState
// Arguments:
// pState - out parameter; return the user state
//
// Return Value:
// Return S_OK if the operation is successful.
// Return E_INVALIDARG if the out parameter is NULL.
// Return other failure HRs returned by the call to the DDI.
HRESULT CordbThread::GetUserState(CorDebugUserState * pState)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pState, CorDebugUserState *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (pState == NULL)
{
ThrowHR(E_INVALIDARG);
}
*pState = GetUserState();
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Retrieve the user state of the current thread.
//
// Notes:
// This caches results between continues. The cache is cleared when the target continues or is flushed.
// See code:CordbThread::CleanupStack, code:CordbThread::MarkStackFramesDirty
//
CorDebugUserState CordbThread::GetUserState()
{
if (m_userState == kInvalidUserState)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_userState = pDAC->GetUserState(m_vmThreadToken);
}
return m_userState;
}
//---------------------------------------------------------------------------------------
//
// This routine finds and returns the current exception off of a thread.
//
// Arguments:
// ppExceptionObject - OUT: Space for storing the exception found on the thread as a value.
//
// Return Value:
// Normal HRESULT semantics.
//
HRESULT CordbThread::GetCurrentException(ICorDebugValue ** ppExceptionObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppExceptionObject, ICorDebugValue **);
*ppExceptionObject = NULL;
EX_TRY
{
if (!HasException())
{
//
// Go to the LS and retrieve any exception object.
//
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetCurrentException(m_vmThreadToken);
if (vmObjHandle.IsNull())
{
hr = S_FALSE;
}
else
{
#if defined(_DEBUG)
// Since we know an exception is in progress on this thread, our assumption about the
// thread's current AppDomain should be correct
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
_ASSERTE(GetAppDomain()->GetADToken() == vmAppDomain);
#endif // _DEBUG
m_vmExcepObjHandle = vmObjHandle;
}
}
if (hr == S_OK)
{
// We've believe this assert may fire in the wild.
// We've seen m_vmExcepObjHandle null in retail builds after stack overflow.
_ASSERTE(!m_vmExcepObjHandle.IsNull());
ICorDebugReferenceValue * pRefValue = NULL;
hr = CordbReferenceValue::BuildFromGCHandle(GetAppDomain(), m_vmExcepObjHandle, &pRefValue);
*ppExceptionObject = pRefValue;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::ClearCurrentException()
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// This API is not implemented. For Continuable Exceptions, see InterceptCurrentException.
// @todo - should it return E_NOTIMPL?
return S_OK;
}
HRESULT CordbThread::CreateStepper(ICorDebugStepper ** ppStepper)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStepper, ICorDebugStepper **);
CordbStepper * pStepper = new (nothrow) CordbStepper(this, NULL);
if (pStepper == NULL)
{
return E_OUTOFMEMORY;
}
pStepper->ExternalAddRef();
*ppStepper = pStepper;
return S_OK;
}
//Returns true if current user state of a thread is USER_WAIT_SLEEP_JOIN
bool CordbThread::IsThreadWaitingOrSleeping()
{
CorDebugUserState userState = m_userState;
if (userState == kInvalidUserState)
{
//If m_userState is not ready, we'll read from DAC only part of it which
//is important for us now, bacuase we don't want possible side effects
//of reading USER_UNSAFE_POINT flag.
//We don't cache the value, because it's potentially incomplete.
IDacDbiInterface *pDAC = GetProcess()->GetDAC();
userState = pDAC->GetPartialUserState(m_vmThreadToken);
}
return (userState & USER_WAIT_SLEEP_JOIN) != 0;
}
//----------------------------------------------------------------------------
// check if the thread is dead
//
// Returns: true if the thread is dead.
//
bool CordbThread::IsThreadDead()
{
return GetProcess()->GetDAC()->IsThreadMarkedDead(m_vmThreadToken);
}
// Helper to return CORDBG_E_BAD_THREAD_STATE if IsThreadDead
//
// Notes:
// IsThreadDead queries the VM Thread's actual state, regardless of what ExitThread
// callbacks have or have not been sent / queued / dispatched.
HRESULT CordbThread::EnsureThreadIsAlive()
{
if (IsThreadDead())
{
return CORDBG_E_BAD_THREAD_STATE;
}
else
{
return S_OK;
}
}
// ----------------------------------------------------------------------------
// CordbThread::EnumerateChains
//
// Description:
// Create and return an ICDChainEnum for enumerating chains on the stack. Since chains have been
// deprecated in Arrowhead, this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChains - out parameter; return the ICDChainEnum
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChains is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbThread::EnumerateChains(ICorDebugChainEnum ** ppChains)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChains, ICorDebugChainEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppChains = NULL;
if (GetProcess()->GetShim() != NULL)
{
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
// use the shim to create an ICDChainEnum
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSW->EnumerateChains(ppChains);
}
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveChain
//
// Description:
// Retrieve the leaf chain on this thread. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the leaf chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbThread::GetActiveChain(ICorDebugChain ** ppChain)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChain, ICorDebugChain **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppChain = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
// use the shim to retrieve the leaf chain
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveChain(ppChain);
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveFrame
//
// Description:
// Retrieve the leaf frame on this thread. Unfortunately, this is one of the cases where we need to
// do different things depending on whether there is a shim. See the Notes below.
//
// Arguments:
// * ppFrame - out parameter; return the leaf frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Also return whatever CreateStackWalk() and GetFrame() return if they fail.
//
// Notes:
// In V2, we return NULL if the leaf frame is not in the leaf chain, i.e. if the leaf chain is
// empty. Note that managed chains are never empty. Also, in V2 it is possible that this API
// will return an internal frame as the active frame on a thread.
//
// The Arrowhead implementation two breaking changes:
// 1) It never returns an internal frame.
// 2) We return a frame if the leaf frame is managed. Otherwise, we return NULL.
//
HRESULT CordbThread::GetActiveFrame(ICorDebugFrame ** ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppFrame = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveFrame(ppFrame);
}
else
{
// This is the Arrowhead case. We could call RefreshStack() here, but since we only need the
// leaf frame, there is no point in walking the entire stack.
RSExtSmartPtr<ICorDebugStackWalk> pSW;
hr = CreateStackWalk(&pSW);
IfFailThrow(hr);
hr = pSW->GetFrame(ppFrame);
IfFailThrow(hr);
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveRegister
//
// Description:
// In V2, retrieve the ICDRegisterSet for the leaf chain. In Arrowhead, retrieve the ICDRegisterSet
// for the leaf CONTEXT.
//
// Arguments:
// * ppRegisters - out parameter; return the ICDRegister
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Also return whatever CreateStackWalk() and GetContext() return if they fail.
//
HRESULT CordbThread::GetRegisterSet(ICorDebugRegisterSet ** ppRegisters)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppRegisters, ICorDebugRegisterSet **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppRegisters = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
// use the shim to retrieve the active ICDRegisterSet
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveRegisterSet(ppRegisters);
}
else
{
// This is the Arrowhead case. We could call RefreshStack() here, but since we only need the
// leaf frame, there is no point in walking the entire stack.
RSExtSmartPtr<ICorDebugStackWalk> pSW;
hr = CreateStackWalk(&pSW);
IfFailThrow(hr);
// retrieve the leaf CONTEXT
DT_CONTEXT ctx;
hr = pSW->GetContext(CONTEXT_FULL, sizeof(ctx), NULL, reinterpret_cast<BYTE *>(&ctx));
IfFailThrow(hr);
// the CordbRegisterSet is responsible for freeing this memory
NewHolder<DebuggerREGDISPLAY> pDRD(new DebuggerREGDISPLAY());
// convert the CONTEXT to a DebuggerREGDISPLAY
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->ConvertContextToDebuggerRegDisplay(&ctx, pDRD, true);
// create the CordbRegisterSet
RSInitHolder<CordbRegisterSet> pRS(new CordbRegisterSet(pDRD,
this,
true, // active
false, // !fQuickUnwind
true)); // own DRD memory
pDRD.SuppressRelease();
pRS.TransferOwnershipExternal(ppRegisters);
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::CreateEval(ICorDebugEval ** ppEval)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppEval, ICorDebugEval **);
CordbEval * pEval = new (nothrow) CordbEval(this);
if (pEval == NULL)
{
return E_OUTOFMEMORY;
}
pEval->ExternalAddRef();
*ppEval = static_cast<ICorDebugEval *>(pEval);
return S_OK;
}
// DAC check
// Double check our results w/ DAC.
// This gives DAC some great coverage.
// Given an IP and the md token (that the RS obtained), use DAC to lookup the md token. Then
// we can compare DAC & the RS and make sure DACs working.
void CheckAgainstDAC(CordbFunction * pFunc, void * pIP, mdMethodDef mdExpected)
{
// This is a hook to add DAC checks against a {function, ip}
}
//---------------------------------------------------------------------------------------
//
// Internal function to build up a stack trace.
//
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// Process is stopped.
//
// Notes:
// Send a IPC events to the LS to build up the stack.
//
//---------------------------------------------------------------------------------------
void CordbThread::RefreshStack()
{
THROW_IF_NEUTERED(this);
// We must have the Stop-Go lock to change our thread's stack-state.
// Also, our caller should have guaranteed that we're synced. And b/c we hold the stop-go lock,
// that shouldn't have changed.
// INTERNAL_SYNC_API_ENTRY() checks that we have the lock and that we are synced.
INTERNAL_SYNC_API_ENTRY(GetProcess());
// bail out early if the stack hasn't changed
if (m_fFramesFresh)
{
return;
}
HRESULT hr = S_OK;
//
// Clean up old snapshot.
//
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// clear the stack frame cache
ClearStackFrameCache();
//
// If we don't have a debugger thread token, then this thread has never
// executed managed code and we have no frame information for it.
//
if (m_vmThreadToken.IsNull())
{
ThrowHR(E_FAIL);
}
// walk the stack using the V3 API and populate the stack frame cache
RSInitHolder<CordbStackWalk> pSW(new CordbStackWalk(this));
pSW->Init();
do
{
RSExtSmartPtr<ICorDebugFrame> pIFrame;
hr = pSW->GetFrame(&pIFrame);
IfFailThrow(hr);
if (pIFrame != NULL)
{
// add the stack frame to the cache
CordbFrame ** ppCFrame = m_stackFrames.AppendThrowing();
*ppCFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
// Now that we have saved the pointer, increment the ref count.
// This has to match the InternalRelease() in code:CordbThread::ClearStackFrameCache.
(*ppCFrame)->InternalAddRef();
}
// advance to the next frame
hr = pSW->Next();
IfFailThrow(hr);
}
while (hr != CORDBG_S_AT_END_OF_STACK);
m_fFramesFresh = true;
}
//---------------------------------------------------------------------------------------
//
// This function is used to invalidate and clean up the cached stack trace.
//
void CordbThread::CleanupStack()
{
_ASSERTE(GetProcess()->GetProcessLock()->HasLock());
// Neuter outstanding CordbChainEnums, CordbFrameEnums, some CordbTypeEnums, and some CordbValueEnums.
m_RefreshStackNeuterList.NeuterAndClear(GetProcess());
m_fContextFresh = false; // invalidate the cached active CONTEXT
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr(); // set the LS pointer to the active CONTEXT to NULL
m_fFramesFresh = false; // invalidate the cached stack trace (frames & chains)
m_userState = kInvalidUserState; // clear the cached user state
// tell the shim to flush its caches as well
if (GetProcess()->GetShim() != NULL)
{
GetProcess()->GetShim()->NotifyOnStackInvalidate();
}
}
// Notifying the thread that the process is being continued.
// This will cause our caches to get invalidated without actually cleaning the caches.
void CordbThread::MarkStackFramesDirty()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// invalidate the cached floating point state
m_fFloatStateValid = false;
// This flag is only true between the window when we get an exception callback and
// when we call continue. Since this function is only called when we continue, we
// need to reset this flag here. Note that in the case of an outstanding funceval,
// we'll set this flag again when the funceval is completed.
m_fException = false;
// Clear the stashed EnC remap IP address if any
// This is important to ensure we don't try to write into LS memory which is no longer
// being used to hold the remap IP.
m_EnCRemapFunctionIP = NULL;
m_fContextFresh = false; // invalidate the cached active CONTEXT
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr(); // set the LS pointer to the active CONTEXT to NULL
m_fFramesFresh = false; // invalidate the cached stack trace (frames & chains)
m_userState = kInvalidUserState; // clear the cached user state
m_RefreshStackNeuterList.NeuterAndClear(GetProcess());
// tell the shim to flush its caches as well
if (GetProcess()->GetShim() != NULL)
{
GetProcess()->GetShim()->NotifyOnStackInvalidate();
}
}
// Set that there's an outstanding exception on this thread.
// This can be called when the process object receives an exception notification.
// This is cleared in code:CordbThread::MarkStackFramesDirty.
void CordbThread::SetExInfo(VMPTR_OBJECTHANDLE vmExcepObjHandle)
{
m_fException = true;
m_vmExcepObjHandle = vmExcepObjHandle;
// CordbThread::GetCurrentException assumes that we always have a m_vmExcepObjHandle when at an exception.
// Push that assert up here.
_ASSERTE(!m_vmExcepObjHandle.IsNull());
}
// ----------------------------------------------------------------------------
// CordbThread::FindFrame
//
// Description:
// Given a FramePointer, find the matching CordbFrame.
//
// Arguments:
// * ppFrame - out parameter; the CordbFrame to be returned
// * fp - the input FramePointer
//
// Return Value:
// Return S_OK on success.
// Return E_FAIL on failure.
//
// Assumptions:
// * This function is only called from the shim.
//
// Notes:
// * Currently this function is only used by the shim to map the FramePointer it gets via the
// DB_IPCE_EXCEPTION_CALLBACK2 callback. When we figure out what to do with the
// DB_IPCE_EXCEPTION_CALLBACK2, we should remove this function.
//
HRESULT CordbThread::FindFrame(ICorDebugFrame ** ppFrame, FramePointer fp)
{
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
_ASSERTE(ppFrame != NULL);
*ppFrame = NULL;
_ASSERTE(GetProcess()->GetShim() != NULL);
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
for (UINT32 i = 0; i < pSSW->GetFrameCount(); i++)
{
ICorDebugFrame * pIFrame = pSSW->GetFrame(i);
CordbFrame * pCFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
#if defined(HOST_64BIT)
// On 64-bit we can simply compare the FramePointer.
if (pCFrame->GetFramePointer() == fp)
#else // !HOST_64BIT
// On other platforms, we need to do a more elaborate check.
if (pCFrame->IsContainedInFrame(fp))
#endif // HOST_64BIT
{
*ppFrame = pIFrame;
(*ppFrame)->AddRef();
return S_OK;
}
}
// Cannot find the frame.
return E_FAIL;
}
#if defined(CROSS_COMPILE) && (defined(TARGET_ARM64) || defined(TARGET_ARM))
extern "C" double FPFillR8(void* pFillSlot)
{
_ASSERTE(!"nyi for platform");
return 0;
}
#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_ARM)
extern "C" double FPFillR8(void* pFillSlot);
#endif
#if defined(TARGET_X86)
// CordbThread::Get32bitFPRegisters
// Converts the values in the floating point register area of the context to real number values. See
// code:CordbThread::LoadFloatState for more details.
// Arguments:
// input: pContext
// output: none (initializes m_floatValues)
void CordbThread::Get32bitFPRegisters(CONTEXT * pContext)
{
// On X86, we get the values by saving our current FPU state, loading
// the other thread's FPU state into our own, saving out each
// value off the FPU stack, and then restoring our FPU state.
//
FLOATING_SAVE_AREA floatarea = pContext->FloatSave; // copy FloatSave
//
// Take the TOP out of the FPU status word. Note, our version of the
// stack runs from 0->7, not 7->0...
//
unsigned int floatStackTop = 7 - ((floatarea.StatusWord & 0x3800) >> 11);
FLOATING_SAVE_AREA currentFPUState;
#ifdef _MSC_VER
__asm fnsave currentFPUState // save the current FPU state.
#else
__asm__ __volatile__
(
" fnsave %0\n" \
: "=m"(currentFPUState)
);
#endif
floatarea.StatusWord &= 0xFF00; // remove any error codes.
floatarea.ControlWord |= 0x3F; // mask all exceptions.
// the x86 FPU stores real numbers as 10 byte values in IEEE format. Here we use
// the hardware to convert these to doubles.
// @dbgtodo Microsoft crossplat: the conversion from a series of bytes to a floating
// point value will need to be done with an explicit conversion routine to unpack
// the IEEE format and compute the real number value represented.
#ifdef _MSC_VER
__asm
{
fninit
frstor floatarea ;; reload the threads FPU state.
}
#else
__asm__
(
" fninit\n" \
" frstor %0\n" \
: /* no outputs */
: "m"(floatarea)
);
#endif
unsigned int i;
for (i = 0; i <= floatStackTop; i++)
{
double td = 0.0;
__asm fstp td // copy out the double
m_floatValues[i] = td;
}
#ifdef _MSC_VER
__asm
{
fninit
frstor currentFPUState ;; restore our saved FPU state.
}
#else
__asm__
(
" fninit\n" \
" frstor %0\n" \
: /* no outputs */
: "m"(currentFPUState)
);
#endif
m_fFloatStateValid = true;
m_floatStackTop = floatStackTop;
} // CordbThread::Get32bitFPRegisters
#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_ARM)
// CordbThread::Get64bitFPRegisters
// Converts the values in the floating point register area of the context to real number values. See
// code:CordbThread::LoadFloatState for more details.
// Arguments:
// input: pFPRegisterBase - starting address of the floating point register storage of the CONTEXT
// registerSize - the size of a floating point register
// start - the index into m_floatValues where we start initializing. For amd64, we start
// at the beginning, but for ia64, the first two registers have fixed values,
// so we start at two.
// nRegisters - the number of registers to be initialized
// output: none (initializes m_floatValues)
void CordbThread::Get64bitFPRegisters(FPRegister64 * rgContextFPRegisters, int start, int nRegisters)
{
// make sure no one has changed the type definition for 64-bit FP registers
_ASSERTE(sizeof(FPRegister64) == 16);
// We convert and copy all the fp registers.
for (int reg = start; reg < nRegisters; reg++)
{
// @dbgtodo Microsoft crossplat: the conversion from a FLOAT128 or M128A struct to a floating
// point value will need to be done with an explicit conversion routine instead
// of the call to FPFillR8
m_floatValues[reg] = FPFillR8(&rgContextFPRegisters[reg - start]);
}
} // CordbThread::Get64bitFPRegisters
#endif // TARGET_X86
// CordbThread::LoadFloatState
// Initializes the float state members of this instance of CordbThread. This function gets the context and
// converts the floating point values from their context representation to a real number value. Floating
// point numbers are represented in IEEE format on all current platforms. We store them in the context as a
// pair of 64-bit integers (IA64 and AMD64) or a series of bytes (x86). Rather than unpack them explicitly
// and do the appropriate mathematical operations to produce the corresponding floating point value, we let
// the hardware do it instead. We load a floating point register with the representation from the context
// and then store it in m_floatValues. Using the hardware is obviously a huge perf win. If/when we make
// cross-plat work, we should at least code necessary conversion routines in assembly. Even with cross-plat,
// we can probably still use the hardware in most cases, as long as the size is appropriate.
//
// Arguments: none
// Return Value: none (initializes data members)
// Note: Throws
void CordbThread::LoadFloatState()
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
DT_CONTEXT tempContext;
GetProcess()->GetDAC()->GetContext(m_vmThreadToken, &tempContext);
#if defined(TARGET_X86)
Get32bitFPRegisters((CONTEXT*) &tempContext);
#elif defined(TARGET_AMD64)
// we have no fixed-value registers, so we begin with the first one and initialize all 16
Get64bitFPRegisters((FPRegister64*) &(tempContext.Xmm0), 0, 16);
#elif defined(TARGET_ARM64)
Get64bitFPRegisters((FPRegister64*) &(tempContext.V), 0, 32);
#elif defined (TARGET_ARM)
Get64bitFPRegisters((FPRegister64*) &(tempContext.D), 0, 32);
#else
_ASSERTE(!"nyi for platform");
#endif // !TARGET_X86
m_fFloatStateValid = true;
} // CordbThread::LoadFloatState
const bool SetIP_fCanSetIPOnly = TRUE;
const bool SetIP_fSetIP = FALSE;
const bool SetIP_fIL = TRUE;
const bool SetIP_fNative = FALSE;
//---------------------------------------------------------------------------------------
//
// Issues a SetIP command to the left-side and returns the result
//
// Arguments:
// fCanSetIPOnly - TRUE if only to do the setip command and not refresh stacks as well.
// debuggerModule - LS token to the debugger module.
// mdMethod - Metadata token for the method.
// nativeCodeJITInfoToken - LS token to the DebuggerJitInfo for the method.
// offset - Offset within the method to set the IP to.
// fIsIl - Is this an IL offset?
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::SetIP(bool fCanSetIPOnly,
CordbNativeCode * pNativeCode,
SIZE_T offset,
bool fIsIL)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VMPTR_DomainAssembly vmDomainAssembly = pNativeCode->GetModule()->m_vmDomainAssembly;
_ASSERTE(!vmDomainAssembly.IsNull());
// If this thread is stopped due to an exception, never allow SetIP
if (HasException())
{
return (CORDBG_E_SET_IP_NOT_ALLOWED_ON_EXCEPTION);
}
DebuggerIPCEvent event;
GetProcess()->InitIPCEvent(&event, DB_IPCE_SET_IP, true, GetAppDomain()->GetADToken());
event.SetIP.fCanSetIPOnly = fCanSetIPOnly;
event.SetIP.vmThreadToken = m_vmThreadToken;
event.SetIP.vmDomainAssembly = vmDomainAssembly;
event.SetIP.mdMethod = pNativeCode->GetMetadataToken();
event.SetIP.vmMethodDesc = pNativeCode->GetVMNativeCodeMethodDescToken();
event.SetIP.startAddress = pNativeCode->GetAddress();
event.SetIP.offset = offset;
event.SetIP.fIsIL = fIsIL;
LOG((LF_CORDB, LL_INFO10000, "[%x] CT::SIP: Info:thread:0x%x"
"mod:0x%x MethodDef:0x%x offset:0x%x il?:0x%x\n",
GetCurrentThreadId(),
VmPtrToCookie(m_vmThreadToken),
VmPtrToCookie(vmDomainAssembly),
pNativeCode->GetMetadataToken(),
offset,
fIsIL));
LOG((LF_CORDB, LL_INFO10000, "[%x] CT::SIP: sizeof(DebuggerIPCEvent):0x%x **********\n",
sizeof(DebuggerIPCEvent)));
HRESULT hr = GetProcess()->m_cordb->SendIPCEvent(GetProcess(), &event, sizeof(DebuggerIPCEvent));
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_SET_IP);
if (!fCanSetIPOnly && SUCCEEDED(event.hr))
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
CleanupStack();
}
return ErrWrapper(event.hr);
}
// Get the context from a thread in managed code.
// This thread should be stopped gracefully by the LS in managed code.
HRESULT CordbThread::GetManagedContext(DT_CONTEXT ** ppContext)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
if (ppContext == NULL)
{
ThrowHR(E_INVALIDARG);
}
*ppContext = NULL;
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Each CordbThread object allocates the m_pContext's DT_CONTEXT structure only once, the first time GetContext is
// invoked.
if(m_pContext == NULL)
{
// Throw if the allocation fails.
m_pContext = reinterpret_cast<DT_CONTEXT *>(new BYTE[sizeof(DT_CONTEXT)]);
}
HRESULT hr = S_OK;
if (m_fContextFresh == false)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_vmLeftSideContext = pDAC->GetManagedStoppedContext(m_vmThreadToken);
if (m_vmLeftSideContext.IsNull())
{
// We don't have a context in managed code.
ThrowHR(CORDBG_E_CONTEXT_UNVAILABLE);
}
else
{
LOG((LF_CORDB, LL_INFO1000, "CT::GC: getting context from left side pointer.\n"));
// The thread we're examining IS handling an exception, So grab the CONTEXT of the exception, NOT the
// currently executing thread's CONTEXT (which would be the context of the exception handler.)
hr = GetProcess()->SafeReadThreadContext(m_vmLeftSideContext.ToLsPtr(), m_pContext);
IfFailThrow(hr);
}
// m_fContextFresh should be marked false when CleanupStack, MarkAllFramesAsDirty, etc get called.
m_fContextFresh = true;
}
_ASSERTE(SUCCEEDED(hr));
(*ppContext) = m_pContext;
return hr;
}
HRESULT CordbThread::SetManagedContext(DT_CONTEXT * pContext)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if(pContext == NULL)
{
ThrowHR(E_INVALIDARG);
}
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_vmLeftSideContext = pDAC->GetManagedStoppedContext(m_vmThreadToken);
if (m_vmLeftSideContext.IsNull())
{
ThrowHR(CORDBG_E_CONTEXT_UNVAILABLE);
}
else
{
// The thread we're examining IS handling an exception, So set the CONTEXT of the exception, NOT the currently
// executing thread's CONTEXT (which would be the context of the exception handler.)
//
// Note: we read the remote context and merge the new one in, then write it back. This ensures that we don't
// write too much information into the remote process.
DT_CONTEXT tempContext = { 0 };
hr = GetProcess()->SafeReadThreadContext(m_vmLeftSideContext.ToLsPtr(), &tempContext);
IfFailThrow(hr);
CORDbgCopyThreadContext(&tempContext, pContext);
hr = GetProcess()->SafeWriteThreadContext(m_vmLeftSideContext.ToLsPtr(), &tempContext);
IfFailThrow(hr);
// @todo - who's updating the regdisplay to guarantee that's in sync w/ our new context?
}
_ASSERTE(SUCCEEDED(hr));
if (m_fContextFresh && (m_pContext != NULL))
{
*m_pContext = *pContext;
}
return hr;
}
HRESULT CordbThread::GetAppDomain(ICorDebugAppDomain ** ppAppDomain)
{
// We don't use the cached m_pAppDomain pointer here because it might be incorrect
// if the thread has transitioned to another domain but we haven't received any events
// from it yet. So we need to ask the left-side for the current domain.
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
ValidateOrThrow(ppAppDomain);
*ppAppDomain = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
CordbAppDomain * pAppDomain = NULL;
hr = GetCurrentAppDomain(&pAppDomain);
IfFailThrow(hr);
_ASSERTE( pAppDomain != NULL );
*ppAppDomain = static_cast<ICorDebugAppDomain *> (pAppDomain);
pAppDomain->ExternalAddRef();
}
}
PUBLIC_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Issues a get appdomain command and returns it.
//
// Arguments:
// ppAppDomain - OUT: Space for storing the app domain of this thread.
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::GetCurrentAppDomain(CordbAppDomain ** ppAppDomain)
{
FAIL_IF_NEUTERED(this);
INTERNAL_API_ENTRY(GetProcess());
*ppAppDomain = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// @dbgtodo ICDThread - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
CordbAppDomain * pAppDomain = GetProcess()->LookupOrCreateAppDomain(vmAppDomain);
_ASSERTE(pAppDomain != NULL); // we should be aware of all AppDomains
*ppAppDomain = pAppDomain;
}
}
EX_CATCH_HRESULT(hr);
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Issues a get_object command and returns the thread object as a value.
//
// Arguments:
// ppThreadObject - OUT: Space for storing the thread object of this thread as a value
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::GetObject(ICorDebugValue ** ppThreadObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppThreadObject, ICorDebugObjectValue **);
// Default to NULL
*ppThreadObject = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// @dbgtodo ICDThread - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetThreadObject(m_vmThreadToken);
if (vmObjHandle.IsNull())
{
ThrowHR(E_FAIL);
}
// We create the object relative to the current AppDomain of the thread
// Thread objects aren't really agile (eg. their m_Context field is domain-bound and
// fixed up manually during transitions). This means that a thread object can only
// be used in the domain the thread was in when the object was created.
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
CordbAppDomain * pThreadCurrentDomain = NULL;
pThreadCurrentDomain = GetProcess()->m_appDomains.GetBaseOrThrow(VmPtrToCookie(vmAppDomain));
_ASSERTE(pThreadCurrentDomain != NULL); // we should be aware of all AppDomains
if (pThreadCurrentDomain == NULL)
{
// fall back to some domain to avoid crashes in retail -
// safe enough for getting the name of the thread etc.
pThreadCurrentDomain = GetProcess()->GetDefaultAppDomain();
}
lockHolder.Release();
ICorDebugReferenceValue * pRefValue = NULL;
hr = CordbReferenceValue::BuildFromGCHandle(pThreadCurrentDomain, vmObjHandle, &pRefValue);
*ppThreadObject = pRefValue;
}
}
EX_CATCH_HRESULT(hr);
// Don't return a null pointer with S_OK.
_ASSERTE((hr != S_OK) || (*ppThreadObject != NULL));
return hr;
}
/*
*
* GetActiveFunctions
*
* This routine is the interface function for ICorDebugThread2::GetActiveFunctions.
*
* Parameters:
* cFunctions - the count of the number of COR_ACTIVE_FUNCTION in pFunctions. Zero
* indicates no pFunctions buffer.
* pcFunctions - pointer to storage for the count of elements filled in to pFunctions, or
* count that would be needed to fill pFunctions, if cFunctions is 0.
* pFunctions - buffer to store results. May be NULL.
*
* Return Value:
* HRESULT from the helper routine.
*
*/
HRESULT CordbThread::GetActiveFunctions(
ULONG32 cFunctions,
ULONG32 * pcFunctions,
COR_ACTIVE_FUNCTION pFunctions[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ULONG32 index;
ULONG32 iRealIndex;
ULONG32 last;
if (((cFunctions != 0) && (pFunctions == NULL)) || (pcFunctions == NULL))
{
return E_INVALIDARG;
}
//
// Default to 0
//
*pcFunctions = 0;
// @dbgtodo synchronization - The ATT macro may slip the thread to a sychronized state. The
// synchronization feature crew needs to figure out what to do here. Then we can use the
// PUBLIC_API_BEGIN macro in this function.
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
if (IsThreadDead())
{
//
// Return zero active functions on this thread.
//
hr = S_OK;
}
else
{
ULONG32 cAllFrames = 0; // the total number of frames (stack frames and internal frames)
ULONG32 cStackFrames = 0; // the number of stack frames
ShimStackWalk * pSSW = NULL;
if (GetProcess()->GetShim() != NULL)
{
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
// initialize the frame counts
cAllFrames = pSSW->GetFrameCount();
for (ULONG32 i = 0; i < cAllFrames; i++)
{
// filter out internal frames
if (CordbFrame::GetCordbFrameFromInterface(pSSW->GetFrame(i))->GetAsNativeFrame() != NULL)
{
cStackFrames += 1;
}
}
_ASSERTE(cStackFrames <= cAllFrames);
}
else
{
RefreshStack();
cAllFrames = m_stackFrames.Count();
cStackFrames = cAllFrames;
// In Arrowhead, the stackwalking API doesn't return internal frames,
// so the frame counts should be equal.
_ASSERTE(cStackFrames == cAllFrames);
}
*pcFunctions = cStackFrames;
//
// If all we want is the count, then return that.
//
if ((pFunctions == NULL) || (cFunctions == 0))
{
hr = S_OK;
}
else
{
//
// Now go down list of frames, storing information
//
last = (cFunctions < cStackFrames) ? cFunctions : cStackFrames;
iRealIndex = 0;
index =0;
while((index < last) && (iRealIndex < cAllFrames))
{
CordbFrame * pThisFrame = NULL;
if (GetProcess()->GetShim())
{
_ASSERTE(pSSW != NULL);
pThisFrame = CordbFrame::GetCordbFrameFromInterface(pSSW->GetFrame(iRealIndex));
}
else
{
pThisFrame = *(m_stackFrames.Get(iRealIndex));
_ASSERTE(pThisFrame->GetAsNativeFrame() != NULL);
}
iRealIndex++;
CordbNativeFrame * pNativeFrame = pThisFrame->GetAsNativeFrame();
if (pNativeFrame == NULL)
{
// filter out internal frames
_ASSERTE(pThisFrame->GetAsInternalFrame() != NULL);
continue;
}
//
// Fill in the easy stuff.
//
CordbFunction * pFunction;
pFunction = (static_cast<CordbFrame *>(pNativeFrame))->GetFunction();
ASSERT(pFunction != NULL);
hr = pFunction->QueryInterface(IID_ICorDebugFunction2,
reinterpret_cast<void **>(&(pFunctions[index].pFunction)));
ASSERT(!FAILED(hr));
CordbModule * pModule = pFunction->GetModule();
pFunctions[index].pModule = pModule;
pModule->ExternalAddRef();
CordbAppDomain * pAppDomain = pNativeFrame->GetCurrentAppDomain();
pFunctions[index].pAppDomain = pAppDomain;
pAppDomain->ExternalAddRef();
pFunctions[index].flags = 0;
//
// Now go to the IL frame (if one exists) to the get the offset.
//
CordbJITILFrame * pJITILFrame;
pJITILFrame = pNativeFrame->m_JITILFrame;
if (pJITILFrame != NULL)
{
hr = pJITILFrame->GetIP(&(pFunctions[index].ilOffset), NULL);
ASSERT(!FAILED(hr));
}
else
{
pFunctions[index].ilOffset = (DWORD) NO_MAPPING;
}
// Update to the next count.
index++;
}
// @todo - The spec says that pcFunctions == # of elements in pFunctions,
// but the behavior here is that it's always the total.
// If we want to fix that, we should uncomment the assignment here:
//*pcFunctions = index;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This is the entry point for continuable exceptions.
// It implements ICorDebugThread2::InterceptCurrentException.
//
// Arguments:
// pFrame - the stack frame to intercept at
//
// Return Value:
// HRESULT indicating success or failure
//
// Notes:
// Since we cannot intercept an exception at an internal frame,
// pFrame should not be an ICorDebugInternalFrame.
//
HRESULT CordbThread::InterceptCurrentException(ICorDebugFrame * pFrame)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
#if defined(FEATURE_DBGIPC_TRANSPORT_DI)
// Continuable exceptions are not implemented on Unix-like platforms.
return E_NOTIMPL;
#else // !FEATURE_DBGIPC_TRANSPORT_DI
HRESULT hr = S_OK;
EX_TRY
{
DebuggerIPCEvent event;
if (pFrame == NULL)
{
ThrowHR(E_INVALIDARG);
}
//
// Verify we were passed a real stack frame, and not an internal
// CLR mocked up one.
//
{
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
hr = pFrame->QueryInterface(IID_ICorDebugInternalFrame, (void **)&pInternalFrame);
if (!FAILED(hr))
{
ThrowHR(E_INVALIDARG);
}
}
//
// If the thread is detached, then there should be no frames on its stack.
//
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
//
// Refresh the stack frames for this thread and verify pFrame is on it.
//
RefreshStack();
//
// Now check if the frame actually lives on the stack of the current thread.
//
// "Cast" the ICDFrame pointer to a CordbFrame pointer.
CordbFrame * pRealFrame = CordbFrame::GetCordbFrameFromInterface(pFrame);
if (!OwnsFrame(pRealFrame))
{
ThrowHR(E_INVALIDARG);
}
//
// pFrame is on the stack - good. Now tell the LS to intercept at that frame.
//
GetProcess()->InitIPCEvent(&event, DB_IPCE_INTERCEPT_EXCEPTION, true, VMPTR_AppDomain::NullPtr());
event.InterceptException.vmThreadToken = m_vmThreadToken;
event.InterceptException.frameToken = pRealFrame->GetFramePointer();
hr = GetProcess()->m_cordb->SendIPCEvent(GetProcess(), &event, sizeof(DebuggerIPCEvent));
//
// Stop now if we can't even send the event.
//
if (!SUCCEEDED(hr))
{
ThrowHR(hr);
}
_ASSERTE(event.type == DB_IPCE_INTERCEPT_EXCEPTION_RESULT);
hr = event.hr;
// Since we are going to exit anyway, we don't need to throw here.
}
}
EX_CATCH_HRESULT(hr);
return hr;
#endif // FEATURE_DBGIPC_TRANSPORT_DI
}
//---------------------------------------------------------------------------------------
//
// Return S_OK if there is a current exception and it is unhandled, otherwise
// return S_FALSE
//
HRESULT CordbThread::HasUnhandledException()
{
FAIL_IF_NEUTERED(this);
HRESULT hr = S_FALSE;
PUBLIC_REENTRANT_API_BEGIN(this)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
if(pDAC->HasUnhandledException(m_vmThreadToken))
{
hr = S_OK;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Create a stackwalker on the current thread. Initially, the stackwalker is stopped at the
// managed filter CONTEXT if there is one. Otherwise it is stopped at the leaf CONTEXT.
//
// Arguments:
// ppStackWalk - out parameter; return the new stackwalker
//
// Return Value:
// Return S_OK on success.
// Return E_FAIL on error.
//
// Notes:
// The filter CONTEXT will be removed in V3.0.
//
HRESULT CordbThread::CreateStackWalk(ICorDebugStackWalk ** ppStackWalk)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStackWalk, ICorDebugStackWalk **);
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
RSInitHolder<CordbStackWalk> pSW(new CordbStackWalk(this));
pSW->Init();
pSW.TransferOwnershipExternal(ppStackWalk);
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This is a callback function used to enumerate the internal frames on a thread.
// Each time this callback is invoked, we'll create a new CordbInternalFrame and store it
// in an array. See code:DacDbiInterfaceImpl::EnumerateInternalFrames for more information.
//
// Arguments:
// pFrameData - contains information about the current internal frame in the enumeration
// pUserData - This is a GetActiveInternalFramesData.
// It contains an array of internl frames to be filled.
//
// static
void CordbThread::GetActiveInternalFramesCallback(const DebuggerIPCE_STRData * pFrameData,
void * pUserData)
{
// Retrieve the CordbThread.
GetActiveInternalFramesData * pCallbackData = reinterpret_cast<GetActiveInternalFramesData *>(pUserData);
CordbThread * pThis = pCallbackData->pThis;
INTERNAL_DAC_CALLBACK(pThis->GetProcess());
// Make sure we are getting invoked for internal frames.
_ASSERTE(pFrameData->eType == DebuggerIPCE_STRData::cStubFrame);
// Look up the CordbAppDomain.
CordbAppDomain * pAppDomain = NULL;
VMPTR_AppDomain vmCurrentAppDomain = pFrameData->vmCurrentAppDomainToken;
if (!vmCurrentAppDomain.IsNull())
{
pAppDomain = pThis->GetProcess()->LookupOrCreateAppDomain(vmCurrentAppDomain);
}
// Create a CordbInternalFrame.
CordbInternalFrame * pInternalFrame = new CordbInternalFrame(pThis,
pFrameData->fp,
pAppDomain,
pFrameData);
// Store the internal frame in the array and update the index to prepare for the next one.
pCallbackData->pInternalFrames.Assign(pCallbackData->uIndex, pInternalFrame);
pCallbackData->uIndex++;
}
//---------------------------------------------------------------------------------------
//
// This function returns an array of ICDInternalFrame2. Each element represents an internal frame
// on the thread. If ppInternalFrames is NULL or cInternalFrames is 0, then we just return
// the number of internal frames on the thread.
//
// Arguments:
// cInternalFrames - the number of elements in ppInternalFrames
// pcInternalFrames - out parameter; return the number of internal frames on the thread
// ppInternalFrames - a buffer to store the array of internal frames
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if
// - ppInternalFrames is NULL but cInternalFrames is not 0
// - pcInternalFrames is NULL
// - cInternalFrames is smaller than the number of internal frames actually on the thread
//
HRESULT CordbThread::GetActiveInternalFrames(ULONG32 cInternalFrames,
ULONG32 * pcInternalFrames,
ICorDebugInternalFrame2 * ppInternalFrames[])
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this);
{
if ( ((cInternalFrames != 0) && (ppInternalFrames == NULL)) ||
(pcInternalFrames == NULL) )
{
ThrowHR(E_INVALIDARG);
}
*pcInternalFrames = 0;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
ULONG32 cActiveInternalFrames = pDAC->GetCountOfInternalFrames(m_vmThreadToken);
// Set the count.
*pcInternalFrames = cActiveInternalFrames;
// Don't need to do anything else if the user is only asking for the count.
if ((cInternalFrames != 0) && (ppInternalFrames != NULL))
{
if (cInternalFrames < cActiveInternalFrames)
{
ThrowWin32(ERROR_INSUFFICIENT_BUFFER);
}
else
{
// initialize the callback data
GetActiveInternalFramesData data;
data.pThis = this;
data.uIndex = 0;
data.pInternalFrames.AllocOrThrow(cActiveInternalFrames);
// We want to ensure it's automatically cleaned up in all cases
// e.g. if we're debugging a MiniDumpNormal and we fail to
// retrieve memory from the target. The exception will be
// caught above this frame.
data.pInternalFrames.EnableAutoClear();
pDAC->EnumerateInternalFrames(m_vmThreadToken,
&CordbThread::GetActiveInternalFramesCallback,
&data);
_ASSERTE(cActiveInternalFrames == data.pInternalFrames.Length());
// Copy the internal frames we have accumulated in GetActiveInternalFramesData to the out
// argument.
for (unsigned int i = 0; i < data.pInternalFrames.Length(); i++)
{
RSInitHolder<CordbInternalFrame> pInternalFrame(data.pInternalFrames[i]);
pInternalFrame.TransferOwnershipExternal(&(ppInternalFrames[i]));
}
}
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ICorDebugThread4
// -------------------------------------------------------------------------------
// Gets the current custom notification on this thread or NULL if no such object exists
// Arguments:
// output: ppNotificationObject - current CustomNotification object.
// if we aren't currently inside a CustomNotification callback, this will
// always return NULL.
// return value:
// S_OK on success
// S_FALSE if no object exists
// CORDBG_E_BAD_REFERENCE_VALUE if the reference is bad
HRESULT CordbThread::GetCurrentCustomDebuggerNotification(ICorDebugValue ** ppNotificationObject)
{
HRESULT hr = S_OK;
PUBLIC_API_NO_LOCK_BEGIN(this);
{
ATT_REQUIRE_STOPPED_MAY_FAIL_OR_THROW(GetProcess(), ThrowHR);
if (ppNotificationObject == NULL)
{
ThrowHR(E_INVALIDARG);
}
*ppNotificationObject = NULL;
//
// Go to the LS and retrieve any notification object.
//
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetCurrentCustomDebuggerNotification(m_vmThreadToken);
#if defined(_DEBUG)
// Since we know a notification has occurred on this thread, our assumption about the
// thread's current AppDomain should be correct
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
_ASSERTE(GetAppDomain()->GetADToken() == vmAppDomain);
#endif // _DEBUG
if (!vmObjHandle.IsNull())
{
ICorDebugReferenceValue * pRefValue = NULL;
IfFailThrow(CordbReferenceValue::BuildFromGCHandle(GetAppDomain(), vmObjHandle, &pRefValue));
*ppNotificationObject = pRefValue;
}
}
PUBLIC_API_END(hr);
return hr;
}
// ICorDebugThread5
/*
* GetBytesAllocated
*
* Returns S_OK if it was possible to obtain the allocation information for the thread
* and sets the corresponding SOH and UOH allocations.
*/
HRESULT CordbThread::GetBytesAllocated(ULONG64 *pSohAllocatedBytes,
ULONG64 *pUohAllocatedBytes)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
DacThreadAllocInfo threadAllocInfo = { 0 };
if (pSohAllocatedBytes == NULL || pUohAllocatedBytes == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->GetThreadAllocInfo(m_vmThreadToken, &threadAllocInfo);
*pSohAllocatedBytes = threadAllocInfo.m_allocBytesSOH;
*pUohAllocatedBytes = threadAllocInfo.m_allocBytesUOH;
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetBytesAllocated
/*
*
* SetRemapIP
*
* This routine communicate the EnC remap IP to the LS by writing it to process memory using
* the pointer that was set in the thread. If the address is null, then we haven't seen
* a RemapOpportunity call for this frame/function combo yet, so invalid to Remap the function.
*
* Parameters:
* offset - the IL offset to set the IP to
*
* Return Value:
* S_OK or CORDBG_E_NO_REMAP_BREAKPIONT.
*
*/
HRESULT CordbThread::SetRemapIP(SIZE_T offset)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// This is only set when we're prepared to do a remap
if (! m_EnCRemapFunctionIP)
{
return CORDBG_E_NO_REMAP_BREAKPIONT;
}
// Write the value of the remap offset into the left side
HRESULT hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(m_EnCRemapFunctionIP), &offset);
// Prevent SetRemapIP from being called twice for the same RemapOpportunity
// If we don't get any calls to RemapFunction, this member will be cleared in
// code:CordbThread::MarkStackFramesDirty when Continue is called
m_EnCRemapFunctionIP = NULL;
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetConnectionID.
//
// Arguments:
// pdwConnectionId - return connection id set on the thread. Can return INVALID_CONNECTION_ID
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT CordbThread::GetConnectionID(CONNID * pConnectionID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the connection id
HRESULT hr = S_OK;
EX_TRY
{
if (pConnectionID == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pConnectionID = pDAC->GetConnectionID(m_vmThreadToken);
if (*pConnectionID == INVALID_CONNECTION_ID)
{
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetConnectionID
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetTaskID.
//
// Arguments:
// pTaskId - return task id set on the thread. Can return INVALID_TASK_ID
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT CordbThread::GetTaskID(TASKID * pTaskID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the task id
HRESULT hr = S_OK;
EX_TRY
{
if (pTaskID == NULL)
{
ThrowHR(E_INVALIDARG);
}
*pTaskID = this->GetTaskID();
if (*pTaskID == INVALID_TASK_ID)
{
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetTaskID
//---------------------------------------------------------------------------------------
// Get the task ID for this thread
//
// return:
// task id set on the thread. Can return INVALID_TASK_ID
//
TASKID CordbThread::GetTaskID()
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
return pDAC->GetTaskID(m_vmThreadToken);
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetVolatileOSThreadID.
//
// Arguments:
// pdwTid - return os thread id
//
// Return Value:
// HRESULT indicating success or failure
//
// Notes:
// Compare with code:CordbThread::GetID
HRESULT CordbThread::GetVolatileOSThreadID(DWORD * pdwTID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the OS thread ID
HRESULT hr = S_OK;
EX_TRY
{
if (pdwTID == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pdwTID = pDAC->TryGetVolatileOSThreadID(m_vmThreadToken);
if (*pdwTID == 0)
{
hr = S_FALSE; // Switched out
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetOSThreadID
//---------------------------------------------------------------------------------------
// Get the thread's volatile OS ID. (this is fiber aware)
//
// Returns:
// Thread's current OS id. For fibers / "logical threads", This may change as a thread executes.
// Throws if the managed thread currently is not mapped to an OS thread (ie, not scheduled)
//
DWORD CordbThread::GetVolatileOSThreadID()
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
DWORD dwThreadID = pDAC->TryGetVolatileOSThreadID(m_vmThreadToken);
if (dwThreadID == 0)
{
ThrowHR(CORDBG_E_THREAD_NOT_SCHEDULED);
}
return dwThreadID;
}
// ----------------------------------------------------------------------------
// CordbThread::ClearStackFrameCache
//
// Description:
// Clear the cache of stack frames maintained by the CordbThread.
//
// Notes:
// We are doing an InternalRelease() here to match the InternalAddRef() in code:CordbThread::RefreshStack.
//
void CordbThread::ClearStackFrameCache()
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
for (int i = 0; i < m_stackFrames.Count(); i++)
{
(*m_stackFrames.Get(i))->Neuter();
(*m_stackFrames.Get(i))->InternalRelease();
}
m_stackFrames.Clear();
}
// ----------------------------------------------------------------------------
// EnumerateBlockingObjectsCallback
//
// Description:
// A small helper used by CordbThread::GetBlockingObjects. This callback adds the enumerated items
// to a list
//
// Arguments:
// blockingObject - the object to add to the list
// pUserData - the list to add it to
VOID EnumerateBlockingObjectsCallback(DacBlockingObject blockingObject, CALLBACK_DATA pUserData)
{
CQuickArrayList<DacBlockingObject>* pDacBlockingObjs = (CQuickArrayList<DacBlockingObject>*)pUserData;
pDacBlockingObjs->Push(blockingObject);
}
// ----------------------------------------------------------------------------
// CordbThread::GetBlockingObjects
//
// Description:
// Returns a list of objects that a thread is blocking on by using Monitor.Enter and
// Monitor.Wait
//
// Arguments:
// ppBlockingObjectEnum - on return this is an enumerator for the list of blocking objects
//
// Return:
// S_OK on success or an appropriate failing HRESULT
HRESULT CordbThread::GetBlockingObjects(ICorDebugBlockingObjectEnum **ppBlockingObjectEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppBlockingObjectEnum, ICorDebugBlockingObjectEnum **);
HRESULT hr = S_OK;
CorDebugBlockingObject* blockingObjs = NULL;
EX_TRY
{
CQuickArrayList<DacBlockingObject> dacBlockingObjects;
IDacDbiInterface* pDac = GetProcess()->GetDAC();
pDac->EnumerateBlockingObjects(m_vmThreadToken,
(IDacDbiInterface::FP_BLOCKINGOBJECT_ENUMERATION_CALLBACK) EnumerateBlockingObjectsCallback,
(CALLBACK_DATA) &dacBlockingObjects);
blockingObjs = new CorDebugBlockingObject[dacBlockingObjects.Size()];
for(SIZE_T i = 0 ; i < dacBlockingObjects.Size(); i++)
{
// ICorDebug API needs to flip the direction of the list from the way DAC stores it
SIZE_T dacObjIndex = dacBlockingObjects.Size()-i-1;
switch(dacBlockingObjects[dacObjIndex].blockingReason)
{
case DacBlockReason_MonitorCriticalSection:
blockingObjs[i].blockingReason = BLOCKING_MONITOR_CRITICAL_SECTION;
break;
case DacBlockReason_MonitorEvent:
blockingObjs[i].blockingReason = BLOCKING_MONITOR_EVENT;
break;
default:
_ASSERTE(!"Should not get here");
ThrowHR(E_FAIL);
break;
}
blockingObjs[i].dwTimeout = dacBlockingObjects[dacObjIndex].dwTimeout;
CordbAppDomain* pAppDomain;
{
RSLockHolder holder(GetProcess()->GetProcessLock());
pAppDomain = GetProcess()->LookupOrCreateAppDomain(dacBlockingObjects[dacObjIndex].vmAppDomain);
}
blockingObjs[i].pBlockingObject = CordbValue::CreateHeapValue(pAppDomain,
dacBlockingObjects[dacObjIndex].vmBlockingObject);
}
CordbBlockingObjectEnumerator* objEnum = new CordbBlockingObjectEnumerator(GetProcess(),
blockingObjs,
(DWORD)dacBlockingObjects.Size());
GetProcess()->GetContinueNeuterList()->Add(GetProcess(), objEnum);
hr = objEnum->QueryInterface(__uuidof(ICorDebugBlockingObjectEnum), (void**)ppBlockingObjectEnum);
_ASSERTE(SUCCEEDED(hr));
}
EX_CATCH_HRESULT(hr);
delete [] blockingObjs;
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
/* ------------------------------------------------------------------------- *
* Unmanaged Thread classes
* ------------------------------------------------------------------------- */
CordbUnmanagedThread::CordbUnmanagedThread(CordbProcess *pProcess, DWORD dwThreadId, HANDLE hThread, void *lpThreadLocalBase)
: CordbBase(pProcess, dwThreadId, enumCordbUnmanagedThread),
m_stackBase(0),
m_stackLimit(0),
m_handle(hThread),
m_threadLocalBase(lpThreadLocalBase),
m_pTLSArray(NULL),
m_pTLSExtendedArray(NULL),
m_state(CUTS_None),
m_originalHandler(NULL),
#ifdef TARGET_X86
m_pSavedLeafSeh(NULL),
#endif
m_continueCountCached(0)
{
m_pLeftSideContext.Set(NULL);
IBEvent()->m_state = CUES_None;
IBEvent()->m_next = NULL;
IBEvent()->m_owner = this;
IBEvent2()->m_state = CUES_None;
IBEvent2()->m_next = NULL;
IBEvent2()->m_owner = this;
OOBEvent()->m_state = CUES_None;
OOBEvent()->m_next = NULL;
OOBEvent()->m_owner = this;
m_pPatchSkipAddress = NULL;
this->GetStackRange(NULL, NULL);
}
CordbUnmanagedThread::~CordbUnmanagedThread()
{
// CordbUnmanagedThread objects will:
// - never send IPC events.
// - never be exposed to the public. (we assert external-ref is always == 0)
// - always manipulated on W32ET (where we can't do IPC stuff)
UnsafeNeuterDeadObject();
_ASSERTE(this->IsNeutered());
// by the time the thread is deleted, it shouldn't have any outstanding debug events.
// Actually, the thread could get deleted while we have an outstanding IB debug event. We could get the IB event, hijack that thread,
// and then since the process is continued, something could go off and kill the hijacked thread.
// If the event is still in the process's queued list, and it still refers back to a thread, then we'll AV when we try to access the event
// (or continue it).
CONSISTENCY_CHECK_MSGF(!HasIBEvent(), ("Deleting thread w/ outstanding IB event:this=%p,event-code=%d\n", this, IBEvent()->m_currentDebugEvent.dwDebugEventCode));
CONSISTENCY_CHECK_MSGF(!HasOOBEvent(), ("Deleting thread w/ outstanding OOB event:this=%p,event-code=%d\n", this, OOBEvent()->m_currentDebugEvent.dwDebugEventCode));
}
#define WINNT_TLS_OFFSET_X86 0xe10 // TLS[0] at fs:[WINNT_TLS_OFFSET]
#define WINNT_TLS_OFFSET_AMD64 0x1480
#define WINNT_TLS_OFFSET_ARM 0xe10
#define WINNT_TLS_OFFSET_ARM64 0x1480
#define WINNT5_TLSEXPANSIONPTR_OFFSET_X86 0xf94 // TLS[64] at [fs:[WINNT5_TLSEXPANSIONPTR_OFFSET]]
#define WINNT5_TLSEXPANSIONPTR_OFFSET_AMD64 0x1780
#define WINNT5_TLSEXPANSIONPTR_OFFSET_ARM 0xf94
#define WINNT5_TLSEXPANSIONPTR_OFFSET_ARM64 0x1780
HRESULT CordbUnmanagedThread::LoadTLSArrayPtr(void)
{
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// Just simple math on NT with a small tls index.
// The TLS slots for 0-63 are embedded in the TIB.
#if defined(TARGET_X86)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_X86;
#elif defined(TARGET_AMD64)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_AMD64;
#elif defined(TARGET_ARM)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_ARM;
#elif defined(TARGET_ARM64)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_ARM64;
#else
PORTABILITY_ASSERT("Implement OOP TLS on your platform");
#endif
// Extended slot is lazily initialized, so check every time.
if (m_pTLSExtendedArray == NULL)
{
// On NT 5 you can have TLS index's greater than 63, so we
// have to grab the ptr to the TLS expansion array first,
// then use that as the base to index off of. This will
// never move once we find it for a given thread, so we
// cache it here so we don't always have to perform two
// ReadProcessMemory's.
#if defined(TARGET_X86)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_X86;
#elif defined(TARGET_AMD64)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_AMD64;
#elif defined(TARGET_ARM)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_ARM;
#elif defined(TARGET_ARM64)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_ARM64;
#else
PORTABILITY_ASSERT("Implement OOP TLS on your platform");
#endif
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(ppTLSArray), &m_pTLSExtendedArray);
}
return hr;
}
/*
VOID CordbUnmanagedThread::VerifyFSChain()
{
#if defined(TARGET_X86)
DT_CONTEXT temp;
temp.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(m_handle, &temp);
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: 0x%x fs=0x%x TIB=0x%x\n",
m_id, temp.SegFs, m_threadLocalBase));
REMOTE_PTR pExceptionRegRecordPtr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &pExceptionRegRecordPtr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read fs:0 value: computed addr=0x%p err=%x\n",
m_id, m_threadLocalBase, hr));
_ASSERTE(FALSE);
return;
}
while(pExceptionRegRecordPtr != EXCEPTION_CHAIN_END && pExceptionRegRecordPtr != NULL)
{
REMOTE_PTR prev;
REMOTE_PTR handler;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pExceptionRegRecordPtr), &prev);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read prev value: computed addr=0x%p err=%x\n",
m_id, pExceptionRegRecordPtr, hr));
return;
}
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS( (VOID*)((DWORD)pExceptionRegRecordPtr+4) ), &handler);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read handler value: computed addr=0x%p err=%x\n",
m_id, (DWORD)pExceptionRegRecordPtr+4, hr));
return;
}
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: OK 0x%x record=0x%x prev=0x%x handler=0x%x\n",
m_id, pExceptionRegRecordPtr, prev, handler));
if(handler == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x NULL handler found\n", m_id));
_ASSERTE(FALSE);
return;
}
if(prev == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x NULL prev found\n", m_id));
_ASSERTE(FALSE);
return;
}
if(prev == pExceptionRegRecordPtr)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x cyclic prev found\n", m_id));
_ASSERTE(FALSE);
return;
}
pExceptionRegRecordPtr = prev;
}
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: OK 0x%x\n", m_id));
#endif
return;
}*/
#ifdef TARGET_X86
HRESULT CordbUnmanagedThread::SaveCurrentLeafSeh()
{
_ASSERTE(m_pSavedLeafSeh == NULL);
REMOTE_PTR pExceptionRegRecordPtr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &pExceptionRegRecordPtr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SCLS: failed to read fs:0 value: computed addr=0x%p err=%x\n", m_threadLocalBase, hr));
return hr;
}
m_pSavedLeafSeh = pExceptionRegRecordPtr;
return S_OK;
}
HRESULT CordbUnmanagedThread::RestoreLeafSeh()
{
_ASSERTE(m_pSavedLeafSeh != NULL);
HRESULT hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &m_pSavedLeafSeh);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::RLS: failed to write fs:0 value: computed addr=0x%p err=%x\n", m_threadLocalBase, hr));
return hr;
}
m_pSavedLeafSeh = NULL;
return S_OK;
}
#endif
// Read the contents from the LS's Predefined TLS block.
// This is an auxillary TLS storage array-of-void*, indexed off the TLS.
// pRead is optional. This makes sense when '0' is a valid default value.
// 1) On success (block exists in LS, we can read it),
// return value of data in the slot, *pRead = true
// 2) On failure to read block (block doens't exist yet, any other failure)
// return value == 0 (assumed default, *pRead = false
REMOTE_PTR CordbUnmanagedThread::GetPreDefTlsSlot(SIZE_T offset)
{
REMOTE_PTR tlsDataAddress;
HRESULT hr = GetClrModuleTlsDataAddress(&tlsDataAddress);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: GetClrModuleTlsDataAddress FAILED %x for 0x%x\n", hr, m_id));
return NULL;
}
REMOTE_PTR data = 0;
// Read the thread's TLS value.
REMOTE_PTR slotAddr = (BYTE*)tlsDataAddress + offset;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(slotAddr), &data);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: failed to get TLS value: tlsData=0x%p offset=%d, err=%x\n",
tlsDataAddress, offset, hr));
return NULL;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETV: EE Thread TLS value is 0x%x for 0x%x\n", data, m_id));
return data;
}
// Read the contents from a LS threads's TLS slot.
HRESULT CordbUnmanagedThread::GetTlsSlot(DWORD slot, REMOTE_PTR * pValue)
{
// Compute the address of the necessary TLS value.
HRESULT hr = LoadTLSArrayPtr();
if (FAILED(hr))
{
return hr;
}
void * pBase = NULL;
SIZE_T slotAdjusted = slot;
if (slot < TLS_MINIMUM_AVAILABLE)
{
pBase = m_pTLSArray;
}
else if (slot < TLS_MINIMUM_AVAILABLE + TLS_EXPANSION_SLOTS)
{
pBase = m_pTLSExtendedArray;
slotAdjusted -= TLS_MINIMUM_AVAILABLE;
// Expansion slot is lazily allocated. If we're trying to read from it, but hasn't been allocated,
// then the TLS slot is still the default value, which is 0 (NULL).
if (pBase == NULL)
{
*pValue = NULL;
return S_OK;
}
}
else
{
// Slot is out of range. Shouldn't happen unless debuggee is corrupted.
_ASSERTE(!"Invalid TLS slot");
return E_UNEXPECTED;
}
void *pEEThreadTLS = (BYTE*)pBase + (slotAdjusted * sizeof(void*));
// Read the thread's TLS value.
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadTLS), pValue);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GTS: failed to read TLS value: computed addr=0x%p slot=%d, err=%x\n",
pEEThreadTLS, slot, hr));
return hr;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GTS: EE Thread TLS value is 0x%p for thread 0x%x, slot 0x%x\n", *pValue, m_id, slot));
return S_OK;
}
// This does a WriteProcessMemory to write to the debuggee's TLS slot
//
// Notes:
// This is very brittle because the OS can lazily allocates storage for TLS slots.
// In order to gaurantee the storage is available, it must have been written to by the debuggee.
// For managed threads, that's easy because the Thread* is already written to the slot.
// But for pure native threads where GetThread() == NULL, the storage may not yet be allocated.
//
// The saving grace is that the debuggee's hijack filters will force the TLS to be allocated before it
// sends a flare.
//
// Therefore, this function can only be called:
// 1) on a managed thread
// 2) on a native thread after that thread has been hijacked and sent a flare.
//
// This is brittle reasoning, but so is the rest of interop-debugging.
//
HRESULT CordbUnmanagedThread::SetTlsSlot(DWORD slot, REMOTE_PTR value)
{
FAIL_IF_NEUTERED(this);
// Compute the address of the necessary TLS value.
HRESULT hr = LoadTLSArrayPtr();
if (FAILED(hr))
{
return hr;
}
void * pBase = NULL;
SIZE_T slotAdjusted = slot;
if (slot < TLS_MINIMUM_AVAILABLE)
{
pBase = m_pTLSArray;
}
else if (slot < TLS_MINIMUM_AVAILABLE + TLS_EXPANSION_SLOTS)
{
pBase = m_pTLSExtendedArray;
slotAdjusted -= TLS_MINIMUM_AVAILABLE;
// Expansion slot is lazily allocated. If we're trying to read from it, but hasn't been allocated,
// then the TLS slot is still the default value, which is 0.
if (pBase == NULL)
{
// See reasoning in header for why this should succeed.
_ASSERTE(!"Can't set to expansion slots because they haven't been allocated");
return E_FAIL;
}
}
else
{
// Slot is out of range. Shouldn't happen unless debuggee is corrupted.
_ASSERTE(!"Invalid TLS slot");
return E_INVALIDARG;
}
void *pEEThreadTLS = (BYTE*)pBase + (slotAdjusted * sizeof(void*));
// Write the thread's TLS value.
hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pEEThreadTLS), &value);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SEETV: failed to set TLS value: computed addr=0x%p slot=%d, err=%x\n", pEEThreadTLS, slot, hr));
return hr;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::SEETV: EE Thread TLS value is now 0x%p for 0x%x\n", value, m_id));
return S_OK;
}
// gets the value of gCurrentThreadInfo.m_pThread
DWORD_PTR CordbUnmanagedThread::GetEEThreadValue()
{
DWORD_PTR ret = NULL;
REMOTE_PTR tlsDataAddress;
HRESULT hr = GetClrModuleTlsDataAddress(&tlsDataAddress);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: GetClrModuleTlsDataAddress FAILED %x for 0x%x\n", hr, m_id));
return NULL;
}
// Read the thread's TLS value.
REMOTE_PTR EEThreadAddr = (BYTE*)tlsDataAddress + GetProcess()->m_runtimeOffsets.m_TLSEEThreadOffset + OFFSETOF__TLS__tls_CurrentThread;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(EEThreadAddr), &ret);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: failed to get TLS value: computed addr=0x%p index=%d, err=%x\n",
EEThreadAddr, GetProcess()->m_runtimeOffsets.m_TLSIndex, hr));
return NULL;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETV: EE Thread TLS value is 0x%p for 0x%x\n", ret, m_id));
return ret;
}
// returns the remote address of gCurrentThreadInfo
HRESULT CordbUnmanagedThread::GetClrModuleTlsDataAddress(REMOTE_PTR* pAddress)
{
*pAddress = NULL;
REMOTE_PTR tlsArrayAddr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_threadLocalBase + WINNT_OFFSETOF__TEB__ThreadLocalStoragePointer), &tlsArrayAddr);
if (FAILED(hr))
{
return hr;
}
// This is the special break-in thread case: TEB.ThreadLocalStoragePointer == NULL
if (tlsArrayAddr == NULL)
{
return E_FAIL;
}
REMOTE_PTR clrModuleTlsDataAddr;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)tlsArrayAddr + GetProcess()->m_runtimeOffsets.m_TLSIndex * sizeof(void*)), &clrModuleTlsDataAddr);
if (FAILED(hr))
{
return hr;
}
if (clrModuleTlsDataAddr == NULL)
{
_ASSERTE(!"No clr module data present at _tls_index for this thread");
return E_FAIL;
}
*pAddress = (BYTE*) clrModuleTlsDataAddr;
return S_OK;
}
/*
* GetEEDebuggerWord
*
* This routine returns the value read from the thread
*
* Parameters:
* pValue - Location to store value.
*
* Returns:
* E_INVALIDARG, E_FAIL, S_OK
*/
HRESULT CordbUnmanagedThread::GetEEDebuggerWord(REMOTE_PTR *pValue)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEEDW: Entered\n"));
if (pValue == NULL)
{
return E_INVALIDARG;
}
return GetTlsSlot(GetProcess()->m_runtimeOffsets.m_debuggerWordTLSIndex, pValue);
}
// SetEEDebuggerWord
//
// This routine writes the value to the thread
//
// Parameters:
// pValue - Value to write.
//
// Returns:
// HRESULT failure code or S_OK
//
// Notes:
// This function is very dangerous. See code:CordbUnmanagedThread::SetEETlsValue for why.
HRESULT CordbUnmanagedThread::SetEEDebuggerWord(REMOTE_PTR value)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SEEDW: Entered - value is 0x%p\n", value));
return SetTlsSlot(GetProcess()->m_runtimeOffsets.m_debuggerWordTLSIndex, value);
}
/*
* GetEEThreadPtr
*
* This routine returns the value read from the thread
*
* Parameters:
* ppEEThread - Location to store value.
*
* Returns:
* E_INVALIDARG, E_FAIL, S_OK
*/
HRESULT CordbUnmanagedThread::GetEEThreadPtr(REMOTE_PTR *ppEEThread)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
if (ppEEThread == NULL)
{
return E_INVALIDARG;
}
*ppEEThread = (REMOTE_PTR)GetEEThreadValue();
return S_OK;
}
void CordbUnmanagedThread::GetEEState(bool *threadStepping, bool *specialManagedException)
{
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
_ASSERTE(pEEThread != NULL);
*threadStepping = false;
*specialManagedException = false;
// Compute the address of the thread's state
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadStateNC = (BYTE*) pEEThread + pRO->m_EEThreadStateNCOffset;
// Grab the thread state out of the EE Thread.
DWORD EEThreadStateNC;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadStateNC), &EEThreadStateNC);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETS: failed to read thread state NC: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadStateNCOffset, pEEThreadStateNC, GetLastError()));
return;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETS: EE Thread state NC is 0x%08x\n", EEThreadStateNC));
// Looks like we've got the state of the thread.
*threadStepping = ((EEThreadStateNC & pRO->m_EEThreadSteppingStateMask) != 0);
*specialManagedException = ((EEThreadStateNC & pRO->m_EEIsManagedExceptionStateMask) != 0);
return;
}
// Is the thread in a "can't stop" region?
// "Can't-Stop" regions include anything that's "inside" the runtime; ie, the runtime has some
// synchronization mechanism that will halt this thread, and so we don't need to suspend it.
// The interop debugger should leave anything in a can't-stop region alone and just let the runtime
// handle it.
bool CordbUnmanagedThread::IsCantStop()
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
// Definition of a can't stop region:
// - Any "Special" thread that doesn't have an EE Thread (includes the real Helper Thread,
// Concurrent GC thread, ThreadPool thread, etc).
// - Any thread in Cooperative code.
// - Any thread w/ a can't-stop count > 0.
// - Any thread holding a "Debugger" Crst. (This is actually a subset of the
// can't-stop count b/c Enter/Leave adjust that count).
// - Any generic, first chance or RaiseException hijacked thread
// If the runtime isn't init yet, not a can't-stop.
// We don't even have the DCB yet.
if (!GetProcess()->m_initialized)
{
return false;
}
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
if (IsRaiseExceptionHijacked())
{
return true;
}
REMOTE_PTR pEEThread;
HRESULT hr = this->GetEEThreadPtr(&pEEThread);
if (FAILED(hr))
{
_ASSERTE(!"Failed to EEThreadPtr in IsCantStop");
return true;
}
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
// @todo- remove this and use the CantStop index below.
// Is this a "special" thread?
// Any thread that can take CLR locks w/o having an EE Thread object should
// be marked as special. These threads are in "can't-stop" regions b/c if we suspend
// them, they may be holding a lock that blocks the helper thread.
// The helper thread is marked as "special".
{
REMOTE_PTR special = GetPreDefTlsSlot(pRO->m_TLSIsSpecialOffset);
// If it's a special thread
if ((special != 0) && (pEEThread == NULL))
{
return true;
}
}
// Check for CantStop regions off the FLS.
// This is the biggest way to describe can't-stop regions when we're in preemptive mode
// (or when we don't have a thread object).
// If a LS thread takes a debugger lock, it will increment the Can't-Stop count.
{
REMOTE_PTR count = GetPreDefTlsSlot(pRO->m_TLSCantStopOffset);
// Just a sanity check here. There's nothing special about 1000, but if the
// stop-count gets this big, 99% chance it's:
// - we're accessing the wrong memory (an issue)
// - someone on the LS is leaking stop-counts. (an issue).
_ASSERTE(count < (REMOTE_PTR)1000);
if (count > 0)
{
LOG((LF_CORDB, LL_INFO1000000, "Thread 0x%x is can't-stop b/c count=%d\n", m_id, count));
return true;
}
}
EX_TRY
{
GetProcess()->UpdateRightSideDCB();
}
EX_CATCH
{
_ASSERTE(!"IsCantStop: Failed updating debugger control block");
}
EX_END_CATCH(SwallowAllExceptions);
// Helper's canary thread is always can't-stop.
if (this->m_id == GetProcess()->GetDCB()->m_CanaryThreadId)
{
return true;
}
// Check helper thread / or anyone pretending to be the helper thread.
if ((this->m_id == GetProcess()->GetDCB()->m_helperThreadId) ||
(this->m_id == GetProcess()->GetDCB()->m_temporaryHelperThreadId) ||
(this->m_id == GetProcess()->m_helperThreadId))
{
return true;
}
if (IsGenericHijacked() || IsFirstChanceHijacked())
return true;
// If this isn't a EE thread (and not the helper thread, and not hijacked), then it's ok to stop.
if (pEEThread == NULL)
return false;
// This checks for an explicit "can't" stop region.
// Eventually, these explicit regions should become a complete subset of the other checks.
REMOTE_PTR count = GetPreDefTlsSlot(GetProcess()->m_runtimeOffsets.m_TLSCantStopOffset);
if (count > 0)
return true;
// If we're in cooperative mode (either managed code or parts inside the runtime), then don't stop.
// Note we could remove this since the check is made in side of the DAC request below,
// but it's faster to look here.
if (GetEEPGCDisabled())
return true;
return false;
}
bool CordbUnmanagedThread::GetEEPGCDisabled()
{
// Note: any failure to read memory is okay for this method. We simply say that the thread has PGC disabled, which
// is always the worst case scenario.
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
// Compute the address of the thread's PGC disabled word
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadPGCDisabled = (BYTE*) pEEThread + pRO->m_EEThreadPGCDisabledOffset;
// Grab the PGC disabled word out of the EE Thread.
DWORD EEThreadPGCDisabled;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadPGCDisabled), &EEThreadPGCDisabled);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETS: failed to read thread PGC Disabled: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadPGCDisabledOffset, pEEThreadPGCDisabled, GetLastError()));
return true;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETS: EE Thread PGC Disabled is 0x%08x\n", EEThreadPGCDisabled));
// Looks like we've got it.
if (EEThreadPGCDisabled == pRO->m_EEThreadPGCDisabledValue)
return true;
else
return false;
}
bool CordbUnmanagedThread::GetEEFrame()
{
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
_ASSERTE(pEEThread != NULL);
// Compute the address of the thread's frame ptr
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadFrame = (BYTE*) pEEThread + pRO->m_EEThreadFrameOffset;
// Grab the thread's frame out of the EE Thread.
DWORD EEThreadFrame;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadFrame), &EEThreadFrame);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETF: failed to read thread frame: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadFrameOffset, pEEThreadFrame, GetLastError()));
return false;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETF: EE Thread's frame is 0x%08x\n", EEThreadFrame));
// Looks like we've got the frame of the thread.
if (EEThreadFrame != pRO->m_EEMaxFrameValue)
return true;
else
return false;
}
// Gets the thread context as if the thread were unhijacked, regardless
// of whether it really is
HRESULT CordbUnmanagedThread::GetThreadContext(DT_CONTEXT* pContext)
{
// While hijacked there are 3 potential contexts we could be resuming back to
// 1) A context provided in SetThreadContext that we defered applying
// 2) The LS copy of the context on the stack being modified in the handler
// 3) The original context present when the hijack was started
//
// Both #1 and #3 are stored in the GetHijackCtx() space so of course you can't
// have them both. You have have #1 if IsContextSet() is true, otherwise it holds #3
//
// GenericHijack, FirstChanceHijackForSync, and RaiseExceptionHijack use #1 if available
// and fallback to #3 if not. In other words they use GetHijackCtx() regardless of which thing it holds
// M2UHandoff uses #1 if available and then falls back to #2.
//
// The reasoning here is that the first three hijacks are intended to be transparent. Since
// the debugger shouldn't know they are occuring then it shouldn't see changes potentially
// made on the LS. The M2UHandoff is not transparent, it has to update the context in order
// to get clear of a bp.
//
// If not hijacked call the normal Win32 function.
HRESULT hr = S_OK;
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: thread=0x%p, flags=0x%x.\n", this, pContext->ContextFlags));
if(IsContextSet() || IsGenericHijacked() || (IsFirstChanceHijacked() && IsBlockingForSync())
|| IsRaiseExceptionHijacked())
{
_ASSERTE(IsFirstChanceHijacked() || IsGenericHijacked() || IsRaiseExceptionHijacked());
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: hijackCtx case IsContextSet=%d IsGenericHijacked=%d"
"HijackedForSync=%d RaiseExceptionHijacked=%d.\n",
IsContextSet(), IsGenericHijacked(), IsBlockingForSync(), IsRaiseExceptionHijacked()));
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: hijackCtx is:\n"));
LogContext(GetHijackCtx());
CORDbgCopyThreadContext(pContext, GetHijackCtx());
}
// use the LS for M2UHandoff
else if (IsFirstChanceHijacked() && !IsBlockingForSync())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: getting LS context for first chance hijack, addr=0x%08x.\n",
m_pLeftSideContext.UnsafeGet()));
// Read the context into a temp context then copy to the out param.
DT_CONTEXT tempContext = { 0 };
hr = GetProcess()->SafeReadThreadContext(m_pLeftSideContext, &tempContext);
if (SUCCEEDED(hr))
CORDbgCopyThreadContext(pContext, &tempContext);
}
// no hijack in place so just call straight through
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: getting context from win32.\n"));
BOOL succ = DbiGetThreadContext(m_handle, pContext);
if (!succ)
hr = HRESULT_FROM_GetLastError();
}
if(IsSSFlagHidden())
{
UnsetSSFlag(pContext);
}
LogContext(pContext);
return hr;
}
// Sets the thread context as if the thread were unhijacked, regardless
// of whether it really is. See GetThreadContext above for more details
// on this abstraction
HRESULT CordbUnmanagedThread::SetThreadContext(DT_CONTEXT* pContext)
{
HRESULT hr = S_OK;
LOG((LF_CORDB, LL_INFO10000,
"CUT::STC: thread=0x%p, flags=0x%x.\n", this, pContext->ContextFlags));
LogContext(pContext);
// If the thread is first chance hijacked, then write the context into the remote process. If the thread is generic
// hijacked, then update the copy of the context that we already have. Otherwise call the normal Win32 function.
if (IsGenericHijacked() || IsFirstChanceHijacked() || IsRaiseExceptionHijacked())
{
if(IsGenericHijacked())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from generic/2nd chance hijack.\n"));
}
else if(IsFirstChanceHijacked())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from 1st chance hijack.\n"));
}
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from RaiseException hijack.\n"));
}
SetState(CUTS_HasContextSet);
CORDbgCopyThreadContext(GetHijackCtx(), pContext);
}
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from win32.\n"));
// If the user is also setting the SS flag then we no longer have to hide it
if(IsSSFlagEnabled(pContext))
{
ClearState(CUTS_IsSSFlagHidden);
}
// if the user is turning off the SS flag but we still want it on then leave it on
// but hidden
if(!IsSSFlagEnabled(pContext) && IsSSFlagNeeded())
{
SetState(CUTS_IsSSFlagHidden);
SetSSFlag(pContext);
}
BOOL succ = DbiSetThreadContext(m_handle, pContext);
if (!succ)
{
hr = HRESULT_FROM_GetLastError();
}
}
return hr;
}
// Turns on the stepping flag internally and tracks whether or not the flag
// should also be seen by the user
VOID CordbUnmanagedThread::BeginStepping()
{
_ASSERTE(!IsGenericHijacked() && !IsFirstChanceHijacked());
_ASSERTE(!IsSSFlagNeeded());
_ASSERTE(!IsSSFlagHidden());
DT_CONTEXT tempContext;
tempContext.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
if(!IsSSFlagEnabled(&tempContext))
{
SetSSFlag(&tempContext);
SetState(CUTS_IsSSFlagHidden);
}
SetState(CUTS_IsSSFlagNeeded);
succ = DbiSetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
}
// Turns off the stepping flag internally. If the user was also not using it then
// the flag is turned off on the context
VOID CordbUnmanagedThread::EndStepping()
{
_ASSERTE(!IsGenericHijacked() && !IsFirstChanceHijacked());
_ASSERTE(IsSSFlagNeeded());
DT_CONTEXT tempContext;
tempContext.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
if(IsSSFlagHidden())
{
UnsetSSFlag(&tempContext);
ClearState(CUTS_IsSSFlagHidden);
}
ClearState(CUTS_IsSSFlagNeeded);
succ = DbiSetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
}
// Writes some details of the given context into the debugger log
VOID CordbUnmanagedThread::LogContext(DT_CONTEXT* pContext)
{
#if defined(TARGET_X86)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Eip=0x%08x, Esp=0x%08x, Eflags=0x%08x\n", pContext->Eip, pContext->Esp,
pContext->EFlags));
#elif defined(TARGET_AMD64)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Rip=" FMT_ADDR ", Rsp=" FMT_ADDR ", Eflags=0x%08x\n",
DBG_ADDR(pContext->Rip),
DBG_ADDR(pContext->Rsp),
pContext->EFlags)); // EFlags is still 32bits on AMD64
#elif defined(TARGET_ARM64)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Pc=" FMT_ADDR ", Sp=" FMT_ADDR ", Lr=" FMT_ADDR ", Cpsr=" FMT_ADDR "\n",
DBG_ADDR(pContext->Pc),
DBG_ADDR(pContext->Sp),
DBG_ADDR(pContext->Lr),
DBG_ADDR(pContext->Cpsr)));
#else // TARGET_X86
PORTABILITY_ASSERT("LogContext needs a PC and stack pointer.");
#endif // TARGET_X86
}
// Hijacks this thread using the FirstChanceSuspend hijack
HRESULT CordbUnmanagedThread::SetupFirstChanceHijackForSync()
{
HRESULT hr = S_OK;
CONSISTENCY_CHECK(!IsBlockingForSync()); // Shouldn't double hijack
CONSISTENCY_CHECK(!IsCantStop()); // must be in stoppable-region.
_ASSERTE(HasIBEvent());
// We used to hijack for real here but now we have a vectored exception handler that will always be
// triggered. So we don't have hijack in the sense that we overwrite the thread's IP. However we still
// set the flag so that when we receive the HijackStartedSignal from the LS we know that this thread
// should block in there rather than continuing.
//hr = SetupFirstChanceHijack(EHijackReason::kFirstChanceSuspend, &(IBEvent()->m_currentDebugEvent.u.Exception.ExceptionRecord));
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// We'd better not be hijacking in a can't stop region!
// This also means we can't hijack in coopeative (since that's a can't-stop)
_ASSERTE(!IsCantStop());
// we should not be stepping into hijacks
_ASSERTE(!IsSSFlagHidden());
_ASSERTE(!IsSSFlagNeeded());
_ASSERTE(!IsContextSet());
// snapshot the current context so we can start spoofing it
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: hijackCtx started as:\n"));
LogContext(GetHijackCtx());
// Save the thread's full context.
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &context);
_ASSERTE(succ);
// for debugging when GetThreadContext fails
if(!succ)
{
DWORD error = GetLastError();
LOG((LF_CORDB, LL_ERROR, "CUT::SFCHFS: DbiGetThreadContext error=0x%x\n", error));
}
GetHijackCtx()->ContextFlags = DT_CONTEXT_FULL;
CORDbgCopyThreadContext(GetHijackCtx(), &context);
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: thread=0x%x Hijacking for sync. Original context is:\n", this));
LogContext(GetHijackCtx());
// We're hijacking now...
SetState(CUTS_FirstChanceHijacked);
GetProcess()->m_state |= CordbProcess::PS_HIJACKS_IN_PLACE;
// We'll decrement this once the hijack returns
GetProcess()->m_cFirstChanceHijackedThreads++;
this->SetState(CUTS_BlockingForSync);
// we don't want to single step into the vectored exception handler
// we will restore the SS flag after returning from the hijack
if(IsSSFlagEnabled(&context))
{
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: thread=0x%x Clearing SS flag\n", this));
UnsetSSFlag(&context);
succ = DbiSetThreadContext(m_handle, &context);
_ASSERTE(succ);
}
// There's a bizarre race where the thread was suspended right as the thread was about to dispatch a
// debug event. We still get the debug event, and then may try to hijack. Resume the thread so that
// it can run to the hijack.
if (this->IsSuspended())
{
LOG((LF_CORDB, LL_ERROR, "CUT::SFCHFS: thread was suspended... resuming\n"));
DWORD success = ResumeThread(this->m_handle);
if (success == 0xFFFFFFFF)
{
// Since we suspended it, we should be able to resume it in this window.
CONSISTENCY_CHECK_MSGF(false, ("Failed to resume thread: tid=0x%x!", this->m_id));
}
else
{
this->ClearState(CUTS_Suspended);
}
}
return hr;
}
HRESULT CordbUnmanagedThread::SetupFirstChanceHijack(EHijackReason::EHijackReason reason, const EXCEPTION_RECORD * pExceptionRecord)
{
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// We'd better not be hijacking in a can't stop region!
// This also means we can't hijack in coopeative (since that's a can't-stop)
_ASSERTE(!IsCantStop());
// we should not be stepping into hijacks
_ASSERTE(!IsSSFlagHidden());
_ASSERTE(!IsSSFlagNeeded());
// There's a bizarre race where the thread was suspended right as the thread was about to dispatch a
// debug event. We still get the debug event, and then may try to hijack. Resume the thread so that
// it can run to the hijack.
if (this->IsSuspended())
{
DWORD succ = ResumeThread(this->m_handle);
if (succ == 0xFFFFFFFF)
{
// Since we suspended it, we should be able to resume it in this window.
CONSISTENCY_CHECK_MSGF(false, ("Failed to resume thread: tid=0x%x!", this->m_id));
}
else
{
this->ClearState(CUTS_Suspended);
}
}
HRESULT hr = S_OK;
EX_TRY
{
// We save off the SEH handler on X86 to make sure we restore it properly after the hijack is complete
// The hijacks don't return normally and the SEH chain might have handlers added that don't get removed by default
#ifdef TARGET_X86
hr = SaveCurrentLeafSeh();
if(FAILED(hr))
ThrowHR(hr);
#endif
CORDB_ADDRESS LSContextAddr;
GetProcess()->GetDAC()->Hijack(VMPTR_Thread::NullPtr(),
GetOSTid(),
pExceptionRecord,
(T_CONTEXT*) GetHijackCtx(),
sizeof(T_CONTEXT),
reason,
NULL,
&LSContextAddr);
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCH: pLeftSideContext=0x%p\n", LSContextAddr));
m_pLeftSideContext.Set(CORDB_ADDRESS_TO_PTR(LSContextAddr));
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCH: Error setting up hijack context hr=0x%x\n", hr));
return hr;
}
// We're hijacked now...
SetState(CUTS_FirstChanceHijacked);
GetProcess()->m_state |= CordbProcess::PS_HIJACKS_IN_PLACE;
// We'll decrement this once the hijack returns
GetProcess()->m_cFirstChanceHijackedThreads++;
return S_OK;
}
HRESULT CordbUnmanagedThread::SetupGenericHijack(DWORD eventCode, const EXCEPTION_RECORD * pRecord)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
_ASSERTE(eventCode == EXCEPTION_DEBUG_EVENT);
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(!IsContextSet());
// Save the thread's full context.
GetHijackCtx()->ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, GetHijackCtx());
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SGH: couldn't get thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
#if defined(TARGET_AMD64) || defined(TARGET_ARM64)
// On X86 Debugger::GenericHijackFunc() ensures the stack is walkable
// by simply using the EBP chain, therefore we can execute the hijack
// by setting the thread's context EIP to point to this function.
// On X64, however, we first attempt to set up a "proper" hijack, with
// a function that allows the OS to unwind the stack (ExceptionHijack).
// If this fails we'll use the same method as on X86, even though the
// stack will become un-walkable
ULONG32 dwThreadId = GetOSTid();
CordbThread * pThread = GetProcess()->TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
// For threads in the thread store we set up the full size
// hijack, otherwise we fallback to hijacking by SetIP.
if (pThread != NULL)
{
HRESULT hr = S_OK;
EX_TRY
{
// Note that the data-target is not atomic, and we have no rollback mechanism.
// We have to do several writes. If the data-target fails the writes half-way through the
// target will be inconsistent.
GetProcess()->GetDAC()->Hijack(
pThread->m_vmThreadToken,
dwThreadId,
pRecord,
(T_CONTEXT*) GetHijackCtx(),
sizeof(T_CONTEXT),
EHijackReason::kGenericHijack,
NULL,
NULL);
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
// Remember that we've hijacked the thread.
SetState(CUTS_GenericHijacked);
return S_OK;
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CUT::SGH: Error setting up hijack context hr=0x%x\n", hr);
// fallthrough (above hijack might have failed due to stack overflow, for example)
}
// else (non-threadstore threads) fallthrough
#endif // TARGET_AMD64 || defined(TARGET_ARM64)
// Remember that we've hijacked the thread.
SetState(CUTS_GenericHijacked);
LOG((LF_CORDB, LL_INFO1000000, "CUT::SGH: Current IP is 0x%08x\n", CORDbgGetIP(GetHijackCtx())));
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
// Wack the IP over to our generic hijack function.
LPVOID holdIP = CORDbgGetIP(GetHijackCtx());
CORDbgSetIP(GetHijackCtx(), pRO->m_genericHijackFuncAddr);
LOG((LF_CORDB, LL_INFO1000000, "CUT::SGH: New IP is 0x%08x\n", CORDbgGetIP(GetHijackCtx())));
// We should never single step into the hijack
BOOL isSSFlagOn = IsSSFlagEnabled(GetHijackCtx());
if(isSSFlagOn)
{
UnsetSSFlag(GetHijackCtx());
}
succ = DbiSetThreadContext(m_handle, GetHijackCtx());
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SGH: couldn't set thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
// Put the original IP back into the local context copy for later.
CORDbgSetIP(GetHijackCtx(), holdIP);
// Set the original SS flag into the local context copy for later
if(isSSFlagOn)
{
SetSSFlag(GetHijackCtx());
}
return S_OK;
}
HRESULT CordbUnmanagedThread::FixupFromGenericHijack()
{
LOG((LF_CORDB, LL_INFO1000, "CUT::FFGH: fixing up from generic hijack. Eip=0x%p, Esp=0x%p\n",
CORDbgGetIP(GetHijackCtx()), CORDbgGetSP(GetHijackCtx())));
// We're no longer hijacked
_ASSERTE(IsGenericHijacked());
ClearState(CUTS_GenericHijacked);
// Clear the exception so we do a DBG_CONTINUE with the original context. Note: we only do generic hijacks on
// in-band events.
IBEvent()->SetState(CUES_ExceptionCleared);
// Using the context we saved when the event came in originally or the new context if set by user,
// reset the thread as if it were never hijacked.
BOOL succ = DbiSetThreadContext(m_handle, GetHijackCtx());
// if the user set the context it has been applied now
ClearState(CUTS_HasContextSet);
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::FFGH: couldn't set thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
DT_CONTEXT * CordbUnmanagedThread::GetHijackCtx()
{
return &m_context;
}
// Enable Single-Step (and bump the eip back one)
// This can only be called after a bp. (because we assume that we executed a bp when we adjust the eip).
HRESULT CordbUnmanagedThread::EnableSSAfterBP()
{
DT_CONTEXT c;
c.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &c);
if (!succ)
return HRESULT_FROM_WIN32(GetLastError());
SetSSFlag(&c);
// Backup IP to point to the instruction we need to execute. Continuing from a breakpoint exception
// continues execution at the instruction after the breakpoint, but we need to continue where the
// breakpoint was.
CORDbgAdjustPCForBreakInstruction(&c);
succ = DbiSetThreadContext(m_handle, &c);
if (!succ)
{
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
//
// FixupAfterOOBException automatically gets the debuggee past an OOB exception event. These are only BP or SS
// events. For SS, we just clear it, assuming that the only reason the thread was stepped in such place was to get it
// off of a BP. For a BP, we clear and backup the IP by one, and turn the trace flag on under the assumption that the
// only thing a debugger is allowed to do with an OOB BP exception is to get us off of it.
//
HRESULT CordbUnmanagedThread::FixupAfterOOBException(CordbUnmanagedEvent *ue)
{
// We really should only be doing things to single steps and breakpoint exceptions.
if (ue->m_currentDebugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
DWORD ec = ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode;
if ((ec == STATUS_BREAKPOINT) || (ec == STATUS_SINGLE_STEP))
{
// Automatically clear the exception.
ue->SetState(CUES_ExceptionCleared);
// Don't bother about toggling the single-step flag. OOB BPs should only be called
// for raw int3 instructions, so no need to rewind and reexecute.
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Setup to skip an native breakpoint
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::SetupForSkipBreakpoint(NativePatch * pNativePatch)
{
_ASSERTE(pNativePatch != NULL);
_ASSERTE(!IsSkippingNativePatch());
_ASSERTE(m_pPatchSkipAddress == NULL);
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
SetState(CUTS_SkippingNativePatch);
#ifdef _DEBUG
// For debugging, provide a way that Cordbg devs can see if we're silently skipping BPs.
static DWORD fTrapOnSkip = -1;
if (fTrapOnSkip == -1)
fTrapOnSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgTrapOnSkip);
if (fTrapOnSkip)
{
CONSISTENCY_CHECK_MSGF(false, ("The CLR is skipping a native BP at %p on thread 0x%x (%d)."
"\nYou're getting this notification in debug builds b/c you have com+ var 'DbgTrapOnSkip' enabled.",
pNativePatch->pAddress, this->m_id, this->m_id));
// We skipped this BP b/c IsCantStop was true. For debugging convenience, call IsCantStop here
// (in case we break at the assert above and want to trace why we're in a CS region)
bool fCantStop = this->IsCantStop();
LOG((LF_CORDB, LL_INFO1000, "In Can'tStopRegion = %d\n", fCantStop));
// Refresh the reg key
fTrapOnSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgTrapOnSkip);
}
#endif
#if defined(TARGET_X86)
STRESS_LOG2(LF_CORDB, LL_INFO100, "CUT::SetupSkip. addr=%p. Opcode=%x\n", pNativePatch->pAddress, (DWORD) pNativePatch->opcode);
#endif
// Replace the BP w/ the opcode.
RemoveRemotePatch(GetProcess(), pNativePatch->pAddress, pNativePatch->opcode);
// Enable the SS flag & Adjust IP.
HRESULT hr = this->EnableSSAfterBP();
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
// Now we return,
// Process continues, LS will single step past BP, and fire a SS exception.
// When we get the SS, we res
// We need to remember this so we can make sure we fixup at the proper address.
// The address of a ss exception is the instruction we finish on, not where
// we originally placed the BP. Since instructions can be variable length,
// we can't work backwards.
m_pPatchSkipAddress = pNativePatch->pAddress;
}
//-----------------------------------------------------------------------------
// Second half of skipping a native bp.
// Note we pass the address in b/c our caller has (from the debug_evet), and
// we don't want to waste storage to remember it ourselves.
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::FixupForSkipBreakpoint()
{
_ASSERTE(m_pPatchSkipAddress != NULL);
_ASSERTE(IsSkippingNativePatch());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
ClearState(CUTS_SkippingNativePatch);
// Only reapply the int3 if it hasn't been removed yet.
if (GetProcess()->GetNativePatch(m_pPatchSkipAddress) != NULL)
{
ApplyRemotePatch(GetProcess(), m_pPatchSkipAddress);
STRESS_LOG1(LF_CORDB, LL_INFO100, "CUT::FixupSetupSkip. addr=%p\n", m_pPatchSkipAddress);
}
else
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "CUT::FixupSetupSkip. Patch removed. Not-reading. addr=%p\n", m_pPatchSkipAddress);
}
m_pPatchSkipAddress = NULL;
}
inline TADDR GetSP(DT_CONTEXT* context)
{
#if defined(TARGET_X86)
return (TADDR)context->Esp;
#elif defined(TARGET_AMD64)
return (TADDR)context->Rsp;
#elif defined(TARGET_ARM) || defined(TARGET_ARM64)
return (TADDR)context->Sp;
#else
_ASSERTE(!"nyi for platform");
#endif
}
BOOL CordbUnmanagedThread::GetStackRange(CORDB_ADDRESS *pBase, CORDB_ADDRESS *pLimit)
{
#if !defined(FEATURE_DBGIPC_TRANSPORT)
if (m_stackBase == 0 && m_stackLimit == 0)
{
HANDLE hProc;
DT_CONTEXT tempContext;
MEMORY_BASIC_INFORMATION mbi;
tempContext.ContextFlags = DT_CONTEXT_FULL;
if (SUCCEEDED(GetProcess()->GetHandle(&hProc)) &&
SUCCEEDED(GetThreadContext(&tempContext)) &&
::VirtualQueryEx(hProc, (LPCVOID)GetSP(&tempContext), &mbi, sizeof(mbi)) != 0)
{
// the lowest stack address is the AllocationBase
TADDR limit = PTR_TO_TADDR(mbi.AllocationBase);
// Now, on to find the stack base:
// Closest to the AllocationBase we might have a MEM_RESERVED block
// for all the as yet unallocated pages...
TADDR regionBase = limit;
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_RESERVE)
regionBase += mbi.RegionSize;
// Next we might have a few guard pages
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_COMMIT && (mbi.Protect & PAGE_GUARD) != 0)
regionBase += mbi.RegionSize;
// And finally the "regular" stack region
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_COMMIT && (mbi.Protect & PAGE_READWRITE) != 0)
regionBase += mbi.RegionSize;
if (limit == regionBase)
goto Exit;
m_stackLimit = limit;
m_stackBase = regionBase;
}
}
Exit:
if (pBase != NULL)
*pBase = m_stackBase;
if (pLimit != NULL)
*pLimit = m_stackLimit;
return (m_stackBase != 0 || m_stackLimit != 0);
#else
if (pBase != NULL)
*pBase = 0;
if (pLimit != NULL)
*pLimit = 0;
return FALSE;
#endif // FEATURE_DBGIPC_TRANSPORT
}
//-----------------------------------------------------------------------------
// Returns the thread context to the state it was in when it last entered RaiseException
// This allows the thread to retrigger an exception caused by RaiseException
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::HijackToRaiseException()
{
LOG((LF_CORDB, LL_INFO1000, "CP::HTRE: hijacking to RaiseException\n"));
_ASSERTE(HasRaiseExceptionEntryCtx());
_ASSERTE(!IsRaiseExceptionHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsContextSet());
BOOL succ = DbiGetThreadContext(m_handle, GetHijackCtx());
_ASSERTE(succ);
succ = DbiSetThreadContext(m_handle, &m_raiseExceptionEntryContext);
_ASSERTE(succ);
SetState(CUTS_IsRaiseExceptionHijacked);
}
//----------------------------------------------------------------------------
// Returns the context to its unhijacked state.
//----------------------------------------------------------------------------
void CordbUnmanagedThread::RestoreFromRaiseExceptionHijack()
{
LOG((LF_CORDB, LL_INFO1000, "CP::RFREH: ending RaiseException hijack\n"));
_ASSERTE(IsRaiseExceptionHijacked());
DT_CONTEXT restoreContext;
restoreContext.ContextFlags = DT_CONTEXT_FULL;
HRESULT hr = GetThreadContext(&restoreContext);
_ASSERTE(SUCCEEDED(hr));
ClearState(CUTS_IsRaiseExceptionHijacked);
hr = SetThreadContext(&restoreContext);
_ASSERTE(SUCCEEDED(hr));
}
//-----------------------------------------------------------------------------
// Attempts to store the state of a thread currently entering RaiseException
// This grabs both a full context and enough state to determine what exception
// RaiseException should be raising. If any of the state can not be retrieved
// then this entrance to RaiseException is silently ignored
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::SaveRaiseExceptionEntryContext()
{
_ASSERTE(FALSE); // should be unused now
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: saving raise exception context.\n"));
_ASSERTE(!HasRaiseExceptionEntryCtx());
_ASSERTE(!IsRaiseExceptionHijacked());
HRESULT hr = S_OK;
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(m_handle, &context);
// if the flag is set, unset it
// we don't want to be single stepping through RaiseException the second time
// sending out OOB SS events. Ultimately we will rethrow the exception which would
// cleared the SS flag anyways.
UnsetSSFlag(&context);
memcpy(&m_raiseExceptionEntryContext, &context, sizeof(DT_CONTEXT));
// calculate the exception that we would expect to come from this invocation of RaiseException
REMOTE_PTR pExceptionInformation = NULL;
#if defined(TARGET_AMD64)
m_raiseExceptionExceptionCode = (DWORD)m_raiseExceptionEntryContext.Rcx;
m_raiseExceptionExceptionFlags = (DWORD)m_raiseExceptionEntryContext.Rdx;
m_raiseExceptionNumberParameters = (DWORD)m_raiseExceptionEntryContext.R8;
pExceptionInformation = (REMOTE_PTR)m_raiseExceptionEntryContext.R9;
#elif defined(TARGET_ARM64)
m_raiseExceptionExceptionCode = (DWORD)m_raiseExceptionEntryContext.X0;
m_raiseExceptionExceptionFlags = (DWORD)m_raiseExceptionEntryContext.X1;
m_raiseExceptionNumberParameters = (DWORD)m_raiseExceptionEntryContext.X2;
pExceptionInformation = (REMOTE_PTR)m_raiseExceptionEntryContext.X3;
#elif defined(TARGET_X86)
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+4), &m_raiseExceptionExceptionCode);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception code.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+8), &m_raiseExceptionExceptionFlags);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception flags.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+12), &m_raiseExceptionNumberParameters);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read number of parameters.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+16), &pExceptionInformation);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception information pointer.\n"));
return;
}
#else
_ASSERTE(!"Implement this for your platform");
return;
#endif
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: RaiseException parameters are 0x%x 0x%x 0x%x 0x%p.\n",
m_raiseExceptionExceptionCode, m_raiseExceptionExceptionFlags,
m_raiseExceptionNumberParameters, pExceptionInformation));
TargetBuffer exceptionInfoTargetBuffer(pExceptionInformation, sizeof(REMOTE_PTR)*m_raiseExceptionNumberParameters);
EX_TRY
{
m_pProcess->SafeReadBuffer(exceptionInfoTargetBuffer, (BYTE*)m_raiseExceptionExceptionInformation);
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception information.\n"));
return;
}
// If everything was succesful then set this flag, otherwise none of the above data is considered valid
SetState(CUTS_HasRaiseExceptionEntryCtx);
return;
}
//-----------------------------------------------------------------------------
// Clears all the state saved in SaveRaiseExceptionContext and returns the thread
// to the state as if RaiseException has yet to be called. This is typically called
// after an exception retriggers or after determining that the exception never will
// retrigger.
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::ClearRaiseExceptionEntryContext()
{
_ASSERTE(FALSE); // should be unused now
LOG((LF_CORDB, LL_INFO1000, "CP::CREEC: clearing raise exception context.\n"));
_ASSERTE(HasRaiseExceptionEntryCtx());
ClearState(CUTS_HasRaiseExceptionEntryCtx);
}
//-----------------------------------------------------------------------------
// Uses a heuristic to determine if the given exception record is likely to be the exception
// raised by the last invocation of RaiseException on this thread. The current heuristic compares
// ExceptionCode, ExceptionFlags, and all ExceptionInformation.
//-----------------------------------------------------------------------------
BOOL CordbUnmanagedThread::IsExceptionFromLastRaiseException(const EXCEPTION_RECORD* pExceptionRecord)
{
_ASSERTE(FALSE); // should be unused now
if(!HasRaiseExceptionEntryCtx())
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - no previous raise context\n"));
return FALSE;
}
if (pExceptionRecord->ExceptionCode != m_raiseExceptionExceptionCode)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - exception codes differ 0x%x 0x%x\n",
pExceptionRecord->ExceptionCode, m_raiseExceptionExceptionCode));
return FALSE;
}
if (pExceptionRecord->ExceptionFlags != m_raiseExceptionExceptionFlags)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - exception flags differ 0x%x 0x%x\n",
pExceptionRecord->ExceptionFlags, m_raiseExceptionExceptionFlags));
return FALSE;
}
if (pExceptionRecord->NumberParameters != m_raiseExceptionNumberParameters)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - number parameters differ 0x%x 0x%x\n",
pExceptionRecord->NumberParameters, m_raiseExceptionNumberParameters));
return FALSE;
}
for(DWORD i = 0; i < pExceptionRecord->NumberParameters; i++)
{
if(m_raiseExceptionExceptionInformation[i] != pExceptionRecord->ExceptionInformation[i])
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - param %d differs 0x%x 0x%x\n",
i, pExceptionRecord->ExceptionInformation[i], m_raiseExceptionExceptionInformation[i]));
return FALSE;
}
}
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: match\n"));
return TRUE;
}
//-----------------------------------------------------------------------------
// Inject an int3 at the given remote address
//-----------------------------------------------------------------------------
// This flavor is assuming our caller already knows the opcode.
HRESULT ApplyRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const BYTE patch = CORDbg_BREAK_INSTRUCTION;
#elif defined(TARGET_ARM64)
const PRD_TYPE patch = CORDbg_BREAK_INSTRUCTION;
#else
const BYTE patch = 0;
PORTABILITY_ASSERT("NYI: ApplyRemotePatch for this platform");
#endif
HRESULT hr = pProcess->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &patch);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
return S_OK;
}
// Get the opcode that we're replacing.
HRESULT ApplyRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress, PRD_TYPE * pOpcode)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// Read out opcode. 1 byte on x86
BYTE opcode;
#elif defined(TARGET_ARM64)
// Read out opcode. 4 bytes on arm64
PRD_TYPE opcode;
#else
BYTE opcode;
PORTABILITY_ASSERT("NYI: ApplyRemotePatch for this platform");
#endif
HRESULT hr = pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &opcode);
if (FAILED(hr))
{
return hr;
}
*pOpcode = (PRD_TYPE) opcode;
ApplyRemotePatch(pProcess, pRemoteAddress);
return S_OK;
}
//-----------------------------------------------------------------------------
// Remove the int3 from the remote address
//-----------------------------------------------------------------------------
HRESULT RemoveRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress, PRD_TYPE opcode)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// Replace the BP w/ the opcode.
BYTE opcode2 = (BYTE) opcode;
#elif defined(TARGET_ARM64)
// 4 bytes on arm64
PRD_TYPE opcode2 = opcode;
#else
PRD_TYPE opcode2 = opcode;
PORTABILITY_ASSERT("NYI: RemoveRemotePatch for this platform");
#endif
pProcess->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &opcode2);
// This may fail because the module has been unloaded. In which case, the patch is also
// gone so it makes sense to return success.
return S_OK;
}
#endif // FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// Simple helper to return the SP value stored in a DebuggerREGDISPLAY.
//
// Arguments:
// pDRD - the DebuggerREGDISPLAY in question
//
// Return Value:
// the SP value
//
inline CORDB_ADDRESS GetSPFromDebuggerREGDISPLAY(DebuggerREGDISPLAY* pDRD)
{
return pDRD->SP;
}
HRESULT CordbContext::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugContext)
*pInterface = static_cast<ICorDebugContext*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugContext*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
/* ------------------------------------------------------------------------- *
* Frame class
* ------------------------------------------------------------------------- */
// This is just used as a proxy object to pass a FramePointer around.
CordbFrame::CordbFrame(CordbProcess * pProcess, FramePointer fp)
: CordbBase(pProcess, 0, enumCordbFrame),
m_fp(fp)
{
UnsafeNeuterDeadObject(); // mark as neutered.
}
CordbFrame::CordbFrame(CordbThread * pThread,
FramePointer fp,
SIZE_T ip,
CordbAppDomain * pCurrentAppDomain)
: CordbBase(pThread->GetProcess(), 0, enumCordbFrame),
m_ip(ip),
m_pThread(pThread),
m_currentAppDomain(pCurrentAppDomain),
m_fp(fp)
{
#ifdef _DEBUG
// For debugging purposes, track what Continue session these frames were created in.
m_DbgContinueCounter = GetProcess()->m_continueCounter;
#endif
HRESULT hr = S_OK;
EX_TRY
{
m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
CordbFrame::~CordbFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by DerivedClasses
void CordbFrame::Neuter()
{
CordbBase::Neuter();
}
HRESULT CordbFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
*pInterface = static_cast<ICorDebugFrame*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugFrame*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetChain
//
// Description:
// Return the owning chain. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the owning chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
// Return E_FAIL if failed to find the chain
//
HRESULT CordbFrame::GetChain(ICorDebugChain **ppChain)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppChain);
*ppChain = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetChainForFrame(static_cast<ICorDebugFrame *>(this), ppChain);
if (*ppChain == NULL)
hr = E_FAIL;
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the stack range taken up by this frame.
// Note that this is not implemented in the base CordbFrame class.
// Instead, this is implemented by the derived classes.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Notes: see code:#GetStackRange
HRESULT CordbFrame::GetStackRange(CORDB_ADDRESS *pStart, CORDB_ADDRESS *pEnd)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(pStart);
ValidateOrThrow(pEnd);
hr = E_NOTIMPL;
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the ICorDebugFunction associated with this frame.
// There is one ICorDebugFunction for each EnC version of a method.
HRESULT CordbFrame::GetFunction(ICorDebugFunction **ppFunction)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFunction);
CordbFunction * pFunc = this->GetFunction();
if (pFunc == NULL)
{
ThrowHR(CORDBG_E_CODE_NOT_AVAILABLE);
}
// @dbgtodo LCG methods, IL stubs, dynamic language debugging
// Don't return an ICDFunction if we are dealing with a dynamic method.
// The dynamic debugging feature crew needs to decide exactly what to hand out for dynamic methods.
if (pFunc->GetMetadataToken() == mdMethodDefNil)
{
ThrowHR(CORDBG_E_CODE_NOT_AVAILABLE);
}
*ppFunction = static_cast<ICorDebugFunction *>(pFunc);
pFunc->ExternalAddRef();
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the token of the ICorDebugFunction associated with this frame.
// There is one ICorDebugFunction for each EnC version of a method.
HRESULT CordbFrame::GetFunctionToken(mdMethodDef *pToken)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(pToken);
CordbFunction * pFunc = GetFunction();
if (pFunc == NULL)
{
hr = CORDBG_E_CODE_NOT_AVAILABLE;
}
else
{
*pToken = pFunc->GetMetadataToken();
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetCaller
//
// Description:
// Return the caller of this frame. The caller is closer to the root.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the caller frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbFrame::GetCaller(ICorDebugFrame **ppFrame)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFrame);
*ppFrame = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetCallerForFrame(this, ppFrame);
}
else
{
*ppFrame = NULL;
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetCallee
//
// Description:
// Return the callee of this frame. The callee is closer to the leaf.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the callee frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbFrame::GetCallee(ICorDebugFrame **ppFrame)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFrame);
*ppFrame = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetCalleeForFrame(static_cast<ICorDebugFrame *>(this), ppFrame);
}
else
{
*ppFrame = NULL;
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Create a stepper on the frame.
HRESULT CordbFrame::CreateStepper(ICorDebugStepper **ppStepper)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStepper, ICorDebugStepper **);
HRESULT hr = S_OK;
EX_TRY
{
RSInitHolder<CordbStepper> pStepper(new CordbStepper(m_pThread, this));
pStepper.TransferOwnershipExternal(ppStepper);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given a frame pointer, determine if it is in the stack range owned by the frame.
//
// Arguments:
// fp - frame pointer to check
//
// Return Value:
// whether the specified frame pointer is in the stack range or not
//
bool CordbFrame::IsContainedInFrame(FramePointer fp)
{
CORDB_ADDRESS stackStart;
CORDB_ADDRESS stackEnd;
// get the stack range
HRESULT hr;
hr = GetStackRange(&stackStart, &stackEnd);
_ASSERTE(SUCCEEDED(hr));
CORDB_ADDRESS sp = PTR_TO_CORDB_ADDRESS(fp.GetSPValue());
if ((stackStart <= sp) && (sp <= stackEnd))
{
return true;
}
else
{
return false;
}
}
//---------------------------------------------------------------------------------------
//
// Given an ICorDebugFrame interface pointer, return a pointer to the base class CordbFrame.
//
// Arguments:
// pFrame - the ICorDebugFrame interface pointer
//
// Return Value:
// the CordbFrame pointer corresponding to the specified interface pointer
//
// Note:
// This is currently only used for continuable exceptions.
//
// static
CordbFrame* CordbFrame::GetCordbFrameFromInterface(ICorDebugFrame *pFrame)
{
CordbFrame* pTargetFrame = NULL;
if (pFrame != NULL)
{
// test for CordbNativeFrame
RSExtSmartPtr<ICorDebugNativeFrame> pNativeFrame;
pFrame->QueryInterface(IID_ICorDebugNativeFrame, (void**)&pNativeFrame);
if (pNativeFrame != NULL)
{
pTargetFrame = static_cast<CordbFrame*>(static_cast<CordbNativeFrame*>(pNativeFrame.GetValue()));
}
else
{
// test for CordbJITILFrame
RSExtSmartPtr<ICorDebugILFrame> pILFrame;
pFrame->QueryInterface(IID_ICorDebugILFrame, (void**)&pILFrame);
if (pILFrame != NULL)
{
pTargetFrame = (static_cast<CordbJITILFrame*>(pILFrame.GetValue()))->m_nativeFrame;
}
else
{
// test for CordbInternalFrame
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
pFrame->QueryInterface(IID_ICorDebugInternalFrame, (void**)&pInternalFrame);
if (pInternalFrame != NULL)
{
pTargetFrame = static_cast<CordbFrame*>(static_cast<CordbInternalFrame*>(pInternalFrame.GetValue()));
}
else
{
// when all else fails, this is just a CordbFrame
pTargetFrame = static_cast<CordbFrame*>(pFrame);
}
}
}
}
return pTargetFrame;
}
/* ------------------------------------------------------------------------- *
* Value Enumerator class
*
* Used by CordbJITILFrame for EnumLocalVars & EnumArgs.
* NOTE NOTE NOTE WE ASSUME that the 'frame' argument is actually the
* CordbJITILFrame's native frame member variable.
* ------------------------------------------------------------------------- */
CordbValueEnum::CordbValueEnum(CordbNativeFrame *frame, ValueEnumMode mode) :
CordbBase(frame->GetProcess(), 0)
{
_ASSERTE( frame != NULL );
_ASSERTE( mode == LOCAL_VARS_ORIGINAL_IL || mode == LOCAL_VARS_REJIT_IL || mode == ARGS);
m_frame = frame;
m_mode = mode;
m_iCurrent = 0;
m_iMax = 0;
}
/*
* CordbValueEnum::Init
*
* Initialize a CordbValueEnum object. Must be called after allocating the object and before using it. If Init
* fails, then destroy the object and release the memory.
*
* Parameters:
* none.
*
* Returns:
* HRESULT for success or failure.
*
*/
HRESULT CordbValueEnum::Init()
{
HRESULT hr = S_OK;
CordbNativeFrame *nil = m_frame;
CordbJITILFrame *jil = nil->m_JITILFrame;
switch (m_mode)
{
case ARGS:
{
// Get the function signature
CordbFunction *func = m_frame->GetFunction();
ULONG methodArgCount;
IfFailRet(func->GetSig(NULL, &methodArgCount, NULL));
// Grab the argument count for the size of the enumeration.
m_iMax = methodArgCount;
if (jil->m_fVarArgFnx && !jil->m_sigParserCached.IsNull())
{
m_iMax = jil->m_allArgsCount;
}
break;
}
case LOCAL_VARS_ORIGINAL_IL:
{
// Get the locals signature.
ULONG localsCount;
IfFailRet(jil->GetOriginalILCode()->GetLocalVarSig(NULL, &localsCount));
// Grab the number of locals for the size of the enumeration.
m_iMax = localsCount;
break;
}
case LOCAL_VARS_REJIT_IL:
{
// Get the locals signature.
ULONG localsCount;
CordbReJitILCode* pCode = jil->GetReJitILCode();
if (pCode == NULL)
{
m_iMax = 0;
}
else
{
IfFailRet(pCode->GetLocalVarSig(NULL, &localsCount));
// Grab the number of locals for the size of the enumeration.
m_iMax = localsCount;
}
break;
}
}
// Everything worked okay, so add this object to the neuter list for objects that are tied to the stack trace.
EX_TRY
{
m_frame->m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
return hr;
}
CordbValueEnum::~CordbValueEnum()
{
_ASSERTE(this->IsNeutered());
_ASSERTE(m_frame == NULL);
}
void CordbValueEnum::Neuter()
{
m_frame = NULL;
CordbBase::Neuter();
}
HRESULT CordbValueEnum::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEnum)
*pInterface = static_cast<ICorDebugEnum*>(this);
else if (id == IID_ICorDebugValueEnum)
*pInterface = static_cast<ICorDebugValueEnum*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugValueEnum*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbValueEnum::Skip(ULONG celt)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = E_FAIL;
if ( (m_iCurrent+celt) < m_iMax ||
celt == 0)
{
m_iCurrent += celt;
hr = S_OK;
}
return hr;
}
HRESULT CordbValueEnum::Reset()
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
m_iCurrent = 0;
return S_OK;
}
HRESULT CordbValueEnum::Clone(ICorDebugEnum **ppEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppEnum, ICorDebugEnum **);
HRESULT hr = S_OK;
EX_TRY
{
*ppEnum = NULL;
RSInitHolder<CordbValueEnum> pCVE(new CordbValueEnum(m_frame, m_mode));
// Initialize the new enum
hr = pCVE->Init();
IfFailThrow(hr);
pCVE.TransferOwnershipExternal(ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbValueEnum::GetCount(ULONG *pcelt)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(pcelt, ULONG *);
if( pcelt == NULL)
{
return E_INVALIDARG;
}
(*pcelt) = m_iMax;
return S_OK;
}
//
// In the event of failure, the current pointer will be left at
// one element past the troublesome element. Thus, if one were
// to repeatedly ask for one element to iterate through the
// array, you would iterate exactly m_iMax times, regardless
// of individual failures.
HRESULT CordbValueEnum::Next(ULONG celt, ICorDebugValue *values[], ULONG *pceltFetched)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(values, ICorDebugValue *,
celt, true, true);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pceltFetched, ULONG *);
if ((pceltFetched == NULL) && (celt != 1))
{
return E_INVALIDARG;
}
if (celt == 0)
{
if (pceltFetched != NULL)
{
*pceltFetched = 0;
}
return S_OK;
}
HRESULT hr = S_OK;
int iMax = min( m_iMax, m_iCurrent+celt);
int i;
for (i = m_iCurrent; i< iMax;i++)
{
switch ( m_mode )
{
case ARGS:
{
hr = m_frame->m_JITILFrame->GetArgument( i, &(values[i-m_iCurrent]) );
break;
}
case LOCAL_VARS_ORIGINAL_IL:
{
hr = m_frame->m_JITILFrame->GetLocalVariableEx(ILCODE_ORIGINAL_IL, i, &(values[i-m_iCurrent]) );
break;
}
case LOCAL_VARS_REJIT_IL:
{
hr = m_frame->m_JITILFrame->GetLocalVariableEx(ILCODE_REJIT_IL, i, &(values[i - m_iCurrent]));
break;
}
}
if ( FAILED( hr ) )
{
break;
}
}
int count = (i - m_iCurrent);
if ( FAILED( hr ) )
{
//
// we failed: +1 pushes us past troublesome element
//
m_iCurrent += 1 + count;
}
else
{
m_iCurrent += count;
}
if (pceltFetched != NULL)
{
*pceltFetched = count;
}
if (FAILED(hr))
{
return hr;
}
//
// If we reached the end of the enumeration, but not the end
// of the number of requested items, we return S_FALSE.
//
if (((ULONG)count) < celt)
{
return S_FALSE;
}
return hr;
}
//-----------------------------------------------------------------------------
// CordbInternalFrame
//-----------------------------------------------------------------------------
CordbInternalFrame::CordbInternalFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
const DebuggerIPCE_STRData * pData)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
m_eFrameType = pData->stubFrame.frameType;
m_funcMetadataToken = pData->stubFrame.funcMetadataToken;
m_vmMethodDesc = pData->stubFrame.vmMethodDesc;
// Some internal frames may not have a Function associated w/ them.
if (!IsNilToken(m_funcMetadataToken))
{
// Find the module of the function. Note that this module isn't necessarily in the same domain as our frame.
// FuncEval frames can point to methods they are going to invoke in another domain.
CordbModule * pModule = NULL;
pModule = GetProcess()->LookupOrCreateModule(pData->stubFrame.vmDomainAssembly);
_ASSERTE(pModule != NULL);
//
if( pModule != NULL )
{
_ASSERTE( (pModule->GetAppDomain() == pCurrentAppDomain) || (m_eFrameType == STUBFRAME_FUNC_EVAL) );
mdMethodDef token = pData->stubFrame.funcMetadataToken;
// @dbgtodo synchronization - push this up.
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// CordbInternalFrame could handle a null function.
// But if we fail to lookup, things are not in a good state anyways.
CordbFunction * pFunction = pModule->LookupOrCreateFunctionLatestVersion(token);
m_function.Assign(pFunction);
}
}
}
CordbInternalFrame::CordbInternalFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
CorDebugInternalFrameType frameType,
mdMethodDef funcMetadataToken,
CordbFunction * pFunction,
VMPTR_MethodDesc vmMethodDesc)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain)
{
m_eFrameType = frameType;
m_funcMetadataToken = funcMetadataToken;
m_function.Assign(pFunction);
m_vmMethodDesc = vmMethodDesc;
}
HRESULT CordbInternalFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugInternalFrame*>(this));
}
else if (id == IID_ICorDebugInternalFrame)
{
*pInterface = static_cast<ICorDebugInternalFrame*>(this);
}
else if (id == IID_ICorDebugInternalFrame2)
{
*pInterface = static_cast<ICorDebugInternalFrame2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugInternalFrame*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
void CordbInternalFrame::Neuter()
{
m_function.Clear();
CordbFrame::Neuter();
}
// ----------------------------------------------------------------------------
// CordbInternalFrame::GetStackRange
//
// Description:
// Return the stack range owned by this frame.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes:
// #GetStackRange
// This is a virtual function and so there are multiple implementations for different types of frames.
// It's very important to note that GetStackRange() can work when even after the frame is neutered.
// Debuggers may rely on this to map old frames up to new frames across Continue() calls.
//
HRESULT CordbInternalFrame::GetStackRange(CORDB_ADDRESS *pStart,
CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// Callers explicit require GetStackRange() to be callable when neutered so that they
// can line up ICorDebugFrame objects across continues. We only return stack ranges
// here and don't access any special data.
OK_IF_NEUTERED(this);
if (GetProcess()->GetShim() != NULL)
{
CORDB_ADDRESS pFramePointer = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
if (pStart)
{
*pStart = pFramePointer;
}
if (pEnd)
{
*pEnd = pFramePointer;
}
return S_OK;
}
else
{
if (pStart != NULL)
{
*pStart = NULL;
}
if (pEnd != NULL)
{
*pEnd = NULL;
}
return E_NOTIMPL;
}
}
// This may return NULL if there's no Method associated w/ this Frame.
// For FuncEval frames, the function returned might also be in a different AppDomain
// than the frame itself.
CordbFunction * CordbInternalFrame::GetFunction()
{
return m_function;
}
// Accessor for the shim private hook code:CordbThread::ConvertFrameForILMethodWithoutMetadata.
// Refer to that function for comments on the return value, the argument, etc.
BOOL CordbInternalFrame::ConvertInternalFrameForILMethodWithoutMetadata(
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
// The only internal frame conversion we need to perform is from STUBFRAME_JIT_COMPILATION to
// STUBFRAME_LIGTHWEIGHT_FUNCTION.
if (m_eFrameType != STUBFRAME_JIT_COMPILATION)
{
return FALSE;
}
// Check whether the internal frame has an associated MethodDesc.
// Currently, the only STUBFRAME_JIT_COMPILATION frame with a NULL MethodDesc is ComPrestubMethodFrame,
// which is not exposed in Whidbey. So convert it according to rule #2 below.
if (m_vmMethodDesc.IsNull())
{
return TRUE;
}
// Retrieve the type of the method associated with the STUBFRAME_JIT_COMPILATION.
IDacDbiInterface::DynamicMethodType type = GetProcess()->GetDAC()->IsILStubOrLCGMethod(m_vmMethodDesc);
// Here are the conversion rules:
// 1) For a normal managed method, we don't convert, and we return FALSE.
// 2) For an IL stub, we convert to NULL, and we return TRUE.
// 3) For a dynamic method, we convert to a STUBFRAME_LIGHTWEIGHT_FUNCTION, and we return TRUE.
if (type == IDacDbiInterface::kNone)
{
return FALSE;
}
else if (type == IDacDbiInterface::kILStub)
{
return TRUE;
}
else if (type == IDacDbiInterface::kLCGMethod)
{
// Here we are basically cloning another CordbInternalFrame.
RSInitHolder<CordbInternalFrame> pInternalFrame(new CordbInternalFrame(m_pThread,
m_fp,
m_currentAppDomain,
STUBFRAME_LIGHTWEIGHT_FUNCTION,
m_funcMetadataToken,
m_function.GetValue(),
m_vmMethodDesc));
pInternalFrame.TransferOwnershipExternal(ppInternalFrame2);
return TRUE;
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Returns the address of an internal frame. The address is a stack pointer, even on IA64.
//
// Arguments:
// pAddress - out parameter; return the frame marker address
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if pAddress is NULL.
//
HRESULT CordbInternalFrame::GetAddress(CORDB_ADDRESS * pAddress)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (pAddress == NULL)
{
return E_INVALIDARG;
}
*pAddress = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Refer to the comment for code:CordbInternalFrame::IsCloserToLeaf
//
BOOL CordbInternalFrame::IsCloserToLeafWorker(ICorDebugFrame * pFrameToCompare)
{
// Get the address of the "this" internal frame.
CORDB_ADDRESS thisFrameAddr = PTR_TO_CORDB_ADDRESS(this->GetFramePointer().GetSPValue());
// Note that a QI on ICorDebugJITILFrame for ICorDebugNativeFrame will work.
RSExtSmartPtr<ICorDebugNativeFrame> pNativeFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugNativeFrame, (void **)&pNativeFrame);
if (pNativeFrame != NULL)
{
// The frame to compare is a CordbNativeFrame.
CordbNativeFrame * pCNativeFrame = static_cast<CordbNativeFrame *>(pNativeFrame.GetValue());
// Compare the address of the "this" internal frame to the SP of the stack frame.
// We can't compare frame pointers because the frame pointer means different things on
// different platforms.
CORDB_ADDRESS stackFrameSP = GetSPFromDebuggerREGDISPLAY(&(pCNativeFrame->m_rd));
return (thisFrameAddr < stackFrameSP);
}
RSExtSmartPtr<ICorDebugRuntimeUnwindableFrame> pRUFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugRuntimeUnwindableFrame, (void **)&pRUFrame);
if (pRUFrame != NULL)
{
// The frame to compare is a CordbRuntimeUnwindableFrame.
CordbRuntimeUnwindableFrame * pCRUFrame =
static_cast<CordbRuntimeUnwindableFrame *>(pRUFrame.GetValue());
DT_CONTEXT * pResumeContext = const_cast<DT_CONTEXT *>(pCRUFrame->GetContext());
CORDB_ADDRESS stackFrameSP = PTR_TO_CORDB_ADDRESS(CORDbgGetSP(pResumeContext));
return (thisFrameAddr < stackFrameSP);
}
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugInternalFrame, (void **)&pInternalFrame);
if (pInternalFrame != NULL)
{
// The frame to compare is a CordbInternalFrame.
CordbInternalFrame * pCInternalFrame =
static_cast<CordbInternalFrame *>(pInternalFrame.GetValue());
CORDB_ADDRESS frameAddr = PTR_TO_CORDB_ADDRESS(pCInternalFrame->GetFramePointer().GetSPValue());
return (thisFrameAddr < frameAddr);
}
// What does this mean? This is unexpected.
_ASSERTE(!"CIF::ICTLW - Unexpected frame type.\n");
ThrowHR(E_FAIL);
}
//---------------------------------------------------------------------------------------
//
// Checks whether the "this" internal frame is closer to the leaf than the specified ICDFrame.
// If the specified ICDFrame represents a stack frame, then we compare the address of the "this"
// internal frame against the SP of the stack frame.
//
// Arguments:
// pFrameToCompare - the ICDFrame to compare against
// pIsCloser - out parameter; returns TRUE if the "this" internal frame is closer to the leaf
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if pFrameToCompare or pIsCloser is NULL.
// E_FAIL if pFrameToCompare is bogus.
//
// Notes:
// This function doesn't deal with the backing store at all.
//
HRESULT CordbInternalFrame::IsCloserToLeaf(ICorDebugFrame * pFrameToCompare,
BOOL * pIsCloser)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this);
{
ValidateOrThrow(pFrameToCompare);
ValidateOrThrow(pIsCloser);
*pIsCloser = IsCloserToLeafWorker(pFrameToCompare);
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
CordbRuntimeUnwindableFrame::CordbRuntimeUnwindableFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
DT_CONTEXT * pContext)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain),
m_context(*pContext)
{
}
void CordbRuntimeUnwindableFrame::Neuter()
{
CordbFrame::Neuter();
}
HRESULT CordbRuntimeUnwindableFrame::QueryInterface(REFIID id, void ** ppInterface)
{
if (id == IID_ICorDebugFrame)
{
*ppInterface = static_cast<ICorDebugFrame *>(static_cast<ICorDebugRuntimeUnwindableFrame *>(this));
}
else if (id == IID_ICorDebugRuntimeUnwindableFrame)
{
*ppInterface = static_cast<ICorDebugRuntimeUnwindableFrame *>(this);
}
else if (id == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown *>(static_cast<ICorDebugRuntimeUnwindableFrame *>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Returns the CONTEXT corresponding to this CordbRuntimeUnwindableFrame.
//
// Return Value:
// Return a pointer to the CONTEXT.
//
const DT_CONTEXT * CordbRuntimeUnwindableFrame::GetContext() const
{
return &m_context;
}
// default constructor to make the compiler happy
CordbMiscFrame::CordbMiscFrame()
{
#ifdef FEATURE_EH_FUNCLETS
this->parentIP = 0;
this->fpParentOrSelf = LEAF_MOST_FRAME;
this->fIsFilterFunclet = false;
#endif // FEATURE_EH_FUNCLETS
}
// the real constructor which stores the funclet-related information in the CordbMiscFrame
CordbMiscFrame::CordbMiscFrame(DebuggerIPCE_JITFuncData * pJITFuncData)
{
#ifdef FEATURE_EH_FUNCLETS
this->parentIP = pJITFuncData->parentNativeOffset;
this->fpParentOrSelf = pJITFuncData->fpParentOrSelf;
this->fIsFilterFunclet = (pJITFuncData->fIsFilterFrame == TRUE);
#endif // FEATURE_EH_FUNCLETS
}
/* ------------------------------------------------------------------------- *
* Native Frame class
* ------------------------------------------------------------------------- */
CordbNativeFrame::CordbNativeFrame(CordbThread * pThread,
FramePointer fp,
CordbNativeCode * pNativeCode,
SIZE_T ip,
DebuggerREGDISPLAY * pDRD,
TADDR taAmbientESP,
bool fQuicklyUnwound,
CordbAppDomain * pCurrentAppDomain,
CordbMiscFrame * pMisc /*= NULL*/,
DT_CONTEXT * pContext /*= NULL*/)
: CordbFrame(pThread, fp, ip, pCurrentAppDomain),
m_rd(*pDRD),
m_quicklyUnwound(fQuicklyUnwound),
m_JITILFrame(NULL),
m_nativeCode(pNativeCode), // implicit InternalAddRef
m_taAmbientESP(taAmbientESP)
{
m_misc = *pMisc;
// Only new CordbNativeFrames created by the new stackwalk contain a CONTEXT.
_ASSERTE(pContext != NULL);
m_context = *pContext;
}
/*
A list of which resources owned by this object are accounted for.
RESOLVED:
CordbJITILFrame* m_JITILFrame; // Neutered
*/
CordbNativeFrame::~CordbNativeFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by CordbThread::CleanupStack
void CordbNativeFrame::Neuter()
{
// Neuter may be called multiple times so be sure to set ptrs to NULL so that we don't
// double release them.
if (IsNeutered())
{
return;
}
m_nativeCode.Clear();
if (m_JITILFrame != NULL)
{
m_JITILFrame->Neuter();
m_JITILFrame.Clear();
}
CordbFrame::Neuter();
}
// CordbNativeFrame::QueryInterface
//
// Description
// interface query for this COM object
//
// NOTE: the COM object associated with this CordbNativeFrame may consist of
// two C++ objects (the CordbNativeFrame and the CordbJITILFrame).
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
//
HRESULT CordbNativeFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugNativeFrame*>(this));
}
else if (id == IID_ICorDebugNativeFrame)
{
*pInterface = static_cast<ICorDebugNativeFrame*>(this);
}
else if (id == IID_ICorDebugNativeFrame2)
{
*pInterface = static_cast<ICorDebugNativeFrame2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugNativeFrame*>(this));
}
else
{
// might be searching for an IL Frame. delegate that search to the
// JITILFrame
if (m_JITILFrame != NULL)
{
return m_JITILFrame->QueryInterfaceInternal(id, pInterface);
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
}
ExternalAddRef();
return S_OK;
}
// Return the CordbNativeCode object associated with this native frame.
// This is just a wrapper around the real helper.
HRESULT CordbNativeFrame::GetCode(ICorDebugCode **ppCode)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppCode, ICorDebugCode **);
FAIL_IF_NEUTERED(this);
CordbNativeCode * pCode = GetNativeCode();
*ppCode = static_cast<ICorDebugCode*> (pCode);
pCode->ExternalAddRef();
return S_OK;;
}
//---------------------------------------------------------------------------------------
//
// Returns the CONTEXT corresponding to this CordbNativeFrame.
//
// Return Value:
// Return a pointer to the CONTEXT.
//
const DT_CONTEXT * CordbNativeFrame::GetContext() const
{
return &m_context;
}
//---------------------------------------------------------------------------------------
//
// This is an internal helper to get the CordbNativeCode object associated with this native frame.
//
// Return Value:
// the associated CordbNativeCode object
//
CordbNativeCode * CordbNativeFrame::GetNativeCode()
{
return this->m_nativeCode;
}
//---------------------------------------------------------------------------------------
//
// This is an internal helper to get the CordbFunction object associated with this native frame.
//
// Return Value:
// the associated CordbFunction object
//
CordbFunction *CordbNativeFrame::GetFunction()
{
return this->m_nativeCode->GetFunction();
}
// Return the native offset.
HRESULT CordbNativeFrame::GetIP(ULONG32 *pnOffset)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pnOffset, ULONG32 *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*pnOffset = (ULONG32)m_ip;
return S_OK;
}
ULONG32 CordbNativeFrame::GetIPOffset()
{
return (ULONG32)m_ip;
}
TADDR CordbNativeFrame::GetReturnRegisterValue()
{
#if defined(TARGET_X86)
return (TADDR)m_context.Eax;
#elif defined(TARGET_AMD64)
return (TADDR)m_context.Rax;
#elif defined(TARGET_ARM)
return (TADDR)m_context.R0;
#elif defined(TARGET_ARM64)
return (TADDR)m_context.X0;
#else
_ASSERTE(!"nyi for platform");
return 0;
#endif
}
// Determine if we can set IP at this point. The specified offset is the native offset.
HRESULT CordbNativeFrame::CanSetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (!IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
hr = m_pThread->SetIP(SetIP_fCanSetIPOnly,
m_nativeCode,
nOffset,
SetIP_fNative );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Try to set the IP to the specified offset. The specified offset is the native offset.
HRESULT CordbNativeFrame::SetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (!IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
hr = m_pThread->SetIP(SetIP_fSetIP,
m_nativeCode,
nOffset,
SetIP_fNative );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Given a (register,offset) description of a stack location, compute
// the real memory address for it.
// This will also handle ambient SP values (which are encoded with regNum == REGNUM_AMBIENT_SP).
CORDB_ADDRESS CordbNativeFrame::GetLSStackAddress(
ICorDebugInfo::RegNum regNum,
signed offset)
{
UINT_PTR *pRegAddr;
CORDB_ADDRESS pRemoteValue;
if (regNum != DBG_TARGET_REGNUM_AMBIENT_SP)
{
// Even if we're inside a funclet, variables (in both x64 and ARM) are still
// relative to the frame pointer or stack pointer, which are accurate in the
// funclet, after the funclet prolog; the frame pointer is re-established in the
// funclet prolog using the PSP. Thus, we just look up the frame pointer in the
// current native frame.
pRegAddr = this->GetAddressOfRegister(
ConvertRegNumToCorDebugRegister(regNum));
// This should never be null as long as regNum is a member of the RegNum enum.
// If it is, an AV dereferencing a null-pointer in retail builds, or an assert in debug
// builds is exactly the behavior we want.
PREFIX_ASSUME(pRegAddr != NULL);
pRemoteValue = PTR_TO_CORDB_ADDRESS(*pRegAddr + offset);
}
else
{
// Use the ambient ESP. At this point we're decoding an ambient-sp var, so
// we should definitely have an ambient-sp. If this is null, then the jit
// likely gave us an inconsistent data.
TADDR taAmbient = this->GetAmbientESP();
_ASSERTE(taAmbient != NULL);
pRemoteValue = PTR_TO_CORDB_ADDRESS(taAmbient + offset);
}
return pRemoteValue;
}
// ----------------------------------------------------------------------------
// CordbNativeFrame::GetStackRange
//
// Description:
// Return the stack range owned by this native frame.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes: see code:#GetStackRange
HRESULT CordbNativeFrame::GetStackRange(CORDB_ADDRESS *pStart,
CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// Callers explicit require GetStackRange() to be callable when neutered so that they
// can line up ICorDebugFrame objects across continues. We only return stack ranges
// here and don't access any special data.
OK_IF_NEUTERED(this);
if (GetProcess()->GetShim() != NULL)
{
if (pStart)
{
// From register set.
*pStart = GetSPFromDebuggerREGDISPLAY(&m_rd);
}
if (pEnd)
{
// The rootmost boundary is the frame pointer.
// <NOTE>
// This is not true on AMD64, on which we use the stack pointer as the frame pointer.
// </NOTE>
*pEnd = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
}
return S_OK;
}
else
{
if (pStart != NULL)
{
*pStart = NULL;
}
if (pEnd != NULL)
{
*pEnd = NULL;
}
return E_NOTIMPL;
}
}
// Return the register set of the native frame.
HRESULT CordbNativeFrame::GetRegisterSet(ICorDebugRegisterSet **ppRegisters)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppRegisters, ICorDebugRegisterSet **);
HRESULT hr = S_OK;
EX_TRY
{
// allocate a new CordbRegisterSet object
RSInitHolder<CordbRegisterSet> pRegisterSet(new CordbRegisterSet(&m_rd,
m_pThread,
IsLeafFrame(),
m_quicklyUnwound));
pRegisterSet.TransferOwnershipExternal(ppRegisters);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Checks whether the frame is a child frame or not.
//
// Arguments:
// pIsChild - out parameter; returns whether the frame is a child frame
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if the out parmater is NULL.
//
HRESULT CordbNativeFrame::IsChild(BOOL * pIsChild)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
if (pIsChild == NULL)
{
ThrowHR(E_INVALIDARG);
}
else
{
*pIsChild = ((this->IsFunclet() && !this->IsFilterFunclet()) ? TRUE : FALSE);
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given an ICDNativeFrame2, check whether it is the parent frame of the current frame.
//
// Arguments:
// pPotentialParentFrame - the ICDNativeFrame2 to check
// pIsParent - out paramter; returns whether the specified frame is indeed the parent frame
//
// Return Value:
// S_OK on success.
// CORDBG_E_NOT_CHILD_FRAME if the current frame is not a child frame.
// E_INVALIDARG if either of the incoming argument is NULL.
// E_FAIL on other failures.
//
HRESULT CordbNativeFrame::IsMatchingParentFrame(ICorDebugNativeFrame2 * pPotentialParentFrame,
BOOL * pIsParent)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pPotentialParentFrame, ICorDebugNativeFrame2 *);
HRESULT hr = S_OK;
EX_TRY
{
if ((pPotentialParentFrame == NULL) || (pIsParent == NULL))
{
ThrowHR(E_INVALIDARG);
}
*pIsParent = FALSE;
if (!this->IsFunclet())
{
ThrowHR(CORDBG_E_NOT_CHILD_FRAME);
}
#ifdef FEATURE_EH_FUNCLETS
CordbNativeFrame * pFrameToCheck = static_cast<CordbNativeFrame *>(pPotentialParentFrame);
if (pFrameToCheck->IsFunclet())
{
*pIsParent = FALSE;
}
else
{
FramePointer fpParent = this->m_misc.fpParentOrSelf;
FramePointer fpToCheck = pFrameToCheck->m_misc.fpParentOrSelf;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pIsParent = pDAC->IsMatchingParentFrame(fpToCheck, fpParent);
}
#endif // FEATURE_EH_FUNCLETS
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Return the stack parameter size of the current frame. Since this information is only used on x86,
// we return S_FALSE and a size of 0 on WIN64 platforms.
//
// Arguments:
// pSize - out parameter; return the size of the stack parameter
//
// Return Value:
// S_OK on success.
// S_FALSE on WIN64 platforms.
// E_INVALIDARG if pSize is NULL.
//
// Notes:
// Always return S_FALSE on WIN64.
//
HRESULT CordbNativeFrame::GetStackParameterSize(ULONG32 * pSize)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
EX_TRY
{
if (pSize == NULL)
{
ThrowHR(E_INVALIDARG);
}
#if defined(TARGET_X86)
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pSize = pDAC->GetStackParameterSize(PTR_TO_CORDB_ADDRESS(CORDbgGetIP(&m_context)));
#else // !TARGET_X86
hr = S_FALSE;
*pSize = 0;
#endif // TARGET_X86
}
EX_CATCH_HRESULT(hr);
return hr;
}
//
// GetAddressOfRegister returns the address of the given register in the
// frame's current register display (eg, a local address). This is usually used to build a
// ICorDebugValue from.
//
UINT_PTR * CordbNativeFrame::GetAddressOfRegister(CorDebugRegister regNum) const
{
UINT_PTR* ret = NULL;
switch (regNum)
{
case REGISTER_STACK_POINTER:
ret = (UINT_PTR*)GetSPAddress(&m_rd);
break;
#if !defined(TARGET_AMD64) && !defined(TARGET_ARM) // @ARMTODO
case REGISTER_FRAME_POINTER:
ret = (UINT_PTR*)GetFPAddress(&m_rd);
break;
#endif
#if defined(TARGET_X86)
case REGISTER_X86_EAX:
ret = (UINT_PTR*)&m_rd.Eax;
break;
case REGISTER_X86_ECX:
ret = (UINT_PTR*)&m_rd.Ecx;
break;
case REGISTER_X86_EDX:
ret = (UINT_PTR*)&m_rd.Edx;
break;
case REGISTER_X86_EBX:
ret = (UINT_PTR*)&m_rd.Ebx;
break;
case REGISTER_X86_ESI:
ret = (UINT_PTR*)&m_rd.Esi;
break;
case REGISTER_X86_EDI:
ret = (UINT_PTR*)&m_rd.Edi;
break;
#elif defined(TARGET_AMD64)
case REGISTER_AMD64_RBP:
ret = (UINT_PTR*)&m_rd.Rbp;
break;
case REGISTER_AMD64_RAX:
ret = (UINT_PTR*)&m_rd.Rax;
break;
case REGISTER_AMD64_RCX:
ret = (UINT_PTR*)&m_rd.Rcx;
break;
case REGISTER_AMD64_RDX:
ret = (UINT_PTR*)&m_rd.Rdx;
break;
case REGISTER_AMD64_RBX:
ret = (UINT_PTR*)&m_rd.Rbx;
break;
case REGISTER_AMD64_RSI:
ret = (UINT_PTR*)&m_rd.Rsi;
break;
case REGISTER_AMD64_RDI:
ret = (UINT_PTR*)&m_rd.Rdi;
break;
case REGISTER_AMD64_R8:
ret = (UINT_PTR*)&m_rd.R8;
break;
case REGISTER_AMD64_R9:
ret = (UINT_PTR*)&m_rd.R9;
break;
case REGISTER_AMD64_R10:
ret = (UINT_PTR*)&m_rd.R10;
break;
case REGISTER_AMD64_R11:
ret = (UINT_PTR*)&m_rd.R11;
break;
case REGISTER_AMD64_R12:
ret = (UINT_PTR*)&m_rd.R12;
break;
case REGISTER_AMD64_R13:
ret = (UINT_PTR*)&m_rd.R13;
break;
case REGISTER_AMD64_R14:
ret = (UINT_PTR*)&m_rd.R14;
break;
case REGISTER_AMD64_R15:
ret = (UINT_PTR*)&m_rd.R15;
break;
#elif defined(TARGET_ARM)
case REGISTER_ARM_R0:
ret = (UINT_PTR*)&m_rd.R0;
break;
case REGISTER_ARM_R1:
ret = (UINT_PTR*)&m_rd.R1;
break;
case REGISTER_ARM_R2:
ret = (UINT_PTR*)&m_rd.R2;
break;
case REGISTER_ARM_R3:
ret = (UINT_PTR*)&m_rd.R3;
break;
case REGISTER_ARM_R4:
ret = (UINT_PTR*)&m_rd.R4;
break;
case REGISTER_ARM_R5:
ret = (UINT_PTR*)&m_rd.R5;
break;
case REGISTER_ARM_R6:
ret = (UINT_PTR*)&m_rd.R6;
break;
case REGISTER_ARM_R7:
ret = (UINT_PTR*)&m_rd.R7;
break;
case REGISTER_ARM_R8:
ret = (UINT_PTR*)&m_rd.R8;
break;
case REGISTER_ARM_R9:
ret = (UINT_PTR*)&m_rd.R9;
break;
case REGISTER_ARM_R10:
ret = (UINT_PTR*)&m_rd.R10;
break;
case REGISTER_ARM_R11:
ret = (UINT_PTR*)&m_rd.R11;
break;
case REGISTER_ARM_R12:
ret = (UINT_PTR*)&m_rd.R12;
break;
case REGISTER_ARM_LR:
ret = (UINT_PTR*)&m_rd.LR;
break;
case REGISTER_ARM_PC:
ret = (UINT_PTR*)&m_rd.PC;
break;
#elif defined(TARGET_ARM64)
case REGISTER_ARM64_X0:
case REGISTER_ARM64_X1:
case REGISTER_ARM64_X2:
case REGISTER_ARM64_X3:
case REGISTER_ARM64_X4:
case REGISTER_ARM64_X5:
case REGISTER_ARM64_X6:
case REGISTER_ARM64_X7:
case REGISTER_ARM64_X8:
case REGISTER_ARM64_X9:
case REGISTER_ARM64_X10:
case REGISTER_ARM64_X11:
case REGISTER_ARM64_X12:
case REGISTER_ARM64_X13:
case REGISTER_ARM64_X14:
case REGISTER_ARM64_X15:
case REGISTER_ARM64_X16:
case REGISTER_ARM64_X17:
case REGISTER_ARM64_X18:
case REGISTER_ARM64_X19:
case REGISTER_ARM64_X20:
case REGISTER_ARM64_X21:
case REGISTER_ARM64_X22:
case REGISTER_ARM64_X23:
case REGISTER_ARM64_X24:
case REGISTER_ARM64_X25:
case REGISTER_ARM64_X26:
case REGISTER_ARM64_X27:
case REGISTER_ARM64_X28:
ret = (UINT_PTR*)&m_rd.X[regNum - REGISTER_ARM64_X0];
break;
case REGISTER_ARM64_LR:
ret = (UINT_PTR*)&m_rd.LR;
break;
case REGISTER_ARM64_PC:
ret = (UINT_PTR*)&m_rd.PC;
break;
#endif
default:
_ASSERT(!"Invalid register number!");
}
return ret;
}
//
// GetLeftSideAddressOfRegister returns the Left Side address of the given register in the frames current register
// display.
//
CORDB_ADDRESS CordbNativeFrame::GetLeftSideAddressOfRegister(CorDebugRegister regNum) const
{
#if !defined(USE_REMOTE_REGISTER_ADDRESS)
// Use marker values as the register address. This is to implement the funceval breaking change.
//
if (IsLeafFrame())
{
return kLeafFrameRegAddr;
}
else
{
return kNonLeafFrameRegAddr;
}
#else // USE_REMOTE_REGISTER_ADDRESS
void* ret = 0;
switch (regNum)
{
#if !defined(TARGET_AMD64)
case REGISTER_FRAME_POINTER:
ret = m_rd.pFP;
break;
#endif
#if defined(TARGET_X86)
case REGISTER_X86_EAX:
ret = m_rd.pEax;
break;
case REGISTER_X86_ECX:
ret = m_rd.pEcx;
break;
case REGISTER_X86_EDX:
ret = m_rd.pEdx;
break;
case REGISTER_X86_EBX:
ret = m_rd.pEbx;
break;
case REGISTER_X86_ESI:
ret = m_rd.pEsi;
break;
case REGISTER_X86_EDI:
ret = m_rd.pEdi;
break;
#elif defined(TARGET_AMD64)
case REGISTER_AMD64_RBP:
ret = m_rd.pRbp;
break;
case REGISTER_AMD64_RAX:
ret = m_rd.pRax;
break;
case REGISTER_AMD64_RCX:
ret = m_rd.pRcx;
break;
case REGISTER_AMD64_RDX:
ret = m_rd.pRdx;
break;
case REGISTER_AMD64_RBX:
ret = m_rd.pRbx;
break;
case REGISTER_AMD64_RSI:
ret = m_rd.pRsi;
break;
case REGISTER_AMD64_RDI:
ret = m_rd.pRdi;
break;
case REGISTER_AMD64_R8:
ret = m_rd.pR8;
break;
case REGISTER_AMD64_R9:
ret = m_rd.pR9;
break;
case REGISTER_AMD64_R10:
ret = m_rd.pR10;
break;
case REGISTER_AMD64_R11:
ret = m_rd.pR11;
break;
case REGISTER_AMD64_R12:
ret = m_rd.pR12;
break;
case REGISTER_AMD64_R13:
ret = m_rd.pR13;
break;
case REGISTER_AMD64_R14:
ret = m_rd.pR14;
break;
case REGISTER_AMD64_R15:
ret = m_rd.pR15;
break;
#endif
default:
_ASSERT(!"Invalid register number!");
}
return PTR_TO_CORDB_ADDRESS(ret);
#endif // !USE_REMOTE_REGISTER_ADDRESS
}
//---------------------------------------------------------------------------------------
//
// Given the native variable information of a variable, return its value.
//
// Arguments:
// pNativeVarInfo - the variable information of the variable to be retrieved
//
// Returns:
// Return the specified value.
// Throw on error.
//
// Assumption:
// This function assumes that the value is either in a register or on the stack
// (i.e. VLT_REG or VLT_STK).
//
// Notes:
// Eventually we should make this more general-purpose.
//
SIZE_T CordbNativeFrame::GetRegisterOrStackValue(const ICorDebugInfo::NativeVarInfo * pNativeVarInfo)
{
SIZE_T uResult;
if (pNativeVarInfo->loc.vlType == ICorDebugInfo::VLT_REG)
{
CorDebugRegister reg = ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg);
uResult = *(reinterpret_cast<SIZE_T *>(GetAddressOfRegister(reg)));
}
else if (pNativeVarInfo->loc.vlType == ICorDebugInfo::VLT_STK)
{
CORDB_ADDRESS remoteAddr = GetLSStackAddress(pNativeVarInfo->loc.vlStk.vlsBaseReg,
pNativeVarInfo->loc.vlStk.vlsOffset);
HRESULT hr = GetProcess()->SafeReadStruct(remoteAddr, &uResult);
IfFailThrow(hr);
}
else
{
ThrowHR(E_FAIL);
}
return uResult;
}
//---------------------------------------------------------------------------------------
//
// Looks in a register and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// reg - The register to use.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, false);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalRegisterValue(reg, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Looks in two registers and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - The register to use for the high word.
// lowWordReg - The register to use for the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalDoubleRegisterValue(CorDebugRegister highWordReg,
CorDebugRegister lowWordReg,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalDoubleRegisterValue(highWordReg, lowWordReg, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses an address and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// address - A local memory address.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, false);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryValue(address, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses a register and an address, retrieving the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - Register to use as the high word.
// lowWordAddress - A local memory address containing the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg,
CORDB_ADDRESS lowWordAddress,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, true);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalRegisterMemoryValue(highWordReg, lowWordAddress, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses a register and an address, retrieving the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - A local memory address to use as the high word.
// lowWordAddress - Register containing the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress,
CorDebugRegister lowWordRegister,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, true);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryRegisterValue(highWordAddress, lowWordRegister, pType, ppValue);
}
HRESULT CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
#if defined(TARGET_X86) || defined(TARGET_64BIT)
#if defined(TARGET_X86)
if ((reg >= REGISTER_X86_FPSTACK_0) && (reg <= REGISTER_X86_FPSTACK_7))
#elif defined(TARGET_AMD64)
if ((reg >= REGISTER_AMD64_XMM0) && (reg <= REGISTER_AMD64_XMM15))
#elif defined(TARGET_ARM64)
if ((reg >= REGISTER_ARM64_V0) && (reg <= REGISTER_ARM64_V31))
#endif
{
return GetLocalFloatingPointValue(reg, pType, ppValue);
}
#endif
// The address of the given register is the address of the value
// in this process. We have no remote address here.
void *pLocalValue = (void*)GetAddressOfRegister(reg);
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegValueHome(this, reg));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
ICorDebugValue *pValue;
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(pLocalValue, REG_SIZE),
pRegHolder,
&pValue); // throws
*ppValue = pValue;
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbNativeFrame::GetLocalDoubleRegisterValue(
CorDebugRegister highWordReg,
CorDebugRegister lowWordReg,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegRegValueHome(this, highWordReg, lowWordReg));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
// sanity check object size
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
//
// nickbe
// 10/31/2002 11:09:42
//
// This assert assumes that the JIT will only partially enregister
// objects that have a size equal to twice the size of a register.
//
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT
CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
_ASSERTE(m_nativeCode->GetFunction() != NULL);
HRESULT hr = S_OK;
ICorDebugValue *pValue;
EX_TRY
{
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
TargetBuffer(address, CordbValue::GetSizeForType(pType, kUnboxed)),
MemoryRange(NULL, 0),
NULL,
&pValue); // throws
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
*ppValue = pValue;
return hr;
}
HRESULT
CordbNativeFrame::GetLocalByRefMemoryValue(CORDB_ADDRESS address,
CordbType * pType,
ICorDebugValue **ppValue)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
LPVOID actualAddress = NULL;
HRESULT hr = GetProcess()->SafeReadStruct(address, &actualAddress);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryValue(PTR_TO_CORDB_ADDRESS(actualAddress), pType, ppValue);
}
HRESULT
CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg,
CORDB_ADDRESS lowWordAddress,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegMemValueHome(this,
highWordReg,
lowWordAddress));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
// See the comment in CordbNativeFrame::GetLocalDoubleRegisterValue
// for more information on this assertion
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT
CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress,
CorDebugRegister lowWordRegister,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new MemRegValueHome(this,
lowWordRegister,
highWordAddress));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
// See the comment in CordbNativeFrame::GetLocalDoubleRegisterValue
// for more information on this assertion
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT CordbNativeFrame::GetLocalFloatingPointValue(DWORD index,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
CorElementType et = pType->m_elementType;
if ((et != ELEMENT_TYPE_R4) &&
(et != ELEMENT_TYPE_R8))
return E_INVALIDARG;
#if defined(TARGET_AMD64)
if (!((index >= REGISTER_AMD64_XMM0) &&
(index <= REGISTER_AMD64_XMM15)))
return E_INVALIDARG;
index -= REGISTER_AMD64_XMM0;
#elif defined(TARGET_ARM64)
if (!((index >= REGISTER_ARM64_V0) &&
(index <= REGISTER_ARM64_V31)))
return E_INVALIDARG;
index -= REGISTER_ARM64_V0;
#elif defined(TARGET_ARM)
if (!((index >= REGISTER_ARM_D0) &&
(index <= REGISTER_ARM_D31)))
return E_INVALIDARG;
index -= REGISTER_ARM_D0;
#else
if (!((index >= REGISTER_X86_FPSTACK_0) &&
(index <= REGISTER_X86_FPSTACK_7)))
return E_INVALIDARG;
index -= REGISTER_X86_FPSTACK_0;
#endif
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Make sure the thread's floating point stack state is loaded
// over from the left side.
//
CordbThread *pThread = m_pThread;
EX_TRY
{
if (!pThread->m_fFloatStateValid)
{
pThread->LoadFloatState();
}
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
#if !defined(TARGET_64BIT)
// This is needed on x86 because we are dealing with a stack.
index = pThread->m_floatStackTop - index;
#endif
if (index >= (sizeof(pThread->m_floatValues) /
sizeof(pThread->m_floatValues[0])))
return E_INVALIDARG;
#ifdef TARGET_X86
// A workaround (sort of) to get around the difference in format between
// a float value and a double value. We can't simply cast a double pointer to
// a float pointer. Instead, we have to cast the double itself to a float.
if (pType->m_elementType == ELEMENT_TYPE_R4)
*(float *)&(pThread->m_floatValues[index]) = (float)pThread->m_floatValues[index];
#endif
ICorDebugValue* pValue;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new FloatRegValueHome(this, index));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(&(pThread->m_floatValues[index]), sizeof(double)),
pRegHolder,
&pValue); // throws
*ppValue = pValue;
}
EX_CATCH_HRESULT(hr);
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Quick accessor to tell if we're the leaf frame.
//
// Return Value:
// whether we are the leaf frame or not
//
bool CordbNativeFrame::IsLeafFrame() const
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// Should only be called by non-neutered stuff.
// Also, since we're not neutered, we know we have a Thread object, and we know it's state is current.
_ASSERTE(!this->IsNeutered());
// If the thread's state is sleeping, then there's no frame below us, but we're actually
// not the leaf frame.
// @todo- consider having Sleep / Wait / Join be an ICDInternalFrame.
_ASSERTE(m_pThread != NULL); // not neutered, so should have a thread
if (m_pThread->IsThreadWaitingOrSleeping())
{
return false;
}
if (!m_optfIsLeafFrame.HasValue())
{
if (GetProcess()->GetShim() != NULL)
{
// In V2, the definition of "leaf frame" is the leaf frame in the leaf chain in the stackwalk.
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
// check if there is any chain
if (pSW->GetChainCount() > 0)
{
// check if the leaf chain has any frame
if (pSW->GetChain(0)->GetLastFrameIndex() > 0)
{
CordbFrame * pCFrame = GetCordbFrameFromInterface(pSW->GetFrame(0));
CordbNativeFrame * pNFrame = pCFrame->GetAsNativeFrame();
if (pNFrame != NULL)
{
// check if the leaf frame in the leaf chain is "this"
if (CompareControlRegisters(GetContext(), pNFrame->GetContext()))
{
m_optfIsLeafFrame = TRUE;
}
}
}
}
if (!m_optfIsLeafFrame.HasValue())
{
m_optfIsLeafFrame = FALSE;
}
}
else
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_optfIsLeafFrame = (pDAC->IsLeafFrame(m_pThread->m_vmThreadToken, &m_context) == TRUE);
}
}
return m_optfIsLeafFrame.GetValue();
}
//---------------------------------------------------------------------------------------
//
// Get the offset used to determine if a variable is live in a particular method frame.
//
// Return Value:
// the offset used for inspection purposes
//
// Notes:
// On WIN64, variables used in funclets are always homed on the stack. Morever, the variable lifetime
// information only covers the parent method. The idea is that the variables which are live in a funclet
// will be the variables which are live in the parent method at the offset at which the exception occurs.
// Thus, to determine if a variable is live in a funclet frame, we need to use the offset of the parent
// method frame at which the exception occurs.
//
SIZE_T CordbNativeFrame::GetInspectionIP()
{
#ifdef FEATURE_EH_FUNCLETS
// On 64-bit, if this is a funclet, then return the offset of the parent method frame at which
// the exception occurs. Otherwise just return the normal offset.
return (IsFunclet() ? GetParentIP() : m_ip);
#else
// Always return the normal offset on all other platforms.
return m_ip;
#endif // FEATURE_EH_FUNCLETS
}
//---------------------------------------------------------------------------------------
//
// Return whether this is a funclet method frame.
//
// Return Value:
// whether this is a funclet method frame.
//
bool CordbNativeFrame::IsFunclet()
{
#ifdef FEATURE_EH_FUNCLETS
return (m_misc.parentIP != NULL);
#else
return false;
#endif // FEATURE_EH_FUNCLETS
}
//---------------------------------------------------------------------------------------
//
// Return whether this is a filter funclet method frame.
//
// Return Value:
// whether this is a filter funclet method frame.
//
bool CordbNativeFrame::IsFilterFunclet()
{
#ifdef FEATURE_EH_FUNCLETS
return (IsFunclet() && m_misc.fIsFilterFunclet);
#else
return false;
#endif // FEATURE_EH_FUNCLETS
}
#ifdef FEATURE_EH_FUNCLETS
//---------------------------------------------------------------------------------------
//
// Return the offset of the parent method frame at which the exception occurs.
//
// Return Value:
// the offset of the parent method frame at which the exception occurs
//
SIZE_T CordbNativeFrame::GetParentIP()
{
return m_misc.parentIP;
}
#endif // FEATURE_EH_FUNCLETS
// Accessor for the shim private hook code:CordbThread::ConvertFrameForILMethodWithoutMetadata.
// Refer to that function for comments on the return value, the argument, etc.
BOOL CordbNativeFrame::ConvertNativeFrameForILMethodWithoutMetadata(
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
IDacDbiInterface::DynamicMethodType type =
pDAC->IsILStubOrLCGMethod(GetNativeCode()->GetVMNativeCodeMethodDescToken());
// Here are the conversion rules:
// 1) For a normal managed method, we don't convert, and we return FALSE.
// 2) For an IL stub, we convert to NULL, and we return TRUE.
// 3) For a dynamic method, we convert to a STUBFRAME_LIGHTWEIGHT_FUNCTION, and we return TRUE.
if (type == IDacDbiInterface::kNone)
{
return FALSE;
}
else if (type == IDacDbiInterface::kILStub)
{
return TRUE;
}
else if (type == IDacDbiInterface::kLCGMethod)
{
RSInitHolder<CordbInternalFrame> pInternalFrame(
new CordbInternalFrame(m_pThread,
m_fp,
m_currentAppDomain,
STUBFRAME_LIGHTWEIGHT_FUNCTION,
GetNativeCode()->GetMetadataToken(),
GetNativeCode()->GetFunction(),
GetNativeCode()->GetVMNativeCodeMethodDescToken()));
pInternalFrame.TransferOwnershipExternal(ppInternalFrame2);
return TRUE;
}
UNREACHABLE();
}
/* ------------------------------------------------------------------------- *
* JIT-IL Frame class
* ------------------------------------------------------------------------- */
CordbJITILFrame::CordbJITILFrame(CordbNativeFrame * pNativeFrame,
CordbILCode * pCode,
UINT_PTR ip,
CorDebugMappingResult mapping,
GENERICS_TYPE_TOKEN exactGenericArgsToken,
DWORD dwExactGenericArgsTokenIndex,
bool fVarArgFnx,
CordbReJitILCode * pRejitCode)
: CordbBase(pNativeFrame->GetProcess(), 0, enumCordbJITILFrame),
m_nativeFrame(pNativeFrame),
m_ilCode(pCode),
m_ip(ip),
m_mapping(mapping),
m_fVarArgFnx(fVarArgFnx),
m_allArgsCount(0),
m_rgbSigParserBuf(NULL),
m_FirstArgAddr(NULL),
m_rgNVI(NULL),
m_genericArgs(),
m_genericArgsLoaded(false),
m_frameParamsToken(exactGenericArgsToken),
m_dwFrameParamsTokenIndex(dwExactGenericArgsTokenIndex),
m_pReJitCode(pRejitCode)
{
// We'll initialize the SigParser in CordbJITILFrame::Init().
m_sigParserCached = SigParser(NULL, 0);
_ASSERTE(m_sigParserCached.IsNull());
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
//---------------------------------------------------------------------------------------
//
// Initialize a CordbJITILFrame object. Must be called after allocating the object and before using it.
// If Init fails, then destroy the object and release the memory.
//
// Return Value:
// HRESULT for the operation
//
// Notes:
// This is a nop if the function is not a vararg function.
//
HRESULT CordbJITILFrame::Init()
{
// ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
_ASSERTE(m_ilCode != NULL);
if (m_fVarArgFnx)
{
// First, we need to find the VASigCookie. Use the native var info to do so.
const ICorDebugInfo::NativeVarInfo * pNativeVarInfo = NULL;
CordbNativeFrame * pNativeFrame = this->m_nativeFrame;
pNativeFrame->m_nativeCode->LoadNativeInfo();
hr = pNativeFrame->m_nativeCode->ILVariableToNative((DWORD)ICorDebugInfo::VARARGS_HND_ILNUM,
pNativeFrame->GetInspectionIP(),
&pNativeVarInfo);
IfFailThrow(hr);
// Check for the case where the VASigCookie isn't pushed on the stack yet.
// This should only be a problem with optimized code.
if (pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK)
{
ThrowHR(E_FAIL);
}
// Retrieve the target address.
CORDB_ADDRESS pRemoteValue = pNativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg,
pNativeVarInfo->loc.vlStk.vlsOffset);
CORDB_ADDRESS argBase;
// Now is the time to ask DacDbi to retrieve the information based on the VASigCookie.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
TargetBuffer sigTargetBuf = pDAC->GetVarArgSig(pRemoteValue, &argBase);
// make sure we are not leaking any memory
_ASSERTE(m_rgbSigParserBuf == NULL);
m_rgbSigParserBuf = new BYTE[sigTargetBuf.cbSize];
GetProcess()->SafeReadBuffer(sigTargetBuf, m_rgbSigParserBuf);
m_sigParserCached = SigParser(m_rgbSigParserBuf, sigTargetBuf.cbSize);
// Note that we should never mutate the SigParser.
// Instead, make a copy and work with the copy instead.
if (!m_sigParserCached.IsNull())
{
SigParser sigParser = m_sigParserCached;
// get the actual count of arguments, including the var args
IfFailThrow(sigParser.SkipMethodHeaderSignature(&m_allArgsCount));
BOOL methodIsStatic;
m_ilCode->GetSig(NULL, NULL, &methodIsStatic); // throws
if (!methodIsStatic)
{
m_allArgsCount++; // skip the "this" object
}
// initialize the variable lifetime information
m_rgNVI = new ICorDebugInfo::NativeVarInfo[m_allArgsCount]; // throws
_ASSERTE(ICorDebugInfo::VLT_COUNT <= ICorDebugInfo::VLT_INVALID);
for (ULONG i = 0; i < m_allArgsCount; i++)
{
m_rgNVI[i].loc.vlType = ICorDebugInfo::VLT_INVALID;
}
}
// GetVarArgSig gets the address of the beginning of the arguments pushed for this frame.
// We'll need the address of the first argument, which will depend on its size and the
// calling convention, so we'll commpute that now that we have the SigParser.
CordbType * pArgType;
IfFailThrow(GetArgumentType(0, &pArgType));
ULONG32 argSize = 0;
IfFailThrow(pArgType->GetUnboxedObjectSize(&argSize));
#if defined(TARGET_X86) // (STACK_GROWS_DOWN_ON_ARGS_WALK)
m_FirstArgAddr = argBase - argSize;
#else // !TARGET_X86 (STACK_GROWS_UP_ON_ARGS_WALK)
AlignAddressForType(pArgType, argBase);
m_FirstArgAddr = argBase;
#endif // !TARGET_X86 (STACK_GROWS_UP_ON_ARGS_WALK)
}
// The stackwalking code can't always successfully retrieve the generics type token.
// For example, on 64-bit, the JIT only encodes the generics type token location if
// a method has catch clause for a generic exception (e.g. "catch(MyException<string> e)").
if ((m_dwFrameParamsTokenIndex != (DWORD)ICorDebugInfo::MAX_ILNUM) && (m_frameParamsToken == NULL))
{
// All variables are unavailable in the prolog and the epilog.
// This includes the generics type token. Failing to get the token just means that
// we won't have full generics information. This should not be a disastrous failure.
//
// Currently, on X64, the JIT is reporting that the variables are live even in the epilog.
// That's why we need this check here. I need to follow up on this.
if ((m_mapping != MAPPING_PROLOG) && (m_mapping != MAPPING_EPILOG))
{
// Find the generics type token using the variable lifetime information.
const ICorDebugInfo::NativeVarInfo * pNativeVarInfo = NULL;
CordbNativeFrame * pNativeFrame = this->m_nativeFrame;
pNativeFrame->m_nativeCode->LoadNativeInfo();
HRESULT hrTmp = pNativeFrame->m_nativeCode->ILVariableToNative(m_dwFrameParamsTokenIndex,
pNativeFrame->GetInspectionIP(),
&pNativeVarInfo);
// It's not a disaster if we can't find the generics token, so don't throw an exception here.
// In fact, it's fairly common in retail code. Even if we can't find the generics token,
// we may still be able to look up the generics type information later by using the MethodDesc,
// the "this" object, etc. If not, we'll at least get the representative type information
// (e.g. Foo<T> instead of Foo<string>).
if (SUCCEEDED(hrTmp))
{
_ASSERTE(pNativeVarInfo != NULL);
// The generics type token should be stored either in a register or on the stack.
SIZE_T uRawToken = pNativeFrame->GetRegisterOrStackValue(pNativeVarInfo);
// Ask DAC to resolve the token for us. We really don't want to deal with all the logic here.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
// On a minidump, we'll throw if we're missing the memory.
ALLOW_DATATARGET_MISSING_MEMORY(
m_frameParamsToken = pDAC->ResolveExactGenericArgsToken(m_dwFrameParamsTokenIndex, uRawToken);
);
}
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
/*
A list of which resources owned by this object are accounted for.
UNKNOWN:
CordbNativeFrame* m_nativeFrame;
CordbILCode * m_ilCode;
CorDebugMappingResult m_mapping;
CORDB_ADDRESS m_FirstArgAddr;
ICorDebugInfo::NativeVarInfo * m_rgNVI; // Deleted in neuter
CordbClass **m_genericArgs;
*/
CordbJITILFrame::~CordbJITILFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by CordbNativeFrame
void CordbJITILFrame::Neuter()
{
// Since neutering here calls Release directly, we don't want to double-release
// if neuter is called multiple times.
if (IsNeutered())
{
return;
}
// Frames include pointers across to other types that specify the
// representation instantiation - reduce the reference counts on these....
for (unsigned int i = 0; i < m_genericArgs.m_cInst; i++)
{
m_genericArgs.m_ppInst[i]->Release();
}
if (m_rgNVI != NULL)
{
delete [] m_rgNVI;
m_rgNVI = NULL;
}
if (m_rgbSigParserBuf != NULL)
{
delete [] m_rgbSigParserBuf;
m_rgbSigParserBuf = NULL;
}
m_pReJitCode.Clear();
// If this class ever inherits from the CordbFrame we'll need a call
// to CordbFrame::Neuter() here instead of to CordbBase::Neuter();
CordbBase::Neuter();
}
//---------------------------------------------------------------------------------------
//
// Load the generic type and method arguments and store them into the frame if possible.
//
// Return Value:
// HRESULT for the operation
//
void CordbJITILFrame::LoadGenericArgs()
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
// The case where there are no type parameters, or the case where we've
// already feched the realInst, is easy.
if (m_genericArgsLoaded)
{
return;
}
_ASSERTE(m_nativeFrame->m_nativeCode != NULL);
if (!m_nativeFrame->m_nativeCode->IsInstantiatedGeneric())
{
m_genericArgs = Instantiation(0, NULL,0);
m_genericArgsLoaded = true;
return;
}
// Find the exact generic arguments for a frame that is executing
// a generic method. The left-side will fetch these from arguments
// given on the stack and/or from the IP.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
UINT32 cGenericClassTypeParams = 0;
DacDbiArrayList<DebuggerIPCE_ExpandedTypeData> rgGenericTypeParams;
pDAC->GetMethodDescParams(GetCurrentAppDomain()->GetADToken(),
m_nativeFrame->GetNativeCode()->GetVMNativeCodeMethodDescToken(),
m_frameParamsToken,
&cGenericClassTypeParams,
&rgGenericTypeParams);
UINT32 cTotalGenericTypeParams = rgGenericTypeParams.Count();
// @dbgtodo reliability - This holder doesn't actually work in this case because it just deletes
// each element on error. The RS classes are all expected to be neutered before the destructor is called.
NewArrayHolder<CordbType *> ppGenericArgs(new CordbType *[cTotalGenericTypeParams]);
for (UINT32 i = 0; i < cTotalGenericTypeParams;i++)
{
// creates a CordbType object for the generic argument
HRESULT hr = CordbType::TypeDataToType(GetCurrentAppDomain(),
&(rgGenericTypeParams[i]),
&ppGenericArgs[i]);
IfFailThrow(hr);
// We add a ref as the instantiation will be stored away in the
// ref-counted data structure associated with the JITILFrame
ppGenericArgs[i]->AddRef();
}
// initialize the generics information
m_genericArgs = Instantiation(cTotalGenericTypeParams, ppGenericArgs, cGenericClassTypeParams);
m_genericArgsLoaded = true;
ppGenericArgs.SuppressRelease();
}
//
// CordbJITILFrame::QueryInterface
//
// Description
// Interface query for this COM object
//
// NOTE: the COM object associated with this CordbJITILFrame may consist of two
// C++ objects (a CordbJITILFrame and its associated CordbNativeFrame)
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
HRESULT CordbJITILFrame::QueryInterface(REFIID id, void **pInterface)
{
if (NULL != m_nativeFrame)
{
// If the native frame does not support the requested interface, then
// the native fram is responsible for delegating the query back to this
// object through QueryInterfaceInternal(...)
return m_nativeFrame->QueryInterface(id, pInterface);
}
// no native frame. Check for interfaces common to CordbNativeFrame and
// CordbJITILFrame
if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugILFrame*>(this));
}
else if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(this);
}
else
{
// didn't find an interface yet. Since there's no native frame
// associated with this IL frame, go ahead and check for the IL frame
return this->QueryInterfaceInternal(id, pInterface);
}
ExternalAddRef();
return S_OK;
}
//
// CordbJITILFrame::QueryInterfaceInternal
//
// Description
// Interface query for interfaces implemented ONLY by CordbJITILFrame (as
// opposed to interfaces implemented by both CordbNativeFrame and
// CordbJITILFrame)
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
// NOTE: id must not be IUnknown or ICorDebugFrame
// NOTE: if this object is in "forward compatibility mode", passing in
// IID_ICorDebugILFrame2 for the id will result in a failure (returns
// E_NOINTERFACE)
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
HRESULT
CordbJITILFrame::QueryInterfaceInternal(REFIID id, void** pInterface)
{
_ASSERTE(IID_ICorDebugFrame != id);
_ASSERTE(IID_IUnknown != id);
// don't query for IUnknown or ICorDebugFrame! Someone else should have
// already taken care of that.
if (id == IID_ICorDebugILFrame)
{
*pInterface = static_cast<ICorDebugILFrame*>(this);
}
else if (id == IID_ICorDebugILFrame2)
{
*pInterface = static_cast<ICorDebugILFrame2*>(this);
}
else if (id == IID_ICorDebugILFrame3)
{
*pInterface = static_cast<ICorDebugILFrame3*>(this);
}
else if (id == IID_ICorDebugILFrame4)
{
*pInterface = static_cast<ICorDebugILFrame4*>(this);
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Get an enumerator for the generic type and method arguments on this frame.
//
// Arguments:
// ppTypeParameterEnum - out parameter; return the enumerator
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::EnumerateTypeParameters(ICorDebugTypeEnum **ppTypeParameterEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppTypeParameterEnum, ICorDebugTypeEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
(*ppTypeParameterEnum) = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// load the generic arguments, which may be cached
LoadGenericArgs();
// create the enumerator
RSInitHolder<CordbTypeEnum> pEnum(
CordbTypeEnum::Build(GetCurrentAppDomain(), m_nativeFrame->m_pThread->GetRefreshStackNeuterList(), m_genericArgs.m_cInst, m_genericArgs.m_ppInst));
if ( pEnum == NULL )
{
ThrowOutOfMemory();
}
pEnum.TransferOwnershipExternal(ppTypeParameterEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetChain
//
// Description:
// Return the owning chain. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the owning chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetChain(ICorDebugChain **ppChain)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChain, ICorDebugChain **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetChain(ppChain);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Return the IL code blob associated with this IL frame.
// Each IL frame corresponds to exactly one IL code blob.
HRESULT CordbJITILFrame::GetCode(ICorDebugCode **ppCode)
{
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppCode, ICorDebugCode **);
*ppCode = static_cast<ICorDebugCode*> (m_ilCode);
m_ilCode->ExternalAddRef();
return S_OK;;
}
// Return the function associated with this IL frame.
// Each IL frame corresponds to exactly one function.
HRESULT CordbJITILFrame::GetFunction(ICorDebugFunction **ppFunction)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
ValidateOrThrow(ppFunction);
CordbFunction * pFunc = m_nativeFrame->GetFunction();
*ppFunction = static_cast<ICorDebugFunction *>(pFunc);
pFunc->ExternalAddRef();
}
PUBLIC_API_END(hr);
return hr;
}
// Return the token of the function associated with this IL frame.
// Each IL frame corresponds to exactly one function.
HRESULT CordbJITILFrame::GetFunctionToken(mdMethodDef *pToken)
{
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pToken, mdMethodDef *);
*pToken = m_nativeFrame->m_nativeCode->GetMetadataToken();
return S_OK;
}
// ----------------------------------------------------------------------------
// CordJITILFrame::GetStackRange
//
// Description:
// Get the stack range owned by the associated native frame.
// IL frames and native frames are 1:1 for normal jitted managed methods.
// Dynamic methods are an exception.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes: see code:#GetStackRange
HRESULT CordbJITILFrame::GetStackRange(CORDB_ADDRESS *pStart, CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// The access of m_nativeFrame is not safe here. It's a weak reference.
OK_IF_NEUTERED(this);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetStackRange(pStart, pEnd);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetCaller
//
// Description:
// Delegate to the associated native frame to return the caller, which is closer to the root.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the caller frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetCaller(ICorDebugFrame **ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetCaller(ppFrame);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetCallee
//
// Description:
// Delegate to the associated native frame to return the callee, which is closer to the leaf.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the callee frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetCallee(ICorDebugFrame **ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetCallee(ppFrame);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Create a stepper on the frame.
HRESULT CordbJITILFrame::CreateStepper(ICorDebugStepper **ppStepper)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// by default, a stepper operates on the IL level, using IL offsets
return m_nativeFrame->CreateStepper(ppStepper);
}
// Return the IL offset and the mapping result.
HRESULT CordbJITILFrame::GetIP(ULONG32 *pnOffset,
CorDebugMappingResult *pMappingResult)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pnOffset, ULONG32 *);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pMappingResult, CorDebugMappingResult *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*pnOffset = (ULONG32)m_ip;
if (pMappingResult)
*pMappingResult = m_mapping;
return S_OK;
}
// Determine if we can set IP at this point. The specified offset is the IL offset.
HRESULT CordbJITILFrame::CanSetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Check to see that this is a leaf frame
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
// delegate to the associated native frame
CordbNativeCode * pNativeCode = m_nativeFrame->m_nativeCode;
hr = m_nativeFrame->m_pThread->SetIP(SetIP_fCanSetIPOnly, // specify that this is for checking only
pNativeCode,
nOffset,
SetIP_fIL );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Try to set the IP to the specified offset. The specified offset is the IL offset.
HRESULT CordbJITILFrame::SetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Check to see that this is a leaf frame
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
// delegate to the native frame
CordbNativeCode * pNativeCode = m_nativeFrame->m_nativeCode;
hr = m_nativeFrame->m_pThread->SetIP(SetIP_fSetIP, // specify that this is a real SetIP operation
pNativeCode,
nOffset,
SetIP_fIL );
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine creates backing native info for a local variable, returning an ICorDebugInfo
// object for the local variable when successful.
//
// Arguments:
// dwIndex - Index of the local variable to create native info for.
// ppNativeInfo - OUT: Space for storing the resulting pointer to native variable info.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::FabricateNativeInfo(DWORD dwIndex,
const ICorDebugInfo::NativeVarInfo ** ppNativeInfo)
{
HRESULT hr = S_OK;
EX_TRY
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(this->GetProcess());
_ASSERTE(m_fVarArgFnx);
// This array should have been populated in CordbJITILFrame::Init().
_ASSERTE(m_rgNVI != NULL);
// check if we have already fabricated all the information
if (m_rgNVI[dwIndex].loc.vlType != ICorDebugInfo::VLT_INVALID)
{
(*ppNativeInfo) = &m_rgNVI[dwIndex];
}
else
{
// We'll initialize everything at once
ULONG cbArchitectureMin;
// m_FirstArgAddr will already be aligned on platforms that require alignment
CORDB_ADDRESS rpCur = m_FirstArgAddr;
#if defined(TARGET_X86) || defined(TARGET_ARM)
cbArchitectureMin = 4;
#elif defined(TARGET_64BIT)
cbArchitectureMin = 8;
#else
cbArchitectureMin = 8; //REVISIT_TODO not sure if this is correct
PORTABILITY_ASSERT("What is the architecture-dependent minimum word size?");
#endif // TARGET_X86
// make a copy of the cached SigParser
SigParser sigParser = m_sigParserCached;
IfFailThrow(sigParser.SkipMethodHeaderSignature(NULL));
ULONG32 cbType;
CordbType * pArgType;
// make sure all the generic type and method arguments are loaded
LoadGenericArgs();
// get a CordbType object for the generic argument
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), &pArgType));
IfFailThrow(pArgType->GetUnboxedObjectSize(&cbType));
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
// The the rpCur pointer starts off in the right spot for the
// first argument, but thereafter we have to decrement it
// before getting the variable's location from it. So increment
// it here to be consistent later.
rpCur += max(cbType, cbArchitectureMin);
#endif
// Grab the IL code's function's method signature so we can see if it's static.
BOOL fMethodIsStatic;
m_ilCode->GetSig(NULL, NULL, &fMethodIsStatic); // throws
ULONG i;
if (fMethodIsStatic)
{
i = 0;
}
else
{
i = 1;
}
for ( ; i < m_allArgsCount; i++)
{
m_rgNVI[i].startOffset = 0;
m_rgNVI[i].endOffset = 0xFFffFFff;
m_rgNVI[i].varNumber = i;
m_rgNVI[i].loc.vlType = ICorDebugInfo::VLT_FIXED_VA;
LoadGenericArgs();
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), &pArgType));
IfFailThrow(pArgType->GetUnboxedObjectSize(&cbType));
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
rpCur -= max(cbType, cbArchitectureMin);
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset =
(unsigned)(m_FirstArgAddr - rpCur);
// Since the JIT adds in the size of this field, we do too to
// be consistent.
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset += sizeof(((CORINFO_VarArgInfo*)0)->argBytes);
#else // STACK_GROWS_UP_ON_ARGS_WALK
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset =
(unsigned)(rpCur - m_FirstArgAddr);
rpCur += max(cbType, cbArchitectureMin);
AlignAddressForType(pArgType, rpCur);
#endif
IfFailThrow(sigParser.SkipExactlyOne());
} // for ( ; i M m_allArgsCount; i++)
(*ppNativeInfo) = &m_rgNVI[dwIndex];
} // else (m_rgNVI[dwIndex].loc.vlType == ICorDebugInfo::VLT_INVALID)
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::ILVariableToNative(DWORD dwVarNumber,
const ICorDebugInfo::NativeVarInfo **ppNativeInfo)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
_ASSERTE(m_nativeFrame->m_nativeCode->IsNativeCodeValid());
// We keep the fixed argument native var infos in the
// CordbFunction, which only is an issue for var args info:
if (!m_fVarArgFnx || //not a var args function
(dwVarNumber < m_nativeFrame->m_nativeCode->GetFixedArgCount()) || // var args,fixed arg
// note that this include the implicit 'this' for nonstatic fnxs
(dwVarNumber >= m_allArgsCount) ||// var args, local variable
(m_sigParserCached.IsNull())) //we don't have any VA info
{
// If we're in a var args fnx, but we're actually looking
// for a local variable, then we want to use the variable
// index as the function sees it - fixed (but not var)
// args are added to local var number to get native info
// We are really trying to find a variable by it's number,
// but "special" variables have a negative number which we
// don't use. We "number" them conceptually between the
// arguments and locals:
//
// arguments special locals
// -----------------------------------------
// Actual numbers: 1 2 3 . . . 4 5 6 7
// Logical numbers: 0 1 2 3 4 5 6 7 8
//
// We have two different counts for the number of arguments: the fixedArgCount
// gives the actual number of arguments and the allArgsCount is the number of
// of fixed arguments plus the number of var args.
//
// Thus, to get the correct actual number for locals we have to compute it as
// logicalNumber - allArgsCount + fixedArgCount
if (m_fVarArgFnx && (dwVarNumber >= m_allArgsCount) && !m_sigParserCached.IsNull())
{
dwVarNumber -= m_allArgsCount;
dwVarNumber += m_nativeFrame->m_nativeCode->GetFixedArgCount();
}
return m_nativeFrame->m_nativeCode->ILVariableToNative(dwVarNumber,
m_nativeFrame->GetInspectionIP(),
ppNativeInfo);
}
return FabricateNativeInfo(dwVarNumber,ppNativeInfo);
}
//---------------------------------------------------------------------------------------
//
// This routine get the type of a particular argument.
//
// Arguments:
// dwIndex - Index of the argument.
// ppResultType - OUT: Space for storing the type of the argument.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::GetArgumentType(DWORD dwIndex,
CordbType ** ppResultType)
{
HRESULT hr = S_OK;
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
LoadGenericArgs();
if (m_fVarArgFnx && !m_sigParserCached.IsNull())
{
SigParser sigParser = m_sigParserCached;
IfFailThrow(sigParser.SkipMethodHeaderSignature(NULL));
// Grab the IL code's function's method signature so we can see if it's static.
BOOL fMethodIsStatic;
m_ilCode->GetSig(NULL, NULL, &fMethodIsStatic); // throws
if (!fMethodIsStatic)
{
if (dwIndex == 0)
{
// Return the signature for the 'this' pointer for the
// class this method is in.
IfFailThrow(m_ilCode->GetClass()->GetThisType(&(this->m_genericArgs), ppResultType));
return hr;
}
else
{
dwIndex--;
}
}
for (ULONG i = 0; i < dwIndex; i++)
{
IfFailThrow(sigParser.SkipExactlyOne());
}
IfFailThrow(sigParser.SkipFunkyAndCustomModifiers());
IfFailThrow(sigParser.SkipAnyVASentinel());
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), ppResultType));
}
else // (!m_fVarArgFnx || m_sigParserCached.IsNull())
{
m_nativeFrame->m_nativeCode->GetArgumentType(dwIndex, &(this->m_genericArgs), ppResultType);
}
return hr;
}
//
// GetNativeVariable uses the JIT variable information to delegate to
// the native frame when the value is really created.
//
HRESULT CordbJITILFrame::GetNativeVariable(CordbType *type,
const ICorDebugInfo::NativeVarInfo *pNativeVarInfo,
ICorDebugValue **ppValue)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
#ifdef FEATURE_EH_FUNCLETS
if (m_nativeFrame->IsFunclet())
{
if ( (pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK) &&
(pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK2) &&
(pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK_BYREF) )
{
_ASSERTE(!"CordbJITILFrame::GetNativeVariable()"
" - Variables used in funclets should always be homed on the stack.\n");
return E_FAIL;
}
}
#endif // FEATURE_EH_FUNCLETS
switch (pNativeVarInfo->loc.vlType)
{
case ICorDebugInfo::VLT_REG:
hr = m_nativeFrame->GetLocalRegisterValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg),
type, ppValue);
break;
case ICorDebugInfo::VLT_REG_BYREF:
{
CORDB_ADDRESS pRemoteByRefAddr = PTR_TO_CORDB_ADDRESS(
*( m_nativeFrame->GetAddressOfRegister(ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg))) );
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteByRefAddr,
type,
ppValue);
}
break;
#if defined(TARGET_64BIT) || defined(TARGET_ARM)
case ICorDebugInfo::VLT_REG_FP:
#if defined(TARGET_ARM) // @ARMTODO
hr = E_NOTIMPL;
#elif defined(TARGET_AMD64)
hr = m_nativeFrame->GetLocalFloatingPointValue(pNativeVarInfo->loc.vlReg.vlrReg + REGISTER_AMD64_XMM0,
type, ppValue);
#elif defined(TARGET_ARM64)
hr = m_nativeFrame->GetLocalFloatingPointValue(pNativeVarInfo->loc.vlReg.vlrReg + REGISTER_ARM64_V0,
type, ppValue);
#else
#error Platform not implemented
#endif // TARGET_ARM @ARMTODO
break;
#endif // TARGET_64BIT || TARGET_ARM
case ICorDebugInfo::VLT_STK_BYREF:
{
CORDB_ADDRESS pRemoteByRefAddr = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg, pNativeVarInfo->loc.vlStk.vlsOffset) ;
hr = m_nativeFrame->GetLocalByRefMemoryValue(pRemoteByRefAddr,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_STK:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg, pNativeVarInfo->loc.vlStk.vlsOffset) ;
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_REG_REG:
hr = m_nativeFrame->GetLocalDoubleRegisterValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegReg.vlrrReg2),
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegReg.vlrrReg1),
type, ppValue);
break;
case ICorDebugInfo::VLT_REG_STK:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlRegStk.vlrsStk.vlrssBaseReg, pNativeVarInfo->loc.vlRegStk.vlrsStk.vlrssOffset);
hr = m_nativeFrame->GetLocalMemoryRegisterValue(
pRemoteValue,
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegStk.vlrsReg),
type, ppValue);
}
break;
case ICorDebugInfo::VLT_STK_REG:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStkReg.vlsrStk.vlsrsBaseReg, pNativeVarInfo->loc.vlStkReg.vlsrStk.vlsrsOffset);
hr = m_nativeFrame->GetLocalRegisterMemoryValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlStkReg.vlsrReg),
pRemoteValue, type, ppValue);
}
break;
case ICorDebugInfo::VLT_STK2:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk2.vls2BaseReg, pNativeVarInfo->loc.vlStk2.vls2Offset);
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_FPSTK:
#if defined(TARGET_ARM) // @ARMTODO
hr = E_NOTIMPL;
#else
/*
@TODO [Microsoft] We have to make this work!!!!!!!!!!!!!
hr = m_nativeFrame->GetLocalFloatingPointValue(
pNativeVarInfo->loc.vlFPstk.vlfReg + REGISTER_X86_FPSTACK_0,
type, ppValue);
*/
hr = CORDBG_E_IL_VAR_NOT_AVAILABLE;
#endif
break;
case ICorDebugInfo::VLT_FIXED_VA:
if (m_sigParserCached.IsNull()) //no var args info
return CORDBG_E_IL_VAR_NOT_AVAILABLE;
CORDB_ADDRESS pRemoteValue;
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
pRemoteValue = m_FirstArgAddr - pNativeVarInfo->loc.vlFixedVarArg.vlfvOffset;
// Remember to subtract out this amount
pRemoteValue += sizeof(((CORINFO_VarArgInfo*)0)->argBytes);
#else // STACK_GROWS_UP_ON_ARGS_WALK
pRemoteValue = m_FirstArgAddr + pNativeVarInfo->loc.vlFixedVarArg.vlfvOffset;
#endif
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
break;
default:
_ASSERTE(!"Invalid locVarType");
hr = E_FAIL;
break;
}
return hr;
}
HRESULT CordbJITILFrame::EnumerateLocalVariables(ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
return EnumerateLocalVariablesEx(ILCODE_ORIGINAL_IL, ppValueEnum);
}
HRESULT CordbJITILFrame::GetLocalVariable(DWORD dwIndex,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
return GetLocalVariableEx(ILCODE_ORIGINAL_IL, dwIndex, ppValue);
}
HRESULT CordbJITILFrame::EnumerateArguments(ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSInitHolder<CordbValueEnum> cdVE(new CordbValueEnum(m_nativeFrame, CordbValueEnum::ARGS));
// Initialize the new enum
hr = cdVE->Init();
IfFailThrow(hr);
cdVE.TransferOwnershipExternal(ppValueEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine gets the value of a particular argument
//
// Arguments:
// dwIndex - Index of the argument.
// ppValue - OUT: Space for storing the value of the argument
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::GetArgument(DWORD dwIndex, ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
const ICorDebugInfo::NativeVarInfo * pNativeInfo;
//
// First, make sure that we've got the jitted variable location data
// loaded from the left side.
//
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_nativeCode->LoadNativeInfo(); //throws
hr = ILVariableToNative(dwIndex, &pNativeInfo);
IfFailThrow(hr);
// Get the type of this argument from the function
CordbType * pType;
hr = GetArgumentType(dwIndex, &pType);
IfFailThrow(hr);
hr = GetNativeVariable(pType, pNativeInfo, ppValue);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetStackDepth(ULONG32 *pDepth)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pDepth, ULONG32 *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
/* !!! */
return E_NOTIMPL;
}
HRESULT CordbJITILFrame::GetStackValue(DWORD dwIndex, ICorDebugValue **ppValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
/* !!! */
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Remaps the active frame to the latest EnC version of the function, preserving the
// execution state of the method such as the values of locals.
// Can only be called when the leaf frame is at a remap opportunity.
//
// Arguments:
// nOffset - the IL offset in the new version of the function to remap to
//
HRESULT CordbJITILFrame::RemapFunction(ULONG32 nOffset)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
#if !defined(FEATURE_ENC_SUPPORTED)
ThrowHR(E_NOTIMPL);
#else // FEATURE_ENC_SUPPORTED
// Can only be called on leaf frame.
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(E_INVALIDARG);
}
// mark frames as not fresh, because this frame has been updated.
m_nativeFrame->m_pThread->CleanupStack();
// Since we may have overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
m_nativeFrame->m_pThread->GetProcess()->m_continueCounter++;
// Tell the left-side to do the remap
hr = m_nativeFrame->m_pThread->SetRemapIP(nOffset);
#endif // FEATURE_ENC_SUPPORTED
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbJITILFrame::GetReturnValueForILOffset(ULONG32 ILoffset, ICorDebugValue** ppReturnValue)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
EX_TRY
{
hr = GetReturnValueForILOffsetImpl(ILoffset, ppReturnValue);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::BuildInstantiationForCallsite(CordbModule * pModule, NewArrayHolder<CordbType*> &types, Instantiation &inst, Instantiation *currentInstantiation, mdToken targetClass, SigParser genericSig)
{
// This function builds an Instantiation object (and backing "types" array) for a given
// class and method signature.
HRESULT hr = S_OK;
RSExtSmartPtr<IMetaDataImport2> pImport2;
IfFailRet(pModule->GetMetaDataImporter()->QueryInterface(IID_IMetaDataImport2, (void**)&pImport2));
// If the targetClass is a TypeSpec that means its first element is GENERICINST.
// We only need to build types for the Instantiation if targetClass is a TypeSpec.
uint32_t classGenerics = 0;
SigParser typeSig;
if (TypeFromToken(targetClass) == mdtTypeSpec)
{
// Our goal with this is to full "classGenerics" with the number of
// generics, and move "typeSig" to the start of the first generic type.
PCCOR_SIGNATURE sig = 0;
ULONG sigCount = 0;
IfFailRet(pImport2->GetTypeSpecFromToken(targetClass, &sig, &sigCount));
typeSig = SigParser(sig, sigCount);
CorElementType elemType;
IfFailRet(typeSig.GetElemType(&elemType));
if (elemType != ELEMENT_TYPE_GENERICINST)
return META_E_BAD_SIGNATURE;
IfFailRet(typeSig.GetElemType(&elemType));
if (elemType != ELEMENT_TYPE_VALUETYPE && elemType != ELEMENT_TYPE_CLASS)
return META_E_BAD_SIGNATURE;
IfFailRet(typeSig.GetToken(NULL));
IfFailRet(typeSig.GetData(&classGenerics));
}
// Similarly for method generics. Simply fill "methodGenerics" with the number
// of generics, and move "genericSig" to the start of the first generic param.
uint32_t methodGenerics = 0;
if (!genericSig.IsNull())
{
uint32_t callingConv = 0;
IfFailRet(genericSig.GetCallingConvInfo(&callingConv));
if (callingConv == IMAGE_CEE_CS_CALLCONV_GENERICINST)
IfFailRet(genericSig.GetData(&methodGenerics));
}
// Now build "types" and "inst".
CordbType *pType = 0;
types = new CordbType*[methodGenerics+classGenerics];
ULONG i = 0;
for (;i < classGenerics; ++i)
{
CorElementType et;
IfFailRet(typeSig.PeekElemType(&et));
if ((et == ELEMENT_TYPE_VAR || et == ELEMENT_TYPE_MVAR) && currentInstantiation->m_cInst == 0)
return E_FAIL;
CordbType::SigToType(pModule, &typeSig, currentInstantiation, &pType);
types[i] = pType;
typeSig.SkipExactlyOne();
}
for (; i < methodGenerics+classGenerics; ++i)
{
CorElementType et;
IfFailRet(genericSig.PeekElemType(&et));
if ((et == ELEMENT_TYPE_VAR || et == ELEMENT_TYPE_MVAR) && currentInstantiation->m_cInst == 0)
return E_FAIL;
CordbType::SigToType(pModule, &genericSig, currentInstantiation, &pType);
types[i] = pType;
genericSig.SkipExactlyOne();
}
inst = Instantiation(methodGenerics+classGenerics, types, classGenerics);
return S_OK;
}
HRESULT CordbJITILFrame::GetReturnValueForILOffsetImpl(ULONG32 ILoffset, ICorDebugValue** ppReturnValue)
{
if (ppReturnValue == NULL)
return E_INVALIDARG;
if (!m_genericArgsLoaded)
LoadGenericArgs();
// First verify that we're stopped at the correct native offset
// by calling ICorDebugCode3::GetReturnValueLiveOffset and
// compare the returned native offset to our current location.
HRESULT hr = S_OK;
CordbNativeCode *pCode = m_nativeFrame->m_nativeCode;
pCode->LoadNativeInfo();
ULONG32 count = 0;
IfFailRet(pCode->GetReturnValueLiveOffsetImpl(&m_genericArgs, ILoffset, 0, &count, NULL));
NewArrayHolder<ULONG32> offsets(new ULONG32[count]);
IfFailRet(pCode->GetReturnValueLiveOffsetImpl(&m_genericArgs, ILoffset, count, &count, offsets));
bool found = false;
ULONG32 currentOffset = m_nativeFrame->GetIPOffset();
for (ULONG32 i = 0; i < count; ++i)
{
if (currentOffset == offsets[i])
{
found = true;
break;
}
}
if (!found)
return E_UNEXPECTED;
// Get the signatures and mdToken for the callee.
SigParser methodSig, genericSig;
mdToken mdFunction = 0, targetClass = 0;
IfFailRet(pCode->GetCallSignature(ILoffset, &targetClass, &mdFunction, methodSig, genericSig));
IfFailRet(CordbNativeCode::SkipToReturn(methodSig));
// Create the Instantiation, type and then return value
NewArrayHolder<CordbType*> types;
Instantiation inst;
CordbType *pType = 0;
IfFailRet(BuildInstantiationForCallsite(GetModule(), types, inst, &m_genericArgs, targetClass, genericSig));
IfFailRet(CordbType::SigToType(GetModule(), &methodSig, &inst, &pType));
return GetReturnValueForType(pType, ppReturnValue);
}
HRESULT CordbJITILFrame::GetReturnValueForType(CordbType *pType, ICorDebugValue **ppReturnValue)
{
#if defined(TARGET_X86)
const CorDebugRegister floatRegister = REGISTER_X86_FPSTACK_0;
#elif defined(TARGET_AMD64)
const CorDebugRegister floatRegister = REGISTER_AMD64_XMM0;
#elif defined(TARGET_ARM64)
const CorDebugRegister floatRegister = REGISTER_ARM64_V0;
#elif defined(TARGET_ARM)
const CorDebugRegister floatRegister = REGISTER_ARM_D0;
#endif
#if defined(TARGET_X86)
const CorDebugRegister ptrRegister = REGISTER_X86_EAX;
const CorDebugRegister ptrHighWordRegister = REGISTER_X86_EDX;
#elif defined(TARGET_AMD64)
const CorDebugRegister ptrRegister = REGISTER_AMD64_RAX;
#elif defined(TARGET_ARM64)
const CorDebugRegister ptrRegister = REGISTER_ARM64_X0;
#elif defined(TARGET_ARM)
const CorDebugRegister ptrRegister = REGISTER_ARM_R0;
const CorDebugRegister ptrHighWordRegister = REGISTER_ARM_R1;
#endif
CorElementType corReturnType = pType->GetElementType();
switch (corReturnType)
{
default:
return m_nativeFrame->GetLocalRegisterValue(ptrRegister, pType, ppReturnValue);
case ELEMENT_TYPE_R4:
case ELEMENT_TYPE_R8:
return m_nativeFrame->GetLocalFloatingPointValue(floatRegister, pType, ppReturnValue);
#if defined(TARGET_X86) || defined(TARGET_ARM)
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
return m_nativeFrame->GetLocalDoubleRegisterValue(ptrHighWordRegister, ptrRegister, pType, ppReturnValue);
#endif
}
}
HRESULT CordbJITILFrame::EnumerateLocalVariablesEx(ILCodeKind flags, ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
EX_TRY
{
RSInitHolder<CordbValueEnum> cdVE(new CordbValueEnum(m_nativeFrame,
flags == ILCODE_ORIGINAL_IL ? CordbValueEnum::LOCAL_VARS_ORIGINAL_IL : CordbValueEnum::LOCAL_VARS_REJIT_IL));
// Initialize the new enum
hr = cdVE->Init();
IfFailThrow(hr);
cdVE.TransferOwnershipExternal(ppValueEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetLocalVariableEx(ILCodeKind flags, DWORD dwIndex, ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
if (flags == ILCODE_REJIT_IL && m_pReJitCode == NULL)
return E_INVALIDARG;
const ICorDebugInfo::NativeVarInfo *pNativeInfo;
//
// First, make sure that we've got the jitted variable location data
// loaded from the left side.
//
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_nativeCode->LoadNativeInfo(); //throws
ULONG cArgs;
if (m_fVarArgFnx && (!m_sigParserCached.IsNull()))
{
cArgs = m_allArgsCount;
}
else
{
cArgs = m_nativeFrame->m_nativeCode->GetFixedArgCount();
}
hr = ILVariableToNative(dwIndex + cArgs, &pNativeInfo);
IfFailThrow(hr);
LoadGenericArgs();
// Get the type of this argument from the function
CordbType *type;
CordbILCode* pActiveCode = m_pReJitCode != NULL ? m_pReJitCode : m_ilCode;
hr = pActiveCode->GetLocalVariableType(dwIndex, &(this->m_genericArgs), &type);
IfFailThrow(hr);
// if the caller wants the original IL local, it should implicitly map to the same index
// variable in the profiler instrumented code. We can't determine whether the instrumented code
// really adhered to this, but we can check two things:
// a) the requested index was valid in the original signature
// (GetLocalVariableType will return E_INVALIDARG if not)
// b) the type of local in the original signature matches the type of local in the instrumented signature
// (the code below will return CORDBG_E_IL_VAR_NOT_AVAILABLE)
if (flags == ILCODE_ORIGINAL_IL && m_pReJitCode != NULL)
{
CordbType* pOriginalType;
hr = m_ilCode->GetLocalVariableType(dwIndex, &(this->m_genericArgs), &pOriginalType);
IfFailThrow(hr);
if (pOriginalType != type)
{
IfFailThrow(CORDBG_E_IL_VAR_NOT_AVAILABLE); // bad profiler, it shouldn't have changed types
}
}
hr = GetNativeVariable(type, pNativeInfo, ppValue);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetCodeEx(ILCodeKind flags, ICorDebugCode **ppCode)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
if (flags == ILCODE_ORIGINAL_IL)
{
return GetCode(ppCode);
}
else
{
*ppCode = m_pReJitCode;
if (m_pReJitCode != NULL)
{
m_pReJitCode->ExternalAddRef();
}
}
return S_OK;
}
CordbILCode* CordbJITILFrame::GetOriginalILCode()
{
return m_ilCode;
}
CordbReJitILCode* CordbJITILFrame::GetReJitILCode()
{
return m_pReJitCode;
}
/* ------------------------------------------------------------------------- *
* Eval class
* ------------------------------------------------------------------------- */
CordbEval::CordbEval(CordbThread *pThread)
: CordbBase(pThread->GetProcess(), 0, enumCordbEval),
m_thread(pThread), // implicit InternalAddRef
m_function(NULL),
m_complete(false),
m_successful(false),
m_aborted(false),
m_resultAddr(NULL),
m_evalDuringException(false)
{
m_vmObjectHandle = VMPTR_OBJECTHANDLE::NullPtr();
m_debuggerEvalKey = LSPTR_DEBUGGEREVAL::NullPtr();
m_resultType.elementType = ELEMENT_TYPE_VOID;
m_resultAppDomainToken = VMPTR_AppDomain::NullPtr();
CordbAppDomain * pDomain = m_thread->GetAppDomain();
(void)pDomain; //prevent "unused variable" error from GCC
#ifdef _DEBUG
// Remember what AD we started in so that we can check that we finish there too.
m_DbgAppDomainStarted = pDomain;
#endif
// Place ourselves on the processes neuter-list.
HRESULT hr = S_OK;
EX_TRY
{
GetProcess()->AddToLeftSideResourceCleanupList(this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
CordbEval::~CordbEval()
{
_ASSERTE(IsNeutered());
}
// Free the left-side resources for the eval.
void CordbEval::NeuterLeftSideResources()
{
SendCleanup();
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
Neuter();
}
// Neuter the CordbEval
//
// Assumptions:
// By the time we neuter the eval, it's associated left-side resources
// are already cleaned up (either explicitly from calling code:CordbEval::SendCleanup
// or implicitly from the left-side exiting).
//
// Notes:
// We place ourselves on a neuter list. This gets called when the neuterlist sweeps.
void CordbEval::Neuter()
{
// By now, we should have freed our target-resources (code:CordbEval::NeuterLeftSideResources
// or code:CordbEval::SendCleanup), unless the target is dead (terminated or about to exit).
BOOL fTargetIsDead = !GetProcess()->IsSafeToSendEvents() || GetProcess()->m_exiting;
(void)fTargetIsDead; //prevent "unused variable" error from GCC
_ASSERTE(fTargetIsDead || (m_debuggerEvalKey == NULL));
m_thread.Clear();
CordbBase::Neuter();
}
HRESULT CordbEval::SendCleanup()
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
HRESULT hr = S_OK;
// Send a message to the left side to release the eval object over
// there if one exists.
if ((m_debuggerEvalKey != NULL) &&
GetProcess()->IsSafeToSendEvents())
{
// Call Abort() before doing new CallFunction()
if (!m_complete)
return CORDBG_E_FUNC_EVAL_NOT_COMPLETE;
// Release the left side handle to the object
DebuggerIPCEvent event;
GetProcess()->InitIPCEvent(
&event,
DB_IPCE_FUNC_EVAL_CLEANUP,
true,
m_thread->GetAppDomain()->GetADToken());
event.FuncEvalCleanup.debuggerEvalKey = m_debuggerEvalKey;
hr = GetProcess()->SendIPCEvent(&event, sizeof(DebuggerIPCEvent));
IfFailRet(hr);
#if _DEBUG
if (SUCCEEDED(hr))
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_CLEANUP_RESULT);
#endif
// Null out the key so we don't try to do this again.
m_debuggerEvalKey = LSPTR_DEBUGGEREVAL::NullPtr();
hr = event.hr;
}
// Release the cached HandleValue for the result. This may cleanup resources,
// like our object handle to the func-eval result.
m_pHandleValue.Clear();
return hr;
}
HRESULT CordbEval::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEval)
{
*pInterface = static_cast<ICorDebugEval*>(this);
}
else if (id == IID_ICorDebugEval2)
{
*pInterface = static_cast<ICorDebugEval2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugEval*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//
// Gather data about an argument to either CallFunction or NewObject
// and place it into a DebuggerIPCE_FuncEvalArgData struct for passing
// to the Left Side.
//
HRESULT CordbEval::GatherArgInfo(ICorDebugValue *pValue,
DebuggerIPCE_FuncEvalArgData *argData)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
HRESULT hr;
CORDB_ADDRESS addr;
CorElementType ty;
bool needRelease = false;
pValue->GetType(&ty);
// Note: if the value passed in is in fact a byref, then we need to dereference it to get to the real thing. Passing
// a byref as a byref to a func eval is never right.
if ((ty == ELEMENT_TYPE_BYREF) || (ty == ELEMENT_TYPE_TYPEDBYREF))
{
ICorDebugReferenceValue *prv = NULL;
// The value had better implement ICorDebugReference value.
IfFailRet(pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&prv));
// This really should always work for a byref, unless we're out of memory.
hr = prv->Dereference(&pValue);
prv->Release();
IfFailRet(hr);
// Make sure to get the type we were referencing for use below.
pValue->GetType(&ty);
needRelease = true;
}
// We should never have a byref by this point.
_ASSERTE((ty != ELEMENT_TYPE_BYREF) && (ty != ELEMENT_TYPE_TYPEDBYREF));
pValue->GetAddress(&addr);
argData->argAddr = CORDB_ADDRESS_TO_PTR(addr);
argData->argElementType = ty;
argData->argIsHandleValue = false;
argData->argIsLiteral = false;
argData->fullArgType = NULL;
argData->fullArgTypeNodeCount = 0;
// We have to have knowledge of our value implementation here,
// which it would nice if we didn't have to know.
CordbValue *cv = NULL;
switch(ty)
{
case ELEMENT_TYPE_CLASS:
case ELEMENT_TYPE_OBJECT:
case ELEMENT_TYPE_STRING:
case ELEMENT_TYPE_PTR:
case ELEMENT_TYPE_ARRAY:
case ELEMENT_TYPE_SZARRAY:
{
ICorDebugHandleValue *pHandle = NULL;
pValue->QueryInterface(IID_ICorDebugHandleValue, (void **) &pHandle);
if (pHandle == NULL)
{
// A reference value
cv = static_cast<CordbValue*> (static_cast<CordbReferenceValue*> (pValue));
argData->argIsHandleValue = !(((CordbReferenceValue *)pValue)->m_valueHome.ObjHandleIsNull());
// Is this a literal value? If, we'll copy the data to the
// buffer area so the left side can get it.
CordbReferenceValue *rv;
rv = static_cast<CordbReferenceValue*>(pValue);
argData->argIsLiteral = rv->CopyLiteralData(argData->argLiteralData);
if (rv->GetValueHome())
{
rv->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
}
else
{
argData->argIsHandleValue = true;
argData->argIsLiteral = false;
pHandle->Release();
argData->argHome.kind = RAK_NONE;
}
}
break;
case ELEMENT_TYPE_VALUETYPE: // OK: this E_T_VALUETYPE comes ICorDebugValue::GetType
// A value class object
cv = static_cast<CordbValue*> (static_cast<CordbVCObjectValue*>(static_cast<ICorDebugObjectValue*> (pValue)));
// The EE does not guarantee to have exact type information
// available for all struct types, so we indicate the type by using a
// DebuggerIPCE_TypeArgData serialization of a type.
//
// At the moment the LHS only cares about this data
// when boxing the "this" pointer.
{
CordbVCObjectValue * pVCObjVal =
static_cast<CordbVCObjectValue *>(static_cast<ICorDebugObjectValue*> (pValue));
unsigned int fullArgTypeNodeCount = 0;
cv->m_type->CountTypeDataNodes(&fullArgTypeNodeCount);
_ASSERTE(fullArgTypeNodeCount > 0);
unsigned int bufferSize = sizeof(DebuggerIPCE_TypeArgData) * fullArgTypeNodeCount;
DebuggerIPCE_TypeArgData *bufferFrom = (DebuggerIPCE_TypeArgData *) _alloca(bufferSize);
DebuggerIPCE_TypeArgData *curr = bufferFrom;
CordbType::GatherTypeData(cv->m_type, &curr);
void *buffer = NULL;
IfFailRet(m_thread->GetProcess()->GetAndWriteRemoteBuffer(m_thread->GetAppDomain(), bufferSize, bufferFrom, &buffer));
argData->fullArgType = buffer;
argData->fullArgTypeNodeCount = fullArgTypeNodeCount;
// Is it enregistered?
if ((addr == NULL) && (pVCObjVal->GetValueHome() != NULL))
{
pVCObjVal->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
}
break;
default:
// A generic value
cv = static_cast<CordbValue*> (static_cast<CordbGenericValue*> (pValue));
// Is this a literal value? If, we'll copy the data to the
// buffer area so the left side can get it.
CordbGenericValue *gv = (CordbGenericValue*)pValue;
argData->argIsLiteral = gv->CopyLiteralData(argData->argLiteralData);
// Is it enregistered?
if ((addr == NULL) && (gv->GetValueHome() != NULL))
{
gv->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
break;
}
// Release pValue if we got it via a dereference from above.
if (needRelease)
pValue->Release();
return S_OK;
}
HRESULT CordbEval::SendFuncEval(unsigned int genericArgsCount,
ICorDebugType *genericArgs[],
void *argData1, unsigned int argData1Size,
void *argData2, unsigned int argData2Size,
DebuggerIPCEvent * event)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
unsigned int genericArgsNodeCount = 0;
DebuggerIPCE_TypeArgData *tyargData = NULL;
CordbType::CountTypeDataNodesForInstantiation(genericArgsCount,genericArgs,&genericArgsNodeCount);
unsigned int tyargDataSize = sizeof(DebuggerIPCE_TypeArgData) * genericArgsNodeCount;
if (genericArgsNodeCount > 0)
{
tyargData = new (nothrow) DebuggerIPCE_TypeArgData[genericArgsNodeCount];
if (tyargData == NULL)
{
return E_OUTOFMEMORY;
}
DebuggerIPCE_TypeArgData *curr_tyargData = tyargData;
CordbType::GatherTypeDataForInstantiation(genericArgsCount, genericArgs, &curr_tyargData);
}
event->FuncEval.genericArgsNodeCount = genericArgsNodeCount;
// Are we doing an eval during an exception? If so, we need to remember
// that over here and also tell the Left Side.
event->FuncEval.evalDuringException = m_thread->HasException();
m_evalDuringException = !!event->FuncEval.evalDuringException;
m_vmThreadOldExceptionHandle = m_thread->GetThreadExceptionRawObjectHandle();
// Corresponding Release() on DB_IPCE_FUNC_EVAL_COMPLETE.
// If a func eval is aborted, the LHS may not complete the abort
// immediately and hence we cant do a SendCleanup(). Hence, we maintain
// an extra ref-count to determine when this can be done.
AddRef();
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(event, sizeof(DebuggerIPCEvent));
// If the send failed, return that failure.
if (FAILED(hr))
goto LExit;
_ASSERTE(event->type == DB_IPCE_FUNC_EVAL_SETUP_RESULT);
hr = event->hr;
// Memory has been allocated to hold info about each argument on
// the left side now, so copy the argument data over to the left
// side. No need to send another event, since the left side won't
// take any more action on this evaluation until the process is
// continued anyway.
//
// The type arguments come first, followed by up to two blobs of data
// for other arguments.
if (SUCCEEDED(hr))
{
EX_TRY
{
CORDB_ADDRESS argdata = event->FuncEvalSetupComplete.argDataArea;
if ((tyargData != NULL) && (tyargDataSize != 0))
{
TargetBuffer tb(argdata, tyargDataSize);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) tyargData); // throws
argdata += tyargDataSize;
}
if ((argData1 != NULL) && (argData1Size != 0))
{
TargetBuffer tb(argdata, argData1Size);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) argData1); // throws
argdata += argData1Size;
}
if ((argData2 != NULL) && (argData2Size != 0))
{
TargetBuffer tb(argdata, argData2Size);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) argData2); // throws
argdata += argData2Size;
}
}
EX_CATCH_HRESULT(hr);
}
LExit:
if (tyargData)
{
delete [] tyargData;
}
// Save the key to the eval on the left side for future reference.
if (SUCCEEDED(hr))
{
m_debuggerEvalKey = event->FuncEvalSetupComplete.debuggerEvalKey;
m_thread->GetProcess()->IncrementOutstandingEvalCount();
}
else
{
// We dont expect to receive a DB_IPCE_FUNC_EVAL_COMPLETE, so just release here
Release();
}
return hr;
}
// Get the AppDomain that an object lives in.
// This does not adjust any reference counts.
// Returns NULL if we can't determine the appdomain, or if the value is known to be agile.
CordbAppDomain * GetAppDomainFromValue(ICorDebugValue * pValue)
{
// Unfortunately, there's no direct way to cast from an ICDValue to a CordbValue.
// So we need to QI for the culprit interfaces and check specifically.
{
RSExtSmartPtr<ICorDebugHandleValue> handleP;
pValue->QueryInterface(IID_ICorDebugHandleValue, (void**)&handleP);
if (handleP != NULL)
{
CordbHandleValue * chp = static_cast<CordbHandleValue *> (handleP.GetValue());
return chp->GetAppDomain();
}
}
{
RSExtSmartPtr<ICorDebugReferenceValue> refP;
pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&refP);
if (refP != NULL)
{
CordbReferenceValue * crp = static_cast<CordbReferenceValue *> (refP.GetValue());
return crp->GetAppDomain();
}
}
{
RSExtSmartPtr<ICorDebugObjectValue> objP;
pValue->QueryInterface(IID_ICorDebugObjectValue, (void**)&objP);
if (objP != NULL)
{
CordbVCObjectValue * crp = static_cast<CordbVCObjectValue*> (objP.GetValue());
return crp->GetAppDomain();
}
}
// Assume nothing else has AD affinity.
return NULL;
}
HRESULT CordbEval::CallFunction(ICorDebugFunction *pFunction,
ULONG32 nArgs,
ICorDebugValue *pArgs[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if (GetProcess()->GetShim() == NULL)
{
return E_NOTIMPL;
}
return CallParameterizedFunction(pFunction,0,NULL,nArgs,pArgs);
}
//-----------------------------------------------------------------------------
// See if we can convert general Func-eval failure HRs (which are usually based on EE-invariants that
// may be meaningless to the user) into a more specific user-friendly hr.
// Doing the conversions here in the RS (instead of in the LS) makes it more clear that these
// HRs definitely map to concepts described by the ICorDebugAPI instead of EE-invariants.
// It also lets us clearly prioritize the HRs in case of ambiguity.
//-----------------------------------------------------------------------------
HRESULT CordbEval::FilterHR(HRESULT hr)
{
// Currently, we only make CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT more specific.
// If it's not that HR, then shortcut our work.
if (hr != CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT)
{
return hr;
}
// In the case of conflicting HRs (if the func-eval fails for multiple reasons),
// we'll try to give priority to the more general HR.
// This communicates the quickest action for the user to be able to get to a
// func-eval friendly spot. It also means less churn in the hrs we return
// because specific hrs are more likely to change than general ones.
// If we got CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT, check the common reasons.
// We'll use the Right-Side's intimate knowledge of the Left-Side to guess _why_
// it's a GC-unsafe spot, and then we'll communicate that back w/ a more meaningful HR.
// If GC safe-spots change, then these errors should be updated.
//
// Most likely is if we're in native code. Check that first.
//
// In V2, we do this check by checking if the leaf chain is native. Since we have no chain in Arrowhead,
// we can't do this check. Instead, we check whether the active frame is NULL or not. If it's NULL,
// then we are stopped in native code.
//
HRESULT hrTemp = S_OK;
if (GetProcess()->GetShim() != NULL)
{
// the V2 case
RSExtSmartPtr<ICorDebugChain> pChain;
hrTemp = m_thread->GetActiveChain(&pChain);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
// pChain should never be NULL here, since we should have at least one thread start chain even if
// there is no managed code on the stack, but let's just be extra careful here.
if (pChain == NULL)
{
return hr;
}
BOOL fManagedChain;
hrTemp = pChain->IsManaged(&fManagedChain);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
if (fManagedChain == FALSE)
{
return CORDBG_E_ILLEGAL_IN_NATIVE_CODE;
}
}
RSExtSmartPtr<ICorDebugFrame> pIFrame;
hrTemp = m_thread->GetActiveFrame(&pIFrame);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
CordbFrame * pFrame = NULL;
pFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
if (GetProcess()->GetShim() == NULL)
{
// the Arrowhead case
if (pFrame == NULL)
{
return CORDBG_E_ILLEGAL_IN_NATIVE_CODE;
}
}
// Next, check if we're in optimized code.
// Optimized code doesn't directly mean that func-evals are illegal; but it greatly
// increases the odds of being at a GC-unsafe point.
// We give this failure higher precedence than the "Is in prolog" failure.
if (pFrame != NULL)
{
CordbNativeFrame * pNativeFrame = pFrame->GetAsNativeFrame();
if (pNativeFrame != NULL)
{
CordbNativeCode * pCode = pNativeFrame->GetNativeCode();
if (pCode != NULL)
{
DWORD flags;
hrTemp = pCode->GetModule()->GetJITCompilerFlags(&flags);
if (SUCCEEDED(hrTemp))
{
if ((flags & CORDEBUG_JIT_DISABLE_OPTIMIZATION) != CORDEBUG_JIT_DISABLE_OPTIMIZATION)
{
return CORDBG_E_ILLEGAL_IN_OPTIMIZED_CODE;
}
} // GetCompilerFlags
} // Code
CordbJITILFrame * pILFrame = pNativeFrame->m_JITILFrame;
if (pILFrame != NULL)
{
if (pILFrame->m_mapping == MAPPING_PROLOG)
{
return CORDBG_E_ILLEGAL_IN_PROLOG;
}
}
} // Native Frame
}
// No filtering.
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine calls a function with the given set of type arguments and actual arguments.
// This is the jumping off point for func-eval.
//
// Arguments:
// pFunction - The function to call.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
// nArgs - The number of arguments for the method in rgpArgs
// rgpArgs - An array of pointers to values for the arguments to the method.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::CallParameterizedFunction(ICorDebugFunction *pFunction,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[],
ULONG32 nArgs,
ICorDebugValue * rgpArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pFunction, ICorDebugFunction *);
if (nArgs > 0)
{
VALIDATE_POINTER_TO_OBJECT_ARRAY(rgpArgs, ICorDebugValue *, nArgs, true, true);
}
HRESULT hr = E_FAIL;
{
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugValues and ICorDebugTypes are in
// the same appdomain as the function. Verify this.
CordbAppDomain * pMethodAppDomain = (static_cast<CordbFunction *> (pFunction))->GetAppDomain();
if (!DoAppDomainsMatch(pMethodAppDomain, nTypeArgs, rgpTypeArgs, nArgs, rgpArgs))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// Must be locked to get a cookie
RsPtrHolder<CordbEval> hFuncEval(this);
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
lockHolder.Release(); // release to send an IPC event.
// Remember the function that we're evaluating.
m_function = static_cast<CordbFunction *>(pFunction);
m_evalType = DB_IPCE_FET_NORMAL;
// Arrange the arguments into a form that the left side can deal
// with. We do this before starting the func eval setup to ensure
// that we can complete this step before mutating the left
// side.
DebuggerIPCE_FuncEvalArgData * pArgData = NULL;
if (nArgs > 0)
{
// We need to make the same type of array that the left side
// holds.
pArgData = new (nothrow) DebuggerIPCE_FuncEvalArgData[nArgs];
if (pArgData == NULL)
{
return E_OUTOFMEMORY;
}
// For each argument, convert its home into something the left
// side can understand.
for (unsigned int i = 0; i < nArgs; i++)
{
hr = GatherArgInfo(rgpArgs[i], &(pArgData[i]));
if (FAILED(hr))
{
delete [] pArgData;
return hr;
}
}
}
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = m_function->GetMetadataToken();
event.FuncEval.vmDomainAssembly = m_function->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = nArgs;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs,
rgpTypeArgs,
reinterpret_cast<void *>(pArgData),
sizeof(DebuggerIPCE_FuncEvalArgData) * nArgs,
NULL,
0,
&event);
// Cleanup
if (pArgData)
{
delete [] pArgData;
}
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
}
// Convert from LS EE-centric failure code to something more friendly to end-users.
// Success HRs will not be converted.
hr = FilterHR(hr);
// Return any failure the Left Side may have told us about.
return hr;
}
BOOL CordbEval::DoAppDomainsMatch( CordbAppDomain * pAppDomain,
ULONG32 nTypes,
ICorDebugType *pTypes[],
ULONG32 nValues,
ICorDebugValue *pValues[] )
{
_ASSERTE( !(pTypes == NULL && nTypes != 0) );
_ASSERTE( !(pValues == NULL && nValues != 0) );
// Make sure each value is in the appdomain.
for(unsigned int i = 0; i < nValues; i++)
{
// Assuming that only Ref Values have AD affinity
CordbAppDomain * pValueAppDomain = GetAppDomainFromValue( pValues[i] );
if ((pValueAppDomain != NULL) && (pValueAppDomain != pAppDomain))
{
LOG((LF_CORDB,LL_INFO1000, "CordbEval::DADM - AD mismatch. appDomain=0x%08x, param #%d=0x%08x, must fail.\n",
pAppDomain, i, pValueAppDomain));
return FALSE;
}
}
for(unsigned int i = 0; i < nTypes; i++ )
{
CordbType* t = static_cast<CordbType*>( pTypes[i] );
CordbAppDomain * pTypeAppDomain = t->GetAppDomain();
if( pTypeAppDomain != NULL && pTypeAppDomain != pAppDomain )
{
LOG((LF_CORDB,LL_INFO1000, "CordbEval::DADM - AD mismatch. appDomain=0x%08x, type param #%d=0x%08x, must fail.\n",
pAppDomain, i, pTypeAppDomain));
return FALSE;
}
}
return TRUE;
}
HRESULT CordbEval::NewObject(ICorDebugFunction *pConstructor,
ULONG32 nArgs,
ICorDebugValue *pArgs[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewParameterizedObject(pConstructor,0,NULL,nArgs,pArgs);
}
//---------------------------------------------------------------------------------------
//
// This routine calls a constructor with the given set of type arguments and actual arguments.
// This is the jumping off point for func-evaling "new".
//
// Arguments:
// pConstructor - The function to call.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
// nArgs - The number of arguments for the method in rgpArgs
// rgpArgs - An array of pointers to values for the arguments to the method.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedObject(ICorDebugFunction * pConstructor,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[],
ULONG32 nArgs,
ICorDebugValue * rgpArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pConstructor, ICorDebugFunction *);
VALIDATE_POINTER_TO_OBJECT_ARRAY(rgpArgs, ICorDebugValue *, nArgs, true, true);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugValues and ICorDebugTypes are in
// the same appdomain as the constructor. Verify this.
CordbAppDomain * pConstructorAppDomain = (static_cast<CordbFunction *> (pConstructor))->GetAppDomain();
if (!DoAppDomainsMatch(pConstructorAppDomain, nTypeArgs, rgpTypeArgs, nArgs, rgpArgs))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
lockHolder.Release();
// Remember the function that we're evaluating.
m_function = static_cast<CordbFunction *>(pConstructor);
m_evalType = DB_IPCE_FET_NEW_OBJECT;
// Arrange the arguments into a form that the left side can deal
// with. We do this before starting the func eval setup to ensure
// that we can complete this step before mutating up the left
// side.
DebuggerIPCE_FuncEvalArgData * pArgData = NULL;
if (nArgs > 0)
{
// We need to make the same type of array that the left side
// holds.
pArgData = new (nothrow) DebuggerIPCE_FuncEvalArgData[nArgs];
if (pArgData == NULL)
{
return E_OUTOFMEMORY;
}
// For each argument, convert its home into something the left
// side can understand.
for (unsigned int i = 0; i < nArgs; i++)
{
hr = GatherArgInfo(rgpArgs[i], &(pArgData[i]));
if (FAILED(hr))
{
delete [] pArgData;
return hr;
}
}
}
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = m_function->GetMetadataToken();
event.FuncEval.vmDomainAssembly = m_function->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = nArgs;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs,
rgpTypeArgs,
reinterpret_cast<void *>(pArgData),
sizeof(DebuggerIPCE_FuncEvalArgData) * nArgs,
NULL,
0,
&event);
// Cleanup
if (pArgData)
{
delete [] pArgData;
}
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::NewObjectNoConstructor(ICorDebugClass *pClass)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewParameterizedObjectNoConstructor(pClass,0,NULL);
}
//---------------------------------------------------------------------------------------
//
// This routine creates an object of a certain type, but does not call the constructor
// for the type on the object.
//
// Arguments:
// pClass - the type of the object to create.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedObjectNoConstructor(ICorDebugClass * pClass,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pClass, ICorDebugClass *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugTypes are in
// the same appdomain as the class. Verify this.
CordbAppDomain * pClassAppDomain = (static_cast<CordbClass *> (pClass))->GetAppDomain();
if (!DoAppDomainsMatch(pClassAppDomain, nTypeArgs, rgpTypeArgs, 0, NULL))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Remember the function that we're evaluating.
m_class = (CordbClass*)pClass;
m_evalType = DB_IPCE_FET_NEW_OBJECT_NC;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = (mdTypeDef)m_class->m_id;
event.FuncEval.vmDomainAssembly = m_class->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs, rgpTypeArgs, NULL, 0, NULL, 0, &event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
/*
*
* NewString
*
* This routine is the interface function for ICorDebugEval::NewString
*
* Parameters:
* string - the string to create - must be null-terminated
*
* Return Value:
* HRESULT from the helper routines on RS and LS.
*
*/
HRESULT CordbEval::NewString(LPCWSTR string)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewStringWithLength(string, (UINT)wcslen(string));
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugEval::NewStringWithLength.
//
// Arguments:
// wszString - the string to create
// iLength - the number of characters that you want to create. Can include embedded nulls.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewStringWithLength(LPCWSTR wszString, UINT iLength)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(wszString, LPCWSTR); // Gotta have a string...
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Length of the string? Don't account for null as COMString::NewString is length-based
SIZE_T cbString = iLength * sizeof(WCHAR);
// Remember that we're doing a func eval for a new string.
m_function = NULL;
m_evalType = DB_IPCE_FET_NEW_STRING;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.stringSize = cbString;
// Note: no function or module here...
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = mdTypeDefNil;
event.FuncEval.vmDomainAssembly = VMPTR_DomainAssembly::NullPtr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = 0;
event.FuncEval.genericArgsNodeCount = 0;
hr = SendFuncEval(0, NULL, (void *)wszString, (unsigned int)cbString, NULL, 0, &event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::NewArray(CorElementType elementType,
ICorDebugClass *pElementClass,
ULONG32 rank,
ULONG32 dims[],
ULONG32 lowBounds[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pElementClass, ICorDebugClass *);
// If you want a class, you gotta pass a class.
if ((elementType == ELEMENT_TYPE_CLASS) && (pElementClass == NULL))
return E_INVALIDARG;
// If you want an array of objects, then why pass a class?
if ((elementType == ELEMENT_TYPE_OBJECT) && (pElementClass != NULL))
return E_INVALIDARG;
// Arg check...
if (elementType == ELEMENT_TYPE_VOID)
return E_INVALIDARG;
CordbType *typ;
HRESULT hr = S_OK;
hr = CordbType::MkUnparameterizedType(m_thread->GetAppDomain(), elementType, (CordbClass *) pElementClass, &typ);
if (FAILED(hr))
return hr;
return NewParameterizedArray(typ, rank,dims,lowBounds);
}
//---------------------------------------------------------------------------------------
//
// This routine sets up a func-eval to create a new array of the given type.
//
// Arguments:
// pElementType - The type of each element of the array.
// rank - Rank of the array.
// rgDimensions - Array of dimensions for the array.
// rmLowBounds - Array of lower bounds on the array.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedArray(ICorDebugType * pElementType,
ULONG32 rank,
ULONG32 rgDimensions[],
ULONG32 rgLowBounds[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pElementType, ICorDebugType *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Callers are free to reuse an ICorDebugEval object for multiple evals. Since we create a Left Side eval
// representation each time, we need to be sure to clean it up now that we know we're done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
// Arg check...
if ((rank == 0) || (rgDimensions == NULL))
{
return E_INVALIDARG;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Remember that we're doing a func eval for a new string.
m_function = NULL;
m_evalType = DB_IPCE_FET_NEW_ARRAY;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.arrayRank = rank;
// Note: no function or module here...
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = mdTypeDefNil;
event.FuncEval.vmDomainAssembly = VMPTR_DomainAssembly::NullPtr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = 1;
// Prefast overflow sanity check.
S_UINT32 allocSize = S_UINT32(rank) * S_UINT32(sizeof(SIZE_T));
if (allocSize.IsOverflow())
{
return E_INVALIDARG;
}
// Just in case sizeof(SIZE_T) != sizeof(ULONG32)
SIZE_T * rgDimensionsSizeT = reinterpret_cast<SIZE_T *>(_alloca(allocSize.Value()));
for (unsigned int i = 0; i < rank; i++)
{
rgDimensionsSizeT[i] = rgDimensions[i];
}
ICorDebugType * rgpGenericArgs[1];
rgpGenericArgs[0] = pElementType;
// @dbgtodo funceval : lower bounds were ignored in V1 - fix this.
hr = SendFuncEval(1,
rgpGenericArgs,
reinterpret_cast<void *>(rgDimensionsSizeT),
rank * sizeof(SIZE_T),
NULL, // (void*)lowBounds,
0, // ((lowBounds == NULL) ? 0 : rank * sizeof(SIZE_T)),
&event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::IsActive(BOOL *pbActive)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pbActive, BOOL *);
*pbActive = (m_complete == true);
return S_OK;
}
/*
* This routine submits an abort request to the LS.
*
* Parameters:
* None.
*
* Returns:
* The HRESULT as returned by the LS.
*
*/
HRESULT
CordbEval::Abort(
void
)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_ALLOW_LIVE_DO_STOPGO(GetProcess());
//
// No need to abort if its already completed.
//
if (m_complete)
{
return S_OK;
}
//
// Can't abort if its never even been started.
//
if (m_debuggerEvalKey == NULL)
{
return E_INVALIDARG;
}
CORDBRequireProcessStateOK(m_thread->GetProcess());
//
// Send over to the left side to get the eval aborted.
//
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event,
DB_IPCE_FUNC_EVAL_ABORT,
true,
m_thread->GetAppDomain()->GetADToken()
);
event.FuncEvalAbort.debuggerEvalKey = m_debuggerEvalKey;
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(&event,
sizeof(DebuggerIPCEvent)
);
//
// If the send failed, return that failure.
//
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_ABORT_RESULT);
//
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
//
m_thread->GetProcess()->m_continueCounter++;
hr = event.hr;
return hr;
}
HRESULT CordbEval::GetResult(ICorDebugValue **ppResult)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppResult, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*ppResult = NULL;
// Is the evaluation complete?
if (!m_complete)
{
return CORDBG_E_FUNC_EVAL_NOT_COMPLETE;
}
if (m_aborted)
{
return CORDBG_S_FUNC_EVAL_ABORTED;
}
// Does the evaluation have a result?
if (m_resultType.elementType == ELEMENT_TYPE_VOID)
{
return CORDBG_S_FUNC_EVAL_HAS_NO_RESULT;
}
HRESULT hr = S_OK;
EX_TRY
{
// Make a ICorDebugValue out of the result.
CordbAppDomain * pAppDomain;
if (!m_resultAppDomainToken.IsNull())
{
// @dbgtodo funceval - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
pAppDomain = m_thread->GetProcess()->LookupOrCreateAppDomain(m_resultAppDomainToken);
}
else
{
pAppDomain = m_thread->GetAppDomain();
}
PREFIX_ASSUME(pAppDomain != NULL);
CordbType * pType = NULL;
hr = CordbType::TypeDataToType(pAppDomain, &m_resultType, &pType);
IfFailThrow(hr);
bool resultInHandle =
((m_resultType.elementType == ELEMENT_TYPE_CLASS) ||
(m_resultType.elementType == ELEMENT_TYPE_SZARRAY) ||
(m_resultType.elementType == ELEMENT_TYPE_OBJECT) ||
(m_resultType.elementType == ELEMENT_TYPE_ARRAY) ||
(m_resultType.elementType == ELEMENT_TYPE_STRING));
if (resultInHandle)
{
// if object handle is null here, something has gone wrong!!!
_ASSERTE(!m_vmObjectHandle.IsNull());
if (m_pHandleValue == NULL)
{
// Create CordbHandleValue for result
RSInitHolder<CordbHandleValue> pHandleValue(new CordbHandleValue(pAppDomain, pType, HANDLE_STRONG));
// Initialize the handle value object. The HandleValue will now
// own the m_objectHandle.
hr = pHandleValue->Init(m_vmObjectHandle);
if (!SUCCEEDED(hr))
{
// Neuter the new object we've been working on. This will
// call Dispose(), and that will go back to the left side
// and free the handle that we got above.
pHandleValue->NeuterLeftSideResources();
//
// Do not delete chv here. The neuter list still has a reference to it, and it will be cleaned up automatically.
ThrowHR(hr);
}
m_pHandleValue.Assign(pHandleValue);
pHandleValue.ClearAndMarkDontNeuter();
}
// This AddRef is for caller to release
//
*ppResult = m_pHandleValue;
m_pHandleValue->ExternalAddRef();
}
else if (CorIsPrimitiveType(m_resultType.elementType) && (m_resultType.elementType != ELEMENT_TYPE_STRING))
{
// create a CordbGenericValue flagged as a literal
hr = CordbEval::CreatePrimitiveLiteral(pType, ppResult);
}
else
{
TargetBuffer remoteValue(m_resultAddr, CordbValue::GetSizeForType(pType, kBoxed));
// Now that we have the module, go ahead and create the result.
CordbValue::CreateValueByType(pAppDomain,
pType,
true,
remoteValue,
MemoryRange(NULL, 0),
NULL,
ppResult); // throws
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbEval::GetThread(ICorDebugThread **ppThread)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppThread, ICorDebugThread **);
*ppThread = static_cast<ICorDebugThread*> (m_thread);
m_thread->ExternalAddRef();
return S_OK;
}
// Create a RS literal for primitive type funceval result. In case the result is used as an argument for
// another funceval, we need to make sure that we're not relying on the LS value, which will be freed and
// thus unavailable.
// Arguments:
// input: pType - CordbType instance representing the type of the primitive value
// output: ppValue - ICorDebugValue representing the result as a literal CordbGenericValue
// Return Value:
// hr: may fail for OOM, ReadProcessMemory failures
HRESULT CordbEval::CreatePrimitiveLiteral(CordbType * pType,
ICorDebugValue ** ppValue)
{
CordbGenericValue * gv = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// Create a generic value.
gv = new CordbGenericValue(pType);
// initialize the local value
int size = CordbValue::GetSizeForType(pType, kBoxed);
if (size > 8)
{
ThrowHR(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
}
TargetBuffer remoteValue(m_resultAddr, size);
BYTE localBuffer[8] = {0};
GetProcess()->SafeReadBuffer (remoteValue, localBuffer);
gv->SetValue(localBuffer);
// Do not delete gv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
gv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugGenericValue*)gv;
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbEval::CreateValue(CorElementType elementType,
ICorDebugClass *pElementClass,
ICorDebugValue **ppValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
CordbType *typ;
// @todo: only primitive values right now.
if (((elementType < ELEMENT_TYPE_BOOLEAN) ||
(elementType > ELEMENT_TYPE_R8)) &&
!(elementType == ELEMENT_TYPE_CLASS))
return E_INVALIDARG;
HRESULT hr = S_OK;
// MkUnparameterizedType now works if you give it ELEMENT_TYPE_CLASS and
// a null pElementClass - it returns the type for ELEMENT_TYPE_OBJECT.
hr = CordbType::MkUnparameterizedType(m_thread->GetAppDomain(), elementType, (CordbClass *) pElementClass, &typ);
if (FAILED(hr))
return hr;
return CreateValueForType(typ, ppValue);
}
// create an ICDValue to represent a value for a funceval
// Arguments:
// input: pIType - the type for the new value
// output: ppValue - the new ICDValue. If there is a failure of some sort, this will be NULL
// ReturnValue: S_OK on success (ppValue should contain a non-NULL address)
// E_OUTOFMEMORY, if we can't allocate space for the new ICDValue
// Notes: We can also get read process memory errors or E_INVALIDARG if errors occur during initialization,
// but in that case, we don't return the hresult. Instead, we just never update ppValue, so it will still be
// NULL on exit.
HRESULT CordbEval::CreateValueForType(ICorDebugType * pIType,
ICorDebugValue ** ppValue)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
VALIDATE_POINTER_TO_OBJECT(pIType, ICorDebugType*);
*ppValue = NULL;
CordbType *pType = static_cast<CordbType *> (pIType);
CorElementType elementType = pType->m_elementType;
// We don't support IntPtr and UIntPtr types as arguments here, but we do support these types as results
// (see code:CordbEval::CreatePrimitiveLiteral) and we have changed the LS to support them as well
if (((elementType < ELEMENT_TYPE_BOOLEAN) ||
(elementType > ELEMENT_TYPE_R8)) &&
!((elementType == ELEMENT_TYPE_CLASS) || (elementType == ELEMENT_TYPE_OBJECT)))
return E_INVALIDARG;
// Note: ELEMENT_TYPE_OBJECT is what we'll get for the null reference case, so allow that.
if ((elementType == ELEMENT_TYPE_CLASS) || (elementType == ELEMENT_TYPE_OBJECT))
{
EX_TRY
{
// create a reference value
CordbReferenceValue *rv = new CordbReferenceValue(pType);
if (SUCCEEDED(rv->InitRef(MemoryRange(NULL,0))))
{
// Do not delete rv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
rv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugReferenceValue*)rv;
}
}
EX_CATCH_HRESULT(hr);
}
else
{
CordbGenericValue * gv = NULL;
EX_TRY
{
// Create a generic value.
gv = new CordbGenericValue(pType);
gv->Init(MemoryRange(NULL,0));
// Do not delete gv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
gv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugGenericValue*)gv;
}
EX_CATCH_HRESULT(hr);
}
return hr;
} // CordbEval::CreateValueForType
/* ------------------------------------------------------------------------- *
* CordbEval2
*
* Extentions to the CordbEval class for Whidbey
*
* ------------------------------------------------------------------------- */
/*
* This routine submits a rude abort request to the LS.
*
* Parameters:
* None.
*
* Returns:
* The HRESULT as returned by the LS.
*
*/
HRESULT
CordbEval::RudeAbort(
void
)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_ALLOW_LIVE_DO_STOPGO(GetProcess());
//
// No need to abort if its already completed.
//
if (m_complete)
{
return S_OK;
}
//
// Can't abort if its never even been started.
//
if (m_debuggerEvalKey == NULL)
{
return E_INVALIDARG;
}
CORDBRequireProcessStateOK(m_thread->GetProcess());
//
// Send over to the left side to get the eval aborted.
//
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event,
DB_IPCE_FUNC_EVAL_RUDE_ABORT,
true,
m_thread->GetAppDomain()->GetADToken()
);
event.FuncEvalRudeAbort.debuggerEvalKey = m_debuggerEvalKey;
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(&event,
sizeof(DebuggerIPCEvent)
);
//
// If the send failed, return that failure.
//
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_RUDE_ABORT_RESULT);
//
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
//
m_thread->GetProcess()->m_continueCounter++;
hr = event.hr;
return hr;
}
/* ------------------------------------------------------------------------- *
* CodeParameter Enumerator class
* ------------------------------------------------------------------------- */
CordbCodeEnum::CordbCodeEnum(unsigned int cCodes, RSSmartPtr<CordbCode> * ppCodes) :
CordbBase(NULL, 0)
{
// Because the array is of smart-ptrs, the elements are already reffed
// We now take ownership of the array itself too.
m_ppCodes = ppCodes;
m_iCurrent = 0;
m_iMax = cCodes;
}
CordbCodeEnum::~CordbCodeEnum()
{
// This will invoke the SmartPtr dtors on each element and call release.
delete [] m_ppCodes;
}
HRESULT CordbCodeEnum::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEnum)
*pInterface = static_cast<ICorDebugEnum*>(this);
else if (id == IID_ICorDebugCodeEnum)
*pInterface = static_cast<ICorDebugCodeEnum*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugCodeEnum*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbCodeEnum::Skip(ULONG celt)
{
HRESULT hr = E_FAIL;
if ( (m_iCurrent+celt) < m_iMax ||
celt == 0)
{
m_iCurrent += celt;
hr = S_OK;
}
return hr;
}
HRESULT CordbCodeEnum::Reset()
{
m_iCurrent = 0;
return S_OK;
}
HRESULT CordbCodeEnum::Clone(ICorDebugEnum **ppEnum)
{
VALIDATE_POINTER_TO_OBJECT(ppEnum, ICorDebugEnum **);
(*ppEnum) = NULL;
HRESULT hr = S_OK;
// Create a new copy of the array because the CordbCodeEnum will
// take ownership of it.
RSSmartPtr<CordbCode> * ppCodes = new (nothrow) RSSmartPtr<CordbCode> [m_iMax];
if (ppCodes == NULL)
{
return E_OUTOFMEMORY;
}
for(UINT i = 0; i < m_iMax; i++)
{
ppCodes[i].Assign(m_ppCodes[i]);
}
CordbCodeEnum *pCVE = new (nothrow) CordbCodeEnum( m_iMax, ppCodes);
if ( pCVE == NULL )
{
delete [] ppCodes;
hr = E_OUTOFMEMORY;
goto LExit;
}
pCVE->ExternalAddRef();
(*ppEnum) = (ICorDebugEnum*)pCVE;
LExit:
return hr;
}
HRESULT CordbCodeEnum::GetCount(ULONG *pcelt)
{
VALIDATE_POINTER_TO_OBJECT(pcelt, ULONG *);
if( pcelt == NULL)
return E_INVALIDARG;
(*pcelt) = m_iMax;
return S_OK;
}
//
// In the event of failure, the current pointer will be left at
// one element past the troublesome element. Thus, if one were
// to repeatedly ask for one element to iterate through the
// array, you would iterate exactly m_iMax times, regardless
// of individual failures.
HRESULT CordbCodeEnum::Next(ULONG celt, ICorDebugCode *values[], ULONG *pceltFetched)
{
VALIDATE_POINTER_TO_OBJECT_ARRAY(values, ICorDebugClass *,
celt, true, true);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pceltFetched, ULONG *);
if ((pceltFetched == NULL) && (celt != 1))
{
return E_INVALIDARG;
}
if (celt == 0)
{
if (pceltFetched != NULL)
{
*pceltFetched = 0;
}
return S_OK;
}
HRESULT hr = S_OK;
int iMax = min( m_iMax, m_iCurrent+celt);
int i;
for (i = m_iCurrent; i < iMax; i++)
{
values[i-m_iCurrent] = m_ppCodes[i];
values[i-m_iCurrent]->AddRef();
}
int count = (i - m_iCurrent);
if ( FAILED( hr ) )
{ //we failed: +1 pushes us past troublesome element
m_iCurrent += 1 + count;
}
else
{
m_iCurrent += count;
}
if (pceltFetched != NULL)
{
*pceltFetched = count;
}
//
// If we reached the end of the enumeration, but not the end
// of the number of requested items, we return S_FALSE.
//
if (((ULONG)count) < celt)
{
return S_FALSE;
}
return hr;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
//
// File: rsthread.cpp
//
//*****************************************************************************
#include "stdafx.h"
#include "primitives.h"
#include <float.h>
#include <tls.h>
// Stack-based holder for RSPTRs that we allocated to give to the LS.
// If LS successfully takes ownership of them, then call SuppressRelease().
// Else, dtor will free them up.
// This is using a table protected by the ProcessLock().
template <class T>
class RsPtrHolder
{
T * m_pObject;
RsPointer<T> m_ptr;
public:
RsPtrHolder(T* pObject)
{
_ASSERTE(pObject != NULL);
m_ptr.AllocHandle(pObject->GetProcess(), pObject);
m_pObject = pObject;
}
// If owner didn't call SuppressRelease() to take ownership, then have dtor free it.
~RsPtrHolder()
{
if (!m_ptr.IsNull())
{
// @dbgtodo synchronization - push this up. Note that since this is in a dtor;
// need to order it well against RSLockHolder.
RSLockHolder lockHolder(m_pObject->GetProcess()->GetProcessLock());
T* pObjTest = m_ptr.UnWrapAndRemove(m_pObject->GetProcess());
(void)pObjTest; //prevent "unused variable" error from GCC
_ASSERTE(pObjTest == m_pObject);
}
}
RsPointer<T> Ptr()
{
return m_ptr;
}
void SuppressRelease()
{
m_ptr = RsPointer<T>::NullPtr();
}
};
/* ------------------------------------------------------------------------- *
* Managed Thread classes
* ------------------------------------------------------------------------- */
//---------------------------------------------------------------------------------------
//
// Instantiate a CordbThread object, which represents a managed thread.
//
// Arguments:
// process - non-null process object that this thread lives in.
// id - OS thread id of this thread.
// handle - OS Handle to the native thread in the debuggee.
//
//---------------------------------------------------------------------------------------
CordbThread::CordbThread(CordbProcess * pProcess, VMPTR_Thread vmThread) :
CordbBase(pProcess,
VmPtrToCookie(vmThread),
enumCordbThread),
m_pContext(NULL),
m_fContextFresh(false),
m_pAppDomain(NULL),
m_debugState(THREAD_RUN),
m_fFramesFresh(false),
m_fFloatStateValid(false),
m_floatStackTop(0),
m_fException(false),
m_EnCRemapFunctionIP(NULL),
m_userState(kInvalidUserState),
m_hCachedThread(INVALID_HANDLE_VALUE),
m_hCachedOutOfProcThread(INVALID_HANDLE_VALUE)
{
m_fHasUnhandledException = FALSE;
m_pExceptionRecord = NULL;
// Thread id may be a "fake" OS id for a CLRHosted thread.
m_vmThreadToken = vmThread;
// This id must be unique for the thread. V2 uses the current OS thread id.
// If we ever support fibers, then we need to use something more unique than that.
m_dwUniqueID = pProcess->GetDAC()->GetUniqueThreadID(vmThread); // may throw
LOG((LF_CORDB, LL_INFO1000, "CT::CT new thread 0x%p vmptr=0x%p id=0x%x\n",
this, m_vmThreadToken, m_dwUniqueID));
// Unique ID should never be 0.
_ASSERTE(m_dwUniqueID != 0);
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr();
m_vmExcepObjHandle = VMPTR_OBJECTHANDLE::NullPtr();
#if defined(_DEBUG)
for (unsigned int i = 0;
i < (sizeof(m_floatValues) / sizeof(m_floatValues[0]));
i++)
{
m_floatValues[i] = 0;
}
#endif
// Set AppDomain
VMPTR_AppDomain vmAppDomain = pProcess->GetDAC()->GetCurrentAppDomain(vmThread);
m_pAppDomain = pProcess->LookupOrCreateAppDomain(vmAppDomain);
_ASSERTE(m_pAppDomain != NULL);
}
CordbThread::~CordbThread()
{
// We've already been neutered, thus we don't need to call CleanupStack().
// That will have neutered + cleared frames + chains.
_ASSERTE(IsNeutered());
// Cleared in neuter
_ASSERTE(m_pContext == NULL);
_ASSERTE(m_hCachedThread == INVALID_HANDLE_VALUE);
_ASSERTE(m_pExceptionRecord == NULL);
}
// Neutered by the CordbProcess
void CordbThread::Neuter()
{
if (IsNeutered())
{
return;
}
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
delete m_pExceptionRecord;
m_pExceptionRecord = NULL;
// Neuter frames & Chains.
CleanupStack();
if (m_hCachedThread != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hCachedThread);
m_hCachedThread = INVALID_HANDLE_VALUE;
}
if( m_pContext != NULL )
{
delete [] m_pContext;
m_pContext = NULL;
}
ClearStackFrameCache();
CordbBase::Neuter();
}
HRESULT CordbThread::QueryInterface(REFIID id, void ** ppInterface)
{
if (id == IID_ICorDebugThread)
{
*ppInterface = static_cast<ICorDebugThread *>(this);
}
else if (id == IID_ICorDebugThread2)
{
*ppInterface = static_cast<ICorDebugThread2 *>(this);
}
else if (id == IID_ICorDebugThread3)
{
*ppInterface = static_cast<ICorDebugThread3*>(this);
}
else if (id == IID_ICorDebugThread4)
{
*ppInterface = static_cast<ICorDebugThread4*>(this);
}
else if (id == IID_ICorDebugThread5)
{
*ppInterface = static_cast<ICorDebugThread5*>(this);
}
else if (id == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown *>(static_cast<ICorDebugThread *>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
#ifdef _DEBUG
// Callback helper for code:CordbThread::DbgAssertThreadDeleted
//
// Arguments:
// vmThread - thread from enumeration of threads in the target.
// pUserData - the CordbThread for the thread that's deleted
//
// static
void CordbThread::DbgAssertThreadDeletedCallback(VMPTR_Thread vmThread, void * pUserData)
{
CordbThread * pThis = reinterpret_cast<CordbThread *>(pUserData);
INTERNAL_DAC_CALLBACK(pThis->GetProcess());
VMPTR_Thread vmThreadDelete = pThis->m_vmThreadToken;
CONSISTENCY_CHECK_MSGF((vmThread != vmThreadDelete),
("A Thread Exit event was sent, but it still shows up in the enumeration.\n vmThreadDelete=%p\n",
VmPtrToCookie(vmThreadDelete)));
}
// Debug-only helper to Assert that this thread is no longer discoverable in DacDbi enumerations
// This is designed to enforce the code:IDacDbiInterface#Enumeration rules for enumerations.
void CordbThread::DbgAssertThreadDeleted()
{
// Enumerate through all threads and ensure the deleted threads don't show up.
GetProcess()->GetDAC()->EnumerateThreads(
DbgAssertThreadDeletedCallback,
this);
}
#endif // _DEBUG
//---------------------------------------------------------------------------------------
// Mark that this thread has an unhandled native exception on it.
//
// Arguments
// pRecord - exception record of 2nd-chance exception that we're hijacking at. This will
// get deep copied into the CordbThread object in case it's needed for hijacking later.
//
// Notes:
// This bit is cleared in code:CordbThread::HijackForUnhandledException
void CordbThread::SetUnhandledNativeException(const EXCEPTION_RECORD * pExceptionRecord)
{
m_fHasUnhandledException = true;
if (m_pExceptionRecord == NULL)
{
m_pExceptionRecord = new EXCEPTION_RECORD(); // throws
}
memcpy(m_pExceptionRecord, pExceptionRecord, sizeof(EXCEPTION_RECORD));
}
//-----------------------------------------------------------------------------
// Returns true if the thread has an unhandled exception
// This is during the window after code:CordbThread::SetUnhandledNativeException is called,
// but before code:CordbThread::HijackForUnhandledException
bool CordbThread::HasUnhandledNativeException()
{
return m_fHasUnhandledException;
}
//---------------------------------------------------------------------------------------
// Determine if the thread's latest exception is a managed exception
//
// Notes:
// The CLR's UnhandledExceptionFilter has to make this same determination.
//
BOOL CordbThread::IsThreadExceptionManaged()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// A Thread's latest exception is managed if the VM Thread object has a managed object
// for the thread's Current Exception property. The CLR's Exception system is very diligent
// about tracking and clearing the thread's managed exception property. The runtime will clear
// the object if the exception is caught by unmanaged code (it can do this in the 2nd-pass).
// It's the presence of a throwable that makes the difference between a managed
// exception event and an unmanaged exception event.
VMPTR_OBJECTHANDLE vmObject = GetProcess()->GetDAC()->GetCurrentException(m_vmThreadToken);
bool fHasThrowable = !vmObject.IsNull();
return fHasThrowable;
}
// ----------------------------------------------------------------------------
// CordbThread::CreateCordbRegisterSet
//
// Description:
// This is a private hook for the shim to create a CordbRegisterSet for a ShimChain.
//
// Arguments:
// * pContext - the CONTEXT to be converted; this must be the leaf CONTEXT of a chain
// * fLeaf - whether the chain is the leaf chain or not
// * reason - the chain reason; this is needed for legacy reasons (see below)
// * ppRegSet - out parameter; return the newly created ICDRegisterSet
//
// Notes:
// * Note that the fQuickUnwind argument of the ctor of CordbRegisterSet is only true
// for an enter-managed chain. We need to keep the same behaviour here. That's why we need the
// chain reason.
//
void CordbThread::CreateCordbRegisterSet(DT_CONTEXT * pContext,
BOOL fLeaf,
CorDebugChainReason reason,
ICorDebugRegisterSet ** ppRegSet)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(GetProcess());
IfFailThrow(EnsureThreadIsAlive());
// The CordbRegisterSet is responsible for freeing this memory.
NewHolder<DebuggerREGDISPLAY> pDRD(new DebuggerREGDISPLAY());
// convert the CONTEXT to a DebuggerREGDISPLAY
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->ConvertContextToDebuggerRegDisplay(pContext, pDRD, fLeaf);
// create the CordbRegisterSet
RSInitHolder<CordbRegisterSet> pRS(new CordbRegisterSet(pDRD,
this,
(fLeaf == TRUE),
(reason == CHAIN_ENTER_MANAGED),
true));
pDRD.SuppressRelease();
pRS.TransferOwnershipExternal(ppRegSet);
}
// ----------------------------------------------------------------------------
// CordbThread::ConvertFrameForILMethodWithoutMetadata
//
// Description:
// This is a private hook for the shim to convert an ICDFrame into an ICDInternalFrame for a dynamic
// method. There are two cases where we need this:
// 1) In Arrowhead, dynamic methods are exposed as first-class stack frames, not internal frames. Thus,
// the shim needs a way to convert an ICDNativeFrame for a dynamic method in Arrowhead to an
// ICDInternalFrame of type STUBFRAME_LIGHTWEIGHT_FUNCTION in V2. Furthermore, IL stubs,
// which are also considered as a type of dynamic methods, are not exposed in V2 at all.
//
// 2) In V2, PrestubMethodFrames (PMFs) can be exposed as one of two things: a chain of type
// CHAIN_CLASS_INIT in most cases, or an internal frame of type STUBFRAME_LIGHTWEIGHT_FUNCTION if
// the method being jitted is a dynamic method. There is no way to make this distinction at the
// public ICD level.
//
// Arguments:
// * pNativeFrame - the native frame to be converted
// * ppInternalFrame - out parameter; the converted internal frame; could be NULL (see Notes below)
//
// Returns:
// Return TRUE if conversion has occurred. Note that even if the return value is TRUE, ppInternalFrame
// could be NULL. See Notes below.
//
// Notes:
// * There are two main types of dynamic methods: ones which are generated by the runtime itself for
// internal purposes (i.e. IL stubs), and ones which are generated by the user. ppInternalFrame
// is NULL for IL stubs. We need this functionality because IL stubs are not exposed at all in V2.
//
BOOL CordbThread::ConvertFrameForILMethodWithoutMetadata(ICorDebugFrame * pFrame,
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
PUBLIC_REENTRANT_API_ENTRY_FOR_SHIM(GetProcess());
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
HRESULT hr = E_FAIL;
CordbFrame * pRealFrame = CordbFrame::GetCordbFrameFromInterface(pFrame);
CordbInternalFrame * pInternalFrame = pRealFrame->GetAsInternalFrame();
if (pInternalFrame != NULL)
{
// The input is an internal frame.
// Check its frame type.
CorDebugInternalFrameType type;
hr = pInternalFrame->GetFrameType(&type);
IfFailThrow(hr);
if (type != STUBFRAME_JIT_COMPILATION)
{
// No conversion is necessary.
return FALSE;
}
else
{
// We are indeed dealing with a PrestubMethodFrame.
return pInternalFrame->ConvertInternalFrameForILMethodWithoutMetadata(ppInternalFrame2);
}
}
else
{
// The input is a native frame.
CordbNativeFrame * pNativeFrame = pRealFrame->GetAsNativeFrame();
_ASSERTE(pNativeFrame != NULL);
return pNativeFrame->ConvertNativeFrameForILMethodWithoutMetadata(ppInternalFrame2);
}
}
//-----------------------------------------------------------------------------
// Hijack a thread at an unhandled exception. This lets it execute the
// CLR's Unhandled Exception Filter (which will send the managed 2nd-chance exception event)
//
// Notes:
// OS will not execute Unhandled Exception Filter (UEF) when debugger is attached.
// The CLR's UEF does useful work, like dispatching 2nd-chance managed exception event
// and allowing Func-eval and Continuable Exceptions for unhandled exceptions.
// So hijack the thread, and the hijack will then execute the CLR's UEF just
// like the OS would.
void CordbThread::HijackForUnhandledException()
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
_ASSERTE(m_pExceptionRecord != NULL);
_ASSERTE(m_fHasUnhandledException);
m_fHasUnhandledException = false;
ULONG32 dwThreadId = GetVolatileOSThreadID();
// Note that the data-target is not atomic, and we have no rollback mechanism.
// We have to do several writes. If the data-target fails the writes half-way through the
// target will be inconsistent.
// We don't bother remembering the original context. LS hijack will have the
// context on its stack and will pass it to RS just like it does for filter-context.
GetProcess()->GetDAC()->Hijack(
m_vmThreadToken,
dwThreadId,
m_pExceptionRecord,
NULL, // LS will have the context.
0, // size of context
EHijackReason::kUnhandledException,
NULL,
NULL);
// Notify debugger to clear the exception.
// This will invoke the data-target.
GetProcess()->ContinueStatusChanged(dwThreadId, DBG_CONTINUE);
}
HRESULT CordbThread::GetProcess(ICorDebugProcess ** ppProcess)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppProcess, ICorDebugProcess **);
FAIL_IF_NEUTERED(this);
*ppProcess = GetProcess();
GetProcess()->ExternalAddRef();
return S_OK;
}
// Public implementation of ICorDebugThread::GetID
// Back in V1.0, GetID originally meant the OS thread ID that this managed thread was running on.
// In theory, that can change (fibers, logical thread scheduling, etc). However, in practice, in V1.0, it would
// not. Thus debuggers took a depedency on GetID being constant.
// In V2, this returns an opaque handle that is unique to this thread and stable for this thread's lifetime.
//
// Compare to code:CordbThread::GetVolatileOSThreadID, which returns the actual OS thread Id (which may change).
HRESULT CordbThread::GetID(DWORD * pdwThreadId)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(pdwThreadId, DWORD *);
FAIL_IF_NEUTERED(this);
*pdwThreadId = GetUniqueId();
return S_OK;
}
// Returns a unique ID that's stable for the life of this thread.
// In a non-hosted scenarios, this can be the OS thread id.
DWORD CordbThread::GetUniqueId()
{
return m_dwUniqueID;
}
// Implementation of public API, ICorDebugThread::GetHandle
// @dbgtodo ICDThread - deprecate in V3, offload to Shim
HRESULT CordbThread::GetHandle(HANDLE * phThreadHandle)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(phThreadHandle, HANDLE *);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (GetProcess()->GetShim() == NULL)
{
_ASSERTE(!"CordbThread::GetHandle() should be not be called on the new architecture");
*phThreadHandle = NULL;
return E_NOTIMPL;
}
#if !defined(FEATURE_DBGIPC_TRANSPORT_DI)
HRESULT hr = S_OK;
EX_TRY
{
HANDLE hThread;
InternalGetHandle(&hThread); // throws on error
*phThreadHandle = hThread;
}
EX_CATCH_HRESULT(hr);
#else // FEATURE_DBGIPC_TRANSPORT_DI
// In the old SL implementation of Mac debugging, we return a thread handle faked up by the PAL on the Mac.
// The returned handle is meaningless. Here we explicitly return E_NOTIMPL. We plan to deprecate this
// function in Dev10 anyway.
//
// @dbgtodo Mac - Check with VS to see if they need the thread handle, e.g. for waiting on thread
// termination.
HRESULT hr = E_NOTIMPL;
#endif // !FEATURE_DBGIPC_TRANSPORT_DI
return hr;
}
// Note that we can return invalid handle
void CordbThread::InternalGetHandle(HANDLE * phThread)
{
INTERNAL_SYNC_API_ENTRY(GetProcess());
RefreshHandle(phThread);
}
//---------------------------------------------------------------------------------------
//
// This is a simple helper to check if a frame lives on the stack of the current thread.
//
// Arguments:
// pFrame - the stack frame to check
//
// Return Value:
// whether the frame lives on the stack of the current thread
//
// Assumption:
// This function assumes that the stack frames are valid, i.e. the stack frames have not been
// made dirty since the last stackwalk.
//
bool CordbThread::OwnsFrame(CordbFrame * pFrame)
{
// preliminary checking
if ( (pFrame != NULL) &&
(!pFrame->IsNeutered()) &&
(pFrame->m_pThread == this)
)
{
//
// Note that this is one of the two remaining places where we need to use the cached stack frames.
// Theoretically, since this is not an exact check anyway, we could just use the thread's stack
// range instead of looping through all the individual frames. However, since we need to maintain
// the stack frame cache for code:CordbThread::GetActiveFunctions, we might as well use the cache here.
//
// make sure this thread actually have frames to check
if (m_stackFrames.Count() != 0)
{
// get the stack range of this thread
FramePointer fpLeaf = (*(m_stackFrames.Get(0)))->GetFramePointer();
FramePointer fpRoot = (*(m_stackFrames.Get(m_stackFrames.Count() - 1)))->GetFramePointer();
FramePointer fpCurrent = pFrame->GetFramePointer();
// compare the stack range against the frame pointer of the specified frame
if (IsEqualOrCloserToLeaf(fpLeaf, fpCurrent) && IsEqualOrCloserToRoot(fpRoot, fpCurrent))
{
return true;
}
}
}
return false;
}
//---------------------------------------------------------------------------------------
//
// This routine is a internal helper function for ICorDebugThread2::GetTaskId.
//
// Arguments:
// pHandle - return thread handle here after fetching from the left side.
//
// Return Value:
// hr - It can fail with CORDBG_E_THREAD_NOT_SCHEDULED.
//
// Notes:
// This method will most likely be deprecated in V3.0. We can't always return the thread handle.
// For example, what does it mean to return a thread handle in remote debugging scenarios?
//
void CordbThread::RefreshHandle(HANDLE * phThread)
{
// here is where we will put code in to fetch the thread handle from the left side.
// This should only happen when CLRTask is hosted.
// Make sure that we are setting the right HR when thread is being switched out.
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
if (phThread == NULL)
{
ThrowHR(E_INVALIDARG);
}
*phThread = INVALID_HANDLE_VALUE;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
HANDLE hThread = pDAC->GetThreadHandle(m_vmThreadToken);
_ASSERTE(hThread != INVALID_HANDLE_VALUE);
PREFAST_ASSUME(hThread != NULL);
// need to dup handle here
if (hThread == m_hCachedOutOfProcThread)
{
*phThread = m_hCachedThread;
}
else
{
BOOL fSuccess = TRUE;
if (m_hCachedThread != INVALID_HANDLE_VALUE)
{
// clear the previous cache
CloseHandle(m_hCachedThread);
m_hCachedOutOfProcThread = INVALID_HANDLE_VALUE;
m_hCachedThread = INVALID_HANDLE_VALUE;
}
// now duplicate the out-of-proc handle
fSuccess = DuplicateHandle(GetProcess()->UnsafeGetProcessHandle(),
hThread,
GetCurrentProcess(),
&m_hCachedThread,
NULL,
FALSE,
DUPLICATE_SAME_ACCESS);
*phThread = m_hCachedThread;
if (fSuccess)
{
m_hCachedOutOfProcThread = hThread;
}
else
{
ThrowLastError();
}
}
} // CordbThread::RefreshHandle
//---------------------------------------------------------------------------------------
//
// This routine sets the debug state of a thread.
//
// Arguments:
// state - The debug state to set to.
//
// Return Value:
// Normal HRESULT semantics.
//
HRESULT CordbThread::SetDebugState(CorDebugThreadState state)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
LOG((LF_CORDB, LL_INFO1000, "CT::SDS: thread=0x%08x 0x%x, state=%d\n", this, m_id, state));
// @dbgtodo- , sync - decide on how to suspend a thread. V2 leverages synchronization
// (see below). For V3, do we just hard suspend the thread?
if (GetProcess()->GetShim() == NULL)
{
return E_NOTIMPL;
}
HRESULT hr = S_OK;
EX_TRY
{
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
// This lets the debugger suspend / resume threads. This is only called when when the
// target is already synchronized. That means all the threads are already suspended. So
// setting the suspend bit here just means that the debugger's continue logic won't resume
// this thread when we do a Continue.
if ((state != THREAD_SUSPEND) && (state != THREAD_RUN))
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->SetDebugState(m_vmThreadToken, state);
m_debugState = state;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::GetDebugState(CorDebugThreadState * pState)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(pState, CorDebugThreadState *);
*pState = m_debugState;
return S_OK;
}
// Public implementation of ICorDebugThread::GetUserState
// Arguments:
// pState - out parameter; return the user state
//
// Return Value:
// Return S_OK if the operation is successful.
// Return E_INVALIDARG if the out parameter is NULL.
// Return other failure HRs returned by the call to the DDI.
HRESULT CordbThread::GetUserState(CorDebugUserState * pState)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pState, CorDebugUserState *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (pState == NULL)
{
ThrowHR(E_INVALIDARG);
}
*pState = GetUserState();
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Retrieve the user state of the current thread.
//
// Notes:
// This caches results between continues. The cache is cleared when the target continues or is flushed.
// See code:CordbThread::CleanupStack, code:CordbThread::MarkStackFramesDirty
//
CorDebugUserState CordbThread::GetUserState()
{
if (m_userState == kInvalidUserState)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_userState = pDAC->GetUserState(m_vmThreadToken);
}
return m_userState;
}
//---------------------------------------------------------------------------------------
//
// This routine finds and returns the current exception off of a thread.
//
// Arguments:
// ppExceptionObject - OUT: Space for storing the exception found on the thread as a value.
//
// Return Value:
// Normal HRESULT semantics.
//
HRESULT CordbThread::GetCurrentException(ICorDebugValue ** ppExceptionObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppExceptionObject, ICorDebugValue **);
*ppExceptionObject = NULL;
EX_TRY
{
if (!HasException())
{
//
// Go to the LS and retrieve any exception object.
//
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetCurrentException(m_vmThreadToken);
if (vmObjHandle.IsNull())
{
hr = S_FALSE;
}
else
{
#if defined(_DEBUG)
// Since we know an exception is in progress on this thread, our assumption about the
// thread's current AppDomain should be correct
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
_ASSERTE(GetAppDomain()->GetADToken() == vmAppDomain);
#endif // _DEBUG
m_vmExcepObjHandle = vmObjHandle;
}
}
if (hr == S_OK)
{
// We've believe this assert may fire in the wild.
// We've seen m_vmExcepObjHandle null in retail builds after stack overflow.
_ASSERTE(!m_vmExcepObjHandle.IsNull());
ICorDebugReferenceValue * pRefValue = NULL;
hr = CordbReferenceValue::BuildFromGCHandle(GetAppDomain(), m_vmExcepObjHandle, &pRefValue);
*ppExceptionObject = pRefValue;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::ClearCurrentException()
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// This API is not implemented. For Continuable Exceptions, see InterceptCurrentException.
// @todo - should it return E_NOTIMPL?
return S_OK;
}
HRESULT CordbThread::CreateStepper(ICorDebugStepper ** ppStepper)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStepper, ICorDebugStepper **);
CordbStepper * pStepper = new (nothrow) CordbStepper(this, NULL);
if (pStepper == NULL)
{
return E_OUTOFMEMORY;
}
pStepper->ExternalAddRef();
*ppStepper = pStepper;
return S_OK;
}
//Returns true if current user state of a thread is USER_WAIT_SLEEP_JOIN
bool CordbThread::IsThreadWaitingOrSleeping()
{
CorDebugUserState userState = m_userState;
if (userState == kInvalidUserState)
{
//If m_userState is not ready, we'll read from DAC only part of it which
//is important for us now, bacuase we don't want possible side effects
//of reading USER_UNSAFE_POINT flag.
//We don't cache the value, because it's potentially incomplete.
IDacDbiInterface *pDAC = GetProcess()->GetDAC();
userState = pDAC->GetPartialUserState(m_vmThreadToken);
}
return (userState & USER_WAIT_SLEEP_JOIN) != 0;
}
//----------------------------------------------------------------------------
// check if the thread is dead
//
// Returns: true if the thread is dead.
//
bool CordbThread::IsThreadDead()
{
return GetProcess()->GetDAC()->IsThreadMarkedDead(m_vmThreadToken);
}
// Helper to return CORDBG_E_BAD_THREAD_STATE if IsThreadDead
//
// Notes:
// IsThreadDead queries the VM Thread's actual state, regardless of what ExitThread
// callbacks have or have not been sent / queued / dispatched.
HRESULT CordbThread::EnsureThreadIsAlive()
{
if (IsThreadDead())
{
return CORDBG_E_BAD_THREAD_STATE;
}
else
{
return S_OK;
}
}
// ----------------------------------------------------------------------------
// CordbThread::EnumerateChains
//
// Description:
// Create and return an ICDChainEnum for enumerating chains on the stack. Since chains have been
// deprecated in Arrowhead, this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChains - out parameter; return the ICDChainEnum
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChains is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbThread::EnumerateChains(ICorDebugChainEnum ** ppChains)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChains, ICorDebugChainEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppChains = NULL;
if (GetProcess()->GetShim() != NULL)
{
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
// use the shim to create an ICDChainEnum
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSW->EnumerateChains(ppChains);
}
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveChain
//
// Description:
// Retrieve the leaf chain on this thread. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the leaf chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbThread::GetActiveChain(ICorDebugChain ** ppChain)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChain, ICorDebugChain **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppChain = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
// use the shim to retrieve the leaf chain
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveChain(ppChain);
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveFrame
//
// Description:
// Retrieve the leaf frame on this thread. Unfortunately, this is one of the cases where we need to
// do different things depending on whether there is a shim. See the Notes below.
//
// Arguments:
// * ppFrame - out parameter; return the leaf frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Also return whatever CreateStackWalk() and GetFrame() return if they fail.
//
// Notes:
// In V2, we return NULL if the leaf frame is not in the leaf chain, i.e. if the leaf chain is
// empty. Note that managed chains are never empty. Also, in V2 it is possible that this API
// will return an internal frame as the active frame on a thread.
//
// The Arrowhead implementation two breaking changes:
// 1) It never returns an internal frame.
// 2) We return a frame if the leaf frame is managed. Otherwise, we return NULL.
//
HRESULT CordbThread::GetActiveFrame(ICorDebugFrame ** ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppFrame = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveFrame(ppFrame);
}
else
{
// This is the Arrowhead case. We could call RefreshStack() here, but since we only need the
// leaf frame, there is no point in walking the entire stack.
RSExtSmartPtr<ICorDebugStackWalk> pSW;
hr = CreateStackWalk(&pSW);
IfFailThrow(hr);
hr = pSW->GetFrame(ppFrame);
IfFailThrow(hr);
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbThread::GetActiveRegister
//
// Description:
// In V2, retrieve the ICDRegisterSet for the leaf chain. In Arrowhead, retrieve the ICDRegisterSet
// for the leaf CONTEXT.
//
// Arguments:
// * ppRegisters - out parameter; return the ICDRegister
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbThread is neutered.
// Also return whatever CreateStackWalk() and GetContext() return if they fail.
//
HRESULT CordbThread::GetRegisterSet(ICorDebugRegisterSet ** ppRegisters)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppRegisters, ICorDebugRegisterSet **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
*ppRegisters = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
if (GetProcess()->GetShim() != NULL)
{
// use the shim to retrieve the active ICDRegisterSet
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
pSSW->GetActiveRegisterSet(ppRegisters);
}
else
{
// This is the Arrowhead case. We could call RefreshStack() here, but since we only need the
// leaf frame, there is no point in walking the entire stack.
RSExtSmartPtr<ICorDebugStackWalk> pSW;
hr = CreateStackWalk(&pSW);
IfFailThrow(hr);
// retrieve the leaf CONTEXT
DT_CONTEXT ctx;
hr = pSW->GetContext(CONTEXT_FULL, sizeof(ctx), NULL, reinterpret_cast<BYTE *>(&ctx));
IfFailThrow(hr);
// the CordbRegisterSet is responsible for freeing this memory
NewHolder<DebuggerREGDISPLAY> pDRD(new DebuggerREGDISPLAY());
// convert the CONTEXT to a DebuggerREGDISPLAY
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->ConvertContextToDebuggerRegDisplay(&ctx, pDRD, true);
// create the CordbRegisterSet
RSInitHolder<CordbRegisterSet> pRS(new CordbRegisterSet(pDRD,
this,
true, // active
false, // !fQuickUnwind
true)); // own DRD memory
pDRD.SuppressRelease();
pRS.TransferOwnershipExternal(ppRegisters);
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbThread::CreateEval(ICorDebugEval ** ppEval)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppEval, ICorDebugEval **);
CordbEval * pEval = new (nothrow) CordbEval(this);
if (pEval == NULL)
{
return E_OUTOFMEMORY;
}
pEval->ExternalAddRef();
*ppEval = static_cast<ICorDebugEval *>(pEval);
return S_OK;
}
// DAC check
// Double check our results w/ DAC.
// This gives DAC some great coverage.
// Given an IP and the md token (that the RS obtained), use DAC to lookup the md token. Then
// we can compare DAC & the RS and make sure DACs working.
void CheckAgainstDAC(CordbFunction * pFunc, void * pIP, mdMethodDef mdExpected)
{
// This is a hook to add DAC checks against a {function, ip}
}
//---------------------------------------------------------------------------------------
//
// Internal function to build up a stack trace.
//
//
// Return Value:
// S_OK on success.
//
// Assumptions:
// Process is stopped.
//
// Notes:
// Send a IPC events to the LS to build up the stack.
//
//---------------------------------------------------------------------------------------
void CordbThread::RefreshStack()
{
THROW_IF_NEUTERED(this);
// We must have the Stop-Go lock to change our thread's stack-state.
// Also, our caller should have guaranteed that we're synced. And b/c we hold the stop-go lock,
// that shouldn't have changed.
// INTERNAL_SYNC_API_ENTRY() checks that we have the lock and that we are synced.
INTERNAL_SYNC_API_ENTRY(GetProcess());
// bail out early if the stack hasn't changed
if (m_fFramesFresh)
{
return;
}
HRESULT hr = S_OK;
//
// Clean up old snapshot.
//
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// clear the stack frame cache
ClearStackFrameCache();
//
// If we don't have a debugger thread token, then this thread has never
// executed managed code and we have no frame information for it.
//
if (m_vmThreadToken.IsNull())
{
ThrowHR(E_FAIL);
}
// walk the stack using the V3 API and populate the stack frame cache
RSInitHolder<CordbStackWalk> pSW(new CordbStackWalk(this));
pSW->Init();
do
{
RSExtSmartPtr<ICorDebugFrame> pIFrame;
hr = pSW->GetFrame(&pIFrame);
IfFailThrow(hr);
if (pIFrame != NULL)
{
// add the stack frame to the cache
CordbFrame ** ppCFrame = m_stackFrames.AppendThrowing();
*ppCFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
// Now that we have saved the pointer, increment the ref count.
// This has to match the InternalRelease() in code:CordbThread::ClearStackFrameCache.
(*ppCFrame)->InternalAddRef();
}
// advance to the next frame
hr = pSW->Next();
IfFailThrow(hr);
}
while (hr != CORDBG_S_AT_END_OF_STACK);
m_fFramesFresh = true;
}
//---------------------------------------------------------------------------------------
//
// This function is used to invalidate and clean up the cached stack trace.
//
void CordbThread::CleanupStack()
{
_ASSERTE(GetProcess()->GetProcessLock()->HasLock());
// Neuter outstanding CordbChainEnums, CordbFrameEnums, some CordbTypeEnums, and some CordbValueEnums.
m_RefreshStackNeuterList.NeuterAndClear(GetProcess());
m_fContextFresh = false; // invalidate the cached active CONTEXT
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr(); // set the LS pointer to the active CONTEXT to NULL
m_fFramesFresh = false; // invalidate the cached stack trace (frames & chains)
m_userState = kInvalidUserState; // clear the cached user state
// tell the shim to flush its caches as well
if (GetProcess()->GetShim() != NULL)
{
GetProcess()->GetShim()->NotifyOnStackInvalidate();
}
}
// Notifying the thread that the process is being continued.
// This will cause our caches to get invalidated without actually cleaning the caches.
void CordbThread::MarkStackFramesDirty()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// invalidate the cached floating point state
m_fFloatStateValid = false;
// This flag is only true between the window when we get an exception callback and
// when we call continue. Since this function is only called when we continue, we
// need to reset this flag here. Note that in the case of an outstanding funceval,
// we'll set this flag again when the funceval is completed.
m_fException = false;
// Clear the stashed EnC remap IP address if any
// This is important to ensure we don't try to write into LS memory which is no longer
// being used to hold the remap IP.
m_EnCRemapFunctionIP = NULL;
m_fContextFresh = false; // invalidate the cached active CONTEXT
m_vmLeftSideContext = VMPTR_CONTEXT::NullPtr(); // set the LS pointer to the active CONTEXT to NULL
m_fFramesFresh = false; // invalidate the cached stack trace (frames & chains)
m_userState = kInvalidUserState; // clear the cached user state
m_RefreshStackNeuterList.NeuterAndClear(GetProcess());
// tell the shim to flush its caches as well
if (GetProcess()->GetShim() != NULL)
{
GetProcess()->GetShim()->NotifyOnStackInvalidate();
}
}
// Set that there's an outstanding exception on this thread.
// This can be called when the process object receives an exception notification.
// This is cleared in code:CordbThread::MarkStackFramesDirty.
void CordbThread::SetExInfo(VMPTR_OBJECTHANDLE vmExcepObjHandle)
{
m_fException = true;
m_vmExcepObjHandle = vmExcepObjHandle;
// CordbThread::GetCurrentException assumes that we always have a m_vmExcepObjHandle when at an exception.
// Push that assert up here.
_ASSERTE(!m_vmExcepObjHandle.IsNull());
}
// ----------------------------------------------------------------------------
// CordbThread::FindFrame
//
// Description:
// Given a FramePointer, find the matching CordbFrame.
//
// Arguments:
// * ppFrame - out parameter; the CordbFrame to be returned
// * fp - the input FramePointer
//
// Return Value:
// Return S_OK on success.
// Return E_FAIL on failure.
//
// Assumptions:
// * This function is only called from the shim.
//
// Notes:
// * Currently this function is only used by the shim to map the FramePointer it gets via the
// DB_IPCE_EXCEPTION_CALLBACK2 callback. When we figure out what to do with the
// DB_IPCE_EXCEPTION_CALLBACK2, we should remove this function.
//
HRESULT CordbThread::FindFrame(ICorDebugFrame ** ppFrame, FramePointer fp)
{
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
_ASSERTE(ppFrame != NULL);
*ppFrame = NULL;
_ASSERTE(GetProcess()->GetShim() != NULL);
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
for (UINT32 i = 0; i < pSSW->GetFrameCount(); i++)
{
ICorDebugFrame * pIFrame = pSSW->GetFrame(i);
CordbFrame * pCFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
#if defined(HOST_64BIT)
// On 64-bit we can simply compare the FramePointer.
if (pCFrame->GetFramePointer() == fp)
#else // !HOST_64BIT
// On other platforms, we need to do a more elaborate check.
if (pCFrame->IsContainedInFrame(fp))
#endif // HOST_64BIT
{
*ppFrame = pIFrame;
(*ppFrame)->AddRef();
return S_OK;
}
}
// Cannot find the frame.
return E_FAIL;
}
#if defined(CROSS_COMPILE) && (defined(TARGET_ARM64) || defined(TARGET_ARM))
extern "C" double FPFillR8(void* pFillSlot)
{
_ASSERTE(!"nyi for platform");
return 0;
}
#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_ARM)
extern "C" double FPFillR8(void* pFillSlot);
#endif
#if defined(TARGET_X86)
// CordbThread::Get32bitFPRegisters
// Converts the values in the floating point register area of the context to real number values. See
// code:CordbThread::LoadFloatState for more details.
// Arguments:
// input: pContext
// output: none (initializes m_floatValues)
void CordbThread::Get32bitFPRegisters(CONTEXT * pContext)
{
// On X86, we get the values by saving our current FPU state, loading
// the other thread's FPU state into our own, saving out each
// value off the FPU stack, and then restoring our FPU state.
//
FLOATING_SAVE_AREA floatarea = pContext->FloatSave; // copy FloatSave
//
// Take the TOP out of the FPU status word. Note, our version of the
// stack runs from 0->7, not 7->0...
//
unsigned int floatStackTop = 7 - ((floatarea.StatusWord & 0x3800) >> 11);
FLOATING_SAVE_AREA currentFPUState;
#ifdef _MSC_VER
__asm fnsave currentFPUState // save the current FPU state.
#else
__asm__ __volatile__
(
" fnsave %0\n" \
: "=m"(currentFPUState)
);
#endif
floatarea.StatusWord &= 0xFF00; // remove any error codes.
floatarea.ControlWord |= 0x3F; // mask all exceptions.
// the x86 FPU stores real numbers as 10 byte values in IEEE format. Here we use
// the hardware to convert these to doubles.
// @dbgtodo Microsoft crossplat: the conversion from a series of bytes to a floating
// point value will need to be done with an explicit conversion routine to unpack
// the IEEE format and compute the real number value represented.
#ifdef _MSC_VER
__asm
{
fninit
frstor floatarea ;; reload the threads FPU state.
}
#else
__asm__
(
" fninit\n" \
" frstor %0\n" \
: /* no outputs */
: "m"(floatarea)
);
#endif
unsigned int i;
for (i = 0; i <= floatStackTop; i++)
{
double td = 0.0;
__asm fstp td // copy out the double
m_floatValues[i] = td;
}
#ifdef _MSC_VER
__asm
{
fninit
frstor currentFPUState ;; restore our saved FPU state.
}
#else
__asm__
(
" fninit\n" \
" frstor %0\n" \
: /* no outputs */
: "m"(currentFPUState)
);
#endif
m_fFloatStateValid = true;
m_floatStackTop = floatStackTop;
} // CordbThread::Get32bitFPRegisters
#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_ARM)
// CordbThread::Get64bitFPRegisters
// Converts the values in the floating point register area of the context to real number values. See
// code:CordbThread::LoadFloatState for more details.
// Arguments:
// input: pFPRegisterBase - starting address of the floating point register storage of the CONTEXT
// registerSize - the size of a floating point register
// start - the index into m_floatValues where we start initializing. For amd64, we start
// at the beginning, but for ia64, the first two registers have fixed values,
// so we start at two.
// nRegisters - the number of registers to be initialized
// output: none (initializes m_floatValues)
void CordbThread::Get64bitFPRegisters(FPRegister64 * rgContextFPRegisters, int start, int nRegisters)
{
// make sure no one has changed the type definition for 64-bit FP registers
_ASSERTE(sizeof(FPRegister64) == 16);
// We convert and copy all the fp registers.
for (int reg = start; reg < nRegisters; reg++)
{
// @dbgtodo Microsoft crossplat: the conversion from a FLOAT128 or M128A struct to a floating
// point value will need to be done with an explicit conversion routine instead
// of the call to FPFillR8
m_floatValues[reg] = FPFillR8(&rgContextFPRegisters[reg - start]);
}
} // CordbThread::Get64bitFPRegisters
#endif // TARGET_X86
// CordbThread::LoadFloatState
// Initializes the float state members of this instance of CordbThread. This function gets the context and
// converts the floating point values from their context representation to a real number value. Floating
// point numbers are represented in IEEE format on all current platforms. We store them in the context as a
// pair of 64-bit integers (IA64 and AMD64) or a series of bytes (x86). Rather than unpack them explicitly
// and do the appropriate mathematical operations to produce the corresponding floating point value, we let
// the hardware do it instead. We load a floating point register with the representation from the context
// and then store it in m_floatValues. Using the hardware is obviously a huge perf win. If/when we make
// cross-plat work, we should at least code necessary conversion routines in assembly. Even with cross-plat,
// we can probably still use the hardware in most cases, as long as the size is appropriate.
//
// Arguments: none
// Return Value: none (initializes data members)
// Note: Throws
void CordbThread::LoadFloatState()
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
DT_CONTEXT tempContext;
GetProcess()->GetDAC()->GetContext(m_vmThreadToken, &tempContext);
#if defined(TARGET_X86)
Get32bitFPRegisters((CONTEXT*) &tempContext);
#elif defined(TARGET_AMD64)
// we have no fixed-value registers, so we begin with the first one and initialize all 16
Get64bitFPRegisters((FPRegister64*) &(tempContext.Xmm0), 0, 16);
#elif defined(TARGET_ARM64)
Get64bitFPRegisters((FPRegister64*) &(tempContext.V), 0, 32);
#elif defined (TARGET_ARM)
Get64bitFPRegisters((FPRegister64*) &(tempContext.D), 0, 32);
#else
_ASSERTE(!"nyi for platform");
#endif // !TARGET_X86
m_fFloatStateValid = true;
} // CordbThread::LoadFloatState
const bool SetIP_fCanSetIPOnly = TRUE;
const bool SetIP_fSetIP = FALSE;
const bool SetIP_fIL = TRUE;
const bool SetIP_fNative = FALSE;
//---------------------------------------------------------------------------------------
//
// Issues a SetIP command to the left-side and returns the result
//
// Arguments:
// fCanSetIPOnly - TRUE if only to do the setip command and not refresh stacks as well.
// debuggerModule - LS token to the debugger module.
// mdMethod - Metadata token for the method.
// nativeCodeJITInfoToken - LS token to the DebuggerJitInfo for the method.
// offset - Offset within the method to set the IP to.
// fIsIl - Is this an IL offset?
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::SetIP(bool fCanSetIPOnly,
CordbNativeCode * pNativeCode,
SIZE_T offset,
bool fIsIL)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VMPTR_DomainAssembly vmDomainAssembly = pNativeCode->GetModule()->m_vmDomainAssembly;
_ASSERTE(!vmDomainAssembly.IsNull());
// If this thread is stopped due to an exception, never allow SetIP
if (HasException())
{
return (CORDBG_E_SET_IP_NOT_ALLOWED_ON_EXCEPTION);
}
DebuggerIPCEvent event;
GetProcess()->InitIPCEvent(&event, DB_IPCE_SET_IP, true, GetAppDomain()->GetADToken());
event.SetIP.fCanSetIPOnly = fCanSetIPOnly;
event.SetIP.vmThreadToken = m_vmThreadToken;
event.SetIP.vmDomainAssembly = vmDomainAssembly;
event.SetIP.mdMethod = pNativeCode->GetMetadataToken();
event.SetIP.vmMethodDesc = pNativeCode->GetVMNativeCodeMethodDescToken();
event.SetIP.startAddress = pNativeCode->GetAddress();
event.SetIP.offset = offset;
event.SetIP.fIsIL = fIsIL;
LOG((LF_CORDB, LL_INFO10000, "[%x] CT::SIP: Info:thread:0x%x"
"mod:0x%x MethodDef:0x%x offset:0x%x il?:0x%x\n",
GetCurrentThreadId(),
VmPtrToCookie(m_vmThreadToken),
VmPtrToCookie(vmDomainAssembly),
pNativeCode->GetMetadataToken(),
offset,
fIsIL));
LOG((LF_CORDB, LL_INFO10000, "[%x] CT::SIP: sizeof(DebuggerIPCEvent):0x%x **********\n",
sizeof(DebuggerIPCEvent)));
HRESULT hr = GetProcess()->m_cordb->SendIPCEvent(GetProcess(), &event, sizeof(DebuggerIPCEvent));
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_SET_IP);
if (!fCanSetIPOnly && SUCCEEDED(event.hr))
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
CleanupStack();
}
return ErrWrapper(event.hr);
}
// Get the context from a thread in managed code.
// This thread should be stopped gracefully by the LS in managed code.
HRESULT CordbThread::GetManagedContext(DT_CONTEXT ** ppContext)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
if (ppContext == NULL)
{
ThrowHR(E_INVALIDARG);
}
*ppContext = NULL;
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Each CordbThread object allocates the m_pContext's DT_CONTEXT structure only once, the first time GetContext is
// invoked.
if(m_pContext == NULL)
{
// Throw if the allocation fails.
m_pContext = reinterpret_cast<DT_CONTEXT *>(new BYTE[sizeof(DT_CONTEXT)]);
}
HRESULT hr = S_OK;
if (m_fContextFresh == false)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_vmLeftSideContext = pDAC->GetManagedStoppedContext(m_vmThreadToken);
if (m_vmLeftSideContext.IsNull())
{
// We don't have a context in managed code.
ThrowHR(CORDBG_E_CONTEXT_UNVAILABLE);
}
else
{
LOG((LF_CORDB, LL_INFO1000, "CT::GC: getting context from left side pointer.\n"));
// The thread we're examining IS handling an exception, So grab the CONTEXT of the exception, NOT the
// currently executing thread's CONTEXT (which would be the context of the exception handler.)
hr = GetProcess()->SafeReadThreadContext(m_vmLeftSideContext.ToLsPtr(), m_pContext);
IfFailThrow(hr);
}
// m_fContextFresh should be marked false when CleanupStack, MarkAllFramesAsDirty, etc get called.
m_fContextFresh = true;
}
_ASSERTE(SUCCEEDED(hr));
(*ppContext) = m_pContext;
return hr;
}
HRESULT CordbThread::SetManagedContext(DT_CONTEXT * pContext)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if(pContext == NULL)
{
ThrowHR(E_INVALIDARG);
}
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_vmLeftSideContext = pDAC->GetManagedStoppedContext(m_vmThreadToken);
if (m_vmLeftSideContext.IsNull())
{
ThrowHR(CORDBG_E_CONTEXT_UNVAILABLE);
}
else
{
// The thread we're examining IS handling an exception, So set the CONTEXT of the exception, NOT the currently
// executing thread's CONTEXT (which would be the context of the exception handler.)
//
// Note: we read the remote context and merge the new one in, then write it back. This ensures that we don't
// write too much information into the remote process.
DT_CONTEXT tempContext = { 0 };
hr = GetProcess()->SafeReadThreadContext(m_vmLeftSideContext.ToLsPtr(), &tempContext);
IfFailThrow(hr);
CORDbgCopyThreadContext(&tempContext, pContext);
hr = GetProcess()->SafeWriteThreadContext(m_vmLeftSideContext.ToLsPtr(), &tempContext);
IfFailThrow(hr);
// @todo - who's updating the regdisplay to guarantee that's in sync w/ our new context?
}
_ASSERTE(SUCCEEDED(hr));
if (m_fContextFresh && (m_pContext != NULL))
{
*m_pContext = *pContext;
}
return hr;
}
HRESULT CordbThread::GetAppDomain(ICorDebugAppDomain ** ppAppDomain)
{
// We don't use the cached m_pAppDomain pointer here because it might be incorrect
// if the thread has transitioned to another domain but we haven't received any events
// from it yet. So we need to ask the left-side for the current domain.
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this);
{
ValidateOrThrow(ppAppDomain);
*ppAppDomain = NULL;
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
CordbAppDomain * pAppDomain = NULL;
hr = GetCurrentAppDomain(&pAppDomain);
IfFailThrow(hr);
_ASSERTE( pAppDomain != NULL );
*ppAppDomain = static_cast<ICorDebugAppDomain *> (pAppDomain);
pAppDomain->ExternalAddRef();
}
}
PUBLIC_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Issues a get appdomain command and returns it.
//
// Arguments:
// ppAppDomain - OUT: Space for storing the app domain of this thread.
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::GetCurrentAppDomain(CordbAppDomain ** ppAppDomain)
{
FAIL_IF_NEUTERED(this);
INTERNAL_API_ENTRY(GetProcess());
*ppAppDomain = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// @dbgtodo ICDThread - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
CordbAppDomain * pAppDomain = GetProcess()->LookupOrCreateAppDomain(vmAppDomain);
_ASSERTE(pAppDomain != NULL); // we should be aware of all AppDomains
*ppAppDomain = pAppDomain;
}
}
EX_CATCH_HRESULT(hr);
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Issues a get_object command and returns the thread object as a value.
//
// Arguments:
// ppThreadObject - OUT: Space for storing the thread object of this thread as a value
//
// Return Value:
// S_OK on success.
//
HRESULT CordbThread::GetObject(ICorDebugValue ** ppThreadObject)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppThreadObject, ICorDebugObjectValue **);
// Default to NULL
*ppThreadObject = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// @dbgtodo ICDThread - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetThreadObject(m_vmThreadToken);
if (vmObjHandle.IsNull())
{
ThrowHR(E_FAIL);
}
// We create the object relative to the current AppDomain of the thread
// Thread objects aren't really agile (eg. their m_Context field is domain-bound and
// fixed up manually during transitions). This means that a thread object can only
// be used in the domain the thread was in when the object was created.
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
CordbAppDomain * pThreadCurrentDomain = NULL;
pThreadCurrentDomain = GetProcess()->m_appDomains.GetBaseOrThrow(VmPtrToCookie(vmAppDomain));
_ASSERTE(pThreadCurrentDomain != NULL); // we should be aware of all AppDomains
if (pThreadCurrentDomain == NULL)
{
// fall back to some domain to avoid crashes in retail -
// safe enough for getting the name of the thread etc.
pThreadCurrentDomain = GetProcess()->GetDefaultAppDomain();
}
lockHolder.Release();
ICorDebugReferenceValue * pRefValue = NULL;
hr = CordbReferenceValue::BuildFromGCHandle(pThreadCurrentDomain, vmObjHandle, &pRefValue);
*ppThreadObject = pRefValue;
}
}
EX_CATCH_HRESULT(hr);
// Don't return a null pointer with S_OK.
_ASSERTE((hr != S_OK) || (*ppThreadObject != NULL));
return hr;
}
/*
*
* GetActiveFunctions
*
* This routine is the interface function for ICorDebugThread2::GetActiveFunctions.
*
* Parameters:
* cFunctions - the count of the number of COR_ACTIVE_FUNCTION in pFunctions. Zero
* indicates no pFunctions buffer.
* pcFunctions - pointer to storage for the count of elements filled in to pFunctions, or
* count that would be needed to fill pFunctions, if cFunctions is 0.
* pFunctions - buffer to store results. May be NULL.
*
* Return Value:
* HRESULT from the helper routine.
*
*/
HRESULT CordbThread::GetActiveFunctions(
ULONG32 cFunctions,
ULONG32 * pcFunctions,
COR_ACTIVE_FUNCTION pFunctions[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ULONG32 index;
ULONG32 iRealIndex;
ULONG32 last;
if (((cFunctions != 0) && (pFunctions == NULL)) || (pcFunctions == NULL))
{
return E_INVALIDARG;
}
//
// Default to 0
//
*pcFunctions = 0;
// @dbgtodo synchronization - The ATT macro may slip the thread to a sychronized state. The
// synchronization feature crew needs to figure out what to do here. Then we can use the
// PUBLIC_API_BEGIN macro in this function.
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
if (IsThreadDead())
{
//
// Return zero active functions on this thread.
//
hr = S_OK;
}
else
{
ULONG32 cAllFrames = 0; // the total number of frames (stack frames and internal frames)
ULONG32 cStackFrames = 0; // the number of stack frames
ShimStackWalk * pSSW = NULL;
if (GetProcess()->GetShim() != NULL)
{
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(this);
// initialize the frame counts
cAllFrames = pSSW->GetFrameCount();
for (ULONG32 i = 0; i < cAllFrames; i++)
{
// filter out internal frames
if (CordbFrame::GetCordbFrameFromInterface(pSSW->GetFrame(i))->GetAsNativeFrame() != NULL)
{
cStackFrames += 1;
}
}
_ASSERTE(cStackFrames <= cAllFrames);
}
else
{
RefreshStack();
cAllFrames = m_stackFrames.Count();
cStackFrames = cAllFrames;
// In Arrowhead, the stackwalking API doesn't return internal frames,
// so the frame counts should be equal.
_ASSERTE(cStackFrames == cAllFrames);
}
*pcFunctions = cStackFrames;
//
// If all we want is the count, then return that.
//
if ((pFunctions == NULL) || (cFunctions == 0))
{
hr = S_OK;
}
else
{
//
// Now go down list of frames, storing information
//
last = (cFunctions < cStackFrames) ? cFunctions : cStackFrames;
iRealIndex = 0;
index =0;
while((index < last) && (iRealIndex < cAllFrames))
{
CordbFrame * pThisFrame = NULL;
if (GetProcess()->GetShim())
{
_ASSERTE(pSSW != NULL);
pThisFrame = CordbFrame::GetCordbFrameFromInterface(pSSW->GetFrame(iRealIndex));
}
else
{
pThisFrame = *(m_stackFrames.Get(iRealIndex));
_ASSERTE(pThisFrame->GetAsNativeFrame() != NULL);
}
iRealIndex++;
CordbNativeFrame * pNativeFrame = pThisFrame->GetAsNativeFrame();
if (pNativeFrame == NULL)
{
// filter out internal frames
_ASSERTE(pThisFrame->GetAsInternalFrame() != NULL);
continue;
}
//
// Fill in the easy stuff.
//
CordbFunction * pFunction;
pFunction = (static_cast<CordbFrame *>(pNativeFrame))->GetFunction();
ASSERT(pFunction != NULL);
hr = pFunction->QueryInterface(IID_ICorDebugFunction2,
reinterpret_cast<void **>(&(pFunctions[index].pFunction)));
ASSERT(!FAILED(hr));
CordbModule * pModule = pFunction->GetModule();
pFunctions[index].pModule = pModule;
pModule->ExternalAddRef();
CordbAppDomain * pAppDomain = pNativeFrame->GetCurrentAppDomain();
pFunctions[index].pAppDomain = pAppDomain;
pAppDomain->ExternalAddRef();
pFunctions[index].flags = 0;
//
// Now go to the IL frame (if one exists) to the get the offset.
//
CordbJITILFrame * pJITILFrame;
pJITILFrame = pNativeFrame->m_JITILFrame;
if (pJITILFrame != NULL)
{
hr = pJITILFrame->GetIP(&(pFunctions[index].ilOffset), NULL);
ASSERT(!FAILED(hr));
}
else
{
pFunctions[index].ilOffset = (DWORD) NO_MAPPING;
}
// Update to the next count.
index++;
}
// @todo - The spec says that pcFunctions == # of elements in pFunctions,
// but the behavior here is that it's always the total.
// If we want to fix that, we should uncomment the assignment here:
//*pcFunctions = index;
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This is the entry point for continuable exceptions.
// It implements ICorDebugThread2::InterceptCurrentException.
//
// Arguments:
// pFrame - the stack frame to intercept at
//
// Return Value:
// HRESULT indicating success or failure
//
// Notes:
// Since we cannot intercept an exception at an internal frame,
// pFrame should not be an ICorDebugInternalFrame.
//
HRESULT CordbThread::InterceptCurrentException(ICorDebugFrame * pFrame)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
#if defined(FEATURE_DBGIPC_TRANSPORT_DI)
// Continuable exceptions are not implemented on Unix-like platforms.
return E_NOTIMPL;
#else // !FEATURE_DBGIPC_TRANSPORT_DI
HRESULT hr = S_OK;
EX_TRY
{
DebuggerIPCEvent event;
if (pFrame == NULL)
{
ThrowHR(E_INVALIDARG);
}
//
// Verify we were passed a real stack frame, and not an internal
// CLR mocked up one.
//
{
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
hr = pFrame->QueryInterface(IID_ICorDebugInternalFrame, (void **)&pInternalFrame);
if (!FAILED(hr))
{
ThrowHR(E_INVALIDARG);
}
}
//
// If the thread is detached, then there should be no frames on its stack.
//
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
//
// Refresh the stack frames for this thread and verify pFrame is on it.
//
RefreshStack();
//
// Now check if the frame actually lives on the stack of the current thread.
//
// "Cast" the ICDFrame pointer to a CordbFrame pointer.
CordbFrame * pRealFrame = CordbFrame::GetCordbFrameFromInterface(pFrame);
if (!OwnsFrame(pRealFrame))
{
ThrowHR(E_INVALIDARG);
}
//
// pFrame is on the stack - good. Now tell the LS to intercept at that frame.
//
GetProcess()->InitIPCEvent(&event, DB_IPCE_INTERCEPT_EXCEPTION, true, VMPTR_AppDomain::NullPtr());
event.InterceptException.vmThreadToken = m_vmThreadToken;
event.InterceptException.frameToken = pRealFrame->GetFramePointer();
hr = GetProcess()->m_cordb->SendIPCEvent(GetProcess(), &event, sizeof(DebuggerIPCEvent));
//
// Stop now if we can't even send the event.
//
if (!SUCCEEDED(hr))
{
ThrowHR(hr);
}
_ASSERTE(event.type == DB_IPCE_INTERCEPT_EXCEPTION_RESULT);
hr = event.hr;
// Since we are going to exit anyway, we don't need to throw here.
}
}
EX_CATCH_HRESULT(hr);
return hr;
#endif // FEATURE_DBGIPC_TRANSPORT_DI
}
//---------------------------------------------------------------------------------------
//
// Return S_OK if there is a current exception and it is unhandled, otherwise
// return S_FALSE
//
HRESULT CordbThread::HasUnhandledException()
{
FAIL_IF_NEUTERED(this);
HRESULT hr = S_FALSE;
PUBLIC_REENTRANT_API_BEGIN(this)
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
if(pDAC->HasUnhandledException(m_vmThreadToken))
{
hr = S_OK;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Create a stackwalker on the current thread. Initially, the stackwalker is stopped at the
// managed filter CONTEXT if there is one. Otherwise it is stopped at the leaf CONTEXT.
//
// Arguments:
// ppStackWalk - out parameter; return the new stackwalker
//
// Return Value:
// Return S_OK on success.
// Return E_FAIL on error.
//
// Notes:
// The filter CONTEXT will be removed in V3.0.
//
HRESULT CordbThread::CreateStackWalk(ICorDebugStackWalk ** ppStackWalk)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStackWalk, ICorDebugStackWalk **);
HRESULT hr = S_OK;
EX_TRY
{
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
hr = EnsureThreadIsAlive();
if (SUCCEEDED(hr))
{
RSInitHolder<CordbStackWalk> pSW(new CordbStackWalk(this));
pSW->Init();
pSW.TransferOwnershipExternal(ppStackWalk);
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This is a callback function used to enumerate the internal frames on a thread.
// Each time this callback is invoked, we'll create a new CordbInternalFrame and store it
// in an array. See code:DacDbiInterfaceImpl::EnumerateInternalFrames for more information.
//
// Arguments:
// pFrameData - contains information about the current internal frame in the enumeration
// pUserData - This is a GetActiveInternalFramesData.
// It contains an array of internl frames to be filled.
//
// static
void CordbThread::GetActiveInternalFramesCallback(const DebuggerIPCE_STRData * pFrameData,
void * pUserData)
{
// Retrieve the CordbThread.
GetActiveInternalFramesData * pCallbackData = reinterpret_cast<GetActiveInternalFramesData *>(pUserData);
CordbThread * pThis = pCallbackData->pThis;
INTERNAL_DAC_CALLBACK(pThis->GetProcess());
// Make sure we are getting invoked for internal frames.
_ASSERTE(pFrameData->eType == DebuggerIPCE_STRData::cStubFrame);
// Look up the CordbAppDomain.
CordbAppDomain * pAppDomain = NULL;
VMPTR_AppDomain vmCurrentAppDomain = pFrameData->vmCurrentAppDomainToken;
if (!vmCurrentAppDomain.IsNull())
{
pAppDomain = pThis->GetProcess()->LookupOrCreateAppDomain(vmCurrentAppDomain);
}
// Create a CordbInternalFrame.
CordbInternalFrame * pInternalFrame = new CordbInternalFrame(pThis,
pFrameData->fp,
pAppDomain,
pFrameData);
// Store the internal frame in the array and update the index to prepare for the next one.
pCallbackData->pInternalFrames.Assign(pCallbackData->uIndex, pInternalFrame);
pCallbackData->uIndex++;
}
//---------------------------------------------------------------------------------------
//
// This function returns an array of ICDInternalFrame2. Each element represents an internal frame
// on the thread. If ppInternalFrames is NULL or cInternalFrames is 0, then we just return
// the number of internal frames on the thread.
//
// Arguments:
// cInternalFrames - the number of elements in ppInternalFrames
// pcInternalFrames - out parameter; return the number of internal frames on the thread
// ppInternalFrames - a buffer to store the array of internal frames
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if
// - ppInternalFrames is NULL but cInternalFrames is not 0
// - pcInternalFrames is NULL
// - cInternalFrames is smaller than the number of internal frames actually on the thread
//
HRESULT CordbThread::GetActiveInternalFrames(ULONG32 cInternalFrames,
ULONG32 * pcInternalFrames,
ICorDebugInternalFrame2 * ppInternalFrames[])
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this);
{
if ( ((cInternalFrames != 0) && (ppInternalFrames == NULL)) ||
(pcInternalFrames == NULL) )
{
ThrowHR(E_INVALIDARG);
}
*pcInternalFrames = 0;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
ULONG32 cActiveInternalFrames = pDAC->GetCountOfInternalFrames(m_vmThreadToken);
// Set the count.
*pcInternalFrames = cActiveInternalFrames;
// Don't need to do anything else if the user is only asking for the count.
if ((cInternalFrames != 0) && (ppInternalFrames != NULL))
{
if (cInternalFrames < cActiveInternalFrames)
{
ThrowWin32(ERROR_INSUFFICIENT_BUFFER);
}
else
{
// initialize the callback data
GetActiveInternalFramesData data;
data.pThis = this;
data.uIndex = 0;
data.pInternalFrames.AllocOrThrow(cActiveInternalFrames);
// We want to ensure it's automatically cleaned up in all cases
// e.g. if we're debugging a MiniDumpNormal and we fail to
// retrieve memory from the target. The exception will be
// caught above this frame.
data.pInternalFrames.EnableAutoClear();
pDAC->EnumerateInternalFrames(m_vmThreadToken,
&CordbThread::GetActiveInternalFramesCallback,
&data);
_ASSERTE(cActiveInternalFrames == data.pInternalFrames.Length());
// Copy the internal frames we have accumulated in GetActiveInternalFramesData to the out
// argument.
for (unsigned int i = 0; i < data.pInternalFrames.Length(); i++)
{
RSInitHolder<CordbInternalFrame> pInternalFrame(data.pInternalFrames[i]);
pInternalFrame.TransferOwnershipExternal(&(ppInternalFrames[i]));
}
}
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ICorDebugThread4
// -------------------------------------------------------------------------------
// Gets the current custom notification on this thread or NULL if no such object exists
// Arguments:
// output: ppNotificationObject - current CustomNotification object.
// if we aren't currently inside a CustomNotification callback, this will
// always return NULL.
// return value:
// S_OK on success
// S_FALSE if no object exists
// CORDBG_E_BAD_REFERENCE_VALUE if the reference is bad
HRESULT CordbThread::GetCurrentCustomDebuggerNotification(ICorDebugValue ** ppNotificationObject)
{
HRESULT hr = S_OK;
PUBLIC_API_NO_LOCK_BEGIN(this);
{
ATT_REQUIRE_STOPPED_MAY_FAIL_OR_THROW(GetProcess(), ThrowHR);
if (ppNotificationObject == NULL)
{
ThrowHR(E_INVALIDARG);
}
*ppNotificationObject = NULL;
//
// Go to the LS and retrieve any notification object.
//
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
VMPTR_OBJECTHANDLE vmObjHandle = pDAC->GetCurrentCustomDebuggerNotification(m_vmThreadToken);
#if defined(_DEBUG)
// Since we know a notification has occurred on this thread, our assumption about the
// thread's current AppDomain should be correct
VMPTR_AppDomain vmAppDomain = pDAC->GetCurrentAppDomain(m_vmThreadToken);
_ASSERTE(GetAppDomain()->GetADToken() == vmAppDomain);
#endif // _DEBUG
if (!vmObjHandle.IsNull())
{
ICorDebugReferenceValue * pRefValue = NULL;
IfFailThrow(CordbReferenceValue::BuildFromGCHandle(GetAppDomain(), vmObjHandle, &pRefValue));
*ppNotificationObject = pRefValue;
}
}
PUBLIC_API_END(hr);
return hr;
}
// ICorDebugThread5
/*
* GetBytesAllocated
*
* Returns S_OK if it was possible to obtain the allocation information for the thread
* and sets the corresponding SOH and UOH allocations.
*/
HRESULT CordbThread::GetBytesAllocated(ULONG64 *pSohAllocatedBytes,
ULONG64 *pUohAllocatedBytes)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
DacThreadAllocInfo threadAllocInfo = { 0 };
if (pSohAllocatedBytes == NULL || pUohAllocatedBytes == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
pDAC->GetThreadAllocInfo(m_vmThreadToken, &threadAllocInfo);
*pSohAllocatedBytes = threadAllocInfo.m_allocBytesSOH;
*pUohAllocatedBytes = threadAllocInfo.m_allocBytesUOH;
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetBytesAllocated
/*
*
* SetRemapIP
*
* This routine communicate the EnC remap IP to the LS by writing it to process memory using
* the pointer that was set in the thread. If the address is null, then we haven't seen
* a RemapOpportunity call for this frame/function combo yet, so invalid to Remap the function.
*
* Parameters:
* offset - the IL offset to set the IP to
*
* Return Value:
* S_OK or CORDBG_E_NO_REMAP_BREAKPIONT.
*
*/
HRESULT CordbThread::SetRemapIP(SIZE_T offset)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// This is only set when we're prepared to do a remap
if (! m_EnCRemapFunctionIP)
{
return CORDBG_E_NO_REMAP_BREAKPIONT;
}
// Write the value of the remap offset into the left side
HRESULT hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(m_EnCRemapFunctionIP), &offset);
// Prevent SetRemapIP from being called twice for the same RemapOpportunity
// If we don't get any calls to RemapFunction, this member will be cleared in
// code:CordbThread::MarkStackFramesDirty when Continue is called
m_EnCRemapFunctionIP = NULL;
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetConnectionID.
//
// Arguments:
// pdwConnectionId - return connection id set on the thread. Can return INVALID_CONNECTION_ID
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT CordbThread::GetConnectionID(CONNID * pConnectionID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the connection id
HRESULT hr = S_OK;
EX_TRY
{
if (pConnectionID == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pConnectionID = pDAC->GetConnectionID(m_vmThreadToken);
if (*pConnectionID == INVALID_CONNECTION_ID)
{
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetConnectionID
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetTaskID.
//
// Arguments:
// pTaskId - return task id set on the thread. Can return INVALID_TASK_ID
//
// Return Value:
// HRESULT indicating success or failure
//
HRESULT CordbThread::GetTaskID(TASKID * pTaskID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the task id
HRESULT hr = S_OK;
EX_TRY
{
if (pTaskID == NULL)
{
ThrowHR(E_INVALIDARG);
}
*pTaskID = this->GetTaskID();
if (*pTaskID == INVALID_TASK_ID)
{
hr = S_FALSE;
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetTaskID
//---------------------------------------------------------------------------------------
// Get the task ID for this thread
//
// return:
// task id set on the thread. Can return INVALID_TASK_ID
//
TASKID CordbThread::GetTaskID()
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
return pDAC->GetTaskID(m_vmThreadToken);
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugThread2::GetVolatileOSThreadID.
//
// Arguments:
// pdwTid - return os thread id
//
// Return Value:
// HRESULT indicating success or failure
//
// Notes:
// Compare with code:CordbThread::GetID
HRESULT CordbThread::GetVolatileOSThreadID(DWORD * pdwTID)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// now retrieve the OS thread ID
HRESULT hr = S_OK;
EX_TRY
{
if (pdwTID == NULL)
{
ThrowHR(E_INVALIDARG);
}
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pdwTID = pDAC->TryGetVolatileOSThreadID(m_vmThreadToken);
if (*pdwTID == 0)
{
hr = S_FALSE; // Switched out
}
}
EX_CATCH_HRESULT(hr);
return hr;
} // CordbThread::GetOSThreadID
//---------------------------------------------------------------------------------------
// Get the thread's volatile OS ID. (this is fiber aware)
//
// Returns:
// Thread's current OS id. For fibers / "logical threads", This may change as a thread executes.
// Throws if the managed thread currently is not mapped to an OS thread (ie, not scheduled)
//
DWORD CordbThread::GetVolatileOSThreadID()
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
DWORD dwThreadID = pDAC->TryGetVolatileOSThreadID(m_vmThreadToken);
if (dwThreadID == 0)
{
ThrowHR(CORDBG_E_THREAD_NOT_SCHEDULED);
}
return dwThreadID;
}
// ----------------------------------------------------------------------------
// CordbThread::ClearStackFrameCache
//
// Description:
// Clear the cache of stack frames maintained by the CordbThread.
//
// Notes:
// We are doing an InternalRelease() here to match the InternalAddRef() in code:CordbThread::RefreshStack.
//
void CordbThread::ClearStackFrameCache()
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
for (int i = 0; i < m_stackFrames.Count(); i++)
{
(*m_stackFrames.Get(i))->Neuter();
(*m_stackFrames.Get(i))->InternalRelease();
}
m_stackFrames.Clear();
}
// ----------------------------------------------------------------------------
// EnumerateBlockingObjectsCallback
//
// Description:
// A small helper used by CordbThread::GetBlockingObjects. This callback adds the enumerated items
// to a list
//
// Arguments:
// blockingObject - the object to add to the list
// pUserData - the list to add it to
VOID EnumerateBlockingObjectsCallback(DacBlockingObject blockingObject, CALLBACK_DATA pUserData)
{
CQuickArrayList<DacBlockingObject>* pDacBlockingObjs = (CQuickArrayList<DacBlockingObject>*)pUserData;
pDacBlockingObjs->Push(blockingObject);
}
// ----------------------------------------------------------------------------
// CordbThread::GetBlockingObjects
//
// Description:
// Returns a list of objects that a thread is blocking on by using Monitor.Enter and
// Monitor.Wait
//
// Arguments:
// ppBlockingObjectEnum - on return this is an enumerator for the list of blocking objects
//
// Return:
// S_OK on success or an appropriate failing HRESULT
HRESULT CordbThread::GetBlockingObjects(ICorDebugBlockingObjectEnum **ppBlockingObjectEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppBlockingObjectEnum, ICorDebugBlockingObjectEnum **);
HRESULT hr = S_OK;
CorDebugBlockingObject* blockingObjs = NULL;
EX_TRY
{
CQuickArrayList<DacBlockingObject> dacBlockingObjects;
IDacDbiInterface* pDac = GetProcess()->GetDAC();
pDac->EnumerateBlockingObjects(m_vmThreadToken,
(IDacDbiInterface::FP_BLOCKINGOBJECT_ENUMERATION_CALLBACK) EnumerateBlockingObjectsCallback,
(CALLBACK_DATA) &dacBlockingObjects);
blockingObjs = new CorDebugBlockingObject[dacBlockingObjects.Size()];
for(SIZE_T i = 0 ; i < dacBlockingObjects.Size(); i++)
{
// ICorDebug API needs to flip the direction of the list from the way DAC stores it
SIZE_T dacObjIndex = dacBlockingObjects.Size()-i-1;
switch(dacBlockingObjects[dacObjIndex].blockingReason)
{
case DacBlockReason_MonitorCriticalSection:
blockingObjs[i].blockingReason = BLOCKING_MONITOR_CRITICAL_SECTION;
break;
case DacBlockReason_MonitorEvent:
blockingObjs[i].blockingReason = BLOCKING_MONITOR_EVENT;
break;
default:
_ASSERTE(!"Should not get here");
ThrowHR(E_FAIL);
break;
}
blockingObjs[i].dwTimeout = dacBlockingObjects[dacObjIndex].dwTimeout;
CordbAppDomain* pAppDomain;
{
RSLockHolder holder(GetProcess()->GetProcessLock());
pAppDomain = GetProcess()->LookupOrCreateAppDomain(dacBlockingObjects[dacObjIndex].vmAppDomain);
}
blockingObjs[i].pBlockingObject = CordbValue::CreateHeapValue(pAppDomain,
dacBlockingObjects[dacObjIndex].vmBlockingObject);
}
CordbBlockingObjectEnumerator* objEnum = new CordbBlockingObjectEnumerator(GetProcess(),
blockingObjs,
(DWORD)dacBlockingObjects.Size());
GetProcess()->GetContinueNeuterList()->Add(GetProcess(), objEnum);
hr = objEnum->QueryInterface(__uuidof(ICorDebugBlockingObjectEnum), (void**)ppBlockingObjectEnum);
_ASSERTE(SUCCEEDED(hr));
}
EX_CATCH_HRESULT(hr);
delete [] blockingObjs;
return hr;
}
#ifdef FEATURE_INTEROP_DEBUGGING
/* ------------------------------------------------------------------------- *
* Unmanaged Thread classes
* ------------------------------------------------------------------------- */
CordbUnmanagedThread::CordbUnmanagedThread(CordbProcess *pProcess, DWORD dwThreadId, HANDLE hThread, void *lpThreadLocalBase)
: CordbBase(pProcess, dwThreadId, enumCordbUnmanagedThread),
m_stackBase(0),
m_stackLimit(0),
m_handle(hThread),
m_threadLocalBase(lpThreadLocalBase),
m_pTLSArray(NULL),
m_pTLSExtendedArray(NULL),
m_state(CUTS_None),
m_originalHandler(NULL),
#ifdef TARGET_X86
m_pSavedLeafSeh(NULL),
#endif
m_continueCountCached(0)
{
m_pLeftSideContext.Set(NULL);
IBEvent()->m_state = CUES_None;
IBEvent()->m_next = NULL;
IBEvent()->m_owner = this;
IBEvent2()->m_state = CUES_None;
IBEvent2()->m_next = NULL;
IBEvent2()->m_owner = this;
OOBEvent()->m_state = CUES_None;
OOBEvent()->m_next = NULL;
OOBEvent()->m_owner = this;
m_pPatchSkipAddress = NULL;
this->GetStackRange(NULL, NULL);
}
CordbUnmanagedThread::~CordbUnmanagedThread()
{
// CordbUnmanagedThread objects will:
// - never send IPC events.
// - never be exposed to the public. (we assert external-ref is always == 0)
// - always manipulated on W32ET (where we can't do IPC stuff)
UnsafeNeuterDeadObject();
_ASSERTE(this->IsNeutered());
// by the time the thread is deleted, it shouldn't have any outstanding debug events.
// Actually, the thread could get deleted while we have an outstanding IB debug event. We could get the IB event, hijack that thread,
// and then since the process is continued, something could go off and kill the hijacked thread.
// If the event is still in the process's queued list, and it still refers back to a thread, then we'll AV when we try to access the event
// (or continue it).
CONSISTENCY_CHECK_MSGF(!HasIBEvent(), ("Deleting thread w/ outstanding IB event:this=%p,event-code=%d\n", this, IBEvent()->m_currentDebugEvent.dwDebugEventCode));
CONSISTENCY_CHECK_MSGF(!HasOOBEvent(), ("Deleting thread w/ outstanding OOB event:this=%p,event-code=%d\n", this, OOBEvent()->m_currentDebugEvent.dwDebugEventCode));
}
#define WINNT_TLS_OFFSET_X86 0xe10 // TLS[0] at fs:[WINNT_TLS_OFFSET]
#define WINNT_TLS_OFFSET_AMD64 0x1480
#define WINNT_TLS_OFFSET_ARM 0xe10
#define WINNT_TLS_OFFSET_ARM64 0x1480
#define WINNT5_TLSEXPANSIONPTR_OFFSET_X86 0xf94 // TLS[64] at [fs:[WINNT5_TLSEXPANSIONPTR_OFFSET]]
#define WINNT5_TLSEXPANSIONPTR_OFFSET_AMD64 0x1780
#define WINNT5_TLSEXPANSIONPTR_OFFSET_ARM 0xf94
#define WINNT5_TLSEXPANSIONPTR_OFFSET_ARM64 0x1780
HRESULT CordbUnmanagedThread::LoadTLSArrayPtr(void)
{
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// Just simple math on NT with a small tls index.
// The TLS slots for 0-63 are embedded in the TIB.
#if defined(TARGET_X86)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_X86;
#elif defined(TARGET_AMD64)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_AMD64;
#elif defined(TARGET_ARM)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_ARM;
#elif defined(TARGET_ARM64)
m_pTLSArray = (BYTE*) m_threadLocalBase + WINNT_TLS_OFFSET_ARM64;
#else
PORTABILITY_ASSERT("Implement OOP TLS on your platform");
#endif
// Extended slot is lazily initialized, so check every time.
if (m_pTLSExtendedArray == NULL)
{
// On NT 5 you can have TLS index's greater than 63, so we
// have to grab the ptr to the TLS expansion array first,
// then use that as the base to index off of. This will
// never move once we find it for a given thread, so we
// cache it here so we don't always have to perform two
// ReadProcessMemory's.
#if defined(TARGET_X86)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_X86;
#elif defined(TARGET_AMD64)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_AMD64;
#elif defined(TARGET_ARM)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_ARM;
#elif defined(TARGET_ARM64)
void *ppTLSArray = (BYTE*) m_threadLocalBase + WINNT5_TLSEXPANSIONPTR_OFFSET_ARM64;
#else
PORTABILITY_ASSERT("Implement OOP TLS on your platform");
#endif
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(ppTLSArray), &m_pTLSExtendedArray);
}
return hr;
}
/*
VOID CordbUnmanagedThread::VerifyFSChain()
{
#if defined(TARGET_X86)
DT_CONTEXT temp;
temp.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(m_handle, &temp);
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: 0x%x fs=0x%x TIB=0x%x\n",
m_id, temp.SegFs, m_threadLocalBase));
REMOTE_PTR pExceptionRegRecordPtr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &pExceptionRegRecordPtr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read fs:0 value: computed addr=0x%p err=%x\n",
m_id, m_threadLocalBase, hr));
_ASSERTE(FALSE);
return;
}
while(pExceptionRegRecordPtr != EXCEPTION_CHAIN_END && pExceptionRegRecordPtr != NULL)
{
REMOTE_PTR prev;
REMOTE_PTR handler;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pExceptionRegRecordPtr), &prev);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read prev value: computed addr=0x%p err=%x\n",
m_id, pExceptionRegRecordPtr, hr));
return;
}
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS( (VOID*)((DWORD)pExceptionRegRecordPtr+4) ), &handler);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x failed to read handler value: computed addr=0x%p err=%x\n",
m_id, (DWORD)pExceptionRegRecordPtr+4, hr));
return;
}
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: OK 0x%x record=0x%x prev=0x%x handler=0x%x\n",
m_id, pExceptionRegRecordPtr, prev, handler));
if(handler == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x NULL handler found\n", m_id));
_ASSERTE(FALSE);
return;
}
if(prev == NULL)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x NULL prev found\n", m_id));
_ASSERTE(FALSE);
return;
}
if(prev == pExceptionRegRecordPtr)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: ERROR 0x%x cyclic prev found\n", m_id));
_ASSERTE(FALSE);
return;
}
pExceptionRegRecordPtr = prev;
}
LOG((LF_CORDB, LL_INFO1000, "CUT::VFSC: OK 0x%x\n", m_id));
#endif
return;
}*/
#ifdef TARGET_X86
HRESULT CordbUnmanagedThread::SaveCurrentLeafSeh()
{
_ASSERTE(m_pSavedLeafSeh == NULL);
REMOTE_PTR pExceptionRegRecordPtr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &pExceptionRegRecordPtr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SCLS: failed to read fs:0 value: computed addr=0x%p err=%x\n", m_threadLocalBase, hr));
return hr;
}
m_pSavedLeafSeh = pExceptionRegRecordPtr;
return S_OK;
}
HRESULT CordbUnmanagedThread::RestoreLeafSeh()
{
_ASSERTE(m_pSavedLeafSeh != NULL);
HRESULT hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(m_threadLocalBase), &m_pSavedLeafSeh);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::RLS: failed to write fs:0 value: computed addr=0x%p err=%x\n", m_threadLocalBase, hr));
return hr;
}
m_pSavedLeafSeh = NULL;
return S_OK;
}
#endif
// Read the contents from the LS's Predefined TLS block.
// This is an auxillary TLS storage array-of-void*, indexed off the TLS.
// pRead is optional. This makes sense when '0' is a valid default value.
// 1) On success (block exists in LS, we can read it),
// return value of data in the slot, *pRead = true
// 2) On failure to read block (block doens't exist yet, any other failure)
// return value == 0 (assumed default, *pRead = false
REMOTE_PTR CordbUnmanagedThread::GetPreDefTlsSlot(SIZE_T offset)
{
REMOTE_PTR tlsDataAddress;
HRESULT hr = GetClrModuleTlsDataAddress(&tlsDataAddress);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: GetClrModuleTlsDataAddress FAILED %x for 0x%x\n", hr, m_id));
return NULL;
}
REMOTE_PTR data = 0;
// Read the thread's TLS value.
REMOTE_PTR slotAddr = (BYTE*)tlsDataAddress + offset;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(slotAddr), &data);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: failed to get TLS value: tlsData=0x%p offset=%d, err=%x\n",
tlsDataAddress, offset, hr));
return NULL;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETV: EE Thread TLS value is 0x%x for 0x%x\n", data, m_id));
return data;
}
// Read the contents from a LS threads's TLS slot.
HRESULT CordbUnmanagedThread::GetTlsSlot(DWORD slot, REMOTE_PTR * pValue)
{
// Compute the address of the necessary TLS value.
HRESULT hr = LoadTLSArrayPtr();
if (FAILED(hr))
{
return hr;
}
void * pBase = NULL;
SIZE_T slotAdjusted = slot;
if (slot < TLS_MINIMUM_AVAILABLE)
{
pBase = m_pTLSArray;
}
else if (slot < TLS_MINIMUM_AVAILABLE + TLS_EXPANSION_SLOTS)
{
pBase = m_pTLSExtendedArray;
slotAdjusted -= TLS_MINIMUM_AVAILABLE;
// Expansion slot is lazily allocated. If we're trying to read from it, but hasn't been allocated,
// then the TLS slot is still the default value, which is 0 (NULL).
if (pBase == NULL)
{
*pValue = NULL;
return S_OK;
}
}
else
{
// Slot is out of range. Shouldn't happen unless debuggee is corrupted.
_ASSERTE(!"Invalid TLS slot");
return E_UNEXPECTED;
}
void *pEEThreadTLS = (BYTE*)pBase + (slotAdjusted * sizeof(void*));
// Read the thread's TLS value.
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadTLS), pValue);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GTS: failed to read TLS value: computed addr=0x%p slot=%d, err=%x\n",
pEEThreadTLS, slot, hr));
return hr;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GTS: EE Thread TLS value is 0x%p for thread 0x%x, slot 0x%x\n", *pValue, m_id, slot));
return S_OK;
}
// This does a WriteProcessMemory to write to the debuggee's TLS slot
//
// Notes:
// This is very brittle because the OS can lazily allocates storage for TLS slots.
// In order to gaurantee the storage is available, it must have been written to by the debuggee.
// For managed threads, that's easy because the Thread* is already written to the slot.
// But for pure native threads where GetThread() == NULL, the storage may not yet be allocated.
//
// The saving grace is that the debuggee's hijack filters will force the TLS to be allocated before it
// sends a flare.
//
// Therefore, this function can only be called:
// 1) on a managed thread
// 2) on a native thread after that thread has been hijacked and sent a flare.
//
// This is brittle reasoning, but so is the rest of interop-debugging.
//
HRESULT CordbUnmanagedThread::SetTlsSlot(DWORD slot, REMOTE_PTR value)
{
FAIL_IF_NEUTERED(this);
// Compute the address of the necessary TLS value.
HRESULT hr = LoadTLSArrayPtr();
if (FAILED(hr))
{
return hr;
}
void * pBase = NULL;
SIZE_T slotAdjusted = slot;
if (slot < TLS_MINIMUM_AVAILABLE)
{
pBase = m_pTLSArray;
}
else if (slot < TLS_MINIMUM_AVAILABLE + TLS_EXPANSION_SLOTS)
{
pBase = m_pTLSExtendedArray;
slotAdjusted -= TLS_MINIMUM_AVAILABLE;
// Expansion slot is lazily allocated. If we're trying to read from it, but hasn't been allocated,
// then the TLS slot is still the default value, which is 0.
if (pBase == NULL)
{
// See reasoning in header for why this should succeed.
_ASSERTE(!"Can't set to expansion slots because they haven't been allocated");
return E_FAIL;
}
}
else
{
// Slot is out of range. Shouldn't happen unless debuggee is corrupted.
_ASSERTE(!"Invalid TLS slot");
return E_INVALIDARG;
}
void *pEEThreadTLS = (BYTE*)pBase + (slotAdjusted * sizeof(void*));
// Write the thread's TLS value.
hr = GetProcess()->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pEEThreadTLS), &value);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SEETV: failed to set TLS value: computed addr=0x%p slot=%d, err=%x\n", pEEThreadTLS, slot, hr));
return hr;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::SEETV: EE Thread TLS value is now 0x%p for 0x%x\n", value, m_id));
return S_OK;
}
// gets the value of gCurrentThreadInfo.m_pThread
DWORD_PTR CordbUnmanagedThread::GetEEThreadValue()
{
DWORD_PTR ret = NULL;
REMOTE_PTR tlsDataAddress;
HRESULT hr = GetClrModuleTlsDataAddress(&tlsDataAddress);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: GetClrModuleTlsDataAddress FAILED %x for 0x%x\n", hr, m_id));
return NULL;
}
// Read the thread's TLS value.
REMOTE_PTR EEThreadAddr = (BYTE*)tlsDataAddress + GetProcess()->m_runtimeOffsets.m_TLSEEThreadOffset + OFFSETOF__TLS__tls_CurrentThread;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(EEThreadAddr), &ret);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETV: failed to get TLS value: computed addr=0x%p index=%d, err=%x\n",
EEThreadAddr, GetProcess()->m_runtimeOffsets.m_TLSIndex, hr));
return NULL;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETV: EE Thread TLS value is 0x%p for 0x%x\n", ret, m_id));
return ret;
}
// returns the remote address of gCurrentThreadInfo
HRESULT CordbUnmanagedThread::GetClrModuleTlsDataAddress(REMOTE_PTR* pAddress)
{
*pAddress = NULL;
REMOTE_PTR tlsArrayAddr;
HRESULT hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_threadLocalBase + WINNT_OFFSETOF__TEB__ThreadLocalStoragePointer), &tlsArrayAddr);
if (FAILED(hr))
{
return hr;
}
// This is the special break-in thread case: TEB.ThreadLocalStoragePointer == NULL
if (tlsArrayAddr == NULL)
{
return E_FAIL;
}
REMOTE_PTR clrModuleTlsDataAddr;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)tlsArrayAddr + GetProcess()->m_runtimeOffsets.m_TLSIndex * sizeof(void*)), &clrModuleTlsDataAddr);
if (FAILED(hr))
{
return hr;
}
if (clrModuleTlsDataAddr == NULL)
{
_ASSERTE(!"No clr module data present at _tls_index for this thread");
return E_FAIL;
}
*pAddress = (BYTE*) clrModuleTlsDataAddr;
return S_OK;
}
/*
* GetEEDebuggerWord
*
* This routine returns the value read from the thread
*
* Parameters:
* pValue - Location to store value.
*
* Returns:
* E_INVALIDARG, E_FAIL, S_OK
*/
HRESULT CordbUnmanagedThread::GetEEDebuggerWord(REMOTE_PTR *pValue)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEEDW: Entered\n"));
if (pValue == NULL)
{
return E_INVALIDARG;
}
return GetTlsSlot(GetProcess()->m_runtimeOffsets.m_debuggerWordTLSIndex, pValue);
}
// SetEEDebuggerWord
//
// This routine writes the value to the thread
//
// Parameters:
// pValue - Value to write.
//
// Returns:
// HRESULT failure code or S_OK
//
// Notes:
// This function is very dangerous. See code:CordbUnmanagedThread::SetEETlsValue for why.
HRESULT CordbUnmanagedThread::SetEEDebuggerWord(REMOTE_PTR value)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SEEDW: Entered - value is 0x%p\n", value));
return SetTlsSlot(GetProcess()->m_runtimeOffsets.m_debuggerWordTLSIndex, value);
}
/*
* GetEEThreadPtr
*
* This routine returns the value read from the thread
*
* Parameters:
* ppEEThread - Location to store value.
*
* Returns:
* E_INVALIDARG, E_FAIL, S_OK
*/
HRESULT CordbUnmanagedThread::GetEEThreadPtr(REMOTE_PTR *ppEEThread)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
if (ppEEThread == NULL)
{
return E_INVALIDARG;
}
*ppEEThread = (REMOTE_PTR)GetEEThreadValue();
return S_OK;
}
void CordbUnmanagedThread::GetEEState(bool *threadStepping, bool *specialManagedException)
{
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
_ASSERTE(pEEThread != NULL);
*threadStepping = false;
*specialManagedException = false;
// Compute the address of the thread's state
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadStateNC = (BYTE*) pEEThread + pRO->m_EEThreadStateNCOffset;
// Grab the thread state out of the EE Thread.
DWORD EEThreadStateNC;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadStateNC), &EEThreadStateNC);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETS: failed to read thread state NC: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadStateNCOffset, pEEThreadStateNC, GetLastError()));
return;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETS: EE Thread state NC is 0x%08x\n", EEThreadStateNC));
// Looks like we've got the state of the thread.
*threadStepping = ((EEThreadStateNC & pRO->m_EEThreadSteppingStateMask) != 0);
*specialManagedException = ((EEThreadStateNC & pRO->m_EEIsManagedExceptionStateMask) != 0);
return;
}
// Is the thread in a "can't stop" region?
// "Can't-Stop" regions include anything that's "inside" the runtime; ie, the runtime has some
// synchronization mechanism that will halt this thread, and so we don't need to suspend it.
// The interop debugger should leave anything in a can't-stop region alone and just let the runtime
// handle it.
bool CordbUnmanagedThread::IsCantStop()
{
CONTRACTL
{
NOTHROW;
}
CONTRACTL_END;
// Definition of a can't stop region:
// - Any "Special" thread that doesn't have an EE Thread (includes the real Helper Thread,
// Concurrent GC thread, ThreadPool thread, etc).
// - Any thread in Cooperative code.
// - Any thread w/ a can't-stop count > 0.
// - Any thread holding a "Debugger" Crst. (This is actually a subset of the
// can't-stop count b/c Enter/Leave adjust that count).
// - Any generic, first chance or RaiseException hijacked thread
// If the runtime isn't init yet, not a can't-stop.
// We don't even have the DCB yet.
if (!GetProcess()->m_initialized)
{
return false;
}
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
if (IsRaiseExceptionHijacked())
{
return true;
}
REMOTE_PTR pEEThread;
HRESULT hr = this->GetEEThreadPtr(&pEEThread);
if (FAILED(hr))
{
_ASSERTE(!"Failed to EEThreadPtr in IsCantStop");
return true;
}
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
// @todo- remove this and use the CantStop index below.
// Is this a "special" thread?
// Any thread that can take CLR locks w/o having an EE Thread object should
// be marked as special. These threads are in "can't-stop" regions b/c if we suspend
// them, they may be holding a lock that blocks the helper thread.
// The helper thread is marked as "special".
{
REMOTE_PTR special = GetPreDefTlsSlot(pRO->m_TLSIsSpecialOffset);
// If it's a special thread
if ((special != 0) && (pEEThread == NULL))
{
return true;
}
}
// Check for CantStop regions off the FLS.
// This is the biggest way to describe can't-stop regions when we're in preemptive mode
// (or when we don't have a thread object).
// If a LS thread takes a debugger lock, it will increment the Can't-Stop count.
{
REMOTE_PTR count = GetPreDefTlsSlot(pRO->m_TLSCantStopOffset);
// Just a sanity check here. There's nothing special about 1000, but if the
// stop-count gets this big, 99% chance it's:
// - we're accessing the wrong memory (an issue)
// - someone on the LS is leaking stop-counts. (an issue).
_ASSERTE(count < (REMOTE_PTR)1000);
if (count > 0)
{
LOG((LF_CORDB, LL_INFO1000000, "Thread 0x%x is can't-stop b/c count=%d\n", m_id, count));
return true;
}
}
EX_TRY
{
GetProcess()->UpdateRightSideDCB();
}
EX_CATCH
{
_ASSERTE(!"IsCantStop: Failed updating debugger control block");
}
EX_END_CATCH(SwallowAllExceptions);
// Helper's canary thread is always can't-stop.
if (this->m_id == GetProcess()->GetDCB()->m_CanaryThreadId)
{
return true;
}
// Check helper thread / or anyone pretending to be the helper thread.
if ((this->m_id == GetProcess()->GetDCB()->m_helperThreadId) ||
(this->m_id == GetProcess()->GetDCB()->m_temporaryHelperThreadId) ||
(this->m_id == GetProcess()->m_helperThreadId))
{
return true;
}
if (IsGenericHijacked() || IsFirstChanceHijacked())
return true;
// If this isn't a EE thread (and not the helper thread, and not hijacked), then it's ok to stop.
if (pEEThread == NULL)
return false;
// This checks for an explicit "can't" stop region.
// Eventually, these explicit regions should become a complete subset of the other checks.
REMOTE_PTR count = GetPreDefTlsSlot(GetProcess()->m_runtimeOffsets.m_TLSCantStopOffset);
if (count > 0)
return true;
// If we're in cooperative mode (either managed code or parts inside the runtime), then don't stop.
// Note we could remove this since the check is made in side of the DAC request below,
// but it's faster to look here.
if (GetEEPGCDisabled())
return true;
return false;
}
bool CordbUnmanagedThread::GetEEPGCDisabled()
{
// Note: any failure to read memory is okay for this method. We simply say that the thread has PGC disabled, which
// is always the worst case scenario.
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
// Compute the address of the thread's PGC disabled word
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadPGCDisabled = (BYTE*) pEEThread + pRO->m_EEThreadPGCDisabledOffset;
// Grab the PGC disabled word out of the EE Thread.
DWORD EEThreadPGCDisabled;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadPGCDisabled), &EEThreadPGCDisabled);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETS: failed to read thread PGC Disabled: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadPGCDisabledOffset, pEEThreadPGCDisabled, GetLastError()));
return true;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETS: EE Thread PGC Disabled is 0x%08x\n", EEThreadPGCDisabled));
// Looks like we've got it.
if (EEThreadPGCDisabled == pRO->m_EEThreadPGCDisabledValue)
return true;
else
return false;
}
bool CordbUnmanagedThread::GetEEFrame()
{
REMOTE_PTR pEEThread;
HRESULT hr = GetEEThreadPtr(&pEEThread);
_ASSERTE(SUCCEEDED(hr));
_ASSERTE(pEEThread != NULL);
// Compute the address of the thread's frame ptr
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
void *pEEThreadFrame = (BYTE*) pEEThread + pRO->m_EEThreadFrameOffset;
// Grab the thread's frame out of the EE Thread.
DWORD EEThreadFrame;
hr = GetProcess()->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pEEThreadFrame), &EEThreadFrame);
if (FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CUT::GEETF: failed to read thread frame: 0x%p + 0x%x = 0x%p, err=%d\n",
pEEThread, pRO->m_EEThreadFrameOffset, pEEThreadFrame, GetLastError()));
return false;
}
LOG((LF_CORDB, LL_INFO1000000, "CUT::GEETF: EE Thread's frame is 0x%08x\n", EEThreadFrame));
// Looks like we've got the frame of the thread.
if (EEThreadFrame != pRO->m_EEMaxFrameValue)
return true;
else
return false;
}
// Gets the thread context as if the thread were unhijacked, regardless
// of whether it really is
HRESULT CordbUnmanagedThread::GetThreadContext(DT_CONTEXT* pContext)
{
// While hijacked there are 3 potential contexts we could be resuming back to
// 1) A context provided in SetThreadContext that we defered applying
// 2) The LS copy of the context on the stack being modified in the handler
// 3) The original context present when the hijack was started
//
// Both #1 and #3 are stored in the GetHijackCtx() space so of course you can't
// have them both. You have have #1 if IsContextSet() is true, otherwise it holds #3
//
// GenericHijack, FirstChanceHijackForSync, and RaiseExceptionHijack use #1 if available
// and fallback to #3 if not. In other words they use GetHijackCtx() regardless of which thing it holds
// M2UHandoff uses #1 if available and then falls back to #2.
//
// The reasoning here is that the first three hijacks are intended to be transparent. Since
// the debugger shouldn't know they are occuring then it shouldn't see changes potentially
// made on the LS. The M2UHandoff is not transparent, it has to update the context in order
// to get clear of a bp.
//
// If not hijacked call the normal Win32 function.
HRESULT hr = S_OK;
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: thread=0x%p, flags=0x%x.\n", this, pContext->ContextFlags));
if(IsContextSet() || IsGenericHijacked() || (IsFirstChanceHijacked() && IsBlockingForSync())
|| IsRaiseExceptionHijacked())
{
_ASSERTE(IsFirstChanceHijacked() || IsGenericHijacked() || IsRaiseExceptionHijacked());
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: hijackCtx case IsContextSet=%d IsGenericHijacked=%d"
"HijackedForSync=%d RaiseExceptionHijacked=%d.\n",
IsContextSet(), IsGenericHijacked(), IsBlockingForSync(), IsRaiseExceptionHijacked()));
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: hijackCtx is:\n"));
LogContext(GetHijackCtx());
CORDbgCopyThreadContext(pContext, GetHijackCtx());
}
// use the LS for M2UHandoff
else if (IsFirstChanceHijacked() && !IsBlockingForSync())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: getting LS context for first chance hijack, addr=0x%08x.\n",
m_pLeftSideContext.UnsafeGet()));
// Read the context into a temp context then copy to the out param.
DT_CONTEXT tempContext = { 0 };
hr = GetProcess()->SafeReadThreadContext(m_pLeftSideContext, &tempContext);
if (SUCCEEDED(hr))
CORDbgCopyThreadContext(pContext, &tempContext);
}
// no hijack in place so just call straight through
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::GTC: getting context from win32.\n"));
BOOL succ = DbiGetThreadContext(m_handle, pContext);
if (!succ)
hr = HRESULT_FROM_GetLastError();
}
if(IsSSFlagHidden())
{
UnsetSSFlag(pContext);
}
LogContext(pContext);
return hr;
}
// Sets the thread context as if the thread were unhijacked, regardless
// of whether it really is. See GetThreadContext above for more details
// on this abstraction
HRESULT CordbUnmanagedThread::SetThreadContext(DT_CONTEXT* pContext)
{
HRESULT hr = S_OK;
LOG((LF_CORDB, LL_INFO10000,
"CUT::STC: thread=0x%p, flags=0x%x.\n", this, pContext->ContextFlags));
LogContext(pContext);
// If the thread is first chance hijacked, then write the context into the remote process. If the thread is generic
// hijacked, then update the copy of the context that we already have. Otherwise call the normal Win32 function.
if (IsGenericHijacked() || IsFirstChanceHijacked() || IsRaiseExceptionHijacked())
{
if(IsGenericHijacked())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from generic/2nd chance hijack.\n"));
}
else if(IsFirstChanceHijacked())
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from 1st chance hijack.\n"));
}
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from RaiseException hijack.\n"));
}
SetState(CUTS_HasContextSet);
CORDbgCopyThreadContext(GetHijackCtx(), pContext);
}
else
{
LOG((LF_CORDB, LL_INFO10000, "CUT::STC: setting context from win32.\n"));
// If the user is also setting the SS flag then we no longer have to hide it
if(IsSSFlagEnabled(pContext))
{
ClearState(CUTS_IsSSFlagHidden);
}
// if the user is turning off the SS flag but we still want it on then leave it on
// but hidden
if(!IsSSFlagEnabled(pContext) && IsSSFlagNeeded())
{
SetState(CUTS_IsSSFlagHidden);
SetSSFlag(pContext);
}
BOOL succ = DbiSetThreadContext(m_handle, pContext);
if (!succ)
{
hr = HRESULT_FROM_GetLastError();
}
}
return hr;
}
// Turns on the stepping flag internally and tracks whether or not the flag
// should also be seen by the user
VOID CordbUnmanagedThread::BeginStepping()
{
_ASSERTE(!IsGenericHijacked() && !IsFirstChanceHijacked());
_ASSERTE(!IsSSFlagNeeded());
_ASSERTE(!IsSSFlagHidden());
DT_CONTEXT tempContext;
tempContext.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
if(!IsSSFlagEnabled(&tempContext))
{
SetSSFlag(&tempContext);
SetState(CUTS_IsSSFlagHidden);
}
SetState(CUTS_IsSSFlagNeeded);
succ = DbiSetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
}
// Turns off the stepping flag internally. If the user was also not using it then
// the flag is turned off on the context
VOID CordbUnmanagedThread::EndStepping()
{
_ASSERTE(!IsGenericHijacked() && !IsFirstChanceHijacked());
_ASSERTE(IsSSFlagNeeded());
DT_CONTEXT tempContext;
tempContext.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
if(IsSSFlagHidden())
{
UnsetSSFlag(&tempContext);
ClearState(CUTS_IsSSFlagHidden);
}
ClearState(CUTS_IsSSFlagNeeded);
succ = DbiSetThreadContext(m_handle, &tempContext);
_ASSERTE(succ);
}
// Writes some details of the given context into the debugger log
VOID CordbUnmanagedThread::LogContext(DT_CONTEXT* pContext)
{
#if defined(TARGET_X86)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Eip=0x%08x, Esp=0x%08x, Eflags=0x%08x\n", pContext->Eip, pContext->Esp,
pContext->EFlags));
#elif defined(TARGET_AMD64)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Rip=" FMT_ADDR ", Rsp=" FMT_ADDR ", Eflags=0x%08x\n",
DBG_ADDR(pContext->Rip),
DBG_ADDR(pContext->Rsp),
pContext->EFlags)); // EFlags is still 32bits on AMD64
#elif defined(TARGET_ARM64)
LOG((LF_CORDB, LL_INFO10000,
"CUT::LC: Pc=" FMT_ADDR ", Sp=" FMT_ADDR ", Lr=" FMT_ADDR ", Cpsr=" FMT_ADDR "\n",
DBG_ADDR(pContext->Pc),
DBG_ADDR(pContext->Sp),
DBG_ADDR(pContext->Lr),
DBG_ADDR(pContext->Cpsr)));
#else // TARGET_X86
PORTABILITY_ASSERT("LogContext needs a PC and stack pointer.");
#endif // TARGET_X86
}
// Hijacks this thread using the FirstChanceSuspend hijack
HRESULT CordbUnmanagedThread::SetupFirstChanceHijackForSync()
{
HRESULT hr = S_OK;
CONSISTENCY_CHECK(!IsBlockingForSync()); // Shouldn't double hijack
CONSISTENCY_CHECK(!IsCantStop()); // must be in stoppable-region.
_ASSERTE(HasIBEvent());
// We used to hijack for real here but now we have a vectored exception handler that will always be
// triggered. So we don't have hijack in the sense that we overwrite the thread's IP. However we still
// set the flag so that when we receive the HijackStartedSignal from the LS we know that this thread
// should block in there rather than continuing.
//hr = SetupFirstChanceHijack(EHijackReason::kFirstChanceSuspend, &(IBEvent()->m_currentDebugEvent.u.Exception.ExceptionRecord));
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// We'd better not be hijacking in a can't stop region!
// This also means we can't hijack in coopeative (since that's a can't-stop)
_ASSERTE(!IsCantStop());
// we should not be stepping into hijacks
_ASSERTE(!IsSSFlagHidden());
_ASSERTE(!IsSSFlagNeeded());
_ASSERTE(!IsContextSet());
// snapshot the current context so we can start spoofing it
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: hijackCtx started as:\n"));
LogContext(GetHijackCtx());
// Save the thread's full context.
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &context);
_ASSERTE(succ);
// for debugging when GetThreadContext fails
if(!succ)
{
DWORD error = GetLastError();
LOG((LF_CORDB, LL_ERROR, "CUT::SFCHFS: DbiGetThreadContext error=0x%x\n", error));
}
GetHijackCtx()->ContextFlags = DT_CONTEXT_FULL;
CORDbgCopyThreadContext(GetHijackCtx(), &context);
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: thread=0x%x Hijacking for sync. Original context is:\n", this));
LogContext(GetHijackCtx());
// We're hijacking now...
SetState(CUTS_FirstChanceHijacked);
GetProcess()->m_state |= CordbProcess::PS_HIJACKS_IN_PLACE;
// We'll decrement this once the hijack returns
GetProcess()->m_cFirstChanceHijackedThreads++;
this->SetState(CUTS_BlockingForSync);
// we don't want to single step into the vectored exception handler
// we will restore the SS flag after returning from the hijack
if(IsSSFlagEnabled(&context))
{
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCHFS: thread=0x%x Clearing SS flag\n", this));
UnsetSSFlag(&context);
succ = DbiSetThreadContext(m_handle, &context);
_ASSERTE(succ);
}
// There's a bizarre race where the thread was suspended right as the thread was about to dispatch a
// debug event. We still get the debug event, and then may try to hijack. Resume the thread so that
// it can run to the hijack.
if (this->IsSuspended())
{
LOG((LF_CORDB, LL_ERROR, "CUT::SFCHFS: thread was suspended... resuming\n"));
DWORD success = ResumeThread(this->m_handle);
if (success == 0xFFFFFFFF)
{
// Since we suspended it, we should be able to resume it in this window.
CONSISTENCY_CHECK_MSGF(false, ("Failed to resume thread: tid=0x%x!", this->m_id));
}
else
{
this->ClearState(CUTS_Suspended);
}
}
return hr;
}
HRESULT CordbUnmanagedThread::SetupFirstChanceHijack(EHijackReason::EHijackReason reason, const EXCEPTION_RECORD * pExceptionRecord)
{
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
// We'd better not be hijacking in a can't stop region!
// This also means we can't hijack in coopeative (since that's a can't-stop)
_ASSERTE(!IsCantStop());
// we should not be stepping into hijacks
_ASSERTE(!IsSSFlagHidden());
_ASSERTE(!IsSSFlagNeeded());
// There's a bizarre race where the thread was suspended right as the thread was about to dispatch a
// debug event. We still get the debug event, and then may try to hijack. Resume the thread so that
// it can run to the hijack.
if (this->IsSuspended())
{
DWORD succ = ResumeThread(this->m_handle);
if (succ == 0xFFFFFFFF)
{
// Since we suspended it, we should be able to resume it in this window.
CONSISTENCY_CHECK_MSGF(false, ("Failed to resume thread: tid=0x%x!", this->m_id));
}
else
{
this->ClearState(CUTS_Suspended);
}
}
HRESULT hr = S_OK;
EX_TRY
{
// We save off the SEH handler on X86 to make sure we restore it properly after the hijack is complete
// The hijacks don't return normally and the SEH chain might have handlers added that don't get removed by default
#ifdef TARGET_X86
hr = SaveCurrentLeafSeh();
if(FAILED(hr))
ThrowHR(hr);
#endif
CORDB_ADDRESS LSContextAddr;
GetProcess()->GetDAC()->Hijack(VMPTR_Thread::NullPtr(),
GetOSTid(),
pExceptionRecord,
(T_CONTEXT*) GetHijackCtx(),
sizeof(T_CONTEXT),
reason,
NULL,
&LSContextAddr);
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCH: pLeftSideContext=0x%p\n", LSContextAddr));
m_pLeftSideContext.Set(CORDB_ADDRESS_TO_PTR(LSContextAddr));
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO10000, "CUT::SFCH: Error setting up hijack context hr=0x%x\n", hr));
return hr;
}
// We're hijacked now...
SetState(CUTS_FirstChanceHijacked);
GetProcess()->m_state |= CordbProcess::PS_HIJACKS_IN_PLACE;
// We'll decrement this once the hijack returns
GetProcess()->m_cFirstChanceHijackedThreads++;
return S_OK;
}
HRESULT CordbUnmanagedThread::SetupGenericHijack(DWORD eventCode, const EXCEPTION_RECORD * pRecord)
{
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
_ASSERTE(eventCode == EXCEPTION_DEBUG_EVENT);
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(!IsContextSet());
// Save the thread's full context.
GetHijackCtx()->ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, GetHijackCtx());
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SGH: couldn't get thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
#if defined(TARGET_AMD64) || defined(TARGET_ARM64)
// On X86 Debugger::GenericHijackFunc() ensures the stack is walkable
// by simply using the EBP chain, therefore we can execute the hijack
// by setting the thread's context EIP to point to this function.
// On X64, however, we first attempt to set up a "proper" hijack, with
// a function that allows the OS to unwind the stack (ExceptionHijack).
// If this fails we'll use the same method as on X86, even though the
// stack will become un-walkable
ULONG32 dwThreadId = GetOSTid();
CordbThread * pThread = GetProcess()->TryLookupOrCreateThreadByVolatileOSId(dwThreadId);
// For threads in the thread store we set up the full size
// hijack, otherwise we fallback to hijacking by SetIP.
if (pThread != NULL)
{
HRESULT hr = S_OK;
EX_TRY
{
// Note that the data-target is not atomic, and we have no rollback mechanism.
// We have to do several writes. If the data-target fails the writes half-way through the
// target will be inconsistent.
GetProcess()->GetDAC()->Hijack(
pThread->m_vmThreadToken,
dwThreadId,
pRecord,
(T_CONTEXT*) GetHijackCtx(),
sizeof(T_CONTEXT),
EHijackReason::kGenericHijack,
NULL,
NULL);
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
// Remember that we've hijacked the thread.
SetState(CUTS_GenericHijacked);
return S_OK;
}
STRESS_LOG1(LF_CORDB, LL_INFO1000, "CUT::SGH: Error setting up hijack context hr=0x%x\n", hr);
// fallthrough (above hijack might have failed due to stack overflow, for example)
}
// else (non-threadstore threads) fallthrough
#endif // TARGET_AMD64 || defined(TARGET_ARM64)
// Remember that we've hijacked the thread.
SetState(CUTS_GenericHijacked);
LOG((LF_CORDB, LL_INFO1000000, "CUT::SGH: Current IP is 0x%08x\n", CORDbgGetIP(GetHijackCtx())));
DebuggerIPCRuntimeOffsets *pRO = &(GetProcess()->m_runtimeOffsets);
// Wack the IP over to our generic hijack function.
LPVOID holdIP = CORDbgGetIP(GetHijackCtx());
CORDbgSetIP(GetHijackCtx(), pRO->m_genericHijackFuncAddr);
LOG((LF_CORDB, LL_INFO1000000, "CUT::SGH: New IP is 0x%08x\n", CORDbgGetIP(GetHijackCtx())));
// We should never single step into the hijack
BOOL isSSFlagOn = IsSSFlagEnabled(GetHijackCtx());
if(isSSFlagOn)
{
UnsetSSFlag(GetHijackCtx());
}
succ = DbiSetThreadContext(m_handle, GetHijackCtx());
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::SGH: couldn't set thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
// Put the original IP back into the local context copy for later.
CORDbgSetIP(GetHijackCtx(), holdIP);
// Set the original SS flag into the local context copy for later
if(isSSFlagOn)
{
SetSSFlag(GetHijackCtx());
}
return S_OK;
}
HRESULT CordbUnmanagedThread::FixupFromGenericHijack()
{
LOG((LF_CORDB, LL_INFO1000, "CUT::FFGH: fixing up from generic hijack. Eip=0x%p, Esp=0x%p\n",
CORDbgGetIP(GetHijackCtx()), CORDbgGetSP(GetHijackCtx())));
// We're no longer hijacked
_ASSERTE(IsGenericHijacked());
ClearState(CUTS_GenericHijacked);
// Clear the exception so we do a DBG_CONTINUE with the original context. Note: we only do generic hijacks on
// in-band events.
IBEvent()->SetState(CUES_ExceptionCleared);
// Using the context we saved when the event came in originally or the new context if set by user,
// reset the thread as if it were never hijacked.
BOOL succ = DbiSetThreadContext(m_handle, GetHijackCtx());
// if the user set the context it has been applied now
ClearState(CUTS_HasContextSet);
if (!succ)
{
LOG((LF_CORDB, LL_INFO1000, "CUT::FFGH: couldn't set thread context: %d\n", GetLastError()));
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
DT_CONTEXT * CordbUnmanagedThread::GetHijackCtx()
{
return &m_context;
}
// Enable Single-Step (and bump the eip back one)
// This can only be called after a bp. (because we assume that we executed a bp when we adjust the eip).
HRESULT CordbUnmanagedThread::EnableSSAfterBP()
{
DT_CONTEXT c;
c.ContextFlags = DT_CONTEXT_FULL;
BOOL succ = DbiGetThreadContext(m_handle, &c);
if (!succ)
return HRESULT_FROM_WIN32(GetLastError());
SetSSFlag(&c);
// Backup IP to point to the instruction we need to execute. Continuing from a breakpoint exception
// continues execution at the instruction after the breakpoint, but we need to continue where the
// breakpoint was.
CORDbgAdjustPCForBreakInstruction(&c);
succ = DbiSetThreadContext(m_handle, &c);
if (!succ)
{
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
//
// FixupAfterOOBException automatically gets the debuggee past an OOB exception event. These are only BP or SS
// events. For SS, we just clear it, assuming that the only reason the thread was stepped in such place was to get it
// off of a BP. For a BP, we clear and backup the IP by one, and turn the trace flag on under the assumption that the
// only thing a debugger is allowed to do with an OOB BP exception is to get us off of it.
//
HRESULT CordbUnmanagedThread::FixupAfterOOBException(CordbUnmanagedEvent *ue)
{
// We really should only be doing things to single steps and breakpoint exceptions.
if (ue->m_currentDebugEvent.dwDebugEventCode == EXCEPTION_DEBUG_EVENT)
{
DWORD ec = ue->m_currentDebugEvent.u.Exception.ExceptionRecord.ExceptionCode;
if ((ec == STATUS_BREAKPOINT) || (ec == STATUS_SINGLE_STEP))
{
// Automatically clear the exception.
ue->SetState(CUES_ExceptionCleared);
// Don't bother about toggling the single-step flag. OOB BPs should only be called
// for raw int3 instructions, so no need to rewind and reexecute.
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Setup to skip an native breakpoint
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::SetupForSkipBreakpoint(NativePatch * pNativePatch)
{
_ASSERTE(pNativePatch != NULL);
_ASSERTE(!IsSkippingNativePatch());
_ASSERTE(m_pPatchSkipAddress == NULL);
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
SetState(CUTS_SkippingNativePatch);
#ifdef _DEBUG
// For debugging, provide a way that Cordbg devs can see if we're silently skipping BPs.
static DWORD fTrapOnSkip = -1;
if (fTrapOnSkip == -1)
fTrapOnSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgTrapOnSkip);
if (fTrapOnSkip)
{
CONSISTENCY_CHECK_MSGF(false, ("The CLR is skipping a native BP at %p on thread 0x%x (%d)."
"\nYou're getting this notification in debug builds b/c you have com+ var 'DbgTrapOnSkip' enabled.",
pNativePatch->pAddress, this->m_id, this->m_id));
// We skipped this BP b/c IsCantStop was true. For debugging convenience, call IsCantStop here
// (in case we break at the assert above and want to trace why we're in a CS region)
bool fCantStop = this->IsCantStop();
LOG((LF_CORDB, LL_INFO1000, "In Can'tStopRegion = %d\n", fCantStop));
// Refresh the reg key
fTrapOnSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgTrapOnSkip);
}
#endif
#if defined(TARGET_X86)
STRESS_LOG2(LF_CORDB, LL_INFO100, "CUT::SetupSkip. addr=%p. Opcode=%x\n", pNativePatch->pAddress, (DWORD) pNativePatch->opcode);
#endif
// Replace the BP w/ the opcode.
RemoveRemotePatch(GetProcess(), pNativePatch->pAddress, pNativePatch->opcode);
// Enable the SS flag & Adjust IP.
HRESULT hr = this->EnableSSAfterBP();
SIMPLIFYING_ASSUMPTION(SUCCEEDED(hr));
// Now we return,
// Process continues, LS will single step past BP, and fire a SS exception.
// When we get the SS, we res
// We need to remember this so we can make sure we fixup at the proper address.
// The address of a ss exception is the instruction we finish on, not where
// we originally placed the BP. Since instructions can be variable length,
// we can't work backwards.
m_pPatchSkipAddress = pNativePatch->pAddress;
}
//-----------------------------------------------------------------------------
// Second half of skipping a native bp.
// Note we pass the address in b/c our caller has (from the debug_evet), and
// we don't want to waste storage to remember it ourselves.
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::FixupForSkipBreakpoint()
{
_ASSERTE(m_pPatchSkipAddress != NULL);
_ASSERTE(IsSkippingNativePatch());
_ASSERTE(GetProcess()->ThreadHoldsProcessLock());
ClearState(CUTS_SkippingNativePatch);
// Only reapply the int3 if it hasn't been removed yet.
if (GetProcess()->GetNativePatch(m_pPatchSkipAddress) != NULL)
{
ApplyRemotePatch(GetProcess(), m_pPatchSkipAddress);
STRESS_LOG1(LF_CORDB, LL_INFO100, "CUT::FixupSetupSkip. addr=%p\n", m_pPatchSkipAddress);
}
else
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "CUT::FixupSetupSkip. Patch removed. Not-reading. addr=%p\n", m_pPatchSkipAddress);
}
m_pPatchSkipAddress = NULL;
}
inline TADDR GetSP(DT_CONTEXT* context)
{
#if defined(TARGET_X86)
return (TADDR)context->Esp;
#elif defined(TARGET_AMD64)
return (TADDR)context->Rsp;
#elif defined(TARGET_ARM) || defined(TARGET_ARM64)
return (TADDR)context->Sp;
#else
_ASSERTE(!"nyi for platform");
#endif
}
BOOL CordbUnmanagedThread::GetStackRange(CORDB_ADDRESS *pBase, CORDB_ADDRESS *pLimit)
{
#if !defined(FEATURE_DBGIPC_TRANSPORT)
if (m_stackBase == 0 && m_stackLimit == 0)
{
HANDLE hProc;
DT_CONTEXT tempContext;
MEMORY_BASIC_INFORMATION mbi;
tempContext.ContextFlags = DT_CONTEXT_FULL;
if (SUCCEEDED(GetProcess()->GetHandle(&hProc)) &&
SUCCEEDED(GetThreadContext(&tempContext)) &&
::VirtualQueryEx(hProc, (LPCVOID)GetSP(&tempContext), &mbi, sizeof(mbi)) != 0)
{
// the lowest stack address is the AllocationBase
TADDR limit = PTR_TO_TADDR(mbi.AllocationBase);
// Now, on to find the stack base:
// Closest to the AllocationBase we might have a MEM_RESERVED block
// for all the as yet unallocated pages...
TADDR regionBase = limit;
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_RESERVE)
regionBase += mbi.RegionSize;
// Next we might have a few guard pages
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_COMMIT && (mbi.Protect & PAGE_GUARD) != 0)
regionBase += mbi.RegionSize;
// And finally the "regular" stack region
if (::VirtualQueryEx(hProc, (LPCVOID) regionBase, &mbi, sizeof(mbi)) == 0
|| mbi.Type != MEM_PRIVATE)
goto Exit;
if (mbi.State == MEM_COMMIT && (mbi.Protect & PAGE_READWRITE) != 0)
regionBase += mbi.RegionSize;
if (limit == regionBase)
goto Exit;
m_stackLimit = limit;
m_stackBase = regionBase;
}
}
Exit:
if (pBase != NULL)
*pBase = m_stackBase;
if (pLimit != NULL)
*pLimit = m_stackLimit;
return (m_stackBase != 0 || m_stackLimit != 0);
#else
if (pBase != NULL)
*pBase = 0;
if (pLimit != NULL)
*pLimit = 0;
return FALSE;
#endif // FEATURE_DBGIPC_TRANSPORT
}
//-----------------------------------------------------------------------------
// Returns the thread context to the state it was in when it last entered RaiseException
// This allows the thread to retrigger an exception caused by RaiseException
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::HijackToRaiseException()
{
LOG((LF_CORDB, LL_INFO1000, "CP::HTRE: hijacking to RaiseException\n"));
_ASSERTE(HasRaiseExceptionEntryCtx());
_ASSERTE(!IsRaiseExceptionHijacked());
_ASSERTE(!IsGenericHijacked());
_ASSERTE(!IsFirstChanceHijacked());
_ASSERTE(!IsContextSet());
BOOL succ = DbiGetThreadContext(m_handle, GetHijackCtx());
_ASSERTE(succ);
succ = DbiSetThreadContext(m_handle, &m_raiseExceptionEntryContext);
_ASSERTE(succ);
SetState(CUTS_IsRaiseExceptionHijacked);
}
//----------------------------------------------------------------------------
// Returns the context to its unhijacked state.
//----------------------------------------------------------------------------
void CordbUnmanagedThread::RestoreFromRaiseExceptionHijack()
{
LOG((LF_CORDB, LL_INFO1000, "CP::RFREH: ending RaiseException hijack\n"));
_ASSERTE(IsRaiseExceptionHijacked());
DT_CONTEXT restoreContext;
restoreContext.ContextFlags = DT_CONTEXT_FULL;
HRESULT hr = GetThreadContext(&restoreContext);
_ASSERTE(SUCCEEDED(hr));
ClearState(CUTS_IsRaiseExceptionHijacked);
hr = SetThreadContext(&restoreContext);
_ASSERTE(SUCCEEDED(hr));
}
//-----------------------------------------------------------------------------
// Attempts to store the state of a thread currently entering RaiseException
// This grabs both a full context and enough state to determine what exception
// RaiseException should be raising. If any of the state can not be retrieved
// then this entrance to RaiseException is silently ignored
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::SaveRaiseExceptionEntryContext()
{
_ASSERTE(FALSE); // should be unused now
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: saving raise exception context.\n"));
_ASSERTE(!HasRaiseExceptionEntryCtx());
_ASSERTE(!IsRaiseExceptionHijacked());
HRESULT hr = S_OK;
DT_CONTEXT context;
context.ContextFlags = DT_CONTEXT_FULL;
DbiGetThreadContext(m_handle, &context);
// if the flag is set, unset it
// we don't want to be single stepping through RaiseException the second time
// sending out OOB SS events. Ultimately we will rethrow the exception which would
// cleared the SS flag anyways.
UnsetSSFlag(&context);
memcpy(&m_raiseExceptionEntryContext, &context, sizeof(DT_CONTEXT));
// calculate the exception that we would expect to come from this invocation of RaiseException
REMOTE_PTR pExceptionInformation = NULL;
#if defined(TARGET_AMD64)
m_raiseExceptionExceptionCode = (DWORD)m_raiseExceptionEntryContext.Rcx;
m_raiseExceptionExceptionFlags = (DWORD)m_raiseExceptionEntryContext.Rdx;
m_raiseExceptionNumberParameters = (DWORD)m_raiseExceptionEntryContext.R8;
pExceptionInformation = (REMOTE_PTR)m_raiseExceptionEntryContext.R9;
#elif defined(TARGET_ARM64)
m_raiseExceptionExceptionCode = (DWORD)m_raiseExceptionEntryContext.X0;
m_raiseExceptionExceptionFlags = (DWORD)m_raiseExceptionEntryContext.X1;
m_raiseExceptionNumberParameters = (DWORD)m_raiseExceptionEntryContext.X2;
pExceptionInformation = (REMOTE_PTR)m_raiseExceptionEntryContext.X3;
#elif defined(TARGET_X86)
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+4), &m_raiseExceptionExceptionCode);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception code.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+8), &m_raiseExceptionExceptionFlags);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception flags.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+12), &m_raiseExceptionNumberParameters);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read number of parameters.\n"));
return;
}
hr = m_pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS((BYTE*)m_raiseExceptionEntryContext.Esp+16), &pExceptionInformation);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception information pointer.\n"));
return;
}
#else
_ASSERTE(!"Implement this for your platform");
return;
#endif
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: RaiseException parameters are 0x%x 0x%x 0x%x 0x%p.\n",
m_raiseExceptionExceptionCode, m_raiseExceptionExceptionFlags,
m_raiseExceptionNumberParameters, pExceptionInformation));
TargetBuffer exceptionInfoTargetBuffer(pExceptionInformation, sizeof(REMOTE_PTR)*m_raiseExceptionNumberParameters);
EX_TRY
{
m_pProcess->SafeReadBuffer(exceptionInfoTargetBuffer, (BYTE*)m_raiseExceptionExceptionInformation);
}
EX_CATCH_HRESULT(hr);
if(FAILED(hr))
{
LOG((LF_CORDB, LL_INFO1000, "CP::SREEC: failed to read exception information.\n"));
return;
}
// If everything was succesful then set this flag, otherwise none of the above data is considered valid
SetState(CUTS_HasRaiseExceptionEntryCtx);
return;
}
//-----------------------------------------------------------------------------
// Clears all the state saved in SaveRaiseExceptionContext and returns the thread
// to the state as if RaiseException has yet to be called. This is typically called
// after an exception retriggers or after determining that the exception never will
// retrigger.
//-----------------------------------------------------------------------------
void CordbUnmanagedThread::ClearRaiseExceptionEntryContext()
{
_ASSERTE(FALSE); // should be unused now
LOG((LF_CORDB, LL_INFO1000, "CP::CREEC: clearing raise exception context.\n"));
_ASSERTE(HasRaiseExceptionEntryCtx());
ClearState(CUTS_HasRaiseExceptionEntryCtx);
}
//-----------------------------------------------------------------------------
// Uses a heuristic to determine if the given exception record is likely to be the exception
// raised by the last invocation of RaiseException on this thread. The current heuristic compares
// ExceptionCode, ExceptionFlags, and all ExceptionInformation.
//-----------------------------------------------------------------------------
BOOL CordbUnmanagedThread::IsExceptionFromLastRaiseException(const EXCEPTION_RECORD* pExceptionRecord)
{
_ASSERTE(FALSE); // should be unused now
if(!HasRaiseExceptionEntryCtx())
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - no previous raise context\n"));
return FALSE;
}
if (pExceptionRecord->ExceptionCode != m_raiseExceptionExceptionCode)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - exception codes differ 0x%x 0x%x\n",
pExceptionRecord->ExceptionCode, m_raiseExceptionExceptionCode));
return FALSE;
}
if (pExceptionRecord->ExceptionFlags != m_raiseExceptionExceptionFlags)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - exception flags differ 0x%x 0x%x\n",
pExceptionRecord->ExceptionFlags, m_raiseExceptionExceptionFlags));
return FALSE;
}
if (pExceptionRecord->NumberParameters != m_raiseExceptionNumberParameters)
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - number parameters differ 0x%x 0x%x\n",
pExceptionRecord->NumberParameters, m_raiseExceptionNumberParameters));
return FALSE;
}
for(DWORD i = 0; i < pExceptionRecord->NumberParameters; i++)
{
if(m_raiseExceptionExceptionInformation[i] != pExceptionRecord->ExceptionInformation[i])
{
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: not a match - param %d differs 0x%x 0x%x\n",
i, pExceptionRecord->ExceptionInformation[i], m_raiseExceptionExceptionInformation[i]));
return FALSE;
}
}
LOG((LF_CORDB, LL_INFO1000, "CP::IEFLRE: match\n"));
return TRUE;
}
//-----------------------------------------------------------------------------
// Inject an int3 at the given remote address
//-----------------------------------------------------------------------------
// This flavor is assuming our caller already knows the opcode.
HRESULT ApplyRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
const BYTE patch = CORDbg_BREAK_INSTRUCTION;
#elif defined(TARGET_ARM64)
const PRD_TYPE patch = CORDbg_BREAK_INSTRUCTION;
#else
const BYTE patch = 0;
PORTABILITY_ASSERT("NYI: ApplyRemotePatch for this platform");
#endif
HRESULT hr = pProcess->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &patch);
SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr);
return S_OK;
}
// Get the opcode that we're replacing.
HRESULT ApplyRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress, PRD_TYPE * pOpcode)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// Read out opcode. 1 byte on x86
BYTE opcode;
#elif defined(TARGET_ARM64)
// Read out opcode. 4 bytes on arm64
PRD_TYPE opcode;
#else
BYTE opcode;
PORTABILITY_ASSERT("NYI: ApplyRemotePatch for this platform");
#endif
HRESULT hr = pProcess->SafeReadStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &opcode);
if (FAILED(hr))
{
return hr;
}
*pOpcode = (PRD_TYPE) opcode;
ApplyRemotePatch(pProcess, pRemoteAddress);
return S_OK;
}
//-----------------------------------------------------------------------------
// Remove the int3 from the remote address
//-----------------------------------------------------------------------------
HRESULT RemoveRemotePatch(CordbProcess * pProcess, const void * pRemoteAddress, PRD_TYPE opcode)
{
#if defined(TARGET_X86) || defined(TARGET_AMD64)
// Replace the BP w/ the opcode.
BYTE opcode2 = (BYTE) opcode;
#elif defined(TARGET_ARM64)
// 4 bytes on arm64
PRD_TYPE opcode2 = opcode;
#else
PRD_TYPE opcode2 = opcode;
PORTABILITY_ASSERT("NYI: RemoveRemotePatch for this platform");
#endif
pProcess->SafeWriteStruct(PTR_TO_CORDB_ADDRESS(pRemoteAddress), &opcode2);
// This may fail because the module has been unloaded. In which case, the patch is also
// gone so it makes sense to return success.
return S_OK;
}
#endif // FEATURE_INTEROP_DEBUGGING
//---------------------------------------------------------------------------------------
//
// Simple helper to return the SP value stored in a DebuggerREGDISPLAY.
//
// Arguments:
// pDRD - the DebuggerREGDISPLAY in question
//
// Return Value:
// the SP value
//
inline CORDB_ADDRESS GetSPFromDebuggerREGDISPLAY(DebuggerREGDISPLAY* pDRD)
{
return pDRD->SP;
}
HRESULT CordbContext::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugContext)
*pInterface = static_cast<ICorDebugContext*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugContext*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
/* ------------------------------------------------------------------------- *
* Frame class
* ------------------------------------------------------------------------- */
// This is just used as a proxy object to pass a FramePointer around.
CordbFrame::CordbFrame(CordbProcess * pProcess, FramePointer fp)
: CordbBase(pProcess, 0, enumCordbFrame),
m_fp(fp)
{
UnsafeNeuterDeadObject(); // mark as neutered.
}
CordbFrame::CordbFrame(CordbThread * pThread,
FramePointer fp,
SIZE_T ip,
CordbAppDomain * pCurrentAppDomain)
: CordbBase(pThread->GetProcess(), 0, enumCordbFrame),
m_ip(ip),
m_pThread(pThread),
m_currentAppDomain(pCurrentAppDomain),
m_fp(fp)
{
#ifdef _DEBUG
// For debugging purposes, track what Continue session these frames were created in.
m_DbgContinueCounter = GetProcess()->m_continueCounter;
#endif
HRESULT hr = S_OK;
EX_TRY
{
m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
CordbFrame::~CordbFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by DerivedClasses
void CordbFrame::Neuter()
{
CordbBase::Neuter();
}
HRESULT CordbFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
*pInterface = static_cast<ICorDebugFrame*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugFrame*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetChain
//
// Description:
// Return the owning chain. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the owning chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
// Return E_FAIL if failed to find the chain
//
HRESULT CordbFrame::GetChain(ICorDebugChain **ppChain)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppChain);
*ppChain = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetChainForFrame(static_cast<ICorDebugFrame *>(this), ppChain);
if (*ppChain == NULL)
hr = E_FAIL;
}
else
{
// This is the Arrowhead case, where ICDChain has been deprecated.
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the stack range taken up by this frame.
// Note that this is not implemented in the base CordbFrame class.
// Instead, this is implemented by the derived classes.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Notes: see code:#GetStackRange
HRESULT CordbFrame::GetStackRange(CORDB_ADDRESS *pStart, CORDB_ADDRESS *pEnd)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(pStart);
ValidateOrThrow(pEnd);
hr = E_NOTIMPL;
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the ICorDebugFunction associated with this frame.
// There is one ICorDebugFunction for each EnC version of a method.
HRESULT CordbFrame::GetFunction(ICorDebugFunction **ppFunction)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFunction);
CordbFunction * pFunc = this->GetFunction();
if (pFunc == NULL)
{
ThrowHR(CORDBG_E_CODE_NOT_AVAILABLE);
}
// @dbgtodo LCG methods, IL stubs, dynamic language debugging
// Don't return an ICDFunction if we are dealing with a dynamic method.
// The dynamic debugging feature crew needs to decide exactly what to hand out for dynamic methods.
if (pFunc->GetMetadataToken() == mdMethodDefNil)
{
ThrowHR(CORDBG_E_CODE_NOT_AVAILABLE);
}
*ppFunction = static_cast<ICorDebugFunction *>(pFunc);
pFunc->ExternalAddRef();
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Return the token of the ICorDebugFunction associated with this frame.
// There is one ICorDebugFunction for each EnC version of a method.
HRESULT CordbFrame::GetFunctionToken(mdMethodDef *pToken)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(pToken);
CordbFunction * pFunc = GetFunction();
if (pFunc == NULL)
{
hr = CORDBG_E_CODE_NOT_AVAILABLE;
}
else
{
*pToken = pFunc->GetMetadataToken();
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetCaller
//
// Description:
// Return the caller of this frame. The caller is closer to the root.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the caller frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbFrame::GetCaller(ICorDebugFrame **ppFrame)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFrame);
*ppFrame = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetCallerForFrame(this, ppFrame);
}
else
{
*ppFrame = NULL;
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbFrame::GetCallee
//
// Description:
// Return the callee of this frame. The callee is closer to the leaf.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the callee frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbFrame::GetCallee(ICorDebugFrame **ppFrame)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
ValidateOrThrow(ppFrame);
*ppFrame = NULL;
if (GetProcess()->GetShim() != NULL)
{
PUBLIC_CALLBACK_IN_THIS_SCOPE0(GetProcess(), GET_PUBLIC_LOCK_HOLDER());
ShimStackWalk * pSSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
pSSW->GetCalleeForFrame(static_cast<ICorDebugFrame *>(this), ppFrame);
}
else
{
*ppFrame = NULL;
hr = E_NOTIMPL;
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
// Create a stepper on the frame.
HRESULT CordbFrame::CreateStepper(ICorDebugStepper **ppStepper)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppStepper, ICorDebugStepper **);
HRESULT hr = S_OK;
EX_TRY
{
RSInitHolder<CordbStepper> pStepper(new CordbStepper(m_pThread, this));
pStepper.TransferOwnershipExternal(ppStepper);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given a frame pointer, determine if it is in the stack range owned by the frame.
//
// Arguments:
// fp - frame pointer to check
//
// Return Value:
// whether the specified frame pointer is in the stack range or not
//
bool CordbFrame::IsContainedInFrame(FramePointer fp)
{
CORDB_ADDRESS stackStart;
CORDB_ADDRESS stackEnd;
// get the stack range
HRESULT hr;
hr = GetStackRange(&stackStart, &stackEnd);
_ASSERTE(SUCCEEDED(hr));
CORDB_ADDRESS sp = PTR_TO_CORDB_ADDRESS(fp.GetSPValue());
if ((stackStart <= sp) && (sp <= stackEnd))
{
return true;
}
else
{
return false;
}
}
//---------------------------------------------------------------------------------------
//
// Given an ICorDebugFrame interface pointer, return a pointer to the base class CordbFrame.
//
// Arguments:
// pFrame - the ICorDebugFrame interface pointer
//
// Return Value:
// the CordbFrame pointer corresponding to the specified interface pointer
//
// Note:
// This is currently only used for continuable exceptions.
//
// static
CordbFrame* CordbFrame::GetCordbFrameFromInterface(ICorDebugFrame *pFrame)
{
CordbFrame* pTargetFrame = NULL;
if (pFrame != NULL)
{
// test for CordbNativeFrame
RSExtSmartPtr<ICorDebugNativeFrame> pNativeFrame;
pFrame->QueryInterface(IID_ICorDebugNativeFrame, (void**)&pNativeFrame);
if (pNativeFrame != NULL)
{
pTargetFrame = static_cast<CordbFrame*>(static_cast<CordbNativeFrame*>(pNativeFrame.GetValue()));
}
else
{
// test for CordbJITILFrame
RSExtSmartPtr<ICorDebugILFrame> pILFrame;
pFrame->QueryInterface(IID_ICorDebugILFrame, (void**)&pILFrame);
if (pILFrame != NULL)
{
pTargetFrame = (static_cast<CordbJITILFrame*>(pILFrame.GetValue()))->m_nativeFrame;
}
else
{
// test for CordbInternalFrame
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
pFrame->QueryInterface(IID_ICorDebugInternalFrame, (void**)&pInternalFrame);
if (pInternalFrame != NULL)
{
pTargetFrame = static_cast<CordbFrame*>(static_cast<CordbInternalFrame*>(pInternalFrame.GetValue()));
}
else
{
// when all else fails, this is just a CordbFrame
pTargetFrame = static_cast<CordbFrame*>(pFrame);
}
}
}
}
return pTargetFrame;
}
/* ------------------------------------------------------------------------- *
* Value Enumerator class
*
* Used by CordbJITILFrame for EnumLocalVars & EnumArgs.
* NOTE NOTE NOTE WE ASSUME that the 'frame' argument is actually the
* CordbJITILFrame's native frame member variable.
* ------------------------------------------------------------------------- */
CordbValueEnum::CordbValueEnum(CordbNativeFrame *frame, ValueEnumMode mode) :
CordbBase(frame->GetProcess(), 0)
{
_ASSERTE( frame != NULL );
_ASSERTE( mode == LOCAL_VARS_ORIGINAL_IL || mode == LOCAL_VARS_REJIT_IL || mode == ARGS);
m_frame = frame;
m_mode = mode;
m_iCurrent = 0;
m_iMax = 0;
}
/*
* CordbValueEnum::Init
*
* Initialize a CordbValueEnum object. Must be called after allocating the object and before using it. If Init
* fails, then destroy the object and release the memory.
*
* Parameters:
* none.
*
* Returns:
* HRESULT for success or failure.
*
*/
HRESULT CordbValueEnum::Init()
{
HRESULT hr = S_OK;
CordbNativeFrame *nil = m_frame;
CordbJITILFrame *jil = nil->m_JITILFrame;
switch (m_mode)
{
case ARGS:
{
// Get the function signature
CordbFunction *func = m_frame->GetFunction();
ULONG methodArgCount;
IfFailRet(func->GetSig(NULL, &methodArgCount, NULL));
// Grab the argument count for the size of the enumeration.
m_iMax = methodArgCount;
if (jil->m_fVarArgFnx && !jil->m_sigParserCached.IsNull())
{
m_iMax = jil->m_allArgsCount;
}
break;
}
case LOCAL_VARS_ORIGINAL_IL:
{
// Get the locals signature.
ULONG localsCount;
IfFailRet(jil->GetOriginalILCode()->GetLocalVarSig(NULL, &localsCount));
// Grab the number of locals for the size of the enumeration.
m_iMax = localsCount;
break;
}
case LOCAL_VARS_REJIT_IL:
{
// Get the locals signature.
ULONG localsCount;
CordbReJitILCode* pCode = jil->GetReJitILCode();
if (pCode == NULL)
{
m_iMax = 0;
}
else
{
IfFailRet(pCode->GetLocalVarSig(NULL, &localsCount));
// Grab the number of locals for the size of the enumeration.
m_iMax = localsCount;
}
break;
}
}
// Everything worked okay, so add this object to the neuter list for objects that are tied to the stack trace.
EX_TRY
{
m_frame->m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
return hr;
}
CordbValueEnum::~CordbValueEnum()
{
_ASSERTE(this->IsNeutered());
_ASSERTE(m_frame == NULL);
}
void CordbValueEnum::Neuter()
{
m_frame = NULL;
CordbBase::Neuter();
}
HRESULT CordbValueEnum::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEnum)
*pInterface = static_cast<ICorDebugEnum*>(this);
else if (id == IID_ICorDebugValueEnum)
*pInterface = static_cast<ICorDebugValueEnum*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugValueEnum*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbValueEnum::Skip(ULONG celt)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = E_FAIL;
if ( (m_iCurrent+celt) < m_iMax ||
celt == 0)
{
m_iCurrent += celt;
hr = S_OK;
}
return hr;
}
HRESULT CordbValueEnum::Reset()
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
m_iCurrent = 0;
return S_OK;
}
HRESULT CordbValueEnum::Clone(ICorDebugEnum **ppEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppEnum, ICorDebugEnum **);
HRESULT hr = S_OK;
EX_TRY
{
*ppEnum = NULL;
RSInitHolder<CordbValueEnum> pCVE(new CordbValueEnum(m_frame, m_mode));
// Initialize the new enum
hr = pCVE->Init();
IfFailThrow(hr);
pCVE.TransferOwnershipExternal(ppEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbValueEnum::GetCount(ULONG *pcelt)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(pcelt, ULONG *);
if( pcelt == NULL)
{
return E_INVALIDARG;
}
(*pcelt) = m_iMax;
return S_OK;
}
//
// In the event of failure, the current pointer will be left at
// one element past the troublesome element. Thus, if one were
// to repeatedly ask for one element to iterate through the
// array, you would iterate exactly m_iMax times, regardless
// of individual failures.
HRESULT CordbValueEnum::Next(ULONG celt, ICorDebugValue *values[], ULONG *pceltFetched)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(values, ICorDebugValue *,
celt, true, true);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pceltFetched, ULONG *);
if ((pceltFetched == NULL) && (celt != 1))
{
return E_INVALIDARG;
}
if (celt == 0)
{
if (pceltFetched != NULL)
{
*pceltFetched = 0;
}
return S_OK;
}
HRESULT hr = S_OK;
int iMax = min( m_iMax, m_iCurrent+celt);
int i;
for (i = m_iCurrent; i< iMax;i++)
{
switch ( m_mode )
{
case ARGS:
{
hr = m_frame->m_JITILFrame->GetArgument( i, &(values[i-m_iCurrent]) );
break;
}
case LOCAL_VARS_ORIGINAL_IL:
{
hr = m_frame->m_JITILFrame->GetLocalVariableEx(ILCODE_ORIGINAL_IL, i, &(values[i-m_iCurrent]) );
break;
}
case LOCAL_VARS_REJIT_IL:
{
hr = m_frame->m_JITILFrame->GetLocalVariableEx(ILCODE_REJIT_IL, i, &(values[i - m_iCurrent]));
break;
}
}
if ( FAILED( hr ) )
{
break;
}
}
int count = (i - m_iCurrent);
if ( FAILED( hr ) )
{
//
// we failed: +1 pushes us past troublesome element
//
m_iCurrent += 1 + count;
}
else
{
m_iCurrent += count;
}
if (pceltFetched != NULL)
{
*pceltFetched = count;
}
if (FAILED(hr))
{
return hr;
}
//
// If we reached the end of the enumeration, but not the end
// of the number of requested items, we return S_FALSE.
//
if (((ULONG)count) < celt)
{
return S_FALSE;
}
return hr;
}
//-----------------------------------------------------------------------------
// CordbInternalFrame
//-----------------------------------------------------------------------------
CordbInternalFrame::CordbInternalFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
const DebuggerIPCE_STRData * pData)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain)
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
m_eFrameType = pData->stubFrame.frameType;
m_funcMetadataToken = pData->stubFrame.funcMetadataToken;
m_vmMethodDesc = pData->stubFrame.vmMethodDesc;
// Some internal frames may not have a Function associated w/ them.
if (!IsNilToken(m_funcMetadataToken))
{
// Find the module of the function. Note that this module isn't necessarily in the same domain as our frame.
// FuncEval frames can point to methods they are going to invoke in another domain.
CordbModule * pModule = NULL;
pModule = GetProcess()->LookupOrCreateModule(pData->stubFrame.vmDomainAssembly);
_ASSERTE(pModule != NULL);
//
if( pModule != NULL )
{
_ASSERTE( (pModule->GetAppDomain() == pCurrentAppDomain) || (m_eFrameType == STUBFRAME_FUNC_EVAL) );
mdMethodDef token = pData->stubFrame.funcMetadataToken;
// @dbgtodo synchronization - push this up.
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// CordbInternalFrame could handle a null function.
// But if we fail to lookup, things are not in a good state anyways.
CordbFunction * pFunction = pModule->LookupOrCreateFunctionLatestVersion(token);
m_function.Assign(pFunction);
}
}
}
CordbInternalFrame::CordbInternalFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
CorDebugInternalFrameType frameType,
mdMethodDef funcMetadataToken,
CordbFunction * pFunction,
VMPTR_MethodDesc vmMethodDesc)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain)
{
m_eFrameType = frameType;
m_funcMetadataToken = funcMetadataToken;
m_function.Assign(pFunction);
m_vmMethodDesc = vmMethodDesc;
}
HRESULT CordbInternalFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugInternalFrame*>(this));
}
else if (id == IID_ICorDebugInternalFrame)
{
*pInterface = static_cast<ICorDebugInternalFrame*>(this);
}
else if (id == IID_ICorDebugInternalFrame2)
{
*pInterface = static_cast<ICorDebugInternalFrame2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugInternalFrame*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
void CordbInternalFrame::Neuter()
{
m_function.Clear();
CordbFrame::Neuter();
}
// ----------------------------------------------------------------------------
// CordbInternalFrame::GetStackRange
//
// Description:
// Return the stack range owned by this frame.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes:
// #GetStackRange
// This is a virtual function and so there are multiple implementations for different types of frames.
// It's very important to note that GetStackRange() can work when even after the frame is neutered.
// Debuggers may rely on this to map old frames up to new frames across Continue() calls.
//
HRESULT CordbInternalFrame::GetStackRange(CORDB_ADDRESS *pStart,
CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// Callers explicit require GetStackRange() to be callable when neutered so that they
// can line up ICorDebugFrame objects across continues. We only return stack ranges
// here and don't access any special data.
OK_IF_NEUTERED(this);
if (GetProcess()->GetShim() != NULL)
{
CORDB_ADDRESS pFramePointer = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
if (pStart)
{
*pStart = pFramePointer;
}
if (pEnd)
{
*pEnd = pFramePointer;
}
return S_OK;
}
else
{
if (pStart != NULL)
{
*pStart = NULL;
}
if (pEnd != NULL)
{
*pEnd = NULL;
}
return E_NOTIMPL;
}
}
// This may return NULL if there's no Method associated w/ this Frame.
// For FuncEval frames, the function returned might also be in a different AppDomain
// than the frame itself.
CordbFunction * CordbInternalFrame::GetFunction()
{
return m_function;
}
// Accessor for the shim private hook code:CordbThread::ConvertFrameForILMethodWithoutMetadata.
// Refer to that function for comments on the return value, the argument, etc.
BOOL CordbInternalFrame::ConvertInternalFrameForILMethodWithoutMetadata(
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
// The only internal frame conversion we need to perform is from STUBFRAME_JIT_COMPILATION to
// STUBFRAME_LIGTHWEIGHT_FUNCTION.
if (m_eFrameType != STUBFRAME_JIT_COMPILATION)
{
return FALSE;
}
// Check whether the internal frame has an associated MethodDesc.
// Currently, the only STUBFRAME_JIT_COMPILATION frame with a NULL MethodDesc is ComPrestubMethodFrame,
// which is not exposed in Whidbey. So convert it according to rule #2 below.
if (m_vmMethodDesc.IsNull())
{
return TRUE;
}
// Retrieve the type of the method associated with the STUBFRAME_JIT_COMPILATION.
IDacDbiInterface::DynamicMethodType type = GetProcess()->GetDAC()->IsILStubOrLCGMethod(m_vmMethodDesc);
// Here are the conversion rules:
// 1) For a normal managed method, we don't convert, and we return FALSE.
// 2) For an IL stub, we convert to NULL, and we return TRUE.
// 3) For a dynamic method, we convert to a STUBFRAME_LIGHTWEIGHT_FUNCTION, and we return TRUE.
if (type == IDacDbiInterface::kNone)
{
return FALSE;
}
else if (type == IDacDbiInterface::kILStub)
{
return TRUE;
}
else if (type == IDacDbiInterface::kLCGMethod)
{
// Here we are basically cloning another CordbInternalFrame.
RSInitHolder<CordbInternalFrame> pInternalFrame(new CordbInternalFrame(m_pThread,
m_fp,
m_currentAppDomain,
STUBFRAME_LIGHTWEIGHT_FUNCTION,
m_funcMetadataToken,
m_function.GetValue(),
m_vmMethodDesc));
pInternalFrame.TransferOwnershipExternal(ppInternalFrame2);
return TRUE;
}
UNREACHABLE();
}
//---------------------------------------------------------------------------------------
//
// Returns the address of an internal frame. The address is a stack pointer, even on IA64.
//
// Arguments:
// pAddress - out parameter; return the frame marker address
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if pAddress is NULL.
//
HRESULT CordbInternalFrame::GetAddress(CORDB_ADDRESS * pAddress)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (pAddress == NULL)
{
return E_INVALIDARG;
}
*pAddress = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Refer to the comment for code:CordbInternalFrame::IsCloserToLeaf
//
BOOL CordbInternalFrame::IsCloserToLeafWorker(ICorDebugFrame * pFrameToCompare)
{
// Get the address of the "this" internal frame.
CORDB_ADDRESS thisFrameAddr = PTR_TO_CORDB_ADDRESS(this->GetFramePointer().GetSPValue());
// Note that a QI on ICorDebugJITILFrame for ICorDebugNativeFrame will work.
RSExtSmartPtr<ICorDebugNativeFrame> pNativeFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugNativeFrame, (void **)&pNativeFrame);
if (pNativeFrame != NULL)
{
// The frame to compare is a CordbNativeFrame.
CordbNativeFrame * pCNativeFrame = static_cast<CordbNativeFrame *>(pNativeFrame.GetValue());
// Compare the address of the "this" internal frame to the SP of the stack frame.
// We can't compare frame pointers because the frame pointer means different things on
// different platforms.
CORDB_ADDRESS stackFrameSP = GetSPFromDebuggerREGDISPLAY(&(pCNativeFrame->m_rd));
return (thisFrameAddr < stackFrameSP);
}
RSExtSmartPtr<ICorDebugRuntimeUnwindableFrame> pRUFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugRuntimeUnwindableFrame, (void **)&pRUFrame);
if (pRUFrame != NULL)
{
// The frame to compare is a CordbRuntimeUnwindableFrame.
CordbRuntimeUnwindableFrame * pCRUFrame =
static_cast<CordbRuntimeUnwindableFrame *>(pRUFrame.GetValue());
DT_CONTEXT * pResumeContext = const_cast<DT_CONTEXT *>(pCRUFrame->GetContext());
CORDB_ADDRESS stackFrameSP = PTR_TO_CORDB_ADDRESS(CORDbgGetSP(pResumeContext));
return (thisFrameAddr < stackFrameSP);
}
RSExtSmartPtr<ICorDebugInternalFrame> pInternalFrame;
pFrameToCompare->QueryInterface(IID_ICorDebugInternalFrame, (void **)&pInternalFrame);
if (pInternalFrame != NULL)
{
// The frame to compare is a CordbInternalFrame.
CordbInternalFrame * pCInternalFrame =
static_cast<CordbInternalFrame *>(pInternalFrame.GetValue());
CORDB_ADDRESS frameAddr = PTR_TO_CORDB_ADDRESS(pCInternalFrame->GetFramePointer().GetSPValue());
return (thisFrameAddr < frameAddr);
}
// What does this mean? This is unexpected.
_ASSERTE(!"CIF::ICTLW - Unexpected frame type.\n");
ThrowHR(E_FAIL);
}
//---------------------------------------------------------------------------------------
//
// Checks whether the "this" internal frame is closer to the leaf than the specified ICDFrame.
// If the specified ICDFrame represents a stack frame, then we compare the address of the "this"
// internal frame against the SP of the stack frame.
//
// Arguments:
// pFrameToCompare - the ICDFrame to compare against
// pIsCloser - out parameter; returns TRUE if the "this" internal frame is closer to the leaf
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if pFrameToCompare or pIsCloser is NULL.
// E_FAIL if pFrameToCompare is bogus.
//
// Notes:
// This function doesn't deal with the backing store at all.
//
HRESULT CordbInternalFrame::IsCloserToLeaf(ICorDebugFrame * pFrameToCompare,
BOOL * pIsCloser)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this);
{
ValidateOrThrow(pFrameToCompare);
ValidateOrThrow(pIsCloser);
*pIsCloser = IsCloserToLeafWorker(pFrameToCompare);
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
CordbRuntimeUnwindableFrame::CordbRuntimeUnwindableFrame(CordbThread * pThread,
FramePointer fp,
CordbAppDomain * pCurrentAppDomain,
DT_CONTEXT * pContext)
: CordbFrame(pThread, fp, 0, pCurrentAppDomain),
m_context(*pContext)
{
}
void CordbRuntimeUnwindableFrame::Neuter()
{
CordbFrame::Neuter();
}
HRESULT CordbRuntimeUnwindableFrame::QueryInterface(REFIID id, void ** ppInterface)
{
if (id == IID_ICorDebugFrame)
{
*ppInterface = static_cast<ICorDebugFrame *>(static_cast<ICorDebugRuntimeUnwindableFrame *>(this));
}
else if (id == IID_ICorDebugRuntimeUnwindableFrame)
{
*ppInterface = static_cast<ICorDebugRuntimeUnwindableFrame *>(this);
}
else if (id == IID_IUnknown)
{
*ppInterface = static_cast<IUnknown *>(static_cast<ICorDebugRuntimeUnwindableFrame *>(this));
}
else
{
*ppInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Returns the CONTEXT corresponding to this CordbRuntimeUnwindableFrame.
//
// Return Value:
// Return a pointer to the CONTEXT.
//
const DT_CONTEXT * CordbRuntimeUnwindableFrame::GetContext() const
{
return &m_context;
}
// default constructor to make the compiler happy
CordbMiscFrame::CordbMiscFrame()
{
#ifdef FEATURE_EH_FUNCLETS
this->parentIP = 0;
this->fpParentOrSelf = LEAF_MOST_FRAME;
this->fIsFilterFunclet = false;
#endif // FEATURE_EH_FUNCLETS
}
// the real constructor which stores the funclet-related information in the CordbMiscFrame
CordbMiscFrame::CordbMiscFrame(DebuggerIPCE_JITFuncData * pJITFuncData)
{
#ifdef FEATURE_EH_FUNCLETS
this->parentIP = pJITFuncData->parentNativeOffset;
this->fpParentOrSelf = pJITFuncData->fpParentOrSelf;
this->fIsFilterFunclet = (pJITFuncData->fIsFilterFrame == TRUE);
#endif // FEATURE_EH_FUNCLETS
}
/* ------------------------------------------------------------------------- *
* Native Frame class
* ------------------------------------------------------------------------- */
CordbNativeFrame::CordbNativeFrame(CordbThread * pThread,
FramePointer fp,
CordbNativeCode * pNativeCode,
SIZE_T ip,
DebuggerREGDISPLAY * pDRD,
TADDR taAmbientESP,
bool fQuicklyUnwound,
CordbAppDomain * pCurrentAppDomain,
CordbMiscFrame * pMisc /*= NULL*/,
DT_CONTEXT * pContext /*= NULL*/)
: CordbFrame(pThread, fp, ip, pCurrentAppDomain),
m_rd(*pDRD),
m_quicklyUnwound(fQuicklyUnwound),
m_JITILFrame(NULL),
m_nativeCode(pNativeCode), // implicit InternalAddRef
m_taAmbientESP(taAmbientESP)
{
m_misc = *pMisc;
// Only new CordbNativeFrames created by the new stackwalk contain a CONTEXT.
_ASSERTE(pContext != NULL);
m_context = *pContext;
}
/*
A list of which resources owned by this object are accounted for.
RESOLVED:
CordbJITILFrame* m_JITILFrame; // Neutered
*/
CordbNativeFrame::~CordbNativeFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by CordbThread::CleanupStack
void CordbNativeFrame::Neuter()
{
// Neuter may be called multiple times so be sure to set ptrs to NULL so that we don't
// double release them.
if (IsNeutered())
{
return;
}
m_nativeCode.Clear();
if (m_JITILFrame != NULL)
{
m_JITILFrame->Neuter();
m_JITILFrame.Clear();
}
CordbFrame::Neuter();
}
// CordbNativeFrame::QueryInterface
//
// Description
// interface query for this COM object
//
// NOTE: the COM object associated with this CordbNativeFrame may consist of
// two C++ objects (the CordbNativeFrame and the CordbJITILFrame).
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
//
HRESULT CordbNativeFrame::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(static_cast<ICorDebugNativeFrame*>(this));
}
else if (id == IID_ICorDebugNativeFrame)
{
*pInterface = static_cast<ICorDebugNativeFrame*>(this);
}
else if (id == IID_ICorDebugNativeFrame2)
{
*pInterface = static_cast<ICorDebugNativeFrame2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugNativeFrame*>(this));
}
else
{
// might be searching for an IL Frame. delegate that search to the
// JITILFrame
if (m_JITILFrame != NULL)
{
return m_JITILFrame->QueryInterfaceInternal(id, pInterface);
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
}
ExternalAddRef();
return S_OK;
}
// Return the CordbNativeCode object associated with this native frame.
// This is just a wrapper around the real helper.
HRESULT CordbNativeFrame::GetCode(ICorDebugCode **ppCode)
{
PUBLIC_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppCode, ICorDebugCode **);
FAIL_IF_NEUTERED(this);
CordbNativeCode * pCode = GetNativeCode();
*ppCode = static_cast<ICorDebugCode*> (pCode);
pCode->ExternalAddRef();
return S_OK;;
}
//---------------------------------------------------------------------------------------
//
// Returns the CONTEXT corresponding to this CordbNativeFrame.
//
// Return Value:
// Return a pointer to the CONTEXT.
//
const DT_CONTEXT * CordbNativeFrame::GetContext() const
{
return &m_context;
}
//---------------------------------------------------------------------------------------
//
// This is an internal helper to get the CordbNativeCode object associated with this native frame.
//
// Return Value:
// the associated CordbNativeCode object
//
CordbNativeCode * CordbNativeFrame::GetNativeCode()
{
return this->m_nativeCode;
}
//---------------------------------------------------------------------------------------
//
// This is an internal helper to get the CordbFunction object associated with this native frame.
//
// Return Value:
// the associated CordbFunction object
//
CordbFunction *CordbNativeFrame::GetFunction()
{
return this->m_nativeCode->GetFunction();
}
// Return the native offset.
HRESULT CordbNativeFrame::GetIP(ULONG32 *pnOffset)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pnOffset, ULONG32 *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*pnOffset = (ULONG32)m_ip;
return S_OK;
}
ULONG32 CordbNativeFrame::GetIPOffset()
{
return (ULONG32)m_ip;
}
TADDR CordbNativeFrame::GetReturnRegisterValue()
{
#if defined(TARGET_X86)
return (TADDR)m_context.Eax;
#elif defined(TARGET_AMD64)
return (TADDR)m_context.Rax;
#elif defined(TARGET_ARM)
return (TADDR)m_context.R0;
#elif defined(TARGET_ARM64)
return (TADDR)m_context.X0;
#else
_ASSERTE(!"nyi for platform");
return 0;
#endif
}
// Determine if we can set IP at this point. The specified offset is the native offset.
HRESULT CordbNativeFrame::CanSetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (!IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
hr = m_pThread->SetIP(SetIP_fCanSetIPOnly,
m_nativeCode,
nOffset,
SetIP_fNative );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Try to set the IP to the specified offset. The specified offset is the native offset.
HRESULT CordbNativeFrame::SetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
if (!IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
hr = m_pThread->SetIP(SetIP_fSetIP,
m_nativeCode,
nOffset,
SetIP_fNative );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Given a (register,offset) description of a stack location, compute
// the real memory address for it.
// This will also handle ambient SP values (which are encoded with regNum == REGNUM_AMBIENT_SP).
CORDB_ADDRESS CordbNativeFrame::GetLSStackAddress(
ICorDebugInfo::RegNum regNum,
signed offset)
{
UINT_PTR *pRegAddr;
CORDB_ADDRESS pRemoteValue;
if (regNum != DBG_TARGET_REGNUM_AMBIENT_SP)
{
// Even if we're inside a funclet, variables (in both x64 and ARM) are still
// relative to the frame pointer or stack pointer, which are accurate in the
// funclet, after the funclet prolog; the frame pointer is re-established in the
// funclet prolog using the PSP. Thus, we just look up the frame pointer in the
// current native frame.
pRegAddr = this->GetAddressOfRegister(
ConvertRegNumToCorDebugRegister(regNum));
// This should never be null as long as regNum is a member of the RegNum enum.
// If it is, an AV dereferencing a null-pointer in retail builds, or an assert in debug
// builds is exactly the behavior we want.
PREFIX_ASSUME(pRegAddr != NULL);
pRemoteValue = PTR_TO_CORDB_ADDRESS(*pRegAddr + offset);
}
else
{
// Use the ambient ESP. At this point we're decoding an ambient-sp var, so
// we should definitely have an ambient-sp. If this is null, then the jit
// likely gave us an inconsistent data.
TADDR taAmbient = this->GetAmbientESP();
_ASSERTE(taAmbient != NULL);
pRemoteValue = PTR_TO_CORDB_ADDRESS(taAmbient + offset);
}
return pRemoteValue;
}
// ----------------------------------------------------------------------------
// CordbNativeFrame::GetStackRange
//
// Description:
// Return the stack range owned by this native frame.
// The start of the stack range is the leafmost boundary, and the end is the rootmost boundary.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes: see code:#GetStackRange
HRESULT CordbNativeFrame::GetStackRange(CORDB_ADDRESS *pStart,
CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// Callers explicit require GetStackRange() to be callable when neutered so that they
// can line up ICorDebugFrame objects across continues. We only return stack ranges
// here and don't access any special data.
OK_IF_NEUTERED(this);
if (GetProcess()->GetShim() != NULL)
{
if (pStart)
{
// From register set.
*pStart = GetSPFromDebuggerREGDISPLAY(&m_rd);
}
if (pEnd)
{
// The rootmost boundary is the frame pointer.
// <NOTE>
// This is not true on AMD64, on which we use the stack pointer as the frame pointer.
// </NOTE>
*pEnd = PTR_TO_CORDB_ADDRESS(GetFramePointer().GetSPValue());
}
return S_OK;
}
else
{
if (pStart != NULL)
{
*pStart = NULL;
}
if (pEnd != NULL)
{
*pEnd = NULL;
}
return E_NOTIMPL;
}
}
// Return the register set of the native frame.
HRESULT CordbNativeFrame::GetRegisterSet(ICorDebugRegisterSet **ppRegisters)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppRegisters, ICorDebugRegisterSet **);
HRESULT hr = S_OK;
EX_TRY
{
// allocate a new CordbRegisterSet object
RSInitHolder<CordbRegisterSet> pRegisterSet(new CordbRegisterSet(&m_rd,
m_pThread,
IsLeafFrame(),
m_quicklyUnwound));
pRegisterSet.TransferOwnershipExternal(ppRegisters);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Checks whether the frame is a child frame or not.
//
// Arguments:
// pIsChild - out parameter; returns whether the frame is a child frame
//
// Return Value:
// S_OK on success.
// E_INVALIDARG if the out parmater is NULL.
//
HRESULT CordbNativeFrame::IsChild(BOOL * pIsChild)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_BEGIN(this)
{
if (pIsChild == NULL)
{
ThrowHR(E_INVALIDARG);
}
else
{
*pIsChild = ((this->IsFunclet() && !this->IsFilterFunclet()) ? TRUE : FALSE);
}
}
PUBLIC_REENTRANT_API_END(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Given an ICDNativeFrame2, check whether it is the parent frame of the current frame.
//
// Arguments:
// pPotentialParentFrame - the ICDNativeFrame2 to check
// pIsParent - out paramter; returns whether the specified frame is indeed the parent frame
//
// Return Value:
// S_OK on success.
// CORDBG_E_NOT_CHILD_FRAME if the current frame is not a child frame.
// E_INVALIDARG if either of the incoming argument is NULL.
// E_FAIL on other failures.
//
HRESULT CordbNativeFrame::IsMatchingParentFrame(ICorDebugNativeFrame2 * pPotentialParentFrame,
BOOL * pIsParent)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pPotentialParentFrame, ICorDebugNativeFrame2 *);
HRESULT hr = S_OK;
EX_TRY
{
if ((pPotentialParentFrame == NULL) || (pIsParent == NULL))
{
ThrowHR(E_INVALIDARG);
}
*pIsParent = FALSE;
if (!this->IsFunclet())
{
ThrowHR(CORDBG_E_NOT_CHILD_FRAME);
}
#ifdef FEATURE_EH_FUNCLETS
CordbNativeFrame * pFrameToCheck = static_cast<CordbNativeFrame *>(pPotentialParentFrame);
if (pFrameToCheck->IsFunclet())
{
*pIsParent = FALSE;
}
else
{
FramePointer fpParent = this->m_misc.fpParentOrSelf;
FramePointer fpToCheck = pFrameToCheck->m_misc.fpParentOrSelf;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pIsParent = pDAC->IsMatchingParentFrame(fpToCheck, fpParent);
}
#endif // FEATURE_EH_FUNCLETS
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// Return the stack parameter size of the current frame. Since this information is only used on x86,
// we return S_FALSE and a size of 0 on WIN64 platforms.
//
// Arguments:
// pSize - out parameter; return the size of the stack parameter
//
// Return Value:
// S_OK on success.
// S_FALSE on WIN64 platforms.
// E_INVALIDARG if pSize is NULL.
//
// Notes:
// Always return S_FALSE on WIN64.
//
HRESULT CordbNativeFrame::GetStackParameterSize(ULONG32 * pSize)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
EX_TRY
{
if (pSize == NULL)
{
ThrowHR(E_INVALIDARG);
}
#if defined(TARGET_X86)
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
*pSize = pDAC->GetStackParameterSize(PTR_TO_CORDB_ADDRESS(CORDbgGetIP(&m_context)));
#else // !TARGET_X86
hr = S_FALSE;
*pSize = 0;
#endif // TARGET_X86
}
EX_CATCH_HRESULT(hr);
return hr;
}
//
// GetAddressOfRegister returns the address of the given register in the
// frame's current register display (eg, a local address). This is usually used to build a
// ICorDebugValue from.
//
UINT_PTR * CordbNativeFrame::GetAddressOfRegister(CorDebugRegister regNum) const
{
UINT_PTR* ret = NULL;
switch (regNum)
{
case REGISTER_STACK_POINTER:
ret = (UINT_PTR*)GetSPAddress(&m_rd);
break;
#if !defined(TARGET_AMD64) && !defined(TARGET_ARM) // @ARMTODO
case REGISTER_FRAME_POINTER:
ret = (UINT_PTR*)GetFPAddress(&m_rd);
break;
#endif
#if defined(TARGET_X86)
case REGISTER_X86_EAX:
ret = (UINT_PTR*)&m_rd.Eax;
break;
case REGISTER_X86_ECX:
ret = (UINT_PTR*)&m_rd.Ecx;
break;
case REGISTER_X86_EDX:
ret = (UINT_PTR*)&m_rd.Edx;
break;
case REGISTER_X86_EBX:
ret = (UINT_PTR*)&m_rd.Ebx;
break;
case REGISTER_X86_ESI:
ret = (UINT_PTR*)&m_rd.Esi;
break;
case REGISTER_X86_EDI:
ret = (UINT_PTR*)&m_rd.Edi;
break;
#elif defined(TARGET_AMD64)
case REGISTER_AMD64_RBP:
ret = (UINT_PTR*)&m_rd.Rbp;
break;
case REGISTER_AMD64_RAX:
ret = (UINT_PTR*)&m_rd.Rax;
break;
case REGISTER_AMD64_RCX:
ret = (UINT_PTR*)&m_rd.Rcx;
break;
case REGISTER_AMD64_RDX:
ret = (UINT_PTR*)&m_rd.Rdx;
break;
case REGISTER_AMD64_RBX:
ret = (UINT_PTR*)&m_rd.Rbx;
break;
case REGISTER_AMD64_RSI:
ret = (UINT_PTR*)&m_rd.Rsi;
break;
case REGISTER_AMD64_RDI:
ret = (UINT_PTR*)&m_rd.Rdi;
break;
case REGISTER_AMD64_R8:
ret = (UINT_PTR*)&m_rd.R8;
break;
case REGISTER_AMD64_R9:
ret = (UINT_PTR*)&m_rd.R9;
break;
case REGISTER_AMD64_R10:
ret = (UINT_PTR*)&m_rd.R10;
break;
case REGISTER_AMD64_R11:
ret = (UINT_PTR*)&m_rd.R11;
break;
case REGISTER_AMD64_R12:
ret = (UINT_PTR*)&m_rd.R12;
break;
case REGISTER_AMD64_R13:
ret = (UINT_PTR*)&m_rd.R13;
break;
case REGISTER_AMD64_R14:
ret = (UINT_PTR*)&m_rd.R14;
break;
case REGISTER_AMD64_R15:
ret = (UINT_PTR*)&m_rd.R15;
break;
#elif defined(TARGET_ARM)
case REGISTER_ARM_R0:
ret = (UINT_PTR*)&m_rd.R0;
break;
case REGISTER_ARM_R1:
ret = (UINT_PTR*)&m_rd.R1;
break;
case REGISTER_ARM_R2:
ret = (UINT_PTR*)&m_rd.R2;
break;
case REGISTER_ARM_R3:
ret = (UINT_PTR*)&m_rd.R3;
break;
case REGISTER_ARM_R4:
ret = (UINT_PTR*)&m_rd.R4;
break;
case REGISTER_ARM_R5:
ret = (UINT_PTR*)&m_rd.R5;
break;
case REGISTER_ARM_R6:
ret = (UINT_PTR*)&m_rd.R6;
break;
case REGISTER_ARM_R7:
ret = (UINT_PTR*)&m_rd.R7;
break;
case REGISTER_ARM_R8:
ret = (UINT_PTR*)&m_rd.R8;
break;
case REGISTER_ARM_R9:
ret = (UINT_PTR*)&m_rd.R9;
break;
case REGISTER_ARM_R10:
ret = (UINT_PTR*)&m_rd.R10;
break;
case REGISTER_ARM_R11:
ret = (UINT_PTR*)&m_rd.R11;
break;
case REGISTER_ARM_R12:
ret = (UINT_PTR*)&m_rd.R12;
break;
case REGISTER_ARM_LR:
ret = (UINT_PTR*)&m_rd.LR;
break;
case REGISTER_ARM_PC:
ret = (UINT_PTR*)&m_rd.PC;
break;
#elif defined(TARGET_ARM64)
case REGISTER_ARM64_X0:
case REGISTER_ARM64_X1:
case REGISTER_ARM64_X2:
case REGISTER_ARM64_X3:
case REGISTER_ARM64_X4:
case REGISTER_ARM64_X5:
case REGISTER_ARM64_X6:
case REGISTER_ARM64_X7:
case REGISTER_ARM64_X8:
case REGISTER_ARM64_X9:
case REGISTER_ARM64_X10:
case REGISTER_ARM64_X11:
case REGISTER_ARM64_X12:
case REGISTER_ARM64_X13:
case REGISTER_ARM64_X14:
case REGISTER_ARM64_X15:
case REGISTER_ARM64_X16:
case REGISTER_ARM64_X17:
case REGISTER_ARM64_X18:
case REGISTER_ARM64_X19:
case REGISTER_ARM64_X20:
case REGISTER_ARM64_X21:
case REGISTER_ARM64_X22:
case REGISTER_ARM64_X23:
case REGISTER_ARM64_X24:
case REGISTER_ARM64_X25:
case REGISTER_ARM64_X26:
case REGISTER_ARM64_X27:
case REGISTER_ARM64_X28:
ret = (UINT_PTR*)&m_rd.X[regNum - REGISTER_ARM64_X0];
break;
case REGISTER_ARM64_LR:
ret = (UINT_PTR*)&m_rd.LR;
break;
case REGISTER_ARM64_PC:
ret = (UINT_PTR*)&m_rd.PC;
break;
#endif
default:
_ASSERT(!"Invalid register number!");
}
return ret;
}
//
// GetLeftSideAddressOfRegister returns the Left Side address of the given register in the frames current register
// display.
//
CORDB_ADDRESS CordbNativeFrame::GetLeftSideAddressOfRegister(CorDebugRegister regNum) const
{
#if !defined(USE_REMOTE_REGISTER_ADDRESS)
// Use marker values as the register address. This is to implement the funceval breaking change.
//
if (IsLeafFrame())
{
return kLeafFrameRegAddr;
}
else
{
return kNonLeafFrameRegAddr;
}
#else // USE_REMOTE_REGISTER_ADDRESS
void* ret = 0;
switch (regNum)
{
#if !defined(TARGET_AMD64)
case REGISTER_FRAME_POINTER:
ret = m_rd.pFP;
break;
#endif
#if defined(TARGET_X86)
case REGISTER_X86_EAX:
ret = m_rd.pEax;
break;
case REGISTER_X86_ECX:
ret = m_rd.pEcx;
break;
case REGISTER_X86_EDX:
ret = m_rd.pEdx;
break;
case REGISTER_X86_EBX:
ret = m_rd.pEbx;
break;
case REGISTER_X86_ESI:
ret = m_rd.pEsi;
break;
case REGISTER_X86_EDI:
ret = m_rd.pEdi;
break;
#elif defined(TARGET_AMD64)
case REGISTER_AMD64_RBP:
ret = m_rd.pRbp;
break;
case REGISTER_AMD64_RAX:
ret = m_rd.pRax;
break;
case REGISTER_AMD64_RCX:
ret = m_rd.pRcx;
break;
case REGISTER_AMD64_RDX:
ret = m_rd.pRdx;
break;
case REGISTER_AMD64_RBX:
ret = m_rd.pRbx;
break;
case REGISTER_AMD64_RSI:
ret = m_rd.pRsi;
break;
case REGISTER_AMD64_RDI:
ret = m_rd.pRdi;
break;
case REGISTER_AMD64_R8:
ret = m_rd.pR8;
break;
case REGISTER_AMD64_R9:
ret = m_rd.pR9;
break;
case REGISTER_AMD64_R10:
ret = m_rd.pR10;
break;
case REGISTER_AMD64_R11:
ret = m_rd.pR11;
break;
case REGISTER_AMD64_R12:
ret = m_rd.pR12;
break;
case REGISTER_AMD64_R13:
ret = m_rd.pR13;
break;
case REGISTER_AMD64_R14:
ret = m_rd.pR14;
break;
case REGISTER_AMD64_R15:
ret = m_rd.pR15;
break;
#endif
default:
_ASSERT(!"Invalid register number!");
}
return PTR_TO_CORDB_ADDRESS(ret);
#endif // !USE_REMOTE_REGISTER_ADDRESS
}
//---------------------------------------------------------------------------------------
//
// Given the native variable information of a variable, return its value.
//
// Arguments:
// pNativeVarInfo - the variable information of the variable to be retrieved
//
// Returns:
// Return the specified value.
// Throw on error.
//
// Assumption:
// This function assumes that the value is either in a register or on the stack
// (i.e. VLT_REG or VLT_STK).
//
// Notes:
// Eventually we should make this more general-purpose.
//
SIZE_T CordbNativeFrame::GetRegisterOrStackValue(const ICorDebugInfo::NativeVarInfo * pNativeVarInfo)
{
SIZE_T uResult;
if (pNativeVarInfo->loc.vlType == ICorDebugInfo::VLT_REG)
{
CorDebugRegister reg = ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg);
uResult = *(reinterpret_cast<SIZE_T *>(GetAddressOfRegister(reg)));
}
else if (pNativeVarInfo->loc.vlType == ICorDebugInfo::VLT_STK)
{
CORDB_ADDRESS remoteAddr = GetLSStackAddress(pNativeVarInfo->loc.vlStk.vlsBaseReg,
pNativeVarInfo->loc.vlStk.vlsOffset);
HRESULT hr = GetProcess()->SafeReadStruct(remoteAddr, &uResult);
IfFailThrow(hr);
}
else
{
ThrowHR(E_FAIL);
}
return uResult;
}
//---------------------------------------------------------------------------------------
//
// Looks in a register and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// reg - The register to use.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, false);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalRegisterValue(reg, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Looks in two registers and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - The register to use for the high word.
// lowWordReg - The register to use for the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalDoubleRegisterValue(CorDebugRegister highWordReg,
CorDebugRegister lowWordReg,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalDoubleRegisterValue(highWordReg, lowWordReg, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses an address and retrieves the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// address - A local memory address.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, false);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryValue(address, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses a register and an address, retrieving the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - Register to use as the high word.
// lowWordAddress - A local memory address containing the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg,
CORDB_ADDRESS lowWordAddress,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, true);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalRegisterMemoryValue(highWordReg, lowWordAddress, pType, ppValue);
}
//---------------------------------------------------------------------------------------
//
// Uses a register and an address, retrieving the value as a specific type, returning it
// as an ICorDebugValue.
//
// Arguments:
// highWordReg - A local memory address to use as the high word.
// lowWordAddress - Register containing the low word.
// cbSigBlob - The number of bytes in the signature given.
// pvSigBlob - A signature stream that describes the type of the value in the register.
// ppValue - OUT: Space to store the resulting ICorDebugValue
//
// Returns:
// S_OK on success, else an error code.
//
HRESULT CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress,
CorDebugRegister lowWordRegister,
ULONG cbSigBlob,
PCCOR_SIGNATURE pvSigBlob,
ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (cbSigBlob == 0)
{
return E_INVALIDARG;
}
VALIDATE_POINTER_TO_OBJECT_ARRAY(pvSigBlob, BYTE, cbSigBlob, true, true);
CordbType * pType;
SigParser sigParser(pvSigBlob, cbSigBlob);
Instantiation emptyInst;
HRESULT hr = CordbType::SigToType(m_JITILFrame->GetModule(), &sigParser, &emptyInst, &pType);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryRegisterValue(highWordAddress, lowWordRegister, pType, ppValue);
}
HRESULT CordbNativeFrame::GetLocalRegisterValue(CorDebugRegister reg,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
#if defined(TARGET_X86) || defined(TARGET_64BIT)
#if defined(TARGET_X86)
if ((reg >= REGISTER_X86_FPSTACK_0) && (reg <= REGISTER_X86_FPSTACK_7))
#elif defined(TARGET_AMD64)
if ((reg >= REGISTER_AMD64_XMM0) && (reg <= REGISTER_AMD64_XMM15))
#elif defined(TARGET_ARM64)
if ((reg >= REGISTER_ARM64_V0) && (reg <= REGISTER_ARM64_V31))
#endif
{
return GetLocalFloatingPointValue(reg, pType, ppValue);
}
#endif
// The address of the given register is the address of the value
// in this process. We have no remote address here.
void *pLocalValue = (void*)GetAddressOfRegister(reg);
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegValueHome(this, reg));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
ICorDebugValue *pValue;
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(pLocalValue, REG_SIZE),
pRegHolder,
&pValue); // throws
*ppValue = pValue;
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbNativeFrame::GetLocalDoubleRegisterValue(
CorDebugRegister highWordReg,
CorDebugRegister lowWordReg,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegRegValueHome(this, highWordReg, lowWordReg));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
// sanity check object size
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
//
// nickbe
// 10/31/2002 11:09:42
//
// This assert assumes that the JIT will only partially enregister
// objects that have a size equal to twice the size of a register.
//
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT
CordbNativeFrame::GetLocalMemoryValue(CORDB_ADDRESS address,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
_ASSERTE(m_nativeCode->GetFunction() != NULL);
HRESULT hr = S_OK;
ICorDebugValue *pValue;
EX_TRY
{
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
TargetBuffer(address, CordbValue::GetSizeForType(pType, kUnboxed)),
MemoryRange(NULL, 0),
NULL,
&pValue); // throws
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
*ppValue = pValue;
return hr;
}
HRESULT
CordbNativeFrame::GetLocalByRefMemoryValue(CORDB_ADDRESS address,
CordbType * pType,
ICorDebugValue **ppValue)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
LPVOID actualAddress = NULL;
HRESULT hr = GetProcess()->SafeReadStruct(address, &actualAddress);
if (FAILED(hr))
{
return hr;
}
return GetLocalMemoryValue(PTR_TO_CORDB_ADDRESS(actualAddress), pType, ppValue);
}
HRESULT
CordbNativeFrame::GetLocalRegisterMemoryValue(CorDebugRegister highWordReg,
CORDB_ADDRESS lowWordAddress,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new RegMemValueHome(this,
highWordReg,
lowWordAddress));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
// See the comment in CordbNativeFrame::GetLocalDoubleRegisterValue
// for more information on this assertion
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT
CordbNativeFrame::GetLocalMemoryRegisterValue(CORDB_ADDRESS highWordAddress,
CorDebugRegister lowWordRegister,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new MemRegValueHome(this,
lowWordRegister,
highWordAddress));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(NULL, 0),
pRegHolder,
ppValue); // throws
}
EX_CATCH_HRESULT(hr);
#ifdef _DEBUG
{
if (SUCCEEDED(hr))
{
ULONG32 objectSize;
hr = (*ppValue)->GetSize(&objectSize);
_ASSERTE(SUCCEEDED(hr));
// See the comment in CordbNativeFrame::GetLocalDoubleRegisterValue
// for more information on this assertion
_ASSERTE(objectSize == 2 * sizeof(void*));
}
}
#endif
return hr;
}
HRESULT CordbNativeFrame::GetLocalFloatingPointValue(DWORD index,
CordbType * pType,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
CorElementType et = pType->m_elementType;
if ((et != ELEMENT_TYPE_R4) &&
(et != ELEMENT_TYPE_R8))
return E_INVALIDARG;
#if defined(TARGET_AMD64)
if (!((index >= REGISTER_AMD64_XMM0) &&
(index <= REGISTER_AMD64_XMM15)))
return E_INVALIDARG;
index -= REGISTER_AMD64_XMM0;
#elif defined(TARGET_ARM64)
if (!((index >= REGISTER_ARM64_V0) &&
(index <= REGISTER_ARM64_V31)))
return E_INVALIDARG;
index -= REGISTER_ARM64_V0;
#elif defined(TARGET_ARM)
if (!((index >= REGISTER_ARM_D0) &&
(index <= REGISTER_ARM_D31)))
return E_INVALIDARG;
index -= REGISTER_ARM_D0;
#else
if (!((index >= REGISTER_X86_FPSTACK_0) &&
(index <= REGISTER_X86_FPSTACK_7)))
return E_INVALIDARG;
index -= REGISTER_X86_FPSTACK_0;
#endif
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Make sure the thread's floating point stack state is loaded
// over from the left side.
//
CordbThread *pThread = m_pThread;
EX_TRY
{
if (!pThread->m_fFloatStateValid)
{
pThread->LoadFloatState();
}
}
EX_CATCH_HRESULT(hr);
if (SUCCEEDED(hr))
{
#if !defined(TARGET_64BIT)
// This is needed on x86 because we are dealing with a stack.
index = pThread->m_floatStackTop - index;
#endif
if (index >= (sizeof(pThread->m_floatValues) /
sizeof(pThread->m_floatValues[0])))
return E_INVALIDARG;
#ifdef TARGET_X86
// A workaround (sort of) to get around the difference in format between
// a float value and a double value. We can't simply cast a double pointer to
// a float pointer. Instead, we have to cast the double itself to a float.
if (pType->m_elementType == ELEMENT_TYPE_R4)
*(float *)&(pThread->m_floatValues[index]) = (float)pThread->m_floatValues[index];
#endif
ICorDebugValue* pValue;
EX_TRY
{
// Provide the register info as we create the value. CreateValueByType will transfer ownership of this to
// the new instance of CordbValue.
EnregisteredValueHomeHolder pRemoteReg(new FloatRegValueHome(this, index));
EnregisteredValueHomeHolder * pRegHolder = pRemoteReg.GetAddr();
CordbValue::CreateValueByType(GetCurrentAppDomain(),
pType,
false,
EMPTY_BUFFER,
MemoryRange(&(pThread->m_floatValues[index]), sizeof(double)),
pRegHolder,
&pValue); // throws
*ppValue = pValue;
}
EX_CATCH_HRESULT(hr);
}
return hr;
}
//---------------------------------------------------------------------------------------
//
// Quick accessor to tell if we're the leaf frame.
//
// Return Value:
// whether we are the leaf frame or not
//
bool CordbNativeFrame::IsLeafFrame() const
{
CONTRACTL
{
THROWS;
}
CONTRACTL_END;
// Should only be called by non-neutered stuff.
// Also, since we're not neutered, we know we have a Thread object, and we know it's state is current.
_ASSERTE(!this->IsNeutered());
// If the thread's state is sleeping, then there's no frame below us, but we're actually
// not the leaf frame.
// @todo- consider having Sleep / Wait / Join be an ICDInternalFrame.
_ASSERTE(m_pThread != NULL); // not neutered, so should have a thread
if (m_pThread->IsThreadWaitingOrSleeping())
{
return false;
}
if (!m_optfIsLeafFrame.HasValue())
{
if (GetProcess()->GetShim() != NULL)
{
// In V2, the definition of "leaf frame" is the leaf frame in the leaf chain in the stackwalk.
PRIVATE_SHIM_CALLBACK_IN_THIS_SCOPE0(GetProcess());
ShimStackWalk * pSW = GetProcess()->GetShim()->LookupOrCreateShimStackWalk(m_pThread);
// check if there is any chain
if (pSW->GetChainCount() > 0)
{
// check if the leaf chain has any frame
if (pSW->GetChain(0)->GetLastFrameIndex() > 0)
{
CordbFrame * pCFrame = GetCordbFrameFromInterface(pSW->GetFrame(0));
CordbNativeFrame * pNFrame = pCFrame->GetAsNativeFrame();
if (pNFrame != NULL)
{
// check if the leaf frame in the leaf chain is "this"
if (CompareControlRegisters(GetContext(), pNFrame->GetContext()))
{
m_optfIsLeafFrame = TRUE;
}
}
}
}
if (!m_optfIsLeafFrame.HasValue())
{
m_optfIsLeafFrame = FALSE;
}
}
else
{
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
m_optfIsLeafFrame = (pDAC->IsLeafFrame(m_pThread->m_vmThreadToken, &m_context) == TRUE);
}
}
return m_optfIsLeafFrame.GetValue();
}
//---------------------------------------------------------------------------------------
//
// Get the offset used to determine if a variable is live in a particular method frame.
//
// Return Value:
// the offset used for inspection purposes
//
// Notes:
// On WIN64, variables used in funclets are always homed on the stack. Morever, the variable lifetime
// information only covers the parent method. The idea is that the variables which are live in a funclet
// will be the variables which are live in the parent method at the offset at which the exception occurs.
// Thus, to determine if a variable is live in a funclet frame, we need to use the offset of the parent
// method frame at which the exception occurs.
//
SIZE_T CordbNativeFrame::GetInspectionIP()
{
#ifdef FEATURE_EH_FUNCLETS
// On 64-bit, if this is a funclet, then return the offset of the parent method frame at which
// the exception occurs. Otherwise just return the normal offset.
return (IsFunclet() ? GetParentIP() : m_ip);
#else
// Always return the normal offset on all other platforms.
return m_ip;
#endif // FEATURE_EH_FUNCLETS
}
//---------------------------------------------------------------------------------------
//
// Return whether this is a funclet method frame.
//
// Return Value:
// whether this is a funclet method frame.
//
bool CordbNativeFrame::IsFunclet()
{
#ifdef FEATURE_EH_FUNCLETS
return (m_misc.parentIP != NULL);
#else
return false;
#endif // FEATURE_EH_FUNCLETS
}
//---------------------------------------------------------------------------------------
//
// Return whether this is a filter funclet method frame.
//
// Return Value:
// whether this is a filter funclet method frame.
//
bool CordbNativeFrame::IsFilterFunclet()
{
#ifdef FEATURE_EH_FUNCLETS
return (IsFunclet() && m_misc.fIsFilterFunclet);
#else
return false;
#endif // FEATURE_EH_FUNCLETS
}
#ifdef FEATURE_EH_FUNCLETS
//---------------------------------------------------------------------------------------
//
// Return the offset of the parent method frame at which the exception occurs.
//
// Return Value:
// the offset of the parent method frame at which the exception occurs
//
SIZE_T CordbNativeFrame::GetParentIP()
{
return m_misc.parentIP;
}
#endif // FEATURE_EH_FUNCLETS
// Accessor for the shim private hook code:CordbThread::ConvertFrameForILMethodWithoutMetadata.
// Refer to that function for comments on the return value, the argument, etc.
BOOL CordbNativeFrame::ConvertNativeFrameForILMethodWithoutMetadata(
ICorDebugInternalFrame2 ** ppInternalFrame2)
{
_ASSERTE(ppInternalFrame2 != NULL);
*ppInternalFrame2 = NULL;
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
IDacDbiInterface::DynamicMethodType type =
pDAC->IsILStubOrLCGMethod(GetNativeCode()->GetVMNativeCodeMethodDescToken());
// Here are the conversion rules:
// 1) For a normal managed method, we don't convert, and we return FALSE.
// 2) For an IL stub, we convert to NULL, and we return TRUE.
// 3) For a dynamic method, we convert to a STUBFRAME_LIGHTWEIGHT_FUNCTION, and we return TRUE.
if (type == IDacDbiInterface::kNone)
{
return FALSE;
}
else if (type == IDacDbiInterface::kILStub)
{
return TRUE;
}
else if (type == IDacDbiInterface::kLCGMethod)
{
RSInitHolder<CordbInternalFrame> pInternalFrame(
new CordbInternalFrame(m_pThread,
m_fp,
m_currentAppDomain,
STUBFRAME_LIGHTWEIGHT_FUNCTION,
GetNativeCode()->GetMetadataToken(),
GetNativeCode()->GetFunction(),
GetNativeCode()->GetVMNativeCodeMethodDescToken()));
pInternalFrame.TransferOwnershipExternal(ppInternalFrame2);
return TRUE;
}
UNREACHABLE();
}
/* ------------------------------------------------------------------------- *
* JIT-IL Frame class
* ------------------------------------------------------------------------- */
CordbJITILFrame::CordbJITILFrame(CordbNativeFrame * pNativeFrame,
CordbILCode * pCode,
UINT_PTR ip,
CorDebugMappingResult mapping,
GENERICS_TYPE_TOKEN exactGenericArgsToken,
DWORD dwExactGenericArgsTokenIndex,
bool fVarArgFnx,
CordbReJitILCode * pRejitCode)
: CordbBase(pNativeFrame->GetProcess(), 0, enumCordbJITILFrame),
m_nativeFrame(pNativeFrame),
m_ilCode(pCode),
m_ip(ip),
m_mapping(mapping),
m_fVarArgFnx(fVarArgFnx),
m_allArgsCount(0),
m_rgbSigParserBuf(NULL),
m_FirstArgAddr(NULL),
m_rgNVI(NULL),
m_genericArgs(),
m_genericArgsLoaded(false),
m_frameParamsToken(exactGenericArgsToken),
m_dwFrameParamsTokenIndex(dwExactGenericArgsTokenIndex),
m_pReJitCode(pRejitCode)
{
// We'll initialize the SigParser in CordbJITILFrame::Init().
m_sigParserCached = SigParser(NULL, 0);
_ASSERTE(m_sigParserCached.IsNull());
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_pThread->GetRefreshStackNeuterList()->Add(GetProcess(), this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
//---------------------------------------------------------------------------------------
//
// Initialize a CordbJITILFrame object. Must be called after allocating the object and before using it.
// If Init fails, then destroy the object and release the memory.
//
// Return Value:
// HRESULT for the operation
//
// Notes:
// This is a nop if the function is not a vararg function.
//
HRESULT CordbJITILFrame::Init()
{
// ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
_ASSERTE(m_ilCode != NULL);
if (m_fVarArgFnx)
{
// First, we need to find the VASigCookie. Use the native var info to do so.
const ICorDebugInfo::NativeVarInfo * pNativeVarInfo = NULL;
CordbNativeFrame * pNativeFrame = this->m_nativeFrame;
pNativeFrame->m_nativeCode->LoadNativeInfo();
hr = pNativeFrame->m_nativeCode->ILVariableToNative((DWORD)ICorDebugInfo::VARARGS_HND_ILNUM,
pNativeFrame->GetInspectionIP(),
&pNativeVarInfo);
IfFailThrow(hr);
// Check for the case where the VASigCookie isn't pushed on the stack yet.
// This should only be a problem with optimized code.
if (pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK)
{
ThrowHR(E_FAIL);
}
// Retrieve the target address.
CORDB_ADDRESS pRemoteValue = pNativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg,
pNativeVarInfo->loc.vlStk.vlsOffset);
CORDB_ADDRESS argBase;
// Now is the time to ask DacDbi to retrieve the information based on the VASigCookie.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
TargetBuffer sigTargetBuf = pDAC->GetVarArgSig(pRemoteValue, &argBase);
// make sure we are not leaking any memory
_ASSERTE(m_rgbSigParserBuf == NULL);
m_rgbSigParserBuf = new BYTE[sigTargetBuf.cbSize];
GetProcess()->SafeReadBuffer(sigTargetBuf, m_rgbSigParserBuf);
m_sigParserCached = SigParser(m_rgbSigParserBuf, sigTargetBuf.cbSize);
// Note that we should never mutate the SigParser.
// Instead, make a copy and work with the copy instead.
if (!m_sigParserCached.IsNull())
{
SigParser sigParser = m_sigParserCached;
// get the actual count of arguments, including the var args
IfFailThrow(sigParser.SkipMethodHeaderSignature(&m_allArgsCount));
BOOL methodIsStatic;
m_ilCode->GetSig(NULL, NULL, &methodIsStatic); // throws
if (!methodIsStatic)
{
m_allArgsCount++; // skip the "this" object
}
// initialize the variable lifetime information
m_rgNVI = new ICorDebugInfo::NativeVarInfo[m_allArgsCount]; // throws
_ASSERTE(ICorDebugInfo::VLT_COUNT <= ICorDebugInfo::VLT_INVALID);
for (ULONG i = 0; i < m_allArgsCount; i++)
{
m_rgNVI[i].loc.vlType = ICorDebugInfo::VLT_INVALID;
}
}
// GetVarArgSig gets the address of the beginning of the arguments pushed for this frame.
// We'll need the address of the first argument, which will depend on its size and the
// calling convention, so we'll commpute that now that we have the SigParser.
CordbType * pArgType;
IfFailThrow(GetArgumentType(0, &pArgType));
ULONG32 argSize = 0;
IfFailThrow(pArgType->GetUnboxedObjectSize(&argSize));
#if defined(TARGET_X86) // (STACK_GROWS_DOWN_ON_ARGS_WALK)
m_FirstArgAddr = argBase - argSize;
#else // !TARGET_X86 (STACK_GROWS_UP_ON_ARGS_WALK)
AlignAddressForType(pArgType, argBase);
m_FirstArgAddr = argBase;
#endif // !TARGET_X86 (STACK_GROWS_UP_ON_ARGS_WALK)
}
// The stackwalking code can't always successfully retrieve the generics type token.
// For example, on 64-bit, the JIT only encodes the generics type token location if
// a method has catch clause for a generic exception (e.g. "catch(MyException<string> e)").
if ((m_dwFrameParamsTokenIndex != (DWORD)ICorDebugInfo::MAX_ILNUM) && (m_frameParamsToken == NULL))
{
// All variables are unavailable in the prolog and the epilog.
// This includes the generics type token. Failing to get the token just means that
// we won't have full generics information. This should not be a disastrous failure.
//
// Currently, on X64, the JIT is reporting that the variables are live even in the epilog.
// That's why we need this check here. I need to follow up on this.
if ((m_mapping != MAPPING_PROLOG) && (m_mapping != MAPPING_EPILOG))
{
// Find the generics type token using the variable lifetime information.
const ICorDebugInfo::NativeVarInfo * pNativeVarInfo = NULL;
CordbNativeFrame * pNativeFrame = this->m_nativeFrame;
pNativeFrame->m_nativeCode->LoadNativeInfo();
HRESULT hrTmp = pNativeFrame->m_nativeCode->ILVariableToNative(m_dwFrameParamsTokenIndex,
pNativeFrame->GetInspectionIP(),
&pNativeVarInfo);
// It's not a disaster if we can't find the generics token, so don't throw an exception here.
// In fact, it's fairly common in retail code. Even if we can't find the generics token,
// we may still be able to look up the generics type information later by using the MethodDesc,
// the "this" object, etc. If not, we'll at least get the representative type information
// (e.g. Foo<T> instead of Foo<string>).
if (SUCCEEDED(hrTmp))
{
_ASSERTE(pNativeVarInfo != NULL);
// The generics type token should be stored either in a register or on the stack.
SIZE_T uRawToken = pNativeFrame->GetRegisterOrStackValue(pNativeVarInfo);
// Ask DAC to resolve the token for us. We really don't want to deal with all the logic here.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
// On a minidump, we'll throw if we're missing the memory.
ALLOW_DATATARGET_MISSING_MEMORY(
m_frameParamsToken = pDAC->ResolveExactGenericArgsToken(m_dwFrameParamsTokenIndex, uRawToken);
);
}
}
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
/*
A list of which resources owned by this object are accounted for.
UNKNOWN:
CordbNativeFrame* m_nativeFrame;
CordbILCode * m_ilCode;
CorDebugMappingResult m_mapping;
CORDB_ADDRESS m_FirstArgAddr;
ICorDebugInfo::NativeVarInfo * m_rgNVI; // Deleted in neuter
CordbClass **m_genericArgs;
*/
CordbJITILFrame::~CordbJITILFrame()
{
_ASSERTE(IsNeutered());
}
// Neutered by CordbNativeFrame
void CordbJITILFrame::Neuter()
{
// Since neutering here calls Release directly, we don't want to double-release
// if neuter is called multiple times.
if (IsNeutered())
{
return;
}
// Frames include pointers across to other types that specify the
// representation instantiation - reduce the reference counts on these....
for (unsigned int i = 0; i < m_genericArgs.m_cInst; i++)
{
m_genericArgs.m_ppInst[i]->Release();
}
if (m_rgNVI != NULL)
{
delete [] m_rgNVI;
m_rgNVI = NULL;
}
if (m_rgbSigParserBuf != NULL)
{
delete [] m_rgbSigParserBuf;
m_rgbSigParserBuf = NULL;
}
m_pReJitCode.Clear();
// If this class ever inherits from the CordbFrame we'll need a call
// to CordbFrame::Neuter() here instead of to CordbBase::Neuter();
CordbBase::Neuter();
}
//---------------------------------------------------------------------------------------
//
// Load the generic type and method arguments and store them into the frame if possible.
//
// Return Value:
// HRESULT for the operation
//
void CordbJITILFrame::LoadGenericArgs()
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
// The case where there are no type parameters, or the case where we've
// already feched the realInst, is easy.
if (m_genericArgsLoaded)
{
return;
}
_ASSERTE(m_nativeFrame->m_nativeCode != NULL);
if (!m_nativeFrame->m_nativeCode->IsInstantiatedGeneric())
{
m_genericArgs = Instantiation(0, NULL,0);
m_genericArgsLoaded = true;
return;
}
// Find the exact generic arguments for a frame that is executing
// a generic method. The left-side will fetch these from arguments
// given on the stack and/or from the IP.
IDacDbiInterface * pDAC = GetProcess()->GetDAC();
UINT32 cGenericClassTypeParams = 0;
DacDbiArrayList<DebuggerIPCE_ExpandedTypeData> rgGenericTypeParams;
pDAC->GetMethodDescParams(GetCurrentAppDomain()->GetADToken(),
m_nativeFrame->GetNativeCode()->GetVMNativeCodeMethodDescToken(),
m_frameParamsToken,
&cGenericClassTypeParams,
&rgGenericTypeParams);
UINT32 cTotalGenericTypeParams = rgGenericTypeParams.Count();
// @dbgtodo reliability - This holder doesn't actually work in this case because it just deletes
// each element on error. The RS classes are all expected to be neutered before the destructor is called.
NewArrayHolder<CordbType *> ppGenericArgs(new CordbType *[cTotalGenericTypeParams]);
for (UINT32 i = 0; i < cTotalGenericTypeParams;i++)
{
// creates a CordbType object for the generic argument
HRESULT hr = CordbType::TypeDataToType(GetCurrentAppDomain(),
&(rgGenericTypeParams[i]),
&ppGenericArgs[i]);
IfFailThrow(hr);
// We add a ref as the instantiation will be stored away in the
// ref-counted data structure associated with the JITILFrame
ppGenericArgs[i]->AddRef();
}
// initialize the generics information
m_genericArgs = Instantiation(cTotalGenericTypeParams, ppGenericArgs, cGenericClassTypeParams);
m_genericArgsLoaded = true;
ppGenericArgs.SuppressRelease();
}
//
// CordbJITILFrame::QueryInterface
//
// Description
// Interface query for this COM object
//
// NOTE: the COM object associated with this CordbJITILFrame may consist of two
// C++ objects (a CordbJITILFrame and its associated CordbNativeFrame)
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
HRESULT CordbJITILFrame::QueryInterface(REFIID id, void **pInterface)
{
if (NULL != m_nativeFrame)
{
// If the native frame does not support the requested interface, then
// the native fram is responsible for delegating the query back to this
// object through QueryInterfaceInternal(...)
return m_nativeFrame->QueryInterface(id, pInterface);
}
// no native frame. Check for interfaces common to CordbNativeFrame and
// CordbJITILFrame
if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugILFrame*>(this));
}
else if (id == IID_ICorDebugFrame)
{
*pInterface = static_cast<ICorDebugFrame*>(this);
}
else
{
// didn't find an interface yet. Since there's no native frame
// associated with this IL frame, go ahead and check for the IL frame
return this->QueryInterfaceInternal(id, pInterface);
}
ExternalAddRef();
return S_OK;
}
//
// CordbJITILFrame::QueryInterfaceInternal
//
// Description
// Interface query for interfaces implemented ONLY by CordbJITILFrame (as
// opposed to interfaces implemented by both CordbNativeFrame and
// CordbJITILFrame)
//
// Parameters
// id the GUID associated with the requested interface
// pInterface [out] the interface pointer
// NOTE: id must not be IUnknown or ICorDebugFrame
// NOTE: if this object is in "forward compatibility mode", passing in
// IID_ICorDebugILFrame2 for the id will result in a failure (returns
// E_NOINTERFACE)
//
// Returns
// HRESULT
// S_OK If this CordbJITILFrame supports the interface
// E_NOINTERFACE If this object does not support the interface
//
// Exceptions
// None
//
HRESULT
CordbJITILFrame::QueryInterfaceInternal(REFIID id, void** pInterface)
{
_ASSERTE(IID_ICorDebugFrame != id);
_ASSERTE(IID_IUnknown != id);
// don't query for IUnknown or ICorDebugFrame! Someone else should have
// already taken care of that.
if (id == IID_ICorDebugILFrame)
{
*pInterface = static_cast<ICorDebugILFrame*>(this);
}
else if (id == IID_ICorDebugILFrame2)
{
*pInterface = static_cast<ICorDebugILFrame2*>(this);
}
else if (id == IID_ICorDebugILFrame3)
{
*pInterface = static_cast<ICorDebugILFrame3*>(this);
}
else if (id == IID_ICorDebugILFrame4)
{
*pInterface = static_cast<ICorDebugILFrame4*>(this);
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Get an enumerator for the generic type and method arguments on this frame.
//
// Arguments:
// ppTypeParameterEnum - out parameter; return the enumerator
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::EnumerateTypeParameters(ICorDebugTypeEnum **ppTypeParameterEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppTypeParameterEnum, ICorDebugTypeEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
(*ppTypeParameterEnum) = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// load the generic arguments, which may be cached
LoadGenericArgs();
// create the enumerator
RSInitHolder<CordbTypeEnum> pEnum(
CordbTypeEnum::Build(GetCurrentAppDomain(), m_nativeFrame->m_pThread->GetRefreshStackNeuterList(), m_genericArgs.m_cInst, m_genericArgs.m_ppInst));
if ( pEnum == NULL )
{
ThrowOutOfMemory();
}
pEnum.TransferOwnershipExternal(ppTypeParameterEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetChain
//
// Description:
// Return the owning chain. Since chains have been deprecated in Arrowhead,
// this function returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppChain - out parameter; return the owning chain
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppChain is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetChain(ICorDebugChain **ppChain)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppChain, ICorDebugChain **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetChain(ppChain);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Return the IL code blob associated with this IL frame.
// Each IL frame corresponds to exactly one IL code blob.
HRESULT CordbJITILFrame::GetCode(ICorDebugCode **ppCode)
{
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppCode, ICorDebugCode **);
*ppCode = static_cast<ICorDebugCode*> (m_ilCode);
m_ilCode->ExternalAddRef();
return S_OK;;
}
// Return the function associated with this IL frame.
// Each IL frame corresponds to exactly one function.
HRESULT CordbJITILFrame::GetFunction(ICorDebugFunction **ppFunction)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
ValidateOrThrow(ppFunction);
CordbFunction * pFunc = m_nativeFrame->GetFunction();
*ppFunction = static_cast<ICorDebugFunction *>(pFunc);
pFunc->ExternalAddRef();
}
PUBLIC_API_END(hr);
return hr;
}
// Return the token of the function associated with this IL frame.
// Each IL frame corresponds to exactly one function.
HRESULT CordbJITILFrame::GetFunctionToken(mdMethodDef *pToken)
{
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pToken, mdMethodDef *);
*pToken = m_nativeFrame->m_nativeCode->GetMetadataToken();
return S_OK;
}
// ----------------------------------------------------------------------------
// CordJITILFrame::GetStackRange
//
// Description:
// Get the stack range owned by the associated native frame.
// IL frames and native frames are 1:1 for normal jitted managed methods.
// Dynamic methods are an exception.
//
// Arguments:
// * pStart - out parameter; return the leaf end of the frame
// * pEnd - out parameter; return the root end of the frame
//
// Return Value:
// Return S_OK on success.
//
// Notes: see code:#GetStackRange
HRESULT CordbJITILFrame::GetStackRange(CORDB_ADDRESS *pStart, CORDB_ADDRESS *pEnd)
{
PUBLIC_REENTRANT_API_ENTRY(this);
// The access of m_nativeFrame is not safe here. It's a weak reference.
OK_IF_NEUTERED(this);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetStackRange(pStart, pEnd);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetCaller
//
// Description:
// Delegate to the associated native frame to return the caller, which is closer to the root.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the caller frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetCaller(ICorDebugFrame **ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetCaller(ppFrame);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// ----------------------------------------------------------------------------
// CordbJITILFrame::GetCallee
//
// Description:
// Delegate to the associated native frame to return the callee, which is closer to the leaf.
// This function has been deprecated in Arrowhead, and so it returns E_NOTIMPL unless there is a shim.
//
// Arguments:
// * ppFrame - out parameter; return the callee frame
//
// Return Value:
// Return S_OK on success.
// Return E_INVALIDARG if ppFrame is NULL.
// Return CORDBG_E_OBJECT_NEUTERED if the CordbJITILFrame is neutered.
// Return E_NOTIMPL if there is no shim.
//
HRESULT CordbJITILFrame::GetCallee(ICorDebugFrame **ppFrame)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppFrame, ICorDebugFrame **);
HRESULT hr = S_OK;
EX_TRY
{
hr = m_nativeFrame->GetCallee(ppFrame);
// Since we are returning anyway, let's not throw even if the call fails.
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Create a stepper on the frame.
HRESULT CordbJITILFrame::CreateStepper(ICorDebugStepper **ppStepper)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// by default, a stepper operates on the IL level, using IL offsets
return m_nativeFrame->CreateStepper(ppStepper);
}
// Return the IL offset and the mapping result.
HRESULT CordbJITILFrame::GetIP(ULONG32 *pnOffset,
CorDebugMappingResult *pMappingResult)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pnOffset, ULONG32 *);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pMappingResult, CorDebugMappingResult *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*pnOffset = (ULONG32)m_ip;
if (pMappingResult)
*pMappingResult = m_mapping;
return S_OK;
}
// Determine if we can set IP at this point. The specified offset is the IL offset.
HRESULT CordbJITILFrame::CanSetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Check to see that this is a leaf frame
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
// delegate to the associated native frame
CordbNativeCode * pNativeCode = m_nativeFrame->m_nativeCode;
hr = m_nativeFrame->m_pThread->SetIP(SetIP_fCanSetIPOnly, // specify that this is for checking only
pNativeCode,
nOffset,
SetIP_fIL );
}
EX_CATCH_HRESULT(hr);
return hr;
}
// Try to set the IP to the specified offset. The specified offset is the IL offset.
HRESULT CordbJITILFrame::SetIP(ULONG32 nOffset)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
// Check to see that this is a leaf frame
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(CORDBG_E_SET_IP_NOT_ALLOWED_ON_NONLEAF_FRAME);
}
// delegate to the native frame
CordbNativeCode * pNativeCode = m_nativeFrame->m_nativeCode;
hr = m_nativeFrame->m_pThread->SetIP(SetIP_fSetIP, // specify that this is a real SetIP operation
pNativeCode,
nOffset,
SetIP_fIL );
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine creates backing native info for a local variable, returning an ICorDebugInfo
// object for the local variable when successful.
//
// Arguments:
// dwIndex - Index of the local variable to create native info for.
// ppNativeInfo - OUT: Space for storing the resulting pointer to native variable info.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::FabricateNativeInfo(DWORD dwIndex,
const ICorDebugInfo::NativeVarInfo ** ppNativeInfo)
{
HRESULT hr = S_OK;
EX_TRY
{
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(this->GetProcess());
_ASSERTE(m_fVarArgFnx);
// This array should have been populated in CordbJITILFrame::Init().
_ASSERTE(m_rgNVI != NULL);
// check if we have already fabricated all the information
if (m_rgNVI[dwIndex].loc.vlType != ICorDebugInfo::VLT_INVALID)
{
(*ppNativeInfo) = &m_rgNVI[dwIndex];
}
else
{
// We'll initialize everything at once
ULONG cbArchitectureMin;
// m_FirstArgAddr will already be aligned on platforms that require alignment
CORDB_ADDRESS rpCur = m_FirstArgAddr;
#if defined(TARGET_X86) || defined(TARGET_ARM)
cbArchitectureMin = 4;
#elif defined(TARGET_64BIT)
cbArchitectureMin = 8;
#else
cbArchitectureMin = 8; //REVISIT_TODO not sure if this is correct
PORTABILITY_ASSERT("What is the architecture-dependent minimum word size?");
#endif // TARGET_X86
// make a copy of the cached SigParser
SigParser sigParser = m_sigParserCached;
IfFailThrow(sigParser.SkipMethodHeaderSignature(NULL));
ULONG32 cbType;
CordbType * pArgType;
// make sure all the generic type and method arguments are loaded
LoadGenericArgs();
// get a CordbType object for the generic argument
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), &pArgType));
IfFailThrow(pArgType->GetUnboxedObjectSize(&cbType));
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
// The the rpCur pointer starts off in the right spot for the
// first argument, but thereafter we have to decrement it
// before getting the variable's location from it. So increment
// it here to be consistent later.
rpCur += max(cbType, cbArchitectureMin);
#endif
// Grab the IL code's function's method signature so we can see if it's static.
BOOL fMethodIsStatic;
m_ilCode->GetSig(NULL, NULL, &fMethodIsStatic); // throws
ULONG i;
if (fMethodIsStatic)
{
i = 0;
}
else
{
i = 1;
}
for ( ; i < m_allArgsCount; i++)
{
m_rgNVI[i].startOffset = 0;
m_rgNVI[i].endOffset = 0xFFffFFff;
m_rgNVI[i].varNumber = i;
m_rgNVI[i].loc.vlType = ICorDebugInfo::VLT_FIXED_VA;
LoadGenericArgs();
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), &pArgType));
IfFailThrow(pArgType->GetUnboxedObjectSize(&cbType));
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
rpCur -= max(cbType, cbArchitectureMin);
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset =
(unsigned)(m_FirstArgAddr - rpCur);
// Since the JIT adds in the size of this field, we do too to
// be consistent.
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset += sizeof(((CORINFO_VarArgInfo*)0)->argBytes);
#else // STACK_GROWS_UP_ON_ARGS_WALK
m_rgNVI[i].loc.vlFixedVarArg.vlfvOffset =
(unsigned)(rpCur - m_FirstArgAddr);
rpCur += max(cbType, cbArchitectureMin);
AlignAddressForType(pArgType, rpCur);
#endif
IfFailThrow(sigParser.SkipExactlyOne());
} // for ( ; i M m_allArgsCount; i++)
(*ppNativeInfo) = &m_rgNVI[dwIndex];
} // else (m_rgNVI[dwIndex].loc.vlType == ICorDebugInfo::VLT_INVALID)
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::ILVariableToNative(DWORD dwVarNumber,
const ICorDebugInfo::NativeVarInfo **ppNativeInfo)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
_ASSERTE(m_nativeFrame->m_nativeCode->IsNativeCodeValid());
// We keep the fixed argument native var infos in the
// CordbFunction, which only is an issue for var args info:
if (!m_fVarArgFnx || //not a var args function
(dwVarNumber < m_nativeFrame->m_nativeCode->GetFixedArgCount()) || // var args,fixed arg
// note that this include the implicit 'this' for nonstatic fnxs
(dwVarNumber >= m_allArgsCount) ||// var args, local variable
(m_sigParserCached.IsNull())) //we don't have any VA info
{
// If we're in a var args fnx, but we're actually looking
// for a local variable, then we want to use the variable
// index as the function sees it - fixed (but not var)
// args are added to local var number to get native info
// We are really trying to find a variable by it's number,
// but "special" variables have a negative number which we
// don't use. We "number" them conceptually between the
// arguments and locals:
//
// arguments special locals
// -----------------------------------------
// Actual numbers: 1 2 3 . . . 4 5 6 7
// Logical numbers: 0 1 2 3 4 5 6 7 8
//
// We have two different counts for the number of arguments: the fixedArgCount
// gives the actual number of arguments and the allArgsCount is the number of
// of fixed arguments plus the number of var args.
//
// Thus, to get the correct actual number for locals we have to compute it as
// logicalNumber - allArgsCount + fixedArgCount
if (m_fVarArgFnx && (dwVarNumber >= m_allArgsCount) && !m_sigParserCached.IsNull())
{
dwVarNumber -= m_allArgsCount;
dwVarNumber += m_nativeFrame->m_nativeCode->GetFixedArgCount();
}
return m_nativeFrame->m_nativeCode->ILVariableToNative(dwVarNumber,
m_nativeFrame->GetInspectionIP(),
ppNativeInfo);
}
return FabricateNativeInfo(dwVarNumber,ppNativeInfo);
}
//---------------------------------------------------------------------------------------
//
// This routine get the type of a particular argument.
//
// Arguments:
// dwIndex - Index of the argument.
// ppResultType - OUT: Space for storing the type of the argument.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::GetArgumentType(DWORD dwIndex,
CordbType ** ppResultType)
{
HRESULT hr = S_OK;
THROW_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess());
LoadGenericArgs();
if (m_fVarArgFnx && !m_sigParserCached.IsNull())
{
SigParser sigParser = m_sigParserCached;
IfFailThrow(sigParser.SkipMethodHeaderSignature(NULL));
// Grab the IL code's function's method signature so we can see if it's static.
BOOL fMethodIsStatic;
m_ilCode->GetSig(NULL, NULL, &fMethodIsStatic); // throws
if (!fMethodIsStatic)
{
if (dwIndex == 0)
{
// Return the signature for the 'this' pointer for the
// class this method is in.
IfFailThrow(m_ilCode->GetClass()->GetThisType(&(this->m_genericArgs), ppResultType));
return hr;
}
else
{
dwIndex--;
}
}
for (ULONG i = 0; i < dwIndex; i++)
{
IfFailThrow(sigParser.SkipExactlyOne());
}
IfFailThrow(sigParser.SkipFunkyAndCustomModifiers());
IfFailThrow(sigParser.SkipAnyVASentinel());
IfFailThrow(CordbType::SigToType(GetModule(), &sigParser, &(this->m_genericArgs), ppResultType));
}
else // (!m_fVarArgFnx || m_sigParserCached.IsNull())
{
m_nativeFrame->m_nativeCode->GetArgumentType(dwIndex, &(this->m_genericArgs), ppResultType);
}
return hr;
}
//
// GetNativeVariable uses the JIT variable information to delegate to
// the native frame when the value is really created.
//
HRESULT CordbJITILFrame::GetNativeVariable(CordbType *type,
const ICorDebugInfo::NativeVarInfo *pNativeVarInfo,
ICorDebugValue **ppValue)
{
INTERNAL_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
HRESULT hr = S_OK;
#ifdef FEATURE_EH_FUNCLETS
if (m_nativeFrame->IsFunclet())
{
if ( (pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK) &&
(pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK2) &&
(pNativeVarInfo->loc.vlType != ICorDebugInfo::VLT_STK_BYREF) )
{
_ASSERTE(!"CordbJITILFrame::GetNativeVariable()"
" - Variables used in funclets should always be homed on the stack.\n");
return E_FAIL;
}
}
#endif // FEATURE_EH_FUNCLETS
switch (pNativeVarInfo->loc.vlType)
{
case ICorDebugInfo::VLT_REG:
hr = m_nativeFrame->GetLocalRegisterValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg),
type, ppValue);
break;
case ICorDebugInfo::VLT_REG_BYREF:
{
CORDB_ADDRESS pRemoteByRefAddr = PTR_TO_CORDB_ADDRESS(
*( m_nativeFrame->GetAddressOfRegister(ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlReg.vlrReg))) );
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteByRefAddr,
type,
ppValue);
}
break;
#if defined(TARGET_64BIT) || defined(TARGET_ARM)
case ICorDebugInfo::VLT_REG_FP:
#if defined(TARGET_ARM) // @ARMTODO
hr = E_NOTIMPL;
#elif defined(TARGET_AMD64)
hr = m_nativeFrame->GetLocalFloatingPointValue(pNativeVarInfo->loc.vlReg.vlrReg + REGISTER_AMD64_XMM0,
type, ppValue);
#elif defined(TARGET_ARM64)
hr = m_nativeFrame->GetLocalFloatingPointValue(pNativeVarInfo->loc.vlReg.vlrReg + REGISTER_ARM64_V0,
type, ppValue);
#else
#error Platform not implemented
#endif // TARGET_ARM @ARMTODO
break;
#endif // TARGET_64BIT || TARGET_ARM
case ICorDebugInfo::VLT_STK_BYREF:
{
CORDB_ADDRESS pRemoteByRefAddr = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg, pNativeVarInfo->loc.vlStk.vlsOffset) ;
hr = m_nativeFrame->GetLocalByRefMemoryValue(pRemoteByRefAddr,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_STK:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk.vlsBaseReg, pNativeVarInfo->loc.vlStk.vlsOffset) ;
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_REG_REG:
hr = m_nativeFrame->GetLocalDoubleRegisterValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegReg.vlrrReg2),
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegReg.vlrrReg1),
type, ppValue);
break;
case ICorDebugInfo::VLT_REG_STK:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlRegStk.vlrsStk.vlrssBaseReg, pNativeVarInfo->loc.vlRegStk.vlrsStk.vlrssOffset);
hr = m_nativeFrame->GetLocalMemoryRegisterValue(
pRemoteValue,
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlRegStk.vlrsReg),
type, ppValue);
}
break;
case ICorDebugInfo::VLT_STK_REG:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStkReg.vlsrStk.vlsrsBaseReg, pNativeVarInfo->loc.vlStkReg.vlsrStk.vlsrsOffset);
hr = m_nativeFrame->GetLocalRegisterMemoryValue(
ConvertRegNumToCorDebugRegister(pNativeVarInfo->loc.vlStkReg.vlsrReg),
pRemoteValue, type, ppValue);
}
break;
case ICorDebugInfo::VLT_STK2:
{
CORDB_ADDRESS pRemoteValue = m_nativeFrame->GetLSStackAddress(
pNativeVarInfo->loc.vlStk2.vls2BaseReg, pNativeVarInfo->loc.vlStk2.vls2Offset);
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
}
break;
case ICorDebugInfo::VLT_FPSTK:
#if defined(TARGET_ARM) // @ARMTODO
hr = E_NOTIMPL;
#else
/*
@TODO [Microsoft] We have to make this work!!!!!!!!!!!!!
hr = m_nativeFrame->GetLocalFloatingPointValue(
pNativeVarInfo->loc.vlFPstk.vlfReg + REGISTER_X86_FPSTACK_0,
type, ppValue);
*/
hr = CORDBG_E_IL_VAR_NOT_AVAILABLE;
#endif
break;
case ICorDebugInfo::VLT_FIXED_VA:
if (m_sigParserCached.IsNull()) //no var args info
return CORDBG_E_IL_VAR_NOT_AVAILABLE;
CORDB_ADDRESS pRemoteValue;
#if defined(TARGET_X86) // STACK_GROWS_DOWN_ON_ARGS_WALK
pRemoteValue = m_FirstArgAddr - pNativeVarInfo->loc.vlFixedVarArg.vlfvOffset;
// Remember to subtract out this amount
pRemoteValue += sizeof(((CORINFO_VarArgInfo*)0)->argBytes);
#else // STACK_GROWS_UP_ON_ARGS_WALK
pRemoteValue = m_FirstArgAddr + pNativeVarInfo->loc.vlFixedVarArg.vlfvOffset;
#endif
hr = m_nativeFrame->GetLocalMemoryValue(pRemoteValue,
type,
ppValue);
break;
default:
_ASSERTE(!"Invalid locVarType");
hr = E_FAIL;
break;
}
return hr;
}
HRESULT CordbJITILFrame::EnumerateLocalVariables(ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
return EnumerateLocalVariablesEx(ILCODE_ORIGINAL_IL, ppValueEnum);
}
HRESULT CordbJITILFrame::GetLocalVariable(DWORD dwIndex,
ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
return GetLocalVariableEx(ILCODE_ORIGINAL_IL, dwIndex, ppValue);
}
HRESULT CordbJITILFrame::EnumerateArguments(ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
EX_TRY
{
RSInitHolder<CordbValueEnum> cdVE(new CordbValueEnum(m_nativeFrame, CordbValueEnum::ARGS));
// Initialize the new enum
hr = cdVE->Init();
IfFailThrow(hr);
cdVE.TransferOwnershipExternal(ppValueEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine gets the value of a particular argument
//
// Arguments:
// dwIndex - Index of the argument.
// ppValue - OUT: Space for storing the value of the argument
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbJITILFrame::GetArgument(DWORD dwIndex, ICorDebugValue ** ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
const ICorDebugInfo::NativeVarInfo * pNativeInfo;
//
// First, make sure that we've got the jitted variable location data
// loaded from the left side.
//
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_nativeCode->LoadNativeInfo(); //throws
hr = ILVariableToNative(dwIndex, &pNativeInfo);
IfFailThrow(hr);
// Get the type of this argument from the function
CordbType * pType;
hr = GetArgumentType(dwIndex, &pType);
IfFailThrow(hr);
hr = GetNativeVariable(pType, pNativeInfo, ppValue);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetStackDepth(ULONG32 *pDepth)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pDepth, ULONG32 *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
/* !!! */
return E_NOTIMPL;
}
HRESULT CordbJITILFrame::GetStackValue(DWORD dwIndex, ICorDebugValue **ppValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
/* !!! */
return E_NOTIMPL;
}
//---------------------------------------------------------------------------------------
//
// Remaps the active frame to the latest EnC version of the function, preserving the
// execution state of the method such as the values of locals.
// Can only be called when the leaf frame is at a remap opportunity.
//
// Arguments:
// nOffset - the IL offset in the new version of the function to remap to
//
HRESULT CordbJITILFrame::RemapFunction(ULONG32 nOffset)
{
HRESULT hr = S_OK;
PUBLIC_API_BEGIN(this)
{
#if !defined(FEATURE_ENC_SUPPORTED)
ThrowHR(E_NOTIMPL);
#else // FEATURE_ENC_SUPPORTED
// Can only be called on leaf frame.
if (!m_nativeFrame->IsLeafFrame())
{
ThrowHR(E_INVALIDARG);
}
// mark frames as not fresh, because this frame has been updated.
m_nativeFrame->m_pThread->CleanupStack();
// Since we may have overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
m_nativeFrame->m_pThread->GetProcess()->m_continueCounter++;
// Tell the left-side to do the remap
hr = m_nativeFrame->m_pThread->SetRemapIP(nOffset);
#endif // FEATURE_ENC_SUPPORTED
}
PUBLIC_API_END(hr);
return hr;
}
HRESULT CordbJITILFrame::GetReturnValueForILOffset(ULONG32 ILoffset, ICorDebugValue** ppReturnValue)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
EX_TRY
{
hr = GetReturnValueForILOffsetImpl(ILoffset, ppReturnValue);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::BuildInstantiationForCallsite(CordbModule * pModule, NewArrayHolder<CordbType*> &types, Instantiation &inst, Instantiation *currentInstantiation, mdToken targetClass, SigParser genericSig)
{
// This function builds an Instantiation object (and backing "types" array) for a given
// class and method signature.
HRESULT hr = S_OK;
RSExtSmartPtr<IMetaDataImport2> pImport2;
IfFailRet(pModule->GetMetaDataImporter()->QueryInterface(IID_IMetaDataImport2, (void**)&pImport2));
// If the targetClass is a TypeSpec that means its first element is GENERICINST.
// We only need to build types for the Instantiation if targetClass is a TypeSpec.
uint32_t classGenerics = 0;
SigParser typeSig;
if (TypeFromToken(targetClass) == mdtTypeSpec)
{
// Our goal with this is to full "classGenerics" with the number of
// generics, and move "typeSig" to the start of the first generic type.
PCCOR_SIGNATURE sig = 0;
ULONG sigCount = 0;
IfFailRet(pImport2->GetTypeSpecFromToken(targetClass, &sig, &sigCount));
typeSig = SigParser(sig, sigCount);
CorElementType elemType;
IfFailRet(typeSig.GetElemType(&elemType));
if (elemType != ELEMENT_TYPE_GENERICINST)
return META_E_BAD_SIGNATURE;
IfFailRet(typeSig.GetElemType(&elemType));
if (elemType != ELEMENT_TYPE_VALUETYPE && elemType != ELEMENT_TYPE_CLASS)
return META_E_BAD_SIGNATURE;
IfFailRet(typeSig.GetToken(NULL));
IfFailRet(typeSig.GetData(&classGenerics));
}
// Similarly for method generics. Simply fill "methodGenerics" with the number
// of generics, and move "genericSig" to the start of the first generic param.
uint32_t methodGenerics = 0;
if (!genericSig.IsNull())
{
uint32_t callingConv = 0;
IfFailRet(genericSig.GetCallingConvInfo(&callingConv));
if (callingConv == IMAGE_CEE_CS_CALLCONV_GENERICINST)
IfFailRet(genericSig.GetData(&methodGenerics));
}
// Now build "types" and "inst".
CordbType *pType = 0;
types = new CordbType*[methodGenerics+classGenerics];
ULONG i = 0;
for (;i < classGenerics; ++i)
{
CorElementType et;
IfFailRet(typeSig.PeekElemType(&et));
if ((et == ELEMENT_TYPE_VAR || et == ELEMENT_TYPE_MVAR) && currentInstantiation->m_cInst == 0)
return E_FAIL;
CordbType::SigToType(pModule, &typeSig, currentInstantiation, &pType);
types[i] = pType;
typeSig.SkipExactlyOne();
}
for (; i < methodGenerics+classGenerics; ++i)
{
CorElementType et;
IfFailRet(genericSig.PeekElemType(&et));
if ((et == ELEMENT_TYPE_VAR || et == ELEMENT_TYPE_MVAR) && currentInstantiation->m_cInst == 0)
return E_FAIL;
CordbType::SigToType(pModule, &genericSig, currentInstantiation, &pType);
types[i] = pType;
genericSig.SkipExactlyOne();
}
inst = Instantiation(methodGenerics+classGenerics, types, classGenerics);
return S_OK;
}
HRESULT CordbJITILFrame::GetReturnValueForILOffsetImpl(ULONG32 ILoffset, ICorDebugValue** ppReturnValue)
{
if (ppReturnValue == NULL)
return E_INVALIDARG;
if (!m_genericArgsLoaded)
LoadGenericArgs();
// First verify that we're stopped at the correct native offset
// by calling ICorDebugCode3::GetReturnValueLiveOffset and
// compare the returned native offset to our current location.
HRESULT hr = S_OK;
CordbNativeCode *pCode = m_nativeFrame->m_nativeCode;
pCode->LoadNativeInfo();
ULONG32 count = 0;
IfFailRet(pCode->GetReturnValueLiveOffsetImpl(&m_genericArgs, ILoffset, 0, &count, NULL));
NewArrayHolder<ULONG32> offsets(new ULONG32[count]);
IfFailRet(pCode->GetReturnValueLiveOffsetImpl(&m_genericArgs, ILoffset, count, &count, offsets));
bool found = false;
ULONG32 currentOffset = m_nativeFrame->GetIPOffset();
for (ULONG32 i = 0; i < count; ++i)
{
if (currentOffset == offsets[i])
{
found = true;
break;
}
}
if (!found)
return E_UNEXPECTED;
// Get the signatures and mdToken for the callee.
SigParser methodSig, genericSig;
mdToken mdFunction = 0, targetClass = 0;
IfFailRet(pCode->GetCallSignature(ILoffset, &targetClass, &mdFunction, methodSig, genericSig));
IfFailRet(CordbNativeCode::SkipToReturn(methodSig));
// Create the Instantiation, type and then return value
NewArrayHolder<CordbType*> types;
Instantiation inst;
CordbType *pType = 0;
IfFailRet(BuildInstantiationForCallsite(GetModule(), types, inst, &m_genericArgs, targetClass, genericSig));
IfFailRet(CordbType::SigToType(GetModule(), &methodSig, &inst, &pType));
return GetReturnValueForType(pType, ppReturnValue);
}
HRESULT CordbJITILFrame::GetReturnValueForType(CordbType *pType, ICorDebugValue **ppReturnValue)
{
#if defined(TARGET_X86)
const CorDebugRegister floatRegister = REGISTER_X86_FPSTACK_0;
#elif defined(TARGET_AMD64)
const CorDebugRegister floatRegister = REGISTER_AMD64_XMM0;
#elif defined(TARGET_ARM64)
const CorDebugRegister floatRegister = REGISTER_ARM64_V0;
#elif defined(TARGET_ARM)
const CorDebugRegister floatRegister = REGISTER_ARM_D0;
#endif
#if defined(TARGET_X86)
const CorDebugRegister ptrRegister = REGISTER_X86_EAX;
const CorDebugRegister ptrHighWordRegister = REGISTER_X86_EDX;
#elif defined(TARGET_AMD64)
const CorDebugRegister ptrRegister = REGISTER_AMD64_RAX;
#elif defined(TARGET_ARM64)
const CorDebugRegister ptrRegister = REGISTER_ARM64_X0;
#elif defined(TARGET_ARM)
const CorDebugRegister ptrRegister = REGISTER_ARM_R0;
const CorDebugRegister ptrHighWordRegister = REGISTER_ARM_R1;
#endif
CorElementType corReturnType = pType->GetElementType();
switch (corReturnType)
{
default:
return m_nativeFrame->GetLocalRegisterValue(ptrRegister, pType, ppReturnValue);
case ELEMENT_TYPE_R4:
case ELEMENT_TYPE_R8:
return m_nativeFrame->GetLocalFloatingPointValue(floatRegister, pType, ppReturnValue);
#if defined(TARGET_X86) || defined(TARGET_ARM)
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
return m_nativeFrame->GetLocalDoubleRegisterValue(ptrHighWordRegister, ptrRegister, pType, ppReturnValue);
#endif
}
}
HRESULT CordbJITILFrame::EnumerateLocalVariablesEx(ILCodeKind flags, ICorDebugValueEnum **ppValueEnum)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppValueEnum, ICorDebugValueEnum **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
HRESULT hr = S_OK;
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
EX_TRY
{
RSInitHolder<CordbValueEnum> cdVE(new CordbValueEnum(m_nativeFrame,
flags == ILCODE_ORIGINAL_IL ? CordbValueEnum::LOCAL_VARS_ORIGINAL_IL : CordbValueEnum::LOCAL_VARS_REJIT_IL));
// Initialize the new enum
hr = cdVE->Init();
IfFailThrow(hr);
cdVE.TransferOwnershipExternal(ppValueEnum);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetLocalVariableEx(ILCodeKind flags, DWORD dwIndex, ICorDebugValue **ppValue)
{
PUBLIC_REENTRANT_API_ENTRY(this);
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
if (flags == ILCODE_REJIT_IL && m_pReJitCode == NULL)
return E_INVALIDARG;
const ICorDebugInfo::NativeVarInfo *pNativeInfo;
//
// First, make sure that we've got the jitted variable location data
// loaded from the left side.
//
HRESULT hr = S_OK;
EX_TRY
{
m_nativeFrame->m_nativeCode->LoadNativeInfo(); //throws
ULONG cArgs;
if (m_fVarArgFnx && (!m_sigParserCached.IsNull()))
{
cArgs = m_allArgsCount;
}
else
{
cArgs = m_nativeFrame->m_nativeCode->GetFixedArgCount();
}
hr = ILVariableToNative(dwIndex + cArgs, &pNativeInfo);
IfFailThrow(hr);
LoadGenericArgs();
// Get the type of this argument from the function
CordbType *type;
CordbILCode* pActiveCode = m_pReJitCode != NULL ? m_pReJitCode : m_ilCode;
hr = pActiveCode->GetLocalVariableType(dwIndex, &(this->m_genericArgs), &type);
IfFailThrow(hr);
// if the caller wants the original IL local, it should implicitly map to the same index
// variable in the profiler instrumented code. We can't determine whether the instrumented code
// really adhered to this, but we can check two things:
// a) the requested index was valid in the original signature
// (GetLocalVariableType will return E_INVALIDARG if not)
// b) the type of local in the original signature matches the type of local in the instrumented signature
// (the code below will return CORDBG_E_IL_VAR_NOT_AVAILABLE)
if (flags == ILCODE_ORIGINAL_IL && m_pReJitCode != NULL)
{
CordbType* pOriginalType;
hr = m_ilCode->GetLocalVariableType(dwIndex, &(this->m_genericArgs), &pOriginalType);
IfFailThrow(hr);
if (pOriginalType != type)
{
IfFailThrow(CORDBG_E_IL_VAR_NOT_AVAILABLE); // bad profiler, it shouldn't have changed types
}
}
hr = GetNativeVariable(type, pNativeInfo, ppValue);
IfFailThrow(hr);
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbJITILFrame::GetCodeEx(ILCodeKind flags, ICorDebugCode **ppCode)
{
HRESULT hr = S_OK;
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
if (flags != ILCODE_ORIGINAL_IL && flags != ILCODE_REJIT_IL)
return E_INVALIDARG;
if (flags == ILCODE_ORIGINAL_IL)
{
return GetCode(ppCode);
}
else
{
*ppCode = m_pReJitCode;
if (m_pReJitCode != NULL)
{
m_pReJitCode->ExternalAddRef();
}
}
return S_OK;
}
CordbILCode* CordbJITILFrame::GetOriginalILCode()
{
return m_ilCode;
}
CordbReJitILCode* CordbJITILFrame::GetReJitILCode()
{
return m_pReJitCode;
}
/* ------------------------------------------------------------------------- *
* Eval class
* ------------------------------------------------------------------------- */
CordbEval::CordbEval(CordbThread *pThread)
: CordbBase(pThread->GetProcess(), 0, enumCordbEval),
m_thread(pThread), // implicit InternalAddRef
m_function(NULL),
m_complete(false),
m_successful(false),
m_aborted(false),
m_resultAddr(NULL),
m_evalDuringException(false)
{
m_vmObjectHandle = VMPTR_OBJECTHANDLE::NullPtr();
m_debuggerEvalKey = LSPTR_DEBUGGEREVAL::NullPtr();
m_resultType.elementType = ELEMENT_TYPE_VOID;
m_resultAppDomainToken = VMPTR_AppDomain::NullPtr();
CordbAppDomain * pDomain = m_thread->GetAppDomain();
(void)pDomain; //prevent "unused variable" error from GCC
#ifdef _DEBUG
// Remember what AD we started in so that we can check that we finish there too.
m_DbgAppDomainStarted = pDomain;
#endif
// Place ourselves on the processes neuter-list.
HRESULT hr = S_OK;
EX_TRY
{
GetProcess()->AddToLeftSideResourceCleanupList(this);
}
EX_CATCH_HRESULT(hr);
SetUnrecoverableIfFailed(GetProcess(), hr);
}
CordbEval::~CordbEval()
{
_ASSERTE(IsNeutered());
}
// Free the left-side resources for the eval.
void CordbEval::NeuterLeftSideResources()
{
SendCleanup();
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
Neuter();
}
// Neuter the CordbEval
//
// Assumptions:
// By the time we neuter the eval, it's associated left-side resources
// are already cleaned up (either explicitly from calling code:CordbEval::SendCleanup
// or implicitly from the left-side exiting).
//
// Notes:
// We place ourselves on a neuter list. This gets called when the neuterlist sweeps.
void CordbEval::Neuter()
{
// By now, we should have freed our target-resources (code:CordbEval::NeuterLeftSideResources
// or code:CordbEval::SendCleanup), unless the target is dead (terminated or about to exit).
BOOL fTargetIsDead = !GetProcess()->IsSafeToSendEvents() || GetProcess()->m_exiting;
(void)fTargetIsDead; //prevent "unused variable" error from GCC
_ASSERTE(fTargetIsDead || (m_debuggerEvalKey == NULL));
m_thread.Clear();
CordbBase::Neuter();
}
HRESULT CordbEval::SendCleanup()
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
HRESULT hr = S_OK;
// Send a message to the left side to release the eval object over
// there if one exists.
if ((m_debuggerEvalKey != NULL) &&
GetProcess()->IsSafeToSendEvents())
{
// Call Abort() before doing new CallFunction()
if (!m_complete)
return CORDBG_E_FUNC_EVAL_NOT_COMPLETE;
// Release the left side handle to the object
DebuggerIPCEvent event;
GetProcess()->InitIPCEvent(
&event,
DB_IPCE_FUNC_EVAL_CLEANUP,
true,
m_thread->GetAppDomain()->GetADToken());
event.FuncEvalCleanup.debuggerEvalKey = m_debuggerEvalKey;
hr = GetProcess()->SendIPCEvent(&event, sizeof(DebuggerIPCEvent));
IfFailRet(hr);
#if _DEBUG
if (SUCCEEDED(hr))
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_CLEANUP_RESULT);
#endif
// Null out the key so we don't try to do this again.
m_debuggerEvalKey = LSPTR_DEBUGGEREVAL::NullPtr();
hr = event.hr;
}
// Release the cached HandleValue for the result. This may cleanup resources,
// like our object handle to the func-eval result.
m_pHandleValue.Clear();
return hr;
}
HRESULT CordbEval::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEval)
{
*pInterface = static_cast<ICorDebugEval*>(this);
}
else if (id == IID_ICorDebugEval2)
{
*pInterface = static_cast<ICorDebugEval2*>(this);
}
else if (id == IID_IUnknown)
{
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugEval*>(this));
}
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
//
// Gather data about an argument to either CallFunction or NewObject
// and place it into a DebuggerIPCE_FuncEvalArgData struct for passing
// to the Left Side.
//
HRESULT CordbEval::GatherArgInfo(ICorDebugValue *pValue,
DebuggerIPCE_FuncEvalArgData *argData)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
HRESULT hr;
CORDB_ADDRESS addr;
CorElementType ty;
bool needRelease = false;
pValue->GetType(&ty);
// Note: if the value passed in is in fact a byref, then we need to dereference it to get to the real thing. Passing
// a byref as a byref to a func eval is never right.
if ((ty == ELEMENT_TYPE_BYREF) || (ty == ELEMENT_TYPE_TYPEDBYREF))
{
ICorDebugReferenceValue *prv = NULL;
// The value had better implement ICorDebugReference value.
IfFailRet(pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&prv));
// This really should always work for a byref, unless we're out of memory.
hr = prv->Dereference(&pValue);
prv->Release();
IfFailRet(hr);
// Make sure to get the type we were referencing for use below.
pValue->GetType(&ty);
needRelease = true;
}
// We should never have a byref by this point.
_ASSERTE((ty != ELEMENT_TYPE_BYREF) && (ty != ELEMENT_TYPE_TYPEDBYREF));
pValue->GetAddress(&addr);
argData->argAddr = CORDB_ADDRESS_TO_PTR(addr);
argData->argElementType = ty;
argData->argIsHandleValue = false;
argData->argIsLiteral = false;
argData->fullArgType = NULL;
argData->fullArgTypeNodeCount = 0;
// We have to have knowledge of our value implementation here,
// which it would nice if we didn't have to know.
CordbValue *cv = NULL;
switch(ty)
{
case ELEMENT_TYPE_CLASS:
case ELEMENT_TYPE_OBJECT:
case ELEMENT_TYPE_STRING:
case ELEMENT_TYPE_PTR:
case ELEMENT_TYPE_ARRAY:
case ELEMENT_TYPE_SZARRAY:
{
ICorDebugHandleValue *pHandle = NULL;
pValue->QueryInterface(IID_ICorDebugHandleValue, (void **) &pHandle);
if (pHandle == NULL)
{
// A reference value
cv = static_cast<CordbValue*> (static_cast<CordbReferenceValue*> (pValue));
argData->argIsHandleValue = !(((CordbReferenceValue *)pValue)->m_valueHome.ObjHandleIsNull());
// Is this a literal value? If, we'll copy the data to the
// buffer area so the left side can get it.
CordbReferenceValue *rv;
rv = static_cast<CordbReferenceValue*>(pValue);
argData->argIsLiteral = rv->CopyLiteralData(argData->argLiteralData);
if (rv->GetValueHome())
{
rv->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
}
else
{
argData->argIsHandleValue = true;
argData->argIsLiteral = false;
pHandle->Release();
argData->argHome.kind = RAK_NONE;
}
}
break;
case ELEMENT_TYPE_VALUETYPE: // OK: this E_T_VALUETYPE comes ICorDebugValue::GetType
// A value class object
cv = static_cast<CordbValue*> (static_cast<CordbVCObjectValue*>(static_cast<ICorDebugObjectValue*> (pValue)));
// The EE does not guarantee to have exact type information
// available for all struct types, so we indicate the type by using a
// DebuggerIPCE_TypeArgData serialization of a type.
//
// At the moment the LHS only cares about this data
// when boxing the "this" pointer.
{
CordbVCObjectValue * pVCObjVal =
static_cast<CordbVCObjectValue *>(static_cast<ICorDebugObjectValue*> (pValue));
unsigned int fullArgTypeNodeCount = 0;
cv->m_type->CountTypeDataNodes(&fullArgTypeNodeCount);
_ASSERTE(fullArgTypeNodeCount > 0);
unsigned int bufferSize = sizeof(DebuggerIPCE_TypeArgData) * fullArgTypeNodeCount;
DebuggerIPCE_TypeArgData *bufferFrom = (DebuggerIPCE_TypeArgData *) _alloca(bufferSize);
DebuggerIPCE_TypeArgData *curr = bufferFrom;
CordbType::GatherTypeData(cv->m_type, &curr);
void *buffer = NULL;
IfFailRet(m_thread->GetProcess()->GetAndWriteRemoteBuffer(m_thread->GetAppDomain(), bufferSize, bufferFrom, &buffer));
argData->fullArgType = buffer;
argData->fullArgTypeNodeCount = fullArgTypeNodeCount;
// Is it enregistered?
if ((addr == NULL) && (pVCObjVal->GetValueHome() != NULL))
{
pVCObjVal->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
}
break;
default:
// A generic value
cv = static_cast<CordbValue*> (static_cast<CordbGenericValue*> (pValue));
// Is this a literal value? If, we'll copy the data to the
// buffer area so the left side can get it.
CordbGenericValue *gv = (CordbGenericValue*)pValue;
argData->argIsLiteral = gv->CopyLiteralData(argData->argLiteralData);
// Is it enregistered?
if ((addr == NULL) && (gv->GetValueHome() != NULL))
{
gv->GetValueHome()->CopyToIPCEType(&(argData->argHome));
}
break;
}
// Release pValue if we got it via a dereference from above.
if (needRelease)
pValue->Release();
return S_OK;
}
HRESULT CordbEval::SendFuncEval(unsigned int genericArgsCount,
ICorDebugType *genericArgs[],
void *argData1, unsigned int argData1Size,
void *argData2, unsigned int argData2Size,
DebuggerIPCEvent * event)
{
FAIL_IF_NEUTERED(this);
INTERNAL_SYNC_API_ENTRY(GetProcess()); //
unsigned int genericArgsNodeCount = 0;
DebuggerIPCE_TypeArgData *tyargData = NULL;
CordbType::CountTypeDataNodesForInstantiation(genericArgsCount,genericArgs,&genericArgsNodeCount);
unsigned int tyargDataSize = sizeof(DebuggerIPCE_TypeArgData) * genericArgsNodeCount;
if (genericArgsNodeCount > 0)
{
tyargData = new (nothrow) DebuggerIPCE_TypeArgData[genericArgsNodeCount];
if (tyargData == NULL)
{
return E_OUTOFMEMORY;
}
DebuggerIPCE_TypeArgData *curr_tyargData = tyargData;
CordbType::GatherTypeDataForInstantiation(genericArgsCount, genericArgs, &curr_tyargData);
}
event->FuncEval.genericArgsNodeCount = genericArgsNodeCount;
// Are we doing an eval during an exception? If so, we need to remember
// that over here and also tell the Left Side.
event->FuncEval.evalDuringException = m_thread->HasException();
m_evalDuringException = !!event->FuncEval.evalDuringException;
m_vmThreadOldExceptionHandle = m_thread->GetThreadExceptionRawObjectHandle();
// Corresponding Release() on DB_IPCE_FUNC_EVAL_COMPLETE.
// If a func eval is aborted, the LHS may not complete the abort
// immediately and hence we cant do a SendCleanup(). Hence, we maintain
// an extra ref-count to determine when this can be done.
AddRef();
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(event, sizeof(DebuggerIPCEvent));
// If the send failed, return that failure.
if (FAILED(hr))
goto LExit;
_ASSERTE(event->type == DB_IPCE_FUNC_EVAL_SETUP_RESULT);
hr = event->hr;
// Memory has been allocated to hold info about each argument on
// the left side now, so copy the argument data over to the left
// side. No need to send another event, since the left side won't
// take any more action on this evaluation until the process is
// continued anyway.
//
// The type arguments come first, followed by up to two blobs of data
// for other arguments.
if (SUCCEEDED(hr))
{
EX_TRY
{
CORDB_ADDRESS argdata = event->FuncEvalSetupComplete.argDataArea;
if ((tyargData != NULL) && (tyargDataSize != 0))
{
TargetBuffer tb(argdata, tyargDataSize);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) tyargData); // throws
argdata += tyargDataSize;
}
if ((argData1 != NULL) && (argData1Size != 0))
{
TargetBuffer tb(argdata, argData1Size);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) argData1); // throws
argdata += argData1Size;
}
if ((argData2 != NULL) && (argData2Size != 0))
{
TargetBuffer tb(argdata, argData2Size);
m_thread->GetProcess()->SafeWriteBuffer(tb, (const BYTE*) argData2); // throws
argdata += argData2Size;
}
}
EX_CATCH_HRESULT(hr);
}
LExit:
if (tyargData)
{
delete [] tyargData;
}
// Save the key to the eval on the left side for future reference.
if (SUCCEEDED(hr))
{
m_debuggerEvalKey = event->FuncEvalSetupComplete.debuggerEvalKey;
m_thread->GetProcess()->IncrementOutstandingEvalCount();
}
else
{
// We dont expect to receive a DB_IPCE_FUNC_EVAL_COMPLETE, so just release here
Release();
}
return hr;
}
// Get the AppDomain that an object lives in.
// This does not adjust any reference counts.
// Returns NULL if we can't determine the appdomain, or if the value is known to be agile.
CordbAppDomain * GetAppDomainFromValue(ICorDebugValue * pValue)
{
// Unfortunately, there's no direct way to cast from an ICDValue to a CordbValue.
// So we need to QI for the culprit interfaces and check specifically.
{
RSExtSmartPtr<ICorDebugHandleValue> handleP;
pValue->QueryInterface(IID_ICorDebugHandleValue, (void**)&handleP);
if (handleP != NULL)
{
CordbHandleValue * chp = static_cast<CordbHandleValue *> (handleP.GetValue());
return chp->GetAppDomain();
}
}
{
RSExtSmartPtr<ICorDebugReferenceValue> refP;
pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&refP);
if (refP != NULL)
{
CordbReferenceValue * crp = static_cast<CordbReferenceValue *> (refP.GetValue());
return crp->GetAppDomain();
}
}
{
RSExtSmartPtr<ICorDebugObjectValue> objP;
pValue->QueryInterface(IID_ICorDebugObjectValue, (void**)&objP);
if (objP != NULL)
{
CordbVCObjectValue * crp = static_cast<CordbVCObjectValue*> (objP.GetValue());
return crp->GetAppDomain();
}
}
// Assume nothing else has AD affinity.
return NULL;
}
HRESULT CordbEval::CallFunction(ICorDebugFunction *pFunction,
ULONG32 nArgs,
ICorDebugValue *pArgs[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
if (GetProcess()->GetShim() == NULL)
{
return E_NOTIMPL;
}
return CallParameterizedFunction(pFunction,0,NULL,nArgs,pArgs);
}
//-----------------------------------------------------------------------------
// See if we can convert general Func-eval failure HRs (which are usually based on EE-invariants that
// may be meaningless to the user) into a more specific user-friendly hr.
// Doing the conversions here in the RS (instead of in the LS) makes it more clear that these
// HRs definitely map to concepts described by the ICorDebugAPI instead of EE-invariants.
// It also lets us clearly prioritize the HRs in case of ambiguity.
//-----------------------------------------------------------------------------
HRESULT CordbEval::FilterHR(HRESULT hr)
{
// Currently, we only make CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT more specific.
// If it's not that HR, then shortcut our work.
if (hr != CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT)
{
return hr;
}
// In the case of conflicting HRs (if the func-eval fails for multiple reasons),
// we'll try to give priority to the more general HR.
// This communicates the quickest action for the user to be able to get to a
// func-eval friendly spot. It also means less churn in the hrs we return
// because specific hrs are more likely to change than general ones.
// If we got CORDBG_E_ILLEGAL_AT_GC_UNSAFE_POINT, check the common reasons.
// We'll use the Right-Side's intimate knowledge of the Left-Side to guess _why_
// it's a GC-unsafe spot, and then we'll communicate that back w/ a more meaningful HR.
// If GC safe-spots change, then these errors should be updated.
//
// Most likely is if we're in native code. Check that first.
//
// In V2, we do this check by checking if the leaf chain is native. Since we have no chain in Arrowhead,
// we can't do this check. Instead, we check whether the active frame is NULL or not. If it's NULL,
// then we are stopped in native code.
//
HRESULT hrTemp = S_OK;
if (GetProcess()->GetShim() != NULL)
{
// the V2 case
RSExtSmartPtr<ICorDebugChain> pChain;
hrTemp = m_thread->GetActiveChain(&pChain);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
// pChain should never be NULL here, since we should have at least one thread start chain even if
// there is no managed code on the stack, but let's just be extra careful here.
if (pChain == NULL)
{
return hr;
}
BOOL fManagedChain;
hrTemp = pChain->IsManaged(&fManagedChain);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
if (fManagedChain == FALSE)
{
return CORDBG_E_ILLEGAL_IN_NATIVE_CODE;
}
}
RSExtSmartPtr<ICorDebugFrame> pIFrame;
hrTemp = m_thread->GetActiveFrame(&pIFrame);
if (FAILED(hrTemp))
{
// just return the original HR if this call fails
return hr;
}
CordbFrame * pFrame = NULL;
pFrame = CordbFrame::GetCordbFrameFromInterface(pIFrame);
if (GetProcess()->GetShim() == NULL)
{
// the Arrowhead case
if (pFrame == NULL)
{
return CORDBG_E_ILLEGAL_IN_NATIVE_CODE;
}
}
// Next, check if we're in optimized code.
// Optimized code doesn't directly mean that func-evals are illegal; but it greatly
// increases the odds of being at a GC-unsafe point.
// We give this failure higher precedence than the "Is in prolog" failure.
if (pFrame != NULL)
{
CordbNativeFrame * pNativeFrame = pFrame->GetAsNativeFrame();
if (pNativeFrame != NULL)
{
CordbNativeCode * pCode = pNativeFrame->GetNativeCode();
if (pCode != NULL)
{
DWORD flags;
hrTemp = pCode->GetModule()->GetJITCompilerFlags(&flags);
if (SUCCEEDED(hrTemp))
{
if ((flags & CORDEBUG_JIT_DISABLE_OPTIMIZATION) != CORDEBUG_JIT_DISABLE_OPTIMIZATION)
{
return CORDBG_E_ILLEGAL_IN_OPTIMIZED_CODE;
}
} // GetCompilerFlags
} // Code
CordbJITILFrame * pILFrame = pNativeFrame->m_JITILFrame;
if (pILFrame != NULL)
{
if (pILFrame->m_mapping == MAPPING_PROLOG)
{
return CORDBG_E_ILLEGAL_IN_PROLOG;
}
}
} // Native Frame
}
// No filtering.
return hr;
}
//---------------------------------------------------------------------------------------
//
// This routine calls a function with the given set of type arguments and actual arguments.
// This is the jumping off point for func-eval.
//
// Arguments:
// pFunction - The function to call.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
// nArgs - The number of arguments for the method in rgpArgs
// rgpArgs - An array of pointers to values for the arguments to the method.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::CallParameterizedFunction(ICorDebugFunction *pFunction,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[],
ULONG32 nArgs,
ICorDebugValue * rgpArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pFunction, ICorDebugFunction *);
if (nArgs > 0)
{
VALIDATE_POINTER_TO_OBJECT_ARRAY(rgpArgs, ICorDebugValue *, nArgs, true, true);
}
HRESULT hr = E_FAIL;
{
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugValues and ICorDebugTypes are in
// the same appdomain as the function. Verify this.
CordbAppDomain * pMethodAppDomain = (static_cast<CordbFunction *> (pFunction))->GetAppDomain();
if (!DoAppDomainsMatch(pMethodAppDomain, nTypeArgs, rgpTypeArgs, nArgs, rgpArgs))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
// Must be locked to get a cookie
RsPtrHolder<CordbEval> hFuncEval(this);
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
lockHolder.Release(); // release to send an IPC event.
// Remember the function that we're evaluating.
m_function = static_cast<CordbFunction *>(pFunction);
m_evalType = DB_IPCE_FET_NORMAL;
// Arrange the arguments into a form that the left side can deal
// with. We do this before starting the func eval setup to ensure
// that we can complete this step before mutating the left
// side.
DebuggerIPCE_FuncEvalArgData * pArgData = NULL;
if (nArgs > 0)
{
// We need to make the same type of array that the left side
// holds.
pArgData = new (nothrow) DebuggerIPCE_FuncEvalArgData[nArgs];
if (pArgData == NULL)
{
return E_OUTOFMEMORY;
}
// For each argument, convert its home into something the left
// side can understand.
for (unsigned int i = 0; i < nArgs; i++)
{
hr = GatherArgInfo(rgpArgs[i], &(pArgData[i]));
if (FAILED(hr))
{
delete [] pArgData;
return hr;
}
}
}
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = m_function->GetMetadataToken();
event.FuncEval.vmDomainAssembly = m_function->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = nArgs;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs,
rgpTypeArgs,
reinterpret_cast<void *>(pArgData),
sizeof(DebuggerIPCE_FuncEvalArgData) * nArgs,
NULL,
0,
&event);
// Cleanup
if (pArgData)
{
delete [] pArgData;
}
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
}
// Convert from LS EE-centric failure code to something more friendly to end-users.
// Success HRs will not be converted.
hr = FilterHR(hr);
// Return any failure the Left Side may have told us about.
return hr;
}
BOOL CordbEval::DoAppDomainsMatch( CordbAppDomain * pAppDomain,
ULONG32 nTypes,
ICorDebugType *pTypes[],
ULONG32 nValues,
ICorDebugValue *pValues[] )
{
_ASSERTE( !(pTypes == NULL && nTypes != 0) );
_ASSERTE( !(pValues == NULL && nValues != 0) );
// Make sure each value is in the appdomain.
for(unsigned int i = 0; i < nValues; i++)
{
// Assuming that only Ref Values have AD affinity
CordbAppDomain * pValueAppDomain = GetAppDomainFromValue( pValues[i] );
if ((pValueAppDomain != NULL) && (pValueAppDomain != pAppDomain))
{
LOG((LF_CORDB,LL_INFO1000, "CordbEval::DADM - AD mismatch. appDomain=0x%08x, param #%d=0x%08x, must fail.\n",
pAppDomain, i, pValueAppDomain));
return FALSE;
}
}
for(unsigned int i = 0; i < nTypes; i++ )
{
CordbType* t = static_cast<CordbType*>( pTypes[i] );
CordbAppDomain * pTypeAppDomain = t->GetAppDomain();
if( pTypeAppDomain != NULL && pTypeAppDomain != pAppDomain )
{
LOG((LF_CORDB,LL_INFO1000, "CordbEval::DADM - AD mismatch. appDomain=0x%08x, type param #%d=0x%08x, must fail.\n",
pAppDomain, i, pTypeAppDomain));
return FALSE;
}
}
return TRUE;
}
HRESULT CordbEval::NewObject(ICorDebugFunction *pConstructor,
ULONG32 nArgs,
ICorDebugValue *pArgs[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewParameterizedObject(pConstructor,0,NULL,nArgs,pArgs);
}
//---------------------------------------------------------------------------------------
//
// This routine calls a constructor with the given set of type arguments and actual arguments.
// This is the jumping off point for func-evaling "new".
//
// Arguments:
// pConstructor - The function to call.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
// nArgs - The number of arguments for the method in rgpArgs
// rgpArgs - An array of pointers to values for the arguments to the method.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedObject(ICorDebugFunction * pConstructor,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[],
ULONG32 nArgs,
ICorDebugValue * rgpArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pConstructor, ICorDebugFunction *);
VALIDATE_POINTER_TO_OBJECT_ARRAY(rgpArgs, ICorDebugValue *, nArgs, true, true);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugValues and ICorDebugTypes are in
// the same appdomain as the constructor. Verify this.
CordbAppDomain * pConstructorAppDomain = (static_cast<CordbFunction *> (pConstructor))->GetAppDomain();
if (!DoAppDomainsMatch(pConstructorAppDomain, nTypeArgs, rgpTypeArgs, nArgs, rgpArgs))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
lockHolder.Release();
// Remember the function that we're evaluating.
m_function = static_cast<CordbFunction *>(pConstructor);
m_evalType = DB_IPCE_FET_NEW_OBJECT;
// Arrange the arguments into a form that the left side can deal
// with. We do this before starting the func eval setup to ensure
// that we can complete this step before mutating up the left
// side.
DebuggerIPCE_FuncEvalArgData * pArgData = NULL;
if (nArgs > 0)
{
// We need to make the same type of array that the left side
// holds.
pArgData = new (nothrow) DebuggerIPCE_FuncEvalArgData[nArgs];
if (pArgData == NULL)
{
return E_OUTOFMEMORY;
}
// For each argument, convert its home into something the left
// side can understand.
for (unsigned int i = 0; i < nArgs; i++)
{
hr = GatherArgInfo(rgpArgs[i], &(pArgData[i]));
if (FAILED(hr))
{
delete [] pArgData;
return hr;
}
}
}
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = m_function->GetMetadataToken();
event.FuncEval.vmDomainAssembly = m_function->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = nArgs;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs,
rgpTypeArgs,
reinterpret_cast<void *>(pArgData),
sizeof(DebuggerIPCE_FuncEvalArgData) * nArgs,
NULL,
0,
&event);
// Cleanup
if (pArgData)
{
delete [] pArgData;
}
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::NewObjectNoConstructor(ICorDebugClass *pClass)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewParameterizedObjectNoConstructor(pClass,0,NULL);
}
//---------------------------------------------------------------------------------------
//
// This routine creates an object of a certain type, but does not call the constructor
// for the type on the object.
//
// Arguments:
// pClass - the type of the object to create.
// nTypeArgs - The number of type-arguments for the method in rgpTypeArgs
// rgpTypeArgs - An array of pointers to types.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedObjectNoConstructor(ICorDebugClass * pClass,
ULONG32 nTypeArgs,
ICorDebugType * rgpTypeArgs[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pClass, ICorDebugClass *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// The LS will assume that all of the ICorDebugTypes are in
// the same appdomain as the class. Verify this.
CordbAppDomain * pClassAppDomain = (static_cast<CordbClass *> (pClass))->GetAppDomain();
if (!DoAppDomainsMatch(pClassAppDomain, nTypeArgs, rgpTypeArgs, 0, NULL))
{
return ErrWrapper(CORDBG_E_APPDOMAIN_MISMATCH);
}
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Remember the function that we're evaluating.
m_class = (CordbClass*)pClass;
m_evalType = DB_IPCE_FET_NEW_OBJECT_NC;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = (mdTypeDef)m_class->m_id;
event.FuncEval.vmDomainAssembly = m_class->GetModule()->GetRuntimeDomainAssembly();
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = nTypeArgs;
hr = SendFuncEval(nTypeArgs, rgpTypeArgs, NULL, 0, NULL, 0, &event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
/*
*
* NewString
*
* This routine is the interface function for ICorDebugEval::NewString
*
* Parameters:
* string - the string to create - must be null-terminated
*
* Return Value:
* HRESULT from the helper routines on RS and LS.
*
*/
HRESULT CordbEval::NewString(LPCWSTR string)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
return NewStringWithLength(string, (UINT)wcslen(string));
}
//---------------------------------------------------------------------------------------
//
// This routine is the interface function for ICorDebugEval::NewStringWithLength.
//
// Arguments:
// wszString - the string to create
// iLength - the number of characters that you want to create. Can include embedded nulls.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewStringWithLength(LPCWSTR wszString, UINT iLength)
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(wszString, LPCWSTR); // Gotta have a string...
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Callers are free to reuse an ICorDebugEval object for multiple
// evals. Since we create a Left Side eval representation each
// time, we need to be sure to clean it up now that we know we're
// done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Length of the string? Don't account for null as COMString::NewString is length-based
SIZE_T cbString = iLength * sizeof(WCHAR);
// Remember that we're doing a func eval for a new string.
m_function = NULL;
m_evalType = DB_IPCE_FET_NEW_STRING;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.stringSize = cbString;
// Note: no function or module here...
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = mdTypeDefNil;
event.FuncEval.vmDomainAssembly = VMPTR_DomainAssembly::NullPtr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = 0;
event.FuncEval.genericArgsNodeCount = 0;
hr = SendFuncEval(0, NULL, (void *)wszString, (unsigned int)cbString, NULL, 0, &event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::NewArray(CorElementType elementType,
ICorDebugClass *pElementClass,
ULONG32 rank,
ULONG32 dims[],
ULONG32 lowBounds[])
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pElementClass, ICorDebugClass *);
// If you want a class, you gotta pass a class.
if ((elementType == ELEMENT_TYPE_CLASS) && (pElementClass == NULL))
return E_INVALIDARG;
// If you want an array of objects, then why pass a class?
if ((elementType == ELEMENT_TYPE_OBJECT) && (pElementClass != NULL))
return E_INVALIDARG;
// Arg check...
if (elementType == ELEMENT_TYPE_VOID)
return E_INVALIDARG;
CordbType *typ;
HRESULT hr = S_OK;
hr = CordbType::MkUnparameterizedType(m_thread->GetAppDomain(), elementType, (CordbClass *) pElementClass, &typ);
if (FAILED(hr))
return hr;
return NewParameterizedArray(typ, rank,dims,lowBounds);
}
//---------------------------------------------------------------------------------------
//
// This routine sets up a func-eval to create a new array of the given type.
//
// Arguments:
// pElementType - The type of each element of the array.
// rank - Rank of the array.
// rgDimensions - Array of dimensions for the array.
// rmLowBounds - Array of lower bounds on the array.
//
// Return Value:
// HRESULT for the operation
//
HRESULT CordbEval::NewParameterizedArray(ICorDebugType * pElementType,
ULONG32 rank,
ULONG32 rgDimensions[],
ULONG32 rgLowBounds[])
{
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pElementType, ICorDebugType *);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
// Callers are free to reuse an ICorDebugEval object for multiple evals. Since we create a Left Side eval
// representation each time, we need to be sure to clean it up now that we know we're done with it.
HRESULT hr = SendCleanup();
if (FAILED(hr))
{
return hr;
}
// Arg check...
if ((rank == 0) || (rgDimensions == NULL))
{
return E_INVALIDARG;
}
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
RsPtrHolder<CordbEval> hFuncEval(this);
lockHolder.Release(); // release to send an IPC event.
if (hFuncEval.Ptr().IsNull())
{
return E_OUTOFMEMORY;
}
// Remember that we're doing a func eval for a new string.
m_function = NULL;
m_evalType = DB_IPCE_FET_NEW_ARRAY;
// Send over to the left side and get it to setup this eval.
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event, DB_IPCE_FUNC_EVAL, true, m_thread->GetAppDomain()->GetADToken());
event.FuncEval.vmThreadToken = m_thread->m_vmThreadToken;
event.FuncEval.funcEvalType = m_evalType;
event.FuncEval.funcEvalKey = hFuncEval.Ptr();
event.FuncEval.arrayRank = rank;
// Note: no function or module here...
event.FuncEval.funcMetadataToken = mdMethodDefNil;
event.FuncEval.funcClassMetadataToken = mdTypeDefNil;
event.FuncEval.vmDomainAssembly = VMPTR_DomainAssembly::NullPtr();
event.FuncEval.argCount = 0;
event.FuncEval.genericArgsCount = 1;
// Prefast overflow sanity check.
S_UINT32 allocSize = S_UINT32(rank) * S_UINT32(sizeof(SIZE_T));
if (allocSize.IsOverflow())
{
return E_INVALIDARG;
}
// Just in case sizeof(SIZE_T) != sizeof(ULONG32)
SIZE_T * rgDimensionsSizeT = reinterpret_cast<SIZE_T *>(_alloca(allocSize.Value()));
for (unsigned int i = 0; i < rank; i++)
{
rgDimensionsSizeT[i] = rgDimensions[i];
}
ICorDebugType * rgpGenericArgs[1];
rgpGenericArgs[0] = pElementType;
// @dbgtodo funceval : lower bounds were ignored in V1 - fix this.
hr = SendFuncEval(1,
rgpGenericArgs,
reinterpret_cast<void *>(rgDimensionsSizeT),
rank * sizeof(SIZE_T),
NULL, // (void*)lowBounds,
0, // ((lowBounds == NULL) ? 0 : rank * sizeof(SIZE_T)),
&event);
if (SUCCEEDED(hr))
{
hFuncEval.SuppressRelease(); // Now LS owns.
}
// Return any failure the Left Side may have told us about.
return hr;
}
HRESULT CordbEval::IsActive(BOOL *pbActive)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(pbActive, BOOL *);
*pbActive = (m_complete == true);
return S_OK;
}
/*
* This routine submits an abort request to the LS.
*
* Parameters:
* None.
*
* Returns:
* The HRESULT as returned by the LS.
*
*/
HRESULT
CordbEval::Abort(
void
)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_ALLOW_LIVE_DO_STOPGO(GetProcess());
//
// No need to abort if its already completed.
//
if (m_complete)
{
return S_OK;
}
//
// Can't abort if its never even been started.
//
if (m_debuggerEvalKey == NULL)
{
return E_INVALIDARG;
}
CORDBRequireProcessStateOK(m_thread->GetProcess());
//
// Send over to the left side to get the eval aborted.
//
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event,
DB_IPCE_FUNC_EVAL_ABORT,
true,
m_thread->GetAppDomain()->GetADToken()
);
event.FuncEvalAbort.debuggerEvalKey = m_debuggerEvalKey;
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(&event,
sizeof(DebuggerIPCEvent)
);
//
// If the send failed, return that failure.
//
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_ABORT_RESULT);
//
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
//
m_thread->GetProcess()->m_continueCounter++;
hr = event.hr;
return hr;
}
HRESULT CordbEval::GetResult(ICorDebugValue **ppResult)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppResult, ICorDebugValue **);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
*ppResult = NULL;
// Is the evaluation complete?
if (!m_complete)
{
return CORDBG_E_FUNC_EVAL_NOT_COMPLETE;
}
if (m_aborted)
{
return CORDBG_S_FUNC_EVAL_ABORTED;
}
// Does the evaluation have a result?
if (m_resultType.elementType == ELEMENT_TYPE_VOID)
{
return CORDBG_S_FUNC_EVAL_HAS_NO_RESULT;
}
HRESULT hr = S_OK;
EX_TRY
{
// Make a ICorDebugValue out of the result.
CordbAppDomain * pAppDomain;
if (!m_resultAppDomainToken.IsNull())
{
// @dbgtodo funceval - push this up
RSLockHolder lockHolder(GetProcess()->GetProcessLock());
pAppDomain = m_thread->GetProcess()->LookupOrCreateAppDomain(m_resultAppDomainToken);
}
else
{
pAppDomain = m_thread->GetAppDomain();
}
PREFIX_ASSUME(pAppDomain != NULL);
CordbType * pType = NULL;
hr = CordbType::TypeDataToType(pAppDomain, &m_resultType, &pType);
IfFailThrow(hr);
bool resultInHandle =
((m_resultType.elementType == ELEMENT_TYPE_CLASS) ||
(m_resultType.elementType == ELEMENT_TYPE_SZARRAY) ||
(m_resultType.elementType == ELEMENT_TYPE_OBJECT) ||
(m_resultType.elementType == ELEMENT_TYPE_ARRAY) ||
(m_resultType.elementType == ELEMENT_TYPE_STRING));
if (resultInHandle)
{
// if object handle is null here, something has gone wrong!!!
_ASSERTE(!m_vmObjectHandle.IsNull());
if (m_pHandleValue == NULL)
{
// Create CordbHandleValue for result
RSInitHolder<CordbHandleValue> pHandleValue(new CordbHandleValue(pAppDomain, pType, HANDLE_STRONG));
// Initialize the handle value object. The HandleValue will now
// own the m_objectHandle.
hr = pHandleValue->Init(m_vmObjectHandle);
if (!SUCCEEDED(hr))
{
// Neuter the new object we've been working on. This will
// call Dispose(), and that will go back to the left side
// and free the handle that we got above.
pHandleValue->NeuterLeftSideResources();
//
// Do not delete chv here. The neuter list still has a reference to it, and it will be cleaned up automatically.
ThrowHR(hr);
}
m_pHandleValue.Assign(pHandleValue);
pHandleValue.ClearAndMarkDontNeuter();
}
// This AddRef is for caller to release
//
*ppResult = m_pHandleValue;
m_pHandleValue->ExternalAddRef();
}
else if (CorIsPrimitiveType(m_resultType.elementType) && (m_resultType.elementType != ELEMENT_TYPE_STRING))
{
// create a CordbGenericValue flagged as a literal
hr = CordbEval::CreatePrimitiveLiteral(pType, ppResult);
}
else
{
TargetBuffer remoteValue(m_resultAddr, CordbValue::GetSizeForType(pType, kBoxed));
// Now that we have the module, go ahead and create the result.
CordbValue::CreateValueByType(pAppDomain,
pType,
true,
remoteValue,
MemoryRange(NULL, 0),
NULL,
ppResult); // throws
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbEval::GetThread(ICorDebugThread **ppThread)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
VALIDATE_POINTER_TO_OBJECT(ppThread, ICorDebugThread **);
*ppThread = static_cast<ICorDebugThread*> (m_thread);
m_thread->ExternalAddRef();
return S_OK;
}
// Create a RS literal for primitive type funceval result. In case the result is used as an argument for
// another funceval, we need to make sure that we're not relying on the LS value, which will be freed and
// thus unavailable.
// Arguments:
// input: pType - CordbType instance representing the type of the primitive value
// output: ppValue - ICorDebugValue representing the result as a literal CordbGenericValue
// Return Value:
// hr: may fail for OOM, ReadProcessMemory failures
HRESULT CordbEval::CreatePrimitiveLiteral(CordbType * pType,
ICorDebugValue ** ppValue)
{
CordbGenericValue * gv = NULL;
HRESULT hr = S_OK;
EX_TRY
{
// Create a generic value.
gv = new CordbGenericValue(pType);
// initialize the local value
int size = CordbValue::GetSizeForType(pType, kBoxed);
if (size > 8)
{
ThrowHR(HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
}
TargetBuffer remoteValue(m_resultAddr, size);
BYTE localBuffer[8] = {0};
GetProcess()->SafeReadBuffer (remoteValue, localBuffer);
gv->SetValue(localBuffer);
// Do not delete gv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
gv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugGenericValue*)gv;
}
EX_CATCH_HRESULT(hr);
return hr;
}
HRESULT CordbEval::CreateValue(CorElementType elementType,
ICorDebugClass *pElementClass,
ICorDebugValue **ppValue)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
CordbType *typ;
// @todo: only primitive values right now.
if (((elementType < ELEMENT_TYPE_BOOLEAN) ||
(elementType > ELEMENT_TYPE_R8)) &&
!(elementType == ELEMENT_TYPE_CLASS))
return E_INVALIDARG;
HRESULT hr = S_OK;
// MkUnparameterizedType now works if you give it ELEMENT_TYPE_CLASS and
// a null pElementClass - it returns the type for ELEMENT_TYPE_OBJECT.
hr = CordbType::MkUnparameterizedType(m_thread->GetAppDomain(), elementType, (CordbClass *) pElementClass, &typ);
if (FAILED(hr))
return hr;
return CreateValueForType(typ, ppValue);
}
// create an ICDValue to represent a value for a funceval
// Arguments:
// input: pIType - the type for the new value
// output: ppValue - the new ICDValue. If there is a failure of some sort, this will be NULL
// ReturnValue: S_OK on success (ppValue should contain a non-NULL address)
// E_OUTOFMEMORY, if we can't allocate space for the new ICDValue
// Notes: We can also get read process memory errors or E_INVALIDARG if errors occur during initialization,
// but in that case, we don't return the hresult. Instead, we just never update ppValue, so it will still be
// NULL on exit.
HRESULT CordbEval::CreateValueForType(ICorDebugType * pIType,
ICorDebugValue ** ppValue)
{
HRESULT hr = S_OK;
PUBLIC_REENTRANT_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_REQUIRE_STOPPED_MAY_FAIL(GetProcess());
VALIDATE_POINTER_TO_OBJECT(ppValue, ICorDebugValue **);
VALIDATE_POINTER_TO_OBJECT(pIType, ICorDebugType*);
*ppValue = NULL;
CordbType *pType = static_cast<CordbType *> (pIType);
CorElementType elementType = pType->m_elementType;
// We don't support IntPtr and UIntPtr types as arguments here, but we do support these types as results
// (see code:CordbEval::CreatePrimitiveLiteral) and we have changed the LS to support them as well
if (((elementType < ELEMENT_TYPE_BOOLEAN) ||
(elementType > ELEMENT_TYPE_R8)) &&
!((elementType == ELEMENT_TYPE_CLASS) || (elementType == ELEMENT_TYPE_OBJECT)))
return E_INVALIDARG;
// Note: ELEMENT_TYPE_OBJECT is what we'll get for the null reference case, so allow that.
if ((elementType == ELEMENT_TYPE_CLASS) || (elementType == ELEMENT_TYPE_OBJECT))
{
EX_TRY
{
// create a reference value
CordbReferenceValue *rv = new CordbReferenceValue(pType);
if (SUCCEEDED(rv->InitRef(MemoryRange(NULL,0))))
{
// Do not delete rv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
rv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugReferenceValue*)rv;
}
}
EX_CATCH_HRESULT(hr);
}
else
{
CordbGenericValue * gv = NULL;
EX_TRY
{
// Create a generic value.
gv = new CordbGenericValue(pType);
gv->Init(MemoryRange(NULL,0));
// Do not delete gv here even if the initialization fails.
// The neuter list still has a reference to it, and it will be cleaned up automatically.
gv->ExternalAddRef();
*ppValue = (ICorDebugValue*)(ICorDebugGenericValue*)gv;
}
EX_CATCH_HRESULT(hr);
}
return hr;
} // CordbEval::CreateValueForType
/* ------------------------------------------------------------------------- *
* CordbEval2
*
* Extentions to the CordbEval class for Whidbey
*
* ------------------------------------------------------------------------- */
/*
* This routine submits a rude abort request to the LS.
*
* Parameters:
* None.
*
* Returns:
* The HRESULT as returned by the LS.
*
*/
HRESULT
CordbEval::RudeAbort(
void
)
{
PUBLIC_API_ENTRY(this);
FAIL_IF_NEUTERED(this);
ATT_ALLOW_LIVE_DO_STOPGO(GetProcess());
//
// No need to abort if its already completed.
//
if (m_complete)
{
return S_OK;
}
//
// Can't abort if its never even been started.
//
if (m_debuggerEvalKey == NULL)
{
return E_INVALIDARG;
}
CORDBRequireProcessStateOK(m_thread->GetProcess());
//
// Send over to the left side to get the eval aborted.
//
DebuggerIPCEvent event;
m_thread->GetProcess()->InitIPCEvent(&event,
DB_IPCE_FUNC_EVAL_RUDE_ABORT,
true,
m_thread->GetAppDomain()->GetADToken()
);
event.FuncEvalRudeAbort.debuggerEvalKey = m_debuggerEvalKey;
HRESULT hr = m_thread->GetProcess()->SendIPCEvent(&event,
sizeof(DebuggerIPCEvent)
);
//
// If the send failed, return that failure.
//
if (FAILED(hr))
{
return hr;
}
_ASSERTE(event.type == DB_IPCE_FUNC_EVAL_RUDE_ABORT_RESULT);
//
// Since we may have
// overwritten anything (objects, code, etc), we should mark
// everything as needing to be re-cached.
//
m_thread->GetProcess()->m_continueCounter++;
hr = event.hr;
return hr;
}
/* ------------------------------------------------------------------------- *
* CodeParameter Enumerator class
* ------------------------------------------------------------------------- */
CordbCodeEnum::CordbCodeEnum(unsigned int cCodes, RSSmartPtr<CordbCode> * ppCodes) :
CordbBase(NULL, 0)
{
// Because the array is of smart-ptrs, the elements are already reffed
// We now take ownership of the array itself too.
m_ppCodes = ppCodes;
m_iCurrent = 0;
m_iMax = cCodes;
}
CordbCodeEnum::~CordbCodeEnum()
{
// This will invoke the SmartPtr dtors on each element and call release.
delete [] m_ppCodes;
}
HRESULT CordbCodeEnum::QueryInterface(REFIID id, void **pInterface)
{
if (id == IID_ICorDebugEnum)
*pInterface = static_cast<ICorDebugEnum*>(this);
else if (id == IID_ICorDebugCodeEnum)
*pInterface = static_cast<ICorDebugCodeEnum*>(this);
else if (id == IID_IUnknown)
*pInterface = static_cast<IUnknown*>(static_cast<ICorDebugCodeEnum*>(this));
else
{
*pInterface = NULL;
return E_NOINTERFACE;
}
ExternalAddRef();
return S_OK;
}
HRESULT CordbCodeEnum::Skip(ULONG celt)
{
HRESULT hr = E_FAIL;
if ( (m_iCurrent+celt) < m_iMax ||
celt == 0)
{
m_iCurrent += celt;
hr = S_OK;
}
return hr;
}
HRESULT CordbCodeEnum::Reset()
{
m_iCurrent = 0;
return S_OK;
}
HRESULT CordbCodeEnum::Clone(ICorDebugEnum **ppEnum)
{
VALIDATE_POINTER_TO_OBJECT(ppEnum, ICorDebugEnum **);
(*ppEnum) = NULL;
HRESULT hr = S_OK;
// Create a new copy of the array because the CordbCodeEnum will
// take ownership of it.
RSSmartPtr<CordbCode> * ppCodes = new (nothrow) RSSmartPtr<CordbCode> [m_iMax];
if (ppCodes == NULL)
{
return E_OUTOFMEMORY;
}
for(UINT i = 0; i < m_iMax; i++)
{
ppCodes[i].Assign(m_ppCodes[i]);
}
CordbCodeEnum *pCVE = new (nothrow) CordbCodeEnum( m_iMax, ppCodes);
if ( pCVE == NULL )
{
delete [] ppCodes;
hr = E_OUTOFMEMORY;
goto LExit;
}
pCVE->ExternalAddRef();
(*ppEnum) = (ICorDebugEnum*)pCVE;
LExit:
return hr;
}
HRESULT CordbCodeEnum::GetCount(ULONG *pcelt)
{
VALIDATE_POINTER_TO_OBJECT(pcelt, ULONG *);
if( pcelt == NULL)
return E_INVALIDARG;
(*pcelt) = m_iMax;
return S_OK;
}
//
// In the event of failure, the current pointer will be left at
// one element past the troublesome element. Thus, if one were
// to repeatedly ask for one element to iterate through the
// array, you would iterate exactly m_iMax times, regardless
// of individual failures.
HRESULT CordbCodeEnum::Next(ULONG celt, ICorDebugCode *values[], ULONG *pceltFetched)
{
VALIDATE_POINTER_TO_OBJECT_ARRAY(values, ICorDebugClass *,
celt, true, true);
VALIDATE_POINTER_TO_OBJECT_OR_NULL(pceltFetched, ULONG *);
if ((pceltFetched == NULL) && (celt != 1))
{
return E_INVALIDARG;
}
if (celt == 0)
{
if (pceltFetched != NULL)
{
*pceltFetched = 0;
}
return S_OK;
}
HRESULT hr = S_OK;
int iMax = min( m_iMax, m_iCurrent+celt);
int i;
for (i = m_iCurrent; i < iMax; i++)
{
values[i-m_iCurrent] = m_ppCodes[i];
values[i-m_iCurrent]->AddRef();
}
int count = (i - m_iCurrent);
if ( FAILED( hr ) )
{ //we failed: +1 pushes us past troublesome element
m_iCurrent += 1 + count;
}
else
{
m_iCurrent += count;
}
if (pceltFetched != NULL)
{
*pceltFetched = count;
}
//
// If we reached the end of the enumeration, but not the end
// of the number of requested items, we return S_FALSE.
//
if (((ULONG)count) < celt)
{
return S_FALSE;
}
return hr;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/tests/palsuite/c_runtime/sscanf_s/test10/test10.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test10.c
**
** Purpose: Tests sscanf_s with wide characters
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../sscanf_s.h"
PALTEST(c_runtime_sscanf_s_test10_paltest_sscanf_test10, "c_runtime/sscanf_s/test10/paltest_sscanf_test10")
{
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
DoWCharTest("1234d", "%C", convert("1"), 1);
DoWCharTest("1234d", "%C", convert("1"), 1);
DoWCharTest("abc", "%2C", convert("ab"), 2);
DoWCharTest(" ab", "%C", convert(" "), 1);
DoCharTest("ab", "%hC", "a", 1);
DoWCharTest("ab", "%lC", convert("a"), 1);
DoWCharTest("ab", "%LC", convert("a"), 1);
DoWCharTest("ab", "%I64C", convert("a"), 1);
PAL_Terminate();
return PASS;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test10.c
**
** Purpose: Tests sscanf_s with wide characters
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../sscanf_s.h"
PALTEST(c_runtime_sscanf_s_test10_paltest_sscanf_test10, "c_runtime/sscanf_s/test10/paltest_sscanf_test10")
{
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
DoWCharTest("1234d", "%C", convert("1"), 1);
DoWCharTest("1234d", "%C", convert("1"), 1);
DoWCharTest("abc", "%2C", convert("ab"), 2);
DoWCharTest(" ab", "%C", convert(" "), 1);
DoCharTest("ab", "%hC", "a", 1);
DoWCharTest("ab", "%lC", convert("a"), 1);
DoWCharTest("ab", "%LC", convert("a"), 1);
DoWCharTest("ab", "%I64C", convert("a"), 1);
PAL_Terminate();
return PASS;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/inc/cycletimer.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// CycleTimer has methods related to getting cycle timer values.
// It uses an all-statics class as a namespace mechanism.
//
#ifndef _CYCLETIMER_H_
#define _CYCLETIMER_H_
#include "windef.h"
class CycleTimer
{
// This returns the value of the *non-thread-virtualized* cycle counter.
static unsigned __int64 GetCycleCount64();
// This wraps GetCycleCount64 in the signature of QueryThreadCycleTime -- but note
// that it ignores the "thrd" argument.
static BOOL WINAPI DefaultQueryThreadCycleTime(_In_ HANDLE thrd, _Out_ PULONG64 cyclesPtr);
// The function pointer type for QueryThreadCycleTime.
typedef BOOL (WINAPI *QueryThreadCycleTimeSig)(_In_ HANDLE, _Out_ PULONG64);
// Returns a function pointer for QueryThreadCycleTime, or else BadFPtr.
static QueryThreadCycleTimeSig GetQueryThreadCycleTime();
// Initialized once from NULL to either BadFPtr or QueryThreadCycleTime.
static QueryThreadCycleTimeSig s_QueryThreadCycleTimeFPtr;
public:
// This method computes the number of cycles/sec for the current machine. The cycles are those counted
// by GetThreadCycleTime; we assume that these are of equal duration, though that is not necessarily true.
// If any OS interaction fails, returns 0.0.
static double CyclesPerSecond();
// Does a large number of queries, and returns the average of their overhead, so other measurements
// can adjust for this.
static unsigned __int64 QueryOverhead();
// There's no "native" atomic add for 64 bit, so we have this convenience function.
static void InterlockedAddU64(unsigned __int64* loc, unsigned __int64 amount);
// Attempts to query the cycle counter of the current thread. If successful, returns "true" and sets
// *cycles to the cycle counter value. Otherwise, returns false. Note that the value returned is (currently)
// virtualized to the current thread only on Windows; on non-windows x86/x64 platforms, directly reads
// the cycle counter and returns that value.
static bool GetThreadCyclesS(unsigned __int64* cycles);
};
#endif // _CYCLETIMER_H_
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// CycleTimer has methods related to getting cycle timer values.
// It uses an all-statics class as a namespace mechanism.
//
#ifndef _CYCLETIMER_H_
#define _CYCLETIMER_H_
#include "windef.h"
class CycleTimer
{
// This returns the value of the *non-thread-virtualized* cycle counter.
static unsigned __int64 GetCycleCount64();
// This wraps GetCycleCount64 in the signature of QueryThreadCycleTime -- but note
// that it ignores the "thrd" argument.
static BOOL WINAPI DefaultQueryThreadCycleTime(_In_ HANDLE thrd, _Out_ PULONG64 cyclesPtr);
// The function pointer type for QueryThreadCycleTime.
typedef BOOL (WINAPI *QueryThreadCycleTimeSig)(_In_ HANDLE, _Out_ PULONG64);
// Returns a function pointer for QueryThreadCycleTime, or else BadFPtr.
static QueryThreadCycleTimeSig GetQueryThreadCycleTime();
// Initialized once from NULL to either BadFPtr or QueryThreadCycleTime.
static QueryThreadCycleTimeSig s_QueryThreadCycleTimeFPtr;
public:
// This method computes the number of cycles/sec for the current machine. The cycles are those counted
// by GetThreadCycleTime; we assume that these are of equal duration, though that is not necessarily true.
// If any OS interaction fails, returns 0.0.
static double CyclesPerSecond();
// Does a large number of queries, and returns the average of their overhead, so other measurements
// can adjust for this.
static unsigned __int64 QueryOverhead();
// There's no "native" atomic add for 64 bit, so we have this convenience function.
static void InterlockedAddU64(unsigned __int64* loc, unsigned __int64 amount);
// Attempts to query the cycle counter of the current thread. If successful, returns "true" and sets
// *cycles to the cycle counter value. Otherwise, returns false. Note that the value returned is (currently)
// virtualized to the current thread only on Windows; on non-windows x86/x64 platforms, directly reads
// the cycle counter and returns that value.
static bool GetThreadCyclesS(unsigned __int64* cycles);
};
#endif // _CYCLETIMER_H_
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/jit/phase.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "phase.h"
//------------------------------------------------------------------------
// Observations ctor: snapshot key compiler variables before running a phase
//
// Arguments:
// compiler - current compiler instance
//
Phase::Observations::Observations(Compiler* compiler)
{
#ifdef DEBUG
m_compiler = compiler->impInlineRoot();
m_fgBBcount = m_compiler->fgBBcount;
m_fgBBNumMax = m_compiler->fgBBNumMax;
m_compHndBBtabCount = m_compiler->compHndBBtabCount;
m_lvaCount = m_compiler->lvaCount;
m_compGenTreeID = m_compiler->compGenTreeID;
m_compStatementID = m_compiler->compStatementID;
m_compBasicBlockID = m_compiler->compBasicBlockID;
#endif
}
//------------------------------------------------------------------------
// Observations Check: verify key compiler variables are unchanged
// if phase claims it made no modifications
//
// Arguments:
// status - status from the just-completed phase
//
void Phase::Observations::Check(PhaseStatus status)
{
#ifdef DEBUG
if (status == PhaseStatus::MODIFIED_NOTHING)
{
assert(m_fgBBcount == m_compiler->fgBBcount);
assert(m_fgBBNumMax == m_compiler->fgBBNumMax);
assert(m_compHndBBtabCount == m_compiler->compHndBBtabCount);
assert(m_lvaCount == m_compiler->lvaCount);
assert(m_compGenTreeID == m_compiler->compGenTreeID);
assert(m_compStatementID == m_compiler->compStatementID);
assert(m_compBasicBlockID == m_compiler->compBasicBlockID);
}
#endif
}
//------------------------------------------------------------------------
// Run: execute a phase and any before and after actions
//
void Phase::Run()
{
Observations observations(comp);
PrePhase();
PhaseStatus status = DoPhase();
PostPhase(status);
observations.Check(status);
}
//------------------------------------------------------------------------
// PrePhase: perform dumps and checks before a phase executes
//
void Phase::PrePhase()
{
comp->BeginPhase(m_phase);
#ifdef DEBUG
// To help in the incremental conversion of jit activity to phases
// without greatly increasing dump size or checked jit time, we
// currently allow the phases that do pre-phase checks and
// dumps via the phase object, and not via explicit calls from
// the various methods in the phase.
//
// In the long run the aim is to get rid of all pre-phase checks
// and dumps, relying instead on post-phase checks and dumps from
// the preceeding phase.
//
// Currently the list is just the set of phases that have custom
// derivations from the Phase class.
static Phases s_allowlist[] = {PHASE_BUILD_SSA, PHASE_OPTIMIZE_VALNUM_CSES, PHASE_RATIONALIZE, PHASE_LOWERING,
PHASE_STACK_LEVEL_SETTER};
bool doPrePhase = false;
for (size_t i = 0; i < sizeof(s_allowlist) / sizeof(Phases); i++)
{
if (m_phase == s_allowlist[i])
{
doPrePhase = true;
break;
}
}
if (VERBOSE)
{
if (doPrePhase)
{
printf("Trees before %s\n", m_name);
comp->fgDispBasicBlocks(true);
}
if (comp->compIsForInlining())
{
printf("\n*************** Inline @[%06u] Starting PHASE %s\n",
Compiler::dspTreeID(comp->impInlineInfo->iciCall), m_name);
}
else
{
printf("\n*************** Starting PHASE %s\n", m_name);
}
}
if (doPrePhase)
{
if ((comp->activePhaseChecks == PhaseChecks::CHECK_ALL) && (comp->expensiveDebugCheckLevel >= 2))
{
// If everyone used the Phase class, this would duplicate the PostPhase() from the previous phase.
// But, not everyone does, so go ahead and do the check here, too.
comp->fgDebugCheckBBlist();
comp->fgDebugCheckLinks();
}
}
#endif // DEBUG
#if DUMP_FLOWGRAPHS
comp->fgDumpFlowGraph(m_phase, Compiler::PhasePosition::PrePhase);
#endif // DUMP_FLOWGRAPHS
}
//------------------------------------------------------------------------
// PostPhase: perform dumps and checks after a phase executes
//
// Arguments:
// status - status from the DoPhase call for this phase
//
void Phase::PostPhase(PhaseStatus status)
{
comp->EndPhase(m_phase);
#ifdef DEBUG
// Don't dump or check post phase unless the phase made changes.
const bool madeChanges = (status != PhaseStatus::MODIFIED_NOTHING);
const char* const statusMessage = madeChanges ? "" : " [no changes]";
bool doPostPhase = false;
// To help in the incremental conversion of jit activity to phases
// without greatly increasing dump size or checked jit time, we
// currently allow the phases that do post-phase checks and
// dumps via the phase object, and not via explicit calls from
// the various methods in the phase.
//
// As we remove the explicit checks and dumps from each phase, we
// will add to this list; once all phases are updated, we can
// remove the list entirely.
//
// This list includes custom derivations from the Phase class as
// well as the new-style phases that have been updated to return
// PhaseStatus from their DoPhase methods.
//
// clang-format off
static Phases s_allowlist[] = {
PHASE_INCPROFILE,
PHASE_IBCPREP,
PHASE_IMPORTATION,
PHASE_PATCHPOINTS,
PHASE_IBCINSTR,
PHASE_INDXCALL,
PHASE_MORPH_INLINE,
PHASE_ALLOCATE_OBJECTS,
PHASE_EMPTY_TRY,
PHASE_EMPTY_FINALLY,
PHASE_MERGE_FINALLY_CHAINS,
PHASE_CLONE_FINALLY,
PHASE_MERGE_THROWS,
PHASE_FWD_SUB,
PHASE_MORPH_GLOBAL,
PHASE_INVERT_LOOPS,
PHASE_OPTIMIZE_LAYOUT,
PHASE_FIND_LOOPS,
PHASE_BUILD_SSA,
PHASE_INSERT_GC_POLLS,
PHASE_RATIONALIZE,
PHASE_LOWERING,
PHASE_STACK_LEVEL_SETTER};
// clang-format on
if (madeChanges)
{
for (size_t i = 0; i < sizeof(s_allowlist) / sizeof(Phases); i++)
{
if (m_phase == s_allowlist[i])
{
doPostPhase = true;
break;
}
}
}
if (VERBOSE)
{
if (comp->compIsForInlining())
{
printf("\n*************** Inline @[%06u] Finishing PHASE %s%s\n",
Compiler::dspTreeID(comp->impInlineInfo->iciCall), m_name, statusMessage);
}
else
{
printf("\n*************** Finishing PHASE %s%s\n", m_name, statusMessage);
}
if (doPostPhase)
{
printf("Trees after %s\n", m_name);
comp->fgDispBasicBlocks(true);
}
}
if (doPostPhase)
{
if (comp->activePhaseChecks == PhaseChecks::CHECK_ALL)
{
comp->fgDebugCheckBBlist();
comp->fgDebugCheckLinks();
comp->fgDebugCheckNodesUniqueness();
comp->fgVerifyHandlerTab();
}
}
// Optionally check profile data, if we have any.
//
// There's no point checking until we've built pred lists, as
// we can't easily reason about consistency without them.
//
// Bypass the "doPostPhase" filter until we're sure all
// phases that mess with profile counts set their phase status
// appropriately.
//
if ((JitConfig.JitProfileChecks() > 0) && comp->fgHaveProfileData() && comp->fgComputePredsDone)
{
comp->fgDebugCheckProfileData();
}
#endif // DEBUG
#if DUMP_FLOWGRAPHS
comp->fgDumpFlowGraph(m_phase, Compiler::PhasePosition::PostPhase);
#endif // DUMP_FLOWGRAPHS
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "phase.h"
//------------------------------------------------------------------------
// Observations ctor: snapshot key compiler variables before running a phase
//
// Arguments:
// compiler - current compiler instance
//
Phase::Observations::Observations(Compiler* compiler)
{
#ifdef DEBUG
m_compiler = compiler->impInlineRoot();
m_fgBBcount = m_compiler->fgBBcount;
m_fgBBNumMax = m_compiler->fgBBNumMax;
m_compHndBBtabCount = m_compiler->compHndBBtabCount;
m_lvaCount = m_compiler->lvaCount;
m_compGenTreeID = m_compiler->compGenTreeID;
m_compStatementID = m_compiler->compStatementID;
m_compBasicBlockID = m_compiler->compBasicBlockID;
#endif
}
//------------------------------------------------------------------------
// Observations Check: verify key compiler variables are unchanged
// if phase claims it made no modifications
//
// Arguments:
// status - status from the just-completed phase
//
void Phase::Observations::Check(PhaseStatus status)
{
#ifdef DEBUG
if (status == PhaseStatus::MODIFIED_NOTHING)
{
assert(m_fgBBcount == m_compiler->fgBBcount);
assert(m_fgBBNumMax == m_compiler->fgBBNumMax);
assert(m_compHndBBtabCount == m_compiler->compHndBBtabCount);
assert(m_lvaCount == m_compiler->lvaCount);
assert(m_compGenTreeID == m_compiler->compGenTreeID);
assert(m_compStatementID == m_compiler->compStatementID);
assert(m_compBasicBlockID == m_compiler->compBasicBlockID);
}
#endif
}
//------------------------------------------------------------------------
// Run: execute a phase and any before and after actions
//
void Phase::Run()
{
Observations observations(comp);
PrePhase();
PhaseStatus status = DoPhase();
PostPhase(status);
observations.Check(status);
}
//------------------------------------------------------------------------
// PrePhase: perform dumps and checks before a phase executes
//
void Phase::PrePhase()
{
comp->BeginPhase(m_phase);
#ifdef DEBUG
// To help in the incremental conversion of jit activity to phases
// without greatly increasing dump size or checked jit time, we
// currently allow the phases that do pre-phase checks and
// dumps via the phase object, and not via explicit calls from
// the various methods in the phase.
//
// In the long run the aim is to get rid of all pre-phase checks
// and dumps, relying instead on post-phase checks and dumps from
// the preceeding phase.
//
// Currently the list is just the set of phases that have custom
// derivations from the Phase class.
static Phases s_allowlist[] = {PHASE_BUILD_SSA, PHASE_OPTIMIZE_VALNUM_CSES, PHASE_RATIONALIZE, PHASE_LOWERING,
PHASE_STACK_LEVEL_SETTER};
bool doPrePhase = false;
for (size_t i = 0; i < sizeof(s_allowlist) / sizeof(Phases); i++)
{
if (m_phase == s_allowlist[i])
{
doPrePhase = true;
break;
}
}
if (VERBOSE)
{
if (doPrePhase)
{
printf("Trees before %s\n", m_name);
comp->fgDispBasicBlocks(true);
}
if (comp->compIsForInlining())
{
printf("\n*************** Inline @[%06u] Starting PHASE %s\n",
Compiler::dspTreeID(comp->impInlineInfo->iciCall), m_name);
}
else
{
printf("\n*************** Starting PHASE %s\n", m_name);
}
}
if (doPrePhase)
{
if ((comp->activePhaseChecks == PhaseChecks::CHECK_ALL) && (comp->expensiveDebugCheckLevel >= 2))
{
// If everyone used the Phase class, this would duplicate the PostPhase() from the previous phase.
// But, not everyone does, so go ahead and do the check here, too.
comp->fgDebugCheckBBlist();
comp->fgDebugCheckLinks();
}
}
#endif // DEBUG
#if DUMP_FLOWGRAPHS
comp->fgDumpFlowGraph(m_phase, Compiler::PhasePosition::PrePhase);
#endif // DUMP_FLOWGRAPHS
}
//------------------------------------------------------------------------
// PostPhase: perform dumps and checks after a phase executes
//
// Arguments:
// status - status from the DoPhase call for this phase
//
void Phase::PostPhase(PhaseStatus status)
{
comp->EndPhase(m_phase);
#ifdef DEBUG
// Don't dump or check post phase unless the phase made changes.
const bool madeChanges = (status != PhaseStatus::MODIFIED_NOTHING);
const char* const statusMessage = madeChanges ? "" : " [no changes]";
bool doPostPhase = false;
// To help in the incremental conversion of jit activity to phases
// without greatly increasing dump size or checked jit time, we
// currently allow the phases that do post-phase checks and
// dumps via the phase object, and not via explicit calls from
// the various methods in the phase.
//
// As we remove the explicit checks and dumps from each phase, we
// will add to this list; once all phases are updated, we can
// remove the list entirely.
//
// This list includes custom derivations from the Phase class as
// well as the new-style phases that have been updated to return
// PhaseStatus from their DoPhase methods.
//
// clang-format off
static Phases s_allowlist[] = {
PHASE_INCPROFILE,
PHASE_IBCPREP,
PHASE_IMPORTATION,
PHASE_PATCHPOINTS,
PHASE_IBCINSTR,
PHASE_INDXCALL,
PHASE_MORPH_INLINE,
PHASE_ALLOCATE_OBJECTS,
PHASE_EMPTY_TRY,
PHASE_EMPTY_FINALLY,
PHASE_MERGE_FINALLY_CHAINS,
PHASE_CLONE_FINALLY,
PHASE_MERGE_THROWS,
PHASE_FWD_SUB,
PHASE_MORPH_GLOBAL,
PHASE_INVERT_LOOPS,
PHASE_OPTIMIZE_LAYOUT,
PHASE_FIND_LOOPS,
PHASE_BUILD_SSA,
PHASE_INSERT_GC_POLLS,
PHASE_RATIONALIZE,
PHASE_LOWERING,
PHASE_STACK_LEVEL_SETTER};
// clang-format on
if (madeChanges)
{
for (size_t i = 0; i < sizeof(s_allowlist) / sizeof(Phases); i++)
{
if (m_phase == s_allowlist[i])
{
doPostPhase = true;
break;
}
}
}
if (VERBOSE)
{
if (comp->compIsForInlining())
{
printf("\n*************** Inline @[%06u] Finishing PHASE %s%s\n",
Compiler::dspTreeID(comp->impInlineInfo->iciCall), m_name, statusMessage);
}
else
{
printf("\n*************** Finishing PHASE %s%s\n", m_name, statusMessage);
}
if (doPostPhase)
{
printf("Trees after %s\n", m_name);
comp->fgDispBasicBlocks(true);
}
}
if (doPostPhase)
{
if (comp->activePhaseChecks == PhaseChecks::CHECK_ALL)
{
comp->fgDebugCheckBBlist();
comp->fgDebugCheckLinks();
comp->fgDebugCheckNodesUniqueness();
comp->fgVerifyHandlerTab();
}
}
// Optionally check profile data, if we have any.
//
// There's no point checking until we've built pred lists, as
// we can't easily reason about consistency without them.
//
// Bypass the "doPostPhase" filter until we're sure all
// phases that mess with profile counts set their phase status
// appropriately.
//
if ((JitConfig.JitProfileChecks() > 0) && comp->fgHaveProfileData() && comp->fgComputePredsDone)
{
comp->fgDebugCheckProfileData();
}
#endif // DEBUG
#if DUMP_FLOWGRAPHS
comp->fgDumpFlowGraph(m_phase, Compiler::PhasePosition::PostPhase);
#endif // DUMP_FLOWGRAPHS
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/inc/cortypeinfo.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This describes information about the COM+ primitive types
//
// Note: This file gets parsed by the Mono IL Linker (https://github.com/mono/linker/) which may throw an exception during parsing.
// Specifically, this (https://github.com/mono/linker/blob/master/corebuild/integration/ILLink.Tasks/CreateRuntimeRootDescriptorFile.cs) will try to
// parse this header, and it may throw an exception while doing that. If you edit this file and get a build failure on msbuild.exe D:\repos\coreclr\build.proj
// you might want to check out the parser linked above.
//
#define NO_SIZE ((BYTE)-1)
// TYPEINFO(type (CorElementType), namespace, class, size, gcType, isArray,isPrim, isFloat,isModifier,isGenVariable)
TYPEINFO(ELEMENT_TYPE_END, NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x00
TYPEINFO(ELEMENT_TYPE_VOID, "System", "Void", 0, TYPE_GC_NONE, false, true, false, false, false) // 0x01
TYPEINFO(ELEMENT_TYPE_BOOLEAN, "System", "Boolean", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x02
TYPEINFO(ELEMENT_TYPE_CHAR, "System", "Char", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x03
TYPEINFO(ELEMENT_TYPE_I1, "System", "SByte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x04
TYPEINFO(ELEMENT_TYPE_U1, "System", "Byte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x05
TYPEINFO(ELEMENT_TYPE_I2, "System", "Int16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x06
TYPEINFO(ELEMENT_TYPE_U2, "System", "UInt16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x07
TYPEINFO(ELEMENT_TYPE_I4, "System", "Int32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x08
TYPEINFO(ELEMENT_TYPE_U4, "System", "UInt32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x09
TYPEINFO(ELEMENT_TYPE_I8, "System", "Int64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0a
TYPEINFO(ELEMENT_TYPE_U8, "System", "UInt64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0b
TYPEINFO(ELEMENT_TYPE_R4, "System", "Single", 4, TYPE_GC_NONE, false, true, true, false, false) // 0x0c
TYPEINFO(ELEMENT_TYPE_R8, "System", "Double", 8, TYPE_GC_NONE, false, true, true, false, false) // 0x0d
TYPEINFO(ELEMENT_TYPE_STRING, "System", "String", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x0e
TYPEINFO(ELEMENT_TYPE_PTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, true, false) // 0x0f
TYPEINFO(ELEMENT_TYPE_BYREF, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_BYREF, false, false, false, true, false) // 0x10
TYPEINFO(ELEMENT_TYPE_VALUETYPE, NULL, NULL, NO_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x11
TYPEINFO(ELEMENT_TYPE_CLASS, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x12
TYPEINFO(ELEMENT_TYPE_VAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // 0x13
TYPEINFO(ELEMENT_TYPE_ARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x14
TYPEINFO(ELEMENT_TYPE_GENERICINST, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x15
TYPEINFO(ELEMENT_TYPE_TYPEDBYREF, "System", "TypedReference",2*TARGET_POINTER_SIZE,TYPE_GC_BYREF, false, false, false, false, false) // 0x16
TYPEINFO(ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED, NULL,NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x17 (unsupported, not in the ECMA spec)
TYPEINFO(ELEMENT_TYPE_I, "System", "IntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x18
TYPEINFO(ELEMENT_TYPE_U, "System", "UIntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x19
TYPEINFO(ELEMENT_TYPE_R_UNSUPPORTED,NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1a (unsupported, not in the ECMA spec)
TYPEINFO(ELEMENT_TYPE_FNPTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1b
TYPEINFO(ELEMENT_TYPE_OBJECT, "System", "Object", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x1c
TYPEINFO(ELEMENT_TYPE_SZARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x1d
TYPEINFO(ELEMENT_TYPE_MVAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // x01e
TYPEINFO(ELEMENT_TYPE_CMOD_REQD, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x1f
TYPEINFO(ELEMENT_TYPE_CMOD_OPT, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x20
TYPEINFO(ELEMENT_TYPE_INTERNAL, NULL, NULL, 0, TYPE_GC_OTHER, false, false, false, false, false) // 0x21
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// This describes information about the COM+ primitive types
//
// Note: This file gets parsed by the Mono IL Linker (https://github.com/mono/linker/) which may throw an exception during parsing.
// Specifically, this (https://github.com/mono/linker/blob/master/corebuild/integration/ILLink.Tasks/CreateRuntimeRootDescriptorFile.cs) will try to
// parse this header, and it may throw an exception while doing that. If you edit this file and get a build failure on msbuild.exe D:\repos\coreclr\build.proj
// you might want to check out the parser linked above.
//
#define NO_SIZE ((BYTE)-1)
// TYPEINFO(type (CorElementType), namespace, class, size, gcType, isArray,isPrim, isFloat,isModifier,isGenVariable)
TYPEINFO(ELEMENT_TYPE_END, NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x00
TYPEINFO(ELEMENT_TYPE_VOID, "System", "Void", 0, TYPE_GC_NONE, false, true, false, false, false) // 0x01
TYPEINFO(ELEMENT_TYPE_BOOLEAN, "System", "Boolean", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x02
TYPEINFO(ELEMENT_TYPE_CHAR, "System", "Char", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x03
TYPEINFO(ELEMENT_TYPE_I1, "System", "SByte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x04
TYPEINFO(ELEMENT_TYPE_U1, "System", "Byte", 1, TYPE_GC_NONE, false, true, false, false, false) // 0x05
TYPEINFO(ELEMENT_TYPE_I2, "System", "Int16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x06
TYPEINFO(ELEMENT_TYPE_U2, "System", "UInt16", 2, TYPE_GC_NONE, false, true, false, false, false) // 0x07
TYPEINFO(ELEMENT_TYPE_I4, "System", "Int32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x08
TYPEINFO(ELEMENT_TYPE_U4, "System", "UInt32", 4, TYPE_GC_NONE, false, true, false, false, false) // 0x09
TYPEINFO(ELEMENT_TYPE_I8, "System", "Int64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0a
TYPEINFO(ELEMENT_TYPE_U8, "System", "UInt64", 8, TYPE_GC_NONE, false, true, false, false, false) // 0x0b
TYPEINFO(ELEMENT_TYPE_R4, "System", "Single", 4, TYPE_GC_NONE, false, true, true, false, false) // 0x0c
TYPEINFO(ELEMENT_TYPE_R8, "System", "Double", 8, TYPE_GC_NONE, false, true, true, false, false) // 0x0d
TYPEINFO(ELEMENT_TYPE_STRING, "System", "String", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x0e
TYPEINFO(ELEMENT_TYPE_PTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, true, false) // 0x0f
TYPEINFO(ELEMENT_TYPE_BYREF, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_BYREF, false, false, false, true, false) // 0x10
TYPEINFO(ELEMENT_TYPE_VALUETYPE, NULL, NULL, NO_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x11
TYPEINFO(ELEMENT_TYPE_CLASS, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x12
TYPEINFO(ELEMENT_TYPE_VAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // 0x13
TYPEINFO(ELEMENT_TYPE_ARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x14
TYPEINFO(ELEMENT_TYPE_GENERICINST, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, false) // 0x15
TYPEINFO(ELEMENT_TYPE_TYPEDBYREF, "System", "TypedReference",2*TARGET_POINTER_SIZE,TYPE_GC_BYREF, false, false, false, false, false) // 0x16
TYPEINFO(ELEMENT_TYPE_VALUEARRAY_UNSUPPORTED, NULL,NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x17 (unsupported, not in the ECMA spec)
TYPEINFO(ELEMENT_TYPE_I, "System", "IntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x18
TYPEINFO(ELEMENT_TYPE_U, "System", "UIntPtr", TARGET_POINTER_SIZE, TYPE_GC_NONE, false, true, false, false, false) // 0x19
TYPEINFO(ELEMENT_TYPE_R_UNSUPPORTED,NULL, NULL, NO_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1a (unsupported, not in the ECMA spec)
TYPEINFO(ELEMENT_TYPE_FNPTR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_NONE, false, false, false, false, false) // 0x1b
TYPEINFO(ELEMENT_TYPE_OBJECT, "System", "Object", TARGET_POINTER_SIZE, TYPE_GC_REF, false, false, false, false, false) // 0x1c
TYPEINFO(ELEMENT_TYPE_SZARRAY, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_REF, true, false, false, true, false) // 0x1d
TYPEINFO(ELEMENT_TYPE_MVAR, NULL, NULL, TARGET_POINTER_SIZE, TYPE_GC_OTHER, false, false, false, false, true) // x01e
TYPEINFO(ELEMENT_TYPE_CMOD_REQD, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x1f
TYPEINFO(ELEMENT_TYPE_CMOD_OPT, NULL, NULL, 0, TYPE_GC_NONE, false, false, false, false, false) // 0x20
TYPEINFO(ELEMENT_TYPE_INTERNAL, NULL, NULL, 0, TYPE_GC_OTHER, false, false, false, false, false) // 0x21
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/jit64/mcc/interop/native.h
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#if defined(_MSC_VER)
#define MCC_API extern "C" __declspec(dllexport)
#define WINAPI __stdcall
#else
#define MCC_API extern "C" __attribute__((visibility("default")))
#define WINAPI
#ifdef HOST_64BIT
#define __int64 long
#else // HOST_64BIT
#define __int64 long long
#endif // HOST_64BIT
#define __int32 int
#define __int16 short int
#define __int8 char // assumes char is signed
#endif
// ---------------------------------
// VType0
// ---------------------------------
struct VType0 {
int count;
__int64 sum;
double average;
__int64 dummy1;
double dummy2;
};
// ---------------------------------
// VType1
// ---------------------------------
struct VType1 {
float count;
float sum;
float average;
float count1;
float sum1;
float average1;
float count2;
float sum2;
float average2;
float count3;
float sum3;
float average3;
float count4;
float sum4;
float average4;
float count5;
float sum5;
float average5;
};
// ---------------------------------
// VType3
// ---------------------------------
struct VType3 {
float f1;
float f2;
float f3;
float f4;
float f5;
float f6;
float f7;
float f8;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
}
void add(VType3 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
}
};
// ---------------------------------
// VType5
// ---------------------------------
struct VType5 {
__int64 f1;
__int64 f2;
__int64 f3;
__int64 f4;
__int64 f5;
__int64 f6;
__int64 f7;
__int64 f8;
__int64 f9;
__int64 f10;
__int64 f11;
__int64 f12;
__int64 f13;
__int64 f14;
__int64 f15;
__int64 f16;
__int64 f17;
__int64 f18;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
f9 = 0;
f10 = 0;
f11 = 0;
f12 = 0;
f13 = 0;
f14 = 0;
f15 = 0;
f16 = 0;
f17 = 0;
f18 = 0;
}
void add(VType5 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
}
};
// ---------------------------------
// VType6
// ---------------------------------
struct VType6 {
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
double f9;
double f10;
double f11;
double f12;
double f13;
double f14;
double f15;
double f16;
double f17;
double f18;
double f19;
double f20;
double f21;
double f22;
double f23;
double f24;
double f25;
double f26;
double f27;
double f28;
double f29;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
f9 = 0;
f10 = 0;
f11 = 0;
f12 = 0;
f13 = 0;
f14 = 0;
f15 = 0;
f16 = 0;
f17 = 0;
f18 = 0;
f19 = 0;
f20 = 0;
f21 = 0;
f22 = 0;
f23 = 0;
f24 = 0;
f25 = 0;
f26 = 0;
f27 = 0;
f28 = 0;
f29 = 0;
}
void add(VType6 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
f19 += val.f19;
f20 += val.f20;
f21 += val.f21;
f22 += val.f22;
f23 += val.f23;
f24 += val.f24;
f25 += val.f25;
f26 += val.f26;
f27 += val.f27;
f28 += val.f28;
f29 += val.f29;
}
};
// ---------------------------------
// VType7
// ---------------------------------
struct VType7 {
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
double f9;
double f10;
double f11;
double f12;
double f13;
double f14;
double f15;
double f16;
double f17;
double f18;
double f19;
double f20;
double f21;
double f22;
double f23;
double f24;
double f25;
double f26;
double f27;
double f28;
double f29;
double f30;
double f31;
double f32;
double f33;
double f34;
double f35;
double f36;
double f37;
double f38;
double f39;
double f40;
double f41;
double f42;
double f43;
double f44;
double f45;
double f46;
double f47;
double f48;
double f49;
double f50;
double f51;
double f52;
double f53;
double f54;
double f55;
double f56;
double f57;
double f58;
double f59;
double f60;
double f61;
double f62;
double f63;
double f64;
double f65;
double f66;
double f67;
double f68;
double f69;
double f70;
double f71;
double f72;
double f73;
double f74;
double f75;
double f76;
double f77;
double f78;
double f79;
double f80;
double f81;
double f82;
double f83;
double f84;
double f85;
double f86;
double f87;
double f88;
double f89;
double f90;
double f91;
double f92;
double f93;
double f94;
double f95;
double f96;
double f97;
double f98;
double f99;
double f100;
double f101;
double f102;
double f103;
double f104;
double f105;
double f106;
double f107;
double f108;
double f109;
double f110;
double f111;
double f112;
double f113;
double f114;
double f115;
double f116;
double f117;
double f118;
double f119;
double f120;
double f121;
double f122;
double f123;
double f124;
double f125;
double f126;
double f127;
double f128;
double f129;
double f130;
double f131;
double f132;
double f133;
double f134;
double f135;
double f136;
double f137;
double f138;
double f139;
double f140;
double f141;
double f142;
double f143;
double f144;
double f145;
double f146;
double f147;
double f148;
double f149;
double f150;
double f151;
double f152;
double f153;
double f154;
double f155;
double f156;
double f157;
double f158;
double f159;
double f160;
double f161;
double f162;
double f163;
double f164;
double f165;
double f166;
double f167;
double f168;
double f169;
double f170;
double f171;
double f172;
double f173;
double f174;
double f175;
double f176;
double f177;
double f178;
double f179;
double f180;
double f181;
double f182;
double f183;
double f184;
double f185;
double f186;
double f187;
double f188;
double f189;
double f190;
double f191;
double f192;
double f193;
double f194;
double f195;
double f196;
double f197;
double f198;
double f199;
double f200;
double f201;
double f202;
double f203;
double f204;
double f205;
double f206;
double f207;
double f208;
double f209;
double f210;
double f211;
double f212;
double f213;
double f214;
double f215;
double f216;
double f217;
double f218;
double f219;
double f220;
double f221;
double f222;
double f223;
double f224;
double f225;
double f226;
double f227;
double f228;
double f229;
double f230;
double f231;
double f232;
double f233;
double f234;
double f235;
double f236;
double f237;
double f238;
double f239;
double f240;
double f241;
double f242;
double f243;
double f244;
double f245;
double f246;
double f247;
double f248;
double f249;
double f250;
double f251;
double f252;
double f253;
double f254;
double f255;
double f256;
double f257;
void reset() {
f1 = (double)0.0;
f2 = (double)0.0;
f3 = (double)0.0;
f4 = (double)0.0;
f5 = (double)0.0;
f6 = (double)0.0;
f7 = (double)0.0;
f8 = (double)0.0;
f9 = (double)0.0;
f10 = (double)0.0;
f11 = (double)0.0;
f12 = (double)0.0;
f13 = (double)0.0;
f14 = (double)0.0;
f15 = (double)0.0;
f16 = (double)0.0;
f17 = (double)0.0;
f18 = (double)0.0;
f19 = (double)0.0;
f20 = (double)0.0;
f21 = (double)0.0;
f22 = (double)0.0;
f23 = (double)0.0;
f24 = (double)0.0;
f25 = (double)0.0;
f26 = (double)0.0;
f27 = (double)0.0;
f28 = (double)0.0;
f29 = (double)0.0;
f30 = (double)0.0;
f31 = (double)0.0;
f32 = (double)0.0;
f33 = (double)0.0;
f34 = (double)0.0;
f35 = (double)0.0;
f36 = (double)0.0;
f37 = (double)0.0;
f38 = (double)0.0;
f39 = (double)0.0;
f40 = (double)0.0;
f41 = (double)0.0;
f42 = (double)0.0;
f43 = (double)0.0;
f44 = (double)0.0;
f45 = (double)0.0;
f46 = (double)0.0;
f47 = (double)0.0;
f48 = (double)0.0;
f49 = (double)0.0;
f50 = (double)0.0;
f51 = (double)0.0;
f52 = (double)0.0;
f53 = (double)0.0;
f54 = (double)0.0;
f55 = (double)0.0;
f56 = (double)0.0;
f57 = (double)0.0;
f58 = (double)0.0;
f59 = (double)0.0;
f60 = (double)0.0;
f61 = (double)0.0;
f62 = (double)0.0;
f63 = (double)0.0;
f64 = (double)0.0;
f65 = (double)0.0;
f66 = (double)0.0;
f67 = (double)0.0;
f68 = (double)0.0;
f69 = (double)0.0;
f70 = (double)0.0;
f71 = (double)0.0;
f72 = (double)0.0;
f73 = (double)0.0;
f74 = (double)0.0;
f75 = (double)0.0;
f76 = (double)0.0;
f77 = (double)0.0;
f78 = (double)0.0;
f79 = (double)0.0;
f80 = (double)0.0;
f81 = (double)0.0;
f82 = (double)0.0;
f83 = (double)0.0;
f84 = (double)0.0;
f85 = (double)0.0;
f86 = (double)0.0;
f87 = (double)0.0;
f88 = (double)0.0;
f89 = (double)0.0;
f90 = (double)0.0;
f91 = (double)0.0;
f92 = (double)0.0;
f93 = (double)0.0;
f94 = (double)0.0;
f95 = (double)0.0;
f96 = (double)0.0;
f97 = (double)0.0;
f98 = (double)0.0;
f99 = (double)0.0;
f100 = (double)0.0;
f101 = (double)0.0;
f102 = (double)0.0;
f103 = (double)0.0;
f104 = (double)0.0;
f105 = (double)0.0;
f106 = (double)0.0;
f107 = (double)0.0;
f108 = (double)0.0;
f109 = (double)0.0;
f110 = (double)0.0;
f111 = (double)0.0;
f112 = (double)0.0;
f113 = (double)0.0;
f114 = (double)0.0;
f115 = (double)0.0;
f116 = (double)0.0;
f117 = (double)0.0;
f118 = (double)0.0;
f119 = (double)0.0;
f120 = (double)0.0;
f121 = (double)0.0;
f122 = (double)0.0;
f123 = (double)0.0;
f124 = (double)0.0;
f125 = (double)0.0;
f126 = (double)0.0;
f127 = (double)0.0;
f128 = (double)0.0;
f129 = (double)0.0;
f130 = (double)0.0;
f131 = (double)0.0;
f132 = (double)0.0;
f133 = (double)0.0;
f134 = (double)0.0;
f135 = (double)0.0;
f136 = (double)0.0;
f137 = (double)0.0;
f138 = (double)0.0;
f139 = (double)0.0;
f140 = (double)0.0;
f141 = (double)0.0;
f142 = (double)0.0;
f143 = (double)0.0;
f144 = (double)0.0;
f145 = (double)0.0;
f146 = (double)0.0;
f147 = (double)0.0;
f148 = (double)0.0;
f149 = (double)0.0;
f150 = (double)0.0;
f151 = (double)0.0;
f152 = (double)0.0;
f153 = (double)0.0;
f154 = (double)0.0;
f155 = (double)0.0;
f156 = (double)0.0;
f157 = (double)0.0;
f158 = (double)0.0;
f159 = (double)0.0;
f160 = (double)0.0;
f161 = (double)0.0;
f162 = (double)0.0;
f163 = (double)0.0;
f164 = (double)0.0;
f165 = (double)0.0;
f166 = (double)0.0;
f167 = (double)0.0;
f168 = (double)0.0;
f169 = (double)0.0;
f170 = (double)0.0;
f171 = (double)0.0;
f172 = (double)0.0;
f173 = (double)0.0;
f174 = (double)0.0;
f175 = (double)0.0;
f176 = (double)0.0;
f177 = (double)0.0;
f178 = (double)0.0;
f179 = (double)0.0;
f180 = (double)0.0;
f181 = (double)0.0;
f182 = (double)0.0;
f183 = (double)0.0;
f184 = (double)0.0;
f185 = (double)0.0;
f186 = (double)0.0;
f187 = (double)0.0;
f188 = (double)0.0;
f189 = (double)0.0;
f190 = (double)0.0;
f191 = (double)0.0;
f192 = (double)0.0;
f193 = (double)0.0;
f194 = (double)0.0;
f195 = (double)0.0;
f196 = (double)0.0;
f197 = (double)0.0;
f198 = (double)0.0;
f199 = (double)0.0;
f200 = (double)0.0;
f201 = (double)0.0;
f202 = (double)0.0;
f203 = (double)0.0;
f204 = (double)0.0;
f205 = (double)0.0;
f206 = (double)0.0;
f207 = (double)0.0;
f208 = (double)0.0;
f209 = (double)0.0;
f210 = (double)0.0;
f211 = (double)0.0;
f212 = (double)0.0;
f213 = (double)0.0;
f214 = (double)0.0;
f215 = (double)0.0;
f216 = (double)0.0;
f217 = (double)0.0;
f218 = (double)0.0;
f219 = (double)0.0;
f220 = (double)0.0;
f221 = (double)0.0;
f222 = (double)0.0;
f223 = (double)0.0;
f224 = (double)0.0;
f225 = (double)0.0;
f226 = (double)0.0;
f227 = (double)0.0;
f228 = (double)0.0;
f229 = (double)0.0;
f230 = (double)0.0;
f231 = (double)0.0;
f232 = (double)0.0;
f233 = (double)0.0;
f234 = (double)0.0;
f235 = (double)0.0;
f236 = (double)0.0;
f237 = (double)0.0;
f238 = (double)0.0;
f239 = (double)0.0;
f240 = (double)0.0;
f241 = (double)0.0;
f242 = (double)0.0;
f243 = (double)0.0;
f244 = (double)0.0;
f245 = (double)0.0;
f246 = (double)0.0;
f247 = (double)0.0;
f248 = (double)0.0;
f249 = (double)0.0;
f250 = (double)0.0;
f251 = (double)0.0;
f252 = (double)0.0;
f253 = (double)0.0;
f254 = (double)0.0;
f255 = (double)0.0;
f256 = (double)0.0;
f257 = (double)0.0;
}
void add(VType7 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
f19 += val.f19;
f20 += val.f20;
f21 += val.f21;
f22 += val.f22;
f23 += val.f23;
f24 += val.f24;
f25 += val.f25;
f26 += val.f26;
f27 += val.f27;
f28 += val.f28;
f29 += val.f29;
f30 += val.f30;
f31 += val.f31;
f32 += val.f32;
f33 += val.f33;
f34 += val.f34;
f35 += val.f35;
f36 += val.f36;
f37 += val.f37;
f38 += val.f38;
f39 += val.f39;
f40 += val.f40;
f41 += val.f41;
f42 += val.f42;
f43 += val.f43;
f44 += val.f44;
f45 += val.f45;
f46 += val.f46;
f47 += val.f47;
f48 += val.f48;
f49 += val.f49;
f50 += val.f50;
f51 += val.f51;
f52 += val.f52;
f53 += val.f53;
f54 += val.f54;
f55 += val.f55;
f56 += val.f56;
f57 += val.f57;
f58 += val.f58;
f59 += val.f59;
f60 += val.f60;
f61 += val.f61;
f62 += val.f62;
f63 += val.f63;
f64 += val.f64;
f65 += val.f65;
f66 += val.f66;
f67 += val.f67;
f68 += val.f68;
f69 += val.f69;
f70 += val.f70;
f71 += val.f71;
f72 += val.f72;
f73 += val.f73;
f74 += val.f74;
f75 += val.f75;
f76 += val.f76;
f77 += val.f77;
f78 += val.f78;
f79 += val.f79;
f80 += val.f80;
f81 += val.f81;
f82 += val.f82;
f83 += val.f83;
f84 += val.f84;
f85 += val.f85;
f86 += val.f86;
f87 += val.f87;
f88 += val.f88;
f89 += val.f89;
f90 += val.f90;
f91 += val.f91;
f92 += val.f92;
f93 += val.f93;
f94 += val.f94;
f95 += val.f95;
f96 += val.f96;
f97 += val.f97;
f98 += val.f98;
f99 += val.f99;
f100 += val.f100;
f101 += val.f101;
f102 += val.f102;
f103 += val.f103;
f104 += val.f104;
f105 += val.f105;
f106 += val.f106;
f107 += val.f107;
f108 += val.f108;
f109 += val.f109;
f110 += val.f110;
f111 += val.f111;
f112 += val.f112;
f113 += val.f113;
f114 += val.f114;
f115 += val.f115;
f116 += val.f116;
f117 += val.f117;
f118 += val.f118;
f119 += val.f119;
f120 += val.f120;
f121 += val.f121;
f122 += val.f122;
f123 += val.f123;
f124 += val.f124;
f125 += val.f125;
f126 += val.f126;
f127 += val.f127;
f128 += val.f128;
f129 += val.f129;
f130 += val.f130;
f131 += val.f131;
f132 += val.f132;
f133 += val.f133;
f134 += val.f134;
f135 += val.f135;
f136 += val.f136;
f137 += val.f137;
f138 += val.f138;
f139 += val.f139;
f140 += val.f140;
f141 += val.f141;
f142 += val.f142;
f143 += val.f143;
f144 += val.f144;
f145 += val.f145;
f146 += val.f146;
f147 += val.f147;
f148 += val.f148;
f149 += val.f149;
f150 += val.f150;
f151 += val.f151;
f152 += val.f152;
f153 += val.f153;
f154 += val.f154;
f155 += val.f155;
f156 += val.f156;
f157 += val.f157;
f158 += val.f158;
f159 += val.f159;
f160 += val.f160;
f161 += val.f161;
f162 += val.f162;
f163 += val.f163;
f164 += val.f164;
f165 += val.f165;
f166 += val.f166;
f167 += val.f167;
f168 += val.f168;
f169 += val.f169;
f170 += val.f170;
f171 += val.f171;
f172 += val.f172;
f173 += val.f173;
f174 += val.f174;
f175 += val.f175;
f176 += val.f176;
f177 += val.f177;
f178 += val.f178;
f179 += val.f179;
f180 += val.f180;
f181 += val.f181;
f182 += val.f182;
f183 += val.f183;
f184 += val.f184;
f185 += val.f185;
f186 += val.f186;
f187 += val.f187;
f188 += val.f188;
f189 += val.f189;
f190 += val.f190;
f191 += val.f191;
f192 += val.f192;
f193 += val.f193;
f194 += val.f194;
f195 += val.f195;
f196 += val.f196;
f197 += val.f197;
f198 += val.f198;
f199 += val.f199;
f200 += val.f200;
f201 += val.f201;
f202 += val.f202;
f203 += val.f203;
f204 += val.f204;
f205 += val.f205;
f206 += val.f206;
f207 += val.f207;
f208 += val.f208;
f209 += val.f209;
f210 += val.f210;
f211 += val.f211;
f212 += val.f212;
f213 += val.f213;
f214 += val.f214;
f215 += val.f215;
f216 += val.f216;
f217 += val.f217;
f218 += val.f218;
f219 += val.f219;
f220 += val.f220;
f221 += val.f221;
f222 += val.f222;
f223 += val.f223;
f224 += val.f224;
f225 += val.f225;
f226 += val.f226;
f227 += val.f227;
f228 += val.f228;
f229 += val.f229;
f230 += val.f230;
f231 += val.f231;
f232 += val.f232;
f233 += val.f233;
f234 += val.f234;
f235 += val.f235;
f236 += val.f236;
f237 += val.f237;
f238 += val.f238;
f239 += val.f239;
f240 += val.f240;
f241 += val.f241;
f242 += val.f242;
f243 += val.f243;
f244 += val.f244;
f245 += val.f245;
f246 += val.f246;
f247 += val.f247;
f248 += val.f248;
f249 += val.f249;
f250 += val.f250;
f251 += val.f251;
f252 += val.f252;
f253 += val.f253;
f254 += val.f254;
f255 += val.f255;
f256 += val.f256;
f257 += val.f257;
}
};
// ---------------------------------
// VType8
// ---------------------------------
struct VType8 {
void reset() {
}
void add(VType8 val) {
}
};
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#if defined(_MSC_VER)
#define MCC_API extern "C" __declspec(dllexport)
#define WINAPI __stdcall
#else
#define MCC_API extern "C" __attribute__((visibility("default")))
#define WINAPI
#ifdef HOST_64BIT
#define __int64 long
#else // HOST_64BIT
#define __int64 long long
#endif // HOST_64BIT
#define __int32 int
#define __int16 short int
#define __int8 char // assumes char is signed
#endif
// ---------------------------------
// VType0
// ---------------------------------
struct VType0 {
int count;
__int64 sum;
double average;
__int64 dummy1;
double dummy2;
};
// ---------------------------------
// VType1
// ---------------------------------
struct VType1 {
float count;
float sum;
float average;
float count1;
float sum1;
float average1;
float count2;
float sum2;
float average2;
float count3;
float sum3;
float average3;
float count4;
float sum4;
float average4;
float count5;
float sum5;
float average5;
};
// ---------------------------------
// VType3
// ---------------------------------
struct VType3 {
float f1;
float f2;
float f3;
float f4;
float f5;
float f6;
float f7;
float f8;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
}
void add(VType3 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
}
};
// ---------------------------------
// VType5
// ---------------------------------
struct VType5 {
__int64 f1;
__int64 f2;
__int64 f3;
__int64 f4;
__int64 f5;
__int64 f6;
__int64 f7;
__int64 f8;
__int64 f9;
__int64 f10;
__int64 f11;
__int64 f12;
__int64 f13;
__int64 f14;
__int64 f15;
__int64 f16;
__int64 f17;
__int64 f18;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
f9 = 0;
f10 = 0;
f11 = 0;
f12 = 0;
f13 = 0;
f14 = 0;
f15 = 0;
f16 = 0;
f17 = 0;
f18 = 0;
}
void add(VType5 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
}
};
// ---------------------------------
// VType6
// ---------------------------------
struct VType6 {
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
double f9;
double f10;
double f11;
double f12;
double f13;
double f14;
double f15;
double f16;
double f17;
double f18;
double f19;
double f20;
double f21;
double f22;
double f23;
double f24;
double f25;
double f26;
double f27;
double f28;
double f29;
void reset() {
f1 = 0;
f2 = 0;
f3 = 0;
f4 = 0;
f5 = 0;
f6 = 0;
f7 = 0;
f8 = 0;
f9 = 0;
f10 = 0;
f11 = 0;
f12 = 0;
f13 = 0;
f14 = 0;
f15 = 0;
f16 = 0;
f17 = 0;
f18 = 0;
f19 = 0;
f20 = 0;
f21 = 0;
f22 = 0;
f23 = 0;
f24 = 0;
f25 = 0;
f26 = 0;
f27 = 0;
f28 = 0;
f29 = 0;
}
void add(VType6 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
f19 += val.f19;
f20 += val.f20;
f21 += val.f21;
f22 += val.f22;
f23 += val.f23;
f24 += val.f24;
f25 += val.f25;
f26 += val.f26;
f27 += val.f27;
f28 += val.f28;
f29 += val.f29;
}
};
// ---------------------------------
// VType7
// ---------------------------------
struct VType7 {
double f1;
double f2;
double f3;
double f4;
double f5;
double f6;
double f7;
double f8;
double f9;
double f10;
double f11;
double f12;
double f13;
double f14;
double f15;
double f16;
double f17;
double f18;
double f19;
double f20;
double f21;
double f22;
double f23;
double f24;
double f25;
double f26;
double f27;
double f28;
double f29;
double f30;
double f31;
double f32;
double f33;
double f34;
double f35;
double f36;
double f37;
double f38;
double f39;
double f40;
double f41;
double f42;
double f43;
double f44;
double f45;
double f46;
double f47;
double f48;
double f49;
double f50;
double f51;
double f52;
double f53;
double f54;
double f55;
double f56;
double f57;
double f58;
double f59;
double f60;
double f61;
double f62;
double f63;
double f64;
double f65;
double f66;
double f67;
double f68;
double f69;
double f70;
double f71;
double f72;
double f73;
double f74;
double f75;
double f76;
double f77;
double f78;
double f79;
double f80;
double f81;
double f82;
double f83;
double f84;
double f85;
double f86;
double f87;
double f88;
double f89;
double f90;
double f91;
double f92;
double f93;
double f94;
double f95;
double f96;
double f97;
double f98;
double f99;
double f100;
double f101;
double f102;
double f103;
double f104;
double f105;
double f106;
double f107;
double f108;
double f109;
double f110;
double f111;
double f112;
double f113;
double f114;
double f115;
double f116;
double f117;
double f118;
double f119;
double f120;
double f121;
double f122;
double f123;
double f124;
double f125;
double f126;
double f127;
double f128;
double f129;
double f130;
double f131;
double f132;
double f133;
double f134;
double f135;
double f136;
double f137;
double f138;
double f139;
double f140;
double f141;
double f142;
double f143;
double f144;
double f145;
double f146;
double f147;
double f148;
double f149;
double f150;
double f151;
double f152;
double f153;
double f154;
double f155;
double f156;
double f157;
double f158;
double f159;
double f160;
double f161;
double f162;
double f163;
double f164;
double f165;
double f166;
double f167;
double f168;
double f169;
double f170;
double f171;
double f172;
double f173;
double f174;
double f175;
double f176;
double f177;
double f178;
double f179;
double f180;
double f181;
double f182;
double f183;
double f184;
double f185;
double f186;
double f187;
double f188;
double f189;
double f190;
double f191;
double f192;
double f193;
double f194;
double f195;
double f196;
double f197;
double f198;
double f199;
double f200;
double f201;
double f202;
double f203;
double f204;
double f205;
double f206;
double f207;
double f208;
double f209;
double f210;
double f211;
double f212;
double f213;
double f214;
double f215;
double f216;
double f217;
double f218;
double f219;
double f220;
double f221;
double f222;
double f223;
double f224;
double f225;
double f226;
double f227;
double f228;
double f229;
double f230;
double f231;
double f232;
double f233;
double f234;
double f235;
double f236;
double f237;
double f238;
double f239;
double f240;
double f241;
double f242;
double f243;
double f244;
double f245;
double f246;
double f247;
double f248;
double f249;
double f250;
double f251;
double f252;
double f253;
double f254;
double f255;
double f256;
double f257;
void reset() {
f1 = (double)0.0;
f2 = (double)0.0;
f3 = (double)0.0;
f4 = (double)0.0;
f5 = (double)0.0;
f6 = (double)0.0;
f7 = (double)0.0;
f8 = (double)0.0;
f9 = (double)0.0;
f10 = (double)0.0;
f11 = (double)0.0;
f12 = (double)0.0;
f13 = (double)0.0;
f14 = (double)0.0;
f15 = (double)0.0;
f16 = (double)0.0;
f17 = (double)0.0;
f18 = (double)0.0;
f19 = (double)0.0;
f20 = (double)0.0;
f21 = (double)0.0;
f22 = (double)0.0;
f23 = (double)0.0;
f24 = (double)0.0;
f25 = (double)0.0;
f26 = (double)0.0;
f27 = (double)0.0;
f28 = (double)0.0;
f29 = (double)0.0;
f30 = (double)0.0;
f31 = (double)0.0;
f32 = (double)0.0;
f33 = (double)0.0;
f34 = (double)0.0;
f35 = (double)0.0;
f36 = (double)0.0;
f37 = (double)0.0;
f38 = (double)0.0;
f39 = (double)0.0;
f40 = (double)0.0;
f41 = (double)0.0;
f42 = (double)0.0;
f43 = (double)0.0;
f44 = (double)0.0;
f45 = (double)0.0;
f46 = (double)0.0;
f47 = (double)0.0;
f48 = (double)0.0;
f49 = (double)0.0;
f50 = (double)0.0;
f51 = (double)0.0;
f52 = (double)0.0;
f53 = (double)0.0;
f54 = (double)0.0;
f55 = (double)0.0;
f56 = (double)0.0;
f57 = (double)0.0;
f58 = (double)0.0;
f59 = (double)0.0;
f60 = (double)0.0;
f61 = (double)0.0;
f62 = (double)0.0;
f63 = (double)0.0;
f64 = (double)0.0;
f65 = (double)0.0;
f66 = (double)0.0;
f67 = (double)0.0;
f68 = (double)0.0;
f69 = (double)0.0;
f70 = (double)0.0;
f71 = (double)0.0;
f72 = (double)0.0;
f73 = (double)0.0;
f74 = (double)0.0;
f75 = (double)0.0;
f76 = (double)0.0;
f77 = (double)0.0;
f78 = (double)0.0;
f79 = (double)0.0;
f80 = (double)0.0;
f81 = (double)0.0;
f82 = (double)0.0;
f83 = (double)0.0;
f84 = (double)0.0;
f85 = (double)0.0;
f86 = (double)0.0;
f87 = (double)0.0;
f88 = (double)0.0;
f89 = (double)0.0;
f90 = (double)0.0;
f91 = (double)0.0;
f92 = (double)0.0;
f93 = (double)0.0;
f94 = (double)0.0;
f95 = (double)0.0;
f96 = (double)0.0;
f97 = (double)0.0;
f98 = (double)0.0;
f99 = (double)0.0;
f100 = (double)0.0;
f101 = (double)0.0;
f102 = (double)0.0;
f103 = (double)0.0;
f104 = (double)0.0;
f105 = (double)0.0;
f106 = (double)0.0;
f107 = (double)0.0;
f108 = (double)0.0;
f109 = (double)0.0;
f110 = (double)0.0;
f111 = (double)0.0;
f112 = (double)0.0;
f113 = (double)0.0;
f114 = (double)0.0;
f115 = (double)0.0;
f116 = (double)0.0;
f117 = (double)0.0;
f118 = (double)0.0;
f119 = (double)0.0;
f120 = (double)0.0;
f121 = (double)0.0;
f122 = (double)0.0;
f123 = (double)0.0;
f124 = (double)0.0;
f125 = (double)0.0;
f126 = (double)0.0;
f127 = (double)0.0;
f128 = (double)0.0;
f129 = (double)0.0;
f130 = (double)0.0;
f131 = (double)0.0;
f132 = (double)0.0;
f133 = (double)0.0;
f134 = (double)0.0;
f135 = (double)0.0;
f136 = (double)0.0;
f137 = (double)0.0;
f138 = (double)0.0;
f139 = (double)0.0;
f140 = (double)0.0;
f141 = (double)0.0;
f142 = (double)0.0;
f143 = (double)0.0;
f144 = (double)0.0;
f145 = (double)0.0;
f146 = (double)0.0;
f147 = (double)0.0;
f148 = (double)0.0;
f149 = (double)0.0;
f150 = (double)0.0;
f151 = (double)0.0;
f152 = (double)0.0;
f153 = (double)0.0;
f154 = (double)0.0;
f155 = (double)0.0;
f156 = (double)0.0;
f157 = (double)0.0;
f158 = (double)0.0;
f159 = (double)0.0;
f160 = (double)0.0;
f161 = (double)0.0;
f162 = (double)0.0;
f163 = (double)0.0;
f164 = (double)0.0;
f165 = (double)0.0;
f166 = (double)0.0;
f167 = (double)0.0;
f168 = (double)0.0;
f169 = (double)0.0;
f170 = (double)0.0;
f171 = (double)0.0;
f172 = (double)0.0;
f173 = (double)0.0;
f174 = (double)0.0;
f175 = (double)0.0;
f176 = (double)0.0;
f177 = (double)0.0;
f178 = (double)0.0;
f179 = (double)0.0;
f180 = (double)0.0;
f181 = (double)0.0;
f182 = (double)0.0;
f183 = (double)0.0;
f184 = (double)0.0;
f185 = (double)0.0;
f186 = (double)0.0;
f187 = (double)0.0;
f188 = (double)0.0;
f189 = (double)0.0;
f190 = (double)0.0;
f191 = (double)0.0;
f192 = (double)0.0;
f193 = (double)0.0;
f194 = (double)0.0;
f195 = (double)0.0;
f196 = (double)0.0;
f197 = (double)0.0;
f198 = (double)0.0;
f199 = (double)0.0;
f200 = (double)0.0;
f201 = (double)0.0;
f202 = (double)0.0;
f203 = (double)0.0;
f204 = (double)0.0;
f205 = (double)0.0;
f206 = (double)0.0;
f207 = (double)0.0;
f208 = (double)0.0;
f209 = (double)0.0;
f210 = (double)0.0;
f211 = (double)0.0;
f212 = (double)0.0;
f213 = (double)0.0;
f214 = (double)0.0;
f215 = (double)0.0;
f216 = (double)0.0;
f217 = (double)0.0;
f218 = (double)0.0;
f219 = (double)0.0;
f220 = (double)0.0;
f221 = (double)0.0;
f222 = (double)0.0;
f223 = (double)0.0;
f224 = (double)0.0;
f225 = (double)0.0;
f226 = (double)0.0;
f227 = (double)0.0;
f228 = (double)0.0;
f229 = (double)0.0;
f230 = (double)0.0;
f231 = (double)0.0;
f232 = (double)0.0;
f233 = (double)0.0;
f234 = (double)0.0;
f235 = (double)0.0;
f236 = (double)0.0;
f237 = (double)0.0;
f238 = (double)0.0;
f239 = (double)0.0;
f240 = (double)0.0;
f241 = (double)0.0;
f242 = (double)0.0;
f243 = (double)0.0;
f244 = (double)0.0;
f245 = (double)0.0;
f246 = (double)0.0;
f247 = (double)0.0;
f248 = (double)0.0;
f249 = (double)0.0;
f250 = (double)0.0;
f251 = (double)0.0;
f252 = (double)0.0;
f253 = (double)0.0;
f254 = (double)0.0;
f255 = (double)0.0;
f256 = (double)0.0;
f257 = (double)0.0;
}
void add(VType7 val) {
f1 += val.f1;
f2 += val.f2;
f3 += val.f3;
f4 += val.f4;
f5 += val.f5;
f6 += val.f6;
f7 += val.f7;
f8 += val.f8;
f9 += val.f9;
f10 += val.f10;
f11 += val.f11;
f12 += val.f12;
f13 += val.f13;
f14 += val.f14;
f15 += val.f15;
f16 += val.f16;
f17 += val.f17;
f18 += val.f18;
f19 += val.f19;
f20 += val.f20;
f21 += val.f21;
f22 += val.f22;
f23 += val.f23;
f24 += val.f24;
f25 += val.f25;
f26 += val.f26;
f27 += val.f27;
f28 += val.f28;
f29 += val.f29;
f30 += val.f30;
f31 += val.f31;
f32 += val.f32;
f33 += val.f33;
f34 += val.f34;
f35 += val.f35;
f36 += val.f36;
f37 += val.f37;
f38 += val.f38;
f39 += val.f39;
f40 += val.f40;
f41 += val.f41;
f42 += val.f42;
f43 += val.f43;
f44 += val.f44;
f45 += val.f45;
f46 += val.f46;
f47 += val.f47;
f48 += val.f48;
f49 += val.f49;
f50 += val.f50;
f51 += val.f51;
f52 += val.f52;
f53 += val.f53;
f54 += val.f54;
f55 += val.f55;
f56 += val.f56;
f57 += val.f57;
f58 += val.f58;
f59 += val.f59;
f60 += val.f60;
f61 += val.f61;
f62 += val.f62;
f63 += val.f63;
f64 += val.f64;
f65 += val.f65;
f66 += val.f66;
f67 += val.f67;
f68 += val.f68;
f69 += val.f69;
f70 += val.f70;
f71 += val.f71;
f72 += val.f72;
f73 += val.f73;
f74 += val.f74;
f75 += val.f75;
f76 += val.f76;
f77 += val.f77;
f78 += val.f78;
f79 += val.f79;
f80 += val.f80;
f81 += val.f81;
f82 += val.f82;
f83 += val.f83;
f84 += val.f84;
f85 += val.f85;
f86 += val.f86;
f87 += val.f87;
f88 += val.f88;
f89 += val.f89;
f90 += val.f90;
f91 += val.f91;
f92 += val.f92;
f93 += val.f93;
f94 += val.f94;
f95 += val.f95;
f96 += val.f96;
f97 += val.f97;
f98 += val.f98;
f99 += val.f99;
f100 += val.f100;
f101 += val.f101;
f102 += val.f102;
f103 += val.f103;
f104 += val.f104;
f105 += val.f105;
f106 += val.f106;
f107 += val.f107;
f108 += val.f108;
f109 += val.f109;
f110 += val.f110;
f111 += val.f111;
f112 += val.f112;
f113 += val.f113;
f114 += val.f114;
f115 += val.f115;
f116 += val.f116;
f117 += val.f117;
f118 += val.f118;
f119 += val.f119;
f120 += val.f120;
f121 += val.f121;
f122 += val.f122;
f123 += val.f123;
f124 += val.f124;
f125 += val.f125;
f126 += val.f126;
f127 += val.f127;
f128 += val.f128;
f129 += val.f129;
f130 += val.f130;
f131 += val.f131;
f132 += val.f132;
f133 += val.f133;
f134 += val.f134;
f135 += val.f135;
f136 += val.f136;
f137 += val.f137;
f138 += val.f138;
f139 += val.f139;
f140 += val.f140;
f141 += val.f141;
f142 += val.f142;
f143 += val.f143;
f144 += val.f144;
f145 += val.f145;
f146 += val.f146;
f147 += val.f147;
f148 += val.f148;
f149 += val.f149;
f150 += val.f150;
f151 += val.f151;
f152 += val.f152;
f153 += val.f153;
f154 += val.f154;
f155 += val.f155;
f156 += val.f156;
f157 += val.f157;
f158 += val.f158;
f159 += val.f159;
f160 += val.f160;
f161 += val.f161;
f162 += val.f162;
f163 += val.f163;
f164 += val.f164;
f165 += val.f165;
f166 += val.f166;
f167 += val.f167;
f168 += val.f168;
f169 += val.f169;
f170 += val.f170;
f171 += val.f171;
f172 += val.f172;
f173 += val.f173;
f174 += val.f174;
f175 += val.f175;
f176 += val.f176;
f177 += val.f177;
f178 += val.f178;
f179 += val.f179;
f180 += val.f180;
f181 += val.f181;
f182 += val.f182;
f183 += val.f183;
f184 += val.f184;
f185 += val.f185;
f186 += val.f186;
f187 += val.f187;
f188 += val.f188;
f189 += val.f189;
f190 += val.f190;
f191 += val.f191;
f192 += val.f192;
f193 += val.f193;
f194 += val.f194;
f195 += val.f195;
f196 += val.f196;
f197 += val.f197;
f198 += val.f198;
f199 += val.f199;
f200 += val.f200;
f201 += val.f201;
f202 += val.f202;
f203 += val.f203;
f204 += val.f204;
f205 += val.f205;
f206 += val.f206;
f207 += val.f207;
f208 += val.f208;
f209 += val.f209;
f210 += val.f210;
f211 += val.f211;
f212 += val.f212;
f213 += val.f213;
f214 += val.f214;
f215 += val.f215;
f216 += val.f216;
f217 += val.f217;
f218 += val.f218;
f219 += val.f219;
f220 += val.f220;
f221 += val.f221;
f222 += val.f222;
f223 += val.f223;
f224 += val.f224;
f225 += val.f225;
f226 += val.f226;
f227 += val.f227;
f228 += val.f228;
f229 += val.f229;
f230 += val.f230;
f231 += val.f231;
f232 += val.f232;
f233 += val.f233;
f234 += val.f234;
f235 += val.f235;
f236 += val.f236;
f237 += val.f237;
f238 += val.f238;
f239 += val.f239;
f240 += val.f240;
f241 += val.f241;
f242 += val.f242;
f243 += val.f243;
f244 += val.f244;
f245 += val.f245;
f246 += val.f246;
f247 += val.f247;
f248 += val.f248;
f249 += val.f249;
f250 += val.f250;
f251 += val.f251;
f252 += val.f252;
f253 += val.f253;
f254 += val.f254;
f255 += val.f255;
f256 += val.f256;
f257 += val.f257;
}
};
// ---------------------------------
// VType8
// ---------------------------------
struct VType8 {
void reset() {
}
void add(VType8 val) {
}
};
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/md/compiler/helper.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// Helper.cpp
//
//
// Implementation of some internal APIs from code:IMetaDataHelper and code:IMetaDataEmitHelper.
//
//*****************************************************************************
#include "stdafx.h"
#include "regmeta.h"
#include "importhelper.h"
#include "mdlog.h"
#if defined(FEATURE_METADATA_EMIT) || defined(FEATURE_METADATA_INTERNAL_APIS)
//*****************************************************************************
// translating signature from one scope to another scope
//
// Implements public API code:IMetaDataEmit::TranslateSigWithScope.
// Implements internal API code:IMetaDataHelper::TranslateSigWithScope.
//*****************************************************************************
STDMETHODIMP RegMeta::TranslateSigWithScope( // S_OK or error.
IMetaDataAssemblyImport *pAssemImport, // [IN] importing assembly interface
const void *pbHashValue, // [IN] Hash Blob for Assembly.
ULONG cbHashValue, // [IN] Count of bytes.
IMetaDataImport *pImport, // [IN] importing interface
PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope
ULONG cbSigBlob, // [IN] count of bytes of signature
IMetaDataAssemblyEmit *pAssemEmit,// [IN] emit assembly interface
IMetaDataEmit *pEmit, // [IN] emit interface
PCOR_SIGNATURE pvTranslatedSig, // [OUT] buffer to hold translated signature
ULONG cbTranslatedSigMax,
ULONG *pcbTranslatedSig) // [OUT] count of bytes in the translated signature
{
#ifdef FEATURE_METADATA_EMIT
HRESULT hr = S_OK;
IMDCommon *pAssemImportMDCommon = NULL;
IMDCommon *pImportMDCommon = NULL;
BEGIN_ENTRYPOINT_NOTHROW;
RegMeta *pRegMetaAssemEmit = static_cast<RegMeta*>(pAssemEmit);
RegMeta *pRegMetaEmit = NULL;
CQuickBytes qkSigEmit;
ULONG cbEmit;
pRegMetaEmit = static_cast<RegMeta*>(pEmit);
{
// This function can cause new TypeRef being introduced.
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
_ASSERTE(pvTranslatedSig && pcbTranslatedSig);
if (pAssemImport)
{
IfFailGo(pAssemImport->QueryInterface(IID_IMDCommon, (void**)&pAssemImportMDCommon));
}
IMetaModelCommon *pAssemImportMetaModelCommon = pAssemImportMDCommon ? pAssemImportMDCommon->GetMetaModelCommon() : 0;
IfFailGo(pImport->QueryInterface(IID_IMDCommon, (void**)&pImportMDCommon));
IMetaModelCommon *pImportMetaModelCommon = pImportMDCommon->GetMetaModelCommon();
IfFailGo( ImportHelper::MergeUpdateTokenInSig( // S_OK or error.
pRegMetaAssemEmit ? &(pRegMetaAssemEmit->m_pStgdb->m_MiniMd) : 0, // The assembly emit scope.
&(pRegMetaEmit->m_pStgdb->m_MiniMd), // The emit scope.
pAssemImportMetaModelCommon, // Assembly where the signature is from.
pbHashValue, // Hash value for the import assembly.
cbHashValue, // Size in bytes.
pImportMetaModelCommon, // The scope where signature is from.
pbSigBlob, // signature from the imported scope
NULL, // Internal OID mapping structure.
&qkSigEmit, // [OUT] translated signature
0, // start from first byte of the signature
0, // don't care how many bytes consumed
&cbEmit)); // [OUT] total number of bytes write to pqkSigEmit
memcpy(pvTranslatedSig, qkSigEmit.Ptr(), cbEmit > cbTranslatedSigMax ? cbTranslatedSigMax :cbEmit );
*pcbTranslatedSig = cbEmit;
if (cbEmit > cbTranslatedSigMax)
hr = CLDB_S_TRUNCATION;
}
ErrExit:
END_ENTRYPOINT_NOTHROW;
if (pAssemImportMDCommon)
pAssemImportMDCommon->Release();
if (pImportMDCommon)
pImportMDCommon->Release();
return hr;
#else //!FEATURE_METADATA_EMIT
return E_NOTIMPL;
#endif //!FEATURE_METADATA_EMIT
} // RegMeta::TranslateSigWithScope
#endif //FEATURE_METADATA_EMIT || FEATURE_METADATA_INTERNAL_APIS
#if defined(FEATURE_METADATA_EMIT) && defined(FEATURE_METADATA_INTERNAL_APIS)
//*****************************************************************************
// Helper : Set ResolutionScope of a TypeRef
//
// Implements internal API code:IMetaDataEmitHelper::SetResolutionScopeHelper.
//*****************************************************************************
HRESULT RegMeta::SetResolutionScopeHelper( // Return hresult.
mdTypeRef tr, // [IN] TypeRef record to update
mdToken rs) // [IN] new ResolutionScope
{
HRESULT hr = NOERROR;
TypeRefRec * pTypeRef;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetTypeRefRecord(RidFromToken(tr), &pTypeRef));
IfFailGo(m_pStgdb->m_MiniMd.PutToken(TBL_TypeRef, TypeRefRec::COL_ResolutionScope, pTypeRef, rs));
ErrExit:
return hr;
} // RegMeta::SetResolutionScopeHelper
//*****************************************************************************
// Helper : Set offset of a ManifestResource
//
// Implements internal API code:IMetaDataEmitHelper::SetManifestResourceOffsetHelper.
//*****************************************************************************
HRESULT
RegMeta::SetManifestResourceOffsetHelper(
mdManifestResource mr, // [IN] The manifest token
ULONG ulOffset) // [IN] new offset
{
HRESULT hr = NOERROR;
ManifestResourceRec * pRec;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetManifestResourceRecord(RidFromToken(mr), &pRec));
pRec->SetOffset(ulOffset);
ErrExit:
return hr;
} // RegMeta::SetManifestResourceOffsetHelper
//*******************************************************************************
//
// Following APIs are used by reflection emit.
//
//*******************************************************************************
//*******************************************************************************
// helper to define method semantics
//
// Implements internal API code:IMetaDataEmitHelper::DefineMethodSemanticsHelper.
//*******************************************************************************
HRESULT RegMeta::DefineMethodSemanticsHelper(
mdToken tkAssociation, // [IN] property or event token
DWORD dwFlags, // [IN] semantics
mdMethodDef md) // [IN] method to associated with
{
HRESULT hr;
LOCKWRITE();
hr = _DefineMethodSemantics((USHORT) dwFlags, md, tkAssociation, false);
ErrExit:
return hr;
} // RegMeta::DefineMethodSemantics
//*******************************************************************************
// helper to set field layout
//
// Implements internal API code:IMetaDataEmitHelper::SetFieldLayoutHelper.
//*******************************************************************************
HRESULT RegMeta::SetFieldLayoutHelper( // Return hresult.
mdFieldDef fd, // [IN] field to associate the layout info
ULONG ulOffset) // [IN] the offset for the field
{
HRESULT hr;
FieldLayoutRec *pFieldLayoutRec;
RID iFieldLayoutRec;
LOCKWRITE();
if (ulOffset == UINT32_MAX)
{
// invalid argument
IfFailGo( E_INVALIDARG );
}
// create a field layout record
IfFailGo(m_pStgdb->m_MiniMd.AddFieldLayoutRecord(&pFieldLayoutRec, &iFieldLayoutRec));
// Set the Field entry.
IfFailGo(m_pStgdb->m_MiniMd.PutToken(
TBL_FieldLayout,
FieldLayoutRec::COL_Field,
pFieldLayoutRec,
fd));
pFieldLayoutRec->SetOffSet(ulOffset);
IfFailGo( m_pStgdb->m_MiniMd.AddFieldLayoutToHash(iFieldLayoutRec) );
ErrExit:
return hr;
} // RegMeta::SetFieldLayout
//*******************************************************************************
// helper to define event
//
// Implements internal API code:IMetaDataEmitHelper::DefineEventHelper.
//*******************************************************************************
STDMETHODIMP RegMeta::DefineEventHelper( // Return hresult.
mdTypeDef td, // [IN] the class/interface on which the event is being defined
LPCWSTR szEvent, // [IN] Name of the event
DWORD dwEventFlags, // [IN] CorEventAttr
mdToken tkEventType, // [IN] a reference (mdTypeRef or mdTypeRef) to the Event class
mdEvent *pmdEvent) // [OUT] output event token
{
HRESULT hr = S_OK;
LOG((LOGMD, "MD RegMeta::DefineEventHelper(0x%08x, %S, 0x%08x, 0x%08x, 0x%08x)\n",
td, szEvent, dwEventFlags, tkEventType, pmdEvent));
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
hr = _DefineEvent(td, szEvent, dwEventFlags, tkEventType, pmdEvent);
ErrExit:
return hr;
} // RegMeta::DefineEvent
//*******************************************************************************
// helper to add a declarative security blob to a class or method
//
// Implements internal API code:IMetaDataEmitHelper::AddDeclarativeSecurityHelper.
//*******************************************************************************
STDMETHODIMP RegMeta::AddDeclarativeSecurityHelper(
mdToken tk, // [IN] Parent token (typedef/methoddef)
DWORD dwAction, // [IN] Security action (CorDeclSecurity)
void const *pValue, // [IN] Permission set blob
DWORD cbValue, // [IN] Byte count of permission set blob
mdPermission*pmdPermission) // [OUT] Output permission token
{
HRESULT hr = S_OK;
DeclSecurityRec *pDeclSec = NULL;
RID iDeclSec;
short sAction = static_cast<short>(dwAction);
mdPermission tkPerm;
LOG((LOGMD, "MD RegMeta::AddDeclarativeSecurityHelper(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\n",
tk, dwAction, pValue, cbValue, pmdPermission));
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
_ASSERTE(TypeFromToken(tk) == mdtTypeDef || TypeFromToken(tk) == mdtMethodDef || TypeFromToken(tk) == mdtAssembly);
// Check for valid Action.
if (sAction == 0 || sAction > dclMaximumValue)
IfFailGo(E_INVALIDARG);
if (CheckDups(MDDupPermission))
{
hr = ImportHelper::FindPermission(&(m_pStgdb->m_MiniMd), tk, sAction, &tkPerm);
if (SUCCEEDED(hr))
{
// Set output parameter.
if (pmdPermission)
*pmdPermission = tkPerm;
if (IsENCOn())
IfFailGo(m_pStgdb->m_MiniMd.GetDeclSecurityRecord(RidFromToken(tkPerm), &pDeclSec));
else
{
hr = META_S_DUPLICATE;
goto ErrExit;
}
}
else if (hr != CLDB_E_RECORD_NOTFOUND)
IfFailGo(hr);
}
// Create a new record.
if (!pDeclSec)
{
IfFailGo(m_pStgdb->m_MiniMd.AddDeclSecurityRecord(&pDeclSec, &iDeclSec));
tkPerm = TokenFromRid(iDeclSec, mdtPermission);
// Set output parameter.
if (pmdPermission)
*pmdPermission = tkPerm;
// Save parent and action information.
IfFailGo(m_pStgdb->m_MiniMd.PutToken(TBL_DeclSecurity, DeclSecurityRec::COL_Parent, pDeclSec, tk));
pDeclSec->SetAction(sAction);
// Turn on the internal security flag on the parent.
if (TypeFromToken(tk) == mdtTypeDef)
IfFailGo(_TurnInternalFlagsOn(tk, tdHasSecurity));
else if (TypeFromToken(tk) == mdtMethodDef)
IfFailGo(_TurnInternalFlagsOn(tk, mdHasSecurity));
IfFailGo(UpdateENCLog(tk));
}
// Write the blob into the record.
IfFailGo(m_pStgdb->m_MiniMd.PutBlob(TBL_DeclSecurity, DeclSecurityRec::COL_PermissionSet,
pDeclSec, pValue, cbValue));
IfFailGo(UpdateENCLog(tkPerm));
ErrExit:
return hr;
} // RegMeta::AddDeclarativeSecurityHelper
//*******************************************************************************
// helper to set type's extends column
//
// Implements internal API code:IMetaDataEmitHelper::SetTypeParent.
//*******************************************************************************
HRESULT RegMeta::SetTypeParent( // Return hresult.
mdTypeDef td, // [IN] Type definition
mdToken tkExtends) // [IN] parent type
{
HRESULT hr;
TypeDefRec *pRec;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetTypeDefRecord(RidFromToken(td), &pRec));
IfFailGo( m_pStgdb->m_MiniMd.PutToken(TBL_TypeDef, TypeDefRec::COL_Extends, pRec, tkExtends) );
ErrExit:
return hr;
} // RegMeta::SetTypeParent
//*******************************************************************************
// helper to set type's extends column
//
// Implements internal API code:IMetaDataEmitHelper::AddInterfaceImpl.
//*******************************************************************************
HRESULT RegMeta::AddInterfaceImpl( // Return hresult.
mdTypeDef td, // [IN] Type definition
mdToken tkInterface) // [IN] interface type
{
HRESULT hr;
InterfaceImplRec *pRec;
RID ii;
LOCKWRITE();
hr = ImportHelper::FindInterfaceImpl(&(m_pStgdb->m_MiniMd), td, tkInterface, (mdInterfaceImpl *)&ii);
if (hr == S_OK)
goto ErrExit;
IfFailGo(m_pStgdb->m_MiniMd.AddInterfaceImplRecord(&pRec, &ii));
IfFailGo(m_pStgdb->m_MiniMd.PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Class, pRec, td));
IfFailGo(m_pStgdb->m_MiniMd.PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Interface, pRec, tkInterface));
ErrExit:
return hr;
} // RegMeta::AddInterfaceImpl
#ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB
//*******************************************************************************
// Helper to determine path separator and number of separated parts.
//
// Implements internal API code:IMDInternalEmit::GetPathSeparator.
//*******************************************************************************
HRESULT
RegMeta::GetPathSeparator(
char *path,
char *separator,
ULONG *partsCount)
{
const char delimiters[] = { '\\', '/', '\0'};
ULONG tokens = 1;
// try first
char delim = delimiters[0];
char* charPtr = strchr(path, delim);
if (charPtr != NULL)
{
// count tokens
while (charPtr != NULL)
{
tokens++;
charPtr = strchr(charPtr + 1, delim);
}
}
else
{
// try second
delim = delimiters[1];
charPtr = strchr(path, delim);
if (charPtr != NULL)
{
// count tokens
while (charPtr != NULL)
{
tokens++;
charPtr = strchr(charPtr + 1, delim);
}
}
else
{
// delimiter not found - set to \0;
delim = delimiters[2];
}
}
*separator = delim;
*partsCount = tokens;
return S_OK;
} // RegMeta::GetPathSeparator
#endif // FEATURE_METADATA_EMIT_PORTABLE_PDB
#endif //FEATURE_METADATA_EMIT && FEATURE_METADATA_INTERNAL_APIS
#ifdef FEATURE_METADATA_INTERNAL_APIS
//*****************************************************************************
// Helper : get metadata information
//
// Implements internal API code:IMetaDataHelper::GetMetadata.
//*****************************************************************************
STDMETHODIMP
RegMeta::GetMetadata(
ULONG ulSelect, // [IN] Selector.
void ** ppData) // [OUT] Put pointer to data here.
{
REGMETA_POSSIBLE_INTERNAL_POINTER_EXPOSED();
switch (ulSelect)
{
case 0:
*ppData = &m_pStgdb->m_MiniMd;
break;
case 1:
*ppData = (void*)g_CodedTokens;
break;
case 2:
*ppData = (void*)g_Tables;
break;
default:
*ppData = 0;
break;
}
return S_OK;
} // RegMeta::GetMetadata
//*******************************************************************************
// helper to change MVID
//
// Implements internal API code:IMDInternalEmit::ChangeMvid.
//*******************************************************************************
HRESULT RegMeta::ChangeMvid( // S_OK or error.
REFGUID newMvid) // GUID to use as the MVID
{
return GetMiniMd()->ChangeMvid(newMvid);
}
//*******************************************************************************
// Helper to change MDUpdateMode value to updateMode.
//
// Implements internal API code:IMDInternalEmit::SetMDUpdateMode.
//*******************************************************************************
HRESULT
RegMeta::SetMDUpdateMode(
ULONG updateMode,
ULONG * pPreviousUpdateMode)
{
HRESULT hr;
OptionValue optionValue;
IfFailGo(m_pStgdb->m_MiniMd.GetOption(&optionValue));
if (pPreviousUpdateMode != NULL)
{
*pPreviousUpdateMode = optionValue.m_UpdateMode;
}
optionValue.m_UpdateMode = updateMode;
IfFailGo(m_pStgdb->m_MiniMd.SetOption(&optionValue));
ErrExit:
return hr;
} // RegMeta::SetMDUpdateMode
#endif //FEATURE_METADATA_INTERNAL_APIS
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// Helper.cpp
//
//
// Implementation of some internal APIs from code:IMetaDataHelper and code:IMetaDataEmitHelper.
//
//*****************************************************************************
#include "stdafx.h"
#include "regmeta.h"
#include "importhelper.h"
#include "mdlog.h"
#if defined(FEATURE_METADATA_EMIT) || defined(FEATURE_METADATA_INTERNAL_APIS)
//*****************************************************************************
// translating signature from one scope to another scope
//
// Implements public API code:IMetaDataEmit::TranslateSigWithScope.
// Implements internal API code:IMetaDataHelper::TranslateSigWithScope.
//*****************************************************************************
STDMETHODIMP RegMeta::TranslateSigWithScope( // S_OK or error.
IMetaDataAssemblyImport *pAssemImport, // [IN] importing assembly interface
const void *pbHashValue, // [IN] Hash Blob for Assembly.
ULONG cbHashValue, // [IN] Count of bytes.
IMetaDataImport *pImport, // [IN] importing interface
PCCOR_SIGNATURE pbSigBlob, // [IN] signature in the importing scope
ULONG cbSigBlob, // [IN] count of bytes of signature
IMetaDataAssemblyEmit *pAssemEmit,// [IN] emit assembly interface
IMetaDataEmit *pEmit, // [IN] emit interface
PCOR_SIGNATURE pvTranslatedSig, // [OUT] buffer to hold translated signature
ULONG cbTranslatedSigMax,
ULONG *pcbTranslatedSig) // [OUT] count of bytes in the translated signature
{
#ifdef FEATURE_METADATA_EMIT
HRESULT hr = S_OK;
IMDCommon *pAssemImportMDCommon = NULL;
IMDCommon *pImportMDCommon = NULL;
BEGIN_ENTRYPOINT_NOTHROW;
RegMeta *pRegMetaAssemEmit = static_cast<RegMeta*>(pAssemEmit);
RegMeta *pRegMetaEmit = NULL;
CQuickBytes qkSigEmit;
ULONG cbEmit;
pRegMetaEmit = static_cast<RegMeta*>(pEmit);
{
// This function can cause new TypeRef being introduced.
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
_ASSERTE(pvTranslatedSig && pcbTranslatedSig);
if (pAssemImport)
{
IfFailGo(pAssemImport->QueryInterface(IID_IMDCommon, (void**)&pAssemImportMDCommon));
}
IMetaModelCommon *pAssemImportMetaModelCommon = pAssemImportMDCommon ? pAssemImportMDCommon->GetMetaModelCommon() : 0;
IfFailGo(pImport->QueryInterface(IID_IMDCommon, (void**)&pImportMDCommon));
IMetaModelCommon *pImportMetaModelCommon = pImportMDCommon->GetMetaModelCommon();
IfFailGo( ImportHelper::MergeUpdateTokenInSig( // S_OK or error.
pRegMetaAssemEmit ? &(pRegMetaAssemEmit->m_pStgdb->m_MiniMd) : 0, // The assembly emit scope.
&(pRegMetaEmit->m_pStgdb->m_MiniMd), // The emit scope.
pAssemImportMetaModelCommon, // Assembly where the signature is from.
pbHashValue, // Hash value for the import assembly.
cbHashValue, // Size in bytes.
pImportMetaModelCommon, // The scope where signature is from.
pbSigBlob, // signature from the imported scope
NULL, // Internal OID mapping structure.
&qkSigEmit, // [OUT] translated signature
0, // start from first byte of the signature
0, // don't care how many bytes consumed
&cbEmit)); // [OUT] total number of bytes write to pqkSigEmit
memcpy(pvTranslatedSig, qkSigEmit.Ptr(), cbEmit > cbTranslatedSigMax ? cbTranslatedSigMax :cbEmit );
*pcbTranslatedSig = cbEmit;
if (cbEmit > cbTranslatedSigMax)
hr = CLDB_S_TRUNCATION;
}
ErrExit:
END_ENTRYPOINT_NOTHROW;
if (pAssemImportMDCommon)
pAssemImportMDCommon->Release();
if (pImportMDCommon)
pImportMDCommon->Release();
return hr;
#else //!FEATURE_METADATA_EMIT
return E_NOTIMPL;
#endif //!FEATURE_METADATA_EMIT
} // RegMeta::TranslateSigWithScope
#endif //FEATURE_METADATA_EMIT || FEATURE_METADATA_INTERNAL_APIS
#if defined(FEATURE_METADATA_EMIT) && defined(FEATURE_METADATA_INTERNAL_APIS)
//*****************************************************************************
// Helper : Set ResolutionScope of a TypeRef
//
// Implements internal API code:IMetaDataEmitHelper::SetResolutionScopeHelper.
//*****************************************************************************
HRESULT RegMeta::SetResolutionScopeHelper( // Return hresult.
mdTypeRef tr, // [IN] TypeRef record to update
mdToken rs) // [IN] new ResolutionScope
{
HRESULT hr = NOERROR;
TypeRefRec * pTypeRef;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetTypeRefRecord(RidFromToken(tr), &pTypeRef));
IfFailGo(m_pStgdb->m_MiniMd.PutToken(TBL_TypeRef, TypeRefRec::COL_ResolutionScope, pTypeRef, rs));
ErrExit:
return hr;
} // RegMeta::SetResolutionScopeHelper
//*****************************************************************************
// Helper : Set offset of a ManifestResource
//
// Implements internal API code:IMetaDataEmitHelper::SetManifestResourceOffsetHelper.
//*****************************************************************************
HRESULT
RegMeta::SetManifestResourceOffsetHelper(
mdManifestResource mr, // [IN] The manifest token
ULONG ulOffset) // [IN] new offset
{
HRESULT hr = NOERROR;
ManifestResourceRec * pRec;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetManifestResourceRecord(RidFromToken(mr), &pRec));
pRec->SetOffset(ulOffset);
ErrExit:
return hr;
} // RegMeta::SetManifestResourceOffsetHelper
//*******************************************************************************
//
// Following APIs are used by reflection emit.
//
//*******************************************************************************
//*******************************************************************************
// helper to define method semantics
//
// Implements internal API code:IMetaDataEmitHelper::DefineMethodSemanticsHelper.
//*******************************************************************************
HRESULT RegMeta::DefineMethodSemanticsHelper(
mdToken tkAssociation, // [IN] property or event token
DWORD dwFlags, // [IN] semantics
mdMethodDef md) // [IN] method to associated with
{
HRESULT hr;
LOCKWRITE();
hr = _DefineMethodSemantics((USHORT) dwFlags, md, tkAssociation, false);
ErrExit:
return hr;
} // RegMeta::DefineMethodSemantics
//*******************************************************************************
// helper to set field layout
//
// Implements internal API code:IMetaDataEmitHelper::SetFieldLayoutHelper.
//*******************************************************************************
HRESULT RegMeta::SetFieldLayoutHelper( // Return hresult.
mdFieldDef fd, // [IN] field to associate the layout info
ULONG ulOffset) // [IN] the offset for the field
{
HRESULT hr;
FieldLayoutRec *pFieldLayoutRec;
RID iFieldLayoutRec;
LOCKWRITE();
if (ulOffset == UINT32_MAX)
{
// invalid argument
IfFailGo( E_INVALIDARG );
}
// create a field layout record
IfFailGo(m_pStgdb->m_MiniMd.AddFieldLayoutRecord(&pFieldLayoutRec, &iFieldLayoutRec));
// Set the Field entry.
IfFailGo(m_pStgdb->m_MiniMd.PutToken(
TBL_FieldLayout,
FieldLayoutRec::COL_Field,
pFieldLayoutRec,
fd));
pFieldLayoutRec->SetOffSet(ulOffset);
IfFailGo( m_pStgdb->m_MiniMd.AddFieldLayoutToHash(iFieldLayoutRec) );
ErrExit:
return hr;
} // RegMeta::SetFieldLayout
//*******************************************************************************
// helper to define event
//
// Implements internal API code:IMetaDataEmitHelper::DefineEventHelper.
//*******************************************************************************
STDMETHODIMP RegMeta::DefineEventHelper( // Return hresult.
mdTypeDef td, // [IN] the class/interface on which the event is being defined
LPCWSTR szEvent, // [IN] Name of the event
DWORD dwEventFlags, // [IN] CorEventAttr
mdToken tkEventType, // [IN] a reference (mdTypeRef or mdTypeRef) to the Event class
mdEvent *pmdEvent) // [OUT] output event token
{
HRESULT hr = S_OK;
LOG((LOGMD, "MD RegMeta::DefineEventHelper(0x%08x, %S, 0x%08x, 0x%08x, 0x%08x)\n",
td, szEvent, dwEventFlags, tkEventType, pmdEvent));
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
hr = _DefineEvent(td, szEvent, dwEventFlags, tkEventType, pmdEvent);
ErrExit:
return hr;
} // RegMeta::DefineEvent
//*******************************************************************************
// helper to add a declarative security blob to a class or method
//
// Implements internal API code:IMetaDataEmitHelper::AddDeclarativeSecurityHelper.
//*******************************************************************************
STDMETHODIMP RegMeta::AddDeclarativeSecurityHelper(
mdToken tk, // [IN] Parent token (typedef/methoddef)
DWORD dwAction, // [IN] Security action (CorDeclSecurity)
void const *pValue, // [IN] Permission set blob
DWORD cbValue, // [IN] Byte count of permission set blob
mdPermission*pmdPermission) // [OUT] Output permission token
{
HRESULT hr = S_OK;
DeclSecurityRec *pDeclSec = NULL;
RID iDeclSec;
short sAction = static_cast<short>(dwAction);
mdPermission tkPerm;
LOG((LOGMD, "MD RegMeta::AddDeclarativeSecurityHelper(0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x)\n",
tk, dwAction, pValue, cbValue, pmdPermission));
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.PreUpdate());
_ASSERTE(TypeFromToken(tk) == mdtTypeDef || TypeFromToken(tk) == mdtMethodDef || TypeFromToken(tk) == mdtAssembly);
// Check for valid Action.
if (sAction == 0 || sAction > dclMaximumValue)
IfFailGo(E_INVALIDARG);
if (CheckDups(MDDupPermission))
{
hr = ImportHelper::FindPermission(&(m_pStgdb->m_MiniMd), tk, sAction, &tkPerm);
if (SUCCEEDED(hr))
{
// Set output parameter.
if (pmdPermission)
*pmdPermission = tkPerm;
if (IsENCOn())
IfFailGo(m_pStgdb->m_MiniMd.GetDeclSecurityRecord(RidFromToken(tkPerm), &pDeclSec));
else
{
hr = META_S_DUPLICATE;
goto ErrExit;
}
}
else if (hr != CLDB_E_RECORD_NOTFOUND)
IfFailGo(hr);
}
// Create a new record.
if (!pDeclSec)
{
IfFailGo(m_pStgdb->m_MiniMd.AddDeclSecurityRecord(&pDeclSec, &iDeclSec));
tkPerm = TokenFromRid(iDeclSec, mdtPermission);
// Set output parameter.
if (pmdPermission)
*pmdPermission = tkPerm;
// Save parent and action information.
IfFailGo(m_pStgdb->m_MiniMd.PutToken(TBL_DeclSecurity, DeclSecurityRec::COL_Parent, pDeclSec, tk));
pDeclSec->SetAction(sAction);
// Turn on the internal security flag on the parent.
if (TypeFromToken(tk) == mdtTypeDef)
IfFailGo(_TurnInternalFlagsOn(tk, tdHasSecurity));
else if (TypeFromToken(tk) == mdtMethodDef)
IfFailGo(_TurnInternalFlagsOn(tk, mdHasSecurity));
IfFailGo(UpdateENCLog(tk));
}
// Write the blob into the record.
IfFailGo(m_pStgdb->m_MiniMd.PutBlob(TBL_DeclSecurity, DeclSecurityRec::COL_PermissionSet,
pDeclSec, pValue, cbValue));
IfFailGo(UpdateENCLog(tkPerm));
ErrExit:
return hr;
} // RegMeta::AddDeclarativeSecurityHelper
//*******************************************************************************
// helper to set type's extends column
//
// Implements internal API code:IMetaDataEmitHelper::SetTypeParent.
//*******************************************************************************
HRESULT RegMeta::SetTypeParent( // Return hresult.
mdTypeDef td, // [IN] Type definition
mdToken tkExtends) // [IN] parent type
{
HRESULT hr;
TypeDefRec *pRec;
LOCKWRITE();
IfFailGo(m_pStgdb->m_MiniMd.GetTypeDefRecord(RidFromToken(td), &pRec));
IfFailGo( m_pStgdb->m_MiniMd.PutToken(TBL_TypeDef, TypeDefRec::COL_Extends, pRec, tkExtends) );
ErrExit:
return hr;
} // RegMeta::SetTypeParent
//*******************************************************************************
// helper to set type's extends column
//
// Implements internal API code:IMetaDataEmitHelper::AddInterfaceImpl.
//*******************************************************************************
HRESULT RegMeta::AddInterfaceImpl( // Return hresult.
mdTypeDef td, // [IN] Type definition
mdToken tkInterface) // [IN] interface type
{
HRESULT hr;
InterfaceImplRec *pRec;
RID ii;
LOCKWRITE();
hr = ImportHelper::FindInterfaceImpl(&(m_pStgdb->m_MiniMd), td, tkInterface, (mdInterfaceImpl *)&ii);
if (hr == S_OK)
goto ErrExit;
IfFailGo(m_pStgdb->m_MiniMd.AddInterfaceImplRecord(&pRec, &ii));
IfFailGo(m_pStgdb->m_MiniMd.PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Class, pRec, td));
IfFailGo(m_pStgdb->m_MiniMd.PutToken( TBL_InterfaceImpl, InterfaceImplRec::COL_Interface, pRec, tkInterface));
ErrExit:
return hr;
} // RegMeta::AddInterfaceImpl
#ifdef FEATURE_METADATA_EMIT_PORTABLE_PDB
//*******************************************************************************
// Helper to determine path separator and number of separated parts.
//
// Implements internal API code:IMDInternalEmit::GetPathSeparator.
//*******************************************************************************
HRESULT
RegMeta::GetPathSeparator(
char *path,
char *separator,
ULONG *partsCount)
{
const char delimiters[] = { '\\', '/', '\0'};
ULONG tokens = 1;
// try first
char delim = delimiters[0];
char* charPtr = strchr(path, delim);
if (charPtr != NULL)
{
// count tokens
while (charPtr != NULL)
{
tokens++;
charPtr = strchr(charPtr + 1, delim);
}
}
else
{
// try second
delim = delimiters[1];
charPtr = strchr(path, delim);
if (charPtr != NULL)
{
// count tokens
while (charPtr != NULL)
{
tokens++;
charPtr = strchr(charPtr + 1, delim);
}
}
else
{
// delimiter not found - set to \0;
delim = delimiters[2];
}
}
*separator = delim;
*partsCount = tokens;
return S_OK;
} // RegMeta::GetPathSeparator
#endif // FEATURE_METADATA_EMIT_PORTABLE_PDB
#endif //FEATURE_METADATA_EMIT && FEATURE_METADATA_INTERNAL_APIS
#ifdef FEATURE_METADATA_INTERNAL_APIS
//*****************************************************************************
// Helper : get metadata information
//
// Implements internal API code:IMetaDataHelper::GetMetadata.
//*****************************************************************************
STDMETHODIMP
RegMeta::GetMetadata(
ULONG ulSelect, // [IN] Selector.
void ** ppData) // [OUT] Put pointer to data here.
{
REGMETA_POSSIBLE_INTERNAL_POINTER_EXPOSED();
switch (ulSelect)
{
case 0:
*ppData = &m_pStgdb->m_MiniMd;
break;
case 1:
*ppData = (void*)g_CodedTokens;
break;
case 2:
*ppData = (void*)g_Tables;
break;
default:
*ppData = 0;
break;
}
return S_OK;
} // RegMeta::GetMetadata
//*******************************************************************************
// helper to change MVID
//
// Implements internal API code:IMDInternalEmit::ChangeMvid.
//*******************************************************************************
HRESULT RegMeta::ChangeMvid( // S_OK or error.
REFGUID newMvid) // GUID to use as the MVID
{
return GetMiniMd()->ChangeMvid(newMvid);
}
//*******************************************************************************
// Helper to change MDUpdateMode value to updateMode.
//
// Implements internal API code:IMDInternalEmit::SetMDUpdateMode.
//*******************************************************************************
HRESULT
RegMeta::SetMDUpdateMode(
ULONG updateMode,
ULONG * pPreviousUpdateMode)
{
HRESULT hr;
OptionValue optionValue;
IfFailGo(m_pStgdb->m_MiniMd.GetOption(&optionValue));
if (pPreviousUpdateMode != NULL)
{
*pPreviousUpdateMode = optionValue.m_UpdateMode;
}
optionValue.m_UpdateMode = updateMode;
IfFailGo(m_pStgdb->m_MiniMd.SetOption(&optionValue));
ErrExit:
return hr;
} // RegMeta::SetMDUpdateMode
#endif //FEATURE_METADATA_INTERNAL_APIS
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/jit/bitsetasuint64.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef bitSetAsUint64_DEFINED
#define bitSetAsUint64_DEFINED 1
#include "bitset.h"
template <typename Env, typename BitSetTraits>
class BitSetOps</*BitSetType*/ UINT64,
/*Brand*/ BSUInt64,
/*Env*/ Env,
/*BitSetTraits*/ BitSetTraits>
{
public:
typedef UINT64 Rep;
private:
static UINT64 Singleton(unsigned bitNum)
{
assert(bitNum < sizeof(UINT64) * BitSetSupport::BitsInByte);
return (UINT64)1 << bitNum;
}
public:
static void Assign(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignNouninit(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignAllowUninitRhs(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignNoCopy(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void ClearD(Env env, UINT64& bs)
{
bs = 0;
}
static UINT64 MakeSingleton(Env env, unsigned bitNum)
{
assert(bitNum < BitSetTraits::GetSize(env));
return Singleton(bitNum);
}
static UINT64 MakeCopy(Env env, UINT64 bs)
{
return bs;
}
static bool IsEmpty(Env env, UINT64 bs)
{
return bs == 0;
}
static unsigned Count(Env env, UINT64 bs)
{
return BitSetSupport::CountBitsInIntegral(bs);
}
static bool IsEmptyUnion(Env env, UINT64 bs1, UINT64 bs2)
{
return (bs1 | bs2) == 0;
}
static void UnionD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 |= bs2;
}
static UINT64 Union(Env env, UINT64& bs1, UINT64 bs2)
{
return bs1 | bs2;
}
static void DiffD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 = bs1 & ~bs2;
}
static UINT64 Diff(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 & ~bs2;
}
static void RemoveElemD(Env env, UINT64& bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
bs1 &= ~Singleton(i);
}
static UINT64 RemoveElem(Env env, UINT64 bs1, unsigned i)
{
return bs1 & ~Singleton(i);
}
static void AddElemD(Env env, UINT64& bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
bs1 |= Singleton(i);
}
static UINT64 AddElem(Env env, UINT64 bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
return bs1 | Singleton(i);
}
static bool IsMember(Env env, const UINT64 bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
return (bs1 & Singleton(i)) != 0;
}
static void IntersectionD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 &= bs2;
}
static UINT64 Intersection(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 & bs2;
}
static bool IsEmptyIntersection(Env env, UINT64 bs1, UINT64 bs2)
{
return (bs1 & bs2) == 0;
}
static void LivenessD(Env env, UINT64& in, const UINT64 def, const UINT64 use, const UINT64 out)
{
in = use | (out & ~def);
}
static bool IsSubset(Env env, UINT64 bs1, UINT64 bs2)
{
return ((bs1 & bs2) == bs1);
}
static bool Equal(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 == bs2;
}
static UINT64 MakeEmpty(Env env)
{
return 0;
}
static UINT64 MakeFull(Env env)
{
unsigned sz = BitSetTraits::GetSize(env);
if (sz == sizeof(UINT64) * 8)
{
return UINT64(-1);
}
else
{
return (UINT64(1) << sz) - 1;
}
}
#ifdef DEBUG
static const char* ToString(Env env, UINT64 bs)
{
const int CharsForUINT64 = sizeof(UINT64) * 2;
char* res = nullptr;
const int AllocSize = CharsForUINT64 + 4;
res = (char*)BitSetTraits::DebugAlloc(env, AllocSize);
UINT64 bits = bs;
unsigned remaining = AllocSize;
char* ptr = res;
for (unsigned bytesDone = 0; bytesDone < sizeof(UINT64); bytesDone += sizeof(unsigned))
{
unsigned bits0 = (unsigned)bits;
sprintf_s(ptr, remaining, "%08X", bits0);
ptr += 8;
remaining -= 8;
bytesDone += 4;
assert(sizeof(unsigned) == 4);
// Doing this twice by 16, rather than once by 32, avoids warnings when size_t == unsigned.
bits = bits >> 16;
bits = bits >> 16;
}
return res;
}
#endif
static UINT64 UninitVal()
{
return 0;
}
static bool MayBeUninit(UINT64 bs)
{
return bs == UninitVal();
}
class Iter
{
UINT64 m_bits;
// The number of bits that have already been iterated over (set or clear).
unsigned m_bitNum;
public:
Iter(Env env, const UINT64& bits) : m_bits(bits), m_bitNum(0)
{
}
bool NextElem(unsigned* pElem)
{
// TODO-Throughtput: use BitScanForward64() intrinsic (see short/long implementation).
if (m_bits)
{
unsigned bitNum = m_bitNum;
while ((m_bits & 0x1) == 0)
{
bitNum++;
m_bits >>= 1;
}
*pElem = bitNum;
m_bitNum = bitNum + 1;
m_bits >>= 1;
return true;
}
else
{
return false;
}
}
};
typedef const UINT64 ValArgType;
typedef UINT64 RetValType;
};
#endif // bitSetAsUint64_DEFINED
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef bitSetAsUint64_DEFINED
#define bitSetAsUint64_DEFINED 1
#include "bitset.h"
template <typename Env, typename BitSetTraits>
class BitSetOps</*BitSetType*/ UINT64,
/*Brand*/ BSUInt64,
/*Env*/ Env,
/*BitSetTraits*/ BitSetTraits>
{
public:
typedef UINT64 Rep;
private:
static UINT64 Singleton(unsigned bitNum)
{
assert(bitNum < sizeof(UINT64) * BitSetSupport::BitsInByte);
return (UINT64)1 << bitNum;
}
public:
static void Assign(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignNouninit(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignAllowUninitRhs(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void AssignNoCopy(Env env, UINT64& lhs, UINT64 rhs)
{
lhs = rhs;
}
static void ClearD(Env env, UINT64& bs)
{
bs = 0;
}
static UINT64 MakeSingleton(Env env, unsigned bitNum)
{
assert(bitNum < BitSetTraits::GetSize(env));
return Singleton(bitNum);
}
static UINT64 MakeCopy(Env env, UINT64 bs)
{
return bs;
}
static bool IsEmpty(Env env, UINT64 bs)
{
return bs == 0;
}
static unsigned Count(Env env, UINT64 bs)
{
return BitSetSupport::CountBitsInIntegral(bs);
}
static bool IsEmptyUnion(Env env, UINT64 bs1, UINT64 bs2)
{
return (bs1 | bs2) == 0;
}
static void UnionD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 |= bs2;
}
static UINT64 Union(Env env, UINT64& bs1, UINT64 bs2)
{
return bs1 | bs2;
}
static void DiffD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 = bs1 & ~bs2;
}
static UINT64 Diff(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 & ~bs2;
}
static void RemoveElemD(Env env, UINT64& bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
bs1 &= ~Singleton(i);
}
static UINT64 RemoveElem(Env env, UINT64 bs1, unsigned i)
{
return bs1 & ~Singleton(i);
}
static void AddElemD(Env env, UINT64& bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
bs1 |= Singleton(i);
}
static UINT64 AddElem(Env env, UINT64 bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
return bs1 | Singleton(i);
}
static bool IsMember(Env env, const UINT64 bs1, unsigned i)
{
assert(i < BitSetTraits::GetSize(env));
return (bs1 & Singleton(i)) != 0;
}
static void IntersectionD(Env env, UINT64& bs1, UINT64 bs2)
{
bs1 &= bs2;
}
static UINT64 Intersection(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 & bs2;
}
static bool IsEmptyIntersection(Env env, UINT64 bs1, UINT64 bs2)
{
return (bs1 & bs2) == 0;
}
static void LivenessD(Env env, UINT64& in, const UINT64 def, const UINT64 use, const UINT64 out)
{
in = use | (out & ~def);
}
static bool IsSubset(Env env, UINT64 bs1, UINT64 bs2)
{
return ((bs1 & bs2) == bs1);
}
static bool Equal(Env env, UINT64 bs1, UINT64 bs2)
{
return bs1 == bs2;
}
static UINT64 MakeEmpty(Env env)
{
return 0;
}
static UINT64 MakeFull(Env env)
{
unsigned sz = BitSetTraits::GetSize(env);
if (sz == sizeof(UINT64) * 8)
{
return UINT64(-1);
}
else
{
return (UINT64(1) << sz) - 1;
}
}
#ifdef DEBUG
static const char* ToString(Env env, UINT64 bs)
{
const int CharsForUINT64 = sizeof(UINT64) * 2;
char* res = nullptr;
const int AllocSize = CharsForUINT64 + 4;
res = (char*)BitSetTraits::DebugAlloc(env, AllocSize);
UINT64 bits = bs;
unsigned remaining = AllocSize;
char* ptr = res;
for (unsigned bytesDone = 0; bytesDone < sizeof(UINT64); bytesDone += sizeof(unsigned))
{
unsigned bits0 = (unsigned)bits;
sprintf_s(ptr, remaining, "%08X", bits0);
ptr += 8;
remaining -= 8;
bytesDone += 4;
assert(sizeof(unsigned) == 4);
// Doing this twice by 16, rather than once by 32, avoids warnings when size_t == unsigned.
bits = bits >> 16;
bits = bits >> 16;
}
return res;
}
#endif
static UINT64 UninitVal()
{
return 0;
}
static bool MayBeUninit(UINT64 bs)
{
return bs == UninitVal();
}
class Iter
{
UINT64 m_bits;
// The number of bits that have already been iterated over (set or clear).
unsigned m_bitNum;
public:
Iter(Env env, const UINT64& bits) : m_bits(bits), m_bitNum(0)
{
}
bool NextElem(unsigned* pElem)
{
// TODO-Throughtput: use BitScanForward64() intrinsic (see short/long implementation).
if (m_bits)
{
unsigned bitNum = m_bitNum;
while ((m_bits & 0x1) == 0)
{
bitNum++;
m_bits >>= 1;
}
*pElem = bitNum;
m_bitNum = bitNum + 1;
m_bits >>= 1;
return true;
}
else
{
return false;
}
}
};
typedef const UINT64 ValArgType;
typedef UINT64 RetValType;
};
#endif // bitSetAsUint64_DEFINED
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/installer/tests/scripts/linux-test/RuntimeInstallation.sh
|
#!/usr/bin/env bash
current_user=$(whoami)
if [[ "$current_user" != "root" ]]; then
echo "script requires superuser privileges to run"
exit 1
fi
source /etc/os-release
distro="$ID"
version="$VERSION_ID"
arch="x64"
result_file="/docker/result.txt"
log_file="/docker/logfile.txt"
exec &>> $log_file
if [[ "$ID" == "ol" ]]; then
distro="oraclelinux"
fi
if [[ "$distro" == "oraclelinux" || "$distro" == "rhel" || "$distro" == "opensuse" ]]; then
version=$(echo $version | cut -d . -f 1)
fi
echo $distro:$version
runtime_version=$1
if [[ "$runtime_version" == "latest" ]]; then
BLOB_RUNTIME_DIR="https://dotnetcli.blob.core.windows.net/dotnet/Runtime/master"
else
BLOB_RUNTIME_DIR="https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$runtime_version"
fi
install_curl(){
apt-get -y install curl
if [ $? -ne 0 ]; then
apt-get update
apt-get -y install curl
fi
}
download_from_blob_deb(){
BLOB_PATH=$1
if curl --output /dev/null --head --fail $BLOB_PATH; then
curl -O -s $BLOB_PATH
else
echo "Could not extract file from blob"
exit 1
fi
}
download_runtime_packages_deb(){
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-host-$runtime_version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-hostfxr-$runtime_version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-runtime-$runtime_version-$arch.deb"
}
install_runtime_packages_deb(){
dpkg -i dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.deb
apt-get install -f -y
dpkg -i *.deb
}
determine_runtime_version_deb(){
if [[ "$runtime_version" == "latest" ]]; then
runtime_version=$(dpkg-deb -f dotnet-runtime-latest-$arch.deb Package)
runtime_version=${runtime_version#dotnet-runtime-}
fi
}
check_if_runtime_is_installed_deb(){
find_runtime=$(apt list --installed | grep dotnet-runtime-$runtime_version)
if [[ -z "$find_runtime" ]]; then
echo "Not able to remove runtime $runtime_version because it is not installed"
exit 1
fi
}
uninstall_runtime_deb(){
apt-get remove -y $(apt list --installed | grep -e dotnet | cut -d "/" -f 1)
runtime_installed_packages=$(apt list --installed | grep -e dotnet)
}
install_wget_yum(){
yum install -y wget
}
install_wget_zypper(){
zypper --non-interactive install wget
}
download_from_blob_rpm(){
BLOB_PATH=$1
if wget --spider $BLOB_PATH; then
wget -nv $BLOB_PATH
else
echo "Could not extract file from blob"
exit 1
fi
}
download_runtime_packages_rpm(){
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-host-$runtime_version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-hostfxr-$runtime_version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-runtime-$runtime_version-$arch.rpm"
}
install_runtime_packages_yum(){
yum localinstall -y dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rm dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rpm -Uvh *.rpm
}
install_runtime_packages_zypper(){
zypper --no-gpg-checks --non-interactive in ./dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rm dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rpm -Uvh *.rpm
}
determine_runtime_version_rpm(){
if [[ "$runtime_version" == "latest" ]]; then
runtime_version=$(rpm -qip dotnet-runtime-latest-$arch.rpm | grep Version)
runtime_version=$(echo $runtime_version | cut -d ":" -f 2)
runtime_version=$(echo $runtime_version | tr _ -)
fi
}
check_if_runtime_is_installed_rpm(){
find_runtime=$(rpm -qa | grep dotnet-runtime-$runtime_version)
if [[ -z "$find_runtime" ]]; then
echo "Not able to remove runtime $runtime_version because it is not installed"
exit 1
fi
}
uninstall_runtime_yum(){
yum remove -y $(rpm -qa | grep -e dotnet)
runtime_installed_packages=$(rpm -qa | grep -e dotnet)
}
uninstall_runtime_zypper(){
zypper -n rm $(rpm -qa | grep -e dotnet)
runtime_installed_packages=$(rpm -qa | grep -e dotnet)
}
determine_success_install(){
if [ -e $result_file ]; then
installed_runtime=$(dotnet --list-runtimes | grep $runtime_version)
if [[ -n "$installed_runtime" ]]; then
success_install=1
else
success_install=0
fi
fi
}
test_result_install(){
if [ -e $result_file ]; then
if [ $success_install -eq 1 ]; then
echo "$distro:$version install -> passed" >> $result_file
else
echo "$distro:$version install -> failed" >> $result_file
fi
fi
}
uninstall_latest_runtime_warning(){
if [[ "$runtime_version" == "latest" ]]; then
echo "Specify runtime version to unistall. Type dotnet --list-runtimes to see runtimes versions installed"
exit 1
fi
}
test_result_uninstall(){
if [[ -z "$runtime_installed_packages" ]]; then
success_uninstall=1
else
success_uninstall=0
fi
if [ -e $result_file ]; then
if [ $success_uninstall -eq 1 ]; then
echo "$distro:$version uninstall -> passed" >> $result_file
else
echo "$distro:$version uninstall -> failed" >> $result_file
fi
fi
}
if [[ "$distro" == "ubuntu" || "$distro" == "debian" ]]; then
if [[ "$2" == "install" ]]; then
install_curl
download_runtime_packages_deb
install_runtime_packages_deb
dotnet --list-runtimes
determine_runtime_version_deb
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_deb
uninstall_runtime_deb
test_result_uninstall
fi
elif [[ "$distro" == "fedora" || "$distro" == "centos" || "$distro" == "oraclelinux" || "$distro" == "rhel" ]]; then
if [[ "$2" == "install" ]]; then
install_wget_yum
download_runtime_packages_rpm
install_runtime_packages_yum
dotnet --list-runtimes
determine_runtime_version_rpm
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_rpm
uninstall_runtime_yum
test_result_uninstall
fi
elif [[ "$distro" == "opensuse" || "$distro" == "sles" ]]; then
if [[ "$2" == "install" ]]; then
install_wget_zypper
download_runtime_packages_rpm
install_runtime_packages_zypper
dotnet --list-runtimes
determine_runtime_version_rpm
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_rpm
uninstall_runtime_zypper
test_result_uninstall
fi
fi
if [ -e $log_file ]; then
ch=$(printf "%-160s" "-")
echo "${ch// /-} "
fi
|
#!/usr/bin/env bash
current_user=$(whoami)
if [[ "$current_user" != "root" ]]; then
echo "script requires superuser privileges to run"
exit 1
fi
source /etc/os-release
distro="$ID"
version="$VERSION_ID"
arch="x64"
result_file="/docker/result.txt"
log_file="/docker/logfile.txt"
exec &>> $log_file
if [[ "$ID" == "ol" ]]; then
distro="oraclelinux"
fi
if [[ "$distro" == "oraclelinux" || "$distro" == "rhel" || "$distro" == "opensuse" ]]; then
version=$(echo $version | cut -d . -f 1)
fi
echo $distro:$version
runtime_version=$1
if [[ "$runtime_version" == "latest" ]]; then
BLOB_RUNTIME_DIR="https://dotnetcli.blob.core.windows.net/dotnet/Runtime/master"
else
BLOB_RUNTIME_DIR="https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$runtime_version"
fi
install_curl(){
apt-get -y install curl
if [ $? -ne 0 ]; then
apt-get update
apt-get -y install curl
fi
}
download_from_blob_deb(){
BLOB_PATH=$1
if curl --output /dev/null --head --fail $BLOB_PATH; then
curl -O -s $BLOB_PATH
else
echo "Could not extract file from blob"
exit 1
fi
}
download_runtime_packages_deb(){
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-host-$runtime_version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-hostfxr-$runtime_version-$arch.deb"
download_from_blob_deb "$BLOB_RUNTIME_DIR/dotnet-runtime-$runtime_version-$arch.deb"
}
install_runtime_packages_deb(){
dpkg -i dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.deb
apt-get install -f -y
dpkg -i *.deb
}
determine_runtime_version_deb(){
if [[ "$runtime_version" == "latest" ]]; then
runtime_version=$(dpkg-deb -f dotnet-runtime-latest-$arch.deb Package)
runtime_version=${runtime_version#dotnet-runtime-}
fi
}
check_if_runtime_is_installed_deb(){
find_runtime=$(apt list --installed | grep dotnet-runtime-$runtime_version)
if [[ -z "$find_runtime" ]]; then
echo "Not able to remove runtime $runtime_version because it is not installed"
exit 1
fi
}
uninstall_runtime_deb(){
apt-get remove -y $(apt list --installed | grep -e dotnet | cut -d "/" -f 1)
runtime_installed_packages=$(apt list --installed | grep -e dotnet)
}
install_wget_yum(){
yum install -y wget
}
install_wget_zypper(){
zypper --non-interactive install wget
}
download_from_blob_rpm(){
BLOB_PATH=$1
if wget --spider $BLOB_PATH; then
wget -nv $BLOB_PATH
else
echo "Could not extract file from blob"
exit 1
fi
}
download_runtime_packages_rpm(){
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-host-$runtime_version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-hostfxr-$runtime_version-$arch.rpm"
download_from_blob_rpm "$BLOB_RUNTIME_DIR/dotnet-runtime-$runtime_version-$arch.rpm"
}
install_runtime_packages_yum(){
yum localinstall -y dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rm dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rpm -Uvh *.rpm
}
install_runtime_packages_zypper(){
zypper --no-gpg-checks --non-interactive in ./dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rm dotnet-runtime-deps-$runtime_version-$distro.$version-$arch.rpm
rpm -Uvh *.rpm
}
determine_runtime_version_rpm(){
if [[ "$runtime_version" == "latest" ]]; then
runtime_version=$(rpm -qip dotnet-runtime-latest-$arch.rpm | grep Version)
runtime_version=$(echo $runtime_version | cut -d ":" -f 2)
runtime_version=$(echo $runtime_version | tr _ -)
fi
}
check_if_runtime_is_installed_rpm(){
find_runtime=$(rpm -qa | grep dotnet-runtime-$runtime_version)
if [[ -z "$find_runtime" ]]; then
echo "Not able to remove runtime $runtime_version because it is not installed"
exit 1
fi
}
uninstall_runtime_yum(){
yum remove -y $(rpm -qa | grep -e dotnet)
runtime_installed_packages=$(rpm -qa | grep -e dotnet)
}
uninstall_runtime_zypper(){
zypper -n rm $(rpm -qa | grep -e dotnet)
runtime_installed_packages=$(rpm -qa | grep -e dotnet)
}
determine_success_install(){
if [ -e $result_file ]; then
installed_runtime=$(dotnet --list-runtimes | grep $runtime_version)
if [[ -n "$installed_runtime" ]]; then
success_install=1
else
success_install=0
fi
fi
}
test_result_install(){
if [ -e $result_file ]; then
if [ $success_install -eq 1 ]; then
echo "$distro:$version install -> passed" >> $result_file
else
echo "$distro:$version install -> failed" >> $result_file
fi
fi
}
uninstall_latest_runtime_warning(){
if [[ "$runtime_version" == "latest" ]]; then
echo "Specify runtime version to unistall. Type dotnet --list-runtimes to see runtimes versions installed"
exit 1
fi
}
test_result_uninstall(){
if [[ -z "$runtime_installed_packages" ]]; then
success_uninstall=1
else
success_uninstall=0
fi
if [ -e $result_file ]; then
if [ $success_uninstall -eq 1 ]; then
echo "$distro:$version uninstall -> passed" >> $result_file
else
echo "$distro:$version uninstall -> failed" >> $result_file
fi
fi
}
if [[ "$distro" == "ubuntu" || "$distro" == "debian" ]]; then
if [[ "$2" == "install" ]]; then
install_curl
download_runtime_packages_deb
install_runtime_packages_deb
dotnet --list-runtimes
determine_runtime_version_deb
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_deb
uninstall_runtime_deb
test_result_uninstall
fi
elif [[ "$distro" == "fedora" || "$distro" == "centos" || "$distro" == "oraclelinux" || "$distro" == "rhel" ]]; then
if [[ "$2" == "install" ]]; then
install_wget_yum
download_runtime_packages_rpm
install_runtime_packages_yum
dotnet --list-runtimes
determine_runtime_version_rpm
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_rpm
uninstall_runtime_yum
test_result_uninstall
fi
elif [[ "$distro" == "opensuse" || "$distro" == "sles" ]]; then
if [[ "$2" == "install" ]]; then
install_wget_zypper
download_runtime_packages_rpm
install_runtime_packages_zypper
dotnet --list-runtimes
determine_runtime_version_rpm
determine_success_install
test_result_install
elif [[ "$2" == "uninstall" ]]; then
uninstall_latest_runtime_warning
fi
if [[ "$3" == "uninstall" || "$2" == "uninstall" ]]; then
check_if_runtime_is_installed_rpm
uninstall_runtime_zypper
test_result_uninstall
fi
fi
if [ -e $log_file ]; then
ch=$(printf "%-160s" "-")
echo "${ch// /-} "
fi
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./global.json
|
{
"sdk": {
"version": "6.0.100",
"allowPrerelease": true,
"rollForward": "major"
},
"tools": {
"dotnet": "6.0.100"
},
"msbuild-sdks": {
"Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22157.6",
"Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.22157.6",
"Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22157.6",
"Microsoft.Build.NoTargets": "3.3.0",
"Microsoft.Build.Traversal": "3.1.6",
"Microsoft.NET.Sdk.IL": "7.0.0-preview.3.22157.1"
}
}
|
{
"sdk": {
"version": "6.0.100",
"allowPrerelease": true,
"rollForward": "major"
},
"tools": {
"dotnet": "6.0.100"
},
"msbuild-sdks": {
"Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22157.6",
"Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.22157.6",
"Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22157.6",
"Microsoft.Build.NoTargets": "3.3.0",
"Microsoft.Build.Traversal": "3.1.6",
"Microsoft.NET.Sdk.IL": "7.0.0-preview.3.22157.1"
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Net.Http/tests/FunctionalTests/SocketsHttpHandlerTest.Http2KeepAlivePing.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
[Collection(nameof(DisableParallelization))]
[ConditionalClass(typeof(SocketsHttpHandler_Http2KeepAlivePing_Test), nameof(IsSupported))]
public sealed class SocketsHttpHandler_Http2KeepAlivePing_Test : HttpClientHandlerTestBase
{
public static readonly bool IsSupported = PlatformDetection.SupportsAlpn && PlatformDetection.IsNotBrowser;
protected override Version UseVersion => HttpVersion20.Value;
private int _pingCounter;
private Http2LoopbackConnection _connection;
private SemaphoreSlim _writeSemaphore = new SemaphoreSlim(1);
private Channel<Frame> _framesChannel = Channel.CreateUnbounded<Frame>();
private CancellationTokenSource _incomingFramesCts = new CancellationTokenSource();
private Task _incomingFramesTask;
private TaskCompletionSource _serverFinished = new TaskCompletionSource();
private int _sendPingResponse = 1;
private static Http2Options NoAutoPingResponseHttp2Options => new Http2Options() { EnableTransparentPingResponse = false };
private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(60);
public SocketsHttpHandler_Http2KeepAlivePing_Test(ITestOutputHelper output) : base(output)
{
}
[OuterLoop("Runs long")]
[Fact]
public async Task KeepAlivePingDelay_Infinite_NoKeepAlivePingIsSent()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
KeepAlivePingDelay = Timeout.InfiniteTimeSpan
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
await client.GetStringAsync(uri);
// Actual request:
await client.GetStringAsync(uri);
// Let connection live until server finishes:
await _serverFinished.Task.WaitAsync(TestTimeout);
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
// Simulate inactive period:
await Task.Delay(5_000);
// We may have received one RTT PING in response to HEADERS, but should receive no KeepAlive PING
Assert.True(_pingCounter <= 1);
Interlocked.Exchange(ref _pingCounter, 0); // reset the counter
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
// Simulate inactive period:
await Task.Delay(5_000);
// We may have received one RTT PING in response to HEADERS, but should receive no KeepAlive PING
Assert.True(_pingCounter <= 1);
await TerminateLoopbackConnectionAsync();
}).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Theory]
[InlineData(HttpKeepAlivePingPolicy.Always)]
[InlineData(HttpKeepAlivePingPolicy.WithActiveRequests)]
public async Task KeepAliveConfigured_KeepAlivePingsAreSentAccordingToPolicy(HttpKeepAlivePingPolicy policy)
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(10),
KeepAlivePingPolicy = policy,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Actual request:
HttpResponseMessage response1 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
// Let connection live until server finishes:
await _serverFinished.Task.WaitAsync(TestTimeout);
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
// Simulate inactive period:
await Task.Delay(5_000);
// We may receive one RTT PING in response to HEADERS.
// Upon that, we expect to receive at least 1 keep alive PING:
Assert.True(_pingCounter > 1);
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
if (policy == HttpKeepAlivePingPolicy.Always)
{
// Simulate inactive period:
await Task.Delay(5_000);
// We may receive one RTT PING in response to HEADERS.
// Upon that, we expect to receive at least 1 keep alive PING:
Assert.True(_pingCounter > 1);
}
else
{
// We should receive no more KeepAlive PINGs
Assert.True(_pingCounter <= 1);
}
await TerminateLoopbackConnectionAsync();
List<Frame> unexpectedFrames = new List<Frame>();
while (_framesChannel.Reader.Count > 0)
{
Frame unexpectedFrame = await _framesChannel.Reader.ReadAsync();
unexpectedFrames.Add(unexpectedFrame);
}
Assert.False(unexpectedFrames.Any(), "Received unexpected frames: \n" + string.Join('\n', unexpectedFrames.Select(f => f.ToString()).ToArray()));
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Fact]
public async Task KeepAliveConfigured_NoPingResponseDuringActiveStream_RequestShouldFail()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1.5),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Actual request:
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
// Let connection live until server finishes:
await _serverFinished.Task;
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
DisablePingResponse();
// Simulate inactive period:
await Task.Delay(6_000);
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
await TerminateLoopbackConnectionAsync();
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Fact]
public async Task HttpKeepAlivePingPolicy_Always_NoPingResponseBetweenStreams_SecondRequestShouldFail()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1.5),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Second request should fail:
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
// Let connection live until server finishes:
await _serverFinished.Task;
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
DisablePingResponse();
// Simulate inactive period:
await Task.Delay(6_000);
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
await TerminateLoopbackConnectionAsync();
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
private async Task ProcessIncomingFramesAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
Frame frame = await _connection.ReadFrameAsync(cancellationToken);
if (frame is PingFrame pingFrame)
{
if (pingFrame.AckFlag)
{
_output?.WriteLine($"Received unexpected PING ACK ({pingFrame.Data})");
await _framesChannel.Writer.WriteAsync(frame, cancellationToken);
}
else
{
_output?.WriteLine($"Received PING ({pingFrame.Data})");
Interlocked.Increment(ref _pingCounter);
if (_sendPingResponse > 0)
{
await GuardConnetionWriteAsync(() => _connection.SendPingAckAsync(pingFrame.Data, cancellationToken), cancellationToken);
}
}
}
else if (frame is WindowUpdateFrame windowUpdateFrame)
{
_output?.WriteLine($"Received WINDOW_UPDATE");
}
else if (frame is not null)
{
//_output?.WriteLine($"Received {frame}");
await _framesChannel.Writer.WriteAsync(frame, cancellationToken);
}
}
}
catch (OperationCanceledException)
{
}
_output?.WriteLine("ProcessIncomingFramesAsync finished");
_connection.Dispose();
}
private void DisablePingResponse() => Interlocked.Exchange(ref _sendPingResponse, 0);
private async Task EstablishConnectionAsync(Http2LoopbackServer server)
{
_connection = await server.EstablishConnectionAsync();
_incomingFramesTask = ProcessIncomingFramesAsync(_incomingFramesCts.Token);
}
private async Task TerminateLoopbackConnectionAsync()
{
_serverFinished.SetResult();
_incomingFramesCts.Cancel();
await _incomingFramesTask;
}
private async Task GuardConnetionWriteAsync(Func<Task> action, CancellationToken cancellationToken = default)
{
await _writeSemaphore.WaitAsync(cancellationToken);
await action();
_writeSemaphore.Release();
}
private async Task<HeadersFrame> ReadRequestHeaderFrameAsync(bool expectEndOfStream = true, CancellationToken cancellationToken = default)
{
// Receive HEADERS frame for request.
Frame frame = await _framesChannel.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (frame == null)
{
throw new IOException("Failed to read Headers frame.");
}
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags & FrameFlags.EndHeaders);
if (expectEndOfStream)
{
Assert.Equal(FrameFlags.EndStream, frame.Flags & FrameFlags.EndStream);
}
return (HeadersFrame)frame;
}
private async Task<int> ReadRequestHeaderAsync(bool expectEndOfStream = true, CancellationToken cancellationToken = default)
{
HeadersFrame frame = await ReadRequestHeaderFrameAsync(expectEndOfStream, cancellationToken);
return frame.StreamId;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
[Collection(nameof(DisableParallelization))]
[ConditionalClass(typeof(SocketsHttpHandler_Http2KeepAlivePing_Test), nameof(IsSupported))]
public sealed class SocketsHttpHandler_Http2KeepAlivePing_Test : HttpClientHandlerTestBase
{
public static readonly bool IsSupported = PlatformDetection.SupportsAlpn && PlatformDetection.IsNotBrowser;
protected override Version UseVersion => HttpVersion20.Value;
private int _pingCounter;
private Http2LoopbackConnection _connection;
private SemaphoreSlim _writeSemaphore = new SemaphoreSlim(1);
private Channel<Frame> _framesChannel = Channel.CreateUnbounded<Frame>();
private CancellationTokenSource _incomingFramesCts = new CancellationTokenSource();
private Task _incomingFramesTask;
private TaskCompletionSource _serverFinished = new TaskCompletionSource();
private int _sendPingResponse = 1;
private static Http2Options NoAutoPingResponseHttp2Options => new Http2Options() { EnableTransparentPingResponse = false };
private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(60);
public SocketsHttpHandler_Http2KeepAlivePing_Test(ITestOutputHelper output) : base(output)
{
}
[OuterLoop("Runs long")]
[Fact]
public async Task KeepAlivePingDelay_Infinite_NoKeepAlivePingIsSent()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
KeepAlivePingDelay = Timeout.InfiniteTimeSpan
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
await client.GetStringAsync(uri);
// Actual request:
await client.GetStringAsync(uri);
// Let connection live until server finishes:
await _serverFinished.Task.WaitAsync(TestTimeout);
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
// Simulate inactive period:
await Task.Delay(5_000);
// We may have received one RTT PING in response to HEADERS, but should receive no KeepAlive PING
Assert.True(_pingCounter <= 1);
Interlocked.Exchange(ref _pingCounter, 0); // reset the counter
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
// Simulate inactive period:
await Task.Delay(5_000);
// We may have received one RTT PING in response to HEADERS, but should receive no KeepAlive PING
Assert.True(_pingCounter <= 1);
await TerminateLoopbackConnectionAsync();
}).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Theory]
[InlineData(HttpKeepAlivePingPolicy.Always)]
[InlineData(HttpKeepAlivePingPolicy.WithActiveRequests)]
public async Task KeepAliveConfigured_KeepAlivePingsAreSentAccordingToPolicy(HttpKeepAlivePingPolicy policy)
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(10),
KeepAlivePingPolicy = policy,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Actual request:
HttpResponseMessage response1 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response1.StatusCode);
// Let connection live until server finishes:
await _serverFinished.Task.WaitAsync(TestTimeout);
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
// Simulate inactive period:
await Task.Delay(5_000);
// We may receive one RTT PING in response to HEADERS.
// Upon that, we expect to receive at least 1 keep alive PING:
Assert.True(_pingCounter > 1);
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
Interlocked.Exchange(ref _pingCounter, 0); // reset the PING counter
if (policy == HttpKeepAlivePingPolicy.Always)
{
// Simulate inactive period:
await Task.Delay(5_000);
// We may receive one RTT PING in response to HEADERS.
// Upon that, we expect to receive at least 1 keep alive PING:
Assert.True(_pingCounter > 1);
}
else
{
// We should receive no more KeepAlive PINGs
Assert.True(_pingCounter <= 1);
}
await TerminateLoopbackConnectionAsync();
List<Frame> unexpectedFrames = new List<Frame>();
while (_framesChannel.Reader.Count > 0)
{
Frame unexpectedFrame = await _framesChannel.Reader.ReadAsync();
unexpectedFrames.Add(unexpectedFrame);
}
Assert.False(unexpectedFrames.Any(), "Received unexpected frames: \n" + string.Join('\n', unexpectedFrames.Select(f => f.ToString()).ToArray()));
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Fact]
public async Task KeepAliveConfigured_NoPingResponseDuringActiveStream_RequestShouldFail()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1.5),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Actual request:
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
// Let connection live until server finishes:
await _serverFinished.Task;
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
DisablePingResponse();
// Simulate inactive period:
await Task.Delay(6_000);
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
await TerminateLoopbackConnectionAsync();
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
[OuterLoop("Runs long")]
[Fact]
public async Task HttpKeepAlivePingPolicy_Always_NoPingResponseBetweenStreams_SecondRequestShouldFail()
{
await Http2LoopbackServer.CreateClientAndServerAsync(async uri =>
{
SocketsHttpHandler handler = new SocketsHttpHandler()
{
KeepAlivePingTimeout = TimeSpan.FromSeconds(1.5),
KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
KeepAlivePingDelay = TimeSpan.FromSeconds(1)
};
handler.SslOptions.RemoteCertificateValidationCallback = delegate { return true; };
using HttpClient client = new HttpClient(handler);
client.DefaultRequestVersion = HttpVersion.Version20;
// Warmup request to create connection:
HttpResponseMessage response0 = await client.GetAsync(uri);
Assert.Equal(HttpStatusCode.OK, response0.StatusCode);
// Second request should fail:
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
// Let connection live until server finishes:
await _serverFinished.Task;
},
async server =>
{
await EstablishConnectionAsync(server);
// Warmup the connection.
int streamId1 = await ReadRequestHeaderAsync();
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId1));
DisablePingResponse();
// Simulate inactive period:
await Task.Delay(6_000);
// Request under the test scope.
int streamId2 = await ReadRequestHeaderAsync();
// Finish the response:
await GuardConnetionWriteAsync(() => _connection.SendDefaultResponseAsync(streamId2));
await TerminateLoopbackConnectionAsync();
}, NoAutoPingResponseHttp2Options).WaitAsync(TestTimeout);
}
private async Task ProcessIncomingFramesAsync(CancellationToken cancellationToken)
{
try
{
while (!cancellationToken.IsCancellationRequested)
{
Frame frame = await _connection.ReadFrameAsync(cancellationToken);
if (frame is PingFrame pingFrame)
{
if (pingFrame.AckFlag)
{
_output?.WriteLine($"Received unexpected PING ACK ({pingFrame.Data})");
await _framesChannel.Writer.WriteAsync(frame, cancellationToken);
}
else
{
_output?.WriteLine($"Received PING ({pingFrame.Data})");
Interlocked.Increment(ref _pingCounter);
if (_sendPingResponse > 0)
{
await GuardConnetionWriteAsync(() => _connection.SendPingAckAsync(pingFrame.Data, cancellationToken), cancellationToken);
}
}
}
else if (frame is WindowUpdateFrame windowUpdateFrame)
{
_output?.WriteLine($"Received WINDOW_UPDATE");
}
else if (frame is not null)
{
//_output?.WriteLine($"Received {frame}");
await _framesChannel.Writer.WriteAsync(frame, cancellationToken);
}
}
}
catch (OperationCanceledException)
{
}
_output?.WriteLine("ProcessIncomingFramesAsync finished");
_connection.Dispose();
}
private void DisablePingResponse() => Interlocked.Exchange(ref _sendPingResponse, 0);
private async Task EstablishConnectionAsync(Http2LoopbackServer server)
{
_connection = await server.EstablishConnectionAsync();
_incomingFramesTask = ProcessIncomingFramesAsync(_incomingFramesCts.Token);
}
private async Task TerminateLoopbackConnectionAsync()
{
_serverFinished.SetResult();
_incomingFramesCts.Cancel();
await _incomingFramesTask;
}
private async Task GuardConnetionWriteAsync(Func<Task> action, CancellationToken cancellationToken = default)
{
await _writeSemaphore.WaitAsync(cancellationToken);
await action();
_writeSemaphore.Release();
}
private async Task<HeadersFrame> ReadRequestHeaderFrameAsync(bool expectEndOfStream = true, CancellationToken cancellationToken = default)
{
// Receive HEADERS frame for request.
Frame frame = await _framesChannel.Reader.ReadAsync(cancellationToken).ConfigureAwait(false);
if (frame == null)
{
throw new IOException("Failed to read Headers frame.");
}
Assert.Equal(FrameType.Headers, frame.Type);
Assert.Equal(FrameFlags.EndHeaders, frame.Flags & FrameFlags.EndHeaders);
if (expectEndOfStream)
{
Assert.Equal(FrameFlags.EndStream, frame.Flags & FrameFlags.EndStream);
}
return (HeadersFrame)frame;
}
private async Task<int> ReadRequestHeaderAsync(bool expectEndOfStream = true, CancellationToken cancellationToken = default)
{
HeadersFrame frame = await ReadRequestHeaderFrameAsync(expectEndOfStream, cancellationToken);
return frame.StreamId;
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/HardwareIntrinsics/General/Vector64/CreateScalar.Int32.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateScalarInt32()
{
var test = new VectorCreate__CreateScalarInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarInt32
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32 value = TestLibrary.Generator.GetInt32();
Vector64<Int32> result = Vector64.CreateScalar(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32 value = TestLibrary.Generator.GetInt32();
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.CreateScalar), new Type[] { typeof(Int32) })
.Invoke(null, new object[] { value });
ValidateResult((Vector64<Int32>)(result), value);
}
private void ValidateResult(Vector64<Int32> result, Int32 expectedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Int32[] resultElements, Int32 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (resultElements[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64.CreateScalar(Int32): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateScalarInt32()
{
var test = new VectorCreate__CreateScalarInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateScalarInt32
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int32 value = TestLibrary.Generator.GetInt32();
Vector64<Int32> result = Vector64.CreateScalar(value);
ValidateResult(result, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int32 value = TestLibrary.Generator.GetInt32();
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.CreateScalar), new Type[] { typeof(Int32) })
.Invoke(null, new object[] { value });
ValidateResult((Vector64<Int32>)(result), value);
}
private void ValidateResult(Vector64<Int32> result, Int32 expectedValue, [CallerMemberName] string method = "")
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValue, method);
}
private void ValidateResult(Int32[] resultElements, Int32 expectedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (resultElements[0] != expectedValue)
{
succeeded = false;
}
else
{
for (var i = 1; i < ElementCount; i++)
{
if (resultElements[i] != 0)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64.CreateScalar(Int32): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: {expectedValue}");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/nativeaot/docs/optimizing.md
|
# Optimizing programs targeting Native AOT
The Native AOT compiler provides multiple switches to influence the compilation process. These switches control the code and metadata that the compiler generates and affect the runtime behavior of the compiled program.
To specify a switch, add a new property to your project file with one or more of the values below. For example, to specify the invariant globalization mode, add
```xml
<PropertyGroup>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
```
under the `<Project>` node of your project file.
## Options related to library features
Native AOT supports enabling and disabling all [documented framework library features](https://docs.microsoft.com/en-us/dotnet/core/deploying/trimming-options#trimming-framework-library-features). For example, to remove globalization specific code and data, add a `<InvariantGlobalization>true</InvariantGlobalization>` property to your project. Disabling a framework feature (or enabling a minimal mode of the feature) can result in significant size savings.
🛈 Native AOT difference: The `EnableUnsafeBinaryFormatterSerialization` framework switch is already set to the optimal value of `false` (removing the support for [obsolete](https://github.com/dotnet/designs/blob/21b274dbc21e4ae54b7e4c5dbd5ef31e439e78db/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md) binary serialization).
## Options related to trimming
The Native AOT compiler supports the [documented options](https://docs.microsoft.com/en-us/dotnet/core/deploying/trim-self-contained) for removing unused code (trimming). By default, the compiler tries to very conservatively remove some of the unused code.
🛈 Native AOT difference: The documented `PublishTrimmed` property is implied to be `true` when Native AOT is active.
By default, the compiler tries to maximize compatibility with existing .NET code at the expense of compilation speed and size of the output executable. This allows people to use their existing code that worked well in a fully dynamic mode without hitting issues caused by trimming. To read more about reflection, see the [Reflection in AOT mode](reflection-in-aot-mode.md) document.
🛈 Native AOT difference: the `TrimMode` of framework assemblies is set to `link` by default. To compile entire framework assemblies, use `TrimmerRootAssembly` to root the selected assemblies. It's not recommended to root the entire framework.
To enable more aggressive removal of unreferenced code, set the `<TrimMode>` property to `link`.
To aid in troubleshooting some of the most common problems related to trimming add `<IlcGenerateCompleteTypeMetadata>true</IlcGenerateCompleteTypeMetadata>` to your project. This ensures types are preserved in their entirety, but the extra members that would otherwise be trimmed cannot be used in runtime reflection. This mode can turn some spurious `NullReferenceExceptions` (caused by reflection APIs returning a null) caused by trimming into more actionable exceptions.
## Options related to metadata generation
* `<IlcGenerateStackTraceData>false</IlcGenerateStackTraceData>`: this disables generation of stack trace metadata that provides textual names in stack traces. This is for example the text string one gets by calling `Exception.ToString()` on a caught exception. With this option disabled, stack traces will still be generated, but will be based on reflection metadata alone (they might be less complete).
* `<IlcTrimMetadata>true</IlcTrimMetadata>`: allows the compiler to remove reflection metadata from things that were not visible targets of reflection. By default, the compiler keeps metadata for everything that was compiled. With this option turned on, reflection metadata (and therefore reflection) will only be available for visible targets of reflection. Visible targets of reflection are things like assemblies rooted from the project file, RD.XML, ILLinkTrim descriptors, DynamicallyAccessedMembers annotations or DynamicDependency annotations.
* `<IlcDisableReflection>true</IlcDisableReflection>`: this completely disables the reflection metadata generation. Very basic reflection will still work (you can still use `typeof`, call `Object.GetType()`, compare the results, and query for basic properties such as `Type.IsValueType` or `Type.BaseType`), but most of the reflection stack will no longer work (no way to query/access methods and fields on types, or get names of types). This mode is experimental - more details in the [Reflection free mode](reflection-free-mode.md) document.
## Options related to code generation
* `<IlcOptimizationPreference>Speed</IlcOptimizationPreference>`: when generating optimized code, favor code execution speed.
* `<IlcOptimizationPreference>Size</IlcOptimizationPreference>`: when generating optimized code, favor smaller code size.
* `<IlcFoldIdenticalMethodBodies>true</IlcFoldIdenticalMethodBodies>`: folds method bodies with identical bytes (method body deduplication). This makes your app smaller, but the stack traces might sometimes look nonsensical (unexpected methods might show up in the stack trace because the expected method had the same bytes as the unexpected method). Note: the current implementation of deduplication doesn't attempt to make the folding unobservable to managed code: delegates pointing to two logically different methods that ended up being folded together will compare equal.
## Special considerations for Linux/macOS
Debugging symbols (data about your program required for debugging) is by default part of native executable files on Unix-like operating systems. To minimize the size of your CoreRT-compiled executable, you can run the `strip` tool to remove the debugging symbols.
No action is needed on Windows since the platform convention is to generate debug information into a separate file (`*.pdb`).
|
# Optimizing programs targeting Native AOT
The Native AOT compiler provides multiple switches to influence the compilation process. These switches control the code and metadata that the compiler generates and affect the runtime behavior of the compiled program.
To specify a switch, add a new property to your project file with one or more of the values below. For example, to specify the invariant globalization mode, add
```xml
<PropertyGroup>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
```
under the `<Project>` node of your project file.
## Options related to library features
Native AOT supports enabling and disabling all [documented framework library features](https://docs.microsoft.com/en-us/dotnet/core/deploying/trimming-options#trimming-framework-library-features). For example, to remove globalization specific code and data, add a `<InvariantGlobalization>true</InvariantGlobalization>` property to your project. Disabling a framework feature (or enabling a minimal mode of the feature) can result in significant size savings.
🛈 Native AOT difference: The `EnableUnsafeBinaryFormatterSerialization` framework switch is already set to the optimal value of `false` (removing the support for [obsolete](https://github.com/dotnet/designs/blob/21b274dbc21e4ae54b7e4c5dbd5ef31e439e78db/accepted/2020/better-obsoletion/binaryformatter-obsoletion.md) binary serialization).
## Options related to trimming
The Native AOT compiler supports the [documented options](https://docs.microsoft.com/en-us/dotnet/core/deploying/trim-self-contained) for removing unused code (trimming). By default, the compiler tries to very conservatively remove some of the unused code.
🛈 Native AOT difference: The documented `PublishTrimmed` property is implied to be `true` when Native AOT is active.
By default, the compiler tries to maximize compatibility with existing .NET code at the expense of compilation speed and size of the output executable. This allows people to use their existing code that worked well in a fully dynamic mode without hitting issues caused by trimming. To read more about reflection, see the [Reflection in AOT mode](reflection-in-aot-mode.md) document.
🛈 Native AOT difference: the `TrimMode` of framework assemblies is set to `link` by default. To compile entire framework assemblies, use `TrimmerRootAssembly` to root the selected assemblies. It's not recommended to root the entire framework.
To enable more aggressive removal of unreferenced code, set the `<TrimMode>` property to `link`.
To aid in troubleshooting some of the most common problems related to trimming add `<IlcGenerateCompleteTypeMetadata>true</IlcGenerateCompleteTypeMetadata>` to your project. This ensures types are preserved in their entirety, but the extra members that would otherwise be trimmed cannot be used in runtime reflection. This mode can turn some spurious `NullReferenceExceptions` (caused by reflection APIs returning a null) caused by trimming into more actionable exceptions.
## Options related to metadata generation
* `<IlcGenerateStackTraceData>false</IlcGenerateStackTraceData>`: this disables generation of stack trace metadata that provides textual names in stack traces. This is for example the text string one gets by calling `Exception.ToString()` on a caught exception. With this option disabled, stack traces will still be generated, but will be based on reflection metadata alone (they might be less complete).
* `<IlcTrimMetadata>true</IlcTrimMetadata>`: allows the compiler to remove reflection metadata from things that were not visible targets of reflection. By default, the compiler keeps metadata for everything that was compiled. With this option turned on, reflection metadata (and therefore reflection) will only be available for visible targets of reflection. Visible targets of reflection are things like assemblies rooted from the project file, RD.XML, ILLinkTrim descriptors, DynamicallyAccessedMembers annotations or DynamicDependency annotations.
* `<IlcDisableReflection>true</IlcDisableReflection>`: this completely disables the reflection metadata generation. Very basic reflection will still work (you can still use `typeof`, call `Object.GetType()`, compare the results, and query for basic properties such as `Type.IsValueType` or `Type.BaseType`), but most of the reflection stack will no longer work (no way to query/access methods and fields on types, or get names of types). This mode is experimental - more details in the [Reflection free mode](reflection-free-mode.md) document.
## Options related to code generation
* `<IlcOptimizationPreference>Speed</IlcOptimizationPreference>`: when generating optimized code, favor code execution speed.
* `<IlcOptimizationPreference>Size</IlcOptimizationPreference>`: when generating optimized code, favor smaller code size.
* `<IlcFoldIdenticalMethodBodies>true</IlcFoldIdenticalMethodBodies>`: folds method bodies with identical bytes (method body deduplication). This makes your app smaller, but the stack traces might sometimes look nonsensical (unexpected methods might show up in the stack trace because the expected method had the same bytes as the unexpected method). Note: the current implementation of deduplication doesn't attempt to make the folding unobservable to managed code: delegates pointing to two logically different methods that ended up being folded together will compare equal.
## Special considerations for Linux/macOS
Debugging symbols (data about your program required for debugging) is by default part of native executable files on Unix-like operating systems. To minimize the size of your CoreRT-compiled executable, you can run the `strip` tool to remove the debugging symbols.
No action is needed on Windows since the platform convention is to generate debug information into a separate file (`*.pdb`).
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/Directed/PREFIX/volatile/1/arglistARM.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
CompareArgs() works as such:
CompareArgs(3,1,2,3,1,2,3)
Where arg0 is 1/2 the number of the
remaining arguments.
And the arguments 1,2,3 and 1,2,3 are
treated as two separate lists of size
arg0 whose elements are compared to one
another.
ie. in this case CompareArgs checks that
arg1==arg4, arg2==arg5, arg3==arg6.
The vararg cookie in the case of x86 and ARM
is after/before the declared arguments respectively:
(from Compiler::lvaInitTypeRef() in lclvars.cpp)
x86 args look something like this:
[this ptr] [hidden return buffer] [declared arguments]* [generic context] [var arg cookie]
ARM is closer to the native ABI:
[hidden return buffer] [this ptr] [generic context] [var arg cookie] [declared arguments]*
*/
.assembly extern legacy library mscorlib {}
.assembly 'arglist'{ //This byte field requests that this assembly not be verified at run time and corresponds to this C# declaration:
//[assembly:System.Security.Permissions.SecurityPermissionAttribute( [mscorlib]System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.SkipVerification )]
}
.method static vararg int32 CompareArgs(int32){
.locals(int32 currentindex, int32 loopconstant)
.maxstack 10
.try{
ldc.i4 2
stloc currentindex
ldarg 0
stloc loopconstant
LOOP: ldloc currentindex
ldc.i4 4
mul
arglist
add
volatile.
unaligned. 0x1
ldind.i4
ldloc currentindex
ldloc loopconstant
add
ldc.i4 4
mul
arglist
add
volatile.
unaligned. 0x1
ldind.i4
ceq
brfalse EXITWITHFAIL
ldloc currentindex
ldloc loopconstant
ldc.i4 1
add
beq EXITWITHPASS
ldc.i4 1
ldloc currentindex
add
stloc currentindex
br LOOP
EXITWITHPASS:
leave SUCCESS
EXITWITHFAIL:
leave FAIL
}catch [mscorlib]System.NullReferenceException{
pop
leave FAIL
}
SUCCESS:
ldc.i4 0x64
ret
FAIL:
ldc.i4 0x0
REALLYDONE:
ret
}
//-------------------------
// Entry point - Main -
//-------------------------
.method static int32 main() {
.entrypoint
.locals ()
.maxstack 10
ldc.i4 1
ldc.i4 1
ldc.i4 1
call vararg int32 CompareArgs(int32,...,int32,int32)
brfalse FAIL
ldc.i4 4
ldc.i4 2
ldc.i4 3
ldc.i4 4
ldc.i4 5
ldc.i4 2
ldc.i4 3
ldc.i4 4
ldc.i4 5
call vararg int32 CompareArgs(int32,...,int32,int32,int32,int32,int32,int32,int32,int32)
brfalse FAIL
PASS:
ldc.i4 0x64
ret
FAIL:
ldc.i4 0x0
ret
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
CompareArgs() works as such:
CompareArgs(3,1,2,3,1,2,3)
Where arg0 is 1/2 the number of the
remaining arguments.
And the arguments 1,2,3 and 1,2,3 are
treated as two separate lists of size
arg0 whose elements are compared to one
another.
ie. in this case CompareArgs checks that
arg1==arg4, arg2==arg5, arg3==arg6.
The vararg cookie in the case of x86 and ARM
is after/before the declared arguments respectively:
(from Compiler::lvaInitTypeRef() in lclvars.cpp)
x86 args look something like this:
[this ptr] [hidden return buffer] [declared arguments]* [generic context] [var arg cookie]
ARM is closer to the native ABI:
[hidden return buffer] [this ptr] [generic context] [var arg cookie] [declared arguments]*
*/
.assembly extern legacy library mscorlib {}
.assembly 'arglist'{ //This byte field requests that this assembly not be verified at run time and corresponds to this C# declaration:
//[assembly:System.Security.Permissions.SecurityPermissionAttribute( [mscorlib]System.Security.Permissions.SecurityAction.RequestMinimum, Flags=System.Security.Permissions.SecurityPermissionFlag.SkipVerification )]
}
.method static vararg int32 CompareArgs(int32){
.locals(int32 currentindex, int32 loopconstant)
.maxstack 10
.try{
ldc.i4 2
stloc currentindex
ldarg 0
stloc loopconstant
LOOP: ldloc currentindex
ldc.i4 4
mul
arglist
add
volatile.
unaligned. 0x1
ldind.i4
ldloc currentindex
ldloc loopconstant
add
ldc.i4 4
mul
arglist
add
volatile.
unaligned. 0x1
ldind.i4
ceq
brfalse EXITWITHFAIL
ldloc currentindex
ldloc loopconstant
ldc.i4 1
add
beq EXITWITHPASS
ldc.i4 1
ldloc currentindex
add
stloc currentindex
br LOOP
EXITWITHPASS:
leave SUCCESS
EXITWITHFAIL:
leave FAIL
}catch [mscorlib]System.NullReferenceException{
pop
leave FAIL
}
SUCCESS:
ldc.i4 0x64
ret
FAIL:
ldc.i4 0x0
REALLYDONE:
ret
}
//-------------------------
// Entry point - Main -
//-------------------------
.method static int32 main() {
.entrypoint
.locals ()
.maxstack 10
ldc.i4 1
ldc.i4 1
ldc.i4 1
call vararg int32 CompareArgs(int32,...,int32,int32)
brfalse FAIL
ldc.i4 4
ldc.i4 2
ldc.i4 3
ldc.i4 4
ldc.i4 5
ldc.i4 2
ldc.i4 3
ldc.i4 4
ldc.i4 5
call vararg int32 CompareArgs(int32,...,int32,int32,int32,int32,int32,int32,int32,int32)
brfalse FAIL
PASS:
ldc.i4 0x64
ret
FAIL:
ldc.i4 0x0
ret
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.EventSetInformation.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Advapi32
{
[LibraryImport(Libraries.Advapi32)]
internal static unsafe partial int EventSetInformation(
long registrationHandle,
EVENT_INFO_CLASS informationClass,
void* eventInformation,
uint informationLength);
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Advapi32
{
[LibraryImport(Libraries.Advapi32)]
internal static unsafe partial int EventSetInformation(
long registrationHandle,
EVENT_INFO_CLASS informationClass,
void* eventInformation,
uint informationLength);
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/Common/src/Microsoft/Win32/SafeHandles/SafeLsaMemoryHandle.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeLsaMemoryHandle : SafeBuffer
{
public SafeLsaMemoryHandle() : base(true) { }
// 0 is an Invalid Handle
internal SafeLsaMemoryHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
return Interop.Advapi32.LsaFreeMemory(handle) == 0;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeLsaMemoryHandle : SafeBuffer
{
public SafeLsaMemoryHandle() : base(true) { }
// 0 is an Invalid Handle
internal SafeLsaMemoryHandle(IntPtr handle) : base(true)
{
SetHandle(handle);
}
protected override bool ReleaseHandle()
{
return Interop.Advapi32.LsaFreeMemory(handle) == 0;
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b26748/b26748.il
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly ILGEN_0x862954f4 {}
.class ILGEN_0x862954f4 {
.field static unsigned int64 field_0x3
.field static float32[] field_0x12
.method static int32 main() {
.entrypoint
.maxstack 18
.locals (int64[] local_0x7,int64 local_0xf,int32 ecode)
ldc.i4.1
stloc ecode
.try {
ldc.i4 255
newarr [mscorlib]System.Int64
stloc local_0x7
ldc.i8 0x2b06ff023e62ea0
stloc local_0xf
ldc.i8 0x4d3410d73e16468
stsfld unsigned int64 ILGEN_0x862954f4::field_0x3
ldc.i4 255
newarr [mscorlib]System.Single
stsfld float32[] ILGEN_0x862954f4::field_0x12
ldloc local_0xf
conv.ovf.i1.un
Start_Orphan_29:
ldloc local_0x7
ldsfld float32[] ILGEN_0x862954f4::field_0x12
ldc.i4.2
ldelem.r4
conv.ovf.u1
ldloc local_0xf
conv.i8
ldc.i8 0x5cc32efe5897244
ldsfld unsigned int64 ILGEN_0x862954f4::field_0x3
rem.un
sub.ovf
stelem.i8
End_Orphan_29:
Start_Orphan_2d:
ldloca local_0xf
pop
End_Orphan_2d:
conv.i4
pop
leave xx
} catch [mscorlib]System.OverflowException {
pop
ldc.i4.0
stloc ecode
leave xx
}
xx:
ldloc ecode
ldc.i4 100
add
ret
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
.assembly extern legacy library mscorlib {}
.assembly extern System.Console
{
.publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )
.ver 4:0:0:0
}
.assembly ILGEN_0x862954f4 {}
.class ILGEN_0x862954f4 {
.field static unsigned int64 field_0x3
.field static float32[] field_0x12
.method static int32 main() {
.entrypoint
.maxstack 18
.locals (int64[] local_0x7,int64 local_0xf,int32 ecode)
ldc.i4.1
stloc ecode
.try {
ldc.i4 255
newarr [mscorlib]System.Int64
stloc local_0x7
ldc.i8 0x2b06ff023e62ea0
stloc local_0xf
ldc.i8 0x4d3410d73e16468
stsfld unsigned int64 ILGEN_0x862954f4::field_0x3
ldc.i4 255
newarr [mscorlib]System.Single
stsfld float32[] ILGEN_0x862954f4::field_0x12
ldloc local_0xf
conv.ovf.i1.un
Start_Orphan_29:
ldloc local_0x7
ldsfld float32[] ILGEN_0x862954f4::field_0x12
ldc.i4.2
ldelem.r4
conv.ovf.u1
ldloc local_0xf
conv.i8
ldc.i8 0x5cc32efe5897244
ldsfld unsigned int64 ILGEN_0x862954f4::field_0x3
rem.un
sub.ovf
stelem.i8
End_Orphan_29:
Start_Orphan_2d:
ldloca local_0xf
pop
End_Orphan_2d:
conv.i4
pop
leave xx
} catch [mscorlib]System.OverflowException {
pop
ldc.i4.0
stloc ecode
leave xx
}
xx:
ldloc ecode
ldc.i4 100
add
ret
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/HardwareIntrinsics/X86/Avx1/BroadcastScalarToVector256.Single.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BroadcastScalarToVector256Single()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector256Single();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector256Single
{
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
public SimpleUnaryOpTest__BroadcastScalarToVector256Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.BroadcastScalarToVector256(
(Single*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.BroadcastScalarToVector256), new Type[] { typeof(Single*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(Single*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.BroadcastScalarToVector256)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BroadcastScalarToVector256Single()
{
var test = new SimpleUnaryOpTest__BroadcastScalarToVector256Single();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_Load();
// Validates calling via reflection works
test.RunReflectionScenario_Load();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__BroadcastScalarToVector256Single
{
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
public SimpleUnaryOpTest__BroadcastScalarToVector256Single()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.BroadcastScalarToVector256(
(Single*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.BroadcastScalarToVector256), new Type[] { typeof(Single*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(Single*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_Load();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.BroadcastScalarToVector256)}<Single>(Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Text.Json/tests/Common/ConstructorTests/ConstructorTests.Stream.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public abstract partial class ConstructorTests
{
[Fact]
[SkipOnCoreClr("https://github.com/dotnet/runtime/issues/45464", ~RuntimeConfiguration.Release)]
public async Task ReadSimpleObjectAsync()
{
async Task RunTestAsync<T>(byte[] testData)
{
using (MemoryStream stream = new MemoryStream(testData))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
var obj = await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options);
((ITestClass)obj).Verify();
}
}
// Array size is the count of the following tests.
Task[] tasks = new Task[16];
// Simple models can be deserialized.
tasks[0] = Task.Run(async () => await RunTestAsync<Parameterized_IndexViewModel_Immutable>(Parameterized_IndexViewModel_Immutable.s_data));
// Complex models can be deserialized.
tasks[1] = Task.Run(async () => await RunTestAsync<ObjWCtorMixedParams>(ObjWCtorMixedParams.s_data));
tasks[2] = Task.Run(async () => await RunTestAsync<Parameterized_Class_With_ComplexTuple>(Parameterized_Class_With_ComplexTuple.s_data));
// JSON that doesn't bind to ctor args are matched with properties or ignored (as appropriate).
tasks[3] = Task.Run(async () => await RunTestAsync<Person_Class>(Person_Class.s_data));
tasks[4] = Task.Run(async () => await RunTestAsync<Person_Struct>(Person_Struct.s_data));
// JSON that doesn't bind to ctor args or properties are sent to ext data if avaiable.
tasks[5] = Task.Run(async () => await RunTestAsync<Parameterized_Person>(Parameterized_Person.s_data));
tasks[6] = Task.Run(async () => await RunTestAsync<Parameterized_Person_ObjExtData>(Parameterized_Person_ObjExtData.s_data));
// Up to 64 ctor args are supported.
tasks[7] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_64_Params>(Class_With_Ctor_With_64_Params.Data));
// Arg deserialization honors attributes on matching property.
tasks[8] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonPropertyName>(Point_MembersHave_JsonPropertyName.s_data));
tasks[9] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonConverter>(Point_MembersHave_JsonConverter.s_data));
tasks[10] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonIgnore>(Point_MembersHave_JsonIgnore.s_data));
tasks[11] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonInclude>(Point_MembersHave_JsonInclude.s_data));
tasks[12] = Task.Run(async () => await RunTestAsync<ClassWithFiveArgs_MembersHave_JsonNumberHandlingAttributes>(ClassWithFiveArgs_MembersHave_JsonNumberHandlingAttributes.s_data));
// Complex JSON as last argument works
tasks[13] = Task.Run(async () => await RunTestAsync<Point_With_Array>(Point_With_Array.s_data));
tasks[14] = Task.Run(async () => await RunTestAsync<Point_With_Dictionary>(Point_With_Dictionary.s_data));
tasks[15] = Task.Run(async () => await RunTestAsync<Point_With_Object>(Point_With_Object.s_data));
await Task.WhenAll(tasks);
}
[Fact]
public async Task ReadSimpleObjectWithTrailingTriviaAsync()
{
async Task RunTestAsync<T>(string testData)
{
byte[] data = Encoding.UTF8.GetBytes(testData + " /* Multi\r\nLine Comment */\t");
using (MemoryStream stream = new MemoryStream(data))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1,
ReadCommentHandling = JsonCommentHandling.Skip,
};
var obj = await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options);
((ITestClass)obj).Verify();
}
}
// Array size is the count of the following tests.
Task[] tasks = new Task[14];
// Simple models can be deserialized.
tasks[0] = Task.Run(async () => await RunTestAsync<Parameterized_IndexViewModel_Immutable>(Parameterized_IndexViewModel_Immutable.s_json));
// Complex models can be deserialized.
tasks[1] = Task.Run(async () => await RunTestAsync<ObjWCtorMixedParams>(ObjWCtorMixedParams.s_json));
tasks[2] = Task.Run(async () => await RunTestAsync<Parameterized_Class_With_ComplexTuple>(Parameterized_Class_With_ComplexTuple.s_json));
// JSON that doesn't bind to ctor args are matched with properties or ignored (as appropriate).
tasks[3] = Task.Run(async () => await RunTestAsync<Person_Class>(Person_Class.s_json));
tasks[4] = Task.Run(async () => await RunTestAsync<Person_Struct>(Person_Struct.s_json));
// JSON that doesn't bind to ctor args or properties are sent to ext data if avaiable.
tasks[5] = Task.Run(async () => await RunTestAsync<Parameterized_Person>(Parameterized_Person.s_json));
tasks[6] = Task.Run(async () => await RunTestAsync<Parameterized_Person_ObjExtData>(Parameterized_Person_ObjExtData.s_json));
// Up to 64 ctor args are supported.
tasks[7] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_64_Params>(Encoding.UTF8.GetString(Class_With_Ctor_With_64_Params.Data)));
// Arg8deserialization honors attributes on matching property.
tasks[8] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonPropertyName>(Point_MembersHave_JsonPropertyName.s_json));
tasks[9] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonConverter>(Point_MembersHave_JsonConverter.s_json));
tasks[10] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonIgnore>(Point_MembersHave_JsonIgnore.s_json));
// Complex JSON as last argument works
tasks[11] = Task.Run(async () => await RunTestAsync<Point_With_Array>(Point_With_Array.s_json));
tasks[12] = Task.Run(async () => await RunTestAsync<Point_With_Dictionary>(Point_With_Dictionary.s_json));
tasks[13] = Task.Run(async () => await RunTestAsync<Point_With_Object>(Point_With_Object.s_json));
await Task.WhenAll(tasks);
}
[Fact]
public async Task Cannot_DeserializeAsync_ObjectWith_Ctor_With_65_Params()
{
async Task RunTestAsync<T>()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
for (int i = 0; i < 64; i++)
{
sb.Append($@"""Int{i}"":{i},");
}
sb.Append($@"""Int64"":64");
sb.Append("}");
string input = sb.ToString();
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(input)))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
await Assert.ThrowsAsync<NotSupportedException>(async () => await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options));
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}")))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
await Assert.ThrowsAsync<NotSupportedException>(async () => await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options));
}
}
Task[] tasks = new Task[2];
tasks[0] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_65_Params>());
tasks[1] = Task.Run(async () => await RunTestAsync<Struct_With_Ctor_With_65_Params>());
await Task.WhenAll(tasks);
}
[Fact]
public async Task ExerciseStreamCodePaths()
{
static string GetPropertyName(int index) =>
new string(new char[] { Convert.ToChar(index + 65), 'V', 'a', 'l', 'u', 'e' });
static byte[] GeneratePayload(int i, string value)
{
string whiteSpace = new string(' ', 16);
StringBuilder sb;
string prefix = "";
sb = new StringBuilder();
sb.Append("{");
for (int j = 0; j < i; j++)
{
sb.Append(prefix);
sb.Append($@"""{GetPropertyName(j)}"":""{value}""");
prefix = ",";
}
sb.Append(prefix);
sb.Append($@"{whiteSpace}""{GetPropertyName(i)}"":{whiteSpace}""{value}""");
prefix = ",";
for (int j = 0; j < 10; j++)
{
sb.Append(prefix);
string keyPair = $@"""rand"":[""{value}""]";
sb.Append($@"""Value{j}"":{{{keyPair},{keyPair},{keyPair}}}");
}
for (int j = i + 1; j < 20; j++)
{
sb.Append(prefix);
sb.Append($@"""{GetPropertyName(j)}"":""{value}""");
}
sb.Append("}");
return Encoding.UTF8.GetBytes(sb.ToString());
}
const string value = "ul4Oolt4VgbNm5Y1qPX911wxhyHFEQmmWBcIBR6BfUaNuIn3YOJ8vqtqz2WAh924rEILMzlh6JUhQDcmH00SI6Kv4iGTHQfGXxqWul4Oolt4VgbNm5Y1qPX911wxhyHFEQmmWBcIBR6";
for (int i = 0; i < 20; i++)
{
using (MemoryStream stream = new MemoryStream(GeneratePayload(i, value)))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
ClassWithStrings obj = await JsonSerializerWrapperForStream.DeserializeWrapper<ClassWithStrings>(stream, options);
obj.Verify(value);
}
}
}
public class ClassWithStrings
{
// Ctor args.
// Ignored.
[JsonIgnore]
public string AValue { get; }
[JsonIgnore]
public string EValue { get; }
[JsonIgnore]
public string IValue { get; }
[JsonIgnore]
public string MValue { get; }
[JsonIgnore]
public string QValue { get; }
// Populated.
public string CValue { get; }
public string GValue { get; }
public string KValue { get; }
public string OValue { get; }
public string SValue { get; }
// Properties.
// Ignored - no setter.
public string BValue { get; }
public string FValue { get; }
public string JValue { get; }
public string NValue { get; }
public string RValue { get; }
// Populated.
public string DValue { get; set; }
public string HValue { get; set; }
public string LValue { get; set; }
public string PValue { get; set; }
public string TValue { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
public ClassWithStrings(
string aValue,
string cValue,
string eValue,
string gValue,
string iValue,
string kValue,
string mValue,
string oValue,
string qValue,
string sValue)
{
AValue = aValue;
CValue = cValue;
EValue = eValue;
GValue = gValue;
IValue = iValue;
KValue = kValue;
MValue = mValue;
OValue = oValue;
QValue = qValue;
SValue = sValue;
}
public void Verify(string expectedStr)
{
// Ctor args.
// Ignored
Assert.Null(AValue);
Assert.Null(EValue);
Assert.Null(IValue);
Assert.Null(MValue);
Assert.Null(QValue);
Assert.Equal(expectedStr, CValue);
Assert.Equal(expectedStr, GValue);
Assert.Equal(expectedStr, KValue);
Assert.Equal(expectedStr, OValue);
Assert.Equal(expectedStr, SValue);
// Getter only members - skipped.
Assert.Null(BValue);
Assert.Null(FValue);
Assert.Null(JValue);
Assert.Null(NValue);
Assert.Null(RValue);
// Members with setters
Assert.Equal(expectedStr, DValue);
Assert.Equal(expectedStr, HValue);
Assert.Equal(expectedStr, LValue);
Assert.Equal(expectedStr, PValue);
Assert.Equal(expectedStr, TValue);
Assert.Equal(10, ExtensionData.Count);
foreach (JsonElement value in ExtensionData.Values)
{
string keyPair = $@"""rand"":[""{expectedStr}""]";
Assert.Equal($@"{{{keyPair},{keyPair},{keyPair}}}", value.GetRawText());
}
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public abstract partial class ConstructorTests
{
[Fact]
[SkipOnCoreClr("https://github.com/dotnet/runtime/issues/45464", ~RuntimeConfiguration.Release)]
public async Task ReadSimpleObjectAsync()
{
async Task RunTestAsync<T>(byte[] testData)
{
using (MemoryStream stream = new MemoryStream(testData))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
var obj = await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options);
((ITestClass)obj).Verify();
}
}
// Array size is the count of the following tests.
Task[] tasks = new Task[16];
// Simple models can be deserialized.
tasks[0] = Task.Run(async () => await RunTestAsync<Parameterized_IndexViewModel_Immutable>(Parameterized_IndexViewModel_Immutable.s_data));
// Complex models can be deserialized.
tasks[1] = Task.Run(async () => await RunTestAsync<ObjWCtorMixedParams>(ObjWCtorMixedParams.s_data));
tasks[2] = Task.Run(async () => await RunTestAsync<Parameterized_Class_With_ComplexTuple>(Parameterized_Class_With_ComplexTuple.s_data));
// JSON that doesn't bind to ctor args are matched with properties or ignored (as appropriate).
tasks[3] = Task.Run(async () => await RunTestAsync<Person_Class>(Person_Class.s_data));
tasks[4] = Task.Run(async () => await RunTestAsync<Person_Struct>(Person_Struct.s_data));
// JSON that doesn't bind to ctor args or properties are sent to ext data if avaiable.
tasks[5] = Task.Run(async () => await RunTestAsync<Parameterized_Person>(Parameterized_Person.s_data));
tasks[6] = Task.Run(async () => await RunTestAsync<Parameterized_Person_ObjExtData>(Parameterized_Person_ObjExtData.s_data));
// Up to 64 ctor args are supported.
tasks[7] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_64_Params>(Class_With_Ctor_With_64_Params.Data));
// Arg deserialization honors attributes on matching property.
tasks[8] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonPropertyName>(Point_MembersHave_JsonPropertyName.s_data));
tasks[9] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonConverter>(Point_MembersHave_JsonConverter.s_data));
tasks[10] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonIgnore>(Point_MembersHave_JsonIgnore.s_data));
tasks[11] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonInclude>(Point_MembersHave_JsonInclude.s_data));
tasks[12] = Task.Run(async () => await RunTestAsync<ClassWithFiveArgs_MembersHave_JsonNumberHandlingAttributes>(ClassWithFiveArgs_MembersHave_JsonNumberHandlingAttributes.s_data));
// Complex JSON as last argument works
tasks[13] = Task.Run(async () => await RunTestAsync<Point_With_Array>(Point_With_Array.s_data));
tasks[14] = Task.Run(async () => await RunTestAsync<Point_With_Dictionary>(Point_With_Dictionary.s_data));
tasks[15] = Task.Run(async () => await RunTestAsync<Point_With_Object>(Point_With_Object.s_data));
await Task.WhenAll(tasks);
}
[Fact]
public async Task ReadSimpleObjectWithTrailingTriviaAsync()
{
async Task RunTestAsync<T>(string testData)
{
byte[] data = Encoding.UTF8.GetBytes(testData + " /* Multi\r\nLine Comment */\t");
using (MemoryStream stream = new MemoryStream(data))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1,
ReadCommentHandling = JsonCommentHandling.Skip,
};
var obj = await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options);
((ITestClass)obj).Verify();
}
}
// Array size is the count of the following tests.
Task[] tasks = new Task[14];
// Simple models can be deserialized.
tasks[0] = Task.Run(async () => await RunTestAsync<Parameterized_IndexViewModel_Immutable>(Parameterized_IndexViewModel_Immutable.s_json));
// Complex models can be deserialized.
tasks[1] = Task.Run(async () => await RunTestAsync<ObjWCtorMixedParams>(ObjWCtorMixedParams.s_json));
tasks[2] = Task.Run(async () => await RunTestAsync<Parameterized_Class_With_ComplexTuple>(Parameterized_Class_With_ComplexTuple.s_json));
// JSON that doesn't bind to ctor args are matched with properties or ignored (as appropriate).
tasks[3] = Task.Run(async () => await RunTestAsync<Person_Class>(Person_Class.s_json));
tasks[4] = Task.Run(async () => await RunTestAsync<Person_Struct>(Person_Struct.s_json));
// JSON that doesn't bind to ctor args or properties are sent to ext data if avaiable.
tasks[5] = Task.Run(async () => await RunTestAsync<Parameterized_Person>(Parameterized_Person.s_json));
tasks[6] = Task.Run(async () => await RunTestAsync<Parameterized_Person_ObjExtData>(Parameterized_Person_ObjExtData.s_json));
// Up to 64 ctor args are supported.
tasks[7] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_64_Params>(Encoding.UTF8.GetString(Class_With_Ctor_With_64_Params.Data)));
// Arg8deserialization honors attributes on matching property.
tasks[8] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonPropertyName>(Point_MembersHave_JsonPropertyName.s_json));
tasks[9] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonConverter>(Point_MembersHave_JsonConverter.s_json));
tasks[10] = Task.Run(async () => await RunTestAsync<Point_MembersHave_JsonIgnore>(Point_MembersHave_JsonIgnore.s_json));
// Complex JSON as last argument works
tasks[11] = Task.Run(async () => await RunTestAsync<Point_With_Array>(Point_With_Array.s_json));
tasks[12] = Task.Run(async () => await RunTestAsync<Point_With_Dictionary>(Point_With_Dictionary.s_json));
tasks[13] = Task.Run(async () => await RunTestAsync<Point_With_Object>(Point_With_Object.s_json));
await Task.WhenAll(tasks);
}
[Fact]
public async Task Cannot_DeserializeAsync_ObjectWith_Ctor_With_65_Params()
{
async Task RunTestAsync<T>()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
for (int i = 0; i < 64; i++)
{
sb.Append($@"""Int{i}"":{i},");
}
sb.Append($@"""Int64"":64");
sb.Append("}");
string input = sb.ToString();
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(input)))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
await Assert.ThrowsAsync<NotSupportedException>(async () => await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options));
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{}")))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
await Assert.ThrowsAsync<NotSupportedException>(async () => await JsonSerializerWrapperForStream.DeserializeWrapper<T>(stream, options));
}
}
Task[] tasks = new Task[2];
tasks[0] = Task.Run(async () => await RunTestAsync<Class_With_Ctor_With_65_Params>());
tasks[1] = Task.Run(async () => await RunTestAsync<Struct_With_Ctor_With_65_Params>());
await Task.WhenAll(tasks);
}
[Fact]
public async Task ExerciseStreamCodePaths()
{
static string GetPropertyName(int index) =>
new string(new char[] { Convert.ToChar(index + 65), 'V', 'a', 'l', 'u', 'e' });
static byte[] GeneratePayload(int i, string value)
{
string whiteSpace = new string(' ', 16);
StringBuilder sb;
string prefix = "";
sb = new StringBuilder();
sb.Append("{");
for (int j = 0; j < i; j++)
{
sb.Append(prefix);
sb.Append($@"""{GetPropertyName(j)}"":""{value}""");
prefix = ",";
}
sb.Append(prefix);
sb.Append($@"{whiteSpace}""{GetPropertyName(i)}"":{whiteSpace}""{value}""");
prefix = ",";
for (int j = 0; j < 10; j++)
{
sb.Append(prefix);
string keyPair = $@"""rand"":[""{value}""]";
sb.Append($@"""Value{j}"":{{{keyPair},{keyPair},{keyPair}}}");
}
for (int j = i + 1; j < 20; j++)
{
sb.Append(prefix);
sb.Append($@"""{GetPropertyName(j)}"":""{value}""");
}
sb.Append("}");
return Encoding.UTF8.GetBytes(sb.ToString());
}
const string value = "ul4Oolt4VgbNm5Y1qPX911wxhyHFEQmmWBcIBR6BfUaNuIn3YOJ8vqtqz2WAh924rEILMzlh6JUhQDcmH00SI6Kv4iGTHQfGXxqWul4Oolt4VgbNm5Y1qPX911wxhyHFEQmmWBcIBR6";
for (int i = 0; i < 20; i++)
{
using (MemoryStream stream = new MemoryStream(GeneratePayload(i, value)))
{
JsonSerializerOptions options = new JsonSerializerOptions
{
DefaultBufferSize = 1
};
ClassWithStrings obj = await JsonSerializerWrapperForStream.DeserializeWrapper<ClassWithStrings>(stream, options);
obj.Verify(value);
}
}
}
public class ClassWithStrings
{
// Ctor args.
// Ignored.
[JsonIgnore]
public string AValue { get; }
[JsonIgnore]
public string EValue { get; }
[JsonIgnore]
public string IValue { get; }
[JsonIgnore]
public string MValue { get; }
[JsonIgnore]
public string QValue { get; }
// Populated.
public string CValue { get; }
public string GValue { get; }
public string KValue { get; }
public string OValue { get; }
public string SValue { get; }
// Properties.
// Ignored - no setter.
public string BValue { get; }
public string FValue { get; }
public string JValue { get; }
public string NValue { get; }
public string RValue { get; }
// Populated.
public string DValue { get; set; }
public string HValue { get; set; }
public string LValue { get; set; }
public string PValue { get; set; }
public string TValue { get; set; }
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }
public ClassWithStrings(
string aValue,
string cValue,
string eValue,
string gValue,
string iValue,
string kValue,
string mValue,
string oValue,
string qValue,
string sValue)
{
AValue = aValue;
CValue = cValue;
EValue = eValue;
GValue = gValue;
IValue = iValue;
KValue = kValue;
MValue = mValue;
OValue = oValue;
QValue = qValue;
SValue = sValue;
}
public void Verify(string expectedStr)
{
// Ctor args.
// Ignored
Assert.Null(AValue);
Assert.Null(EValue);
Assert.Null(IValue);
Assert.Null(MValue);
Assert.Null(QValue);
Assert.Equal(expectedStr, CValue);
Assert.Equal(expectedStr, GValue);
Assert.Equal(expectedStr, KValue);
Assert.Equal(expectedStr, OValue);
Assert.Equal(expectedStr, SValue);
// Getter only members - skipped.
Assert.Null(BValue);
Assert.Null(FValue);
Assert.Null(JValue);
Assert.Null(NValue);
Assert.Null(RValue);
// Members with setters
Assert.Equal(expectedStr, DValue);
Assert.Equal(expectedStr, HValue);
Assert.Equal(expectedStr, LValue);
Assert.Equal(expectedStr, PValue);
Assert.Equal(expectedStr, TValue);
Assert.Equal(10, ExtensionData.Count);
foreach (JsonElement value in ExtensionData.Values)
{
string keyPair = $@"""rand"":[""{expectedStr}""]";
Assert.Equal($@"{{{keyPair},{keyPair},{keyPair}}}", value.GetRawText());
}
}
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.ServiceModel.Syndication/tests/System.ServiceModel.Syndication.Tests.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetFrameworkMinimum)</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="BasicScenarioTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Rss20ItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Rss20FeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Atom10ItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Atom10FeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedTests.cs" />
<Compile Include="Utils\CompareHelper.cs" />
<Compile Include="Utils\ThrowingXmlReader.cs" />
<Compile Include="Utils\XmlDiff.cs" />
<Compile Include="Utils\XmlDiffDocument.cs" />
<Compile Include="Utils\XmlDiffOption.cs" />
<Compile Include="System\ServiceModel\Syndication\AtomPub10ServiceDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\AtomPub10CategoriesDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\CategoriesDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ServiceDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ServiceDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ReferencedCategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\InlineCategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\CategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationElementExtensionCollectionTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationElementExtensionTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationItemTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationCategoryTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\UrlSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\TextSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationPersonTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationLinkTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ResourceCollectionInfoTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationVersionsTests.cs" />
<Compile Include="System\ServiceModel\Syndication\WorkspaceTests.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
<Compile Include="$(MSBuildThisFileDirectory)netcoreapp\BasicScenarioTests.netcoreapp.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedTests.netcoreapp.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationTextInputTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlDateTimeDataTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlUriDataTests.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\**\*.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\atom_feeds.dat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\rss_feeds.dat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\System.ServiceModel.Syndication.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceModel" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetFrameworkMinimum)</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<Compile Include="BasicScenarioTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Rss20ItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Rss20FeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Atom10ItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\Atom10FeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationItemFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedTests.cs" />
<Compile Include="Utils\CompareHelper.cs" />
<Compile Include="Utils\ThrowingXmlReader.cs" />
<Compile Include="Utils\XmlDiff.cs" />
<Compile Include="Utils\XmlDiffDocument.cs" />
<Compile Include="Utils\XmlDiffOption.cs" />
<Compile Include="System\ServiceModel\Syndication\AtomPub10ServiceDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\AtomPub10CategoriesDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\CategoriesDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ServiceDocumentFormatterTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ServiceDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ReferencedCategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\InlineCategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\CategoriesDocumentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationElementExtensionCollectionTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationElementExtensionTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationItemTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationCategoryTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\UrlSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\TextSyndicationContentTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationPersonTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationLinkTests.cs" />
<Compile Include="System\ServiceModel\Syndication\ResourceCollectionInfoTests.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationVersionsTests.cs" />
<Compile Include="System\ServiceModel\Syndication\WorkspaceTests.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'">
<Compile Include="$(MSBuildThisFileDirectory)netcoreapp\BasicScenarioTests.netcoreapp.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationFeedTests.netcoreapp.cs" />
<Compile Include="System\ServiceModel\Syndication\SyndicationTextInputTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlDateTimeDataTests.cs" />
<Compile Include="System\ServiceModel\Syndication\XmlUriDataTests.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\**\*.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\atom_feeds.dat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="$(MSBuildThisFileDirectory)\TestFeeds\rss_feeds.dat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\System.ServiceModel.Syndication.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceModel" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/pal/src/include/pal/shm.hpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
include/pal/shm.hpp
Abstract:
C++ typesafe accessors for shared memory routines
--*/
#ifndef _SHM_HPP_
#define _SHM_HPP_
#include "shmemory.h"
//
// Some compilers (e.g., HPUX/IA64) warn about using NULL to initialize
// something of type SHMPTR, since SHMPTR is defined as DWORD_PTR, which
// isn't considered a pointer type...
//
#define SHMPTR_TO_TYPED_PTR(type, shmptr) reinterpret_cast<type*>(shmptr)
/* Set ptr to NULL if shmPtr == 0, else set ptr to SHMPTR_TO_TYPED_PTR(type, shmptr)
return FALSE if SHMPTR_TO_TYPED_PTR returns NULL ptr from non null shmptr,
TRUE otherwise */
#define SHMPTR_TO_TYPED_PTR_BOOL(type, ptr, shmptr) \
((shmptr != 0) ? ((ptr = SHMPTR_TO_TYPED_PTR(type, shmptr)) != NULL) : ((ptr = NULL) == NULL))
#endif // _SHM_HPP_
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*++
Module Name:
include/pal/shm.hpp
Abstract:
C++ typesafe accessors for shared memory routines
--*/
#ifndef _SHM_HPP_
#define _SHM_HPP_
#include "shmemory.h"
//
// Some compilers (e.g., HPUX/IA64) warn about using NULL to initialize
// something of type SHMPTR, since SHMPTR is defined as DWORD_PTR, which
// isn't considered a pointer type...
//
#define SHMPTR_TO_TYPED_PTR(type, shmptr) reinterpret_cast<type*>(shmptr)
/* Set ptr to NULL if shmPtr == 0, else set ptr to SHMPTR_TO_TYPED_PTR(type, shmptr)
return FALSE if SHMPTR_TO_TYPED_PTR returns NULL ptr from non null shmptr,
TRUE otherwise */
#define SHMPTR_TO_TYPED_PTR_BOOL(type, ptr, shmptr) \
((shmptr != 0) ? ((ptr = SHMPTR_TO_TYPED_PTR(type, shmptr)) != NULL) : ((ptr = NULL) == NULL))
#endif // _SHM_HPP_
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/mono/mono/tests/verifier/invalid_stojb_bad_token.il
|
.assembly extern mscorlib
{
.ver 2:0:0:0
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
}
.assembly 'ldobj_test'
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module ldobj.exe
.class Class extends [mscorlib]System.Object
{
.field public int32 valid
}
.class public Template`1<T>
extends [mscorlib]System.Object
{
}
.class sealed public StructTemplate`1<T>
extends [mscorlib]System.ValueType
{
.field public !0 t
}
.class sealed public StructTemplate2`1<T>
extends [mscorlib]System.ValueType
{
.field public !0 t
}
.class public auto ansi sealed MyStruct
extends [mscorlib]System.ValueType
{
.field public int32 foo
}
.class public auto ansi sealed MyStruct2
extends [mscorlib]System.ValueType
{
.field public int32 foo
}
.method public static int32 Main ()
{
.entrypoint
.maxstack 8
.locals init (int32 V_0, int32& V_1 , int32 V_2)
ldloca.s 2
stloc.1
ldloc.1
ldloc.0
.emitbyte 0x81
.emitbyte 0x01
.emitbyte 0x00
.emitbyte 0x00
.emitbyte 0x06
ldc.i4.0
ret
}
|
.assembly extern mscorlib
{
.ver 2:0:0:0
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
}
.assembly 'ldobj_test'
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module ldobj.exe
.class Class extends [mscorlib]System.Object
{
.field public int32 valid
}
.class public Template`1<T>
extends [mscorlib]System.Object
{
}
.class sealed public StructTemplate`1<T>
extends [mscorlib]System.ValueType
{
.field public !0 t
}
.class sealed public StructTemplate2`1<T>
extends [mscorlib]System.ValueType
{
.field public !0 t
}
.class public auto ansi sealed MyStruct
extends [mscorlib]System.ValueType
{
.field public int32 foo
}
.class public auto ansi sealed MyStruct2
extends [mscorlib]System.ValueType
{
.field public int32 foo
}
.method public static int32 Main ()
{
.entrypoint
.maxstack 8
.locals init (int32 V_0, int32& V_1 , int32 V_2)
ldloca.s 2
stloc.1
ldloc.1
ldloc.0
.emitbyte 0x81
.emitbyte 0x01
.emitbyte 0x00
.emitbyte 0x00
.emitbyte 0x06
ldc.i4.0
ret
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.IlGen
{
/// <summary>
/// Until run-time, the exact xml state cannot always be determined. However, the construction analyzer
/// keeps track of the set of possible xml states at each node in order to reduce run-time state management.
/// </summary>
internal enum PossibleXmlStates
{
None = 0,
WithinSequence,
EnumAttrs,
WithinContent,
WithinAttr,
WithinComment,
WithinPI,
Any,
};
/// <summary>
/// 1. Some expressions are lazily materialized by creating an iterator over the results (ex. LiteralString, Content).
/// 2. Some expressions are incrementally constructed by a Writer (ex. ElementCtor, XsltCopy).
/// 3. Some expressions can be iterated or written (ex. List).
/// </summary>
internal enum XmlILConstructMethod
{
Iterator, // Construct iterator over expression's results
Writer, // Construct expression through calls to Writer
WriterThenIterator, // Construct expression through calls to caching Writer; then construct iterator over cached results
IteratorThenWriter, // Iterate over expression's results and send each item to Writer
};
/// <summary>
/// Every node is annotated with information about how it will be constructed by ILGen.
/// </summary>
internal sealed class XmlILConstructInfo : IQilAnnotation
{
private readonly QilNodeType _nodeType;
private PossibleXmlStates _xstatesInitial, _xstatesFinal, _xstatesBeginLoop, _xstatesEndLoop;
private bool _isNmspInScope, _mightHaveNmsp, _mightHaveAttrs, _mightHaveDupAttrs, _mightHaveNmspAfterAttrs;
private XmlILConstructMethod _constrMeth;
private XmlILConstructInfo? _parentInfo;
private ArrayList? _callersInfo;
private bool _isReadOnly;
private static volatile XmlILConstructInfo? s_default;
/// <summary>
/// Get ConstructInfo annotation for the specified node. Lazily create if necessary.
/// </summary>
public static XmlILConstructInfo Read(QilNode nd)
{
XmlILAnnotation? ann = nd.Annotation as XmlILAnnotation;
XmlILConstructInfo? constrInfo = (ann != null) ? ann.ConstructInfo : null;
if (constrInfo == null)
{
if (s_default == null)
{
constrInfo = new XmlILConstructInfo(QilNodeType.Unknown);
constrInfo._isReadOnly = true;
s_default = constrInfo;
}
else
{
constrInfo = s_default;
}
}
return constrInfo;
}
/// <summary>
/// Create and initialize XmlILConstructInfo annotation for the specified node.
/// </summary>
public static XmlILConstructInfo Write(QilNode nd)
{
XmlILAnnotation ann = XmlILAnnotation.Write(nd);
XmlILConstructInfo? constrInfo = ann.ConstructInfo;
if (constrInfo == null || constrInfo._isReadOnly)
{
constrInfo = new XmlILConstructInfo(nd.NodeType);
ann.ConstructInfo = constrInfo;
}
return constrInfo;
}
/// <summary>
/// Default to worst possible construction information.
/// </summary>
private XmlILConstructInfo(QilNodeType nodeType)
{
_nodeType = nodeType;
_xstatesInitial = _xstatesFinal = PossibleXmlStates.Any;
_xstatesBeginLoop = _xstatesEndLoop = PossibleXmlStates.None;
_isNmspInScope = false;
_mightHaveNmsp = true;
_mightHaveAttrs = true;
_mightHaveDupAttrs = true;
_mightHaveNmspAfterAttrs = true;
_constrMeth = XmlILConstructMethod.Iterator;
_parentInfo = null;
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression begins.
/// </summary>
public PossibleXmlStates InitialStates
{
get { return _xstatesInitial; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesInitial = value;
}
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression ends.
/// </summary>
public PossibleXmlStates FinalStates
{
get { return _xstatesFinal; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesFinal = value;
}
}
/// <summary>
/// Xml states that are possible as looping begins. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates BeginLoopStates
{
//get { return this.xstatesBeginLoop; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesBeginLoop = value;
}
}
/// <summary>
/// Xml states that are possible as looping ends. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates EndLoopStates
{
//get { return this.xstatesEndLoop; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesEndLoop = value;
}
}
/// <summary>
/// Return the method that will be used to construct the annotated node.
/// </summary>
public XmlILConstructMethod ConstructMethod
{
get { return _constrMeth; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_constrMeth = value;
}
}
/// <summary>
/// Returns true if construction method is Writer or WriterThenIterator.
/// </summary>
public bool PushToWriterFirst
{
get { return _constrMeth == XmlILConstructMethod.Writer || _constrMeth == XmlILConstructMethod.WriterThenIterator; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Iterator:
_constrMeth = XmlILConstructMethod.WriterThenIterator;
break;
case XmlILConstructMethod.IteratorThenWriter:
_constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is Writer or IteratorThenWriter.
/// </summary>
public bool PushToWriterLast
{
get { return _constrMeth == XmlILConstructMethod.Writer || _constrMeth == XmlILConstructMethod.IteratorThenWriter; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Iterator:
_constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
_constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is IteratorThenWriter or Iterator.
/// </summary>
public bool PullFromIteratorFirst
{
get { return _constrMeth == XmlILConstructMethod.IteratorThenWriter || _constrMeth == XmlILConstructMethod.Iterator; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Writer:
_constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
_constrMeth = XmlILConstructMethod.Iterator;
break;
}
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of another constructor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo? ParentInfo
{
//get { return this.parentInfo; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_parentInfo = value;
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of an ElementCtor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo? ParentElementInfo
{
get
{
if (_parentInfo != null && _parentInfo._nodeType == QilNodeType.ElementCtor)
return _parentInfo;
return null;
}
}
/// <summary>
/// This annotation is only applicable to NamespaceDecl nodes and to ElementCtor and AttributeCtor nodes with
/// literal names. If the namespace is already guaranteed to be constructed, then this property will be true.
/// </summary>
public bool IsNamespaceInScope
{
get { return _isNmspInScope; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_isNmspInScope = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have local namespaces
/// added to it at runtime, then this property will be true.
/// </summary>
public bool MightHaveNamespaces
{
get { return _mightHaveNmsp; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveNmsp = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have namespaces added to it after
/// attributes have already been added, then this property will be true.
/// </summary>
public bool MightHaveNamespacesAfterAttributes
{
get { return _mightHaveNmspAfterAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveNmspAfterAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have attributes added to it at
/// runtime, then this property will be true.
/// </summary>
public bool MightHaveAttributes
{
get { return _mightHaveAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have multiple attributes added to
/// it with the same name, then this property will be true.
/// </summary>
public bool MightHaveDuplicateAttributes
{
get { return _mightHaveDupAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveDupAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annotations
/// for all QilInvoke nodes which call the annotated function.
/// </summary>
public ArrayList CallersInfo
{
get
{
if (_callersInfo == null)
_callersInfo = new ArrayList();
return _callersInfo;
}
}
/// <summary>
/// Return name of this annotation.
/// </summary>
public string Name
{
get { return "ConstructInfo"; }
}
/// <summary>
/// Return string representation of this annotation.
/// </summary>
public override string ToString()
{
string s = "";
if (_constrMeth != XmlILConstructMethod.Iterator)
{
s += _constrMeth.ToString();
s += $", {_xstatesInitial}";
if (_xstatesBeginLoop != PossibleXmlStates.None)
{
s += $" => {_xstatesBeginLoop} => {_xstatesEndLoop}";
}
s += $" => {_xstatesFinal}";
if (!MightHaveAttributes)
s += ", NoAttrs";
if (!MightHaveDuplicateAttributes)
s += ", NoDupAttrs";
if (!MightHaveNamespaces)
s += ", NoNmsp";
if (!MightHaveNamespacesAfterAttributes)
s += ", NoNmspAfterAttrs";
}
return s;
}
}
/// <summary>
/// Scans the content of an constructor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal class XmlILStateAnalyzer
{
protected XmlILConstructInfo? parentInfo;
protected QilFactory fac;
protected PossibleXmlStates xstates;
protected bool withinElem;
/// <summary>
/// Constructor.
/// </summary>
public XmlILStateAnalyzer(QilFactory fac)
{
this.fac = fac;
}
/// <summary>
/// Perform analysis on the specified constructor and its content. Return the ndContent that was passed in,
/// or a replacement.
/// </summary>
public virtual QilNode? Analyze(QilNode? ndConstr, QilNode? ndContent)
{
if (ndConstr == null)
{
// Root expression is analyzed
this.parentInfo = null;
this.xstates = PossibleXmlStates.WithinSequence;
this.withinElem = false;
Debug.Assert(ndContent != null);
ndContent = AnalyzeContent(ndContent);
}
else
{
this.parentInfo = XmlILConstructInfo.Write(ndConstr);
if (ndConstr.NodeType == QilNodeType.Function)
{
// Results of function should be pushed to writer
this.parentInfo.ConstructMethod = XmlILConstructMethod.Writer;
// Start with PossibleXmlStates.None and then add additional possible starting states
PossibleXmlStates xstates = PossibleXmlStates.None;
foreach (XmlILConstructInfo infoCaller in this.parentInfo.CallersInfo)
{
if (xstates == PossibleXmlStates.None)
{
xstates = infoCaller.InitialStates;
}
else if (xstates != infoCaller.InitialStates)
{
xstates = PossibleXmlStates.Any;
}
// Function's results are pushed to Writer, so make sure that Invoke nodes' construct methods match
infoCaller.PushToWriterFirst = true;
}
this.parentInfo.InitialStates = xstates;
}
else
{
// Build a standalone tree, with this constructor as its root
if (ndConstr.NodeType != QilNodeType.Choice)
this.parentInfo.InitialStates = this.parentInfo.FinalStates = PossibleXmlStates.WithinSequence;
// Don't stream Rtf; fully cache the Rtf and copy it into any containing tree in order to simplify XmlILVisitor.VisitRtfCtor
if (ndConstr.NodeType != QilNodeType.RtfCtor)
this.parentInfo.ConstructMethod = XmlILConstructMethod.WriterThenIterator;
}
// Set withinElem = true if analyzing element content
this.withinElem = (ndConstr.NodeType == QilNodeType.ElementCtor);
switch (ndConstr.NodeType)
{
case QilNodeType.DocumentCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.ElementCtor: this.xstates = PossibleXmlStates.EnumAttrs; break;
case QilNodeType.AttributeCtor: this.xstates = PossibleXmlStates.WithinAttr; break;
case QilNodeType.NamespaceDecl: Debug.Assert(ndContent == null); break;
case QilNodeType.TextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.RawTextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.CommentCtor: this.xstates = PossibleXmlStates.WithinComment; break;
case QilNodeType.PICtor: this.xstates = PossibleXmlStates.WithinPI; break;
case QilNodeType.XsltCopy: this.xstates = PossibleXmlStates.Any; break;
case QilNodeType.XsltCopyOf: Debug.Assert(ndContent == null); break;
case QilNodeType.Function: this.xstates = this.parentInfo.InitialStates; break;
case QilNodeType.RtfCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.Choice: this.xstates = PossibleXmlStates.Any; break;
default: Debug.Fail($"{ndConstr.NodeType} is not handled by XmlILStateAnalyzer."); break;
}
if (ndContent != null)
ndContent = AnalyzeContent(ndContent);
if (ndConstr.NodeType == QilNodeType.Choice)
AnalyzeChoice((ndConstr as QilChoice)!, this.parentInfo);
// Since Function will never be another node's content, set its final states here
if (ndConstr.NodeType == QilNodeType.Function)
this.parentInfo.FinalStates = this.xstates;
}
return ndContent;
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
protected virtual QilNode AnalyzeContent(QilNode nd)
{
XmlILConstructInfo info;
QilNode ndChild;
// Handle special node-types that are replaced
switch (nd.NodeType)
{
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Iterator references are shared and cannot be annotated directly with ConstructInfo,
// so wrap them with Nop node.
nd = this.fac.Nop(nd);
break;
}
// Get node's ConstructInfo annotation
info = XmlILConstructInfo.Write(nd);
// Set node's guaranteed parent constructor
info.ParentInfo = this.parentInfo;
// Construct all content using the Writer
info.PushToWriterLast = true;
// Set states that are possible before expression is constructed
info.InitialStates = this.xstates;
switch (nd.NodeType)
{
case QilNodeType.Loop: AnalyzeLoop((nd as QilLoop)!, info); break;
case QilNodeType.Sequence: AnalyzeSequence((nd as QilList)!, info); break;
case QilNodeType.Conditional: AnalyzeConditional((nd as QilTernary)!, info); break;
case QilNodeType.Choice: AnalyzeChoice((nd as QilChoice)!, info); break;
case QilNodeType.Error:
case QilNodeType.Warning:
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
break;
case QilNodeType.Nop:
ndChild = (nd as QilUnary)!.Child;
switch (ndChild.NodeType)
{
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Copy iterator items as content
AnalyzeCopy(nd, info);
break;
default:
// Ensure that construct method is Writer and recursively analyze content
info.ConstructMethod = XmlILConstructMethod.Writer;
AnalyzeContent(ndChild);
break;
}
break;
default:
AnalyzeCopy(nd, info);
break;
}
// Set states that are possible after expression is constructed
info.FinalStates = this.xstates;
return nd;
}
/// <summary>
/// Analyze loop.
/// </summary>
protected virtual void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info)
{
XmlQueryType typ = ndLoop.XmlType!;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
if (!typ.IsSingleton)
StartLoop(typ, info);
// Body constructs content
ndLoop.Body = AnalyzeContent(ndLoop.Body);
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Analyze list.
/// </summary>
protected virtual void AnalyzeSequence(QilList ndSeq, XmlILConstructInfo info)
{
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Analyze each item in the list
for (int idx = 0; idx < ndSeq.Count; idx++)
ndSeq[idx] = AnalyzeContent(ndSeq[idx]);
}
/// <summary>
/// Analyze conditional.
/// </summary>
protected virtual void AnalyzeConditional(QilTernary ndCond, XmlILConstructInfo info)
{
PossibleXmlStates xstatesTrue;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Visit true branch; save resulting states
ndCond.Center = AnalyzeContent(ndCond.Center);
xstatesTrue = this.xstates;
// Restore starting states and visit false branch
this.xstates = info.InitialStates;
ndCond.Right = AnalyzeContent(ndCond.Right);
// Conditional ending states consist of combination of true and false branch states
if (xstatesTrue != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Analyze choice.
/// </summary>
protected virtual void AnalyzeChoice(QilChoice ndChoice, XmlILConstructInfo info)
{
PossibleXmlStates xstatesChoice;
int idx;
// Visit default branch; save resulting states
idx = ndChoice.Branches.Count - 1;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
xstatesChoice = this.xstates;
// Visit all other branches
while (--idx >= 0)
{
// Restore starting states and visit the next branch
this.xstates = info.InitialStates;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
// Choice ending states consist of combination of all branch states
if (xstatesChoice != this.xstates)
xstatesChoice = PossibleXmlStates.Any;
}
this.xstates = xstatesChoice;
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected virtual void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info)
{
XmlQueryType typ = ndCopy.XmlType!;
// Copying item(s) to output involves looping if there is not exactly one item in the sequence
if (!typ.IsSingleton)
StartLoop(typ, info);
// Determine state transitions that may take place
if (MaybeContent(typ))
{
if (MaybeAttrNmsp(typ))
{
// Node might be Attr/Nmsp or non-Attr/Nmsp, so transition from EnumAttrs to WithinContent *may* occur
if (this.xstates == PossibleXmlStates.EnumAttrs)
this.xstates = PossibleXmlStates.Any;
}
else
{
// Node is guaranteed not to be Attr/Nmsp, so transition to WithinContent will occur if starting
// state is EnumAttrs or if constructing within an element (guaranteed to be in EnumAttrs or WithinContent state)
if (this.xstates == PossibleXmlStates.EnumAttrs || this.withinElem)
this.xstates = PossibleXmlStates.WithinContent;
}
}
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Calculate starting xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void StartLoop(XmlQueryType typ, XmlILConstructInfo info)
{
Debug.Assert(!typ.IsSingleton);
// This is tricky, because the looping introduces a feedback loop:
// 1. Because loops may be executed many times, the beginning set of states must include the ending set of states.
// 2. Because loops may be executed 0 times, the final set of states after all looping is complete must include
// the initial set of states.
//
// +-- states-initial
// | |
// | states-begin-loop <--+
// | | |
// | +--------------+ |
// | | Construction | |
// | +--------------+ |
// | | |
// | states-end-loop ----+
// | |
// +--> states-final
// Save starting loop states
info.BeginLoopStates = this.xstates;
if (typ.MaybeMany)
{
// If transition might occur from EnumAttrs to WithinContent, then states-end might be WithinContent, which
// means states-begin needs to also include WithinContent.
if (this.xstates == PossibleXmlStates.EnumAttrs && MaybeContent(typ))
info.BeginLoopStates = this.xstates = PossibleXmlStates.Any;
}
}
/// <summary>
/// Calculate ending xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void EndLoop(XmlQueryType typ, XmlILConstructInfo info)
{
Debug.Assert(!typ.IsSingleton);
// Save ending loop states
info.EndLoopStates = this.xstates;
// If it's possible to loop zero times, then states-final needs to include states-initial
if (typ.MaybeEmpty && info.InitialStates != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Return true if an instance of the specified type might be an attribute or a namespace node.
/// </summary>
private bool MaybeAttrNmsp(XmlQueryType typ)
{
return (typ.NodeKinds & (XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
/// <summary>
/// Return true if an instance of the specified type might be a non-empty content type (attr/nsmp don't count).
/// </summary>
private bool MaybeContent(XmlQueryType typ)
{
return !typ.IsNode || (typ.NodeKinds & ~(XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
}
/// <summary>
/// Scans the content of an ElementCtor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal sealed class XmlILElementAnalyzer : XmlILStateAnalyzer
{
private readonly NameTable _attrNames = new NameTable();
private readonly ArrayList _dupAttrs = new ArrayList();
/// <summary>
/// Constructor.
/// </summary>
public XmlILElementAnalyzer(QilFactory fac) : base(fac)
{
}
/// <summary>
/// Analyze the content argument of the ElementCtor. Try to eliminate as many runtime checks as possible,
/// both for the ElementCtor and for content constructors.
/// </summary>
public override QilNode? Analyze(QilNode? ndElem, QilNode? ndContent)
{
Debug.Assert(ndElem!.NodeType == QilNodeType.ElementCtor);
this.parentInfo = XmlILConstructInfo.Write(ndElem);
// Start by assuming that these properties are false (they default to true, but analyzer might be able to
// prove they are really false).
this.parentInfo.MightHaveNamespacesAfterAttributes = false;
this.parentInfo.MightHaveAttributes = false;
this.parentInfo.MightHaveDuplicateAttributes = false;
// The element's namespace might need to be declared
this.parentInfo.MightHaveNamespaces = !this.parentInfo.IsNamespaceInScope;
// Clear list of duplicate attributes
_dupAttrs.Clear();
return base.Analyze(ndElem, ndContent);
}
/// <summary>
/// Analyze loop.
/// </summary>
protected override void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info)
{
// Constructing attributes/namespaces in a loop can cause duplicates, namespaces after attributes, etc.
if (ndLoop.XmlType!.MaybeMany)
CheckAttributeNamespaceConstruct(ndLoop.XmlType);
base.AnalyzeLoop(ndLoop, info);
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected override void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info)
{
if (ndCopy.NodeType == QilNodeType.AttributeCtor)
{
QilBinary? binaryNode = ndCopy as QilBinary;
Debug.Assert(binaryNode != null);
AnalyzeAttributeCtor(binaryNode, info);
}
else
{
CheckAttributeNamespaceConstruct(ndCopy.XmlType!);
}
base.AnalyzeCopy(ndCopy, info);
}
/// <summary>
/// Analyze attribute constructor.
/// </summary>
private void AnalyzeAttributeCtor(QilBinary ndAttr, XmlILConstructInfo info)
{
if (ndAttr.Left.NodeType == QilNodeType.LiteralQName)
{
QilName? ndName = ndAttr.Left as QilName;
Debug.Assert(ndName != null);
XmlQualifiedName qname;
int idx;
// This attribute might be constructed on the parent element
this.parentInfo!.MightHaveAttributes = true;
// Check to see whether this attribute is a duplicate of a previous attribute
if (!this.parentInfo.MightHaveDuplicateAttributes)
{
qname = new XmlQualifiedName(_attrNames.Add(ndName.LocalName), _attrNames.Add(ndName.NamespaceUri));
for (idx = 0; idx < _dupAttrs.Count; idx++)
{
XmlQualifiedName qnameDup = (XmlQualifiedName)_dupAttrs[idx]!;
if ((object)qnameDup.Name == (object)qname.Name && (object)qnameDup.Namespace == (object)qname.Namespace)
{
// A duplicate attribute has been encountered
this.parentInfo.MightHaveDuplicateAttributes = true;
}
}
if (idx >= _dupAttrs.Count)
{
// This is not a duplicate attribute, so add it to the set
_dupAttrs.Add(qname);
}
}
// The attribute's namespace might need to be declared
if (!info.IsNamespaceInScope)
this.parentInfo.MightHaveNamespaces = true;
}
else
{
// Attribute prefix and namespace are not known at compile-time
CheckAttributeNamespaceConstruct(ndAttr.XmlType!);
}
}
/// <summary>
/// If type might contain attributes or namespaces, set appropriate parent element flags.
/// </summary>
private void CheckAttributeNamespaceConstruct(XmlQueryType typ)
{
// If content might contain attributes,
if ((typ.NodeKinds & XmlNodeKindFlags.Attribute) != XmlNodeKindFlags.None)
{
// Mark element as possibly having attributes and duplicate attributes (since we don't know the names)
this.parentInfo!.MightHaveAttributes = true;
this.parentInfo.MightHaveDuplicateAttributes = true;
// Attribute namespaces might be declared
this.parentInfo.MightHaveNamespaces = true;
}
// If content might contain namespaces,
if ((typ.NodeKinds & XmlNodeKindFlags.Namespace) != XmlNodeKindFlags.None)
{
// Then element might have namespaces,
this.parentInfo!.MightHaveNamespaces = true;
// If attributes might already have been constructed,
if (this.parentInfo.MightHaveAttributes)
{
// Then attributes might precede namespace declarations
this.parentInfo.MightHaveNamespacesAfterAttributes = true;
}
}
}
}
/// <summary>
/// Scans constructed content, looking for redundant namespace declarations. If any are found, then they are marked
/// and removed later.
/// </summary>
internal sealed class XmlILNamespaceAnalyzer
{
private readonly XmlNamespaceManager _nsmgr = new XmlNamespaceManager(new NameTable());
private bool _addInScopeNmsp;
private int _cntNmsp;
/// <summary>
/// Perform scan.
/// </summary>
public void Analyze(QilNode nd, bool defaultNmspInScope)
{
_addInScopeNmsp = false;
_cntNmsp = 0;
// If xmlns="" is in-scope, push it onto the namespace stack
if (defaultNmspInScope)
{
_nsmgr.PushScope();
_nsmgr.AddNamespace(string.Empty, string.Empty);
_cntNmsp++;
}
AnalyzeContent(nd);
if (defaultNmspInScope)
_nsmgr.PopScope();
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
private void AnalyzeContent(QilNode nd)
{
int cntNmspSave;
switch (nd.NodeType)
{
case QilNodeType.Loop:
_addInScopeNmsp = false;
AnalyzeContent((nd as QilLoop)!.Body);
break;
case QilNodeType.Sequence:
foreach (QilNode ndContent in nd)
AnalyzeContent(ndContent);
break;
case QilNodeType.Conditional:
_addInScopeNmsp = false;
AnalyzeContent((nd as QilTernary)!.Center);
AnalyzeContent((nd as QilTernary)!.Right);
break;
case QilNodeType.Choice:
_addInScopeNmsp = false;
QilList ndBranches = (nd as QilChoice)!.Branches;
for (int idx = 0; idx < ndBranches.Count; idx++)
AnalyzeContent(ndBranches[idx]);
break;
case QilNodeType.ElementCtor:
// Start a new namespace scope
_addInScopeNmsp = true;
_nsmgr.PushScope();
cntNmspSave = _cntNmsp;
if (CheckNamespaceInScope((nd as QilBinary)!))
AnalyzeContent((nd as QilBinary)!.Right);
_nsmgr.PopScope();
_addInScopeNmsp = false;
_cntNmsp = cntNmspSave;
break;
case QilNodeType.AttributeCtor:
_addInScopeNmsp = false;
CheckNamespaceInScope((nd as QilBinary)!);
break;
case QilNodeType.NamespaceDecl:
CheckNamespaceInScope((nd as QilBinary)!);
break;
case QilNodeType.Nop:
AnalyzeContent((nd as QilUnary)!.Child);
break;
default:
_addInScopeNmsp = false;
break;
}
}
/// <summary>
/// Determine whether an ElementCtor, AttributeCtor, or NamespaceDecl's namespace is already declared. If it is,
/// set the IsNamespaceInScope property to True. Otherwise, add the namespace to the set of in-scope namespaces if
/// addInScopeNmsp is True. Return false if the name is computed or is invalid.
/// </summary>
private bool CheckNamespaceInScope(QilBinary nd)
{
QilName? ndName;
string prefix, ns;
string? prefixExisting, nsExisting;
XPathNodeType nodeType;
switch (nd.NodeType)
{
case QilNodeType.ElementCtor:
case QilNodeType.AttributeCtor:
ndName = nd.Left as QilName;
if (ndName != null)
{
prefix = ndName.Prefix;
ns = ndName.NamespaceUri;
nodeType = (nd.NodeType == QilNodeType.ElementCtor) ? XPathNodeType.Element : XPathNodeType.Attribute;
break;
}
// Not a literal name, so return false
return false;
default:
Debug.Assert(nd.NodeType == QilNodeType.NamespaceDecl);
prefix = (string)(QilLiteral)nd.Left;
ns = (string)(QilLiteral)nd.Right;
nodeType = XPathNodeType.Namespace;
break;
}
// Attribute with null namespace and xmlns:xml are always in-scope
if (nd.NodeType == QilNodeType.AttributeCtor && ns.Length == 0 ||
prefix == "xml" && ns == XmlReservedNs.NsXml)
{
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
return true;
}
// Don't process names that are invalid
if (!ValidateNames.ValidateName(prefix, string.Empty, ns, nodeType, ValidateNames.Flags.CheckPrefixMapping))
return false;
// Atomize names
prefix = _nsmgr.NameTable!.Add(prefix);
ns = _nsmgr.NameTable.Add(ns);
// Determine whether namespace is already in-scope
for (int iNmsp = 0; iNmsp < _cntNmsp; iNmsp++)
{
_nsmgr.GetNamespaceDeclaration(iNmsp, out prefixExisting, out nsExisting);
// If prefix is already declared,
if ((object)prefix == (object?)prefixExisting)
{
// Then if the namespace is the same, this namespace is redundant
if ((object)ns == (object?)nsExisting)
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
// Else quit searching, because any further matching prefixes will be hidden (not in-scope)
Debug.Assert(nd.NodeType != QilNodeType.NamespaceDecl || !_nsmgr.HasNamespace(prefix) || _nsmgr.LookupNamespace(prefix) == ns,
"Compilers must ensure that namespace declarations do not conflict with the namespace used by the element constructor.");
break;
}
}
// If not in-scope, then add if it's allowed
if (_addInScopeNmsp)
{
_nsmgr.AddNamespace(prefix, ns);
_cntNmsp++;
}
return true;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Xsl.Qil;
namespace System.Xml.Xsl.IlGen
{
/// <summary>
/// Until run-time, the exact xml state cannot always be determined. However, the construction analyzer
/// keeps track of the set of possible xml states at each node in order to reduce run-time state management.
/// </summary>
internal enum PossibleXmlStates
{
None = 0,
WithinSequence,
EnumAttrs,
WithinContent,
WithinAttr,
WithinComment,
WithinPI,
Any,
};
/// <summary>
/// 1. Some expressions are lazily materialized by creating an iterator over the results (ex. LiteralString, Content).
/// 2. Some expressions are incrementally constructed by a Writer (ex. ElementCtor, XsltCopy).
/// 3. Some expressions can be iterated or written (ex. List).
/// </summary>
internal enum XmlILConstructMethod
{
Iterator, // Construct iterator over expression's results
Writer, // Construct expression through calls to Writer
WriterThenIterator, // Construct expression through calls to caching Writer; then construct iterator over cached results
IteratorThenWriter, // Iterate over expression's results and send each item to Writer
};
/// <summary>
/// Every node is annotated with information about how it will be constructed by ILGen.
/// </summary>
internal sealed class XmlILConstructInfo : IQilAnnotation
{
private readonly QilNodeType _nodeType;
private PossibleXmlStates _xstatesInitial, _xstatesFinal, _xstatesBeginLoop, _xstatesEndLoop;
private bool _isNmspInScope, _mightHaveNmsp, _mightHaveAttrs, _mightHaveDupAttrs, _mightHaveNmspAfterAttrs;
private XmlILConstructMethod _constrMeth;
private XmlILConstructInfo? _parentInfo;
private ArrayList? _callersInfo;
private bool _isReadOnly;
private static volatile XmlILConstructInfo? s_default;
/// <summary>
/// Get ConstructInfo annotation for the specified node. Lazily create if necessary.
/// </summary>
public static XmlILConstructInfo Read(QilNode nd)
{
XmlILAnnotation? ann = nd.Annotation as XmlILAnnotation;
XmlILConstructInfo? constrInfo = (ann != null) ? ann.ConstructInfo : null;
if (constrInfo == null)
{
if (s_default == null)
{
constrInfo = new XmlILConstructInfo(QilNodeType.Unknown);
constrInfo._isReadOnly = true;
s_default = constrInfo;
}
else
{
constrInfo = s_default;
}
}
return constrInfo;
}
/// <summary>
/// Create and initialize XmlILConstructInfo annotation for the specified node.
/// </summary>
public static XmlILConstructInfo Write(QilNode nd)
{
XmlILAnnotation ann = XmlILAnnotation.Write(nd);
XmlILConstructInfo? constrInfo = ann.ConstructInfo;
if (constrInfo == null || constrInfo._isReadOnly)
{
constrInfo = new XmlILConstructInfo(nd.NodeType);
ann.ConstructInfo = constrInfo;
}
return constrInfo;
}
/// <summary>
/// Default to worst possible construction information.
/// </summary>
private XmlILConstructInfo(QilNodeType nodeType)
{
_nodeType = nodeType;
_xstatesInitial = _xstatesFinal = PossibleXmlStates.Any;
_xstatesBeginLoop = _xstatesEndLoop = PossibleXmlStates.None;
_isNmspInScope = false;
_mightHaveNmsp = true;
_mightHaveAttrs = true;
_mightHaveDupAttrs = true;
_mightHaveNmspAfterAttrs = true;
_constrMeth = XmlILConstructMethod.Iterator;
_parentInfo = null;
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression begins.
/// </summary>
public PossibleXmlStates InitialStates
{
get { return _xstatesInitial; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesInitial = value;
}
}
/// <summary>
/// Xml states that are possible as construction of the annotated expression ends.
/// </summary>
public PossibleXmlStates FinalStates
{
get { return _xstatesFinal; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesFinal = value;
}
}
/// <summary>
/// Xml states that are possible as looping begins. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates BeginLoopStates
{
//get { return this.xstatesBeginLoop; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesBeginLoop = value;
}
}
/// <summary>
/// Xml states that are possible as looping ends. This is None if the annotated expression does not loop.
/// </summary>
public PossibleXmlStates EndLoopStates
{
//get { return this.xstatesEndLoop; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_xstatesEndLoop = value;
}
}
/// <summary>
/// Return the method that will be used to construct the annotated node.
/// </summary>
public XmlILConstructMethod ConstructMethod
{
get { return _constrMeth; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_constrMeth = value;
}
}
/// <summary>
/// Returns true if construction method is Writer or WriterThenIterator.
/// </summary>
public bool PushToWriterFirst
{
get { return _constrMeth == XmlILConstructMethod.Writer || _constrMeth == XmlILConstructMethod.WriterThenIterator; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Iterator:
_constrMeth = XmlILConstructMethod.WriterThenIterator;
break;
case XmlILConstructMethod.IteratorThenWriter:
_constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is Writer or IteratorThenWriter.
/// </summary>
public bool PushToWriterLast
{
get { return _constrMeth == XmlILConstructMethod.Writer || _constrMeth == XmlILConstructMethod.IteratorThenWriter; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Iterator:
_constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
_constrMeth = XmlILConstructMethod.Writer;
break;
}
}
}
/// <summary>
/// Returns true if construction method is IteratorThenWriter or Iterator.
/// </summary>
public bool PullFromIteratorFirst
{
get { return _constrMeth == XmlILConstructMethod.IteratorThenWriter || _constrMeth == XmlILConstructMethod.Iterator; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
Debug.Assert(value);
switch (_constrMeth)
{
case XmlILConstructMethod.Writer:
_constrMeth = XmlILConstructMethod.IteratorThenWriter;
break;
case XmlILConstructMethod.WriterThenIterator:
_constrMeth = XmlILConstructMethod.Iterator;
break;
}
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of another constructor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo? ParentInfo
{
//get { return this.parentInfo; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_parentInfo = value;
}
}
/// <summary>
/// If the annotated expression will be constructed as the content of an ElementCtor, and this can be
/// guaranteed at compile-time, then this property will be the non-null XmlILConstructInfo of that constructor.
/// </summary>
public XmlILConstructInfo? ParentElementInfo
{
get
{
if (_parentInfo != null && _parentInfo._nodeType == QilNodeType.ElementCtor)
return _parentInfo;
return null;
}
}
/// <summary>
/// This annotation is only applicable to NamespaceDecl nodes and to ElementCtor and AttributeCtor nodes with
/// literal names. If the namespace is already guaranteed to be constructed, then this property will be true.
/// </summary>
public bool IsNamespaceInScope
{
get { return _isNmspInScope; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_isNmspInScope = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have local namespaces
/// added to it at runtime, then this property will be true.
/// </summary>
public bool MightHaveNamespaces
{
get { return _mightHaveNmsp; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveNmsp = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have namespaces added to it after
/// attributes have already been added, then this property will be true.
/// </summary>
public bool MightHaveNamespacesAfterAttributes
{
get { return _mightHaveNmspAfterAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveNmspAfterAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have attributes added to it at
/// runtime, then this property will be true.
/// </summary>
public bool MightHaveAttributes
{
get { return _mightHaveAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to ElementCtor nodes. If the element might have multiple attributes added to
/// it with the same name, then this property will be true.
/// </summary>
public bool MightHaveDuplicateAttributes
{
get { return _mightHaveDupAttrs; }
set
{
Debug.Assert(!_isReadOnly, "This XmlILConstructInfo instance is read-only.");
_mightHaveDupAttrs = value;
}
}
/// <summary>
/// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annotations
/// for all QilInvoke nodes which call the annotated function.
/// </summary>
public ArrayList CallersInfo
{
get
{
if (_callersInfo == null)
_callersInfo = new ArrayList();
return _callersInfo;
}
}
/// <summary>
/// Return name of this annotation.
/// </summary>
public string Name
{
get { return "ConstructInfo"; }
}
/// <summary>
/// Return string representation of this annotation.
/// </summary>
public override string ToString()
{
string s = "";
if (_constrMeth != XmlILConstructMethod.Iterator)
{
s += _constrMeth.ToString();
s += $", {_xstatesInitial}";
if (_xstatesBeginLoop != PossibleXmlStates.None)
{
s += $" => {_xstatesBeginLoop} => {_xstatesEndLoop}";
}
s += $" => {_xstatesFinal}";
if (!MightHaveAttributes)
s += ", NoAttrs";
if (!MightHaveDuplicateAttributes)
s += ", NoDupAttrs";
if (!MightHaveNamespaces)
s += ", NoNmsp";
if (!MightHaveNamespacesAfterAttributes)
s += ", NoNmspAfterAttrs";
}
return s;
}
}
/// <summary>
/// Scans the content of an constructor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal class XmlILStateAnalyzer
{
protected XmlILConstructInfo? parentInfo;
protected QilFactory fac;
protected PossibleXmlStates xstates;
protected bool withinElem;
/// <summary>
/// Constructor.
/// </summary>
public XmlILStateAnalyzer(QilFactory fac)
{
this.fac = fac;
}
/// <summary>
/// Perform analysis on the specified constructor and its content. Return the ndContent that was passed in,
/// or a replacement.
/// </summary>
public virtual QilNode? Analyze(QilNode? ndConstr, QilNode? ndContent)
{
if (ndConstr == null)
{
// Root expression is analyzed
this.parentInfo = null;
this.xstates = PossibleXmlStates.WithinSequence;
this.withinElem = false;
Debug.Assert(ndContent != null);
ndContent = AnalyzeContent(ndContent);
}
else
{
this.parentInfo = XmlILConstructInfo.Write(ndConstr);
if (ndConstr.NodeType == QilNodeType.Function)
{
// Results of function should be pushed to writer
this.parentInfo.ConstructMethod = XmlILConstructMethod.Writer;
// Start with PossibleXmlStates.None and then add additional possible starting states
PossibleXmlStates xstates = PossibleXmlStates.None;
foreach (XmlILConstructInfo infoCaller in this.parentInfo.CallersInfo)
{
if (xstates == PossibleXmlStates.None)
{
xstates = infoCaller.InitialStates;
}
else if (xstates != infoCaller.InitialStates)
{
xstates = PossibleXmlStates.Any;
}
// Function's results are pushed to Writer, so make sure that Invoke nodes' construct methods match
infoCaller.PushToWriterFirst = true;
}
this.parentInfo.InitialStates = xstates;
}
else
{
// Build a standalone tree, with this constructor as its root
if (ndConstr.NodeType != QilNodeType.Choice)
this.parentInfo.InitialStates = this.parentInfo.FinalStates = PossibleXmlStates.WithinSequence;
// Don't stream Rtf; fully cache the Rtf and copy it into any containing tree in order to simplify XmlILVisitor.VisitRtfCtor
if (ndConstr.NodeType != QilNodeType.RtfCtor)
this.parentInfo.ConstructMethod = XmlILConstructMethod.WriterThenIterator;
}
// Set withinElem = true if analyzing element content
this.withinElem = (ndConstr.NodeType == QilNodeType.ElementCtor);
switch (ndConstr.NodeType)
{
case QilNodeType.DocumentCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.ElementCtor: this.xstates = PossibleXmlStates.EnumAttrs; break;
case QilNodeType.AttributeCtor: this.xstates = PossibleXmlStates.WithinAttr; break;
case QilNodeType.NamespaceDecl: Debug.Assert(ndContent == null); break;
case QilNodeType.TextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.RawTextCtor: Debug.Assert(ndContent == null); break;
case QilNodeType.CommentCtor: this.xstates = PossibleXmlStates.WithinComment; break;
case QilNodeType.PICtor: this.xstates = PossibleXmlStates.WithinPI; break;
case QilNodeType.XsltCopy: this.xstates = PossibleXmlStates.Any; break;
case QilNodeType.XsltCopyOf: Debug.Assert(ndContent == null); break;
case QilNodeType.Function: this.xstates = this.parentInfo.InitialStates; break;
case QilNodeType.RtfCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.Choice: this.xstates = PossibleXmlStates.Any; break;
default: Debug.Fail($"{ndConstr.NodeType} is not handled by XmlILStateAnalyzer."); break;
}
if (ndContent != null)
ndContent = AnalyzeContent(ndContent);
if (ndConstr.NodeType == QilNodeType.Choice)
AnalyzeChoice((ndConstr as QilChoice)!, this.parentInfo);
// Since Function will never be another node's content, set its final states here
if (ndConstr.NodeType == QilNodeType.Function)
this.parentInfo.FinalStates = this.xstates;
}
return ndContent;
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
protected virtual QilNode AnalyzeContent(QilNode nd)
{
XmlILConstructInfo info;
QilNode ndChild;
// Handle special node-types that are replaced
switch (nd.NodeType)
{
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Iterator references are shared and cannot be annotated directly with ConstructInfo,
// so wrap them with Nop node.
nd = this.fac.Nop(nd);
break;
}
// Get node's ConstructInfo annotation
info = XmlILConstructInfo.Write(nd);
// Set node's guaranteed parent constructor
info.ParentInfo = this.parentInfo;
// Construct all content using the Writer
info.PushToWriterLast = true;
// Set states that are possible before expression is constructed
info.InitialStates = this.xstates;
switch (nd.NodeType)
{
case QilNodeType.Loop: AnalyzeLoop((nd as QilLoop)!, info); break;
case QilNodeType.Sequence: AnalyzeSequence((nd as QilList)!, info); break;
case QilNodeType.Conditional: AnalyzeConditional((nd as QilTernary)!, info); break;
case QilNodeType.Choice: AnalyzeChoice((nd as QilChoice)!, info); break;
case QilNodeType.Error:
case QilNodeType.Warning:
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
break;
case QilNodeType.Nop:
ndChild = (nd as QilUnary)!.Child;
switch (ndChild.NodeType)
{
case QilNodeType.For:
case QilNodeType.Let:
case QilNodeType.Parameter:
// Copy iterator items as content
AnalyzeCopy(nd, info);
break;
default:
// Ensure that construct method is Writer and recursively analyze content
info.ConstructMethod = XmlILConstructMethod.Writer;
AnalyzeContent(ndChild);
break;
}
break;
default:
AnalyzeCopy(nd, info);
break;
}
// Set states that are possible after expression is constructed
info.FinalStates = this.xstates;
return nd;
}
/// <summary>
/// Analyze loop.
/// </summary>
protected virtual void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info)
{
XmlQueryType typ = ndLoop.XmlType!;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
if (!typ.IsSingleton)
StartLoop(typ, info);
// Body constructs content
ndLoop.Body = AnalyzeContent(ndLoop.Body);
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Analyze list.
/// </summary>
protected virtual void AnalyzeSequence(QilList ndSeq, XmlILConstructInfo info)
{
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Analyze each item in the list
for (int idx = 0; idx < ndSeq.Count; idx++)
ndSeq[idx] = AnalyzeContent(ndSeq[idx]);
}
/// <summary>
/// Analyze conditional.
/// </summary>
protected virtual void AnalyzeConditional(QilTernary ndCond, XmlILConstructInfo info)
{
PossibleXmlStates xstatesTrue;
// Ensure that construct method is Writer
info.ConstructMethod = XmlILConstructMethod.Writer;
// Visit true branch; save resulting states
ndCond.Center = AnalyzeContent(ndCond.Center);
xstatesTrue = this.xstates;
// Restore starting states and visit false branch
this.xstates = info.InitialStates;
ndCond.Right = AnalyzeContent(ndCond.Right);
// Conditional ending states consist of combination of true and false branch states
if (xstatesTrue != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Analyze choice.
/// </summary>
protected virtual void AnalyzeChoice(QilChoice ndChoice, XmlILConstructInfo info)
{
PossibleXmlStates xstatesChoice;
int idx;
// Visit default branch; save resulting states
idx = ndChoice.Branches.Count - 1;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
xstatesChoice = this.xstates;
// Visit all other branches
while (--idx >= 0)
{
// Restore starting states and visit the next branch
this.xstates = info.InitialStates;
ndChoice.Branches[idx] = AnalyzeContent(ndChoice.Branches[idx]);
// Choice ending states consist of combination of all branch states
if (xstatesChoice != this.xstates)
xstatesChoice = PossibleXmlStates.Any;
}
this.xstates = xstatesChoice;
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected virtual void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info)
{
XmlQueryType typ = ndCopy.XmlType!;
// Copying item(s) to output involves looping if there is not exactly one item in the sequence
if (!typ.IsSingleton)
StartLoop(typ, info);
// Determine state transitions that may take place
if (MaybeContent(typ))
{
if (MaybeAttrNmsp(typ))
{
// Node might be Attr/Nmsp or non-Attr/Nmsp, so transition from EnumAttrs to WithinContent *may* occur
if (this.xstates == PossibleXmlStates.EnumAttrs)
this.xstates = PossibleXmlStates.Any;
}
else
{
// Node is guaranteed not to be Attr/Nmsp, so transition to WithinContent will occur if starting
// state is EnumAttrs or if constructing within an element (guaranteed to be in EnumAttrs or WithinContent state)
if (this.xstates == PossibleXmlStates.EnumAttrs || this.withinElem)
this.xstates = PossibleXmlStates.WithinContent;
}
}
if (!typ.IsSingleton)
EndLoop(typ, info);
}
/// <summary>
/// Calculate starting xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void StartLoop(XmlQueryType typ, XmlILConstructInfo info)
{
Debug.Assert(!typ.IsSingleton);
// This is tricky, because the looping introduces a feedback loop:
// 1. Because loops may be executed many times, the beginning set of states must include the ending set of states.
// 2. Because loops may be executed 0 times, the final set of states after all looping is complete must include
// the initial set of states.
//
// +-- states-initial
// | |
// | states-begin-loop <--+
// | | |
// | +--------------+ |
// | | Construction | |
// | +--------------+ |
// | | |
// | states-end-loop ----+
// | |
// +--> states-final
// Save starting loop states
info.BeginLoopStates = this.xstates;
if (typ.MaybeMany)
{
// If transition might occur from EnumAttrs to WithinContent, then states-end might be WithinContent, which
// means states-begin needs to also include WithinContent.
if (this.xstates == PossibleXmlStates.EnumAttrs && MaybeContent(typ))
info.BeginLoopStates = this.xstates = PossibleXmlStates.Any;
}
}
/// <summary>
/// Calculate ending xml states that will result when iterating over and constructing an expression of the specified type.
/// </summary>
private void EndLoop(XmlQueryType typ, XmlILConstructInfo info)
{
Debug.Assert(!typ.IsSingleton);
// Save ending loop states
info.EndLoopStates = this.xstates;
// If it's possible to loop zero times, then states-final needs to include states-initial
if (typ.MaybeEmpty && info.InitialStates != this.xstates)
this.xstates = PossibleXmlStates.Any;
}
/// <summary>
/// Return true if an instance of the specified type might be an attribute or a namespace node.
/// </summary>
private bool MaybeAttrNmsp(XmlQueryType typ)
{
return (typ.NodeKinds & (XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
/// <summary>
/// Return true if an instance of the specified type might be a non-empty content type (attr/nsmp don't count).
/// </summary>
private bool MaybeContent(XmlQueryType typ)
{
return !typ.IsNode || (typ.NodeKinds & ~(XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None;
}
}
/// <summary>
/// Scans the content of an ElementCtor and tries to minimize the number of well-formed checks that will have
/// to be made at runtime when constructing content.
/// </summary>
internal sealed class XmlILElementAnalyzer : XmlILStateAnalyzer
{
private readonly NameTable _attrNames = new NameTable();
private readonly ArrayList _dupAttrs = new ArrayList();
/// <summary>
/// Constructor.
/// </summary>
public XmlILElementAnalyzer(QilFactory fac) : base(fac)
{
}
/// <summary>
/// Analyze the content argument of the ElementCtor. Try to eliminate as many runtime checks as possible,
/// both for the ElementCtor and for content constructors.
/// </summary>
public override QilNode? Analyze(QilNode? ndElem, QilNode? ndContent)
{
Debug.Assert(ndElem!.NodeType == QilNodeType.ElementCtor);
this.parentInfo = XmlILConstructInfo.Write(ndElem);
// Start by assuming that these properties are false (they default to true, but analyzer might be able to
// prove they are really false).
this.parentInfo.MightHaveNamespacesAfterAttributes = false;
this.parentInfo.MightHaveAttributes = false;
this.parentInfo.MightHaveDuplicateAttributes = false;
// The element's namespace might need to be declared
this.parentInfo.MightHaveNamespaces = !this.parentInfo.IsNamespaceInScope;
// Clear list of duplicate attributes
_dupAttrs.Clear();
return base.Analyze(ndElem, ndContent);
}
/// <summary>
/// Analyze loop.
/// </summary>
protected override void AnalyzeLoop(QilLoop ndLoop, XmlILConstructInfo info)
{
// Constructing attributes/namespaces in a loop can cause duplicates, namespaces after attributes, etc.
if (ndLoop.XmlType!.MaybeMany)
CheckAttributeNamespaceConstruct(ndLoop.XmlType);
base.AnalyzeLoop(ndLoop, info);
}
/// <summary>
/// Analyze copying items.
/// </summary>
protected override void AnalyzeCopy(QilNode ndCopy, XmlILConstructInfo info)
{
if (ndCopy.NodeType == QilNodeType.AttributeCtor)
{
QilBinary? binaryNode = ndCopy as QilBinary;
Debug.Assert(binaryNode != null);
AnalyzeAttributeCtor(binaryNode, info);
}
else
{
CheckAttributeNamespaceConstruct(ndCopy.XmlType!);
}
base.AnalyzeCopy(ndCopy, info);
}
/// <summary>
/// Analyze attribute constructor.
/// </summary>
private void AnalyzeAttributeCtor(QilBinary ndAttr, XmlILConstructInfo info)
{
if (ndAttr.Left.NodeType == QilNodeType.LiteralQName)
{
QilName? ndName = ndAttr.Left as QilName;
Debug.Assert(ndName != null);
XmlQualifiedName qname;
int idx;
// This attribute might be constructed on the parent element
this.parentInfo!.MightHaveAttributes = true;
// Check to see whether this attribute is a duplicate of a previous attribute
if (!this.parentInfo.MightHaveDuplicateAttributes)
{
qname = new XmlQualifiedName(_attrNames.Add(ndName.LocalName), _attrNames.Add(ndName.NamespaceUri));
for (idx = 0; idx < _dupAttrs.Count; idx++)
{
XmlQualifiedName qnameDup = (XmlQualifiedName)_dupAttrs[idx]!;
if ((object)qnameDup.Name == (object)qname.Name && (object)qnameDup.Namespace == (object)qname.Namespace)
{
// A duplicate attribute has been encountered
this.parentInfo.MightHaveDuplicateAttributes = true;
}
}
if (idx >= _dupAttrs.Count)
{
// This is not a duplicate attribute, so add it to the set
_dupAttrs.Add(qname);
}
}
// The attribute's namespace might need to be declared
if (!info.IsNamespaceInScope)
this.parentInfo.MightHaveNamespaces = true;
}
else
{
// Attribute prefix and namespace are not known at compile-time
CheckAttributeNamespaceConstruct(ndAttr.XmlType!);
}
}
/// <summary>
/// If type might contain attributes or namespaces, set appropriate parent element flags.
/// </summary>
private void CheckAttributeNamespaceConstruct(XmlQueryType typ)
{
// If content might contain attributes,
if ((typ.NodeKinds & XmlNodeKindFlags.Attribute) != XmlNodeKindFlags.None)
{
// Mark element as possibly having attributes and duplicate attributes (since we don't know the names)
this.parentInfo!.MightHaveAttributes = true;
this.parentInfo.MightHaveDuplicateAttributes = true;
// Attribute namespaces might be declared
this.parentInfo.MightHaveNamespaces = true;
}
// If content might contain namespaces,
if ((typ.NodeKinds & XmlNodeKindFlags.Namespace) != XmlNodeKindFlags.None)
{
// Then element might have namespaces,
this.parentInfo!.MightHaveNamespaces = true;
// If attributes might already have been constructed,
if (this.parentInfo.MightHaveAttributes)
{
// Then attributes might precede namespace declarations
this.parentInfo.MightHaveNamespacesAfterAttributes = true;
}
}
}
}
/// <summary>
/// Scans constructed content, looking for redundant namespace declarations. If any are found, then they are marked
/// and removed later.
/// </summary>
internal sealed class XmlILNamespaceAnalyzer
{
private readonly XmlNamespaceManager _nsmgr = new XmlNamespaceManager(new NameTable());
private bool _addInScopeNmsp;
private int _cntNmsp;
/// <summary>
/// Perform scan.
/// </summary>
public void Analyze(QilNode nd, bool defaultNmspInScope)
{
_addInScopeNmsp = false;
_cntNmsp = 0;
// If xmlns="" is in-scope, push it onto the namespace stack
if (defaultNmspInScope)
{
_nsmgr.PushScope();
_nsmgr.AddNamespace(string.Empty, string.Empty);
_cntNmsp++;
}
AnalyzeContent(nd);
if (defaultNmspInScope)
_nsmgr.PopScope();
}
/// <summary>
/// Recursively analyze content. Return "nd" or a replacement for it.
/// </summary>
private void AnalyzeContent(QilNode nd)
{
int cntNmspSave;
switch (nd.NodeType)
{
case QilNodeType.Loop:
_addInScopeNmsp = false;
AnalyzeContent((nd as QilLoop)!.Body);
break;
case QilNodeType.Sequence:
foreach (QilNode ndContent in nd)
AnalyzeContent(ndContent);
break;
case QilNodeType.Conditional:
_addInScopeNmsp = false;
AnalyzeContent((nd as QilTernary)!.Center);
AnalyzeContent((nd as QilTernary)!.Right);
break;
case QilNodeType.Choice:
_addInScopeNmsp = false;
QilList ndBranches = (nd as QilChoice)!.Branches;
for (int idx = 0; idx < ndBranches.Count; idx++)
AnalyzeContent(ndBranches[idx]);
break;
case QilNodeType.ElementCtor:
// Start a new namespace scope
_addInScopeNmsp = true;
_nsmgr.PushScope();
cntNmspSave = _cntNmsp;
if (CheckNamespaceInScope((nd as QilBinary)!))
AnalyzeContent((nd as QilBinary)!.Right);
_nsmgr.PopScope();
_addInScopeNmsp = false;
_cntNmsp = cntNmspSave;
break;
case QilNodeType.AttributeCtor:
_addInScopeNmsp = false;
CheckNamespaceInScope((nd as QilBinary)!);
break;
case QilNodeType.NamespaceDecl:
CheckNamespaceInScope((nd as QilBinary)!);
break;
case QilNodeType.Nop:
AnalyzeContent((nd as QilUnary)!.Child);
break;
default:
_addInScopeNmsp = false;
break;
}
}
/// <summary>
/// Determine whether an ElementCtor, AttributeCtor, or NamespaceDecl's namespace is already declared. If it is,
/// set the IsNamespaceInScope property to True. Otherwise, add the namespace to the set of in-scope namespaces if
/// addInScopeNmsp is True. Return false if the name is computed or is invalid.
/// </summary>
private bool CheckNamespaceInScope(QilBinary nd)
{
QilName? ndName;
string prefix, ns;
string? prefixExisting, nsExisting;
XPathNodeType nodeType;
switch (nd.NodeType)
{
case QilNodeType.ElementCtor:
case QilNodeType.AttributeCtor:
ndName = nd.Left as QilName;
if (ndName != null)
{
prefix = ndName.Prefix;
ns = ndName.NamespaceUri;
nodeType = (nd.NodeType == QilNodeType.ElementCtor) ? XPathNodeType.Element : XPathNodeType.Attribute;
break;
}
// Not a literal name, so return false
return false;
default:
Debug.Assert(nd.NodeType == QilNodeType.NamespaceDecl);
prefix = (string)(QilLiteral)nd.Left;
ns = (string)(QilLiteral)nd.Right;
nodeType = XPathNodeType.Namespace;
break;
}
// Attribute with null namespace and xmlns:xml are always in-scope
if (nd.NodeType == QilNodeType.AttributeCtor && ns.Length == 0 ||
prefix == "xml" && ns == XmlReservedNs.NsXml)
{
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
return true;
}
// Don't process names that are invalid
if (!ValidateNames.ValidateName(prefix, string.Empty, ns, nodeType, ValidateNames.Flags.CheckPrefixMapping))
return false;
// Atomize names
prefix = _nsmgr.NameTable!.Add(prefix);
ns = _nsmgr.NameTable.Add(ns);
// Determine whether namespace is already in-scope
for (int iNmsp = 0; iNmsp < _cntNmsp; iNmsp++)
{
_nsmgr.GetNamespaceDeclaration(iNmsp, out prefixExisting, out nsExisting);
// If prefix is already declared,
if ((object)prefix == (object?)prefixExisting)
{
// Then if the namespace is the same, this namespace is redundant
if ((object)ns == (object?)nsExisting)
XmlILConstructInfo.Write(nd).IsNamespaceInScope = true;
// Else quit searching, because any further matching prefixes will be hidden (not in-scope)
Debug.Assert(nd.NodeType != QilNodeType.NamespaceDecl || !_nsmgr.HasNamespace(prefix) || _nsmgr.LookupNamespace(prefix) == ns,
"Compilers must ensure that namespace declarations do not conflict with the namespace used by the element constructor.");
break;
}
}
// If not in-scope, then add if it's allowed
if (_addInScopeNmsp)
{
_nsmgr.AddNamespace(prefix, ns);
_cntNmsp++;
}
return true;
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<NoWarn>$(NoWarn);0436</NoWarn>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
<TargetFramework>$(NetCoreAppCurrent)-windows</TargetFramework>
<DefineConstants>UNITTEST</DefineConstants>
<EnableLibraryImportGenerator>true</EnableLibraryImportGenerator>
<Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<DefaultReferenceExclusion Include="System.Net.Http.WinHttpHandler" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs"
Link="CommonTest\System\Net\SslProtocolSupport.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs"
Link="Common\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.HRESULT_FROM_WIN32.cs"
Link="Common\Interop\Windows\Interop.HRESULT_FROM_WIN32.cs" />
<Compile Include="$(CommonPath)Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs"
Link="Common\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs" />
<Compile Include="$(CommonPath)Interop\Windows\WinHttp\Interop.SafeWinHttpHandle.cs"
Link="Common\Interop\Windows\WinHttp\Interop.SafeWinHttpHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\WinHttp\Interop.winhttp_types.cs"
Link="Common\Interop\Windows\WinHttp\Interop.winhttp_types.cs" />
<Compile Include="$(CommonPath)System\CharArrayHelpers.cs"
Link="Common\System\CharArrayHelpers.cs" />
<Compile Include="$(CommonPath)System\StringExtensions.cs"
Link="Common\System\StringExtensions.cs" />
<Compile Include="$(CommonPath)System\IO\StreamHelpers.CopyValidation.cs"
Link="Common\System\IO\StreamHelpers.CopyValidation.cs" />
<Compile Include="$(CommonPath)System\Net\HttpKnownHeaderNames.cs"
Link="Common\System\Net\HttpKnownHeaderNames.cs" />
<Compile Include="$(CommonPath)System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs"
Link="Common\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs" />
<Compile Include="$(CommonPath)System\Net\HttpStatusDescription.cs"
Link="Common\System\Net\HttpStatusDescription.cs" />
<Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs"
Link="Common\System\Net\Logging\NetEventSource.Common.cs" />
<Compile Include="$(CommonPath)System\Net\UriScheme.cs"
Link="Common\System\Net\UriScheme.cs" />
<Compile Include="$(CommonPath)System\Net\SecurityProtocol.cs"
Link="Common\System\Net\SecurityProtocol.cs" />
<Compile Include="$(CommonPath)System\Net\Http\HttpHandlerDefaults.cs"
Link="Common\System\Net\Http\HttpHandlerDefaults.cs" />
<Compile Include="$(CommonPath)\System\Net\Http\WinInetProxyHelper.cs"
Link="Common\System\Net\Http\WinInetProxyHelper.cs" />
<Compile Include="$(CommonPath)System\Net\Security\CertificateHelper.cs"
Link="Common\System\Net\Security\CertificateHelper.cs" />
<Compile Include="$(CommonPath)System\Net\Security\CertificateHelper.Windows.cs"
Link="Common\System\Net\Security\CertificateHelper.Windows.cs" />
<Compile Include="$(CommonPath)System\Runtime\ExceptionServices\ExceptionStackTrace.cs"
Link="Common\System\Runtime\ExceptionServices\ExceptionStackTrace.cs" />
<Compile Include="$(CommonPath)System\Text\SimpleRegex.cs"
Link="Common\System\Text\SimpleRegex.cs" />
<Compile Include="$(CommonPath)System\Threading\Tasks\RendezvousAwaitable.cs"
Link="Common\System\Threading\Tasks\RendezvousAwaitable.cs" />
<Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs"
Link="Common\System\Threading\Tasks\TaskToApm.cs" />
<Compile Include="..\..\src\System\Net\Http\NoWriteNoSeekStreamContent.cs"
Link="ProductionCode\NoWriteNoSeekStreamContent.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpAuthHelper.cs"
Link="ProductionCode\WinHttpAuthHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpChannelBinding.cs"
Link="ProductionCode\WinHttpChannelBinding.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpChunkMode.cs"
Link="ProductionCode\WinHttpChunkMode.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpCookieContainerAdapter.cs"
Link="ProductionCode\WinHttpCookieContainerAdapter.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpException.cs"
Link="ProductionCode\WinHttpException.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpHandler.cs"
Link="ProductionCode\WinHttpHandler.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestCallback.cs"
Link="ProductionCode\WinHttpRequestCallback.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestState.cs"
Link="ProductionCode\WinHttpRequestState.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestStream.cs"
Link="ProductionCode\WinHttpRequestStream.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseHeaderReader.cs"
Link="ProductionCode\WinHttpResponseHeaderReader.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseParser.cs"
Link="ProductionCode\WinHttpResponseParser.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseStream.cs"
Link="ProductionCode\WinHttpResponseStream.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTraceHelper.cs"
Link="ProductionCode\WinHttpTraceHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTrailersHelper.cs"
Link="ProductionCode\WinHttpTrailersHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTransportContext.cs"
Link="ProductionCode\WinHttpTransportContext.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpWindowsProxy.cs"
Link="ProductionCode\HttpWindowsProxy.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\FailedProxyCache.cs"
Link="ProductionCode\FailedProxyCache.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\IMultiWebProxy.cs"
Link="ProductionCode\IMultiWebProxy.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\MultiProxy.cs"
Link="ProductionCode\MultiProxy.cs" />
<Compile Include="APICallHistory.cs" />
<Compile Include="ClientCertificateHelper.cs" />
<Compile Include="ClientCertificateScenarioTest.cs" />
<Compile Include="FakeInterop.cs" />
<Compile Include="FakeMarshal.cs" />
<Compile Include="FakeRegistry.cs" />
<Compile Include="FakeSafeWinHttpHandle.cs" />
<Compile Include="FakeX509Certificates.cs" />
<Compile Include="HttpWindowsProxyTest.cs" />
<Compile Include="SafeWinHttpHandleTest.cs" />
<Compile Include="SendRequestHelper.cs" />
<Compile Include="TestServer.cs" />
<Compile Include="TestControl.cs" />
<Compile Include="WinHttpHandlerTest.cs" />
<Compile Include="WinHttpRequestStreamTest.cs" />
<Compile Include="WinHttpResponseHeaderReaderTest.cs" />
<Compile Include="WinHttpResponseStreamTest.cs" />
<Compile Include="XunitTestAssemblyAtrributes.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<NoWarn>$(NoWarn);0436</NoWarn>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
<TargetFramework>$(NetCoreAppCurrent)-windows</TargetFramework>
<DefineConstants>UNITTEST</DefineConstants>
<EnableLibraryImportGenerator>true</EnableLibraryImportGenerator>
<Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<DefaultReferenceExclusion Include="System.Net.Http.WinHttpHandler" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(CommonTestPath)System\Net\SslProtocolSupport.cs"
Link="CommonTest\System\Net\SslProtocolSupport.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs"
Link="Common\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.HRESULT_FROM_WIN32.cs"
Link="Common\Interop\Windows\Interop.HRESULT_FROM_WIN32.cs" />
<Compile Include="$(CommonPath)Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs"
Link="Common\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs" />
<Compile Include="$(CommonPath)Interop\Windows\WinHttp\Interop.SafeWinHttpHandle.cs"
Link="Common\Interop\Windows\WinHttp\Interop.SafeWinHttpHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\WinHttp\Interop.winhttp_types.cs"
Link="Common\Interop\Windows\WinHttp\Interop.winhttp_types.cs" />
<Compile Include="$(CommonPath)System\CharArrayHelpers.cs"
Link="Common\System\CharArrayHelpers.cs" />
<Compile Include="$(CommonPath)System\StringExtensions.cs"
Link="Common\System\StringExtensions.cs" />
<Compile Include="$(CommonPath)System\IO\StreamHelpers.CopyValidation.cs"
Link="Common\System\IO\StreamHelpers.CopyValidation.cs" />
<Compile Include="$(CommonPath)System\Net\HttpKnownHeaderNames.cs"
Link="Common\System\Net\HttpKnownHeaderNames.cs" />
<Compile Include="$(CommonPath)System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs"
Link="Common\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs" />
<Compile Include="$(CommonPath)System\Net\HttpStatusDescription.cs"
Link="Common\System\Net\HttpStatusDescription.cs" />
<Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs"
Link="Common\System\Net\Logging\NetEventSource.Common.cs" />
<Compile Include="$(CommonPath)System\Net\UriScheme.cs"
Link="Common\System\Net\UriScheme.cs" />
<Compile Include="$(CommonPath)System\Net\SecurityProtocol.cs"
Link="Common\System\Net\SecurityProtocol.cs" />
<Compile Include="$(CommonPath)System\Net\Http\HttpHandlerDefaults.cs"
Link="Common\System\Net\Http\HttpHandlerDefaults.cs" />
<Compile Include="$(CommonPath)\System\Net\Http\WinInetProxyHelper.cs"
Link="Common\System\Net\Http\WinInetProxyHelper.cs" />
<Compile Include="$(CommonPath)System\Net\Security\CertificateHelper.cs"
Link="Common\System\Net\Security\CertificateHelper.cs" />
<Compile Include="$(CommonPath)System\Net\Security\CertificateHelper.Windows.cs"
Link="Common\System\Net\Security\CertificateHelper.Windows.cs" />
<Compile Include="$(CommonPath)System\Runtime\ExceptionServices\ExceptionStackTrace.cs"
Link="Common\System\Runtime\ExceptionServices\ExceptionStackTrace.cs" />
<Compile Include="$(CommonPath)System\Text\SimpleRegex.cs"
Link="Common\System\Text\SimpleRegex.cs" />
<Compile Include="$(CommonPath)System\Threading\Tasks\RendezvousAwaitable.cs"
Link="Common\System\Threading\Tasks\RendezvousAwaitable.cs" />
<Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs"
Link="Common\System\Threading\Tasks\TaskToApm.cs" />
<Compile Include="..\..\src\System\Net\Http\NoWriteNoSeekStreamContent.cs"
Link="ProductionCode\NoWriteNoSeekStreamContent.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpAuthHelper.cs"
Link="ProductionCode\WinHttpAuthHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpChannelBinding.cs"
Link="ProductionCode\WinHttpChannelBinding.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpChunkMode.cs"
Link="ProductionCode\WinHttpChunkMode.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpCookieContainerAdapter.cs"
Link="ProductionCode\WinHttpCookieContainerAdapter.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpException.cs"
Link="ProductionCode\WinHttpException.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpHandler.cs"
Link="ProductionCode\WinHttpHandler.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestCallback.cs"
Link="ProductionCode\WinHttpRequestCallback.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestState.cs"
Link="ProductionCode\WinHttpRequestState.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpRequestStream.cs"
Link="ProductionCode\WinHttpRequestStream.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseHeaderReader.cs"
Link="ProductionCode\WinHttpResponseHeaderReader.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseParser.cs"
Link="ProductionCode\WinHttpResponseParser.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpResponseStream.cs"
Link="ProductionCode\WinHttpResponseStream.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTraceHelper.cs"
Link="ProductionCode\WinHttpTraceHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTrailersHelper.cs"
Link="ProductionCode\WinHttpTrailersHelper.cs" />
<Compile Include="..\..\src\System\Net\Http\WinHttpTransportContext.cs"
Link="ProductionCode\WinHttpTransportContext.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\HttpWindowsProxy.cs"
Link="ProductionCode\HttpWindowsProxy.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\FailedProxyCache.cs"
Link="ProductionCode\FailedProxyCache.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\IMultiWebProxy.cs"
Link="ProductionCode\IMultiWebProxy.cs" />
<Compile Include="..\..\..\System.Net.Http\src\System\Net\Http\SocketsHttpHandler\MultiProxy.cs"
Link="ProductionCode\MultiProxy.cs" />
<Compile Include="APICallHistory.cs" />
<Compile Include="ClientCertificateHelper.cs" />
<Compile Include="ClientCertificateScenarioTest.cs" />
<Compile Include="FakeInterop.cs" />
<Compile Include="FakeMarshal.cs" />
<Compile Include="FakeRegistry.cs" />
<Compile Include="FakeSafeWinHttpHandle.cs" />
<Compile Include="FakeX509Certificates.cs" />
<Compile Include="HttpWindowsProxyTest.cs" />
<Compile Include="SafeWinHttpHandleTest.cs" />
<Compile Include="SendRequestHelper.cs" />
<Compile Include="TestServer.cs" />
<Compile Include="TestControl.cs" />
<Compile Include="WinHttpHandlerTest.cs" />
<Compile Include="WinHttpRequestStreamTest.cs" />
<Compile Include="WinHttpResponseHeaderReaderTest.cs" />
<Compile Include="WinHttpResponseStreamTest.cs" />
<Compile Include="XunitTestAssemblyAtrributes.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/mono/mono/metadata/mono-perfcounters-def.h
|
/**
* \file
* Define the system and runtime performance counters.
* Each category is defined with the macro:
* PERFCTR_CAT(catid, name, help, type, instances, first_counter_id)
* and after that follows the counters inside the category, defined by the macro:
* PERFCTR_COUNTER(counter_id, name, help, type, field)
* field is the field inside MonoPerfCounters per predefined counters.
* Note we set it to unused for unrelated counters: it is unused
* in those cases.
*/
PERFCTR_CAT(CPU, "Processor", "", MultiInstance, CPU, CPU_USER_TIME)
PERFCTR_COUNTER(CPU_USER_TIME, "% User Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_PRIV_TIME, "% Privileged Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_INTR_TIME, "% Interrupt Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_DCP_TIME, "% DCP Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_PROC_TIME, "% Processor Time", "", Timer100NsInverse, unused)
PERFCTR_CAT(PROC, "Process", "", MultiInstance, Process, PROC_USER_TIME)
PERFCTR_COUNTER(PROC_USER_TIME, "% User Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_PRIV_TIME, "% Privileged Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_PROC_TIME, "% Processor Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_THREADS, "Thread Count", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_VBYTES, "Virtual Bytes", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_WSET, "Working Set", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_PBYTES, "Private Bytes", "", NumberOfItems64, unused)
/* sample runtime counter */
PERFCTR_CAT(MONO_MEM, "Mono Memory", "", SingleInstance, Mono, MEM_NUM_OBJECTS)
PERFCTR_COUNTER(MEM_NUM_OBJECTS, "Allocated Objects", "", NumberOfItems64, unused)
PERFCTR_COUNTER(MEM_PHYS_TOTAL, "Total Physical Memory", "Physical memory installed in the machine, in bytes", NumberOfItems64, unused)
PERFCTR_COUNTER(MEM_PHYS_AVAILABLE, "Available Physical Memory", "Physical memory available in the machine, in bytes", NumberOfItems64, unused)
PERFCTR_CAT(ASPNET, "ASP.NET", "", MultiInstance, Mono, ASPNET_REQ_Q)
PERFCTR_COUNTER(ASPNET_REQ_Q, "Requests Queued", "", NumberOfItems64, aspnet_requests_queued)
PERFCTR_COUNTER(ASPNET_REQ_TOTAL, "Requests Total", "", NumberOfItems32, aspnet_requests)
PERFCTR_COUNTER(ASPNET_REQ_PSEC, "Requests/Sec", "", RateOfCountsPerSecond32, aspnet_requests)
PERFCTR_CAT(JIT, ".NET CLR JIT", "", MultiInstance, Mono, JIT_BYTES)
PERFCTR_COUNTER(JIT_BYTES, "# of IL Bytes JITted", "", NumberOfItems32, jit_bytes)
PERFCTR_COUNTER(JIT_METHODS, "# of IL Methods JITted", "", NumberOfItems32, jit_methods)
PERFCTR_COUNTER(JIT_TIME, "% Time in JIT", "", RawFraction, jit_time)
PERFCTR_COUNTER(JIT_BYTES_PSEC, "IL Bytes Jitted/Sec", "", RateOfCountsPerSecond32, jit_bytes)
PERFCTR_COUNTER(JIT_FAILURES, "Standard Jit Failures", "", NumberOfItems32, jit_failures)
PERFCTR_CAT(EXC, ".NET CLR Exceptions", "", MultiInstance, Mono, EXC_THROWN)
PERFCTR_COUNTER(EXC_THROWN, "# of Exceps Thrown", "", NumberOfItems32, exceptions_thrown)
PERFCTR_COUNTER(EXC_THROWN_PSEC, "# of Exceps Thrown/Sec", "", RateOfCountsPerSecond32, exceptions_thrown)
PERFCTR_COUNTER(EXC_FILTERS_PSEC, "# of Filters/Sec", "", RateOfCountsPerSecond32, exceptions_filters)
PERFCTR_COUNTER(EXC_FINALLYS_PSEC, "# of Finallys/Sec", "", RateOfCountsPerSecond32, exceptions_finallys)
PERFCTR_COUNTER(EXC_CATCH_DEPTH, "Throw to Catch Depth/Sec", "", NumberOfItems32, exceptions_depth)
PERFCTR_CAT(GC, ".NET CLR Memory", "", MultiInstance, Mono, GC_GEN0)
PERFCTR_COUNTER(GC_GEN0, "# Gen 0 Collections", "", NumberOfItems32, gc_collections0)
PERFCTR_COUNTER(GC_GEN1, "# Gen 1 Collections", "", NumberOfItems32, gc_collections1)
PERFCTR_COUNTER(GC_GEN2, "# Gen 2 Collections", "", NumberOfItems32, gc_collections2)
PERFCTR_COUNTER(GC_PROM0, "Promoted Memory from Gen 0", "", NumberOfItems32, gc_promotions0)
PERFCTR_COUNTER(GC_PROM1, "Promoted Memory from Gen 1", "", NumberOfItems32, gc_promotions1)
PERFCTR_COUNTER(GC_PROM0SEC, "Gen 0 Promoted Bytes/Sec", "", RateOfCountsPerSecond32, gc_promotions0)
PERFCTR_COUNTER(GC_PROM1SEC, "Gen 1 Promoted Bytes/Sec", "", RateOfCountsPerSecond32, gc_promotions1)
PERFCTR_COUNTER(GC_PROMFIN, "Promoted Finalization-Memory from Gen 0", "", NumberOfItems32, gc_promotion_finalizers)
PERFCTR_COUNTER(GC_GEN0SIZE, "Gen 0 heap size", "", NumberOfItems64, gc_gen0size)
PERFCTR_COUNTER(GC_GEN1SIZE, "Gen 1 heap size", "", NumberOfItems64, gc_gen1size)
PERFCTR_COUNTER(GC_GEN2SIZE, "Gen 2 heap size", "", NumberOfItems64, gc_gen2size)
PERFCTR_COUNTER(GC_LOSIZE, "Large Object Heap size", "", NumberOfItems32, gc_lossize)
PERFCTR_COUNTER(GC_FINSURV, "Finalization Survivors", "", NumberOfItems32, gc_fin_survivors)
PERFCTR_COUNTER(GC_NHANDLES, "# GC Handles", "", NumberOfItems32, gc_num_handles)
PERFCTR_COUNTER(GC_BYTESSEC, "Allocated Bytes/sec", "", RateOfCountsPerSecond32, gc_allocated)
PERFCTR_COUNTER(GC_INDGC, "# Induced GC", "", NumberOfItems32, gc_induced)
PERFCTR_COUNTER(GC_PERCTIME, "% Time in GC", "", RawFraction, gc_time)
PERFCTR_COUNTER(GC_BYTES, "# Bytes in all Heaps", "", NumberOfItems64, gc_total_bytes)
PERFCTR_COUNTER(GC_COMMBYTES, "# Total committed Bytes", "", NumberOfItems64, gc_committed_bytes)
PERFCTR_COUNTER(GC_RESBYTES, "# Total reserved Bytes", "", NumberOfItems64, gc_reserved_bytes)
PERFCTR_COUNTER(GC_PINNED, "# of Pinned Objects", "", NumberOfItems32, gc_num_pinned)
PERFCTR_COUNTER(GC_SYNKB, "# of Sink Blocks in use", "", NumberOfItems32, gc_sync_blocks)
PERFCTR_CAT(LOADING, ".NET CLR Loading", "", MultiInstance, Mono, LOADING_CLASSES)
PERFCTR_COUNTER(LOADING_CLASSES, "Current Classes Loaded", "", NumberOfItems32, loader_classes)
PERFCTR_COUNTER(LOADING_TOTCLASSES, "Total Classes Loaded", "", NumberOfItems32, loader_total_classes)
PERFCTR_COUNTER(LOADING_CLASSESSEC, "Rate of Classes Loaded", "", RateOfCountsPerSecond32, loader_total_classes)
PERFCTR_COUNTER(LOADING_APPDOMAINS, "Current appdomains", "", NumberOfItems32, loader_appdomains)
PERFCTR_COUNTER(LOADING_TOTAPPDOMAINS, "Total Appdomains", "", NumberOfItems32, loader_total_appdomains)
PERFCTR_COUNTER(LOADING_APPDOMAINSEC, "Rate of appdomains", "", RateOfCountsPerSecond32, loader_total_appdomains)
PERFCTR_COUNTER(LOADING_ASSEMBLIES, "Current Assemblies", "", NumberOfItems32, loader_assemblies)
PERFCTR_COUNTER(LOADING_TOTASSEMBLIES, "Total Assemblies", "", NumberOfItems32, loader_total_assemblies)
PERFCTR_COUNTER(LOADING_ASSEMBLIESEC, "Rate of Assemblies", "", RateOfCountsPerSecond32, loader_total_assemblies)
PERFCTR_COUNTER(LOADING_FAILURES, "Total # of Load Failures", "", NumberOfItems32, loader_failures)
PERFCTR_COUNTER(LOADING_FAILURESSEC, "Rate of Load Failures", "", RateOfCountsPerSecond32, loader_failures)
PERFCTR_COUNTER(LOADING_BYTES, "Bytes in Loader Heap", "", NumberOfItems32, loader_bytes)
PERFCTR_COUNTER(LOADING_APPUNLOADED, "Total appdomains unloaded", "", NumberOfItems32, loader_appdomains_uloaded)
PERFCTR_COUNTER(LOADING_APPUNLOADEDSEC, "Rate of appdomains unloaded", "", RateOfCountsPerSecond32, loader_appdomains_uloaded)
PERFCTR_CAT(THREAD, ".NET CLR LocksAndThreads", "", MultiInstance, Mono, THREAD_CONTENTIONS)
PERFCTR_COUNTER(THREAD_CONTENTIONS, "Total # of Contentions", "", NumberOfItems32, thread_contentions)
PERFCTR_COUNTER(THREAD_CONTENTIONSSEC, "Contention Rate / sec", "", RateOfCountsPerSecond32, thread_contentions)
PERFCTR_COUNTER(THREAD_QUEUELEN, "Current Queue Length", "", NumberOfItems32, thread_queue_len)
PERFCTR_COUNTER(THREAD_QUEUELENP, "Queue Length Peak", "", NumberOfItems32, thread_queue_max)
PERFCTR_COUNTER(THREAD_QUEUELENSEC, "Queue Length / sec", "", RateOfCountsPerSecond32, thread_queue_max)
PERFCTR_COUNTER(THREAD_NUMLOG, "# of current logical Threads", "", NumberOfItems32, thread_num_logical)
PERFCTR_COUNTER(THREAD_NUMPHYS, "# of current physical Threads", "", NumberOfItems32, thread_num_physical)
PERFCTR_COUNTER(THREAD_NUMREC, "# of current recognized threads", "", NumberOfItems32, thread_cur_recognized)
PERFCTR_COUNTER(THREAD_TOTREC, "# of total recognized threads", "", NumberOfItems32, thread_num_recognized)
PERFCTR_COUNTER(THREAD_TOTRECSEC, "rate of recognized threads / sec", "", RateOfCountsPerSecond32, thread_num_recognized)
PERFCTR_CAT(INTEROP, ".NET CLR Interop", "", MultiInstance, Mono, INTEROP_NUMCCW)
PERFCTR_COUNTER(INTEROP_NUMCCW, "# of CCWs", "", NumberOfItems32, interop_num_ccw)
PERFCTR_COUNTER(INTEROP_STUBS, "# of Stubs", "", NumberOfItems32, interop_num_stubs)
PERFCTR_COUNTER(INTEROP_MARSH, "# of marshalling", "", NumberOfItems32, interop_num_marshals)
PERFCTR_CAT(SECURITY, ".NET CLR Security", "", MultiInstance, Mono, SECURITY_CHECKS)
PERFCTR_COUNTER(SECURITY_CHECKS, "Total Runtime Checks", "", NumberOfItems32, security_num_checks)
PERFCTR_COUNTER(SECURITY_LCHECKS, "# Link Time Checks", "", NumberOfItems32, security_num_link_checks)
PERFCTR_COUNTER(SECURITY_PERCTIME, "% Time in RT checks", "", RawFraction, security_time)
PERFCTR_COUNTER(SECURITY_SWDEPTH, "Stack Walk Depth", "", NumberOfItems32, security_depth)
PERFCTR_CAT(THREADPOOL, "Mono Threadpool", "", MultiInstance, Mono, THREADPOOL_WORKITEMS)
PERFCTR_COUNTER(THREADPOOL_WORKITEMS, "Work Items Added", "", NumberOfItems64, threadpool_workitems)
PERFCTR_COUNTER(THREADPOOL_WORKITEMS_PSEC, "Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_workitems)
PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS, "IO Work Items Added", "", NumberOfItems64, threadpool_ioworkitems)
PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS_PSEC, "IO Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_ioworkitems)
PERFCTR_COUNTER(THREADPOOL_THREADS, "# of Threads", "", NumberOfItems32, threadpool_threads)
PERFCTR_COUNTER(THREADPOOL_IOTHREADS, "# of IO Threads", "", NumberOfItems32, threadpool_iothreads)
PERFCTR_CAT(NETWORK, "Network Interface", "", MultiInstance, NetworkInterface, NETWORK_BYTESRECSEC)
PERFCTR_COUNTER(NETWORK_BYTESRECSEC, "Bytes Received/sec", "", RateOfCountsPerSecond64, unused)
PERFCTR_COUNTER(NETWORK_BYTESSENTSEC, "Bytes Sent/sec", "", RateOfCountsPerSecond64, unused)
PERFCTR_COUNTER(NETWORK_BYTESTOTALSEC, "Bytes Total/sec", "", RateOfCountsPerSecond64, unused)
|
/**
* \file
* Define the system and runtime performance counters.
* Each category is defined with the macro:
* PERFCTR_CAT(catid, name, help, type, instances, first_counter_id)
* and after that follows the counters inside the category, defined by the macro:
* PERFCTR_COUNTER(counter_id, name, help, type, field)
* field is the field inside MonoPerfCounters per predefined counters.
* Note we set it to unused for unrelated counters: it is unused
* in those cases.
*/
PERFCTR_CAT(CPU, "Processor", "", MultiInstance, CPU, CPU_USER_TIME)
PERFCTR_COUNTER(CPU_USER_TIME, "% User Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_PRIV_TIME, "% Privileged Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_INTR_TIME, "% Interrupt Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_DCP_TIME, "% DCP Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(CPU_PROC_TIME, "% Processor Time", "", Timer100NsInverse, unused)
PERFCTR_CAT(PROC, "Process", "", MultiInstance, Process, PROC_USER_TIME)
PERFCTR_COUNTER(PROC_USER_TIME, "% User Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_PRIV_TIME, "% Privileged Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_PROC_TIME, "% Processor Time", "", Timer100Ns, unused)
PERFCTR_COUNTER(PROC_THREADS, "Thread Count", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_VBYTES, "Virtual Bytes", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_WSET, "Working Set", "", NumberOfItems64, unused)
PERFCTR_COUNTER(PROC_PBYTES, "Private Bytes", "", NumberOfItems64, unused)
/* sample runtime counter */
PERFCTR_CAT(MONO_MEM, "Mono Memory", "", SingleInstance, Mono, MEM_NUM_OBJECTS)
PERFCTR_COUNTER(MEM_NUM_OBJECTS, "Allocated Objects", "", NumberOfItems64, unused)
PERFCTR_COUNTER(MEM_PHYS_TOTAL, "Total Physical Memory", "Physical memory installed in the machine, in bytes", NumberOfItems64, unused)
PERFCTR_COUNTER(MEM_PHYS_AVAILABLE, "Available Physical Memory", "Physical memory available in the machine, in bytes", NumberOfItems64, unused)
PERFCTR_CAT(ASPNET, "ASP.NET", "", MultiInstance, Mono, ASPNET_REQ_Q)
PERFCTR_COUNTER(ASPNET_REQ_Q, "Requests Queued", "", NumberOfItems64, aspnet_requests_queued)
PERFCTR_COUNTER(ASPNET_REQ_TOTAL, "Requests Total", "", NumberOfItems32, aspnet_requests)
PERFCTR_COUNTER(ASPNET_REQ_PSEC, "Requests/Sec", "", RateOfCountsPerSecond32, aspnet_requests)
PERFCTR_CAT(JIT, ".NET CLR JIT", "", MultiInstance, Mono, JIT_BYTES)
PERFCTR_COUNTER(JIT_BYTES, "# of IL Bytes JITted", "", NumberOfItems32, jit_bytes)
PERFCTR_COUNTER(JIT_METHODS, "# of IL Methods JITted", "", NumberOfItems32, jit_methods)
PERFCTR_COUNTER(JIT_TIME, "% Time in JIT", "", RawFraction, jit_time)
PERFCTR_COUNTER(JIT_BYTES_PSEC, "IL Bytes Jitted/Sec", "", RateOfCountsPerSecond32, jit_bytes)
PERFCTR_COUNTER(JIT_FAILURES, "Standard Jit Failures", "", NumberOfItems32, jit_failures)
PERFCTR_CAT(EXC, ".NET CLR Exceptions", "", MultiInstance, Mono, EXC_THROWN)
PERFCTR_COUNTER(EXC_THROWN, "# of Exceps Thrown", "", NumberOfItems32, exceptions_thrown)
PERFCTR_COUNTER(EXC_THROWN_PSEC, "# of Exceps Thrown/Sec", "", RateOfCountsPerSecond32, exceptions_thrown)
PERFCTR_COUNTER(EXC_FILTERS_PSEC, "# of Filters/Sec", "", RateOfCountsPerSecond32, exceptions_filters)
PERFCTR_COUNTER(EXC_FINALLYS_PSEC, "# of Finallys/Sec", "", RateOfCountsPerSecond32, exceptions_finallys)
PERFCTR_COUNTER(EXC_CATCH_DEPTH, "Throw to Catch Depth/Sec", "", NumberOfItems32, exceptions_depth)
PERFCTR_CAT(GC, ".NET CLR Memory", "", MultiInstance, Mono, GC_GEN0)
PERFCTR_COUNTER(GC_GEN0, "# Gen 0 Collections", "", NumberOfItems32, gc_collections0)
PERFCTR_COUNTER(GC_GEN1, "# Gen 1 Collections", "", NumberOfItems32, gc_collections1)
PERFCTR_COUNTER(GC_GEN2, "# Gen 2 Collections", "", NumberOfItems32, gc_collections2)
PERFCTR_COUNTER(GC_PROM0, "Promoted Memory from Gen 0", "", NumberOfItems32, gc_promotions0)
PERFCTR_COUNTER(GC_PROM1, "Promoted Memory from Gen 1", "", NumberOfItems32, gc_promotions1)
PERFCTR_COUNTER(GC_PROM0SEC, "Gen 0 Promoted Bytes/Sec", "", RateOfCountsPerSecond32, gc_promotions0)
PERFCTR_COUNTER(GC_PROM1SEC, "Gen 1 Promoted Bytes/Sec", "", RateOfCountsPerSecond32, gc_promotions1)
PERFCTR_COUNTER(GC_PROMFIN, "Promoted Finalization-Memory from Gen 0", "", NumberOfItems32, gc_promotion_finalizers)
PERFCTR_COUNTER(GC_GEN0SIZE, "Gen 0 heap size", "", NumberOfItems64, gc_gen0size)
PERFCTR_COUNTER(GC_GEN1SIZE, "Gen 1 heap size", "", NumberOfItems64, gc_gen1size)
PERFCTR_COUNTER(GC_GEN2SIZE, "Gen 2 heap size", "", NumberOfItems64, gc_gen2size)
PERFCTR_COUNTER(GC_LOSIZE, "Large Object Heap size", "", NumberOfItems32, gc_lossize)
PERFCTR_COUNTER(GC_FINSURV, "Finalization Survivors", "", NumberOfItems32, gc_fin_survivors)
PERFCTR_COUNTER(GC_NHANDLES, "# GC Handles", "", NumberOfItems32, gc_num_handles)
PERFCTR_COUNTER(GC_BYTESSEC, "Allocated Bytes/sec", "", RateOfCountsPerSecond32, gc_allocated)
PERFCTR_COUNTER(GC_INDGC, "# Induced GC", "", NumberOfItems32, gc_induced)
PERFCTR_COUNTER(GC_PERCTIME, "% Time in GC", "", RawFraction, gc_time)
PERFCTR_COUNTER(GC_BYTES, "# Bytes in all Heaps", "", NumberOfItems64, gc_total_bytes)
PERFCTR_COUNTER(GC_COMMBYTES, "# Total committed Bytes", "", NumberOfItems64, gc_committed_bytes)
PERFCTR_COUNTER(GC_RESBYTES, "# Total reserved Bytes", "", NumberOfItems64, gc_reserved_bytes)
PERFCTR_COUNTER(GC_PINNED, "# of Pinned Objects", "", NumberOfItems32, gc_num_pinned)
PERFCTR_COUNTER(GC_SYNKB, "# of Sink Blocks in use", "", NumberOfItems32, gc_sync_blocks)
PERFCTR_CAT(LOADING, ".NET CLR Loading", "", MultiInstance, Mono, LOADING_CLASSES)
PERFCTR_COUNTER(LOADING_CLASSES, "Current Classes Loaded", "", NumberOfItems32, loader_classes)
PERFCTR_COUNTER(LOADING_TOTCLASSES, "Total Classes Loaded", "", NumberOfItems32, loader_total_classes)
PERFCTR_COUNTER(LOADING_CLASSESSEC, "Rate of Classes Loaded", "", RateOfCountsPerSecond32, loader_total_classes)
PERFCTR_COUNTER(LOADING_APPDOMAINS, "Current appdomains", "", NumberOfItems32, loader_appdomains)
PERFCTR_COUNTER(LOADING_TOTAPPDOMAINS, "Total Appdomains", "", NumberOfItems32, loader_total_appdomains)
PERFCTR_COUNTER(LOADING_APPDOMAINSEC, "Rate of appdomains", "", RateOfCountsPerSecond32, loader_total_appdomains)
PERFCTR_COUNTER(LOADING_ASSEMBLIES, "Current Assemblies", "", NumberOfItems32, loader_assemblies)
PERFCTR_COUNTER(LOADING_TOTASSEMBLIES, "Total Assemblies", "", NumberOfItems32, loader_total_assemblies)
PERFCTR_COUNTER(LOADING_ASSEMBLIESEC, "Rate of Assemblies", "", RateOfCountsPerSecond32, loader_total_assemblies)
PERFCTR_COUNTER(LOADING_FAILURES, "Total # of Load Failures", "", NumberOfItems32, loader_failures)
PERFCTR_COUNTER(LOADING_FAILURESSEC, "Rate of Load Failures", "", RateOfCountsPerSecond32, loader_failures)
PERFCTR_COUNTER(LOADING_BYTES, "Bytes in Loader Heap", "", NumberOfItems32, loader_bytes)
PERFCTR_COUNTER(LOADING_APPUNLOADED, "Total appdomains unloaded", "", NumberOfItems32, loader_appdomains_uloaded)
PERFCTR_COUNTER(LOADING_APPUNLOADEDSEC, "Rate of appdomains unloaded", "", RateOfCountsPerSecond32, loader_appdomains_uloaded)
PERFCTR_CAT(THREAD, ".NET CLR LocksAndThreads", "", MultiInstance, Mono, THREAD_CONTENTIONS)
PERFCTR_COUNTER(THREAD_CONTENTIONS, "Total # of Contentions", "", NumberOfItems32, thread_contentions)
PERFCTR_COUNTER(THREAD_CONTENTIONSSEC, "Contention Rate / sec", "", RateOfCountsPerSecond32, thread_contentions)
PERFCTR_COUNTER(THREAD_QUEUELEN, "Current Queue Length", "", NumberOfItems32, thread_queue_len)
PERFCTR_COUNTER(THREAD_QUEUELENP, "Queue Length Peak", "", NumberOfItems32, thread_queue_max)
PERFCTR_COUNTER(THREAD_QUEUELENSEC, "Queue Length / sec", "", RateOfCountsPerSecond32, thread_queue_max)
PERFCTR_COUNTER(THREAD_NUMLOG, "# of current logical Threads", "", NumberOfItems32, thread_num_logical)
PERFCTR_COUNTER(THREAD_NUMPHYS, "# of current physical Threads", "", NumberOfItems32, thread_num_physical)
PERFCTR_COUNTER(THREAD_NUMREC, "# of current recognized threads", "", NumberOfItems32, thread_cur_recognized)
PERFCTR_COUNTER(THREAD_TOTREC, "# of total recognized threads", "", NumberOfItems32, thread_num_recognized)
PERFCTR_COUNTER(THREAD_TOTRECSEC, "rate of recognized threads / sec", "", RateOfCountsPerSecond32, thread_num_recognized)
PERFCTR_CAT(INTEROP, ".NET CLR Interop", "", MultiInstance, Mono, INTEROP_NUMCCW)
PERFCTR_COUNTER(INTEROP_NUMCCW, "# of CCWs", "", NumberOfItems32, interop_num_ccw)
PERFCTR_COUNTER(INTEROP_STUBS, "# of Stubs", "", NumberOfItems32, interop_num_stubs)
PERFCTR_COUNTER(INTEROP_MARSH, "# of marshalling", "", NumberOfItems32, interop_num_marshals)
PERFCTR_CAT(SECURITY, ".NET CLR Security", "", MultiInstance, Mono, SECURITY_CHECKS)
PERFCTR_COUNTER(SECURITY_CHECKS, "Total Runtime Checks", "", NumberOfItems32, security_num_checks)
PERFCTR_COUNTER(SECURITY_LCHECKS, "# Link Time Checks", "", NumberOfItems32, security_num_link_checks)
PERFCTR_COUNTER(SECURITY_PERCTIME, "% Time in RT checks", "", RawFraction, security_time)
PERFCTR_COUNTER(SECURITY_SWDEPTH, "Stack Walk Depth", "", NumberOfItems32, security_depth)
PERFCTR_CAT(THREADPOOL, "Mono Threadpool", "", MultiInstance, Mono, THREADPOOL_WORKITEMS)
PERFCTR_COUNTER(THREADPOOL_WORKITEMS, "Work Items Added", "", NumberOfItems64, threadpool_workitems)
PERFCTR_COUNTER(THREADPOOL_WORKITEMS_PSEC, "Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_workitems)
PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS, "IO Work Items Added", "", NumberOfItems64, threadpool_ioworkitems)
PERFCTR_COUNTER(THREADPOOL_IOWORKITEMS_PSEC, "IO Work Items Added/Sec", "", RateOfCountsPerSecond32, threadpool_ioworkitems)
PERFCTR_COUNTER(THREADPOOL_THREADS, "# of Threads", "", NumberOfItems32, threadpool_threads)
PERFCTR_COUNTER(THREADPOOL_IOTHREADS, "# of IO Threads", "", NumberOfItems32, threadpool_iothreads)
PERFCTR_CAT(NETWORK, "Network Interface", "", MultiInstance, NetworkInterface, NETWORK_BYTESRECSEC)
PERFCTR_COUNTER(NETWORK_BYTESRECSEC, "Bytes Received/sec", "", RateOfCountsPerSecond64, unused)
PERFCTR_COUNTER(NETWORK_BYTESSENTSEC, "Bytes Sent/sec", "", RateOfCountsPerSecond64, unused)
PERFCTR_COUNTER(NETWORK_BYTESTOTALSEC, "Bytes Total/sec", "", RateOfCountsPerSecond64, unused)
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/coreclr/ildasm/dasm_sz.h
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _DASM_SZ_H_
#define _DASM_SZ_H_
unsigned SizeOfValueType(mdToken tk, IMDInternalImport* pImport);
unsigned SizeOfField(mdToken tk, IMDInternalImport* pImport);
unsigned SizeOfField(PCCOR_SIGNATURE *ppSig, ULONG cSig, IMDInternalImport* pImport);
#endif
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef _DASM_SZ_H_
#define _DASM_SZ_H_
unsigned SizeOfValueType(mdToken tk, IMDInternalImport* pImport);
unsigned SizeOfField(mdToken tk, IMDInternalImport* pImport);
unsigned SizeOfField(PCCOR_SIGNATURE *ppSig, ULONG cSig, IMDInternalImport* pImport);
#endif
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/EndpointChannelBindingToken.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
internal static class EndpointChannelBindingToken
{
internal static ChannelBinding? Build(SafeDeleteContext securityContext)
{
using (X509Certificate2? cert = CertificateValidationPal.GetRemoteCertificate(securityContext))
{
if (cert == null)
return null;
SafeChannelBindingHandle bindingHandle = new SafeChannelBindingHandle(ChannelBindingKind.Endpoint);
byte[] bindingHash = GetHashForChannelBinding(cert);
bindingHandle.SetCertHash(bindingHash);
return bindingHandle;
}
}
private static byte[] GetHashForChannelBinding(X509Certificate2 cert)
{
Oid signatureAlgorithm = cert.SignatureAlgorithm;
switch (signatureAlgorithm.Value)
{
// RFC 5929 4.1 says that MD5 and SHA1 both upgrade to SHA256 for cbt calculation
case "1.2.840.113549.2.5": // MD5
case "1.2.840.113549.1.1.4": // MD5RSA
case "1.3.14.3.2.26": // SHA1
case "1.2.840.10040.4.3": // SHA1DSA
case "1.2.840.10045.4.1": // SHA1ECDSA
case "1.2.840.113549.1.1.5": // SHA1RSA
case "2.16.840.1.101.3.4.2.1": // SHA256
case "1.2.840.10045.4.3.2": // SHA256ECDSA
case "1.2.840.113549.1.1.11": // SHA256RSA
return SHA256.HashData(cert.RawDataMemory.Span);
case "2.16.840.1.101.3.4.2.2": // SHA384
case "1.2.840.10045.4.3.3": // SHA384ECDSA
case "1.2.840.113549.1.1.12": // SHA384RSA
return SHA384.HashData(cert.RawDataMemory.Span);
case "2.16.840.1.101.3.4.2.3": // SHA512
case "1.2.840.10045.4.3.4": // SHA512ECDSA
case "1.2.840.113549.1.1.13": // SHA512RSA
return SHA512.HashData(cert.RawDataMemory.Span);
default:
throw new ArgumentException(signatureAlgorithm.Value);
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
internal static class EndpointChannelBindingToken
{
internal static ChannelBinding? Build(SafeDeleteContext securityContext)
{
using (X509Certificate2? cert = CertificateValidationPal.GetRemoteCertificate(securityContext))
{
if (cert == null)
return null;
SafeChannelBindingHandle bindingHandle = new SafeChannelBindingHandle(ChannelBindingKind.Endpoint);
byte[] bindingHash = GetHashForChannelBinding(cert);
bindingHandle.SetCertHash(bindingHash);
return bindingHandle;
}
}
private static byte[] GetHashForChannelBinding(X509Certificate2 cert)
{
Oid signatureAlgorithm = cert.SignatureAlgorithm;
switch (signatureAlgorithm.Value)
{
// RFC 5929 4.1 says that MD5 and SHA1 both upgrade to SHA256 for cbt calculation
case "1.2.840.113549.2.5": // MD5
case "1.2.840.113549.1.1.4": // MD5RSA
case "1.3.14.3.2.26": // SHA1
case "1.2.840.10040.4.3": // SHA1DSA
case "1.2.840.10045.4.1": // SHA1ECDSA
case "1.2.840.113549.1.1.5": // SHA1RSA
case "2.16.840.1.101.3.4.2.1": // SHA256
case "1.2.840.10045.4.3.2": // SHA256ECDSA
case "1.2.840.113549.1.1.11": // SHA256RSA
return SHA256.HashData(cert.RawDataMemory.Span);
case "2.16.840.1.101.3.4.2.2": // SHA384
case "1.2.840.10045.4.3.3": // SHA384ECDSA
case "1.2.840.113549.1.1.12": // SHA384RSA
return SHA384.HashData(cert.RawDataMemory.Span);
case "2.16.840.1.101.3.4.2.3": // SHA512
case "1.2.840.10045.4.3.4": // SHA512ECDSA
case "1.2.840.113549.1.1.13": // SHA512RSA
return SHA512.HashData(cert.RawDataMemory.Span);
default:
throw new ArgumentException(signatureAlgorithm.Value);
}
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/Interop/DisabledRuntimeMarshalling/DisabledRuntimeMarshallingNative.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
struct StructWithShortAndBool
{
bool b;
short s;
// Make sure we don't have any cases where the native code could return a value of this type one way,
// but an invalid managed declaration would expect it differently. This ensures that test failures won't be
// due to crashes from a mismatched return scheme in the calling convention.
int padding;
};
struct StructWithWCharAndShort
{
short s;
WCHAR c;
};
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithShortAndBool(StructWithShortAndBool str, short s, bool b)
{
return str.s == s && str.b == b;
}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithWCharAndShort(StructWithWCharAndShort str, short s, WCHAR c)
{
return str.s == s && str.c == c;
}
using CheckStructWithShortAndBoolCallback = bool (STDMETHODCALLTYPE*)(StructWithShortAndBool, short, bool);
extern "C" DLL_EXPORT CheckStructWithShortAndBoolCallback STDMETHODCALLTYPE GetStructWithShortAndBoolCallback()
{
return &CheckStructWithShortAndBool;
}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CallCheckStructWithShortAndBoolCallback(CheckStructWithShortAndBoolCallback cb, StructWithShortAndBool str, short s, bool b)
{
return cb(str, s, b);
}
extern "C" DLL_EXPORT BYTE PassThrough(BYTE b)
{
return b;
}
extern "C" DLL_EXPORT void Invalid(...) {}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithShortAndBoolWithVariantBool(StructWithShortAndBool str, short s, VARIANT_BOOL b)
{
// Specifically use VARIANT_TRUE here as invalid marshalling (in the "disabled runtime marshalling" case) will incorrectly marshal VARAINT_TRUE
// but could accidentally marshal VARIANT_FALSE correctly since it is 0, which is the same representation as a zero or sign extension of the C# false value.
return str.s == s && str.b == (b == VARIANT_TRUE);
}
using CheckStructWithShortAndBoolWithVariantBoolCallback = bool (STDMETHODCALLTYPE*)(StructWithShortAndBool, short, VARIANT_BOOL);
extern "C" DLL_EXPORT CheckStructWithShortAndBoolWithVariantBoolCallback STDMETHODCALLTYPE GetStructWithShortAndBoolWithVariantBoolCallback()
{
return &CheckStructWithShortAndBoolWithVariantBool;
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include <xplatform.h>
struct StructWithShortAndBool
{
bool b;
short s;
// Make sure we don't have any cases where the native code could return a value of this type one way,
// but an invalid managed declaration would expect it differently. This ensures that test failures won't be
// due to crashes from a mismatched return scheme in the calling convention.
int padding;
};
struct StructWithWCharAndShort
{
short s;
WCHAR c;
};
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithShortAndBool(StructWithShortAndBool str, short s, bool b)
{
return str.s == s && str.b == b;
}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithWCharAndShort(StructWithWCharAndShort str, short s, WCHAR c)
{
return str.s == s && str.c == c;
}
using CheckStructWithShortAndBoolCallback = bool (STDMETHODCALLTYPE*)(StructWithShortAndBool, short, bool);
extern "C" DLL_EXPORT CheckStructWithShortAndBoolCallback STDMETHODCALLTYPE GetStructWithShortAndBoolCallback()
{
return &CheckStructWithShortAndBool;
}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CallCheckStructWithShortAndBoolCallback(CheckStructWithShortAndBoolCallback cb, StructWithShortAndBool str, short s, bool b)
{
return cb(str, s, b);
}
extern "C" DLL_EXPORT BYTE PassThrough(BYTE b)
{
return b;
}
extern "C" DLL_EXPORT void Invalid(...) {}
extern "C" DLL_EXPORT bool STDMETHODCALLTYPE CheckStructWithShortAndBoolWithVariantBool(StructWithShortAndBool str, short s, VARIANT_BOOL b)
{
// Specifically use VARIANT_TRUE here as invalid marshalling (in the "disabled runtime marshalling" case) will incorrectly marshal VARAINT_TRUE
// but could accidentally marshal VARIANT_FALSE correctly since it is 0, which is the same representation as a zero or sign extension of the C# false value.
return str.s == s && str.b == (b == VARIANT_TRUE);
}
using CheckStructWithShortAndBoolWithVariantBoolCallback = bool (STDMETHODCALLTYPE*)(StructWithShortAndBool, short, VARIANT_BOOL);
extern "C" DLL_EXPORT CheckStructWithShortAndBoolWithVariantBoolCallback STDMETHODCALLTYPE GetStructWithShortAndBoolWithVariantBoolCallback()
{
return &CheckStructWithShortAndBoolWithVariantBool;
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_71.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 5 -dp 0.0 -dw 0.4</CLRTestExecutionArguments>
<IsGCSimulatorTest>true</IsGCSimulatorTest>
<CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="GCSimulator.cs" />
<Compile Include="lifetimefx.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GCStressIncompatible>true</GCStressIncompatible>
<CLRTestExecutionArguments>-t 3 -tp 0 -dz 17 -sdz 8500 -dc 10000 -sdc 5000 -lt 5 -dp 0.0 -dw 0.4</CLRTestExecutionArguments>
<IsGCSimulatorTest>true</IsGCSimulatorTest>
<CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="GCSimulator.cs" />
<Compile Include="lifetimefx.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/Methodical/NaN/arithm32_r.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="arithm32.cs" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="arithm32.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/Loader/classloader/rmv/il/RMV-2-5-8-two.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="RMV-2-5-8-two.il" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="RMV-2-5-8-two.il" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobWriterImpl.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System.Reflection.Metadata
{
internal static class BlobWriterImpl
{
internal const int SingleByteCompressedIntegerMaxValue = 0x7f;
internal const int TwoByteCompressedIntegerMaxValue = 0x3fff;
internal const int MaxCompressedIntegerValue = 0x1fffffff;
internal const int MinSignedCompressedIntegerValue = unchecked((int)0xF0000000);
internal const int MaxSignedCompressedIntegerValue = 0x0FFFFFFF;
internal static int GetCompressedIntegerSize(int value)
{
Debug.Assert(value <= MaxCompressedIntegerValue);
if (value <= SingleByteCompressedIntegerMaxValue)
{
return 1;
}
if (value <= TwoByteCompressedIntegerMaxValue)
{
return 2;
}
return 4;
}
internal static void WriteCompressedInteger(ref BlobWriter writer, uint value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedInteger(BlobBuilder writer, uint value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(ref BlobWriter writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteConstant(ref BlobWriter writer, object? value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
internal static void WriteConstant(BlobBuilder writer, object? value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
namespace System.Reflection.Metadata
{
internal static class BlobWriterImpl
{
internal const int SingleByteCompressedIntegerMaxValue = 0x7f;
internal const int TwoByteCompressedIntegerMaxValue = 0x3fff;
internal const int MaxCompressedIntegerValue = 0x1fffffff;
internal const int MinSignedCompressedIntegerValue = unchecked((int)0xF0000000);
internal const int MaxSignedCompressedIntegerValue = 0x0FFFFFFF;
internal static int GetCompressedIntegerSize(int value)
{
Debug.Assert(value <= MaxCompressedIntegerValue);
if (value <= SingleByteCompressedIntegerMaxValue)
{
return 1;
}
if (value <= TwoByteCompressedIntegerMaxValue)
{
return 2;
}
return 4;
}
internal static void WriteCompressedInteger(ref BlobWriter writer, uint value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedInteger(BlobBuilder writer, uint value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(ref BlobWriter writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteConstant(ref BlobWriter writer, object? value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
internal static void WriteConstant(BlobBuilder writer, object? value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/libraries/System.Private.CoreLib/gen/EventSourceGenerator.cs
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Generators
{
[Generator]
public partial class EventSourceGenerator : ISourceGenerator
{
// Example input:
//
// [EventSource(Guid = "49592C0F-5A05-516D-AA4B-A64E02026C89", Name = "System.Runtime")]
// [EventSourceAutoGenerate]
// internal sealed partial class RuntimeEventSource : EventSource
//
// Example generated output:
//
// using System;
//
// namespace System.Diagnostics.Tracing
// {
// partial class RuntimeEventSource
// {
// private RuntimeEventSource() : base(new Guid(0x49592c0f,0x5a05,0x516d,0xaa,0x4b,0xa6,0x4e,0x02,0x02,0x6c,0x89), "System.Runtime") { }
//
// private protected override ReadOnlySpan<byte> ProviderMetadata => new byte[] { 0x11, 0x0, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x0, };
// }
// }
public void Initialize(GeneratorInitializationContext context)
=> context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
public void Execute(GeneratorExecutionContext context)
{
SyntaxReceiver? receiver = context.SyntaxReceiver as SyntaxReceiver;
if ((receiver?.CandidateClasses?.Count ?? 0) == 0)
{
// nothing to do yet
return;
}
Parser? p = new Parser(context.Compilation, context.ReportDiagnostic, context.CancellationToken);
EventSourceClass[]? eventSources = p.GetEventSourceClasses(receiver.CandidateClasses);
if (eventSources?.Length > 0)
{
Emitter? e = new Emitter(context);
e.Emit(eventSources, context.CancellationToken);
}
}
private sealed class SyntaxReceiver : ISyntaxReceiver
{
private List<ClassDeclarationSyntax>? _candidateClasses;
public List<ClassDeclarationSyntax>? CandidateClasses => _candidateClasses;
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Only add classes annotated [EventSourceAutoGenerate] to reduce busy work.
const string EventSourceAttribute = "EventSourceAutoGenerateAttribute";
const string EventSourceAttributeShort = "EventSourceAutoGenerate";
// Only classes
if (syntaxNode is ClassDeclarationSyntax classDeclaration)
{
// Check if has EventSource attribute before adding to candidates
// as we don't want to add every class in the project
foreach (AttributeListSyntax? cal in classDeclaration.AttributeLists)
{
foreach (AttributeSyntax? ca in cal.Attributes)
{
// Check if Span length matches before allocating the string to check more
int length = ca.Name.Span.Length;
if (length != EventSourceAttribute.Length && length != EventSourceAttributeShort.Length)
{
continue;
}
// Possible match, now check the string value
string attrName = ca.Name.ToString();
if (attrName == EventSourceAttribute || attrName == EventSourceAttributeShort)
{
// Match add to candidates
_candidateClasses ??= new List<ClassDeclarationSyntax>();
_candidateClasses.Add(classDeclaration);
return;
}
}
}
}
}
}
private sealed class EventSourceClass
{
public string Namespace = string.Empty;
public string ClassName = string.Empty;
public string SourceName = string.Empty;
public Guid Guid = Guid.Empty;
}
}
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Generators
{
[Generator]
public partial class EventSourceGenerator : ISourceGenerator
{
// Example input:
//
// [EventSource(Guid = "49592C0F-5A05-516D-AA4B-A64E02026C89", Name = "System.Runtime")]
// [EventSourceAutoGenerate]
// internal sealed partial class RuntimeEventSource : EventSource
//
// Example generated output:
//
// using System;
//
// namespace System.Diagnostics.Tracing
// {
// partial class RuntimeEventSource
// {
// private RuntimeEventSource() : base(new Guid(0x49592c0f,0x5a05,0x516d,0xaa,0x4b,0xa6,0x4e,0x02,0x02,0x6c,0x89), "System.Runtime") { }
//
// private protected override ReadOnlySpan<byte> ProviderMetadata => new byte[] { 0x11, 0x0, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x2e, 0x52, 0x75, 0x6e, 0x74, 0x69, 0x6d, 0x65, 0x0, };
// }
// }
public void Initialize(GeneratorInitializationContext context)
=> context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
public void Execute(GeneratorExecutionContext context)
{
SyntaxReceiver? receiver = context.SyntaxReceiver as SyntaxReceiver;
if ((receiver?.CandidateClasses?.Count ?? 0) == 0)
{
// nothing to do yet
return;
}
Parser? p = new Parser(context.Compilation, context.ReportDiagnostic, context.CancellationToken);
EventSourceClass[]? eventSources = p.GetEventSourceClasses(receiver.CandidateClasses);
if (eventSources?.Length > 0)
{
Emitter? e = new Emitter(context);
e.Emit(eventSources, context.CancellationToken);
}
}
private sealed class SyntaxReceiver : ISyntaxReceiver
{
private List<ClassDeclarationSyntax>? _candidateClasses;
public List<ClassDeclarationSyntax>? CandidateClasses => _candidateClasses;
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Only add classes annotated [EventSourceAutoGenerate] to reduce busy work.
const string EventSourceAttribute = "EventSourceAutoGenerateAttribute";
const string EventSourceAttributeShort = "EventSourceAutoGenerate";
// Only classes
if (syntaxNode is ClassDeclarationSyntax classDeclaration)
{
// Check if has EventSource attribute before adding to candidates
// as we don't want to add every class in the project
foreach (AttributeListSyntax? cal in classDeclaration.AttributeLists)
{
foreach (AttributeSyntax? ca in cal.Attributes)
{
// Check if Span length matches before allocating the string to check more
int length = ca.Name.Span.Length;
if (length != EventSourceAttribute.Length && length != EventSourceAttributeShort.Length)
{
continue;
}
// Possible match, now check the string value
string attrName = ca.Name.ToString();
if (attrName == EventSourceAttribute || attrName == EventSourceAttributeShort)
{
// Match add to candidates
_candidateClasses ??= new List<ClassDeclarationSyntax>();
_candidateClasses.Add(classDeclaration);
return;
}
}
}
}
}
}
private sealed class EventSourceClass
{
public string Namespace = string.Empty;
public string ClassName = string.Empty;
public string SourceName = string.Empty;
public Guid Guid = Guid.Empty;
}
}
}
| -1 |
dotnet/runtime
| 66,431 |
Enable/fix compiler warning 4996 in host
|
Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
elinor-fung
| 2022-03-10T03:32:13Z | 2022-03-10T21:23:56Z |
0046648f91cd1b393c5d852789fbb16477ba4256
|
6cb2ae678fd4d2555b05edf611c7d5fa48cdc8a3
|
Enable/fix compiler warning 4996 in host. Contributes to https://github.com/dotnet/runtime/issues/66154
cc @GrabYourPitchforks @AaronRobinsonMSFT
|
./src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_r.ilproj
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="faultbeforetrybody.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\eh_common.csproj" />
</ItemGroup>
</Project>
|
<Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>PdbOnly</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="faultbeforetrybody.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\common\eh_common.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime
| 66,427 |
Remove 4146 from libunwind
|
Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
AaronRobinsonMSFT
| 2022-03-10T01:32:16Z | 2022-03-14T21:00:38Z |
7e1dd58065e624dd3431c9dcbde9e30b3b5beaed
|
c3d393250cd63a679405fa9e35684772cbf2e1ef
|
Remove 4146 from libunwind. Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
./src/coreclr/pal/src/libunwind/CMakeLists.txt
|
# This is a custom file written for .NET Core's build system
# It overwrites the one found in upstream
project(unwind)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# define variables for the configure_file below
set(PKG_MAJOR "1")
set(PKG_MINOR "5")
set(PKG_EXTRA "-rc2")
# The HAVE___THREAD set to 1 causes creation of thread local variable with tls_model("initial-exec")
# which is incompatible with usage of the unwind code in a shared library.
add_definitions(-DHAVE___THREAD=0)
add_definitions(-D_GNU_SOURCE)
add_definitions(-DPACKAGE_STRING="")
add_definitions(-DPACKAGE_BUGREPORT="")
if(CLR_CMAKE_HOST_UNIX)
if (CLR_CMAKE_HOST_ARCH_AMD64)
set(arch x86_64)
elseif(CLR_CMAKE_HOST_ARCH_ARM64)
set(arch aarch64)
elseif(CLR_CMAKE_HOST_ARCH_ARM)
set(arch arm)
elseif(CLR_CMAKE_HOST_ARCH_ARMV6)
set(arch arm)
elseif(CLR_CMAKE_HOST_ARCH_I386)
set(arch x86)
elseif(CLR_CMAKE_HOST_ARCH_S390X)
set(arch s390x)
elseif(CLR_CMAKE_HOST_ARCH_LOONGARCH64)
set(arch loongarch64)
endif ()
# Disable warning due to incorrect format specifier in debugging printf via the Debug macro
add_compile_options(-Wno-format -Wno-format-security)
add_compile_options(-Wno-implicit-fallthrough)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wno-header-guard)
else()
add_compile_options(-Wno-unused-value)
add_compile_options(-Wno-unused-result)
add_compile_options(-Wno-implicit-function-declaration)
add_compile_options(-Wno-incompatible-pointer-types)
endif()
if(CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARMV6)
# Ensure that the remote and local unwind code can reside in the same binary without name clashing
add_definitions("-Darm_search_unwind_table=UNW_OBJ(arm_search_unwind_table)")
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# Disable warning due to labs function called on unsigned argument
add_compile_options(-Wno-absolute-value)
# Disable warning in asm: use of SP or PC in the list is deprecated
add_compile_options(-Wno-inline-asm)
endif()
# Disable warning for a bug in the libunwind source src/arm/Gtrace.c:529, but not in code that we exercise
add_compile_options(-Wno-implicit-function-declaration)
# Disable warning due to an unused function prel31_read
add_compile_options(-Wno-unused-function)
# We compile code with -std=c99 and the asm keyword is not recognized as it is a gnu extension
add_definitions(-Dasm=__asm__)
elseif(CLR_CMAKE_HOST_ARCH_ARM64)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# Disable warning due to labs function called on unsigned argument
add_compile_options(-Wno-absolute-value)
endif()
# We compile code with -std=c99 and the asm keyword is not recognized as it is a gnu extension
add_definitions(-Dasm=__asm__)
# Disable warning for a bug in the libunwind source src/aarch64/Ginit.c, but not in code that we exercise
add_compile_options(-Wno-incompatible-pointer-types)
elseif(CLR_CMAKE_HOST_ARCH_I386)
# Disable warning for a bug in the libunwind source src/x86/Gos-linux.c, but not in code that we exercise
add_compile_options(-Wno-incompatible-pointer-types)
elseif(CLR_CMAKE_HOST_ARCH_LOONGARCH64)
###TODO: maybe add options for LOONGARCH64
endif()
if (CLR_CMAKE_HOST_OSX)
add_definitions(-DUNW_REMOTE_ONLY)
add_compile_options(-Wno-sometimes-uninitialized)
add_compile_options(-Wno-implicit-function-declaration)
# Our posix abstraction layer will provide these headers
set(HAVE_ELF_H 1)
set(HAVE_ENDIAN_H 1)
# include paths
include_directories(include/tdep)
include_directories(include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/tdep)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
# files for macos compilation
include_directories(../libunwind_mac/include)
endif(CLR_CMAKE_HOST_OSX)
endif(CLR_CMAKE_HOST_UNIX)
if(CLR_CMAKE_HOST_WIN32)
if (CLR_CMAKE_TARGET_ARCH_AMD64)
set(TARGET_AMD64 1)
set(arch x86_64)
add_definitions(-D__x86_64__)
add_definitions(-D__amd64__)
elseif(CLR_CMAKE_TARGET_ARCH_ARM64)
set(TARGET_AARCH64 1)
set(arch aarch64)
add_definitions(-D__aarch64__)
elseif(CLR_CMAKE_TARGET_ARCH_ARM)
set(TARGET_ARM 1)
set(arch arm)
add_definitions(-D__arm__)
elseif(CLR_CMAKE_TARGET_ARCH_ARMV6)
set(TARGET_ARM 1)
set(arch arm)
add_definitions(-D__arm__)
elseif(CLR_CMAKE_TARGET_ARCH_S390X)
set(TARGET_S390X 1)
set(arch s390x)
add_definitions(-D__s390x__)
else ()
message(FATAL_ERROR "Unrecognized TARGET")
endif ()
# Windows builds will only support remote unwind
add_definitions(-DUNW_REMOTE_ONLY)
add_definitions(-DHAVE_UNW_GET_ACCESSORS)
# Disable security warnings
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
if(CLR_CMAKE_TARGET_LINUX)
add_definitions(-D__linux__)
endif ()
# Assume we are using default MSVC compiler
add_compile_options(/TC) # compile all files as C
add_compile_options(/permissive-)
# include paths
include_directories(include/tdep)
include_directories(include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/tdep)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
# files for cross os compilation
include_directories(include/win)
add_definitions(-D_CRT_DECLARE_NONSTDC_NAMES)
# Warnings in release builds
add_compile_options(-wd4068) # ignore unknown pragma warnings (gcc pragmas)
add_compile_options(-wd4146) # minus operator applied to unsigned
add_compile_options(-wd4244) # possible loss of data
add_compile_options(-wd4334) # 32-bit shift implicitly converted to 64 bits
# Disable warning due to incorrect format specifier in debugging printf via the Debug macro
add_compile_options(-wd4311) # pointer truncation from 'unw_word_t *' to 'long'
add_compile_options(-wd4475) # 'fprintf' : length modifier 'L' cannot be used
add_compile_options(-wd4477) # fprintf argument type
endif (CLR_CMAKE_HOST_WIN32)
if(CLR_CMAKE_TARGET_ARCH_ARM OR CLR_CMAKE_TARGET_ARCH_ARMV6)
# The arm sources include ex_tables.h from include/tdep-arm without going through a redirection
# in include/tdep like it works for similar files on other architectures. So we need to add
# the include/tdep-arm to include directories
include_directories(include/tdep-arm)
endif()
include(configure.cmake)
add_subdirectory(src)
|
# This is a custom file written for .NET Core's build system
# It overwrites the one found in upstream
project(unwind)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# define variables for the configure_file below
set(PKG_MAJOR "1")
set(PKG_MINOR "5")
set(PKG_EXTRA "-rc2")
# The HAVE___THREAD set to 1 causes creation of thread local variable with tls_model("initial-exec")
# which is incompatible with usage of the unwind code in a shared library.
add_definitions(-DHAVE___THREAD=0)
add_definitions(-D_GNU_SOURCE)
add_definitions(-DPACKAGE_STRING="")
add_definitions(-DPACKAGE_BUGREPORT="")
if(CLR_CMAKE_HOST_UNIX)
if (CLR_CMAKE_HOST_ARCH_AMD64)
set(arch x86_64)
elseif(CLR_CMAKE_HOST_ARCH_ARM64)
set(arch aarch64)
elseif(CLR_CMAKE_HOST_ARCH_ARM)
set(arch arm)
elseif(CLR_CMAKE_HOST_ARCH_ARMV6)
set(arch arm)
elseif(CLR_CMAKE_HOST_ARCH_I386)
set(arch x86)
elseif(CLR_CMAKE_HOST_ARCH_S390X)
set(arch s390x)
elseif(CLR_CMAKE_HOST_ARCH_LOONGARCH64)
set(arch loongarch64)
endif ()
# Disable warning due to incorrect format specifier in debugging printf via the Debug macro
add_compile_options(-Wno-format -Wno-format-security)
add_compile_options(-Wno-implicit-fallthrough)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wno-header-guard)
else()
add_compile_options(-Wno-unused-value)
add_compile_options(-Wno-unused-result)
add_compile_options(-Wno-implicit-function-declaration)
add_compile_options(-Wno-incompatible-pointer-types)
endif()
if(CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARMV6)
# Ensure that the remote and local unwind code can reside in the same binary without name clashing
add_definitions("-Darm_search_unwind_table=UNW_OBJ(arm_search_unwind_table)")
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# Disable warning due to labs function called on unsigned argument
add_compile_options(-Wno-absolute-value)
# Disable warning in asm: use of SP or PC in the list is deprecated
add_compile_options(-Wno-inline-asm)
endif()
# Disable warning for a bug in the libunwind source src/arm/Gtrace.c:529, but not in code that we exercise
add_compile_options(-Wno-implicit-function-declaration)
# Disable warning due to an unused function prel31_read
add_compile_options(-Wno-unused-function)
# We compile code with -std=c99 and the asm keyword is not recognized as it is a gnu extension
add_definitions(-Dasm=__asm__)
elseif(CLR_CMAKE_HOST_ARCH_ARM64)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# Disable warning due to labs function called on unsigned argument
add_compile_options(-Wno-absolute-value)
endif()
# We compile code with -std=c99 and the asm keyword is not recognized as it is a gnu extension
add_definitions(-Dasm=__asm__)
# Disable warning for a bug in the libunwind source src/aarch64/Ginit.c, but not in code that we exercise
add_compile_options(-Wno-incompatible-pointer-types)
elseif(CLR_CMAKE_HOST_ARCH_I386)
# Disable warning for a bug in the libunwind source src/x86/Gos-linux.c, but not in code that we exercise
add_compile_options(-Wno-incompatible-pointer-types)
elseif(CLR_CMAKE_HOST_ARCH_LOONGARCH64)
###TODO: maybe add options for LOONGARCH64
endif()
if (CLR_CMAKE_HOST_OSX)
add_definitions(-DUNW_REMOTE_ONLY)
add_compile_options(-Wno-sometimes-uninitialized)
add_compile_options(-Wno-implicit-function-declaration)
# Our posix abstraction layer will provide these headers
set(HAVE_ELF_H 1)
set(HAVE_ENDIAN_H 1)
# include paths
include_directories(include/tdep)
include_directories(include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/tdep)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
# files for macos compilation
include_directories(../libunwind_mac/include)
endif(CLR_CMAKE_HOST_OSX)
endif(CLR_CMAKE_HOST_UNIX)
if(CLR_CMAKE_HOST_WIN32)
if (CLR_CMAKE_TARGET_ARCH_AMD64)
set(TARGET_AMD64 1)
set(arch x86_64)
add_definitions(-D__x86_64__)
add_definitions(-D__amd64__)
elseif(CLR_CMAKE_TARGET_ARCH_ARM64)
set(TARGET_AARCH64 1)
set(arch aarch64)
add_definitions(-D__aarch64__)
elseif(CLR_CMAKE_TARGET_ARCH_ARM)
set(TARGET_ARM 1)
set(arch arm)
add_definitions(-D__arm__)
elseif(CLR_CMAKE_TARGET_ARCH_ARMV6)
set(TARGET_ARM 1)
set(arch arm)
add_definitions(-D__arm__)
elseif(CLR_CMAKE_TARGET_ARCH_S390X)
set(TARGET_S390X 1)
set(arch s390x)
add_definitions(-D__s390x__)
else ()
message(FATAL_ERROR "Unrecognized TARGET")
endif ()
# Windows builds will only support remote unwind
add_definitions(-DUNW_REMOTE_ONLY)
add_definitions(-DHAVE_UNW_GET_ACCESSORS)
# Disable security warnings
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
if(CLR_CMAKE_TARGET_LINUX)
add_definitions(-D__linux__)
endif ()
# Assume we are using default MSVC compiler
add_compile_options(/TC) # compile all files as C
add_compile_options(/permissive-)
# include paths
include_directories(include/tdep)
include_directories(include)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include/tdep)
include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
# files for cross os compilation
include_directories(include/win)
add_definitions(-D_CRT_DECLARE_NONSTDC_NAMES)
# Warnings in release builds
add_compile_options(-wd4068) # ignore unknown pragma warnings (gcc pragmas)
add_compile_options(-wd4244) # possible loss of data
add_compile_options(-wd4334) # 32-bit shift implicitly converted to 64 bits
# Disable warning due to incorrect format specifier in debugging printf via the Debug macro
add_compile_options(-wd4311) # pointer truncation from 'unw_word_t *' to 'long'
add_compile_options(-wd4475) # 'fprintf' : length modifier 'L' cannot be used
add_compile_options(-wd4477) # fprintf argument type
endif (CLR_CMAKE_HOST_WIN32)
if(CLR_CMAKE_TARGET_ARCH_ARM OR CLR_CMAKE_TARGET_ARCH_ARMV6)
# The arm sources include ex_tables.h from include/tdep-arm without going through a redirection
# in include/tdep like it works for similar files on other architectures. So we need to add
# the include/tdep-arm to include directories
include_directories(include/tdep-arm)
endif()
include(configure.cmake)
add_subdirectory(src)
| 1 |
dotnet/runtime
| 66,427 |
Remove 4146 from libunwind
|
Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
AaronRobinsonMSFT
| 2022-03-10T01:32:16Z | 2022-03-14T21:00:38Z |
7e1dd58065e624dd3431c9dcbde9e30b3b5beaed
|
c3d393250cd63a679405fa9e35684772cbf2e1ef
|
Remove 4146 from libunwind. Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
./src/coreclr/pal/src/libunwind/include/dwarf_i.h
|
#ifndef DWARF_I_H
#define DWARF_I_H
/* This file contains definitions that cannot be used in code outside
of libunwind. In particular, most inline functions are here
because otherwise they'd generate unresolved references when the
files are compiled with inlining disabled. */
#include "dwarf.h"
#include "libunwind_i.h"
/* Unless we are told otherwise, assume that a "machine address" is
the size of an unw_word_t. */
#ifndef dwarf_addr_size
# define dwarf_addr_size(as) (sizeof (unw_word_t))
#endif
#ifndef dwarf_to_unw_regnum
# define dwarf_to_unw_regnum_map UNW_OBJ (dwarf_to_unw_regnum_map)
extern const uint8_t dwarf_to_unw_regnum_map[DWARF_REGNUM_MAP_LENGTH];
/* REG is evaluated multiple times; it better be side-effects free! */
# define dwarf_to_unw_regnum(reg) \
(((reg) < DWARF_REGNUM_MAP_LENGTH) ? dwarf_to_unw_regnum_map[reg] : 0)
#endif
#ifdef UNW_LOCAL_ONLY
/* In the local-only case, we can let the compiler directly access
memory and don't need to worry about differing byte-order. */
typedef union __attribute__ ((packed))
{
int8_t s8;
int16_t s16;
int32_t s32;
int64_t s64;
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
void *ptr;
}
dwarf_misaligned_value_t;
static inline int
dwarf_reads8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int8_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s8;
*addr += sizeof (mvp->s8);
return 0;
}
static inline int
dwarf_reads16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int16_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s16;
*addr += sizeof (mvp->s16);
return 0;
}
static inline int
dwarf_reads32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int32_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s32;
*addr += sizeof (mvp->s32);
return 0;
}
static inline int
dwarf_reads64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int64_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s64;
*addr += sizeof (mvp->s64);
return 0;
}
static inline int
dwarf_readu8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint8_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u8;
*addr += sizeof (mvp->u8);
return 0;
}
static inline int
dwarf_readu16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint16_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u16;
*addr += sizeof (mvp->u16);
return 0;
}
static inline int
dwarf_readu32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint32_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u32;
*addr += sizeof (mvp->u32);
return 0;
}
static inline int
dwarf_readu64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint64_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u64;
*addr += sizeof (mvp->u64);
return 0;
}
#else /* !UNW_LOCAL_ONLY */
static inline int
dwarf_readu8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint8_t *valp, void *arg)
{
unw_word_t val, aligned_addr = *addr & -sizeof (unw_word_t);
unw_word_t off = *addr - aligned_addr;
int ret;
*addr += 1;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(sizeof (unw_word_t) - 1 - off);
#endif
*valp = (uint8_t) val;
return ret;
}
static inline int
dwarf_readu16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint16_t *val, void *arg)
{
uint8_t v0, v1;
int ret;
if ((ret = dwarf_readu8 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu8 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint16_t) v0 << 8 | v1;
else
*val = (uint16_t) v1 << 8 | v0;
return 0;
}
static inline int
dwarf_readu32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint32_t *val, void *arg)
{
uint16_t v0, v1;
int ret;
if ((ret = dwarf_readu16 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu16 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint32_t) v0 << 16 | v1;
else
*val = (uint32_t) v1 << 16 | v0;
return 0;
}
static inline int
dwarf_readu64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint64_t *val, void *arg)
{
uint32_t v0, v1;
int ret;
if ((ret = dwarf_readu32 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu32 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint64_t) v0 << 32 | v1;
else
*val = (uint64_t) v1 << 32 | v0;
return 0;
}
static inline int
dwarf_reads8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int8_t *val, void *arg)
{
uint8_t uval;
int ret;
if ((ret = dwarf_readu8 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int8_t) uval;
return 0;
}
static inline int
dwarf_reads16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int16_t *val, void *arg)
{
uint16_t uval;
int ret;
if ((ret = dwarf_readu16 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int16_t) uval;
return 0;
}
static inline int
dwarf_reads32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int32_t *val, void *arg)
{
uint32_t uval;
int ret;
if ((ret = dwarf_readu32 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int32_t) uval;
return 0;
}
static inline int
dwarf_reads64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int64_t *val, void *arg)
{
uint64_t uval;
int ret;
if ((ret = dwarf_readu64 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int64_t) uval;
return 0;
}
#endif /* !UNW_LOCAL_ONLY */
static inline int
dwarf_readw (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *val, void *arg)
{
uint32_t u32;
uint64_t u64;
int ret;
switch (dwarf_addr_size (as))
{
case 4:
ret = dwarf_readu32 (as, a, addr, &u32, arg);
if (ret < 0)
return ret;
*val = u32;
return ret;
case 8:
ret = dwarf_readu64 (as, a, addr, &u64, arg);
if (ret < 0)
return ret;
*val = u64;
return ret;
default:
abort ();
}
}
/* Read an unsigned "little-endian base 128" value. See Chapter 7.6
of DWARF spec v3. */
static inline int
dwarf_read_uleb128 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *valp, void *arg)
{
unw_word_t val = 0, shift = 0;
unsigned char byte;
int ret;
do
{
if ((ret = dwarf_readu8 (as, a, addr, &byte, arg)) < 0)
return ret;
val |= ((unw_word_t) byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*valp = val;
return 0;
}
/* Read a signed "little-endian base 128" value. See Chapter 7.6 of
DWARF spec v3. */
static inline int
dwarf_read_sleb128 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *valp, void *arg)
{
unw_word_t val = 0, shift = 0;
unsigned char byte;
int ret;
do
{
if ((ret = dwarf_readu8 (as, a, addr, &byte, arg)) < 0)
return ret;
val |= ((unw_word_t) byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
if (shift < 8 * sizeof (unw_word_t) && (byte & 0x40) != 0)
/* sign-extend negative value */
val |= ((unw_word_t) -1) << shift;
*valp = val;
return 0;
}
static ALWAYS_INLINE int
dwarf_read_encoded_pointer_inlined (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unsigned char encoding,
const unw_proc_info_t *pi,
unw_word_t *valp, void *arg)
{
unw_word_t val, initial_addr = *addr;
uint16_t uval16;
uint32_t uval32;
uint64_t uval64;
int16_t sval16 = 0;
int32_t sval32 = 0;
int64_t sval64 = 0;
int ret;
/* DW_EH_PE_omit and DW_EH_PE_aligned don't follow the normal
format/application encoding. Handle them first. */
if (encoding == DW_EH_PE_omit)
{
*valp = 0;
return 0;
}
else if (encoding == DW_EH_PE_aligned)
{
int size = dwarf_addr_size (as);
*addr = (initial_addr + size - 1) & -size;
return dwarf_readw (as, a, addr, valp, arg);
}
switch (encoding & DW_EH_PE_FORMAT_MASK)
{
case DW_EH_PE_ptr:
if ((ret = dwarf_readw (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_uleb128:
if ((ret = dwarf_read_uleb128 (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_udata2:
if ((ret = dwarf_readu16 (as, a, addr, &uval16, arg)) < 0)
return ret;
val = uval16;
break;
case DW_EH_PE_udata4:
if ((ret = dwarf_readu32 (as, a, addr, &uval32, arg)) < 0)
return ret;
val = uval32;
break;
case DW_EH_PE_udata8:
if ((ret = dwarf_readu64 (as, a, addr, &uval64, arg)) < 0)
return ret;
val = uval64;
break;
case DW_EH_PE_sleb128:
if ((ret = dwarf_read_uleb128 (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_sdata2:
if ((ret = dwarf_reads16 (as, a, addr, &sval16, arg)) < 0)
return ret;
val = sval16;
break;
case DW_EH_PE_sdata4:
if ((ret = dwarf_reads32 (as, a, addr, &sval32, arg)) < 0)
return ret;
val = sval32;
break;
case DW_EH_PE_sdata8:
if ((ret = dwarf_reads64 (as, a, addr, &sval64, arg)) < 0)
return ret;
val = sval64;
break;
default:
Debug (1, "unexpected encoding format 0x%x\n",
encoding & DW_EH_PE_FORMAT_MASK);
return -UNW_EINVAL;
}
if (val == 0)
{
/* 0 is a special value and always absolute. */
*valp = 0;
return 0;
}
switch (encoding & DW_EH_PE_APPL_MASK)
{
case DW_EH_PE_absptr:
break;
case DW_EH_PE_pcrel:
val += initial_addr;
break;
case DW_EH_PE_datarel:
/* XXX For now, assume that data-relative addresses are relative
to the global pointer. */
val += pi->gp;
break;
case DW_EH_PE_funcrel:
val += pi->start_ip;
break;
case DW_EH_PE_textrel:
/* XXX For now we don't support text-rel values. If there is a
platform which needs this, we probably would have to add a
"segbase" member to unw_proc_info_t. */
default:
Debug (1, "unexpected application type 0x%x\n",
encoding & DW_EH_PE_APPL_MASK);
return -UNW_EINVAL;
}
/* Trim off any extra bits. Assume that sign extension isn't
required; the only place it is needed is MIPS kernel space
addresses. */
if (sizeof (val) > dwarf_addr_size (as))
{
assert (dwarf_addr_size (as) == 4);
val = (uint32_t) val;
}
if (encoding & DW_EH_PE_indirect)
{
unw_word_t indirect_addr = val;
if ((ret = dwarf_readw (as, a, &indirect_addr, &val, arg)) < 0)
return ret;
}
*valp = val;
return 0;
}
#endif /* DWARF_I_H */
|
#ifndef DWARF_I_H
#define DWARF_I_H
/* This file contains definitions that cannot be used in code outside
of libunwind. In particular, most inline functions are here
because otherwise they'd generate unresolved references when the
files are compiled with inlining disabled. */
#include "dwarf.h"
#include "libunwind_i.h"
/* Unless we are told otherwise, assume that a "machine address" is
the size of an unw_word_t. */
#ifndef dwarf_addr_size
# define dwarf_addr_size(as) (sizeof (unw_word_t))
#endif
#ifndef dwarf_to_unw_regnum
# define dwarf_to_unw_regnum_map UNW_OBJ (dwarf_to_unw_regnum_map)
extern const uint8_t dwarf_to_unw_regnum_map[DWARF_REGNUM_MAP_LENGTH];
/* REG is evaluated multiple times; it better be side-effects free! */
# define dwarf_to_unw_regnum(reg) \
(((reg) < DWARF_REGNUM_MAP_LENGTH) ? dwarf_to_unw_regnum_map[reg] : 0)
#endif
#ifdef UNW_LOCAL_ONLY
/* In the local-only case, we can let the compiler directly access
memory and don't need to worry about differing byte-order. */
typedef union __attribute__ ((packed))
{
int8_t s8;
int16_t s16;
int32_t s32;
int64_t s64;
uint8_t u8;
uint16_t u16;
uint32_t u32;
uint64_t u64;
void *ptr;
}
dwarf_misaligned_value_t;
static inline int
dwarf_reads8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int8_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s8;
*addr += sizeof (mvp->s8);
return 0;
}
static inline int
dwarf_reads16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int16_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s16;
*addr += sizeof (mvp->s16);
return 0;
}
static inline int
dwarf_reads32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int32_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s32;
*addr += sizeof (mvp->s32);
return 0;
}
static inline int
dwarf_reads64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int64_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->s64;
*addr += sizeof (mvp->s64);
return 0;
}
static inline int
dwarf_readu8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint8_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u8;
*addr += sizeof (mvp->u8);
return 0;
}
static inline int
dwarf_readu16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint16_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u16;
*addr += sizeof (mvp->u16);
return 0;
}
static inline int
dwarf_readu32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint32_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u32;
*addr += sizeof (mvp->u32);
return 0;
}
static inline int
dwarf_readu64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint64_t *val, void *arg)
{
dwarf_misaligned_value_t *mvp = (void *) (uintptr_t) *addr;
*val = mvp->u64;
*addr += sizeof (mvp->u64);
return 0;
}
#else /* !UNW_LOCAL_ONLY */
static inline int
dwarf_readu8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint8_t *valp, void *arg)
{
unw_word_t val, aligned_addr = UNW_ALIGN(*addr, sizeof (unw_word_t));
unw_word_t off = *addr - aligned_addr;
int ret;
*addr += 1;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(sizeof (unw_word_t) - 1 - off);
#endif
*valp = (uint8_t) val;
return ret;
}
static inline int
dwarf_readu16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint16_t *val, void *arg)
{
uint8_t v0, v1;
int ret;
if ((ret = dwarf_readu8 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu8 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint16_t) v0 << 8 | v1;
else
*val = (uint16_t) v1 << 8 | v0;
return 0;
}
static inline int
dwarf_readu32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint32_t *val, void *arg)
{
uint16_t v0, v1;
int ret;
if ((ret = dwarf_readu16 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu16 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint32_t) v0 << 16 | v1;
else
*val = (uint32_t) v1 << 16 | v0;
return 0;
}
static inline int
dwarf_readu64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
uint64_t *val, void *arg)
{
uint32_t v0, v1;
int ret;
if ((ret = dwarf_readu32 (as, a, addr, &v0, arg)) < 0
|| (ret = dwarf_readu32 (as, a, addr, &v1, arg)) < 0)
return ret;
if (tdep_big_endian (as))
*val = (uint64_t) v0 << 32 | v1;
else
*val = (uint64_t) v1 << 32 | v0;
return 0;
}
static inline int
dwarf_reads8 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int8_t *val, void *arg)
{
uint8_t uval;
int ret;
if ((ret = dwarf_readu8 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int8_t) uval;
return 0;
}
static inline int
dwarf_reads16 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int16_t *val, void *arg)
{
uint16_t uval;
int ret;
if ((ret = dwarf_readu16 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int16_t) uval;
return 0;
}
static inline int
dwarf_reads32 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int32_t *val, void *arg)
{
uint32_t uval;
int ret;
if ((ret = dwarf_readu32 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int32_t) uval;
return 0;
}
static inline int
dwarf_reads64 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
int64_t *val, void *arg)
{
uint64_t uval;
int ret;
if ((ret = dwarf_readu64 (as, a, addr, &uval, arg)) < 0)
return ret;
*val = (int64_t) uval;
return 0;
}
#endif /* !UNW_LOCAL_ONLY */
static inline int
dwarf_readw (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *val, void *arg)
{
uint32_t u32;
uint64_t u64;
int ret;
switch (dwarf_addr_size (as))
{
case 4:
ret = dwarf_readu32 (as, a, addr, &u32, arg);
if (ret < 0)
return ret;
*val = u32;
return ret;
case 8:
ret = dwarf_readu64 (as, a, addr, &u64, arg);
if (ret < 0)
return ret;
*val = u64;
return ret;
default:
abort ();
}
}
/* Read an unsigned "little-endian base 128" value. See Chapter 7.6
of DWARF spec v3. */
static inline int
dwarf_read_uleb128 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *valp, void *arg)
{
unw_word_t val = 0, shift = 0;
unsigned char byte;
int ret;
do
{
if ((ret = dwarf_readu8 (as, a, addr, &byte, arg)) < 0)
return ret;
val |= ((unw_word_t) byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
*valp = val;
return 0;
}
/* Read a signed "little-endian base 128" value. See Chapter 7.6 of
DWARF spec v3. */
static inline int
dwarf_read_sleb128 (unw_addr_space_t as, unw_accessors_t *a, unw_word_t *addr,
unw_word_t *valp, void *arg)
{
unw_word_t val = 0, shift = 0;
unsigned char byte;
int ret;
do
{
if ((ret = dwarf_readu8 (as, a, addr, &byte, arg)) < 0)
return ret;
val |= ((unw_word_t) byte & 0x7f) << shift;
shift += 7;
}
while (byte & 0x80);
if (shift < 8 * sizeof (unw_word_t) && (byte & 0x40) != 0)
/* sign-extend negative value */
val |= ((unw_word_t) -1) << shift;
*valp = val;
return 0;
}
static ALWAYS_INLINE int
dwarf_read_encoded_pointer_inlined (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unsigned char encoding,
const unw_proc_info_t *pi,
unw_word_t *valp, void *arg)
{
unw_word_t val, initial_addr = *addr;
uint16_t uval16;
uint32_t uval32;
uint64_t uval64;
int16_t sval16 = 0;
int32_t sval32 = 0;
int64_t sval64 = 0;
int ret;
/* DW_EH_PE_omit and DW_EH_PE_aligned don't follow the normal
format/application encoding. Handle them first. */
if (encoding == DW_EH_PE_omit)
{
*valp = 0;
return 0;
}
else if (encoding == DW_EH_PE_aligned)
{
int size = dwarf_addr_size (as);
*addr = (initial_addr + size - 1) & -size;
return dwarf_readw (as, a, addr, valp, arg);
}
switch (encoding & DW_EH_PE_FORMAT_MASK)
{
case DW_EH_PE_ptr:
if ((ret = dwarf_readw (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_uleb128:
if ((ret = dwarf_read_uleb128 (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_udata2:
if ((ret = dwarf_readu16 (as, a, addr, &uval16, arg)) < 0)
return ret;
val = uval16;
break;
case DW_EH_PE_udata4:
if ((ret = dwarf_readu32 (as, a, addr, &uval32, arg)) < 0)
return ret;
val = uval32;
break;
case DW_EH_PE_udata8:
if ((ret = dwarf_readu64 (as, a, addr, &uval64, arg)) < 0)
return ret;
val = uval64;
break;
case DW_EH_PE_sleb128:
if ((ret = dwarf_read_uleb128 (as, a, addr, &val, arg)) < 0)
return ret;
break;
case DW_EH_PE_sdata2:
if ((ret = dwarf_reads16 (as, a, addr, &sval16, arg)) < 0)
return ret;
val = sval16;
break;
case DW_EH_PE_sdata4:
if ((ret = dwarf_reads32 (as, a, addr, &sval32, arg)) < 0)
return ret;
val = sval32;
break;
case DW_EH_PE_sdata8:
if ((ret = dwarf_reads64 (as, a, addr, &sval64, arg)) < 0)
return ret;
val = sval64;
break;
default:
Debug (1, "unexpected encoding format 0x%x\n",
encoding & DW_EH_PE_FORMAT_MASK);
return -UNW_EINVAL;
}
if (val == 0)
{
/* 0 is a special value and always absolute. */
*valp = 0;
return 0;
}
switch (encoding & DW_EH_PE_APPL_MASK)
{
case DW_EH_PE_absptr:
break;
case DW_EH_PE_pcrel:
val += initial_addr;
break;
case DW_EH_PE_datarel:
/* XXX For now, assume that data-relative addresses are relative
to the global pointer. */
val += pi->gp;
break;
case DW_EH_PE_funcrel:
val += pi->start_ip;
break;
case DW_EH_PE_textrel:
/* XXX For now we don't support text-rel values. If there is a
platform which needs this, we probably would have to add a
"segbase" member to unw_proc_info_t. */
default:
Debug (1, "unexpected application type 0x%x\n",
encoding & DW_EH_PE_APPL_MASK);
return -UNW_EINVAL;
}
/* Trim off any extra bits. Assume that sign extension isn't
required; the only place it is needed is MIPS kernel space
addresses. */
if (sizeof (val) > dwarf_addr_size (as))
{
assert (dwarf_addr_size (as) == 4);
val = (uint32_t) val;
}
if (encoding & DW_EH_PE_indirect)
{
unw_word_t indirect_addr = val;
if ((ret = dwarf_readw (as, a, &indirect_addr, &val, arg)) < 0)
return ret;
}
*valp = val;
return 0;
}
#endif /* DWARF_I_H */
| 1 |
dotnet/runtime
| 66,427 |
Remove 4146 from libunwind
|
Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
AaronRobinsonMSFT
| 2022-03-10T01:32:16Z | 2022-03-14T21:00:38Z |
7e1dd58065e624dd3431c9dcbde9e30b3b5beaed
|
c3d393250cd63a679405fa9e35684772cbf2e1ef
|
Remove 4146 from libunwind. Contributes to https://github.com/dotnet/runtime/issues/66154
~~This converts the invalid arithmetic negation on an unsigned value to use the identity of bitwise negation plus one.~~
Upstream PR: https://github.com/libunwind/libunwind/pull/333
/cc @GrabYourPitchforks @jkotas @janvorli @am11
|
./src/coreclr/pal/src/libunwind/include/remote.h
|
#ifndef REMOTE_H
#define REMOTE_H
/* Helper functions for accessing (remote) memory. These functions
assume that all addresses are naturally aligned (e.g., 32-bit
quantity is stored at a 32-bit-aligned address. */
#ifdef UNW_LOCAL_ONLY
static inline int
fetch8 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int8_t *valp, void *arg)
{
*valp = *(int8_t *) (uintptr_t) *addr;
*addr += 1;
return 0;
}
static inline int
fetch16 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int16_t *valp, void *arg)
{
*valp = *(int16_t *) (uintptr_t) *addr;
*addr += 2;
return 0;
}
static inline int
fetch32 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int32_t *valp, void *arg)
{
*valp = *(int32_t *) (uintptr_t) *addr;
*addr += 4;
return 0;
}
static inline int
fetchw (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unw_word_t *valp, void *arg)
{
*valp = *(unw_word_t *) (uintptr_t) *addr;
*addr += sizeof (unw_word_t);
return 0;
}
#else /* !UNW_LOCAL_ONLY */
#define WSIZE (sizeof (unw_word_t))
static inline int
fetch8 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int8_t *valp, void *arg)
{
unw_word_t val, aligned_addr = *addr & -WSIZE, off = *addr - aligned_addr;
int ret;
*addr += 1;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 1 - off);
#endif
*valp = val & 0xff;
return ret;
}
static inline int
fetch16 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int16_t *valp, void *arg)
{
unw_word_t val, aligned_addr = *addr & -WSIZE, off = *addr - aligned_addr;
int ret;
if ((off & 0x1) != 0)
return -UNW_EINVAL;
*addr += 2;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 2 - off);
#endif
*valp = val & 0xffff;
return ret;
}
static inline int
fetch32 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int32_t *valp, void *arg)
{
unw_word_t val, aligned_addr = *addr & -WSIZE, off = *addr - aligned_addr;
int ret;
if ((off & 0x3) != 0)
return -UNW_EINVAL;
*addr += 4;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 4 - off);
#endif
*valp = val & 0xffffffff;
return ret;
}
static inline int
fetchw (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unw_word_t *valp, void *arg)
{
int ret;
ret = (*a->access_mem) (as, *addr, valp, 0, arg);
*addr += WSIZE;
return ret;
}
#endif /* !UNW_LOCAL_ONLY */
#endif /* REMOTE_H */
|
#ifndef REMOTE_H
#define REMOTE_H
/* Helper functions for accessing (remote) memory. These functions
assume that all addresses are naturally aligned (e.g., 32-bit
quantity is stored at a 32-bit-aligned address. */
#ifdef UNW_LOCAL_ONLY
static inline int
fetch8 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int8_t *valp, void *arg)
{
*valp = *(int8_t *) (uintptr_t) *addr;
*addr += 1;
return 0;
}
static inline int
fetch16 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int16_t *valp, void *arg)
{
*valp = *(int16_t *) (uintptr_t) *addr;
*addr += 2;
return 0;
}
static inline int
fetch32 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int32_t *valp, void *arg)
{
*valp = *(int32_t *) (uintptr_t) *addr;
*addr += 4;
return 0;
}
static inline int
fetchw (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unw_word_t *valp, void *arg)
{
*valp = *(unw_word_t *) (uintptr_t) *addr;
*addr += sizeof (unw_word_t);
return 0;
}
#else /* !UNW_LOCAL_ONLY */
#define WSIZE (sizeof (unw_word_t))
static inline int
fetch8 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int8_t *valp, void *arg)
{
unw_word_t val, aligned_addr = UNW_ALIGN(*addr, WSIZE), off = *addr - aligned_addr;
int ret;
*addr += 1;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 1 - off);
#endif
*valp = val & 0xff;
return ret;
}
static inline int
fetch16 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int16_t *valp, void *arg)
{
unw_word_t val, aligned_addr = UNW_ALIGN(*addr, WSIZE), off = *addr - aligned_addr;
int ret;
if ((off & 0x1) != 0)
return -UNW_EINVAL;
*addr += 2;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 2 - off);
#endif
*valp = val & 0xffff;
return ret;
}
static inline int
fetch32 (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, int32_t *valp, void *arg)
{
unw_word_t val, aligned_addr = UNW_ALIGN(*addr, WSIZE), off = *addr - aligned_addr;
int ret;
if ((off & 0x3) != 0)
return -UNW_EINVAL;
*addr += 4;
ret = (*a->access_mem) (as, aligned_addr, &val, 0, arg);
#if UNW_BYTE_ORDER == UNW_LITTLE_ENDIAN
val >>= 8*off;
#else
val >>= 8*(WSIZE - 4 - off);
#endif
*valp = val & 0xffffffff;
return ret;
}
static inline int
fetchw (unw_addr_space_t as, unw_accessors_t *a,
unw_word_t *addr, unw_word_t *valp, void *arg)
{
int ret;
ret = (*a->access_mem) (as, *addr, valp, 0, arg);
*addr += WSIZE;
return ret;
}
#endif /* !UNW_LOCAL_ONLY */
#endif /* REMOTE_H */
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.