File: EventProvider.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (833 lines) | stat: -rw-r--r-- 31,997 bytes parent folder | download | duplicates (7)
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
824
825
826
827
828
829
830
831
832
833
//------------------------------------------------------------------------------
// <copyright file="etwprovider.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.Win32;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Threading;
using System.Security.Permissions;
using System.Security;
using System.Diagnostics.CodeAnalysis;

namespace System.Diagnostics.Eventing{

    [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
    public class EventProvider : IDisposable 
    {
        [SecurityCritical]
        UnsafeNativeMethods.EtwEnableCallback m_etwCallback;  // Trace Callback function
        private long m_regHandle;                       // Trace Registration Handle
        private byte m_level;                            // Tracing Level
        private long m_anyKeywordMask;                  // Trace Enable Flags
        private long m_allKeywordMask;                  // Match all keyword
        private int m_enabled;                           // Enabled flag from Trace callback
        private Guid m_providerId;                       // Control Guid 
        private int m_disposed;                          // when 1, provider has unregister
        [ThreadStatic]
        private static WriteEventErrorCode t_returnCode; // thread slot to keep last error
        private static bool s_platformNotSupported = (Environment.OSVersion.Version.Major < 6);
        private static bool s_preWin7 = (Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor < 1));        

        private const int s_basicTypeAllocationBufferSize = 16;
        private const int s_etwMaxMumberArguments = 32;
        private const int s_etwAPIMaxStringCount = 8;
        private const int s_maxEventDataDescriptors = 128;
        private const int s_traceEventMaximumSize = 65482;
        private const int s_traceEventMaximumStringSize = 32724;

        [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
        public enum WriteEventErrorCode : int
        {
            //check mapping to runtime codes
            NoError = 0,
            NoFreeBuffers = 1,
            EventTooBig = 2
        }

        [StructLayout(LayoutKind.Explicit, Size = 16)]
        private struct EventData
        {
            [FieldOffset(0)]
            internal ulong DataPointer;
            [FieldOffset(8)]
            internal uint Size;
            [FieldOffset(12)]
            internal int Reserved;
        }

        private enum ActivityControl : uint
        {
            EVENT_ACTIVITY_CTRL_GET_ID = 1,
            EVENT_ACTIVITY_CTRL_SET_ID = 2,
            EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
            EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
            EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
        }

        /// <summary>
        /// Constructor for EventProvider class.  
        /// </summary>
        /// <param name="ProviderGuid">
        /// Unique GUID among all trace sources running on a system
        /// </param>
        [SecuritySafeCritical]
        [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
        public EventProvider(Guid providerGuid)
        {            
            m_providerId = providerGuid;

            //
            // EtwRegister the ProviderId with ETW
            //
            EtwRegister();
        }

        /// <summary>
        /// This method registers the controlGuid of this class with ETW.
        /// We need to be running on Vista or above. If not an 
        /// PlatformNotSupported exception will be thrown. 
        /// If for some reason the ETW EtwRegister call failed
        /// a NotSupported exception will be thrown. 
        /// </summary>
        [System.Security.SecurityCritical]
        private unsafe void EtwRegister()
        {

            uint status;

            //
            // Check only the mayor version
            //

            if (s_platformNotSupported)
            {
                throw new PlatformNotSupportedException(SR.GetString(SR.NotSupported_DownLevelVista));
            }

            m_etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack);


            status = UnsafeNativeMethods.EventRegister(ref m_providerId, m_etwCallback, null, ref m_regHandle);
            if (status != 0)
            {
                throw new Win32Exception((int)status);
            }

        }

        //
        // implement Dispose Pattern to early deregister from ETW insted of waiting for 
        // the finalizer to call deregistration.
        // Once the user is done with the provider it needs to call Close() or Dispose()
        // If neither are called the finalizer will unregister the provider anyway
        //
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        [System.Security.SecuritySafeCritical]
        protected virtual void Dispose(bool disposing)
        {
            //
            // explicit cleanup is done by calling Dispose with true from 
            // Dispose() or Close(). The disposing arguement is ignored because there
            // are no unmanaged resources.
            // The finalizer calls Dispose with false.
            //

            //
            // check if the object has been allready disposed
            //
            if (m_disposed == 1) return;

            if (Interlocked.Exchange(ref m_disposed, 1) != 0)
            {
                // somebody is allready disposing the provider
                return;
            }

            //
            // Disables Tracing in the provider, then unregister
            // 

            m_enabled = 0;

            Deregister();
        }

        /// <summary>
        /// This method deregisters the controlGuid of this class with ETW.
        /// 
        /// </summary>
        public virtual void Close()
        {
            Dispose();
        }

        ~EventProvider()
        {
            Dispose(false);
        }

        /// <summary>
        /// This method un-registers from ETW.
        /// </summary>
        [System.Security.SecurityCritical]
        private unsafe void Deregister()
        {
            //
            // Unregister from ETW using the RegHandle saved from
            // the register call.
            //

            if (m_regHandle != 0)
            {
                UnsafeNativeMethods.EventUnregister(m_regHandle);
                m_regHandle = 0;
            }
        }

        [System.Security.SecurityCritical]
        unsafe void EtwEnableCallBack(
                        [In] ref System.Guid sourceId,
                        [In] int isEnabled,
                        [In] byte setLevel,
                        [In] long anyKeyword,
                        [In] long allKeyword,
                        [In] void* filterData,
                        [In] void* callbackContext
                        )
        {

            m_enabled = isEnabled;
            m_level = setLevel;
            m_anyKeywordMask = anyKeyword;
            m_allKeywordMask = allKeyword;
            return;
        }

        /// <summary>
        /// IsEnabled, method used to test if provider is enabled
        /// </summary>
        public bool IsEnabled()
        {
            return (m_enabled != 0) ? true : false;
        }

        /// <summary>
        /// IsEnabled, method used to test if event is enabled
        /// </summary>
        /// <param name="Lvl">
        /// Level  to test
        /// </param>
        /// <param name="Keyword">
        /// Keyword  to test
        /// </param>
        public bool IsEnabled(byte level, long keywords)
        {

            //
            // If not enabled at all, return false.
            //

            if (m_enabled == 0)
            {
                return false;
            }

            // This also covers the case of Level == 0.
            if ((level <= m_level) || 
                (m_level == 0))
            {

                //
                // Check if Keyword is enabled
                //

                if ((keywords == 0) ||
                    (((keywords & m_anyKeywordMask) != 0) &&
                     ((keywords & m_allKeywordMask) == m_allKeywordMask)))
                {
                    return true;
                }
            }

            return false;
        }

        public static WriteEventErrorCode GetLastWriteEventError()
        {
            return t_returnCode;
        } 

        //
        // Helper function to set the last error on the thread
        //
        private static void SetLastError(int error){
            switch (error)
            {
                case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW:
                case UnsafeNativeMethods.ERROR_MORE_DATA:
                    t_returnCode = WriteEventErrorCode.EventTooBig;
                    break;
                case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY:
                    t_returnCode = WriteEventErrorCode.NoFreeBuffers;
                    break;
            }
        }


        [System.Security.SecurityCritical]
        private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer)
        /*++

        Routine Description:

           This routine is used by WriteEvent to unbox the object type and
           to fill the passed in ETW data descriptor. 

        Arguments:

           data - argument to be decoded

           dataDescriptor - pointer to the descriptor to be filled

           dataBuffer - storage buffer for storing user data, needed because cant get the address of the object

        Return Value:

           null if the object is a basic type other than string. String otherwise

        --*/
        {
            dataDescriptor->Reserved = 0;

            string sRet = data as string;
            if (sRet != null)
            {
                dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
                return sRet;
            }

            if (data == null)
            {
                dataDescriptor->Size = 0;
                dataDescriptor->DataPointer = 0;
            }
            else if (data is IntPtr)
            {
                dataDescriptor->Size = (uint)sizeof(IntPtr);
                IntPtr* intptrPtr = (IntPtr*)dataBuffer;
                *intptrPtr = (IntPtr)data;
                dataDescriptor->DataPointer = (ulong)intptrPtr;
            }
            else if (data is int)
            {
                dataDescriptor->Size = (uint)sizeof(int);
                int* intptrPtr = (int*)dataBuffer;
                *intptrPtr = (int)data;
                dataDescriptor->DataPointer = (ulong)intptrPtr;
            }
            else if (data is long)
            {
                dataDescriptor->Size = (uint)sizeof(long);
                long* longptr = (long*)dataBuffer;
                *longptr = (long)data;
                dataDescriptor->DataPointer = (ulong)longptr;
            }
            else if (data is uint)
            {
                dataDescriptor->Size = (uint)sizeof(uint);
                uint* uintptr = (uint*)dataBuffer;
                *uintptr = (uint)data;
                dataDescriptor->DataPointer = (ulong)uintptr;
            }
            else if (data is UInt64)
            {
                dataDescriptor->Size = (uint)sizeof(ulong);
                UInt64* ulongptr = (ulong*)dataBuffer;
                *ulongptr = (ulong)data;
                dataDescriptor->DataPointer = (ulong)ulongptr;
            }
            else if (data is char)
            {
                dataDescriptor->Size = (uint)sizeof(char);
                char* charptr = (char*)dataBuffer;
                *charptr = (char)data;
                dataDescriptor->DataPointer = (ulong)charptr;
            }
            else if (data is byte)
            {
                dataDescriptor->Size = (uint)sizeof(byte);
                byte* byteptr = (byte*)dataBuffer;
                *byteptr = (byte)data;
                dataDescriptor->DataPointer = (ulong)byteptr;
            }
            else if (data is short)
            {
                dataDescriptor->Size = (uint)sizeof(short);
                short* shortptr = (short*)dataBuffer;
                *shortptr = (short)data;
                dataDescriptor->DataPointer = (ulong)shortptr;
            }
            else if (data is sbyte)
            {
                dataDescriptor->Size = (uint)sizeof(sbyte);
                sbyte* sbyteptr = (sbyte*)dataBuffer;
                *sbyteptr = (sbyte)data;
                dataDescriptor->DataPointer = (ulong)sbyteptr;
            }
            else if (data is ushort)
            {
                dataDescriptor->Size = (uint)sizeof(ushort);
                ushort* ushortptr = (ushort*)dataBuffer;
                *ushortptr = (ushort)data;
                dataDescriptor->DataPointer = (ulong)ushortptr;
            }
            else if (data is float)
            {
                dataDescriptor->Size = (uint)sizeof(float);
                float* floatptr = (float*)dataBuffer;
                *floatptr = (float)data;
                dataDescriptor->DataPointer = (ulong)floatptr;
            }
            else if (data is double)
            {
                dataDescriptor->Size = (uint)sizeof(double);
                double* doubleptr = (double*)dataBuffer;
                *doubleptr = (double)data;
                dataDescriptor->DataPointer = (ulong)doubleptr;
            }
            else if (data is bool)
            {
                dataDescriptor->Size = (uint)sizeof(bool);
                bool* boolptr = (bool*)dataBuffer;
                *boolptr = (bool)data;
                dataDescriptor->DataPointer = (ulong)boolptr;
            }
            else if (data is Guid)
            {
                dataDescriptor->Size = (uint)sizeof(Guid);
                Guid* guidptr = (Guid*)dataBuffer;
                *guidptr = (Guid)data;
                dataDescriptor->DataPointer = (ulong)guidptr;
            }
            else if (data is decimal)
            {
                dataDescriptor->Size = (uint)sizeof(decimal);
                decimal* decimalptr = (decimal*)dataBuffer;
                *decimalptr = (decimal)data;
                dataDescriptor->DataPointer = (ulong)decimalptr;
            }
            else if (data is Boolean)
            {
                dataDescriptor->Size = (uint)sizeof(Boolean);
                Boolean* booleanptr = (Boolean*)dataBuffer;
                *booleanptr = (Boolean)data;
                dataDescriptor->DataPointer = (ulong)booleanptr;
            }
            else
            {
                //To our eyes, everything else is a just a string
                sRet = data.ToString();
                dataDescriptor->Size = (uint)((sRet.Length + 1) * 2);
                return sRet;
            }

            return null;
        }


        /// <summary>
        /// WriteMessageEvent, method to write a string with level and Keyword.
        /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId().
        /// </summary>
        /// <param name="level">
        /// Level  to test  
        /// </param>
        /// <param name="Keyword">
        /// Keyword  to test 
        /// </param>
        [System.Security.SecurityCritical]
        public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKeywords)
        {
            int status = 0;

            if (eventMessage == null)
            {
                throw new ArgumentNullException("eventMessage");
            }

            if (IsEnabled(eventLevel, eventKeywords))
            {
                if (eventMessage.Length > s_traceEventMaximumStringSize)
                {
                    t_returnCode = WriteEventErrorCode.EventTooBig;
                    return false;
                }
                unsafe
                {
                    fixed (char* pdata = eventMessage)
                    {
                        status = (int)UnsafeNativeMethods.EventWriteString(m_regHandle, eventLevel, eventKeywords, pdata);
                    }

                    if (status != 0)
                    {
                        SetLastError(status);
                        return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// WriteMessageEvent, method to write a string with level=0 and Keyword=0
        /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId().
        /// </summary>
        /// <param name="eventMessage">
        /// Message to log  
        /// </param> 
        public bool WriteMessageEvent(string eventMessage)
        {
            return WriteMessageEvent(eventMessage, 0, 0);
        }

 
        /// <summary>
        /// WriteEvent method to write parameters with event schema properties
        /// </summary>
        /// <param name="EventDescriptor">
        /// Event Descriptor for this event. 
        /// </param>        
        public bool WriteEvent(ref EventDescriptor eventDescriptor, params  object[] eventPayload)
        {
            return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload);            
        }

        /// <summary>
        /// WriteEvent, method to write a string with event schema properties
        /// </summary>
        /// <param name="EventDescriptor">
        /// Event Descriptor for this event. 
        /// </param>
        /// <param name="dataString">
        /// string to log. 
        /// </param>
        [System.Security.SecurityCritical]
        [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
        public bool WriteEvent(ref EventDescriptor eventDescriptor, string data)
        {
            uint status = 0;

            if (data == null)
            {
                throw new ArgumentNullException("dataString");
            }

            if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
            {
                if (data.Length > s_traceEventMaximumStringSize)
                {
                    t_returnCode = WriteEventErrorCode.EventTooBig; 
                    return false;
                }

                EventData userData;

                userData.Size = (uint)((data.Length +1)* 2);
                userData.Reserved = 0;

                unsafe
                {
                    fixed (char* pdata = data)
                    {
                        Guid activityId = GetActivityId();
                        userData.DataPointer = (ulong)pdata;
                        if (s_preWin7)
                        {
                            status = UnsafeNativeMethods.EventWrite(m_regHandle, 
                                                                     ref eventDescriptor, 
                                                                     1, 
                                                                     &userData);
                        }
                        else
                        {
                            status = UnsafeNativeMethods.EventWriteTransfer(m_regHandle, 
                                                                             ref eventDescriptor, 
                                                                             (activityId == Guid.Empty) ? null : &activityId, 
                                                                             null, 
                                                                             1, 
                                                                             &userData);
                        }
                    }
                }
            }

            if (status != 0)
            {
                SetLastError((int)status);
                return false;
            }
            return true;
        }

        /// <summary>
        /// WriteEvent, method to be used by generated code on a derived class
        /// </summary>
        /// <param name="EventDescriptor">
        /// Event Descriptor for this event. 
        /// </param>
        /// <param name="count">
        /// number of event descriptors 
        /// </param>
        /// <param name="data">
        /// pointer  do the event data
        /// </param> 
        [System.Security.SecurityCritical]
        protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, IntPtr data)
        {
            uint status = 0;

            unsafe
            {
                if (s_preWin7)
                {
                    status = UnsafeNativeMethods.EventWrite(
                                                        m_regHandle, 
                                                        ref eventDescriptor,
                                                        (uint)dataCount, 
                                                        (void*)data);
                }
                else
                {
                    Guid activityId = GetActivityId();

                    status = UnsafeNativeMethods.EventWriteTransfer(
                                        m_regHandle, 
                                        ref eventDescriptor,
                                        (activityId == Guid.Empty) ? null : &activityId, 
                                        null, 
                                        (uint)dataCount, 
                                        (void*)data);
                }
            }

            if (status != 0)
            {
                SetLastError((int)status);
                return false;
            }
            return true;

        }


        /// <summary>
        /// WriteTransferEvent, method to write a parameters with event schema properties
        /// </summary>
        /// <param name="eventDescriptor">
        /// Event Descriptor for this event. 
        /// </param>
        [System.Security.SecurityCritical]
        public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload)
        {
            uint status = 0;

            if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
            {
                Guid activityId = GetActivityId();

                unsafe
                {
                    int argCount = 0;
                    EventData* userDataPtr = null;
                    
                    if ((eventPayload != null) && (eventPayload.Length != 0))
                    {
                        argCount = eventPayload.Length;
                        if (argCount > s_etwMaxMumberArguments)
                        {
                            //
                            //too many arguments to log
                            //
                            throw new ArgumentOutOfRangeException("eventPayload",
                                SR.GetString(SR.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxMumberArguments));
                        }

                        uint totalEventSize = 0;
                        int index;
                        int stringIndex = 0;
                        int[] stringPosition = new int[s_etwAPIMaxStringCount]; //used to keep the position of strings in the eventPayload parameter
                        string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter                        
                        EventData* userData = stackalloc EventData[argCount];             // allocation for the data descriptors
                        userDataPtr = (EventData*)userData;
                        byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument
                        byte* currentBuffer = dataBuffer;

                        //
                        // The loop below goes through all the arguments and fills in the data 
                        // descriptors. For strings save the location in the dataString array.
                        // Caculates the total size of the event by adding the data descriptor
                        // size value set in EncodeObjec method.
                        //
                        for (index = 0; index < eventPayload.Length; index++)
                        {                            
                            string isString;
                            isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer);
                            currentBuffer += s_basicTypeAllocationBufferSize;
                            totalEventSize += userDataPtr->Size;
                            userDataPtr++;
                            if (isString != null)
                            {
                                if (stringIndex < s_etwAPIMaxStringCount)
                                {
                                    dataString[stringIndex] = isString;
                                    stringPosition[stringIndex] = index;
                                    stringIndex++;
                                }
                                else
                                {
                                    throw new ArgumentOutOfRangeException("eventPayload",
                                        SR.GetString(SR.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount));
                                }
                             }
                        }

                        if (totalEventSize > s_traceEventMaximumSize)
                        {
                            t_returnCode = WriteEventErrorCode.EventTooBig;
                            return false;
                        }

                        fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3],
                                v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7])
                        {
                            userDataPtr = (EventData*)userData;
                            if (dataString[0] != null)
                            {
                                userDataPtr[stringPosition[0]].DataPointer = (ulong)v0;
                            }
                            if (dataString[1] != null)
                            {
                                userDataPtr[stringPosition[1]].DataPointer = (ulong)v1;
                            }
                            if (dataString[2] != null)
                            {
                                userDataPtr[stringPosition[2]].DataPointer = (ulong)v2;
                            }
                            if (dataString[3] != null)
                            {
                                userDataPtr[stringPosition[3]].DataPointer = (ulong)v3;
                            }
                            if (dataString[4] != null)
                            {
                                userDataPtr[stringPosition[4]].DataPointer = (ulong)v4;
                            }
                            if (dataString[5] != null)
                            {
                                userDataPtr[stringPosition[5]].DataPointer = (ulong)v5;
                            }
                            if (dataString[6] != null)
                            {
                                userDataPtr[stringPosition[6]].DataPointer = (ulong)v6;
                            }
                            if (dataString[7] != null)
                            {
                                userDataPtr[stringPosition[7]].DataPointer = (ulong)v7;
                            }
                        }
                    }

                    if (relatedActivityId == Guid.Empty && s_preWin7)
                    {
                        // If relatedActivityId is Guid.Empty, this is not a real transfer: just call EventWrite().
                        // For pre-Win7 platforms we cannot set the activityId from CorrelationManager
                        // because we cannot set relatedActivityId to null (Win7 bug 116784)
                        status = UnsafeNativeMethods.EventWrite (m_regHandle, 
                                                                 ref eventDescriptor, 
                                                                 (uint)argCount, 
                                                                 userDataPtr);
                    }
                    else
                    {                    
                        status = UnsafeNativeMethods.EventWriteTransfer (m_regHandle, 
                                                                         ref eventDescriptor, 
                                                                         (activityId == Guid.Empty) ? null : &activityId, 
                                                                         (relatedActivityId == Guid.Empty && !s_preWin7)? null : &relatedActivityId,
                                                                         (uint)argCount, 
                                                                         userDataPtr);
                    }
                }
            }

            if (status != 0)
            {
                SetLastError((int)status);
                return false;
            }
            return true;
        }

        [System.Security.SecurityCritical]
        protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data)
        {
            uint status = 0;
            
            Guid activityId = GetActivityId();         
            
            unsafe
            {                
                status = UnsafeNativeMethods.EventWriteTransfer(
                                                m_regHandle, 
                                                ref eventDescriptor,
                                                (activityId == Guid.Empty) ? null : &activityId, 
                                                &relatedActivityId, 
                                                (uint)dataCount, 
                                                (void*)data);
            }

            if (status != 0)
            {
                SetLastError((int)status);
                return false;
            }
            return true;
        }

        [System.Security.SecurityCritical]
        private static Guid GetActivityId()
        {                        
            return Trace.CorrelationManager.ActivityId;
        }


        [System.Security.SecurityCritical]
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification="Does not expose Trace.CorrelationManager")]
        public static void SetActivityId(ref Guid id)
        {
            Trace.CorrelationManager.ActivityId = id;
            UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref id);
        }

        [System.Security.SecurityCritical]
        public static Guid CreateActivityId()
        {
            Guid newId = new Guid();
            UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId);
            return newId;
        }

    }
    
}