summaryrefslogtreecommitdiff
path: root/src/vm/eventpipe.cpp
blob: e041615efc649dafa434c51d3fca443b7d65dbe3 (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
// 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 "eventpipe.h"
#include "eventpipebuffermanager.h"
#include "eventpipeconfiguration.h"
#include "eventpipeevent.h"
#include "eventpipefile.h"
#include "eventpipeprovider.h"
#include "eventpipejsonfile.h"
#include "sampleprofiler.h"

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

#ifdef FEATURE_PERFTRACING

CrstStatic EventPipe::s_configCrst;
bool EventPipe::s_tracingInitialized = false;
EventPipeConfiguration* EventPipe::s_pConfig = NULL;
EventPipeBufferManager* EventPipe::s_pBufferManager = NULL;
EventPipeFile* EventPipe::s_pFile = NULL;
#ifdef _DEBUG
EventPipeFile* EventPipe::s_pSyncFile = NULL;
EventPipeJsonFile* EventPipe::s_pJsonFile = NULL;
#endif // _DEBUG

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

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

void EventPipe::Initialize()
{
    STANDARD_VM_CONTRACT;

    s_tracingInitialized = s_configCrst.InitNoThrow(
        CrstEventPipe,
        (CrstFlags)(CRST_REENTRANCY | CRST_TAKEN_DURING_SHUTDOWN));

    s_pConfig = new EventPipeConfiguration();
    s_pConfig->Initialize();

    s_pBufferManager = new EventPipeBufferManager();

#ifdef FEATURE_PAL
    // 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();
#endif
}

void EventPipe::EnableOnStartup()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Test COMPLUS variable to enable tracing at start-up.
    if((CLRConfig::GetConfigValue(CLRConfig::INTERNAL_PerformanceTracing) & 1) == 1)
    {
        SString outputPath;
        outputPath.Printf("Process-%d.netperf", GetCurrentProcessId());
        Enable(
            outputPath.GetUnicode(),
            1024 /* 1 GB circular buffer */,
            NULL /* pProviders */,
            0 /* numProviders */);
    }
}

void EventPipe::Shutdown()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    Disable();

    if(s_pConfig != NULL)
    {
        delete(s_pConfig);
        s_pConfig = NULL;
    }
    if(s_pBufferManager != NULL)
    {
        delete(s_pBufferManager);
        s_pBufferManager = NULL;
    }
}

void EventPipe::Enable(
    LPCWSTR strOutputPath,
    uint circularBufferSizeInMB,
    EventPipeProviderConfiguration *pProviders,
    int numProviders)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // If tracing is not initialized or is already enabled, bail here.
    if(!s_tracingInitialized || s_pConfig->Enabled())
    {
        return;
    }

    // Take the lock before enabling tracing.
    CrstHolder _crst(GetLock());

    // Create the event pipe file.
    SString eventPipeFileOutputPath(strOutputPath);
    s_pFile = new EventPipeFile(eventPipeFileOutputPath);

#ifdef _DEBUG
    if((CLRConfig::GetConfigValue(CLRConfig::INTERNAL_PerformanceTracing) & 2) == 2)
    {
        // Create a synchronous file.
        SString eventPipeSyncFileOutputPath;
        eventPipeSyncFileOutputPath.Printf("Process-%d.sync.netperf", GetCurrentProcessId());
        s_pSyncFile = new EventPipeFile(eventPipeSyncFileOutputPath);

        // Create a JSON file.
        SString outputFilePath;
        outputFilePath.Printf("Process-%d.PerfView.json", GetCurrentProcessId());
        s_pJsonFile = new EventPipeJsonFile(outputFilePath);
    }
#endif // _DEBUG

    // Enable tracing.
    s_pConfig->Enable(circularBufferSizeInMB, pProviders, numProviders);

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

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

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

    // Take the lock before disabling tracing.
    CrstHolder _crst(GetLock());

    if(s_pConfig->Enabled())
    {
        // Disable the profiler.
        SampleProfiler::Disable();

        // Disable tracing.
        s_pConfig->Disable();

        // Flush all write buffers to make sure that all threads see the change.
        FlushProcessWriteBuffers();

        // Write to the file.
        LARGE_INTEGER disableTimeStamp;
        QueryPerformanceCounter(&disableTimeStamp);
        s_pBufferManager->WriteAllBuffersToFile(s_pFile, disableTimeStamp);

        // Before closing the file, do rundown.
        s_pConfig->EnableRundown();

        // Ask the runtime to emit rundown events.
        if(g_fEEStarted && !g_fEEShutDown)
        {
            ETW::EnumerationLog::EndRundown();
        }

        // Disable the event pipe now that rundown is complete.
        s_pConfig->Disable();

        if(s_pFile != NULL)
        {
            delete(s_pFile);
            s_pFile = NULL;
        }
#ifdef _DEBUG
        if(s_pSyncFile != NULL)
        {
            delete(s_pSyncFile);
            s_pSyncFile = NULL;
        }
        if(s_pJsonFile != NULL)
        {
            delete(s_pJsonFile);
            s_pJsonFile = NULL;
        }
#endif // _DEBUG

        // De-allocate buffers.
        s_pBufferManager->DeAllocateBuffers();

        // Delete deferred providers.
        // Providers can't be deleted during tracing because they may be needed when serializing the file.
        s_pConfig->DeleteDeferredProviders();
    }
}

bool EventPipe::Enabled()
{
    LIMITED_METHOD_CONTRACT;

    bool enabled = false;
    if(s_pConfig != NULL)
    {
        enabled = s_pConfig->Enabled();
    }

    return enabled;
}

EventPipeProvider* EventPipe::CreateProvider(const GUID &providerID, EventPipeCallback pCallbackFunction, void *pCallbackData)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    return new EventPipeProvider(providerID, pCallbackFunction, pCallbackData);
}

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.
            // NOTE: This will remove it from all of the EventPipe data structures.
            delete(pProvider);
        }
    }
}

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

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

    // Get the current thread;
    Thread *pThread = GetThread();
    if(pThread == NULL)
    {
        // We can't write an event without the thread object.
        return;
    }

    if(!s_pConfig->RundownEnabled() && s_pBufferManager != NULL)
    {
        if(!s_pBufferManager->WriteEvent(pThread, event, pData, length, pActivityId, pRelatedActivityId))
        {
            // This is used in DEBUG to make sure that we don't log an event synchronously that we didn't log to the buffer.
            return;
        }
    }
    else if(s_pConfig->RundownEnabled())
    {
        // Write synchronously to the file.
        // We're under lock and blocking the disabling thread.
        EventPipeEventInstance instance(
            event,
            pThread->GetOSThreadId(),
            pData,
            length,
            pActivityId,
            pRelatedActivityId);

        if(s_pFile != NULL)
        {
            s_pFile->WriteEvent(instance);
        }
    }

#ifdef _DEBUG
    {
        GCX_PREEMP();

        // Create an instance of the event for the synchronous path.
        EventPipeEventInstance instance(
            event,
            pThread->GetOSThreadId(),
            pData,
            length,
            pActivityId,
            pRelatedActivityId);

        // Write to the EventPipeFile if it exists.
        if(s_pSyncFile != NULL)
        {
            s_pSyncFile->WriteEvent(instance);
        }
 
        // Write to the EventPipeJsonFile if it exists.
        if(s_pJsonFile != NULL)
        {
            s_pJsonFile->WriteEvent(instance);
        }
    }
#endif // _DEBUG
}

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

    // Write the event to the thread's buffer.
    if(s_pBufferManager != NULL)
    {
        // Specify the sampling thread as the "current thread", so that we select the right buffer.
        // Specify the target thread so that the event gets properly attributed.
        if(!s_pBufferManager->WriteEvent(pSamplingThread, *pEvent, pData, length, NULL /* pActivityId */, NULL /* pRelatedActivityId */, pTargetThread, &stackContents))
        {
            // This is used in DEBUG to make sure that we don't log an event synchronously that we didn't log to the buffer.
            return;
        }
    }

#ifdef _DEBUG
    {
        GCX_PREEMP();

        // Create an instance for the synchronous path.
        SampleProfilerEventInstance instance(*pEvent, pTargetThread, pData, length);
        stackContents.CopyTo(instance.GetStack());

        // Write to the EventPipeFile.
        if(s_pSyncFile != NULL)
        {
            s_pSyncFile->WriteEvent(instance);
        }

        // Write to the EventPipeJsonFile if it exists.
        if(s_pJsonFile != NULL)
        {
            s_pJsonFile->WriteEvent(instance);
        }
    }
#endif // _DEBUG
}

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

    Thread *pThread = GetThread();
    if(pThread != NULL)
    {
        return WalkManagedStackForThread(pThread, stackContents);
    }

    return false;
}

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

    stackContents.Reset();

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

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

StackWalkAction EventPipe::StackWalkCallback(CrawlFrame *pCf, StackContents *pData)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
        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;
}

EventPipeConfiguration* EventPipe::GetConfiguration()
{
    LIMITED_METHOD_CONTRACT;

    return s_pConfig;
}

CrstStatic* EventPipe::GetLock()
{
    LIMITED_METHOD_CONTRACT;

    return &s_configCrst;
}

void QCALLTYPE EventPipeInternal::Enable(
        __in_z LPCWSTR outputFile,
        unsigned int circularBufferSizeInMB,
        long profilerSamplingRateInNanoseconds,
        EventPipeProviderConfiguration *pProviders,
        int numProviders)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;
    SampleProfiler::SetSamplingRate(profilerSamplingRateInNanoseconds);
    EventPipe::Enable(outputFile, circularBufferSizeInMB, pProviders, numProviders);
    END_QCALL;
}

void QCALLTYPE EventPipeInternal::Disable()
{
    QCALL_CONTRACT;

    BEGIN_QCALL;
    EventPipe::Disable();
    END_QCALL;
}

INT_PTR QCALLTYPE EventPipeInternal::CreateProvider(
    GUID providerID,
    EventPipeCallback pCallbackFunc)
{
    QCALL_CONTRACT;

    EventPipeProvider *pProvider = NULL;

    BEGIN_QCALL;

    pProvider = EventPipe::CreateProvider(providerID, pCallbackFunc, NULL);

    END_QCALL;

    return reinterpret_cast<INT_PTR>(pProvider);
}

INT_PTR QCALLTYPE EventPipeInternal::DefineEvent(
    INT_PTR provHandle,
    unsigned int eventID,
    __int64 keywords,
    unsigned int eventVersion,
    unsigned int level,
    void *pMetadata,
    unsigned int metadataLength)
{
    QCALL_CONTRACT;

    EventPipeEvent *pEvent = NULL;

    BEGIN_QCALL;

    _ASSERTE(provHandle != NULL);
    _ASSERTE(pMetadata != NULL);
    EventPipeProvider *pProvider = reinterpret_cast<EventPipeProvider *>(provHandle);
    pEvent = pProvider->AddEvent(eventID, keywords, eventVersion, (EventPipeEventLevel)level, (BYTE *)pMetadata, metadataLength);
    _ASSERTE(pEvent != NULL);

    END_QCALL;

    return reinterpret_cast<INT_PTR>(pEvent);
}

void QCALLTYPE EventPipeInternal::DeleteProvider(
    INT_PTR provHandle)
{
    QCALL_CONTRACT;
    BEGIN_QCALL;

    if(provHandle != NULL)
    {
        EventPipeProvider *pProvider = reinterpret_cast<EventPipeProvider*>(provHandle);
        EventPipe::DeleteProvider(pProvider);
    }

    END_QCALL;
}

void QCALLTYPE EventPipeInternal::WriteEvent(
    INT_PTR eventHandle,
    unsigned int eventID,
    void *pData,
    unsigned int length,
    LPCGUID pActivityId,
    LPCGUID pRelatedActivityId)
{
    QCALL_CONTRACT;
    BEGIN_QCALL;

    _ASSERTE(eventHandle != NULL);
    EventPipeEvent *pEvent = reinterpret_cast<EventPipeEvent *>(eventHandle);
    EventPipe::WriteEvent(*pEvent, (BYTE *)pData, length, pActivityId, pRelatedActivityId);

    END_QCALL;
}

#endif // FEATURE_PERFTRACING