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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 127 additions & 0 deletions docs/design/datacontracts/CodeNotifications.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# Contract CodeNotifications

This contract provides read/write access to the in-target JIT code notification
allowlist. The runtime consults this table when JIT-compiling or discarding a
method; if the (module, methodToken) pair is present with a non-zero flag set,
the runtime raises a `DEBUG_CODE_NOTIFICATION` event so the debugger/DAC can
observe JIT events for that method.

Unlike the [Notifications](Notifications.md) contract (which only decodes
events raised by the runtime), this contract writes into the target process
and may lazily allocate the notification table when needed.

## APIs of contract

``` csharp
/// Notification flag set. Mapped to/from the native `CLRDATA_METHNOTIFY_*` values at the
/// IXCLRData COM boundary (None=0, Generated=1, Discarded=2).
[Flags]
public enum CodeNotificationKind : uint { None = 0, Generated = 1, Discarded = 2 }

// Set the JIT code notification flags for a specific method.
void SetCodeNotification(TargetPointer module, uint methodToken, CodeNotificationKind flags);

// Get the JIT code notification flags for a specific method. Returns None for both an unset
// method and an unallocated in-target table — the cDAC cannot (and does not need to)
// distinguish the two, since "no notifications present" is the same observable state.
CodeNotificationKind GetCodeNotification(TargetPointer module, uint methodToken);

// Set notification flags for all methods in a module, or all methods if module is null.
void SetAllCodeNotifications(TargetPointer module, CodeNotificationKind flags);
```

## Version 1

Data descriptors used:
| Data Descriptor Name | Field | Type | Purpose |
| --- | --- | --- | --- |
| `JITNotification` | `State` | uint16 | Notification flags (CLRDATA_METHNOTIFY_*) |
| `JITNotification` | `ClrModule` | nuint | Target pointer to the module |
| `JITNotification` | `MethodToken` | uint32 | Method metadata token |

Global variables used:
| Global Name | Type | Purpose |
| --- | --- | --- |
| `JITNotificationTable` | TargetPointer | Pointer to the `g_pNotificationTable` array of `JITNotification` entries |
| `JITNotificationTableSize` | uint32 | Maximum number of entries in the notification table (excluding bookkeeping) |

Contracts used: none

The JIT notification table is an array of `JITNotification` structs. Index 0 is reserved for
bookkeeping: its `MethodToken` field stores the current entry count (length). The table capacity
is a compile-time invariant exposed via the `JITNotificationTableSize` global, so slot 0's
`ClrModule` and `State` fields are unused. Actual entries start at index 1.

On Windows, the table starts as NULL (`g_pNotificationTable == 0`). On Unix, it is pre-allocated
at startup; the runtime's `new JITNotification[1001]` default-constructs every slot with
`state = 0`, `clrModule = 0`, `methodToken = 0`, so slot 0's length starts at 0 naturally.
The contract handles both cases uniformly:
- **GetCodeNotification** returns `CodeNotificationKind.None` when the table is NULL, which
is the same value returned when the method is not registered. The cDAC does not distinguish
"table absent" from "entry absent" — both are surfaced as "no notifications for this method".
This is a deliberate simplification from the legacy DAC, which returned `E_OUTOFMEMORY` when
`JITNotifications::IsActive()` was false; the information to the caller is semantically the
Comment thread
max-charlamb marked this conversation as resolved.
same in both cases.
- **SetAllCodeNotifications** is a no-op when the table is NULL.
- **SetCodeNotification** with `CodeNotificationKind.None` is a no-op when the table is NULL.
- **SetCodeNotification** with a non-zero flag lazily allocates the table via `Target.AllocateMemory`,
zero-fills it (so slot 0's length starts at 0), and writes the pointer back to
`g_pNotificationTable`. If the in-target table is full, a `COMException` with
`HResult == E_FAIL` is thrown, matching the legacy DAC's `SetNotification` failure path.
If `AllocateMemory` is not available (e.g., when the debugger host does not support
`ICLRDataTarget2`), a `NotImplementedException` is thrown.

This contract doesn't currently offer a capacity check, so consumers won't be able to
confirm in advance whether a batch of notification updates will all succeed. If a batch
would overflow the in-target table, the contract writes as many entries as fit and then
throws `COMException` with `HResult == E_FAIL` from the first `SetCodeNotification`
that cannot allocate a slot.

``` csharp
void SetCodeNotification(TargetPointer module, uint methodToken, CodeNotificationKind flags)
{
// Read g_pNotificationTable pointer
TargetPointer tablePointer = target.ReadPointer(
target.ReadGlobalPointer("JITNotificationTable"));

if (tablePointer == null)
{
if (flags == CodeNotificationKind.None) return; // nothing to clear
// Lazily allocate via Target.AllocateMemory
tablePointer = AllocateAndInitializeTable();
}

// Read bookkeeping from index 0 (length only; capacity comes from the global).
uint length = Read<uint>(tablePointer + MethodTokenOffset);
uint capacity = target.ReadGlobal<uint>("JITNotificationTableSize");
ulong entriesBase = tablePointer + entrySize;

if (flags == CodeNotificationKind.None)
{
// Find and clear the matching entry
}
else
{
// Find existing entry and update, or find free slot and insert.
// If no free slot is found: throw COMException with HResult = E_FAIL.
}
}

CodeNotificationKind GetCodeNotification(TargetPointer module, uint methodToken)
{
// Returns CodeNotificationKind.None both when the table is NULL and when the method
// is not registered. The cDAC does not distinguish these cases (legacy DAC did, via
// E_OUTOFMEMORY vs. S_OK+None); the observable state is the same.
}

void SetAllCodeNotifications(TargetPointer module, CodeNotificationKind flags)
{
// If table pointer is NULL, return (no-op)
// Iterate all active entries; if module is non-null, filter by module
// Set or clear each matching entry's flags.
// When clearing (flags == None), trim trailing free entries from the stored length.
// This deliberately diverges from JITNotifications::SetAllNotifications in
// src/coreclr/vm/util.cpp, whose length algorithm can orphan entries from other modules
// that sit past the trimmed length.
}
```
5 changes: 4 additions & 1 deletion docs/design/datacontracts/Notifications.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Contract Notifications

This contract is for debugger notifications.
This contract is for decoding debugger notifications raised by the runtime.

## APIs of contract

Expand All @@ -14,6 +14,9 @@ void SetGcNotification(int condemnedGeneration);
bool TryParseNotification(ReadOnlySpan<TargetPointer> exceptionInformation, out NotificationData? notification);
```

Management of the JIT code-notification allowlist is a separate contract, see
[CodeNotifications](CodeNotifications.md).

## Version 1

Data descriptors used: none
Expand Down
31 changes: 30 additions & 1 deletion src/coreclr/debug/daccess/cdac.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,28 @@ namespace

return S_OK;
}

int AllocVirtualCallback(uint32_t size, uint64_t* allocatedAddress, void* context)
{
ICorDebugDataTarget* target = reinterpret_cast<ICorDebugDataTarget*>(context);
ICLRDataTarget2* target2 = nullptr;
HRESULT hr = target->QueryInterface(__uuidof(ICLRDataTarget2), (void**)&target2);
if (FAILED(hr))
{
*allocatedAddress = 0;
return hr;
}

CLRDATA_ADDRESS addr = 0;
hr = target2->AllocVirtual(0, size, MEM_COMMIT, PAGE_READWRITE, &addr);
target2->Release();
*allocatedAddress = addr;
if (FAILED(hr))
{
*allocatedAddress = 0;
}
return hr;
}
}

CDAC CDAC::Create(uint64_t descriptorAddr, ICorDebugDataTarget* target, IUnknown* legacyImpl)
Expand All @@ -89,8 +111,15 @@ CDAC CDAC::Create(uint64_t descriptorAddr, ICorDebugDataTarget* target, IUnknown
decltype(&cdac_reader_init) init = reinterpret_cast<decltype(&cdac_reader_init)>(::GetProcAddress(cdacLib, "cdac_reader_init"));
_ASSERTE(init != nullptr);

// Check if the target supports memory allocation (ICLRDataTarget2)
ICLRDataTarget2* target2 = nullptr;
auto allocCallback = (target->QueryInterface(__uuidof(ICLRDataTarget2), (void**)&target2) == S_OK)
? &AllocVirtualCallback : nullptr;
if (target2 != nullptr)
target2->Release();

intptr_t handle;
if (init(descriptorAddr, &ReadFromTargetCallback, &WriteToTargetCallback, &ReadThreadContext, target, &handle) != 0)
if (init(descriptorAddr, &ReadFromTargetCallback, &WriteToTargetCallback, &ReadThreadContext, allocCallback, target, &handle) != 0)
{
::FreeLibrary(cdacLib);
return {};
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/debug/daccess/daccess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6019,7 +6019,7 @@ ClrDataAccess::GetHostJitNotificationTable()
if (m_jitNotificationTable == NULL)
{
m_jitNotificationTable =
JITNotifications::InitializeNotificationTable(1000);
JITNotifications::InitializeNotificationTable(JIT_NOTIFICATION_TABLE_SIZE);
}

return m_jitNotificationTable;
Expand Down
4 changes: 2 additions & 2 deletions src/coreclr/vm/cdacstress.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,8 @@ bool CdacStress::Initialize()
// Get the address of the contract descriptor in our own process
uint64_t descriptorAddr = reinterpret_cast<uint64_t>(&DotNetRuntimeContractDescriptor);

// Initialize the cDAC reader with in-process callbacks
if (init(descriptorAddr, &ReadFromTargetCallback, &WriteToTargetCallback, &ReadThreadContextCallback, nullptr, &s_cdacHandle) != 0)
// Initialize the cDAC reader with in-process callbacks (no alloc_virtual for in-process stress)
if (init(descriptorAddr, &ReadFromTargetCallback, &WriteToTargetCallback, &ReadThreadContextCallback, nullptr, nullptr, &s_cdacHandle) != 0)
{
LOG((LF_GCROOTS, LL_WARNING, "CDAC GC Stress: cdac_reader_init failed\n"));
::FreeLibrary(s_cdacModule);
Expand Down
10 changes: 10 additions & 0 deletions src/coreclr/vm/datadescriptor/datadescriptor.inc
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,13 @@ CDAC_TYPE_BEGIN(ObjectHandle)
CDAC_TYPE_SIZE(sizeof(OBJECTHANDLE))
CDAC_TYPE_END(ObjectHandle)

CDAC_TYPE_BEGIN(JITNotification)
CDAC_TYPE_SIZE(sizeof(::JITNotification))
CDAC_TYPE_FIELD(JITNotification, T_UINT16, State, offsetof(::JITNotification, state))
CDAC_TYPE_FIELD(JITNotification, T_NUINT, ClrModule, offsetof(::JITNotification, clrModule))
CDAC_TYPE_FIELD(JITNotification, T_UINT32, MethodToken, offsetof(::JITNotification, methodToken))
CDAC_TYPE_END(JITNotification)

// Object

CDAC_TYPE_BEGIN(Object)
Expand Down Expand Up @@ -1448,6 +1455,8 @@ CDAC_GLOBAL(DispatchThisPtrMask, T_NUINT, InteropLib::ABI::DispatchThisPtrMask)
CDAC_GLOBAL_POINTER(ComWrappersVtablePtrs, InteropLib::ABI::g_knownQueryInterfaceImplementations)
#endif // FEATURE_COMWRAPPERS
CDAC_GLOBAL_POINTER(GcNotificationFlags, &::g_gcNotificationFlags)
CDAC_GLOBAL_POINTER(JITNotificationTable, &::g_pNotificationTable)
CDAC_GLOBAL(JITNotificationTableSize, T_UINT32, JIT_NOTIFICATION_TABLE_SIZE)
CDAC_GLOBAL_POINTER(GlobalAllocContext, &::g_global_alloc_context)
CDAC_GLOBAL_POINTER(CoreLib, &::g_CoreLib)
#ifdef TARGET_WINDOWS
Expand Down Expand Up @@ -1505,6 +1514,7 @@ CDAC_GLOBAL_CONTRACT(AuxiliarySymbols, c1)
CDAC_GLOBAL_CONTRACT(BuiltInCOM, c1)
#endif // FEATURE_COMINTEROP
CDAC_GLOBAL_CONTRACT(CodeVersions, c1)
CDAC_GLOBAL_CONTRACT(CodeNotifications, c1)
#ifdef FEATURE_COMWRAPPERS
CDAC_GLOBAL_CONTRACT(ComWrappers, c1)
#endif // FEATURE_COMWRAPPERS
Expand Down
7 changes: 6 additions & 1 deletion src/coreclr/vm/util.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,11 @@ inline bool IsInCantStopRegion()

BOOL IsValidMethodCodeNotification(ULONG32 Notification);

// Number of usable JIT notification entries. The allocated table has
// JIT_NOTIFICATION_TABLE_SIZE + 1 slots; slot 0 stores bookkeeping (length).
// Referenced by the cDAC via CDAC_GLOBAL(JITNotificationTableSize, ...).
constexpr UINT JIT_NOTIFICATION_TABLE_SIZE = 1000;

typedef DPTR(struct JITNotification) PTR_JITNotification;
struct JITNotification
{
Expand Down Expand Up @@ -598,7 +603,7 @@ GVAL_DECL(ULONG32, g_dacNotificationFlags);
inline void
InitializeJITNotificationTable()
{
g_pNotificationTable = new (nothrow) JITNotification[1001];
g_pNotificationTable = new (nothrow) JITNotification[JIT_NOTIFICATION_TABLE_SIZE + 1];
}

#endif // TARGET_UNIX && !DACCESS_COMPILE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ public abstract class ContractRegistry
/// </summary>
public virtual INotifications Notifications => GetContract<INotifications>();
/// <summary>
/// Gets an instance of the CodeNotifications contract for the target.
/// </summary>
public virtual ICodeNotifications CodeNotifications => GetContract<ICodeNotifications>();
/// <summary>
/// Gets an instance of the SignatureDecoder contract for the target.
/// </summary>
public virtual ISignatureDecoder SignatureDecoder => GetContract<ISignatureDecoder>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;

namespace Microsoft.Diagnostics.DataContractReader.Contracts;

/// <summary>
/// Kinds of JIT code notifications that can be requested for a given method.
/// The contract layer only exchanges this typed enum — COM wrappers translate
/// to/from the raw uint at the boundary.
/// </summary>
[Flags]
public enum CodeNotificationKind : uint
{
None = 0,
Generated = 1,
Discarded = 2,
}

/// <summary>
/// Contract for reading and writing the JIT code notification table in the target process.
/// The table is an allowlist of (module, method token) pairs that causes the runtime to
/// raise <c>DEBUG_CODE_NOTIFICATION</c> events when the specified methods are JIT-compiled
/// or discarded.
/// </summary>
public interface ICodeNotifications : IContract
{
static string IContract.Name { get; } = nameof(CodeNotifications);

/// <summary>
/// Set the notification flags for a single (module, methodToken) pair.
/// If the in-target table has not been allocated yet, lazily allocates it when
/// <paramref name="flags"/> is non-zero.
/// </summary>
void SetCodeNotification(TargetPointer module, uint methodToken, CodeNotificationKind flags) => throw new NotImplementedException();

/// <summary>
/// Get the notification flags for a single (module, methodToken) pair.
/// </summary>
CodeNotificationKind GetCodeNotification(TargetPointer module, uint methodToken) => throw new NotImplementedException();

/// <summary>
Comment thread
max-charlamb marked this conversation as resolved.
/// Set notification flags for all methods in a module, or all methods if module is null.
/// </summary>
void SetAllCodeNotifications(TargetPointer module, CodeNotificationKind flags) => throw new NotImplementedException();
}

public readonly struct CodeNotifications : ICodeNotifications
{
// Everything throws NotImplementedException
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public enum DataType
/* VM Data Types */

ObjectHandle,
JITNotification,
CodePointer,
Thread,
ThreadStore,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,20 @@ public abstract class Target
/// <param name="buffer">Source of the bytes to write, the number of bytes to write is the span length</param>
public abstract void WriteBuffer(ulong address, Span<byte> buffer);

/// <summary>
/// Allocate memory in the target process
/// </summary>
/// <param name="size">The number of bytes to allocate</param>
/// <returns>The address of the allocated memory in the target process</returns>
/// <exception cref="NotImplementedException">Thrown when the target does not support memory allocation</exception>
/// <remarks>
/// This is used for lazy allocation patterns where the debugger needs to allocate memory
/// in the target process (e.g., JIT notification tables on Windows).
/// The default implementation throws <see cref="NotImplementedException"/>.
/// </remarks>
public virtual TargetPointer AllocateMemory(uint size)
=> throw new NotImplementedException("Target does not support memory allocation");

/// <summary>
/// Read a null-terminated UTF-8 string from the target
/// </summary>
Expand Down Expand Up @@ -188,6 +202,20 @@ public abstract class Target
/// <param name="value">Value to write</param>
public abstract void Write<T>(ulong address, T value) where T : unmanaged, IBinaryInteger<T>, IMinMaxValue<T>;

/// <summary>
/// Write a target pointer to the target in target endianness, using the target's pointer size.
/// </summary>
/// <param name="address">Address to write to</param>
/// <param name="value">Pointer value to write</param>
public abstract void WritePointer(ulong address, TargetPointer value);

/// <summary>
/// Write a target NUInt to the target in target endianness, using the target's pointer size.
/// </summary>
/// <param name="address">Address to write to</param>
/// <param name="value">Pointer value to write</param>
public abstract void WriteNUInt(ulong address, TargetNUInt value);

/// <summary>
/// Read a target pointer from a span of bytes
/// </summary>
Expand Down
Loading
Loading