mscorlib(4.0.0.0) API with additions
EventSource.cs
1 using Microsoft.Reflection;
2 using Microsoft.Win32;
6 using System.Reflection;
7 using System.Resources;
11 using System.Security;
13 using System.Text;
14 using System.Threading;
15 using System.Threading.Tasks;
16 
18 {
20  [__DynamicallyInvokable]
21  public class EventSource : IDisposable
22  {
24  [__DynamicallyInvokable]
25  protected internal struct EventData
26  {
27  internal long m_Ptr;
28 
29  internal int m_Size;
30 
31  internal int m_Reserved;
32 
35  [__DynamicallyInvokable]
36  public IntPtr DataPointer
37  {
38  get
39  {
40  return (IntPtr)m_Ptr;
41  }
42  set
43  {
44  m_Ptr = (long)value;
45  }
46  }
47 
50  [__DynamicallyInvokable]
51  public int Size
52  {
53  [__DynamicallyInvokable]
54  get
55  {
56  return m_Size;
57  }
58  [__DynamicallyInvokable]
59  set
60  {
61  m_Size = value;
62  }
63  }
64 
65  [SecurityCritical]
66  internal unsafe void SetMetadata(byte* pointer, int size, int reserved)
67  {
68  m_Ptr = (long)(ulong)(UIntPtr)(void*)pointer;
69  m_Size = size;
70  m_Reserved = reserved;
71  }
72  }
73 
74  private struct Sha1ForNonSecretPurposes
75  {
76  private long length;
77 
78  private uint[] w;
79 
80  private int pos;
81 
82  public void Start()
83  {
84  if (w == null)
85  {
86  w = new uint[85];
87  }
88  length = 0L;
89  pos = 0;
90  w[80] = 1732584193u;
91  w[81] = 4023233417u;
92  w[82] = 2562383102u;
93  w[83] = 271733878u;
94  w[84] = 3285377520u;
95  }
96 
97  public void Append(byte input)
98  {
99  w[pos / 4] = ((w[pos / 4] << 8) | input);
100  if (64 == ++pos)
101  {
102  Drain();
103  }
104  }
105 
106  public void Append(byte[] input)
107  {
108  foreach (byte input2 in input)
109  {
110  Append(input2);
111  }
112  }
113 
114  public void Finish(byte[] output)
115  {
116  long num = length + 8 * pos;
117  Append(128);
118  while (pos != 56)
119  {
120  Append(0);
121  }
122  Append((byte)(num >> 56));
123  Append((byte)(num >> 48));
124  Append((byte)(num >> 40));
125  Append((byte)(num >> 32));
126  Append((byte)(num >> 24));
127  Append((byte)(num >> 16));
128  Append((byte)(num >> 8));
129  Append((byte)num);
130  int num2 = (output.Length < 20) ? output.Length : 20;
131  for (int i = 0; i != num2; i++)
132  {
133  uint num3 = w[80 + i / 4];
134  output[i] = (byte)(num3 >> 24);
135  w[80 + i / 4] = num3 << 8;
136  }
137  }
138 
139  private void Drain()
140  {
141  for (int i = 16; i != 80; i++)
142  {
143  w[i] = Rol1(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
144  }
145  uint num = w[80];
146  uint num2 = w[81];
147  uint num3 = w[82];
148  uint num4 = w[83];
149  uint num5 = w[84];
150  for (int j = 0; j != 20; j++)
151  {
152  uint num6 = (num2 & num3) | (~num2 & num4);
153  uint num7 = Rol5(num) + num6 + num5 + 1518500249 + w[j];
154  num5 = num4;
155  num4 = num3;
156  num3 = Rol30(num2);
157  num2 = num;
158  num = num7;
159  }
160  for (int k = 20; k != 40; k++)
161  {
162  uint num8 = num2 ^ num3 ^ num4;
163  uint num9 = Rol5(num) + num8 + num5 + 1859775393 + w[k];
164  num5 = num4;
165  num4 = num3;
166  num3 = Rol30(num2);
167  num2 = num;
168  num = num9;
169  }
170  for (int l = 40; l != 60; l++)
171  {
172  uint num10 = (num2 & num3) | (num2 & num4) | (num3 & num4);
173  uint num11 = (uint)((int)(Rol5(num) + num10 + num5) + -1894007588 + (int)w[l]);
174  num5 = num4;
175  num4 = num3;
176  num3 = Rol30(num2);
177  num2 = num;
178  num = num11;
179  }
180  for (int m = 60; m != 80; m++)
181  {
182  uint num12 = num2 ^ num3 ^ num4;
183  uint num13 = (uint)((int)(Rol5(num) + num12 + num5) + -899497514 + (int)w[m]);
184  num5 = num4;
185  num4 = num3;
186  num3 = Rol30(num2);
187  num2 = num;
188  num = num13;
189  }
190  w[80] += num;
191  w[81] += num2;
192  w[82] += num3;
193  w[83] += num4;
194  w[84] += num5;
195  length += 512L;
196  pos = 0;
197  }
198 
199  private static uint Rol1(uint input)
200  {
201  return (input << 1) | (input >> 31);
202  }
203 
204  private static uint Rol5(uint input)
205  {
206  return (input << 5) | (input >> 27);
207  }
208 
209  private static uint Rol30(uint input)
210  {
211  return (input << 30) | (input >> 2);
212  }
213  }
214 
215  private class OverideEventProvider : EventProvider
216  {
217  private EventSource m_eventSource;
218 
219  public OverideEventProvider(EventSource eventSource)
220  {
221  m_eventSource = eventSource;
222  }
223 
224  protected override void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int perEventSourceSessionId, int etwSessionId)
225  {
226  EventListener listener = null;
227  m_eventSource.SendCommand(listener, perEventSourceSessionId, etwSessionId, (EventCommand)command, IsEnabled(), base.Level, base.MatchAnyKeyword, arguments);
228  }
229  }
230 
231  internal struct EventMetadata
232  {
233  public EventDescriptor Descriptor;
234 
235  public EventTags Tags;
236 
237  public bool EnabledForAnyListener;
238 
239  public bool EnabledForETW;
240 
241  public bool HasRelatedActivityID;
242 
243  public byte TriggersActivityTracking;
244 
245  public string Name;
246 
247  public string Message;
248 
249  public ParameterInfo[] Parameters;
250 
251  public TraceLoggingEventTypes TraceLoggingEventTypes;
252 
253  public EventActivityOptions ActivityOptions;
254  }
255 
256  private string m_name;
257 
258  internal int m_id;
259 
260  private Guid m_guid;
261 
262  internal volatile EventMetadata[] m_eventData;
263 
264  private volatile byte[] m_rawManifest;
265 
266  private EventHandler<EventCommandEventArgs> m_eventCommandExecuted;
267 
268  private EventSourceSettings m_config;
269 
270  private bool m_eventSourceEnabled;
271 
272  internal EventLevel m_level;
273 
274  internal EventKeywords m_matchAnyKeyword;
275 
276  internal volatile EventDispatcher m_Dispatchers;
277 
278  private volatile OverideEventProvider m_provider;
279 
280  private bool m_completelyInited;
281 
282  private Exception m_constructionException;
283 
284  private byte m_outOfBandMessageCount;
285 
286  private EventCommandEventArgs m_deferredCommands;
287 
288  private string[] m_traits;
289 
290  internal static uint s_currentPid;
291 
292  [ThreadStatic]
293  private static byte m_EventSourceExceptionRecurenceCount = 0;
294 
295  internal volatile ulong[] m_channelData;
296 
297  private SessionMask m_curLiveSessions;
298 
299  private EtwSession[] m_etwSessionIdMap;
300 
301  private List<EtwSession> m_legacySessions;
302 
303  internal long m_keywordTriggers;
304 
305  internal SessionMask m_activityFilteringForETWEnabled;
306 
307  internal static Action<Guid> s_activityDying;
308 
309  private ActivityTracker m_activityTracker;
310 
311  internal const string s_ActivityStartSuffix = "Start";
312 
313  internal const string s_ActivityStopSuffix = "Stop";
314 
315  private static readonly byte[] namespaceBytes = new byte[16]
316  {
317  72,
318  44,
319  45,
320  178,
321  195,
322  144,
323  71,
324  200,
325  135,
326  248,
327  26,
328  21,
329  191,
330  193,
331  48,
332  251
333  };
334 
335  private static readonly Guid AspNetEventSourceGuid = new Guid("ee799f41-cfa5-550b-bf2c-344747c1c668");
336 
337  private byte[] providerMetadata;
338 
341  [__DynamicallyInvokable]
342  public string Name
343  {
344  [__DynamicallyInvokable]
345  get
346  {
347  return m_name;
348  }
349  }
350 
353  [__DynamicallyInvokable]
354  public Guid Guid
355  {
356  [__DynamicallyInvokable]
357  get
358  {
359  return m_guid;
360  }
361  }
362 
365  [__DynamicallyInvokable]
367  {
368  [__DynamicallyInvokable]
369  get
370  {
371  return m_config;
372  }
373  }
374 
377  [__DynamicallyInvokable]
378  public static Guid CurrentThreadActivityId
379  {
380  [SecuritySafeCritical]
381  [__DynamicallyInvokable]
382  get
383  {
384  Guid ActivityId = default(Guid);
385  UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_ID, ref ActivityId);
386  return ActivityId;
387  }
388  }
389 
390  internal static Guid InternalCurrentThreadActivityId
391  {
392  [SecurityCritical]
393  get
394  {
396  if (guid == Guid.Empty)
397  {
398  guid = FallbackActivityId;
399  }
400  return guid;
401  }
402  }
403 
404  internal static Guid FallbackActivityId
405  {
406  [SecurityCritical]
407  get
408  {
409  return new Guid((uint)AppDomain.GetCurrentThreadId(), (ushort)s_currentPid, (ushort)(s_currentPid >> 16), 148, 27, 135, 213, 166, 92, 54, 100);
410  }
411  }
412 
415  [__DynamicallyInvokable]
416  public Exception ConstructionException
417  {
418  [__DynamicallyInvokable]
419  get
420  {
421  return m_constructionException;
422  }
423  }
424 
425  private bool IsDisposed
426  {
427  get
428  {
429  if (m_provider != null)
430  {
431  return m_provider.m_disposed;
432  }
433  return true;
434  }
435  }
436 
437  private bool ThrowOnEventWriteErrors
438  {
439  get
440  {
441  return (m_config & EventSourceSettings.ThrowOnEventWriteErrors) != EventSourceSettings.Default;
442  }
443  set
444  {
445  if (value)
446  {
447  m_config |= EventSourceSettings.ThrowOnEventWriteErrors;
448  }
449  else
450  {
451  m_config &= ~EventSourceSettings.ThrowOnEventWriteErrors;
452  }
453  }
454  }
455 
456  private bool SelfDescribingEvents
457  {
458  get
459  {
460  return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != EventSourceSettings.Default;
461  }
462  set
463  {
464  if (!value)
465  {
466  m_config |= EventSourceSettings.EtwManifestEventFormat;
467  m_config &= ~EventSourceSettings.EtwSelfDescribingEventFormat;
468  }
469  else
470  {
471  m_config |= EventSourceSettings.EtwSelfDescribingEventFormat;
472  m_config &= ~EventSourceSettings.EtwManifestEventFormat;
473  }
474  }
475  }
476 
478  public event EventHandler<EventCommandEventArgs> EventCommandExecuted
479  {
480  add
481  {
482  m_eventCommandExecuted = (EventHandler<EventCommandEventArgs>)Delegate.Combine(m_eventCommandExecuted, value);
483  for (EventCommandEventArgs eventCommandEventArgs = m_deferredCommands; eventCommandEventArgs != null; eventCommandEventArgs = eventCommandEventArgs.nextCommand)
484  {
485  value(this, eventCommandEventArgs);
486  }
487  }
488  remove
489  {
490  m_eventCommandExecuted = (EventHandler<EventCommandEventArgs>)Delegate.Remove(m_eventCommandExecuted, value);
491  }
492  }
493 
497  [__DynamicallyInvokable]
498  public bool IsEnabled()
499  {
500  return m_eventSourceEnabled;
501  }
502 
508  [__DynamicallyInvokable]
509  public bool IsEnabled(EventLevel level, EventKeywords keywords)
510  {
511  return IsEnabled(level, keywords, EventChannel.None);
512  }
513 
520  [__DynamicallyInvokable]
521  public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel)
522  {
523  if (!m_eventSourceEnabled)
524  {
525  return false;
526  }
527  if (!IsEnabledCommon(m_eventSourceEnabled, m_level, m_matchAnyKeyword, level, keywords, channel))
528  {
529  return false;
530  }
531  return true;
532  }
533 
537  [__DynamicallyInvokable]
538  public static Guid GetGuid(Type eventSourceType)
539  {
540  if (eventSourceType == null)
541  {
542  throw new ArgumentNullException("eventSourceType");
543  }
544  EventSourceAttribute eventSourceAttribute = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute));
545  string name = eventSourceType.Name;
546  if (eventSourceAttribute != null)
547  {
548  if (eventSourceAttribute.Guid != null)
549  {
550  Guid result = Guid.Empty;
551  if (Guid.TryParse(eventSourceAttribute.Guid, out result))
552  {
553  return result;
554  }
555  }
556  if (eventSourceAttribute.Name != null)
557  {
558  name = eventSourceAttribute.Name;
559  }
560  }
561  if (name == null)
562  {
563  throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeName"), "eventSourceType");
564  }
565  return GenerateGuidFromName(name.ToUpperInvariant());
566  }
567 
571  [__DynamicallyInvokable]
572  public static string GetName(Type eventSourceType)
573  {
574  return GetName(eventSourceType, EventManifestOptions.None);
575  }
576 
581  [__DynamicallyInvokable]
582  public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest)
583  {
584  return GenerateManifest(eventSourceType, assemblyPathToIncludeInManifest, EventManifestOptions.None);
585  }
586 
592  [__DynamicallyInvokable]
593  public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags)
594  {
595  if (eventSourceType == null)
596  {
597  throw new ArgumentNullException("eventSourceType");
598  }
599  byte[] array = CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags);
600  if (array != null)
601  {
602  return Encoding.UTF8.GetString(array, 0, array.Length);
603  }
604  return null;
605  }
606 
609  [__DynamicallyInvokable]
611  {
613  lock (EventListener.EventListenersLock)
614  {
615  foreach (WeakReference s_EventSource in EventListener.s_EventSources)
616  {
617  EventSource eventSource = s_EventSource.Target as EventSource;
618  if (eventSource != null && !eventSource.IsDisposed)
619  {
620  list.Add(eventSource);
621  }
622  }
623  return list;
624  }
625  }
626 
631  [__DynamicallyInvokable]
632  public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary<string, string> commandArguments)
633  {
634  if (eventSource == null)
635  {
636  throw new ArgumentNullException("eventSource");
637  }
638  if (command <= EventCommand.Update && command != EventCommand.SendManifest)
639  {
640  throw new ArgumentException(Environment.GetResourceString("EventSource_InvalidCommand"), "command");
641  }
642  eventSource.SendCommand(null, 0, 0, command, enable: true, EventLevel.LogAlways, EventKeywords.None, commandArguments);
643  }
644 
647  [SecuritySafeCritical]
648  [__DynamicallyInvokable]
649  public static void SetCurrentThreadActivityId(Guid activityId)
650  {
651  Guid a = activityId;
652  if (UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref activityId) == 0)
653  {
654  Action<Guid> action = s_activityDying;
655  if (action != null && a != activityId)
656  {
657  if (activityId == Guid.Empty)
658  {
659  activityId = FallbackActivityId;
660  }
661  action(activityId);
662  }
663  }
664  if (TplEtwProvider.Log != null)
665  {
666  TplEtwProvider.Log.SetActivityId(activityId);
667  }
668  }
669 
673  [SecuritySafeCritical]
674  [__DynamicallyInvokable]
675  public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
676  {
677  oldActivityThatWillContinue = activityId;
678  UnsafeNativeMethods.ManifestEtw.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref oldActivityThatWillContinue);
679  if (TplEtwProvider.Log != null)
680  {
681  TplEtwProvider.Log.SetActivityId(activityId);
682  }
683  }
684 
688  [__DynamicallyInvokable]
689  public string GetTrait(string key)
690  {
691  if (m_traits != null)
692  {
693  for (int i = 0; i < m_traits.Length - 1; i += 2)
694  {
695  if (m_traits[i] == key)
696  {
697  return m_traits[i + 1];
698  }
699  }
700  }
701  return null;
702  }
703 
706  [__DynamicallyInvokable]
707  public override string ToString()
708  {
709  return Environment.GetResourceString("EventSource_ToString", Name, Guid);
710  }
711 
713  [__DynamicallyInvokable]
714  protected EventSource()
716  {
717  }
718 
722  [__DynamicallyInvokable]
723  protected EventSource(bool throwOnEventWriteErrors)
724  : this((EventSourceSettings)(4 | (throwOnEventWriteErrors ? 1 : 0)))
725  {
726  }
727 
730  [__DynamicallyInvokable]
731  protected EventSource(EventSourceSettings settings)
732  : this(settings, (string[])null)
733  {
734  }
735 
741  [__DynamicallyInvokable]
742  protected EventSource(EventSourceSettings settings, params string[] traits)
743  {
744  m_config = ValidateSettings(settings);
745  Type type = GetType();
746  Initialize(GetGuid(type), GetName(type), traits);
747  }
748 
751  [__DynamicallyInvokable]
752  protected virtual void OnEventCommand(EventCommandEventArgs command)
753  {
754  }
755 
758  [SecuritySafeCritical]
759  [__DynamicallyInvokable]
760  protected void WriteEvent(int eventId)
761  {
762  WriteEventCore(eventId, 0, null);
763  }
764 
769  [SecuritySafeCritical]
770  [__DynamicallyInvokable]
771  protected unsafe void WriteEvent(int eventId, int arg1)
772  {
773  if (m_eventSourceEnabled)
774  {
775  EventData* ptr = stackalloc EventData[1];
776  ptr->DataPointer = (IntPtr)(void*)(&arg1);
777  ptr->Size = 4;
778  WriteEventCore(eventId, 1, ptr);
779  }
780  }
781 
786  [SecuritySafeCritical]
787  [__DynamicallyInvokable]
788  protected unsafe void WriteEvent(int eventId, int arg1, int arg2)
789  {
790  if (m_eventSourceEnabled)
791  {
792  EventData* ptr = stackalloc EventData[2];
793  ptr->DataPointer = (IntPtr)(void*)(&arg1);
794  ptr->Size = 4;
795  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
796  ptr[1].Size = 4;
797  WriteEventCore(eventId, 2, ptr);
798  }
799  }
800 
806  [SecuritySafeCritical]
807  [__DynamicallyInvokable]
808  protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3)
809  {
810  if (m_eventSourceEnabled)
811  {
812  EventData* ptr = stackalloc EventData[3];
813  ptr->DataPointer = (IntPtr)(void*)(&arg1);
814  ptr->Size = 4;
815  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
816  ptr[1].Size = 4;
817  ptr[2].DataPointer = (IntPtr)(void*)(&arg3);
818  ptr[2].Size = 4;
819  WriteEventCore(eventId, 3, ptr);
820  }
821  }
822 
826  [SecuritySafeCritical]
827  [__DynamicallyInvokable]
828  protected unsafe void WriteEvent(int eventId, long arg1)
829  {
830  if (m_eventSourceEnabled)
831  {
832  EventData* ptr = stackalloc EventData[1];
833  ptr->DataPointer = (IntPtr)(void*)(&arg1);
834  ptr->Size = 8;
835  WriteEventCore(eventId, 1, ptr);
836  }
837  }
838 
843  [SecuritySafeCritical]
844  [__DynamicallyInvokable]
845  protected unsafe void WriteEvent(int eventId, long arg1, long arg2)
846  {
847  if (m_eventSourceEnabled)
848  {
849  EventData* ptr = stackalloc EventData[2];
850  ptr->DataPointer = (IntPtr)(void*)(&arg1);
851  ptr->Size = 8;
852  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
853  ptr[1].Size = 8;
854  WriteEventCore(eventId, 2, ptr);
855  }
856  }
857 
863  [SecuritySafeCritical]
864  [__DynamicallyInvokable]
865  protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3)
866  {
867  if (m_eventSourceEnabled)
868  {
869  EventData* ptr = stackalloc EventData[3];
870  ptr->DataPointer = (IntPtr)(void*)(&arg1);
871  ptr->Size = 8;
872  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
873  ptr[1].Size = 8;
874  ptr[2].DataPointer = (IntPtr)(void*)(&arg3);
875  ptr[2].Size = 8;
876  WriteEventCore(eventId, 3, ptr);
877  }
878  }
879 
883  [SecuritySafeCritical]
884  [__DynamicallyInvokable]
885  protected unsafe void WriteEvent(int eventId, string arg1)
886  {
887  if (m_eventSourceEnabled)
888  {
889  if (arg1 == null)
890  {
891  arg1 = "";
892  }
893  fixed (char* value = arg1)
894  {
895  EventData* ptr = stackalloc EventData[1];
896  ptr->DataPointer = (IntPtr)(void*)value;
897  ptr->Size = (arg1.Length + 1) * 2;
898  WriteEventCore(eventId, 1, ptr);
899  }
900  }
901  }
902 
907  [SecuritySafeCritical]
908  [__DynamicallyInvokable]
909  protected unsafe void WriteEvent(int eventId, string arg1, string arg2)
910  {
911  if (m_eventSourceEnabled)
912  {
913  if (arg1 == null)
914  {
915  arg1 = "";
916  }
917  if (arg2 == null)
918  {
919  arg2 = "";
920  }
921  fixed (char* value = arg1)
922  {
923  fixed (char* value2 = arg2)
924  {
925  EventData* ptr = stackalloc EventData[2];
926  ptr->DataPointer = (IntPtr)(void*)value;
927  ptr->Size = (arg1.Length + 1) * 2;
928  ptr[1].DataPointer = (IntPtr)(void*)value2;
929  ptr[1].Size = (arg2.Length + 1) * 2;
930  WriteEventCore(eventId, 2, ptr);
931  }
932  }
933  }
934  }
935 
941  [SecuritySafeCritical]
942  [__DynamicallyInvokable]
943  protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3)
944  {
945  if (m_eventSourceEnabled)
946  {
947  if (arg1 == null)
948  {
949  arg1 = "";
950  }
951  if (arg2 == null)
952  {
953  arg2 = "";
954  }
955  if (arg3 == null)
956  {
957  arg3 = "";
958  }
959  fixed (char* value = arg1)
960  {
961  fixed (char* value2 = arg2)
962  {
963  fixed (char* value3 = arg3)
964  {
965  EventData* ptr = stackalloc EventData[3];
966  ptr->DataPointer = (IntPtr)(void*)value;
967  ptr->Size = (arg1.Length + 1) * 2;
968  ptr[1].DataPointer = (IntPtr)(void*)value2;
969  ptr[1].Size = (arg2.Length + 1) * 2;
970  ptr[2].DataPointer = (IntPtr)(void*)value3;
971  ptr[2].Size = (arg3.Length + 1) * 2;
972  WriteEventCore(eventId, 3, ptr);
973  }
974  }
975  }
976  }
977  }
978 
983  [SecuritySafeCritical]
984  [__DynamicallyInvokable]
985  protected unsafe void WriteEvent(int eventId, string arg1, int arg2)
986  {
987  if (m_eventSourceEnabled)
988  {
989  if (arg1 == null)
990  {
991  arg1 = "";
992  }
993  fixed (char* value = arg1)
994  {
995  EventData* ptr = stackalloc EventData[2];
996  ptr->DataPointer = (IntPtr)(void*)value;
997  ptr->Size = (arg1.Length + 1) * 2;
998  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
999  ptr[1].Size = 4;
1000  WriteEventCore(eventId, 2, ptr);
1001  }
1002  }
1003  }
1004 
1010  [SecuritySafeCritical]
1011  [__DynamicallyInvokable]
1012  protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3)
1013  {
1014  if (m_eventSourceEnabled)
1015  {
1016  if (arg1 == null)
1017  {
1018  arg1 = "";
1019  }
1020  fixed (char* value = arg1)
1021  {
1022  EventData* ptr = stackalloc EventData[3];
1023  ptr->DataPointer = (IntPtr)(void*)value;
1024  ptr->Size = (arg1.Length + 1) * 2;
1025  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
1026  ptr[1].Size = 4;
1027  ptr[2].DataPointer = (IntPtr)(void*)(&arg3);
1028  ptr[2].Size = 4;
1029  WriteEventCore(eventId, 3, ptr);
1030  }
1031  }
1032  }
1033 
1038  [SecuritySafeCritical]
1039  [__DynamicallyInvokable]
1040  protected unsafe void WriteEvent(int eventId, string arg1, long arg2)
1041  {
1042  if (m_eventSourceEnabled)
1043  {
1044  if (arg1 == null)
1045  {
1046  arg1 = "";
1047  }
1048  fixed (char* value = arg1)
1049  {
1050  EventData* ptr = stackalloc EventData[2];
1051  ptr->DataPointer = (IntPtr)(void*)value;
1052  ptr->Size = (arg1.Length + 1) * 2;
1053  ptr[1].DataPointer = (IntPtr)(void*)(&arg2);
1054  ptr[1].Size = 8;
1055  WriteEventCore(eventId, 2, ptr);
1056  }
1057  }
1058  }
1059 
1064  [SecuritySafeCritical]
1065  [__DynamicallyInvokable]
1066  protected unsafe void WriteEvent(int eventId, long arg1, string arg2)
1067  {
1068  if (m_eventSourceEnabled)
1069  {
1070  if (arg2 == null)
1071  {
1072  arg2 = "";
1073  }
1074  fixed (char* value = arg2)
1075  {
1076  EventData* ptr = stackalloc EventData[2];
1077  ptr->DataPointer = (IntPtr)(void*)(&arg1);
1078  ptr->Size = 8;
1079  ptr[1].DataPointer = (IntPtr)(void*)value;
1080  ptr[1].Size = (arg2.Length + 1) * 2;
1081  WriteEventCore(eventId, 2, ptr);
1082  }
1083  }
1084  }
1085 
1090  [SecuritySafeCritical]
1091  [__DynamicallyInvokable]
1092  protected unsafe void WriteEvent(int eventId, int arg1, string arg2)
1093  {
1094  if (m_eventSourceEnabled)
1095  {
1096  if (arg2 == null)
1097  {
1098  arg2 = "";
1099  }
1100  fixed (char* value = arg2)
1101  {
1102  EventData* ptr = stackalloc EventData[2];
1103  ptr->DataPointer = (IntPtr)(void*)(&arg1);
1104  ptr->Size = 4;
1105  ptr[1].DataPointer = (IntPtr)(void*)value;
1106  ptr[1].Size = (arg2.Length + 1) * 2;
1107  WriteEventCore(eventId, 2, ptr);
1108  }
1109  }
1110  }
1111 
1115  [SecuritySafeCritical]
1116  [__DynamicallyInvokable]
1117  protected unsafe void WriteEvent(int eventId, byte[] arg1)
1118  {
1119  if (m_eventSourceEnabled)
1120  {
1121  if (arg1 == null)
1122  {
1123  arg1 = new byte[0];
1124  }
1125  int size = arg1.Length;
1126  fixed (byte* value = &arg1[0])
1127  {
1128  EventData* ptr = stackalloc EventData[2];
1129  ptr->DataPointer = (IntPtr)(void*)(&size);
1130  ptr->Size = 4;
1131  ptr[1].DataPointer = (IntPtr)(void*)value;
1132  ptr[1].Size = size;
1133  WriteEventCore(eventId, 2, ptr);
1134  }
1135  }
1136  }
1137 
1142  [SecuritySafeCritical]
1143  [__DynamicallyInvokable]
1144  protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2)
1145  {
1146  if (m_eventSourceEnabled)
1147  {
1148  if (arg2 == null)
1149  {
1150  arg2 = new byte[0];
1151  }
1152  int size = arg2.Length;
1153  fixed (byte* value = &arg2[0])
1154  {
1155  EventData* ptr = stackalloc EventData[3];
1156  ptr->DataPointer = (IntPtr)(void*)(&arg1);
1157  ptr->Size = 8;
1158  ptr[1].DataPointer = (IntPtr)(void*)(&size);
1159  ptr[1].Size = 4;
1160  ptr[2].DataPointer = (IntPtr)(void*)value;
1161  ptr[2].Size = size;
1162  WriteEventCore(eventId, 3, ptr);
1163  }
1164  }
1165  }
1166 
1171  [SecurityCritical]
1172  [CLSCompliant(false)]
1173  protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventData* data)
1174  {
1175  WriteEventWithRelatedActivityIdCore(eventId, null, eventDataCount, data);
1176  }
1177 
1183  [SecurityCritical]
1184  [CLSCompliant(false)]
1185  protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventData* data)
1186  {
1187  if (m_eventSourceEnabled)
1188  {
1189  try
1190  {
1191  if (relatedActivityId != null)
1192  {
1193  ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
1194  }
1195  if (m_eventData[eventId].EnabledForETW)
1196  {
1197  EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
1198  EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
1199  Guid* activityID = null;
1200  Guid activityId = Guid.Empty;
1201  Guid relatedActivityId2 = Guid.Empty;
1202  if (opcode != 0 && relatedActivityId == null && (activityOptions & EventActivityOptions.Disable) == EventActivityOptions.None)
1203  {
1204  switch (opcode)
1205  {
1206  case EventOpcode.Start:
1207  m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId2, m_eventData[eventId].ActivityOptions);
1208  break;
1209  case EventOpcode.Stop:
1210  m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
1211  break;
1212  }
1213  if (activityId != Guid.Empty)
1214  {
1215  activityID = &activityId;
1216  }
1217  if (relatedActivityId2 != Guid.Empty)
1218  {
1219  relatedActivityId = &relatedActivityId2;
1220  }
1221  }
1222  SessionMask m = SessionMask.All;
1223  if ((ulong)m_curLiveSessions != 0L)
1224  {
1225  m = GetEtwSessionMask(eventId, relatedActivityId);
1226  }
1227  if ((ulong)m != 0L || (m_legacySessions != null && m_legacySessions.Count > 0))
1228  {
1229  if (!SelfDescribingEvents)
1230  {
1231  if (m.IsEqualOrSupersetOf(m_curLiveSessions))
1232  {
1233  if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, activityID, relatedActivityId, eventDataCount, (IntPtr)(void*)data))
1234  {
1235  ThrowEventSourceException(m_eventData[eventId].Name);
1236  }
1237  }
1238  else
1239  {
1240  long num = m_eventData[eventId].Descriptor.Keywords & (long)(~SessionMask.All.ToEventKeywords());
1241  EventDescriptor eventDescriptor = new EventDescriptor(m_eventData[eventId].Descriptor.EventId, m_eventData[eventId].Descriptor.Version, m_eventData[eventId].Descriptor.Channel, m_eventData[eventId].Descriptor.Level, m_eventData[eventId].Descriptor.Opcode, m_eventData[eventId].Descriptor.Task, (long)m.ToEventKeywords() | num);
1242  if (!m_provider.WriteEvent(ref eventDescriptor, activityID, relatedActivityId, eventDataCount, (IntPtr)(void*)data))
1243  {
1244  ThrowEventSourceException(m_eventData[eventId].Name);
1245  }
1246  }
1247  }
1248  else
1249  {
1250  TraceLoggingEventTypes traceLoggingEventTypes = m_eventData[eventId].TraceLoggingEventTypes;
1251  if (traceLoggingEventTypes == null)
1252  {
1253  traceLoggingEventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name, EventTags.None, m_eventData[eventId].Parameters);
1254  Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, traceLoggingEventTypes, null);
1255  }
1256  long num2 = m_eventData[eventId].Descriptor.Keywords & (long)(~SessionMask.All.ToEventKeywords());
1257  EventSourceOptions eventSourceOptions = default(EventSourceOptions);
1258  eventSourceOptions.Keywords = (EventKeywords)((long)m.ToEventKeywords() | num2);
1259  eventSourceOptions.Level = (EventLevel)m_eventData[eventId].Descriptor.Level;
1260  eventSourceOptions.Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
1261  EventSourceOptions options = eventSourceOptions;
1262  WriteMultiMerge(m_eventData[eventId].Name, ref options, traceLoggingEventTypes, activityID, relatedActivityId, data);
1263  }
1264  }
1265  }
1266  if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener)
1267  {
1268  WriteToAllListeners(eventId, relatedActivityId, eventDataCount, data);
1269  }
1270  }
1271  catch (Exception ex)
1272  {
1273  if (ex is EventSourceException)
1274  {
1275  throw;
1276  }
1277  ThrowEventSourceException(m_eventData[eventId].Name, ex);
1278  }
1279  }
1280  }
1281 
1285  [SecuritySafeCritical]
1286  [__DynamicallyInvokable]
1287  protected void WriteEvent(int eventId, params object[] args)
1288  {
1289  WriteEventVarargs(eventId, null, args);
1290  }
1291 
1296  [SecuritySafeCritical]
1297  [__DynamicallyInvokable]
1298  protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args)
1299  {
1300  WriteEventVarargs(eventId, &relatedActivityId, args);
1301  }
1302 
1304  [__DynamicallyInvokable]
1305  public void Dispose()
1306  {
1307  Dispose(disposing: true);
1308  GC.SuppressFinalize(this);
1309  }
1310 
1314  [__DynamicallyInvokable]
1315  protected virtual void Dispose(bool disposing)
1316  {
1317  if (disposing)
1318  {
1319  if (m_eventSourceEnabled)
1320  {
1321  try
1322  {
1323  SendManifest(m_rawManifest);
1324  }
1325  catch (Exception)
1326  {
1327  }
1328  m_eventSourceEnabled = false;
1329  }
1330  if (m_provider != null)
1331  {
1332  m_provider.Dispose();
1333  m_provider = null;
1334  }
1335  }
1336  m_eventSourceEnabled = false;
1337  }
1338 
1340  [__DynamicallyInvokable]
1341  ~EventSource()
1342  {
1343  Dispose(disposing: false);
1344  }
1345 
1346  internal void WriteStringToListener(EventListener listener, string msg, SessionMask m)
1347  {
1348  if (m_eventSourceEnabled)
1349  {
1350  if (listener == null)
1351  {
1352  WriteEventString(EventLevel.LogAlways, (long)m.ToEventKeywords(), msg);
1353  return;
1354  }
1355  List<object> list = new List<object>();
1356  list.Add(msg);
1357  EventWrittenEventArgs eventWrittenEventArgs = new EventWrittenEventArgs(this);
1358  eventWrittenEventArgs.EventId = 0;
1359  eventWrittenEventArgs.Payload = new ReadOnlyCollection<object>(list);
1360  listener.OnEventWritten(eventWrittenEventArgs);
1361  }
1362  }
1363 
1364  [SecurityCritical]
1365  private unsafe void WriteEventRaw(string eventName, ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data)
1366  {
1367  if (m_provider == null)
1368  {
1369  ThrowEventSourceException(eventName);
1370  }
1371  else if (!m_provider.WriteEventRaw(ref eventDescriptor, activityID, relatedActivityID, dataCount, data))
1372  {
1373  ThrowEventSourceException(eventName);
1374  }
1375  }
1376 
1377  internal EventSource(Guid eventSourceGuid, string eventSourceName)
1378  : this(eventSourceGuid, eventSourceName, EventSourceSettings.EtwManifestEventFormat)
1379  {
1380  }
1381 
1382  internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[] traits = null)
1383  {
1384  m_config = ValidateSettings(settings);
1385  Initialize(eventSourceGuid, eventSourceName, traits);
1386  }
1387 
1388  [SecuritySafeCritical]
1389  private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits)
1390  {
1391  try
1392  {
1393  m_traits = traits;
1394  if (m_traits != null && m_traits.Length % 2 != 0)
1395  {
1396  throw new ArgumentException(Environment.GetResourceString("TraitEven"), "traits");
1397  }
1398  if (eventSourceGuid == Guid.Empty)
1399  {
1400  throw new ArgumentException(Environment.GetResourceString("EventSource_NeedGuid"));
1401  }
1402  if (eventSourceName == null)
1403  {
1404  throw new ArgumentException(Environment.GetResourceString("EventSource_NeedName"));
1405  }
1406  m_name = eventSourceName;
1407  m_guid = eventSourceGuid;
1408  m_curLiveSessions = new SessionMask(0u);
1409  m_etwSessionIdMap = new EtwSession[4];
1410  m_activityTracker = ActivityTracker.Instance;
1411  InitializeProviderMetadata();
1412  OverideEventProvider overideEventProvider = new OverideEventProvider(this);
1413  overideEventProvider.Register(eventSourceGuid);
1414  EventListener.AddEventSource(this);
1415  m_provider = overideEventProvider;
1416  int num = Environment.OSVersion.Version.Major * 10 + Environment.OSVersion.Version.Minor;
1417  if (Name != "System.Diagnostics.Eventing.FrameworkEventSource" || num >= 62)
1418  {
1419  try
1420  {
1421  byte[] array = providerMetadata;
1422  fixed (IntPtr* data = array)
1423  {
1424  int num2 = m_provider.SetInformation(UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS.SetTraits, data, providerMetadata.Length);
1425  }
1426  }
1427  finally
1428  {
1429  }
1430  }
1431  m_completelyInited = true;
1432  }
1433  catch (Exception ex)
1434  {
1435  if (m_constructionException == null)
1436  {
1437  m_constructionException = ex;
1438  }
1439  ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + ex.Message, flush: true);
1440  }
1441  lock (EventListener.EventListenersLock)
1442  {
1443  for (EventCommandEventArgs eventCommandEventArgs = m_deferredCommands; eventCommandEventArgs != null; eventCommandEventArgs = eventCommandEventArgs.nextCommand)
1444  {
1445  DoCommand(eventCommandEventArgs);
1446  }
1447  }
1448  }
1449 
1450  private static string GetName(Type eventSourceType, EventManifestOptions flags)
1451  {
1452  if (eventSourceType == null)
1453  {
1454  throw new ArgumentNullException("eventSourceType");
1455  }
1456  EventSourceAttribute eventSourceAttribute = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags);
1457  if (eventSourceAttribute != null && eventSourceAttribute.Name != null)
1458  {
1459  return eventSourceAttribute.Name;
1460  }
1461  return eventSourceType.Name;
1462  }
1463 
1464  private static Guid GenerateGuidFromName(string name)
1465  {
1466  byte[] array = Encoding.BigEndianUnicode.GetBytes(name);
1467  Sha1ForNonSecretPurposes sha1ForNonSecretPurposes = default(Sha1ForNonSecretPurposes);
1468  sha1ForNonSecretPurposes.Start();
1469  sha1ForNonSecretPurposes.Append(namespaceBytes);
1470  sha1ForNonSecretPurposes.Append(array);
1471  Array.Resize(ref array, 16);
1472  sha1ForNonSecretPurposes.Finish(array);
1473  array[7] = (byte)((array[7] & 0xF) | 0x50);
1474  return new Guid(array);
1475  }
1476 
1477  [SecurityCritical]
1478  private unsafe object DecodeObject(int eventId, int parameterId, ref EventData* data)
1479  {
1480  IntPtr dataPointer = data->DataPointer;
1481  data++;
1482  Type type = m_eventData[eventId].Parameters[parameterId].ParameterType;
1483  while (true)
1484  {
1485  if (type == typeof(IntPtr))
1486  {
1487  return *(IntPtr*)(void*)dataPointer;
1488  }
1489  if (type == typeof(int))
1490  {
1491  return *(int*)(void*)dataPointer;
1492  }
1493  if (type == typeof(uint))
1494  {
1495  return *(uint*)(void*)dataPointer;
1496  }
1497  if (type == typeof(long))
1498  {
1499  return *(long*)(void*)dataPointer;
1500  }
1501  if (type == typeof(ulong))
1502  {
1503  return (ulong)(*(long*)(void*)dataPointer);
1504  }
1505  if (type == typeof(byte))
1506  {
1507  return *(byte*)(void*)dataPointer;
1508  }
1509  if (type == typeof(sbyte))
1510  {
1511  return *(sbyte*)(void*)dataPointer;
1512  }
1513  if (type == typeof(short))
1514  {
1515  return *(short*)(void*)dataPointer;
1516  }
1517  if (type == typeof(ushort))
1518  {
1519  return *(ushort*)(void*)dataPointer;
1520  }
1521  if (type == typeof(float))
1522  {
1523  return *(float*)(void*)dataPointer;
1524  }
1525  if (type == typeof(double))
1526  {
1527  return *(double*)(void*)dataPointer;
1528  }
1529  if (type == typeof(decimal))
1530  {
1531  return *(decimal*)(void*)dataPointer;
1532  }
1533  if (type == typeof(bool))
1534  {
1535  if (*(int*)(void*)dataPointer == 1)
1536  {
1537  return true;
1538  }
1539  return false;
1540  }
1541  if (type == typeof(Guid))
1542  {
1543  return *(Guid*)(void*)dataPointer;
1544  }
1545  if (type == typeof(char))
1546  {
1547  return (char)(*(ushort*)(void*)dataPointer);
1548  }
1549  if (type == typeof(DateTime))
1550  {
1551  long fileTime = *(long*)(void*)dataPointer;
1552  return DateTime.FromFileTimeUtc(fileTime);
1553  }
1554  if (type == typeof(byte[]))
1555  {
1556  int num = *(int*)(void*)dataPointer;
1557  byte[] array = new byte[num];
1558  dataPointer = data->DataPointer;
1559  data++;
1560  for (int i = 0; i < num; i++)
1561  {
1562  array[i] = ((byte*)(void*)dataPointer)[i];
1563  }
1564  return array;
1565  }
1566  if (type == typeof(byte*))
1567  {
1568  return null;
1569  }
1570  if (!type.IsEnum())
1571  {
1572  break;
1573  }
1574  type = Enum.GetUnderlyingType(type);
1575  }
1576  return Marshal.PtrToStringUni(dataPointer);
1577  }
1578 
1579  private EventDispatcher GetDispatcher(EventListener listener)
1580  {
1581  EventDispatcher eventDispatcher;
1582  for (eventDispatcher = m_Dispatchers; eventDispatcher != null; eventDispatcher = eventDispatcher.m_Next)
1583  {
1584  if (eventDispatcher.m_Listener == listener)
1585  {
1586  return eventDispatcher;
1587  }
1588  }
1589  return eventDispatcher;
1590  }
1591 
1592  [SecurityCritical]
1593  private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object[] args)
1594  {
1595  if (m_eventSourceEnabled)
1596  {
1597  try
1598  {
1599  if (childActivityID != null)
1600  {
1601  ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
1602  if (!m_eventData[eventId].HasRelatedActivityID)
1603  {
1604  throw new ArgumentException(Environment.GetResourceString("EventSource_NoRelatedActivityId"));
1605  }
1606  }
1607  LogEventArgsMismatches(m_eventData[eventId].Parameters, args);
1608  if (m_eventData[eventId].EnabledForETW)
1609  {
1610  Guid* activityID = null;
1611  Guid activityId = Guid.Empty;
1612  Guid relatedActivityId = Guid.Empty;
1613  EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
1614  EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
1615  if (childActivityID == null && (activityOptions & EventActivityOptions.Disable) == EventActivityOptions.None)
1616  {
1617  switch (opcode)
1618  {
1619  case EventOpcode.Start:
1620  m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions);
1621  break;
1622  case EventOpcode.Stop:
1623  m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
1624  break;
1625  }
1626  if (activityId != Guid.Empty)
1627  {
1628  activityID = &activityId;
1629  }
1630  if (relatedActivityId != Guid.Empty)
1631  {
1632  childActivityID = &relatedActivityId;
1633  }
1634  }
1635  SessionMask m = SessionMask.All;
1636  if ((ulong)m_curLiveSessions != 0L)
1637  {
1638  m = GetEtwSessionMask(eventId, childActivityID);
1639  }
1640  if ((ulong)m != 0L || (m_legacySessions != null && m_legacySessions.Count > 0))
1641  {
1642  if (!SelfDescribingEvents)
1643  {
1644  if (m.IsEqualOrSupersetOf(m_curLiveSessions))
1645  {
1646  if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, activityID, childActivityID, args))
1647  {
1648  ThrowEventSourceException(m_eventData[eventId].Name);
1649  }
1650  }
1651  else
1652  {
1653  long num = m_eventData[eventId].Descriptor.Keywords & (long)(~SessionMask.All.ToEventKeywords());
1654  EventDescriptor eventDescriptor = new EventDescriptor(m_eventData[eventId].Descriptor.EventId, m_eventData[eventId].Descriptor.Version, m_eventData[eventId].Descriptor.Channel, m_eventData[eventId].Descriptor.Level, m_eventData[eventId].Descriptor.Opcode, m_eventData[eventId].Descriptor.Task, (long)m.ToEventKeywords() | num);
1655  if (!m_provider.WriteEvent(ref eventDescriptor, activityID, childActivityID, args))
1656  {
1657  ThrowEventSourceException(m_eventData[eventId].Name);
1658  }
1659  }
1660  }
1661  else
1662  {
1663  TraceLoggingEventTypes traceLoggingEventTypes = m_eventData[eventId].TraceLoggingEventTypes;
1664  if (traceLoggingEventTypes == null)
1665  {
1666  traceLoggingEventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name, EventTags.None, m_eventData[eventId].Parameters);
1667  Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, traceLoggingEventTypes, null);
1668  }
1669  long num2 = m_eventData[eventId].Descriptor.Keywords & (long)(~SessionMask.All.ToEventKeywords());
1670  EventSourceOptions eventSourceOptions = default(EventSourceOptions);
1671  eventSourceOptions.Keywords = (EventKeywords)((long)m.ToEventKeywords() | num2);
1672  eventSourceOptions.Level = (EventLevel)m_eventData[eventId].Descriptor.Level;
1673  eventSourceOptions.Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
1674  EventSourceOptions options = eventSourceOptions;
1675  WriteMultiMerge(m_eventData[eventId].Name, ref options, traceLoggingEventTypes, activityID, childActivityID, args);
1676  }
1677  }
1678  }
1679  if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener)
1680  {
1681  if (AppContextSwitches.PreserveEventListnerObjectIdentity)
1682  {
1683  WriteToAllListeners(eventId, childActivityID, args);
1684  }
1685  else
1686  {
1687  object[] args2 = SerializeEventArgs(eventId, args);
1688  WriteToAllListeners(eventId, childActivityID, args2);
1689  }
1690  }
1691  }
1692  catch (Exception ex)
1693  {
1694  if (ex is EventSourceException)
1695  {
1696  throw;
1697  }
1698  ThrowEventSourceException(m_eventData[eventId].Name, ex);
1699  }
1700  }
1701  }
1702 
1703  [SecurityCritical]
1704  private object[] SerializeEventArgs(int eventId, object[] args)
1705  {
1706  TraceLoggingEventTypes traceLoggingEventTypes = m_eventData[eventId].TraceLoggingEventTypes;
1707  if (traceLoggingEventTypes == null)
1708  {
1709  traceLoggingEventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name, EventTags.None, m_eventData[eventId].Parameters);
1710  Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, traceLoggingEventTypes, null);
1711  }
1712  object[] array = new object[traceLoggingEventTypes.typeInfos.Length];
1713  for (int i = 0; i < traceLoggingEventTypes.typeInfos.Length; i++)
1714  {
1715  array[i] = traceLoggingEventTypes.typeInfos[i].GetData(args[i]);
1716  }
1717  return array;
1718  }
1719 
1720  private void LogEventArgsMismatches(ParameterInfo[] infos, object[] args)
1721  {
1722  bool flag = args.Length == infos.Length;
1723  int num = 0;
1724  while (flag && num < args.Length)
1725  {
1726  Type parameterType = infos[num].ParameterType;
1727  if ((args[num] != null && args[num].GetType() != parameterType) || (args[num] == null && (!parameterType.IsGenericType || !(parameterType.GetGenericTypeDefinition() == typeof(Nullable<>)))))
1728  {
1729  flag = false;
1730  break;
1731  }
1732  num++;
1733  }
1734  if (!flag)
1735  {
1736  Debugger.Log(0, null, Environment.GetResourceString("EventSource_VarArgsParameterMismatch") + "\r\n");
1737  }
1738  }
1739 
1740  private int GetParamLengthIncludingByteArray(ParameterInfo[] parameters)
1741  {
1742  int num = 0;
1743  foreach (ParameterInfo parameterInfo in parameters)
1744  {
1745  num = ((!(parameterInfo.ParameterType == typeof(byte[]))) ? (num + 1) : (num + 2));
1746  }
1747  return num;
1748  }
1749 
1750  [SecurityCritical]
1751  private unsafe void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventData* data)
1752  {
1753  int num = m_eventData[eventId].Parameters.Length;
1754  int paramLengthIncludingByteArray = GetParamLengthIncludingByteArray(m_eventData[eventId].Parameters);
1755  if (eventDataCount != paramLengthIncludingByteArray)
1756  {
1757  ReportOutOfBandMessage(Environment.GetResourceString("EventSource_EventParametersMismatch", eventId, eventDataCount, num), flush: true);
1758  num = Math.Min(num, eventDataCount);
1759  }
1760  object[] array = new object[num];
1761  EventData* data2 = data;
1762  for (int i = 0; i < num; i++)
1763  {
1764  array[i] = DecodeObject(eventId, i, ref data2);
1765  }
1766  WriteToAllListeners(eventId, childActivityID, array);
1767  }
1768 
1769  [SecurityCritical]
1770  private unsafe void WriteToAllListeners(int eventId, Guid* childActivityID, params object[] args)
1771  {
1772  EventWrittenEventArgs eventWrittenEventArgs = new EventWrittenEventArgs(this);
1773  eventWrittenEventArgs.EventId = eventId;
1774  if (childActivityID != null)
1775  {
1776  eventWrittenEventArgs.RelatedActivityId = *childActivityID;
1777  }
1778  eventWrittenEventArgs.EventName = m_eventData[eventId].Name;
1779  eventWrittenEventArgs.Message = m_eventData[eventId].Message;
1780  eventWrittenEventArgs.Payload = new ReadOnlyCollection<object>(args);
1781  DispatchToAllListeners(eventId, childActivityID, eventWrittenEventArgs);
1782  }
1783 
1784  [SecurityCritical]
1785  private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs)
1786  {
1787  Exception ex = null;
1788  for (EventDispatcher eventDispatcher = m_Dispatchers; eventDispatcher != null; eventDispatcher = eventDispatcher.m_Next)
1789  {
1790  if (eventId == -1 || eventDispatcher.m_EventEnabled[eventId])
1791  {
1792  ActivityFilter activityFilter = eventDispatcher.m_Listener.m_activityFilter;
1793  if (activityFilter == null || ActivityFilter.PassesActivityFilter(activityFilter, childActivityID, m_eventData[eventId].TriggersActivityTracking > 0, this, eventId) || !eventDispatcher.m_activityFilteringEnabled)
1794  {
1795  try
1796  {
1797  eventDispatcher.m_Listener.OnEventWritten(eventCallbackArgs);
1798  }
1799  catch (Exception ex2)
1800  {
1801  ReportOutOfBandMessage("ERROR: Exception during EventSource.OnEventWritten: " + ex2.Message, flush: false);
1802  ex = ex2;
1803  }
1804  }
1805  }
1806  }
1807  if (ex != null)
1808  {
1809  throw new EventSourceException(ex);
1810  }
1811  }
1812 
1813  [SecuritySafeCritical]
1814  private unsafe void WriteEventString(EventLevel level, long keywords, string msgString)
1815  {
1816  if (m_provider == null)
1817  {
1818  return;
1819  }
1820  string text = "EventSourceMessage";
1821  if (SelfDescribingEvents)
1822  {
1823  EventSourceOptions eventSourceOptions = default(EventSourceOptions);
1824  eventSourceOptions.Keywords = (EventKeywords)keywords;
1825  eventSourceOptions.Level = level;
1826  EventSourceOptions options = eventSourceOptions;
1827  var anon = new
1828  {
1829  message = msgString
1830  };
1831  TraceLoggingEventTypes eventTypes = new TraceLoggingEventTypes(text, EventTags.None, anon.GetType());
1832  WriteMultiMergeInner(text, ref options, eventTypes, null, null, anon);
1833  return;
1834  }
1835  if (m_rawManifest == null && m_outOfBandMessageCount == 1)
1836  {
1837  ManifestBuilder manifestBuilder = new ManifestBuilder(Name, Guid, Name, null, EventManifestOptions.None);
1838  manifestBuilder.StartEvent(text, new EventAttribute(0)
1839  {
1840  Level = EventLevel.LogAlways,
1841  Task = (EventTask)65534
1842  });
1843  manifestBuilder.AddEventParameter(typeof(string), "message");
1844  manifestBuilder.EndEvent();
1845  SendManifest(manifestBuilder.CreateManifest());
1846  }
1847  fixed (char* ptr = msgString)
1848  {
1849  EventDescriptor eventDescriptor = new EventDescriptor(0, 0, 0, (byte)level, 0, 0, keywords);
1850  EventProvider.EventData eventData = default(EventProvider.EventData);
1851  eventData.Ptr = (ulong)ptr;
1852  eventData.Size = (uint)(2 * (msgString.Length + 1));
1853  eventData.Reserved = 0u;
1854  m_provider.WriteEvent(ref eventDescriptor, null, null, 1, (IntPtr)(void*)(&eventData));
1855  }
1856  }
1857 
1858  private void WriteStringToAllListeners(string eventName, string msg)
1859  {
1860  EventWrittenEventArgs eventWrittenEventArgs = new EventWrittenEventArgs(this);
1861  eventWrittenEventArgs.EventId = 0;
1862  eventWrittenEventArgs.Message = msg;
1863  eventWrittenEventArgs.Payload = new ReadOnlyCollection<object>(new List<object>
1864  {
1865  msg
1866  });
1867  eventWrittenEventArgs.PayloadNames = new ReadOnlyCollection<string>(new List<string>
1868  {
1869  "message"
1870  });
1871  eventWrittenEventArgs.EventName = eventName;
1872  for (EventDispatcher eventDispatcher = m_Dispatchers; eventDispatcher != null; eventDispatcher = eventDispatcher.m_Next)
1873  {
1874  bool flag = false;
1875  if (eventDispatcher.m_EventEnabled == null)
1876  {
1877  flag = true;
1878  }
1879  else
1880  {
1881  for (int i = 0; i < eventDispatcher.m_EventEnabled.Length; i++)
1882  {
1883  if (eventDispatcher.m_EventEnabled[i])
1884  {
1885  flag = true;
1886  break;
1887  }
1888  }
1889  }
1890  try
1891  {
1892  if (flag)
1893  {
1894  eventDispatcher.m_Listener.OnEventWritten(eventWrittenEventArgs);
1895  }
1896  }
1897  catch
1898  {
1899  }
1900  }
1901  }
1902 
1903  [SecurityCritical]
1904  private unsafe SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID)
1905  {
1906  SessionMask result = default(SessionMask);
1907  for (int i = 0; (long)i < 4L; i++)
1908  {
1909  EtwSession etwSession = m_etwSessionIdMap[i];
1910  if (etwSession != null)
1911  {
1912  ActivityFilter activityFilter = etwSession.m_activityFilter;
1913  if ((activityFilter == null && !m_activityFilteringForETWEnabled[i]) || (activityFilter != null && ActivityFilter.PassesActivityFilter(activityFilter, childActivityID, m_eventData[eventId].TriggersActivityTracking > 0, this, eventId)) || !m_activityFilteringForETWEnabled[i])
1914  {
1915  result[i] = true;
1916  }
1917  }
1918  }
1919  if (m_legacySessions != null && m_legacySessions.Count > 0 && m_eventData[eventId].Descriptor.Opcode == 9)
1920  {
1921  Guid* ptr = null;
1922  {
1923  foreach (EtwSession legacySession in m_legacySessions)
1924  {
1925  if (legacySession != null)
1926  {
1927  ActivityFilter activityFilter2 = legacySession.m_activityFilter;
1928  if (activityFilter2 != null)
1929  {
1930  if (ptr == null)
1931  {
1932  Guid internalCurrentThreadActivityId = InternalCurrentThreadActivityId;
1933  ptr = &internalCurrentThreadActivityId;
1934  }
1935  ActivityFilter.FlowActivityIfNeeded(activityFilter2, ptr, childActivityID);
1936  }
1937  }
1938  }
1939  return result;
1940  }
1941  }
1942  return result;
1943  }
1944 
1945  private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword)
1946  {
1947  if (!enable)
1948  {
1949  return false;
1950  }
1951  EventLevel level = (EventLevel)m_eventData[eventNum].Descriptor.Level;
1952  EventKeywords eventKeywords = (EventKeywords)(m_eventData[eventNum].Descriptor.Keywords & (long)(~SessionMask.All.ToEventKeywords()));
1953  EventChannel channel = (EventChannel)m_eventData[eventNum].Descriptor.Channel;
1954  return IsEnabledCommon(enable, currentLevel, currentMatchAnyKeyword, level, eventKeywords, channel);
1955  }
1956 
1957  private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword, EventLevel eventLevel, EventKeywords eventKeywords, EventChannel eventChannel)
1958  {
1959  if (!enabled)
1960  {
1961  return false;
1962  }
1963  if (currentLevel != 0 && currentLevel < eventLevel)
1964  {
1965  return false;
1966  }
1967  if (currentMatchAnyKeyword != EventKeywords.None && eventKeywords != EventKeywords.None)
1968  {
1969  if (eventChannel != 0 && m_channelData != null && m_channelData.Length > (int)eventChannel)
1970  {
1971  EventKeywords eventKeywords2 = (EventKeywords)((long)m_channelData[(uint)eventChannel] | (long)eventKeywords);
1972  if (eventKeywords2 != EventKeywords.None && (eventKeywords2 & currentMatchAnyKeyword) == EventKeywords.None)
1973  {
1974  return false;
1975  }
1976  }
1977  else if ((eventKeywords & currentMatchAnyKeyword) == EventKeywords.None)
1978  {
1979  return false;
1980  }
1981  }
1982  return true;
1983  }
1984 
1985  [MethodImpl(MethodImplOptions.NoInlining)]
1986  private void ThrowEventSourceException(string eventName, Exception innerEx = null)
1987  {
1988  if (m_EventSourceExceptionRecurenceCount <= 0)
1989  {
1990  try
1991  {
1992  m_EventSourceExceptionRecurenceCount++;
1993  string text = "EventSourceException";
1994  if (eventName != null)
1995  {
1996  text = text + " while processing event \"" + eventName + "\"";
1997  }
1998  switch (EventProvider.GetLastWriteEventError())
1999  {
2000  case EventProvider.WriteEventErrorCode.EventTooBig:
2001  ReportOutOfBandMessage(text + ": " + Environment.GetResourceString("EventSource_EventTooBig"), flush: true);
2002  if (ThrowOnEventWriteErrors)
2003  {
2004  throw new EventSourceException(Environment.GetResourceString("EventSource_EventTooBig"), innerEx);
2005  }
2006  break;
2007  case EventProvider.WriteEventErrorCode.NoFreeBuffers:
2008  ReportOutOfBandMessage(text + ": " + Environment.GetResourceString("EventSource_NoFreeBuffers"), flush: true);
2009  if (ThrowOnEventWriteErrors)
2010  {
2011  throw new EventSourceException(Environment.GetResourceString("EventSource_NoFreeBuffers"), innerEx);
2012  }
2013  break;
2014  case EventProvider.WriteEventErrorCode.NullInput:
2015  ReportOutOfBandMessage(text + ": " + Environment.GetResourceString("EventSource_NullInput"), flush: true);
2016  if (ThrowOnEventWriteErrors)
2017  {
2018  throw new EventSourceException(Environment.GetResourceString("EventSource_NullInput"), innerEx);
2019  }
2020  break;
2021  case EventProvider.WriteEventErrorCode.TooManyArgs:
2022  ReportOutOfBandMessage(text + ": " + Environment.GetResourceString("EventSource_TooManyArgs"), flush: true);
2023  if (ThrowOnEventWriteErrors)
2024  {
2025  throw new EventSourceException(Environment.GetResourceString("EventSource_TooManyArgs"), innerEx);
2026  }
2027  break;
2028  default:
2029  if (innerEx != null)
2030  {
2031  ReportOutOfBandMessage(text + ": " + innerEx.GetType() + ":" + innerEx.Message, flush: true);
2032  }
2033  else
2034  {
2035  ReportOutOfBandMessage(text, flush: true);
2036  }
2037  if (ThrowOnEventWriteErrors)
2038  {
2039  throw new EventSourceException(innerEx);
2040  }
2041  break;
2042  }
2043  }
2044  finally
2045  {
2046  m_EventSourceExceptionRecurenceCount--;
2047  }
2048  }
2049  }
2050 
2051  private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string eventName)
2052  {
2053  if (eventData.Descriptor.Opcode != 9 && eventData.Descriptor.Opcode != 240 && eventData.Descriptor.Opcode != 1)
2054  {
2055  ThrowEventSourceException(eventName);
2056  }
2057  }
2058 
2059  internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string eventName)
2060  {
2061  if (opcode == EventOpcode.Info && eventName != null)
2062  {
2063  if (eventName.EndsWith("Start"))
2064  {
2065  return EventOpcode.Start;
2066  }
2067  if (eventName.EndsWith("Stop"))
2068  {
2069  return EventOpcode.Stop;
2070  }
2071  }
2072  return opcode;
2073  }
2074 
2075  internal void SendCommand(EventListener listener, int perEventSourceSessionId, int etwSessionId, EventCommand command, bool enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string> commandArguments)
2076  {
2077  EventCommandEventArgs eventCommandEventArgs = new EventCommandEventArgs(command, commandArguments, this, listener, perEventSourceSessionId, etwSessionId, enable, level, matchAnyKeyword);
2078  lock (EventListener.EventListenersLock)
2079  {
2080  if (m_completelyInited)
2081  {
2082  m_deferredCommands = null;
2083  DoCommand(eventCommandEventArgs);
2084  }
2085  else
2086  {
2087  eventCommandEventArgs.nextCommand = m_deferredCommands;
2088  m_deferredCommands = eventCommandEventArgs;
2089  }
2090  }
2091  }
2092 
2093  internal void DoCommand(EventCommandEventArgs commandArgs)
2094  {
2095  if (m_provider != null)
2096  {
2097  m_outOfBandMessageCount = 0;
2098  bool flag = commandArgs.perEventSourceSessionId > 0 && (long)commandArgs.perEventSourceSessionId <= 4L;
2099  try
2100  {
2101  EnsureDescriptorsInitialized();
2102  commandArgs.dispatcher = GetDispatcher(commandArgs.listener);
2103  if (commandArgs.dispatcher == null && commandArgs.listener != null)
2104  {
2105  throw new ArgumentException(Environment.GetResourceString("EventSource_ListenerNotFound"));
2106  }
2107  if (commandArgs.Arguments == null)
2108  {
2109  commandArgs.Arguments = new Dictionary<string, string>();
2110  }
2111  if (commandArgs.Command == EventCommand.Update)
2112  {
2113  for (int i = 0; i < m_eventData.Length; i++)
2114  {
2115  EnableEventForDispatcher(commandArgs.dispatcher, i, IsEnabledByDefault(i, commandArgs.enable, commandArgs.level, commandArgs.matchAnyKeyword));
2116  }
2117  if (commandArgs.enable)
2118  {
2119  if (!m_eventSourceEnabled)
2120  {
2121  m_level = commandArgs.level;
2122  m_matchAnyKeyword = commandArgs.matchAnyKeyword;
2123  }
2124  else
2125  {
2126  if (commandArgs.level > m_level)
2127  {
2128  m_level = commandArgs.level;
2129  }
2130  if (commandArgs.matchAnyKeyword == EventKeywords.None)
2131  {
2132  m_matchAnyKeyword = EventKeywords.None;
2133  }
2134  else if (m_matchAnyKeyword != EventKeywords.None)
2135  {
2136  m_matchAnyKeyword |= commandArgs.matchAnyKeyword;
2137  }
2138  }
2139  }
2140  bool flag2 = commandArgs.perEventSourceSessionId >= 0;
2141  if (commandArgs.perEventSourceSessionId == 0 && !commandArgs.enable)
2142  {
2143  flag2 = false;
2144  }
2145  if (commandArgs.listener == null)
2146  {
2147  if (!flag2)
2148  {
2149  commandArgs.perEventSourceSessionId = -commandArgs.perEventSourceSessionId;
2150  }
2151  commandArgs.perEventSourceSessionId--;
2152  }
2153  commandArgs.Command = (flag2 ? EventCommand.Enable : EventCommand.Disable);
2154  if (flag2 && commandArgs.dispatcher == null && !SelfDescribingEvents)
2155  {
2156  SendManifest(m_rawManifest);
2157  }
2158  if (flag2 && commandArgs.perEventSourceSessionId != -1)
2159  {
2160  bool participateInSampling = false;
2161  ParseCommandArgs(commandArgs.Arguments, out participateInSampling, out string activityFilters, out int sessionIdBit);
2162  if (commandArgs.listener == null && commandArgs.Arguments.Count > 0 && commandArgs.perEventSourceSessionId != sessionIdBit)
2163  {
2164  throw new ArgumentException(Environment.GetResourceString("EventSource_SessionIdError", commandArgs.perEventSourceSessionId + 44, sessionIdBit + 44));
2165  }
2166  if (commandArgs.listener == null)
2167  {
2168  UpdateEtwSession(commandArgs.perEventSourceSessionId, commandArgs.etwSessionId, bEnable: true, activityFilters, participateInSampling);
2169  }
2170  else
2171  {
2172  ActivityFilter.UpdateFilter(ref commandArgs.listener.m_activityFilter, this, 0, activityFilters);
2173  commandArgs.dispatcher.m_activityFilteringEnabled = participateInSampling;
2174  }
2175  }
2176  else if (!flag2 && commandArgs.listener == null && commandArgs.perEventSourceSessionId >= 0 && (long)commandArgs.perEventSourceSessionId < 4L)
2177  {
2178  commandArgs.Arguments["EtwSessionKeyword"] = (commandArgs.perEventSourceSessionId + 44).ToString(CultureInfo.InvariantCulture);
2179  }
2180  if (commandArgs.enable)
2181  {
2182  m_eventSourceEnabled = true;
2183  }
2184  OnEventCommand(commandArgs);
2185  m_eventCommandExecuted?.Invoke(this, commandArgs);
2186  if (commandArgs.listener == null && !flag2 && commandArgs.perEventSourceSessionId != -1)
2187  {
2188  UpdateEtwSession(commandArgs.perEventSourceSessionId, commandArgs.etwSessionId, bEnable: false, null, participateInSampling: false);
2189  }
2190  if (!commandArgs.enable)
2191  {
2192  if (commandArgs.listener == null)
2193  {
2194  for (int j = 0; (long)j < 4L; j++)
2195  {
2196  EtwSession etwSession = m_etwSessionIdMap[j];
2197  if (etwSession != null)
2198  {
2199  ActivityFilter.DisableFilter(ref etwSession.m_activityFilter, this);
2200  }
2201  }
2202  m_activityFilteringForETWEnabled = new SessionMask(0u);
2203  m_curLiveSessions = new SessionMask(0u);
2204  if (m_etwSessionIdMap != null)
2205  {
2206  for (int k = 0; (long)k < 4L; k++)
2207  {
2208  m_etwSessionIdMap[k] = null;
2209  }
2210  }
2211  if (m_legacySessions != null)
2212  {
2213  m_legacySessions.Clear();
2214  }
2215  }
2216  else
2217  {
2218  ActivityFilter.DisableFilter(ref commandArgs.listener.m_activityFilter, this);
2219  commandArgs.dispatcher.m_activityFilteringEnabled = false;
2220  }
2221  for (int l = 0; l < m_eventData.Length; l++)
2222  {
2223  bool enabledForAnyListener = false;
2224  for (EventDispatcher eventDispatcher = m_Dispatchers; eventDispatcher != null; eventDispatcher = eventDispatcher.m_Next)
2225  {
2226  if (eventDispatcher.m_EventEnabled[l])
2227  {
2228  enabledForAnyListener = true;
2229  break;
2230  }
2231  }
2232  m_eventData[l].EnabledForAnyListener = enabledForAnyListener;
2233  }
2234  if (!AnyEventEnabled())
2235  {
2236  m_level = EventLevel.LogAlways;
2237  m_matchAnyKeyword = EventKeywords.None;
2238  m_eventSourceEnabled = false;
2239  }
2240  }
2241  UpdateKwdTriggers(commandArgs.enable);
2242  }
2243  else
2244  {
2245  if (commandArgs.Command == EventCommand.SendManifest && m_rawManifest != null)
2246  {
2247  SendManifest(m_rawManifest);
2248  }
2249  OnEventCommand(commandArgs);
2250  m_eventCommandExecuted?.Invoke(this, commandArgs);
2251  }
2252  if (m_completelyInited && ((commandArgs.listener != null) | flag))
2253  {
2254  SessionMask sessions = SessionMask.FromId(commandArgs.perEventSourceSessionId);
2255  ReportActivitySamplingInfo(commandArgs.listener, sessions);
2256  }
2257  }
2258  catch (Exception ex)
2259  {
2260  ReportOutOfBandMessage("ERROR: Exception in Command Processing for EventSource " + Name + ": " + ex.Message, flush: true);
2261  }
2262  }
2263  }
2264 
2265  internal void UpdateEtwSession(int sessionIdBit, int etwSessionId, bool bEnable, string activityFilters, bool participateInSampling)
2266  {
2267  if ((long)sessionIdBit < 4L)
2268  {
2269  if (bEnable)
2270  {
2271  EtwSession etwSession = EtwSession.GetEtwSession(etwSessionId, bCreateIfNeeded: true);
2272  ActivityFilter.UpdateFilter(ref etwSession.m_activityFilter, this, sessionIdBit, activityFilters);
2273  m_etwSessionIdMap[sessionIdBit] = etwSession;
2274  m_activityFilteringForETWEnabled[sessionIdBit] = participateInSampling;
2275  }
2276  else
2277  {
2278  EtwSession etwSession2 = EtwSession.GetEtwSession(etwSessionId);
2279  m_etwSessionIdMap[sessionIdBit] = null;
2280  m_activityFilteringForETWEnabled[sessionIdBit] = false;
2281  if (etwSession2 != null)
2282  {
2283  ActivityFilter.DisableFilter(ref etwSession2.m_activityFilter, this);
2284  EtwSession.RemoveEtwSession(etwSession2);
2285  }
2286  }
2287  m_curLiveSessions[sessionIdBit] = bEnable;
2288  return;
2289  }
2290  if (bEnable)
2291  {
2292  if (m_legacySessions == null)
2293  {
2294  m_legacySessions = new List<EtwSession>(8);
2295  }
2296  EtwSession etwSession3 = EtwSession.GetEtwSession(etwSessionId, bCreateIfNeeded: true);
2297  if (!m_legacySessions.Contains(etwSession3))
2298  {
2299  m_legacySessions.Add(etwSession3);
2300  }
2301  return;
2302  }
2303  EtwSession etwSession4 = EtwSession.GetEtwSession(etwSessionId);
2304  if (etwSession4 != null)
2305  {
2306  if (m_legacySessions != null)
2307  {
2308  m_legacySessions.Remove(etwSession4);
2309  }
2310  EtwSession.RemoveEtwSession(etwSession4);
2311  }
2312  }
2313 
2314  internal static bool ParseCommandArgs(IDictionary<string, string> commandArguments, out bool participateInSampling, out string activityFilters, out int sessionIdBit)
2315  {
2316  bool result = true;
2317  participateInSampling = false;
2318  if (commandArguments.TryGetValue("ActivitySamplingStartEvent", out activityFilters))
2319  {
2320  participateInSampling = true;
2321  }
2322  if (commandArguments.TryGetValue("ActivitySampling", out string value))
2323  {
2324  if (string.Compare(value, "false", StringComparison.OrdinalIgnoreCase) == 0 || value == "0")
2325  {
2326  participateInSampling = false;
2327  }
2328  else
2329  {
2330  participateInSampling = true;
2331  }
2332  }
2333  int result2 = -1;
2334  if (!commandArguments.TryGetValue("EtwSessionKeyword", out string value2) || !int.TryParse(value2, out result2) || result2 < 44 || (long)result2 >= 48L)
2335  {
2336  sessionIdBit = -1;
2337  result = false;
2338  }
2339  else
2340  {
2341  sessionIdBit = result2 - 44;
2342  }
2343  return result;
2344  }
2345 
2346  internal void UpdateKwdTriggers(bool enable)
2347  {
2348  if (enable)
2349  {
2350  ulong num = (ulong)m_matchAnyKeyword;
2351  if (num == 0L)
2352  {
2353  num = ulong.MaxValue;
2354  }
2355  m_keywordTriggers = 0L;
2356  for (int i = 0; (long)i < 4L; i++)
2357  {
2358  EtwSession etwSession = m_etwSessionIdMap[i];
2359  if (etwSession != null)
2360  {
2361  ActivityFilter activityFilter = etwSession.m_activityFilter;
2362  ActivityFilter.UpdateKwdTriggers(activityFilter, m_guid, this, (EventKeywords)num);
2363  }
2364  }
2365  }
2366  else
2367  {
2368  m_keywordTriggers = 0L;
2369  }
2370  }
2371 
2372  internal bool EnableEventForDispatcher(EventDispatcher dispatcher, int eventId, bool value)
2373  {
2374  if (dispatcher == null)
2375  {
2376  if (eventId >= m_eventData.Length)
2377  {
2378  return false;
2379  }
2380  if (m_provider != null)
2381  {
2382  m_eventData[eventId].EnabledForETW = value;
2383  }
2384  }
2385  else
2386  {
2387  if (eventId >= dispatcher.m_EventEnabled.Length)
2388  {
2389  return false;
2390  }
2391  dispatcher.m_EventEnabled[eventId] = value;
2392  if (value)
2393  {
2394  m_eventData[eventId].EnabledForAnyListener = true;
2395  }
2396  }
2397  return true;
2398  }
2399 
2400  private bool AnyEventEnabled()
2401  {
2402  for (int i = 0; i < m_eventData.Length; i++)
2403  {
2404  if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener)
2405  {
2406  return true;
2407  }
2408  }
2409  return false;
2410  }
2411 
2412  [SecuritySafeCritical]
2413  private void EnsureDescriptorsInitialized()
2414  {
2415  if (m_eventData == null)
2416  {
2417  m_rawManifest = CreateManifestAndDescriptors(GetType(), Name, this);
2418  foreach (WeakReference s_EventSource in EventListener.s_EventSources)
2419  {
2420  EventSource eventSource = s_EventSource.Target as EventSource;
2421  if (eventSource != null && eventSource.Guid == m_guid && !eventSource.IsDisposed && eventSource != this)
2422  {
2423  throw new ArgumentException(Environment.GetResourceString("EventSource_EventSourceGuidInUse", m_guid));
2424  }
2425  }
2426  for (EventDispatcher eventDispatcher = m_Dispatchers; eventDispatcher != null; eventDispatcher = eventDispatcher.m_Next)
2427  {
2428  if (eventDispatcher.m_EventEnabled == null)
2429  {
2430  eventDispatcher.m_EventEnabled = new bool[m_eventData.Length];
2431  }
2432  }
2433  }
2434  if (s_currentPid == 0)
2435  {
2436  s_currentPid = Win32Native.GetCurrentProcessId();
2437  }
2438  }
2439 
2440  [SecuritySafeCritical]
2441  private unsafe bool SendManifest(byte[] rawManifest)
2442  {
2443  bool result = true;
2444  if (rawManifest == null)
2445  {
2446  return false;
2447  }
2448  fixed (byte* ptr2 = rawManifest)
2449  {
2450  EventDescriptor eventDescriptor = new EventDescriptor(65534, 1, 0, 0, 254, 65534, 72057594037927935L);
2451  ManifestEnvelope manifestEnvelope = default(ManifestEnvelope);
2452  manifestEnvelope.Format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
2453  manifestEnvelope.MajorVersion = 1;
2454  manifestEnvelope.MinorVersion = 0;
2455  manifestEnvelope.Magic = 91;
2456  int num = rawManifest.Length;
2457  manifestEnvelope.ChunkNumber = 0;
2458  EventProvider.EventData* ptr = stackalloc EventProvider.EventData[2];
2459  ptr->Ptr = (ulong)(&manifestEnvelope);
2460  ptr->Size = (uint)sizeof(ManifestEnvelope);
2461  ptr->Reserved = 0u;
2462  ptr[1].Ptr = (ulong)ptr2;
2463  ptr[1].Reserved = 0u;
2464  int num2 = 65280;
2465  while (true)
2466  {
2467  IL_00ca:
2468  manifestEnvelope.TotalChunks = (ushort)((num + (num2 - 1)) / num2);
2469  while (num > 0)
2470  {
2471  ptr[1].Size = (uint)Math.Min(num, num2);
2472  if (m_provider != null && !m_provider.WriteEvent(ref eventDescriptor, null, null, 2, (IntPtr)(void*)ptr))
2473  {
2474  if (EventProvider.GetLastWriteEventError() != EventProvider.WriteEventErrorCode.EventTooBig || manifestEnvelope.ChunkNumber != 0 || num2 <= 256)
2475  {
2476  result = false;
2477  if (ThrowOnEventWriteErrors)
2478  {
2479  ThrowEventSourceException("SendManifest");
2480  }
2481  break;
2482  }
2483  num2 /= 2;
2484  goto IL_00ca;
2485  }
2486  num -= num2;
2487  ptr[1].Ptr += (uint)num2;
2488  manifestEnvelope.ChunkNumber++;
2489  if ((int)manifestEnvelope.ChunkNumber % 5 == 0)
2490  {
2491  Thread.Sleep(15);
2492  }
2493  }
2494  break;
2495  }
2496  }
2497  return result;
2498  }
2499 
2500  internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None)
2501  {
2502  if (!member.Module.Assembly.ReflectionOnly() && (flags & EventManifestOptions.AllowEventSourceOverride) == EventManifestOptions.None)
2503  {
2504  Attribute result = null;
2505  object[] customAttributes = member.GetCustomAttributes(attributeType, inherit: false);
2506  int num = 0;
2507  if (num < customAttributes.Length)
2508  {
2509  object obj = customAttributes[num];
2510  result = (Attribute)obj;
2511  }
2512  return result;
2513  }
2514  string fullName = attributeType.FullName;
2515  foreach (CustomAttributeData customAttribute in CustomAttributeData.GetCustomAttributes(member))
2516  {
2517  if (AttributeTypeNamesMatch(attributeType, customAttribute.Constructor.ReflectedType))
2518  {
2519  Attribute attribute = null;
2520  if (customAttribute.ConstructorArguments.Count == 1)
2521  {
2522  attribute = (Attribute)Activator.CreateInstance(attributeType, customAttribute.ConstructorArguments[0].Value);
2523  }
2524  else if (customAttribute.ConstructorArguments.Count == 0)
2525  {
2526  attribute = (Attribute)Activator.CreateInstance(attributeType);
2527  }
2528  if (attribute != null)
2529  {
2530  Type type = attribute.GetType();
2531  foreach (CustomAttributeNamedArgument namedArgument in customAttribute.NamedArguments)
2532  {
2533  PropertyInfo property = type.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Instance | BindingFlags.Public);
2534  object obj2 = namedArgument.TypedValue.Value;
2535  if (property.PropertyType.IsEnum)
2536  {
2537  obj2 = Enum.Parse(property.PropertyType, obj2.ToString());
2538  }
2539  property.SetValue(attribute, obj2, null);
2540  }
2541  return attribute;
2542  }
2543  }
2544  }
2545  return null;
2546  }
2547 
2548  private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAttributeType)
2549  {
2550  if (!(attributeType == reflectedAttributeType) && !string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal))
2551  {
2552  if (string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && attributeType.Namespace.EndsWith("Diagnostics.Tracing"))
2553  {
2554  return reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing");
2555  }
2556  return false;
2557  }
2558  return true;
2559  }
2560 
2561  private static Type GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly)
2562  {
2563  if (eventSourceType.BaseType() == null)
2564  {
2565  return null;
2566  }
2567  do
2568  {
2569  eventSourceType = eventSourceType.BaseType();
2570  }
2571  while (eventSourceType != null && eventSourceType.IsAbstract());
2572  if (eventSourceType != null)
2573  {
2574  if (!allowEventSourceOverride)
2575  {
2576  if ((reflectionOnly && eventSourceType.FullName != typeof(EventSource).FullName) || (!reflectionOnly && eventSourceType != typeof(EventSource)))
2577  {
2578  return null;
2579  }
2580  }
2581  else if (eventSourceType.Name != "EventSource")
2582  {
2583  return null;
2584  }
2585  }
2586  return eventSourceType;
2587  }
2588 
2589  private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string eventSourceDllName, EventSource source, EventManifestOptions flags = EventManifestOptions.None)
2590  {
2591  ManifestBuilder manifestBuilder = null;
2592  bool flag = source == null || !source.SelfDescribingEvents;
2593  Exception ex = null;
2594  byte[] result = null;
2595  if (eventSourceType.IsAbstract() && (flags & EventManifestOptions.Strict) == EventManifestOptions.None)
2596  {
2597  return null;
2598  }
2599  try
2600  {
2601  MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
2602  int num = 1;
2603  EventMetadata[] eventData = null;
2604  Dictionary<string, string> eventsByName = null;
2605  if (source != null || (flags & EventManifestOptions.Strict) != 0)
2606  {
2607  eventData = new EventMetadata[methods.Length + 1];
2608  eventData[0].Name = "";
2609  }
2610  ResourceManager resources = null;
2611  EventSourceAttribute eventSourceAttribute = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags);
2612  if (eventSourceAttribute != null && eventSourceAttribute.LocalizationResources != null)
2613  {
2614  resources = new ResourceManager(eventSourceAttribute.LocalizationResources, eventSourceType.Assembly());
2615  }
2616  manifestBuilder = new ManifestBuilder(GetName(eventSourceType, flags), GetGuid(eventSourceType), eventSourceDllName, resources, flags);
2617  manifestBuilder.StartEvent("EventSourceMessage", new EventAttribute(0)
2618  {
2619  Level = EventLevel.LogAlways,
2620  Task = (EventTask)65534
2621  });
2622  manifestBuilder.AddEventParameter(typeof(string), "message");
2623  manifestBuilder.EndEvent();
2624  if ((flags & EventManifestOptions.Strict) != 0)
2625  {
2626  if (!(GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != EventManifestOptions.None, eventSourceType.Assembly().ReflectionOnly()) != null))
2627  {
2628  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_TypeMustDeriveFromEventSource"));
2629  }
2630  if (!eventSourceType.IsAbstract() && !eventSourceType.IsSealed())
2631  {
2632  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_TypeMustBeSealedOrAbstract"));
2633  }
2634  }
2635  string[] array = new string[3]
2636  {
2637  "Keywords",
2638  "Tasks",
2639  "Opcodes"
2640  };
2641  foreach (string text in array)
2642  {
2643  Type nestedType = eventSourceType.GetNestedType(text);
2644  if (nestedType != null)
2645  {
2646  if (eventSourceType.IsAbstract())
2647  {
2648  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_AbstractMustNotDeclareKTOC", nestedType.Name));
2649  }
2650  else
2651  {
2652  FieldInfo[] fields = nestedType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
2653  foreach (FieldInfo staticField in fields)
2654  {
2655  AddProviderEnumKind(manifestBuilder, staticField, text);
2656  }
2657  }
2658  }
2659  }
2660  manifestBuilder.AddKeyword("Session3", 17592186044416uL);
2661  manifestBuilder.AddKeyword("Session2", 35184372088832uL);
2662  manifestBuilder.AddKeyword("Session1", 70368744177664uL);
2663  manifestBuilder.AddKeyword("Session0", 140737488355328uL);
2664  if (eventSourceType != typeof(EventSource))
2665  {
2666  foreach (MethodInfo methodInfo in methods)
2667  {
2668  ParameterInfo[] args = methodInfo.GetParameters();
2669  EventAttribute eventAttribute = (EventAttribute)GetCustomAttributeHelper(methodInfo, typeof(EventAttribute), flags);
2670  if (eventAttribute != null && source != null && eventAttribute.EventId <= 3 && source.Guid.Equals(AspNetEventSourceGuid))
2671  {
2672  eventAttribute.ActivityOptions |= EventActivityOptions.Disable;
2673  }
2674  if (!methodInfo.IsStatic)
2675  {
2676  if (eventSourceType.IsAbstract())
2677  {
2678  if (eventAttribute != null)
2679  {
2680  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", methodInfo.Name, eventAttribute.EventId));
2681  }
2682  }
2683  else
2684  {
2685  if (eventAttribute == null)
2686  {
2687  if (methodInfo.ReturnType != typeof(void) || methodInfo.IsVirtual || GetCustomAttributeHelper(methodInfo, typeof(NonEventAttribute), flags) != null)
2688  {
2689  continue;
2690  }
2691  EventAttribute eventAttribute2 = new EventAttribute(num);
2692  eventAttribute = eventAttribute2;
2693  }
2694  else if (eventAttribute.EventId <= 0)
2695  {
2696  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_NeedPositiveId", methodInfo.Name), runtimeCritical: true);
2697  continue;
2698  }
2699  if (methodInfo.Name.LastIndexOf('.') >= 0)
2700  {
2701  manifestBuilder.ManifestError(Environment.GetResourceString("EventSource_EventMustNotBeExplicitImplementation", methodInfo.Name, eventAttribute.EventId));
2702  }
2703  num++;
2704  string name = methodInfo.Name;
2705  if (eventAttribute.Opcode == EventOpcode.Info)
2706  {
2707  bool flag2 = eventAttribute.Task == EventTask.None;
2708  if (flag2)
2709  {
2710  eventAttribute.Task = (EventTask)(65534 - eventAttribute.EventId);
2711  }
2712  if (!eventAttribute.IsOpcodeSet)
2713  {
2714  eventAttribute.Opcode = GetOpcodeWithDefault(EventOpcode.Info, name);
2715  }
2716  if (flag2)
2717  {
2718  if (eventAttribute.Opcode == EventOpcode.Start)
2719  {
2720  string text2 = name.Substring(0, name.Length - "Start".Length);
2721  if (string.Compare(name, 0, text2, 0, text2.Length) == 0 && string.Compare(name, text2.Length, "Start", 0, Math.Max(name.Length - text2.Length, "Start".Length)) == 0)
2722  {
2723  manifestBuilder.AddTask(text2, (int)eventAttribute.Task);
2724  }
2725  }
2726  else if (eventAttribute.Opcode == EventOpcode.Stop)
2727  {
2728  int num2 = eventAttribute.EventId - 1;
2729  if (eventData != null && num2 < eventData.Length)
2730  {
2731  EventMetadata eventMetadata = eventData[num2];
2732  string text3 = name.Substring(0, name.Length - "Stop".Length);
2733  if (eventMetadata.Descriptor.Opcode == 1 && string.Compare(eventMetadata.Name, 0, text3, 0, text3.Length) == 0 && string.Compare(eventMetadata.Name, text3.Length, "Start", 0, Math.Max(eventMetadata.Name.Length - text3.Length, "Start".Length)) == 0)
2734  {
2735  eventAttribute.Task = (EventTask)eventMetadata.Descriptor.Task;
2736  flag2 = false;
2737  }
2738  }
2739  if (flag2 && (flags & EventManifestOptions.Strict) != 0)
2740  {
2741  throw new ArgumentException(Environment.GetResourceString("EventSource_StopsFollowStarts"));
2742  }
2743  }
2744  }
2745  }
2746  bool hasRelatedActivityID = RemoveFirstArgIfRelatedActivityId(ref args);
2747  if (source == null || !source.SelfDescribingEvents)
2748  {
2749  manifestBuilder.StartEvent(name, eventAttribute);
2750  for (int l = 0; l < args.Length; l++)
2751  {
2752  manifestBuilder.AddEventParameter(args[l].ParameterType, args[l].Name);
2753  }
2754  manifestBuilder.EndEvent();
2755  }
2756  if (source != null || (flags & EventManifestOptions.Strict) != 0)
2757  {
2758  DebugCheckEvent(ref eventsByName, eventData, methodInfo, eventAttribute, manifestBuilder, flags);
2759  if (eventAttribute.Channel != 0)
2760  {
2761  eventAttribute.Keywords |= (EventKeywords)manifestBuilder.GetChannelKeyword(eventAttribute.Channel);
2762  }
2763  string key = "event_" + name;
2764  string localizedMessage = manifestBuilder.GetLocalizedMessage(key, CultureInfo.CurrentUICulture, etwFormat: false);
2765  if (localizedMessage != null)
2766  {
2767  eventAttribute.Message = localizedMessage;
2768  }
2769  AddEventDescriptor(ref eventData, name, eventAttribute, args, hasRelatedActivityID);
2770  }
2771  }
2772  }
2773  }
2774  }
2775  NameInfo.ReserveEventIDsBelow(num);
2776  if (source != null)
2777  {
2778  TrimEventDescriptors(ref eventData);
2779  source.m_eventData = eventData;
2780  source.m_channelData = manifestBuilder.GetChannelData();
2781  }
2782  if (!eventSourceType.IsAbstract() && (source == null || !source.SelfDescribingEvents))
2783  {
2784  flag = ((flags & EventManifestOptions.OnlyIfNeededForRegistration) == EventManifestOptions.None || manifestBuilder.GetChannelData().Length != 0);
2785  if (!flag && (flags & EventManifestOptions.Strict) == EventManifestOptions.None)
2786  {
2787  return null;
2788  }
2789  result = manifestBuilder.CreateManifest();
2790  }
2791  }
2792  catch (Exception ex2)
2793  {
2794  if ((flags & EventManifestOptions.Strict) == EventManifestOptions.None)
2795  {
2796  throw;
2797  }
2798  ex = ex2;
2799  }
2800  if ((flags & EventManifestOptions.Strict) != 0 && (manifestBuilder.Errors.Count > 0 || ex != null))
2801  {
2802  string text4 = string.Empty;
2803  if (manifestBuilder.Errors.Count > 0)
2804  {
2805  bool flag3 = true;
2806  foreach (string error in manifestBuilder.Errors)
2807  {
2808  if (!flag3)
2809  {
2810  text4 += Environment.NewLine;
2811  }
2812  flag3 = false;
2813  text4 += error;
2814  }
2815  }
2816  else
2817  {
2818  text4 = "Unexpected error: " + ex.Message;
2819  }
2820  throw new ArgumentException(text4, ex);
2821  }
2822  if (!flag)
2823  {
2824  return null;
2825  }
2826  return result;
2827  }
2828 
2829  private static bool RemoveFirstArgIfRelatedActivityId(ref ParameterInfo[] args)
2830  {
2831  if (args.Length != 0 && args[0].ParameterType == typeof(Guid) && string.Compare(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase) == 0)
2832  {
2833  ParameterInfo[] array = new ParameterInfo[args.Length - 1];
2834  Array.Copy(args, 1, array, 0, args.Length - 1);
2835  args = array;
2836  return true;
2837  }
2838  return false;
2839  }
2840 
2841  private static void AddProviderEnumKind(ManifestBuilder manifest, FieldInfo staticField, string providerEnumKind)
2842  {
2843  bool flag = staticField.Module.Assembly.ReflectionOnly();
2844  Type fieldType = staticField.FieldType;
2845  if ((!flag && fieldType == typeof(EventOpcode)) || AttributeTypeNamesMatch(fieldType, typeof(EventOpcode)))
2846  {
2847  if (!(providerEnumKind != "Opcodes"))
2848  {
2849  int value = (int)staticField.GetRawConstantValue();
2850  manifest.AddOpcode(staticField.Name, value);
2851  return;
2852  }
2853  }
2854  else if ((!flag && fieldType == typeof(EventTask)) || AttributeTypeNamesMatch(fieldType, typeof(EventTask)))
2855  {
2856  if (!(providerEnumKind != "Tasks"))
2857  {
2858  int value2 = (int)staticField.GetRawConstantValue();
2859  manifest.AddTask(staticField.Name, value2);
2860  return;
2861  }
2862  }
2863  else
2864  {
2865  if ((flag || !(fieldType == typeof(EventKeywords))) && !AttributeTypeNamesMatch(fieldType, typeof(EventKeywords)))
2866  {
2867  return;
2868  }
2869  if (!(providerEnumKind != "Keywords"))
2870  {
2871  ulong value3 = (ulong)(long)staticField.GetRawConstantValue();
2872  manifest.AddKeyword(staticField.Name, value3);
2873  return;
2874  }
2875  }
2876  manifest.ManifestError(Environment.GetResourceString("EventSource_EnumKindMismatch", staticField.Name, staticField.FieldType.Name, providerEnumKind));
2877  }
2878 
2879  private static void AddEventDescriptor(ref EventMetadata[] eventData, string eventName, EventAttribute eventAttribute, ParameterInfo[] eventParameters, bool hasRelatedActivityID)
2880  {
2881  if (eventData == null || eventData.Length <= eventAttribute.EventId)
2882  {
2883  EventMetadata[] array = new EventMetadata[Math.Max(eventData.Length + 16, eventAttribute.EventId + 1)];
2884  Array.Copy(eventData, array, eventData.Length);
2885  eventData = array;
2886  }
2887  eventData[eventAttribute.EventId].Descriptor = new EventDescriptor(eventAttribute.EventId, eventAttribute.Version, (byte)eventAttribute.Channel, (byte)eventAttribute.Level, (byte)eventAttribute.Opcode, (int)eventAttribute.Task, (long)eventAttribute.Keywords | (long)SessionMask.All.ToEventKeywords());
2888  eventData[eventAttribute.EventId].Tags = eventAttribute.Tags;
2889  eventData[eventAttribute.EventId].Name = eventName;
2890  eventData[eventAttribute.EventId].Parameters = eventParameters;
2891  eventData[eventAttribute.EventId].Message = eventAttribute.Message;
2892  eventData[eventAttribute.EventId].ActivityOptions = eventAttribute.ActivityOptions;
2893  eventData[eventAttribute.EventId].HasRelatedActivityID = hasRelatedActivityID;
2894  }
2895 
2896  private static void TrimEventDescriptors(ref EventMetadata[] eventData)
2897  {
2898  int num = eventData.Length;
2899  while (0 < num)
2900  {
2901  num--;
2902  if (eventData[num].Descriptor.EventId != 0)
2903  {
2904  break;
2905  }
2906  }
2907  if (eventData.Length - num > 2)
2908  {
2909  EventMetadata[] array = new EventMetadata[num + 1];
2910  Array.Copy(eventData, array, array.Length);
2911  eventData = array;
2912  }
2913  }
2914 
2915  internal void AddListener(EventListener listener)
2916  {
2917  lock (EventListener.EventListenersLock)
2918  {
2919  bool[] eventEnabled = null;
2920  if (m_eventData != null)
2921  {
2922  eventEnabled = new bool[m_eventData.Length];
2923  }
2924  m_Dispatchers = new EventDispatcher(m_Dispatchers, eventEnabled, listener);
2925  listener.OnEventSourceCreated(this);
2926  }
2927  }
2928 
2929  private static void DebugCheckEvent(ref Dictionary<string, string> eventsByName, EventMetadata[] eventData, MethodInfo method, EventAttribute eventAttribute, ManifestBuilder manifest, EventManifestOptions options)
2930  {
2931  int eventId = eventAttribute.EventId;
2932  string name = method.Name;
2933  int helperCallFirstArg = GetHelperCallFirstArg(method);
2934  if (helperCallFirstArg >= 0 && eventId != helperCallFirstArg)
2935  {
2936  manifest.ManifestError(Environment.GetResourceString("EventSource_MismatchIdToWriteEvent", name, eventId, helperCallFirstArg), runtimeCritical: true);
2937  }
2938  if (eventId < eventData.Length && eventData[eventId].Descriptor.EventId != 0)
2939  {
2940  manifest.ManifestError(Environment.GetResourceString("EventSource_EventIdReused", name, eventId, eventData[eventId].Name), runtimeCritical: true);
2941  }
2942  for (int i = 0; i < eventData.Length; i++)
2943  {
2944  if (eventData[i].Name != null && eventData[i].Descriptor.Task == (int)eventAttribute.Task && (EventOpcode)eventData[i].Descriptor.Opcode == eventAttribute.Opcode)
2945  {
2946  manifest.ManifestError(Environment.GetResourceString("EventSource_TaskOpcodePairReused", name, eventId, eventData[i].Name, i));
2947  if ((options & EventManifestOptions.Strict) == EventManifestOptions.None)
2948  {
2949  break;
2950  }
2951  }
2952  }
2953  if (eventAttribute.Opcode != 0)
2954  {
2955  bool flag = false;
2956  if (eventAttribute.Task == EventTask.None)
2957  {
2958  flag = true;
2959  }
2960  else
2961  {
2962  EventTask eventTask = (EventTask)(65534 - eventId);
2963  if (eventAttribute.Opcode != EventOpcode.Start && eventAttribute.Opcode != EventOpcode.Stop && eventAttribute.Task == eventTask)
2964  {
2965  flag = true;
2966  }
2967  }
2968  if (flag)
2969  {
2970  manifest.ManifestError(Environment.GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", name, eventId));
2971  }
2972  }
2973  if (eventsByName == null)
2974  {
2975  eventsByName = new Dictionary<string, string>();
2976  }
2977  if (eventsByName.ContainsKey(name))
2978  {
2979  manifest.ManifestError(Environment.GetResourceString("EventSource_EventNameReused", name), runtimeCritical: true);
2980  }
2981  eventsByName[name] = name;
2982  }
2983 
2984  [SecuritySafeCritical]
2985  private static int GetHelperCallFirstArg(MethodInfo method)
2986  {
2988  byte[] iLAsByteArray = method.GetMethodBody().GetILAsByteArray();
2989  int num = -1;
2990  for (int i = 0; i < iLAsByteArray.Length; i++)
2991  {
2992  switch (iLAsByteArray[i])
2993  {
2994  case 14:
2995  case 16:
2996  i++;
2997  continue;
2998  case 21:
2999  case 22:
3000  case 23:
3001  case 24:
3002  case 25:
3003  case 26:
3004  case 27:
3005  case 28:
3006  case 29:
3007  case 30:
3008  if (i > 0 && iLAsByteArray[i - 1] == 2)
3009  {
3010  num = iLAsByteArray[i] - 22;
3011  }
3012  continue;
3013  case 31:
3014  if (i > 0 && iLAsByteArray[i - 1] == 2)
3015  {
3016  num = iLAsByteArray[i + 1];
3017  }
3018  i++;
3019  continue;
3020  case 32:
3021  i += 4;
3022  continue;
3023  case 40:
3024  i += 4;
3025  if (num >= 0)
3026  {
3027  for (int j = i + 1; j < iLAsByteArray.Length; j++)
3028  {
3029  if (iLAsByteArray[j] == 42)
3030  {
3031  return num;
3032  }
3033  if (iLAsByteArray[j] != 0)
3034  {
3035  break;
3036  }
3037  }
3038  }
3039  num = -1;
3040  continue;
3041  case 44:
3042  case 45:
3043  num = -1;
3044  i++;
3045  continue;
3046  case 57:
3047  case 58:
3048  num = -1;
3049  i += 4;
3050  continue;
3051  case 140:
3052  case 141:
3053  i += 4;
3054  continue;
3055  case 254:
3056  i++;
3057  if (i < iLAsByteArray.Length && iLAsByteArray[i] < 6)
3058  {
3059  continue;
3060  }
3061  break;
3062  case 0:
3063  case 1:
3064  case 2:
3065  case 3:
3066  case 4:
3067  case 5:
3068  case 6:
3069  case 7:
3070  case 8:
3071  case 9:
3072  case 10:
3073  case 11:
3074  case 12:
3075  case 13:
3076  case 20:
3077  case 37:
3078  case 103:
3079  case 104:
3080  case 105:
3081  case 106:
3082  case 109:
3083  case 110:
3084  case 162:
3085  continue;
3086  }
3087  return -1;
3088  }
3089  return -1;
3090  }
3091 
3092  internal void ReportOutOfBandMessage(string msg, bool flush)
3093  {
3094  try
3095  {
3096  Debugger.Log(0, null, msg + "\r\n");
3097  if (m_outOfBandMessageCount < 15)
3098  {
3099  m_outOfBandMessageCount++;
3100  goto IL_0048;
3101  }
3102  if (m_outOfBandMessageCount != 16)
3103  {
3104  m_outOfBandMessageCount = 16;
3105  msg = "Reached message limit. End of EventSource error messages.";
3106  goto IL_0048;
3107  }
3108  goto end_IL_0000;
3109  IL_0048:
3110  WriteEventString(EventLevel.LogAlways, -1L, msg);
3111  WriteStringToAllListeners("EventSourceMessage", msg);
3112  end_IL_0000:;
3113  }
3114  catch (Exception)
3115  {
3116  }
3117  }
3118 
3119  private EventSourceSettings ValidateSettings(EventSourceSettings settings)
3120  {
3121  EventSourceSettings eventSourceSettings = EventSourceSettings.EtwManifestEventFormat | EventSourceSettings.EtwSelfDescribingEventFormat;
3122  if ((settings & eventSourceSettings) == eventSourceSettings)
3123  {
3124  throw new ArgumentException(Environment.GetResourceString("EventSource_InvalidEventFormat"), "settings");
3125  }
3126  if ((settings & eventSourceSettings) == EventSourceSettings.Default)
3127  {
3128  settings |= EventSourceSettings.EtwSelfDescribingEventFormat;
3129  }
3130  return settings;
3131  }
3132 
3133  private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions)
3134  {
3135  for (int i = 0; (long)i < 4L; i++)
3136  {
3137  if (sessions[i])
3138  {
3139  ActivityFilter activityFilter;
3140  if (listener == null)
3141  {
3142  EtwSession etwSession = m_etwSessionIdMap[i];
3143  activityFilter = etwSession.m_activityFilter;
3144  }
3145  else
3146  {
3147  activityFilter = listener.m_activityFilter;
3148  }
3149  if (activityFilter != null)
3150  {
3151  SessionMask m = default(SessionMask);
3152  m[i] = true;
3153  foreach (Tuple<int, int> item in activityFilter.GetFilterAsTuple(m_guid))
3154  {
3155  WriteStringToListener(listener, string.Format(CultureInfo.InvariantCulture, "Session {0}: {1} = {2}", i, item.Item1, item.Item2), m);
3156  }
3157  bool flag = (listener == null) ? m_activityFilteringForETWEnabled[i] : GetDispatcher(listener).m_activityFilteringEnabled;
3158  WriteStringToListener(listener, string.Format(CultureInfo.InvariantCulture, "Session {0}: Activity Sampling support: {1}", i, flag ? "enabled" : "disabled"), m);
3159  }
3160  }
3161  }
3162  }
3163 
3168  [__DynamicallyInvokable]
3169  public EventSource(string eventSourceName)
3170  : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
3171  {
3172  }
3173 
3181  [__DynamicallyInvokable]
3182  public EventSource(string eventSourceName, EventSourceSettings config)
3183  : this(eventSourceName, config, (string[])null)
3184  {
3185  }
3186 
3195  [__DynamicallyInvokable]
3196  public EventSource(string eventSourceName, EventSourceSettings config, params string[] traits)
3197  : this((eventSourceName == null) ? default(Guid) : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName, config, traits)
3198  {
3199  if (eventSourceName == null)
3200  {
3201  throw new ArgumentNullException("eventSourceName");
3202  }
3203  }
3204 
3209  [SecuritySafeCritical]
3210  [__DynamicallyInvokable]
3211  public void Write(string eventName)
3212  {
3213  if (eventName == null)
3214  {
3215  throw new ArgumentNullException("eventName");
3216  }
3217  if (IsEnabled())
3218  {
3219  EventSourceOptions options = default(EventSourceOptions);
3220  EmptyStruct data = default(EmptyStruct);
3221  WriteImpl(eventName, ref options, ref data, null, null);
3222  }
3223  }
3224 
3230  [SecuritySafeCritical]
3231  [__DynamicallyInvokable]
3232  public void Write(string eventName, EventSourceOptions options)
3233  {
3234  if (eventName == null)
3235  {
3236  throw new ArgumentNullException("eventName");
3237  }
3238  if (IsEnabled())
3239  {
3240  EmptyStruct data = default(EmptyStruct);
3241  WriteImpl(eventName, ref options, ref data, null, null);
3242  }
3243  }
3244 
3249  [SecuritySafeCritical]
3250  [__DynamicallyInvokable]
3251  public void Write<T>(string eventName, T data)
3252  {
3253  if (IsEnabled())
3254  {
3255  EventSourceOptions options = default(EventSourceOptions);
3256  WriteImpl(eventName, ref options, ref data, null, null);
3257  }
3258  }
3259 
3265  [SecuritySafeCritical]
3266  [__DynamicallyInvokable]
3267  public void Write<T>(string eventName, EventSourceOptions options, T data)
3268  {
3269  if (IsEnabled())
3270  {
3271  WriteImpl(eventName, ref options, ref data, null, null);
3272  }
3273  }
3274 
3280  [SecuritySafeCritical]
3281  [__DynamicallyInvokable]
3282  public void Write<T>(string eventName, ref EventSourceOptions options, ref T data)
3283  {
3284  if (IsEnabled())
3285  {
3286  WriteImpl(eventName, ref options, ref data, null, null);
3287  }
3288  }
3289 
3297  [SecuritySafeCritical]
3298  [__DynamicallyInvokable]
3299  public unsafe void Write<T>(string eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, ref T data)
3300  {
3301  if (IsEnabled())
3302  {
3303  fixed (Guid* pActivityId = &activityId)
3304  {
3305  fixed (Guid* ptr = &relatedActivityId)
3306  {
3307  WriteImpl(eventName, ref options, ref data, pActivityId, (Guid*)(long)((relatedActivityId == Guid.Empty) ? ((IntPtr)(void*)null) : ((IntPtr)ptr)));
3308  }
3309  }
3310  }
3311  }
3312 
3313  [SecuritySafeCritical]
3314  private unsafe void WriteMultiMerge(string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values)
3315  {
3316  if (IsEnabled())
3317  {
3318  byte level = ((options.valuesSet & 4) != 0) ? options.level : eventTypes.level;
3319  EventKeywords keywords = ((options.valuesSet & 1) != 0) ? options.keywords : eventTypes.keywords;
3320  if (IsEnabled((EventLevel)level, keywords))
3321  {
3322  WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
3323  }
3324  }
3325  }
3326 
3327  [SecuritySafeCritical]
3328  private unsafe void WriteMultiMergeInner(string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values)
3329  {
3330  int num = 0;
3331  byte level = ((options.valuesSet & 4) != 0) ? options.level : eventTypes.level;
3332  byte opcode = ((options.valuesSet & 8) != 0) ? options.opcode : eventTypes.opcode;
3333  EventTags tags = ((options.valuesSet & 2) != 0) ? options.tags : eventTypes.Tags;
3334  EventKeywords keywords = ((options.valuesSet & 1) != 0) ? options.keywords : eventTypes.keywords;
3335  NameInfo nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
3336  if (nameInfo != null)
3337  {
3338  num = nameInfo.identity;
3339  EventDescriptor eventDescriptor = new EventDescriptor(num, level, opcode, (long)keywords);
3340  int pinCount = eventTypes.pinCount;
3341  byte* scratch = stackalloc byte[(int)checked(unchecked((ulong)(uint)eventTypes.scratchSize) * 1uL)];
3342  EventData* ptr = stackalloc EventData[eventTypes.dataCount + 3];
3343  GCHandle* ptr2 = stackalloc GCHandle[pinCount];
3344  byte[] array = providerMetadata;
3345  fixed (byte* pointer = array)
3346  {
3347  byte[] nameMetadata = nameInfo.nameMetadata;
3348  fixed (byte* pointer2 = nameMetadata)
3349  {
3350  byte[] typeMetadata = eventTypes.typeMetadata;
3351  fixed (byte* pointer3 = typeMetadata)
3352  {
3353  ptr->SetMetadata(pointer, providerMetadata.Length, 2);
3354  ptr[1].SetMetadata(pointer2, nameInfo.nameMetadata.Length, 1);
3355  ptr[2].SetMetadata(pointer3, eventTypes.typeMetadata.Length, 1);
3357  try
3358  {
3359  DataCollector.ThreadInstance.Enable(scratch, eventTypes.scratchSize, ptr + 3, eventTypes.dataCount, ptr2, pinCount);
3360  for (int i = 0; i < eventTypes.typeInfos.Length; i++)
3361  {
3362  eventTypes.typeInfos[i].WriteObjectData(TraceLoggingDataCollector.Instance, values[i]);
3363  }
3364  WriteEventRaw(eventName, ref eventDescriptor, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - ptr), (IntPtr)(void*)ptr);
3365  }
3366  finally
3367  {
3368  WriteCleanup(ptr2, pinCount);
3369  }
3370  }
3371  }
3372  }
3373  }
3374  }
3375 
3376  [SecuritySafeCritical]
3377  internal unsafe void WriteMultiMerge(string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, EventData* data)
3378  {
3379  if (IsEnabled())
3380  {
3381  fixed (EventSourceOptions* ptr2 = &options)
3382  {
3383  EventDescriptor descriptor;
3384  NameInfo nameInfo = UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
3385  if (nameInfo != null)
3386  {
3387  EventData* ptr = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
3388  byte[] array = providerMetadata;
3389  fixed (byte* pointer = array)
3390  {
3391  byte[] nameMetadata = nameInfo.nameMetadata;
3392  fixed (byte* pointer2 = nameMetadata)
3393  {
3394  byte[] typeMetadata = eventTypes.typeMetadata;
3395  fixed (byte* pointer3 = typeMetadata)
3396  {
3397  ptr->SetMetadata(pointer, providerMetadata.Length, 2);
3398  ptr[1].SetMetadata(pointer2, nameInfo.nameMetadata.Length, 1);
3399  ptr[2].SetMetadata(pointer3, eventTypes.typeMetadata.Length, 1);
3400  int num = 3;
3401  for (int i = 0; i < eventTypes.typeInfos.Length; i++)
3402  {
3403  if (eventTypes.typeInfos[i].DataType == typeof(string))
3404  {
3405  ptr[num].m_Ptr = (long)(&ptr[num + 1].m_Size);
3406  ptr[num].m_Size = 2;
3407  num++;
3408  ptr[num].m_Ptr = data[i].m_Ptr;
3409  ptr[num].m_Size = data[i].m_Size - 2;
3410  num++;
3411  }
3412  else
3413  {
3414  ptr[num].m_Ptr = data[i].m_Ptr;
3415  ptr[num].m_Size = data[i].m_Size;
3416  if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
3417  {
3418  ptr[num].m_Size = 1;
3419  }
3420  num++;
3421  }
3422  }
3423  WriteEventRaw(eventName, ref descriptor, activityID, childActivityID, num, (IntPtr)(void*)ptr);
3424  }
3425  }
3426  }
3427  }
3428  }
3429  }
3430  }
3431 
3432  [SecuritySafeCritical]
3433  private unsafe void WriteImpl<T>(string eventName, ref EventSourceOptions options, ref T data, Guid* pActivityId, Guid* pRelatedActivityId)
3434  {
3435  try
3436  {
3437  SimpleEventTypes<T> instance = SimpleEventTypes<T>.Instance;
3438  try
3439  {
3440  fixed (EventSourceOptions* ptr3 = &options)
3441  {
3442  options.Opcode = (options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName));
3443  EventDescriptor descriptor;
3444  NameInfo nameInfo = UpdateDescriptor(eventName, instance, ref options, out descriptor);
3445  if (nameInfo != null)
3446  {
3447  int pinCount = instance.pinCount;
3448  byte* scratch = stackalloc byte[(int)checked(unchecked((ulong)(uint)instance.scratchSize) * 1uL)];
3449  EventData* ptr = stackalloc EventData[instance.dataCount + 3];
3450  GCHandle* ptr2 = stackalloc GCHandle[pinCount];
3451  try
3452  {
3453  byte[] array = providerMetadata;
3454  fixed (byte* pointer = array)
3455  {
3456  byte[] nameMetadata = nameInfo.nameMetadata;
3457  fixed (byte* pointer2 = nameMetadata)
3458  {
3459  byte[] typeMetadata = instance.typeMetadata;
3460  fixed (byte* pointer3 = typeMetadata)
3461  {
3462  ptr->SetMetadata(pointer, providerMetadata.Length, 2);
3463  ptr[1].SetMetadata(pointer2, nameInfo.nameMetadata.Length, 1);
3464  ptr[2].SetMetadata(pointer3, instance.typeMetadata.Length, 1);
3466  EventOpcode opcode = (EventOpcode)descriptor.Opcode;
3467  Guid activityId = Guid.Empty;
3468  Guid relatedActivityId = Guid.Empty;
3469  if (pActivityId == null && pRelatedActivityId == null && (options.ActivityOptions & EventActivityOptions.Disable) == EventActivityOptions.None)
3470  {
3471  switch (opcode)
3472  {
3473  case EventOpcode.Start:
3474  m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
3475  break;
3476  case EventOpcode.Stop:
3477  m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
3478  break;
3479  }
3480  if (activityId != Guid.Empty)
3481  {
3482  pActivityId = &activityId;
3483  }
3484  if (relatedActivityId != Guid.Empty)
3485  {
3486  pRelatedActivityId = &relatedActivityId;
3487  }
3488  }
3489  try
3490  {
3491  DataCollector.ThreadInstance.Enable(scratch, instance.scratchSize, ptr + 3, instance.dataCount, ptr2, pinCount);
3492  instance.typeInfo.WriteData(TraceLoggingDataCollector.Instance, ref data);
3493  WriteEventRaw(eventName, ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - ptr), (IntPtr)(void*)ptr);
3494  if (m_Dispatchers != null)
3495  {
3496  EventPayload payload = (EventPayload)instance.typeInfo.GetData(data);
3497  WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, payload);
3498  }
3499  }
3500  catch (Exception ex)
3501  {
3502  if (ex is EventSourceException)
3503  {
3504  throw;
3505  }
3506  ThrowEventSourceException(eventName, ex);
3507  }
3508  finally
3509  {
3510  WriteCleanup(ptr2, pinCount);
3511  }
3512  }
3513  }
3514  }
3515  }
3516  finally
3517  {
3518  }
3519  }
3520  }
3521  }
3522  finally
3523  {
3524  }
3525  }
3526  catch (Exception ex2)
3527  {
3528  if (ex2 is EventSourceException)
3529  {
3530  throw;
3531  }
3532  ThrowEventSourceException(eventName, ex2);
3533  }
3534  }
3535 
3536  [SecurityCritical]
3537  private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
3538  {
3539  EventWrittenEventArgs eventWrittenEventArgs = new EventWrittenEventArgs(this);
3540  eventWrittenEventArgs.EventName = eventName;
3541  eventWrittenEventArgs.m_keywords = (EventKeywords)eventDescriptor.Keywords;
3542  eventWrittenEventArgs.m_opcode = (EventOpcode)eventDescriptor.Opcode;
3543  eventWrittenEventArgs.m_tags = tags;
3544  eventWrittenEventArgs.EventId = -1;
3545  if (pActivityId != null)
3546  {
3547  eventWrittenEventArgs.RelatedActivityId = *pActivityId;
3548  }
3549  if (payload != null)
3550  {
3551  eventWrittenEventArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
3552  eventWrittenEventArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
3553  }
3554  DispatchToAllListeners(-1, pActivityId, eventWrittenEventArgs);
3555  }
3556 
3557  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
3558  [SecurityCritical]
3559  [NonEvent]
3560  private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
3561  {
3562  DataCollector.ThreadInstance.Disable();
3563  for (int i = 0; i != cPins; i++)
3564  {
3565  if (IntPtr.Zero != (IntPtr)pPins[i])
3566  {
3567  pPins[i].Free();
3568  }
3569  }
3570  }
3571 
3572  private void InitializeProviderMetadata()
3573  {
3574  if (m_traits != null)
3575  {
3576  List<byte> list = new List<byte>(100);
3577  for (int i = 0; i < m_traits.Length - 1; i += 2)
3578  {
3579  if (!m_traits[i].StartsWith("ETW_"))
3580  {
3581  continue;
3582  }
3583  string text = m_traits[i].Substring(4);
3584  if (!byte.TryParse(text, out byte result))
3585  {
3586  if (!(text == "GROUP"))
3587  {
3588  throw new ArgumentException(Environment.GetResourceString("UnknownEtwTrait", text), "traits");
3589  }
3590  result = 1;
3591  }
3592  string value = m_traits[i + 1];
3593  int count = list.Count;
3594  list.Add(0);
3595  list.Add(0);
3596  list.Add(result);
3597  int num = AddValueToMetaData(list, value) + 3;
3598  list[count] = (byte)num;
3599  list[count + 1] = (byte)(num >> 8);
3600  }
3601  providerMetadata = Statics.MetadataForString(Name, 0, list.Count, 0);
3602  int num2 = providerMetadata.Length - list.Count;
3603  foreach (byte item in list)
3604  {
3605  providerMetadata[num2++] = item;
3606  }
3607  }
3608  else
3609  {
3610  providerMetadata = Statics.MetadataForString(Name, 0, 0, 0);
3611  }
3612  }
3613 
3614  private static int AddValueToMetaData(List<byte> metaData, string value)
3615  {
3616  if (value.Length == 0)
3617  {
3618  return 0;
3619  }
3620  int count = metaData.Count;
3621  char c = value[0];
3622  switch (c)
3623  {
3624  case '@':
3625  metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
3626  break;
3627  case '{':
3628  metaData.AddRange(new Guid(value).ToByteArray());
3629  break;
3630  case '#':
3631  for (int i = 1; i < value.Length; i++)
3632  {
3633  if (value[i] != ' ')
3634  {
3635  if (i + 1 >= value.Length)
3636  {
3637  throw new ArgumentException(Environment.GetResourceString("EvenHexDigits"), "traits");
3638  }
3639  metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
3640  i++;
3641  }
3642  }
3643  break;
3644  default:
3645  if (' ' <= c)
3646  {
3647  metaData.AddRange(Encoding.UTF8.GetBytes(value));
3648  break;
3649  }
3650  throw new ArgumentException(Environment.GetResourceString("IllegalValue", value), "traits");
3651  }
3652  return metaData.Count - count;
3653  }
3654 
3655  private static int HexDigit(char c)
3656  {
3657  if ('0' <= c && c <= '9')
3658  {
3659  return c - 48;
3660  }
3661  if ('a' <= c)
3662  {
3663  c = (char)(c - 32);
3664  }
3665  if ('A' <= c && c <= 'F')
3666  {
3667  return c - 65 + 10;
3668  }
3669  throw new ArgumentException(Environment.GetResourceString("BadHexDigit", c), "traits");
3670  }
3671 
3672  private NameInfo UpdateDescriptor(string name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor)
3673  {
3674  NameInfo nameInfo = null;
3675  int traceloggingId = 0;
3676  byte level = ((options.valuesSet & 4) != 0) ? options.level : eventInfo.level;
3677  byte opcode = ((options.valuesSet & 8) != 0) ? options.opcode : eventInfo.opcode;
3678  EventTags tags = ((options.valuesSet & 2) != 0) ? options.tags : eventInfo.Tags;
3679  EventKeywords keywords = ((options.valuesSet & 1) != 0) ? options.keywords : eventInfo.keywords;
3680  if (IsEnabled((EventLevel)level, keywords))
3681  {
3682  nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
3683  traceloggingId = nameInfo.identity;
3684  }
3685  descriptor = new EventDescriptor(traceloggingId, level, opcode, (long)keywords);
3686  return nameInfo;
3687  }
3688  }
3689 }
Obtains information about the attributes of a member and provides access to member metadata.
Definition: MemberInfo.cs:14
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
A platform-specific type that is used to represent a pointer or a handle.
Definition: UIntPtr.cs:14
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
Definition: CultureInfo.cs:263
Discovers the attributes of a parameter and provides access to parameter metadata.
virtual Assembly Assembly
Gets the appropriate T:System.Reflection.Assembly for this instance of T:System.Reflection....
Definition: Module.cs:133
Allows the event tracing for Windows (ETW) name to be defined independently of the name of the event ...
unsafe void WriteEvent(int eventId, long arg1, string arg2)
Writes an event by using the provided event identifier and 64-bit integer, and string arguments.
string Name
The friendly name of the class that is derived from the event source.
Definition: EventSource.cs:343
EventActivityOptions
Specifies the tracking of activity start and stop events.
virtual IList< CustomAttributeNamedArgument > NamedArguments
Gets the list of named arguments specified for the attribute instance represented by the T:System....
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
unsafe string GetString(byte *bytes, int byteCount)
When overridden in a derived class, decodes a specified number of bytes starting at a specified addre...
Definition: Encoding.cs:1918
The ETW listener should use a manifest-based format when raising events. Setting this option is a dir...
The ETW listener should use self-describing event format. This is the default option when creating a ...
unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid *relatedActivityId, int eventDataCount, EventData *data)
[Supported in the .NET Framework 4.5.1 and later versions] Writes an event that indicates that the cu...
Specifies overrides of default event settings such as the log level, keywords and operation code when...
EventOpcode
Defines the standard operation codes that the event source attaches to events.
Definition: EventOpcode.cs:8
abstract Type FieldType
Gets the type of this field object.
Definition: FieldInfo.cs:34
Represents a named argument of a custom attribute in the reflection-only context.
ReflectionPermissionFlag
Specifies the permitted use of the N:System.Reflection and N:System.Reflection.Emit namespaces.
virtual byte [] GetBytes(char[] chars)
When overridden in a derived class, encodes all the characters in the specified character array into ...
Definition: Encoding.cs:1576
int Count
Gets the number of elements contained in the T:System.Collections.Generic.List`1.
Definition: List.cs:296
Provides methods for enabling and disabling events from event sources.
Definition: EventListener.cs:8
void Dispose()
Releases all resources used by the current instance of the T:System.Diagnostics.Tracing....
Provides the base class for a generic read-only collection.
Discovers the attributes of a method and provides access to method metadata.
Definition: MethodInfo.cs:13
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
string GetTrait(string key)
Gets the trait value associated with the specified key.
Definition: EventSource.cs:689
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
EventSource(string eventSourceName, EventSourceSettings config)
Creates a new instance of the T:System.Diagnostics.Tracing.EventSource class with the specified name ...
static string GetName(Type eventSourceType)
Gets the friendly name of the event source.
Definition: EventSource.cs:572
unsafe void WriteEvent(int eventId, string arg1, int arg2)
Writes an event by using the provided event identifier and arguments.
Definition: EventSource.cs:985
EventManifestOptions
Specifies how the ETW manifest for the event source is generated.
EventKeywords
Defines the standard keywords that apply to events.
Definition: EventKeywords.cs:6
bool IsVirtual
Gets a value indicating whether the method is virtual.
Definition: MethodBase.cs:253
static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags)
Returns a string of the XML manifest that is associated with the current event source.
Definition: EventSource.cs:593
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
Definition: IDisposable.cs:8
Discovers the attributes of a field and provides access to field metadata.
Definition: FieldInfo.cs:15
static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest)
Returns a string of the XML manifest that is associated with the current event source.
Definition: EventSource.cs:582
BindingFlags
Specifies flags that control binding and the way in which the search for members and types is conduct...
Definition: BindingFlags.cs:10
Definition: __Canon.cs:3
virtual Type ReturnType
Gets the return type of this method.
Definition: MethodInfo.cs:23
abstract object [] GetCustomAttributes(bool inherit)
When overridden in a derived class, returns an array of all custom attributes applied to this member.
Provides access to custom attribute data for assemblies, modules, types, members and parameters that ...
Exception ConstructionException
[Supported in the .NET Framework 4.5.1 and later versions] Gets any exception that was thrown during ...
Definition: EventSource.cs:417
static IList< CustomAttributeData > GetCustomAttributes(MemberInfo target)
Returns a list of T:System.Reflection.CustomAttributeData objects representing data about the attribu...
Guid Guid
The unique identifier for the event source.
Definition: EventSource.cs:355
virtual void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.Diagnostics.Tracing.EventSource class and optio...
EventKeywords Keywords
Gets or sets the keywords applied to the event. If this property is not set, the event’s keywords wil...
Exposes the enumerator, which supports a simple iteration over a collection of a specified type....
Definition: IEnumerable.cs:9
The exception that is thrown when an error occurs during event tracing for Windows (ETW).
static Delegate Remove(Delegate source, Delegate value)
Removes the last occurrence of the invocation list of a delegate from the invocation list of another ...
Definition: Delegate.cs:287
static Delegate Combine(Delegate a, Delegate b)
Concatenates the invocation lists of two delegates.
Definition: Delegate.cs:202
Represents a resource manager that provides convenient access to culture-specific resources at run ti...
bool IsStatic
Gets a value indicating whether the method is static.
Definition: MethodBase.cs:227
A type representing a date and time value.
EventSource()
Creates a new instance of the T:System.Diagnostics.Tracing.EventSource class.
Definition: EventSource.cs:714
static IEnumerable< EventSource > GetSources()
Gets a snapshot of all the event sources for the application domain.
Definition: EventSource.cs:610
static CultureInfo CurrentUICulture
Gets or sets the T:System.Globalization.CultureInfo object that represents the current user interface...
Definition: CultureInfo.cs:174
Cer
Specifies a method's behavior when called within a constrained execution region.
Definition: Cer.cs:5
Represents a weak reference, which references an object while still allowing that object to be reclai...
static Encoding BigEndianUnicode
Gets an encoding for the UTF-16 format that uses the big endian byte order.
Definition: Encoding.cs:991
unsafe void WriteEvent(int eventId, long arg1)
Writes an event by using the provided event identifier and 64-bit integer argument.
Definition: EventSource.cs:828
EventLevel
Identifies the level of an event.
Definition: EventLevel.cs:5
void Add(T item)
Adds an object to the end of the T:System.Collections.Generic.List`1.
Definition: List.cs:510
override string ToString()
Obtains a string representation of the current event source instance.
Definition: EventSource.cs:707
EventLevel Level
Gets or sets the event level applied to the event.
bool TryGetValue(TKey key, out TValue value)
Gets the value associated with the specified key.
Provides information about, and means to manipulate, the current environment and platform....
Definition: Environment.cs:21
Represents a globally unique identifier (GUID).To browse the .NET Framework source code for this type...
Definition: Guid.cs:14
Type ReflectedType
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
static void SendCommand(EventSource eventSource, EventCommand command, IDictionary< string, string > commandArguments)
Sends a command to a specified event source.
Definition: EventSource.cs:632
unsafe void WriteEvent(int eventId, int arg1, string arg2)
Writes an event by using the provided event identifier and 32-bit integer and string arguments.
void WriteEvent(int eventId)
Writes an event by using the provided event identifier.
Definition: EventSource.cs:760
EventSourceSettings
Specifies configuration options for an event source.
unsafe void WriteEvent(int eventId, long arg1, byte[] arg2)
Writes the event data using the specified indentifier and 64-bit integer and byte array arguments.
static void SetCurrentThreadActivityId(Guid activityId)
[Supported in the .NET Framework 4.5.1 and later versions] Sets the activity ID on the current thread...
Definition: EventSource.cs:649
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
An event that is published when an application starts a new transaction or activity....
Provides the arguments for the M:System.Diagnostics.Tracing.EventSource.OnEventCommand(System....
Opens the file if it exists and seeks to the end of the file, or creates a new file....
unsafe void WriteEventCore(int eventId, int eventDataCount, EventData *data)
Creates a new Overload:System.Diagnostics.Tracing.EventSource.WriteEvent overload by using the provid...
unsafe void WriteEvent(int eventId, string arg1, long arg2)
Writes an event by using the provided event identifier and arguments.
virtual void OnEventCommand(EventCommandEventArgs command)
Called when the current event source is updated by the controller.
Definition: EventSource.cs:752
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
Provides the ability to create events for event tracing for Windows (ETW).
Definition: EventSource.cs:21
void Write(string eventName)
Writes an event without fields, but with the specified name and default options.
static void PrepareConstrainedRegions()
Designates a body of code as a constrained execution region (CER).
IntPtr DataPointer
Gets or sets the pointer to the data for the new Overload:System.Diagnostics.Tracing....
Definition: EventSource.cs:37
Represents a delegate, which is a data structure that refers to a static method or to a class instanc...
Definition: Delegate.cs:15
bool IsEnabled()
Determines whether the current event source is enabled.
Definition: EventSource.cs:498
Represents type declarations: class types, interface types, array types, value types,...
Definition: Type.cs:18
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel)
Determines whether the current event source is enabled for events with the specified level,...
Definition: EventSource.cs:521
Provides a way to access a managed object from unmanaged memory.
Definition: GCHandle.cs:10
Provides the event data for creating fast Overload:System.Diagnostics.Tracing.EventSource....
Definition: EventSource.cs:25
MethodImplOptions
Defines the details of how a method is implemented.
void AddRange(IEnumerable< T > collection)
Adds the elements of the specified collection to the end of the T:System.Collections....
Definition: List.cs:545
Indicates that data in the pipe is transmitted and read as a stream of messages.
string Name
Gets or sets the name of the event source.
abstract string Name
Gets the name of the current member.
Definition: MemberInfo.cs:27
static bool TryParse(string input, out Guid result)
Converts the string representation of a GUID to the equivalent T:System.Guid structure.
Definition: Guid.cs:323
object Value
Gets the value of the argument for a simple argument or for an element of an array argument; gets a c...
EventSource(EventSourceSettings settings, params string[] traits)
Initializes a new instance of the T:System.Diagnostics.Tracing.EventSource to be used with non-contra...
Definition: EventSource.cs:742
EventSource(EventSourceSettings settings)
Creates a new instance of the T:System.Diagnostics.Tracing.EventSource class with the specified confi...
Definition: EventSource.cs:731
virtual MethodBody GetMethodBody()
When overridden in a derived class, gets a T:System.Reflection.MethodBody object that provides access...
Definition: MethodBase.cs:631
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
Discovers the attributes of a property and provides access to property metadata.
Definition: PropertyInfo.cs:15
The exception that is thrown when one of the arguments provided to a method is not valid.
void Free()
Releases a T:System.Runtime.InteropServices.GCHandle.
Definition: GCHandle.cs:119
unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3)
Writes an event by using the provided event identifier and string arguments.
Definition: EventSource.cs:943
static unsafe string PtrToStringUni(IntPtr ptr, int len)
Allocates a managed T:System.String and copies a specified number of characters from an unmanaged Uni...
Definition: Marshal.cs:103
EventTags
Specifies the tracking of activity start and stop events. You should only use the lower 24 bits....
Definition: EventTags.cs:6
virtual ConstructorInfo Constructor
Gets a T:System.Reflection.ConstructorInfo object that represents the constructor that would have ini...
Attribute can be applied to an enumeration.
unsafe void WriteEvent(int eventId, string arg1, string arg2)
Writes an event by using the provided event identifier and string arguments.
Definition: EventSource.cs:909
unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args)
[Supported in the .NET Framework 4.5.1 and later versions] Writes an event that indicates that the cu...
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
void WriteEvent(int eventId, params object[] args)
Writes an event by using the provided event identifier and array of arguments.
EventSource(string eventSourceName)
Creates a new instance of the T:System.Diagnostics.Tracing.EventSource class with the specified name.
unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3)
Writes an event by using the provided event identifier and 64-bit arguments.
Definition: EventSource.cs:865
virtual byte [] GetILAsByteArray()
Returns the MSIL for the method body, as an array of bytes.
Definition: MethodBody.cs:52
EventTask
Defines the tasks that apply to events.
Definition: EventTask.cs:8
virtual Module Module
Gets the module in which the type that declares the member represented by the current T:System....
Definition: MemberInfo.cs:78
unsafe void WriteEvent(int eventId, byte[] arg1)
Writes an event by using the provided event identifier and byte array argument.
virtual object GetRawConstantValue()
Returns a literal value associated with the field by a compiler.
Definition: FieldInfo.cs:341
void Write(string eventName, EventSourceOptions options)
Writes an event without fields, but with the specified name and options.
CustomAttributeTypedArgument TypedValue
Gets a T:System.Reflection.CustomAttributeTypedArgument structure that can be used to obtain the type...
EventSourceSettings Settings
Gets the settings applied to this event source.
Definition: EventSource.cs:367
virtual Type ParameterType
Gets the Type of this parameter.
static Encoding UTF8
Gets an encoding for the UTF-8 format.
Definition: Encoding.cs:1023
MemberInfo MemberInfo
Gets the attribute member that would be used to set the named argument.
virtual bool ReflectionOnly
Gets a T:System.Boolean value indicating whether this assembly was loaded into the reflection-only co...
Definition: Assembly.cs:182
unsafe void WriteEvent(int eventId, string arg1)
Writes an event by using the provided event identifier and string argument.
Definition: EventSource.cs:885
unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3)
Writes an event by using the provided event identifier and arguments.
Consistency
Specifies a reliability contract.
Definition: Consistency.cs:5
string Name
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
Definition: _MethodInfo.cs:24
static readonly Guid Empty
A read-only instance of the T:System.Guid structure whose value is all zeros.
Definition: Guid.cs:126
void Assert()
Declares that the calling code can access the resource protected by a permission demand through the c...
EventCommand
Describes the command (P:System.Diagnostics.Tracing.EventCommandEventArgs.Command property) that is p...
Definition: EventCommand.cs:5
unsafe void WriteEvent(int eventId, int arg1, int arg2)
Writes an event by using the provided event identifier and 32-bit integer arguments.
Definition: EventSource.cs:788
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
virtual IList< CustomAttributeTypedArgument > ConstructorArguments
Gets the list of positional arguments specified for the attribute instance represented by the T:Syste...
bool IsEnabled(EventLevel level, EventKeywords keywords)
Determines whether the current event source that has the specified level and keyword is enabled.
Definition: EventSource.cs:509
static void Sleep(int millisecondsTimeout)
Suspends the current thread for the specified number of milliseconds.
Definition: Thread.cs:746
static Guid GetGuid(Type eventSourceType)
Gets the unique identifier for this implementation of the event source.
Definition: EventSource.cs:538
int Size
Gets or sets the number of payload items in the new Overload:System.Diagnostics.Tracing....
Definition: EventSource.cs:52
string Guid
Gets or sets the event source identifier.
unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3)
Writes an event by using the provided event identifier and 32-bit integer arguments.
Definition: EventSource.cs:808
static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue)
[Supported in the .NET Framework 4.5.1 and later versions] Sets the activity ID on the current thread...
Definition: EventSource.cs:675
EventOpcode Opcode
Gets or sets the operation code to use for the specified event.
Controls access to non-public types and members through the N:System.Reflection APIs....
Provides atomic operations for variables that are shared by multiple threads.
Definition: Interlocked.cs:10
unsafe void WriteEvent(int eventId, long arg1, long arg2)
Writes an event by using the provided event identifier and 64-bit arguments.
Definition: EventSource.cs:845
unsafe void WriteEvent(int eventId, int arg1)
Writes an event by using the provided event identifier and 32-bit integer argument.
Definition: EventSource.cs:771
EventHandler< EventCommandEventArgs > EventCommandExecuted
Occurs when a command comes from an event listener.
Definition: EventSource.cs:479
abstract ParameterInfo [] GetParameters()
When overridden in a derived class, gets the parameters of the specified method or constructor.
EventChannel
Specifies the event log channel for the event.
Definition: EventChannel.cs:8
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
Provides a set of static methods and properties that provide support for compilers....
static Guid CurrentThreadActivityId
[Supported in the .NET Framework 4.5.1 and later versions] Gets the activity ID of the current thread...
Definition: EventSource.cs:379
Creates and controls a thread, sets its priority, and gets its status.
Definition: Thread.cs:18