summaryrefslogtreecommitdiff
path: root/src/vm/eventpipe.cpp
blob: 7eab2c82a95a6b9e77c18819f7533dd0a5eca291 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#include "common.h"
#include "clrtypes.h"
#include "safemath.h"
#include "diagnosticsipc.h"
#include "eventpipe.h"
#include "eventpipebuffermanager.h"
#include "eventpipeconfiguration.h"
#include "eventpipeeventpayload.h"
#include "eventpipesessionprovider.h"
#include "eventpipeevent.h"
#include "eventpipeeventsource.h"
#include "eventpipefile.h"
#include "eventpipeprovider.h"
#include "eventpipesession.h"
#include "eventpipejsonfile.h"
#include "eventtracebase.h"
#include "sampleprofiler.h"
#include "win32threadpool.h"
#include "ceemain.h"

#ifdef FEATURE_PAL
#include "pal.h"
#endif // FEATURE_PAL

#ifdef FEATURE_PERFTRACING

CrstStatic EventPipe::s_configCrst;
Volatile<EventPipeState> EventPipe::s_state(EventPipeState::NotInitialized);
EventPipeConfiguration EventPipe::s_config;
EventPipeEventSource *EventPipe::s_pEventSource = nullptr;
VolatilePtr<EventPipeSession> EventPipe::s_pSessions[MaxNumberOfSessions];
Volatile<uint64_t> EventPipe::s_allowWrite = 0;
#ifndef FEATURE_PAL
unsigned int * EventPipe::s_pProcGroupOffsets = nullptr;
#endif
Volatile<uint32_t> EventPipe::s_numberOfSessions(0);

// This function is auto-generated from /src/scripts/genEventPipe.py
#ifdef FEATURE_PAL
extern "C"
#endif
void InitProvidersAndEvents();

void EventPipe::Initialize()
{
    STANDARD_VM_CONTRACT;

    if (s_state != EventPipeState::NotInitialized)
    {
        _ASSERTE(!"EventPipe::Initialize was already initialized.");
        return;
    }

    const bool tracingInitialized = s_configCrst.InitNoThrow(
        CrstEventPipe,
        (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN | CRST_HOST_BREAKABLE));

    // Initialize the session container to nullptr.
    for (VolatilePtr<EventPipeSession> &session : s_pSessions)
        session.Store(nullptr);

    s_config.Initialize();

    s_pEventSource = new EventPipeEventSource();

    // This calls into auto-generated code to initialize the runtime providers
    // and events so that the EventPipe configuration lock isn't taken at runtime
    InitProvidersAndEvents();

    // Set the sampling rate for the sample profiler.
    const unsigned long DefaultProfilerSamplingRateInNanoseconds = 1000000; // 1 msec.
    SampleProfiler::SetSamplingRate(DefaultProfilerSamplingRateInNanoseconds);


    if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EventPipeProcNumbers) != 0)
    {
#ifndef FEATURE_PAL
        // setup the windows processor group offset table
        WORD numGroups = ::GetActiveProcessorGroupCount();
        s_pProcGroupOffsets = new (nothrow) unsigned int[numGroups];
        if (s_pProcGroupOffsets)
        {
            unsigned int countProcs = 0;
            for (WORD i = 0; i < numGroups; i++)
            {
                s_pProcGroupOffsets[i] = countProcs;
                countProcs += GetActiveProcessorCount(i);
            }
        }
#endif
    }


    {
        CrstHolder _crst(GetLock());
        if (tracingInitialized)
            s_state = EventPipeState::Initialized;
    }
}

void EventPipe::Shutdown()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(s_state != EventPipeState::ShuttingDown);
    }
    CONTRACTL_END;

    if (g_fProcessDetach)
    {
        // If g_fProcessDetach is true, all threads except this got ripped because someone called ExitProcess().
        // This check is an attempt recognize that case and skip all unsafe cleanup work.

        // Since event reading/writing could happen while that ExitProcess happened, the stream is probably
        // screwed anyway. Therefore we do NOT attempt to flush buffer, do rundown. Cleaning up memory at this
        // point is rather meaningless too since the process is going to terminate soon. Therefore we simply
        // quickly exit here

        // TODO: Consider releasing the resources that could last longer than the process (e.g. the files)
        return;
    }

    if (s_state != EventPipeState::Initialized)
        return;

    // We are shutting down, so if disabling EventPipe throws, we need to move along anyway.
    EX_TRY
    {
        {
            CrstHolder _crst(GetLock());
            s_state = EventPipeState::ShuttingDown;
        }

        for (uint32_t i = 0; i < MaxNumberOfSessions; ++i)
        {
            EventPipeSession *pSession = s_pSessions[i].Load();
            if (pSession)
                Disable(reinterpret_cast<EventPipeSessionID>(pSession));
        }

        // dotnet/coreclr: issue 24850: EventPipe shutdown race conditions
        // Deallocating providers/events here might cause AV if a WriteEvent
        // was to occur. Thus, we are not doing this cleanup.

        // // Remove EventPipeEventSource first since it tries to use the data structures that we remove below.
        // // We need to do this after disabling sessions since those try to write to EventPipeEventSource.
        // delete s_pEventSource;
        // s_pEventSource = nullptr;
        // s_config.Shutdown();
    }
    EX_CATCH {}
    EX_END_CATCH(SwallowAllExceptions);
}

EventPipeSessionID EventPipe::Enable(
    LPCWSTR strOutputPath,
    uint32_t circularBufferSizeInMB,
    const EventPipeProviderConfiguration *pProviders,
    uint32_t numProviders,
    EventPipeSessionType sessionType,
    EventPipeSerializationFormat format,
    const bool rundownRequested,
    IpcStream *const pStream)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        PRECONDITION(format < EventPipeSerializationFormat::Count);
        PRECONDITION(circularBufferSizeInMB > 0);
        PRECONDITION(numProviders > 0 && pProviders != nullptr);
    }
    CONTRACTL_END;

    // If the state or arguments are invalid, bail here.
    if (sessionType == EventPipeSessionType::File && strOutputPath == nullptr)
        return 0;
    if (sessionType == EventPipeSessionType::IpcStream && pStream == nullptr)
        return 0;

    EventPipeSessionID sessionId = 0;
    RunWithCallbackPostponed([&](EventPipeProviderCallbackDataQueue *pEventPipeProviderCallbackDataQueue) {
        if (s_state != EventPipeState::Initialized)
            return;

        const uint32_t SessionIndex = GenerateSessionIndex();
        if (SessionIndex >= EventPipe::MaxNumberOfSessions)
            return;

        EventPipeSession *const pSession = new EventPipeSession(
            SessionIndex,
            strOutputPath,
            pStream,
            sessionType,
            format,
            rundownRequested,
            circularBufferSizeInMB,
            pProviders,
            numProviders);

        const bool fSuccess = EnableInternal(pSession, pEventPipeProviderCallbackDataQueue);
        if (fSuccess)
            sessionId = reinterpret_cast<EventPipeSessionID>(pSession);
        else
            delete pSession;
    });

    return sessionId;
}

bool EventPipe::EnableInternal(
    EventPipeSession *const pSession,
    EventPipeProviderCallbackDataQueue* pEventPipeProviderCallbackDataQueue)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        PRECONDITION(s_state == EventPipeState::Initialized);
        PRECONDITION(pSession != nullptr && pSession->IsValid());
        PRECONDITION(IsLockOwnedByCurrentThread());
    }
    CONTRACTL_END;

    if (pSession == nullptr || !pSession->IsValid())
        return false;

    // Return if the index is invalid.
    if (pSession->GetIndex() >= MaxNumberOfSessions)
    {
        _ASSERTE(!"Session index was out of range.");
        return false;
    }

    if (s_numberOfSessions >= MaxNumberOfSessions)
    {
        _ASSERTE(!"Max number of sessions reached.");
        return false;
    }

    // Register the SampleProfiler the very first time.
    SampleProfiler::Initialize(pEventPipeProviderCallbackDataQueue);

    // Enable the EventPipe EventSource.
    s_pEventSource->Enable(pSession);

    // Save the session.
    if (s_pSessions[pSession->GetIndex()].LoadWithoutBarrier() != nullptr)
    {
        _ASSERTE(!"Attempting to override an existing session.");
        return false;
    }
    s_pSessions[pSession->GetIndex()].Store(pSession);
    s_allowWrite |= pSession->GetMask();
    ++s_numberOfSessions;

    // Enable tracing.
    s_config.Enable(*pSession, pEventPipeProviderCallbackDataQueue);

    // Enable the sample profiler
    SampleProfiler::Enable(pEventPipeProviderCallbackDataQueue);

    // Enable the session.
    pSession->Enable();

    return true;
}

void EventPipe::Disable(EventPipeSessionID id)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    SetupThread();

    if (id == 0)
        return;

    // Don't block GC during clean-up.
    GCX_PREEMP();

    RunWithCallbackPostponed([&](EventPipeProviderCallbackDataQueue *pEventPipeProviderCallbackDataQueue) {
        if (s_numberOfSessions > 0)
            DisableInternal(id, pEventPipeProviderCallbackDataQueue);
    });
}

static void LogProcessInformationEvent(EventPipeEventSource &eventSource)
{
    // Get the managed command line.
    LPCWSTR pCmdLine = GetManagedCommandLine();

    // Checkout https://github.com/dotnet/coreclr/pull/24433 for more information about this fall back.
    if (pCmdLine == nullptr)
    {
        // Use the result from GetCommandLineW() instead
        pCmdLine = GetCommandLineW();
    }

    // Log the process information event.
    eventSource.SendProcessInfo(pCmdLine);
}

void EventPipe::DisableInternal(EventPipeSessionID id, EventPipeProviderCallbackDataQueue *pEventPipeProviderCallbackDataQueue)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(id != 0);
        PRECONDITION(s_numberOfSessions > 0);
        PRECONDITION(IsLockOwnedByCurrentThread());
    }
    CONTRACTL_END;

    if (!IsSessionIdInCollection(id))
        return;

    // If the session was not found, then there is nothing else to do.
    EventPipeSession *const pSession = reinterpret_cast<EventPipeSession *>(id);

    // Disable the profiler.
    SampleProfiler::Disable();

    // Log the process information event.
    LogProcessInformationEvent(*s_pEventSource);

    // Disable pSession tracing.
    s_config.Disable(*pSession, pEventPipeProviderCallbackDataQueue);

    pSession->Disable(); // WriteAllBuffersToFile, and remove providers.

    // Do rundown before fully stopping the session unless rundown wasn't requested
    if (pSession->RundownRequested())
    {
        pSession->EnableRundown(); // Set Rundown provider.

        EventPipeThread *const pEventPipeThread = EventPipeThread::GetOrCreate();
        if (pEventPipeThread != nullptr)
        {
            pEventPipeThread->SetAsRundownThread(pSession);
            {
                s_config.Enable(*pSession, pEventPipeProviderCallbackDataQueue);
                {
                    pSession->ExecuteRundown();
                }
                s_config.Disable(*pSession, pEventPipeProviderCallbackDataQueue);
            }
            pEventPipeThread->SetAsRundownThread(nullptr);
        }
        else
        {
            _ASSERTE(!"Failed to get or create the EventPipeThread for rundown events.");
        }
    }

    s_allowWrite &= ~(pSession->GetMask()); 
    pSession->SuspendWriteEvent();
    bool ignored;
    pSession->WriteAllBuffersToFile(&ignored); // Flush the buffers to the stream/file

    --s_numberOfSessions;

    // At this point, we should not be writing events to this session anymore
    // This is a good time to remove the session from the array.
    _ASSERTE(s_pSessions[pSession->GetIndex()] == pSession);

    // Remove the session from the array, and mask.
    s_pSessions[pSession->GetIndex()].Store(nullptr);

    // Write a final sequence point to the file now that all events have
    // been emitted.
    pSession->WriteSequencePointUnbuffered();

    delete pSession;

    // Providers can't be deleted during tracing because they may be needed when serializing the file.
    s_config.DeleteDeferredProviders();
}

EventPipeSession *EventPipe::GetSession(EventPipeSessionID id)
{
    LIMITED_METHOD_CONTRACT;

    {
        CrstHolder _crst(GetLock());

        if (s_state == EventPipeState::NotInitialized)
        {
            _ASSERTE(!"EventPipe::GetSession invoked before EventPipe was initialized.");
            return nullptr;
        }

        return IsSessionIdInCollection(id) ?
            reinterpret_cast<EventPipeSession*>(id) : nullptr;
    }
}

EventPipeProvider *EventPipe::CreateProvider(const SString &providerName, EventPipeCallback pCallbackFunction, void *pCallbackData)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(!IsLockOwnedByCurrentThread());
    }
    CONTRACTL_END;

    EventPipeProvider *pProvider = NULL;
    RunWithCallbackPostponed([&](EventPipeProviderCallbackDataQueue *pEventPipeProviderCallbackDataQueue) {
        pProvider = CreateProvider(providerName, pCallbackFunction, pCallbackData, pEventPipeProviderCallbackDataQueue);
    });

    return pProvider;
}

EventPipeProvider *EventPipe::CreateProvider(const SString &providerName, EventPipeCallback pCallbackFunction, void *pCallbackData, EventPipeProviderCallbackDataQueue* pEventPipeProviderCallbackDataQueue)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        PRECONDITION(IsLockOwnedByCurrentThread());
    }
    CONTRACTL_END;

    return s_config.CreateProvider(
        providerName,
        pCallbackFunction,
        pCallbackData,
        pEventPipeProviderCallbackDataQueue);
}

EventPipeProvider *EventPipe::GetProvider(const SString &providerName)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    return s_config.GetProvider(providerName);
}

void EventPipe::DeleteProvider(EventPipeProvider *pProvider)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Take the lock to make sure that we don't have a race
    // between disabling tracing and deleting a provider
    // where we hold a provider after tracing has been disabled.
    CrstHolder _crst(GetLock());

    if (pProvider != NULL)
    {
        if (Enabled())
        {
            // Save the provider until the end of the tracing session.
            pProvider->SetDeleteDeferred();
        }
        else
        {
            // Delete the provider now.
            s_config.DeleteProvider(pProvider);
        }
    }
}

void EventPipe::WriteEvent(EventPipeEvent &event, BYTE *pData, unsigned int length, LPCGUID pActivityId, LPCGUID pRelatedActivityId)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    EventPipeEventPayload payload(pData, length);
    WriteEventInternal(event, payload, pActivityId, pRelatedActivityId);
}

void EventPipe::WriteEvent(EventPipeEvent &event, EventData *pEventData, unsigned int eventDataCount, LPCGUID pActivityId, LPCGUID pRelatedActivityId)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    EventPipeEventPayload payload(pEventData, eventDataCount);
    WriteEventInternal(event, payload, pActivityId, pRelatedActivityId);
}

void EventPipe::WriteEventInternal(EventPipeEvent &event, EventPipeEventPayload &payload, LPCGUID pActivityId, LPCGUID pRelatedActivityId)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // We can't proceed if tracing is not initialized.
    if (s_state == EventPipeState::NotInitialized)
        return;

    // Exit early if the event is not enabled.
    if (!event.IsEnabled())
        return;

    // Get the current thread;
    Thread *const pThread = GetThread();

    // If the activity id isn't specified AND we are in a managed thread, pull it from the current thread.
    // If pThread is NULL (we aren't in writing from a managed thread) then pActivityId can be NULL
    if (pActivityId == nullptr && pThread != nullptr)
        pActivityId = pThread->GetActivityId();

    WriteEventInternal(
        pThread,
        event,
        payload,
        pActivityId,
        pRelatedActivityId);
}

void EventPipe::WriteEventInternal(
    Thread *pThread,
    EventPipeEvent &event,
    EventPipeEventPayload &payload,
    LPCGUID pActivityId,
    LPCGUID pRelatedActivityId,
    Thread *pEventThread,
    StackContents *pStack)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // We can't proceed if tracing is not initialized.
    if (s_state == EventPipeState::NotInitialized)
        return;

    EventPipeThread *const pEventPipeThread = EventPipeThread::GetOrCreate();
    if (pEventPipeThread == nullptr)
    {
        _ASSERTE(!"Failed to get or create an EventPipeThread.");
        return;
    }

    if (pEventPipeThread->IsRundownThread())
    {
        EventPipeSession *const pRundownSession = pEventPipeThread->GetRundownSession();
        _ASSERTE(pRundownSession != nullptr);
        _ASSERTE(pThread != nullptr);

        BYTE *pData = payload.GetFlatData();
        if (pThread != nullptr && pRundownSession != nullptr && pData != nullptr)
        {
            // EventPipeFile::WriteEvent needs to allocate a metadata event
            // and can therefore throw. In this context we will silently
            // fail rather than disrupt the caller
            EX_TRY
            {
                _ASSERTE(pRundownSession != nullptr);
                if (pRundownSession != nullptr)
                    pRundownSession->WriteEventBuffered(
                        pThread,
                        event,
                        payload,
                        pActivityId,
                        pRelatedActivityId,
                        pEventThread,
                        pStack);
            }
            EX_CATCH {}
            EX_END_CATCH(SwallowAllExceptions);
        }
    }
    else
    {
        for (uint32_t i = 0; i < MaxNumberOfSessions; ++i)
        {
            if ((s_allowWrite & ((uint64_t)1 << i)) == 0)
                continue;

            // Now that we know this session is probably live we pay the perf cost of the memory barriers
            // Setting this flag lets a thread trying to do a concurrent disable that it is not safe to delete
            // session ID i. The if check above also ensures that once the session is unpublished this thread
            // will eventually stop ever storing ID i into the WriteInProgress flag. This is important to
            // guarantee termination of the YIELD_WHILE loop in SuspendWriteEvents.
            pEventPipeThread->SetSessionWriteInProgress(i);
            {
                EventPipeSession *const pSession = s_pSessions[i].Load();

                // Disable is allowed to set s_pSessions[i] = NULL at any time and that may have occured in between
                // the check and the load
                if (pSession != nullptr)
                    pSession->WriteEventBuffered(
                        pThread,
                        event,
                        payload,
                        pActivityId,
                        pRelatedActivityId,
                        pEventThread,
                        pStack);
            }
            // Do not reference pSession past this point, we are signaling Disable() that it is safe to
            // delete it
            pEventPipeThread->SetSessionWriteInProgress(UINT32_MAX);
        }
    }
}

void EventPipe::WriteSampleProfileEvent(Thread *pSamplingThread, EventPipeEvent *pEvent, Thread *pTargetThread, StackContents &stackContents, BYTE *pData, unsigned int length)
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        PRECONDITION(pEvent != nullptr);
    }
    CONTRACTL_END;

    EventPipeEventPayload payload(pData, length);
    WriteEventInternal(
        pSamplingThread,
        *pEvent,
        payload,
        nullptr /* pActivityId */,
        nullptr /* pRelatedActivityId */,
        pTargetThread,
        &stackContents
    );
}

bool EventPipe::WalkManagedStackForCurrentThread(StackContents &stackContents)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    Thread *pThread = GetThread();
    return (pThread != NULL) ? WalkManagedStackForThread(pThread, stackContents) : false;
}

bool EventPipe::WalkManagedStackForThread(Thread *pThread, StackContents &stackContents)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(pThread != NULL);
    }
    CONTRACTL_END;

    // Calling into StackWalkFrames in preemptive mode violates the host contract,
    // but this contract is not used on CoreCLR.
    CONTRACT_VIOLATION(HostViolation);

    stackContents.Reset();

    StackWalkAction swaRet = pThread->StackWalkFrames(
        (PSTACKWALKFRAMESCALLBACK)&StackWalkCallback,
        &stackContents,
        ALLOW_ASYNC_STACK_WALK | FUNCTIONSONLY | HANDLESKIPPEDFRAMES | ALLOW_INVALID_OBJECTS);

    return ((swaRet == SWA_DONE) || (swaRet == SWA_CONTINUE));
}

StackWalkAction EventPipe::StackWalkCallback(CrawlFrame *pCf, StackContents *pData)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(pCf != NULL);
        PRECONDITION(pData != NULL);
    }
    CONTRACTL_END;

    // Get the IP.
    UINT_PTR controlPC = (UINT_PTR)pCf->GetRegisterSet()->ControlPC;
    if (controlPC == 0)
    {
        if (pData->GetLength() == 0)
        {
            // This happens for pinvoke stubs on the top of the stack.
            return SWA_CONTINUE;
        }
    }

    _ASSERTE(controlPC != 0);

    // Add the IP to the captured stack.
    pData->Append(
        controlPC,
        pCf->GetFunction());

    // Continue the stack walk.
    return SWA_CONTINUE;
}

uint32_t EventPipe::GenerateSessionIndex()
{
    LIMITED_METHOD_CONTRACT;
    PRECONDITION(IsLockOwnedByCurrentThread());

    for (uint32_t i = 0; i < MaxNumberOfSessions; ++i)
        if (s_pSessions[i].LoadWithoutBarrier() == nullptr)
            return i;
    return MaxNumberOfSessions;
}

bool EventPipe::IsSessionIdInCollection(EventPipeSessionID id)
{
    LIMITED_METHOD_CONTRACT;
    PRECONDITION(id != 0);
    PRECONDITION(IsLockOwnedByCurrentThread());

    const EventPipeSession *const pSession = reinterpret_cast<EventPipeSession *>(id);
    for (uint32_t i = 0; i < MaxNumberOfSessions; ++i)
    {
        if (s_pSessions[i] == pSession)
        {
            _ASSERTE(i == pSession->GetIndex());
            return true;
        }
    }
    return false;
}

EventPipeEventInstance *EventPipe::GetNextEvent(EventPipeSessionID sessionID)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_PREEMPTIVE;
        PRECONDITION(!IsLockOwnedByCurrentThread());
    }
    CONTRACTL_END;

    // Only fetch the next event if a tracing session exists.
    // The buffer manager is not disposed until the process is shutdown.
    EventPipeSession *const pSession = GetSession(sessionID);
    return pSession ? pSession->GetNextEvent() : nullptr;
}

HANDLE EventPipe::GetWaitHandle(EventPipeSessionID sessionID)
{
    LIMITED_METHOD_CONTRACT;

    EventPipeSession *const pSession = GetSession(sessionID);
    return pSession ? pSession->GetWaitEvent()->GetHandleUNHOSTED() : 0;
}

void EventPipe::InvokeCallback(EventPipeProviderCallbackData eventPipeProviderCallbackData)
{
    EventPipeProvider::InvokeCallback(eventPipeProviderCallbackData);
}

EventPipeEventInstance *EventPipe::BuildEventMetadataEvent(EventPipeEventInstance &instance, unsigned int metadataId)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    return s_config.BuildEventMetadataEvent(instance, metadataId);
}

#ifdef DEBUG
bool EventPipe::IsLockOwnedByCurrentThread()
{
    return GetLock()->OwnedByCurrentThread();
}
#endif

#endif // FEATURE_PERFTRACING