Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit b174565

Browse files
authored
Fix EventPipeBuffer to use ClrVirtualAlloc instead of malloc (#28038)
1 parent b825061 commit b174565

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/vm/eventpipebuffer.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@ EventPipeBuffer::EventPipeBuffer(unsigned int bufferSize, EventPipeThread* pWrit
2323
m_state = EventPipeBufferState::WRITABLE;
2424
m_pWriterThread = pWriterThread;
2525
m_eventSequenceNumber = eventSequenceNumber;
26-
m_pBuffer = new BYTE[bufferSize];
26+
// Use ClrVirtualAlloc instead of malloc to allocate buffer to avoid potential internal fragmentation in the native CRT heap.
27+
// (See https://github.com/dotnet/runtime/pull/35924 and https://github.com/microsoft/ApplicationInsights-dotnet/issues/1678 for more details)
28+
m_pBuffer = (BYTE*)ClrVirtualAlloc(NULL, bufferSize, MEM_COMMIT, PAGE_READWRITE);
2729
memset(m_pBuffer, 0, bufferSize);
2830
m_pLimit = m_pBuffer + bufferSize;
2931
m_pCurrent = GetNextAlignedAddress(m_pBuffer);
@@ -47,7 +49,7 @@ EventPipeBuffer::~EventPipeBuffer()
4749
}
4850
CONTRACTL_END;
4951

50-
delete[] m_pBuffer;
52+
ClrVirtualFree(m_pBuffer, 0, MEM_RELEASE);
5153
}
5254

5355
bool EventPipeBuffer::WriteEvent(Thread *pThread, EventPipeSession &session, EventPipeEvent &event, EventPipeEventPayload &payload, LPCGUID pActivityId, LPCGUID pRelatedActivityId, StackContents *pStack)

src/vm/eventpipebuffermanager.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,12 @@ EventPipeBuffer* EventPipeBufferManager::AllocateBufferForThread(EventPipeThread
168168
const unsigned int maxBufferSize = 1024 * 1024;
169169
bufferSize = Min(bufferSize, maxBufferSize);
170170

171+
// Make the buffer size fit into with pagesize-aligned block,
172+
// since ClrVirtualAlloc expects page-aligned sizes to be passed
173+
// as arguments (see ctor of EventPipeBuffer)
174+
bufferSize = (bufferSize + g_SystemInfo.dwAllocationGranularity - 1) & ~static_cast<unsigned int>(g_SystemInfo.dwAllocationGranularity - 1);
175+
176+
171177
// EX_TRY is used here as opposed to new (nothrow) because
172178
// the constructor also allocates a private buffer, which
173179
// could throw, and cannot be easily checked

0 commit comments

Comments
 (0)