diff options
Diffstat (limited to 'src/mscorlib/src/System/Diagnostics/Eventing')
17 files changed, 279 insertions, 362 deletions
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs index a7124a26ff..1a1f5fa2c0 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs @@ -72,7 +72,7 @@ namespace System.Diagnostics.Tracing } - Contract.Assert((options & EventActivityOptions.Disable) == 0); + Debug.Assert((options & EventActivityOptions.Disable) == 0); var currentActivity = m_current.Value; var fullActivityName = NormalizeActivityName(providerName, activityName, task); @@ -191,7 +191,7 @@ namespace System.Diagnostics.Tracing else { orphan.m_stopped = 1; - Contract.Assert(orphan.m_stopped != 0); + Debug.Assert(orphan.m_stopped != 0); } orphan = orphan.m_creator; } @@ -221,7 +221,6 @@ namespace System.Diagnostics.Tracing /// <summary> /// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise) /// </summary> - [System.Security.SecuritySafeCritical] public void Enable() { if (m_current == null) @@ -366,7 +365,6 @@ namespace System.Diagnostics.Tracing /// byte (since the top nibble can't be zero you can determine if this is true by seeing if /// this byte is nonZero. This offset is needed to efficiently create the ID for child activities. /// </summary> - [System.Security.SecuritySafeCritical] private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset) { fixed (Guid* outPtr = &idRet) @@ -403,7 +401,6 @@ namespace System.Diagnostics.Tracing /// sufficient space for this ID. By doing this, we preserve the fact that this activity /// is a child (of unknown depth) from that ancestor. /// </summary> - [System.Security.SecurityCritical] private unsafe void CreateOverflowGuid(Guid* outPtr) { // Search backwards for an ancestor that has sufficient space to put the ID. @@ -452,7 +449,6 @@ namespace System.Diagnostics.Tracing /// is the maximum number of bytes that fit in a GUID) if the path did not fit. /// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a /// special (longer prefix) that indicates that this ID is allocated differently - [System.Security.SecurityCritical] private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false) { byte* ptr = (byte*)outPtr; @@ -526,11 +522,10 @@ namespace System.Diagnostics.Tracing /// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes /// the new byte (in the high bits) of the next byte. /// </summary> - [System.Security.SecurityCritical] private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value) { - Contract.Assert(0 <= value && value < 16); - Contract.Assert(ptr < endPtr); + Debug.Assert(0 <= value && value < 16); + Debug.Assert(ptr < endPtr); if (*ptr != 0) *ptr++ |= (byte)value; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs index 6ea8d98d92..ce0fcb6acb 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs @@ -74,7 +74,6 @@ namespace System.Diagnostics.Tracing private static bool m_setInformationMissing; - [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level @@ -128,7 +127,6 @@ namespace System.Diagnostics.Tracing // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> - [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; @@ -157,7 +155,6 @@ namespace System.Diagnostics.Tracing // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> - [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // @@ -175,16 +172,31 @@ namespace System.Diagnostics.Tracing // Disable the provider. m_enabled = false; - // Do most of the work under a lock to avoid shutdown race. + // Do most of the work under a lock to avoid shutdown race. + + long registrationHandle = 0; lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; - Deregister(); + registrationHandle = m_regHandle; + m_regHandle = 0; m_disposed = true; } + + // We do the Unregistration outside the EventListenerLock because there is a lock + // inside the ETW routines. This lock is taken before ETW issues commands + // Thus the ETW lock gets taken first and then our EventListenersLock gets taken + // in SendCommand(), and also here. If we called EventUnregister after taking + // the EventListenersLock then the take-lock order is reversed and we can have + // deadlocks in race conditions (dispose racing with an ETW command). + // + // We solve by Unregistering after releasing the EventListenerLock. + if (registrationHandle != 0) + EventUnregister(registrationHandle); + } /// <summary> @@ -201,33 +213,10 @@ namespace System.Diagnostics.Tracing Dispose(false); } - /// <summary> - /// This method un-registers from ETW. - /// </summary> - // <SecurityKernel Critical="True" Ring="0"> - // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> - // </SecurityKernel> - // TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] - private unsafe void Deregister() - { - // - // Unregister from ETW using the RegHandle saved from - // the register call. - // - - if (m_regHandle != 0) - { - EventUnregister(); - m_regHandle = 0; - } - } - // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Parameter filterData of type: Void*" /> // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" /> // </SecurityKernel> - [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int controlCode, @@ -348,7 +337,6 @@ namespace System.Diagnostics.Tracing /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> - [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; @@ -424,7 +412,6 @@ namespace System.Diagnostics.Tracing /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> - [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { // We wish the EventSource package to be legal for Windows Store applications. @@ -470,7 +457,7 @@ namespace System.Diagnostics.Tracing } if (providerInstance->NextOffset == 0) break; - Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); + Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } @@ -552,7 +539,6 @@ namespace System.Diagnostics.Tracing /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> - [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { @@ -685,7 +671,6 @@ namespace System.Diagnostics.Tracing // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> - [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ @@ -934,7 +919,6 @@ namespace System.Diagnostics.Tracing // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; @@ -1131,13 +1115,12 @@ namespace System.Diagnostics.Tracing // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode - Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || + Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); @@ -1154,7 +1137,6 @@ namespace System.Diagnostics.Tracing } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, @@ -1183,7 +1165,6 @@ namespace System.Diagnostics.Tracing // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). - [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; @@ -1191,12 +1172,9 @@ namespace System.Diagnostics.Tracing return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } - [SecurityCritical] - private uint EventUnregister() + private uint EventUnregister(long registrationHandle) { - uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); - m_regHandle = 0; - return status; + return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle); } static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; @@ -1209,7 +1187,7 @@ namespace System.Diagnostics.Tracing } private static int bitindex(uint n) { - Contract.Assert(bitcount(n) == 1); + Debug.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs index 8c2edfdec2..aa0d8d72d1 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs @@ -529,7 +529,6 @@ namespace System.Diagnostics.Tracing /// </summary> internal static Guid InternalCurrentThreadActivityId { - [System.Security.SecurityCritical] get { Guid retval = CurrentThreadActivityId; @@ -543,12 +542,11 @@ namespace System.Diagnostics.Tracing internal static Guid FallbackActivityId { - [System.Security.SecurityCritical] get { #pragma warning disable 612, 618 int threadID = AppDomain.GetCurrentThreadId(); - + // Managed thread IDs are more aggressively re-used than native thread IDs, // so we'll use the latter... return new Guid(unchecked((uint)threadID), @@ -608,7 +606,7 @@ namespace System.Diagnostics.Tracing add { m_eventCommandExecuted += value; - + // If we have an EventHandler<EventCommandEventArgs> attached to the EventSource before the first command arrives // It should get a chance to handle the deferred commands. EventCommandEventArgs deferredCommands = m_deferredCommands; @@ -706,7 +704,7 @@ namespace System.Diagnostics.Tracing return; } - + /// <summary> /// This method is called when the eventSource is updated by the controller. /// </summary> @@ -714,7 +712,6 @@ namespace System.Diagnostics.Tracing #pragma warning disable 1591 // optimized for common signatures (no args) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId) { @@ -722,7 +719,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (ints) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, int arg1) { @@ -735,7 +731,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, int arg1, int arg2) { @@ -750,7 +745,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3) { @@ -768,7 +762,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (longs) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, long arg1) { @@ -781,7 +774,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, long arg1, long arg2) { @@ -796,7 +788,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3) { @@ -814,7 +805,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (strings) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1) { @@ -831,7 +821,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1, string arg2) { @@ -852,7 +841,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3) { @@ -878,7 +866,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (string and ints) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1, int arg2) { @@ -897,7 +884,6 @@ namespace System.Diagnostics.Tracing } } - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3) { @@ -919,7 +905,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (string and longs) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, string arg1, long arg2) { @@ -939,7 +924,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (long and string) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, long arg1, string arg2) { @@ -959,7 +943,6 @@ namespace System.Diagnostics.Tracing } // optimized for common signatures (int and string) - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, int arg1, string arg2) { @@ -977,70 +960,68 @@ namespace System.Diagnostics.Tracing } } } - - [SecuritySafeCritical] - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, byte[] arg1) - { - if (m_eventSourceEnabled) - { - EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; - if (arg1 == null || arg1.Length == 0) - { - int blobSize = 0; - descrs[0].DataPointer = (IntPtr)(&blobSize); - descrs[0].Size = 4; - descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content - descrs[1].Size = 0; - WriteEventCore(eventId, 2, descrs); - } - else - { - int blobSize = arg1.Length; - fixed (byte* blob = &arg1[0]) - { - descrs[0].DataPointer = (IntPtr)(&blobSize); - descrs[0].Size = 4; - descrs[1].DataPointer = (IntPtr)blob; - descrs[1].Size = blobSize; - WriteEventCore(eventId, 2, descrs); - } - } - } - } - - [SecuritySafeCritical] - [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] - protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2) - { - if (m_eventSourceEnabled) - { - EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; - descrs[0].DataPointer = (IntPtr)(&arg1); - descrs[0].Size = 8; - if (arg2 == null || arg2.Length == 0) - { - int blobSize = 0; - descrs[1].DataPointer = (IntPtr)(&blobSize); - descrs[1].Size = 4; - descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents - descrs[2].Size = 0; - WriteEventCore(eventId, 3, descrs); - } - else - { - int blobSize = arg2.Length; - fixed (byte* blob = &arg2[0]) - { - descrs[1].DataPointer = (IntPtr)(&blobSize); - descrs[1].Size = 4; - descrs[2].DataPointer = (IntPtr)blob; - descrs[2].Size = blobSize; - WriteEventCore(eventId, 3, descrs); - } - } - } - } + + [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] + protected unsafe void WriteEvent(int eventId, byte[] arg1) + { + if (m_eventSourceEnabled) + { + EventSource.EventData* descrs = stackalloc EventSource.EventData[2]; + if (arg1 == null || arg1.Length == 0) + { + int blobSize = 0; + descrs[0].DataPointer = (IntPtr)(&blobSize); + descrs[0].Size = 4; + descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content + descrs[1].Size = 0; + WriteEventCore(eventId, 2, descrs); + } + else + { + int blobSize = arg1.Length; + fixed (byte* blob = &arg1[0]) + { + descrs[0].DataPointer = (IntPtr)(&blobSize); + descrs[0].Size = 4; + descrs[1].DataPointer = (IntPtr)blob; + descrs[1].Size = blobSize; + WriteEventCore(eventId, 2, descrs); + } + } + } + } + + [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] + protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2) + { + if (m_eventSourceEnabled) + { + EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; + descrs[0].DataPointer = (IntPtr)(&arg1); + descrs[0].Size = 8; + if (arg2 == null || arg2.Length == 0) + { + int blobSize = 0; + descrs[1].DataPointer = (IntPtr)(&blobSize); + descrs[1].Size = 4; + descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents + descrs[2].Size = 0; + WriteEventCore(eventId, 3, descrs); + } + else + { + int blobSize = arg2.Length; + fixed (byte* blob = &arg2[0]) + { + descrs[1].DataPointer = (IntPtr)(&blobSize); + descrs[1].Size = 4; + descrs[2].DataPointer = (IntPtr)blob; + descrs[2].Size = blobSize; + WriteEventCore(eventId, 3, descrs); + } + } + } + } #pragma warning restore 1591 @@ -1067,7 +1048,6 @@ namespace System.Diagnostics.Tracing /// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param> /// <param name="size">The size of the metadata blob.</param> /// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param> - [SecurityCritical] internal unsafe void SetMetadata(byte* pointer, int size, int reserved) { this.m_Ptr = (long)(ulong)(UIntPtr)pointer; @@ -1109,7 +1089,6 @@ namespace System.Diagnostics.Tracing /// } /// </code> /// </remarks> - [SecurityCritical] [CLSCompliant(false)] protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data) { @@ -1141,7 +1120,6 @@ namespace System.Diagnostics.Tracing /// } /// </code> /// </remarks> - [SecurityCritical] [CLSCompliant(false)] protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data) { @@ -1149,36 +1127,37 @@ namespace System.Diagnostics.Tracing { try { - Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (relatedActivityId != null) ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); -#if FEATURE_MANAGED_ETW - if (m_eventData[eventId].EnabledForETW) + EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; + EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions; + Guid* pActivityId = null; + Guid activityId = Guid.Empty; + Guid relActivityId = Guid.Empty; + + if (opcode != EventOpcode.Info && relatedActivityId == null && + ((activityOptions & EventActivityOptions.Disable) == 0)) { - EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; - EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions; - Guid* pActivityId = null; - Guid activityId = Guid.Empty; - Guid relActivityId = Guid.Empty; - - if (opcode != EventOpcode.Info && relatedActivityId == null && - ((activityOptions & EventActivityOptions.Disable) == 0)) + if (opcode == EventOpcode.Start) { - if (opcode == EventOpcode.Start) - { - m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relActivityId, m_eventData[eventId].ActivityOptions); - } - else if (opcode == EventOpcode.Stop) - { - m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId); - } - - if (activityId != Guid.Empty) - pActivityId = &activityId; - if (relActivityId != Guid.Empty) - relatedActivityId = &relActivityId; + m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relActivityId, m_eventData[eventId].ActivityOptions); } + else if (opcode == EventOpcode.Stop) + { + m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId); + } + + if (activityId != Guid.Empty) + pActivityId = &activityId; + if (relActivityId != Guid.Empty) + relatedActivityId = &relActivityId; + } + +#if FEATURE_MANAGED_ETW + if (m_eventData[eventId].EnabledForETW) + { #if FEATURE_ACTIVITYSAMPLING // this code should be kept in sync with WriteEventVarargs(). @@ -1298,7 +1277,6 @@ namespace System.Diagnostics.Tracing /// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> - [SecuritySafeCritical] [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] protected unsafe void WriteEvent(int eventId, params object[] args) { @@ -1313,7 +1291,6 @@ namespace System.Diagnostics.Tracing /// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/> /// check so that the varargs call is not made when the EventSource is not active. /// </summary> - [SecuritySafeCritical] protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args) { WriteEventVarargs(eventId, &relatedActivityId, args); @@ -1380,7 +1357,7 @@ namespace System.Diagnostics.Tracing #if FEATURE_ACTIVITYSAMPLING internal void WriteStringToListener(EventListener listener, string msg, SessionMask m) { - Contract.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0)); + Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0)); if (m_eventSourceEnabled) { @@ -1390,18 +1367,18 @@ namespace System.Diagnostics.Tracing } else { - List<object> arg = new List<object>(); - arg.Add(msg); EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventId = 0; - eventCallbackArgs.Payload = new ReadOnlyCollection<object>(arg); + eventCallbackArgs.Message = msg; + eventCallbackArgs.Payload = new ReadOnlyCollection<object>(new List<object>() { msg }); + eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>(new List<string> { "message" }); + eventCallbackArgs.EventName = "EventSourceMessage"; listener.OnEventWritten(eventCallbackArgs); } } } #endif - [SecurityCritical] private unsafe void WriteEventRaw( string eventName, ref EventDescriptor eventDescriptor, @@ -1443,7 +1420,6 @@ namespace System.Diagnostics.Tracing /// member, and any future access to the "Log" would throw the cached exception). /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] - [SecuritySafeCritical] private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits) { try @@ -1500,7 +1476,7 @@ namespace System.Diagnostics.Tracing #endif { int setInformationResult; - System.Runtime.InteropServices.GCHandle metadataHandle = + System.Runtime.InteropServices.GCHandle metadataHandle = System.Runtime.InteropServices.GCHandle.Alloc(this.providerMetadata, System.Runtime.InteropServices.GCHandleType.Pinned); IntPtr providerMetadata = metadataHandle.AddrOfPinnedObject(); @@ -1513,7 +1489,7 @@ namespace System.Diagnostics.Tracing } #endif // FEATURE_MANAGED_ETW - Contract.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. + Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted. // We are logically completely initialized at this point. m_completelyInited = true; } @@ -1742,7 +1718,6 @@ namespace System.Diagnostics.Tracing return new Guid(bytes); } - [SecurityCritical] private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data) { // TODO FIX : We use reflection which in turn uses EventSource, right now we carefully avoid @@ -1754,7 +1729,7 @@ namespace System.Diagnostics.Tracing Type dataType = GetDataType(m_eventData[eventId], parameterId); - Again: + Again: if (dataType == typeof(IntPtr)) { return *((IntPtr*)dataPointer); @@ -1889,14 +1864,13 @@ namespace System.Diagnostics.Tracing return dispatcher; } - [SecurityCritical] private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object[] args) { if (m_eventSourceEnabled) { try { - Contract.Assert(m_eventData != null); // You must have initialized this if you enabled the source. + Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source. if (childActivityID != null) { ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name); @@ -1916,33 +1890,34 @@ namespace System.Diagnostics.Tracing } LogEventArgsMismatches(m_eventData[eventId].Parameters, args); -#if FEATURE_MANAGED_ETW - if (m_eventData[eventId].EnabledForETW) + + Guid* pActivityId = null; + Guid activityId = Guid.Empty; + Guid relatedActivityId = Guid.Empty; + EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; + EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions; + + if (childActivityID == null && + ((activityOptions & EventActivityOptions.Disable) == 0)) { - Guid* pActivityId = null; - Guid activityId = Guid.Empty; - Guid relatedActivityId = Guid.Empty; - EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode; - EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions; - - if (childActivityID == null && - ((activityOptions & EventActivityOptions.Disable) == 0)) + if (opcode == EventOpcode.Start) { - if (opcode == EventOpcode.Start) - { - m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions); - } - else if (opcode == EventOpcode.Stop) - { - m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId); - } - - if (activityId != Guid.Empty) - pActivityId = &activityId; - if (relatedActivityId != Guid.Empty) - childActivityID = &relatedActivityId; + m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions); + } + else if (opcode == EventOpcode.Stop) + { + m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId); } + if (activityId != Guid.Empty) + pActivityId = &activityId; + if (relatedActivityId != Guid.Empty) + childActivityID = &relatedActivityId; + } + +#if FEATURE_MANAGED_ETW + if (m_eventData[eventId].EnabledForETW) + { #if FEATURE_ACTIVITYSAMPLING // this code should be kept in sync with WriteEventWithRelatedActivityIdCore(). SessionMask etwSessions = SessionMask.All; @@ -2059,7 +2034,6 @@ namespace System.Diagnostics.Tracing } } - [SecurityCritical] unsafe private object[] SerializeEventArgs(int eventId, object[] args) { TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes; @@ -2120,9 +2094,9 @@ namespace System.Diagnostics.Tracing private int GetParamLenghtIncludingByteArray(ParameterInfo[] parameters) { int sum = 0; - foreach(ParameterInfo info in parameters) + foreach (ParameterInfo info in parameters) { - if(info.ParameterType == typeof(byte[])) + if (info.ParameterType == typeof(byte[])) { sum += 2; } @@ -2135,7 +2109,6 @@ namespace System.Diagnostics.Tracing return sum; } - [SecurityCritical] unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventSource.EventData* data) { // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious @@ -2159,7 +2132,6 @@ namespace System.Diagnostics.Tracing } // helper for writing to all EventListeners attached the current eventSource. - [SecurityCritical] unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, params object[] args) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); @@ -2173,13 +2145,12 @@ namespace System.Diagnostics.Tracing DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs); } - [SecurityCritical] private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs) { Exception lastThrownException = null; for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next) { - Contract.Assert(dispatcher.m_EventEnabled != null); + Debug.Assert(dispatcher.m_EventEnabled != null); if (eventId == -1 || dispatcher.m_EventEnabled[eventId]) { #if FEATURE_ACTIVITYSAMPLING @@ -2214,8 +2185,7 @@ namespace System.Diagnostics.Tracing throw new EventSourceException(lastThrownException); } } - - [SecuritySafeCritical] + [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEventString(EventLevel level, long keywords, string msgString) { @@ -2310,7 +2280,6 @@ namespace System.Diagnostics.Tracing } #if FEATURE_ACTIVITYSAMPLING - [SecurityCritical] unsafe private SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID) { SessionMask etwSessions = new SessionMask(); @@ -2429,9 +2398,9 @@ namespace System.Diagnostics.Tracing try { m_EventSourceExceptionRecurenceCount++; - + string errorPrefix = "EventSourceException"; - if(eventName != null) + if (eventName != null) { errorPrefix += " while processing event \"" + eventName + "\""; } @@ -2473,7 +2442,7 @@ namespace System.Diagnostics.Tracing private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string eventName) { if ((EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Send && - (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive && + (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive && (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Start) { ThrowEventSourceException(eventName); @@ -2545,7 +2514,7 @@ namespace System.Diagnostics.Tracing public TraceLoggingEventTypes TraceLoggingEventTypes; public EventActivityOptions ActivityOptions; - + #if PROJECTN public EventParameterType[] ParameterTypes; #endif @@ -2611,7 +2580,7 @@ namespace System.Diagnostics.Tracing { // PRECONDITION: We should be holding the EventListener.EventListenersLock // We defer commands until we are completely inited. This allows error messages to be sent. - Contract.Assert(m_completelyInited); + Debug.Assert(m_completelyInited); #if FEATURE_MANAGED_ETW if (m_provider == null) // If we failed to construct @@ -2623,7 +2592,7 @@ namespace System.Diagnostics.Tracing try { EnsureDescriptorsInitialized(); - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); // Find the per-EventSource dispatcher corresponding to registered dispatcher commandArgs.dispatcher = GetDispatcher(commandArgs.listener); @@ -2682,7 +2651,7 @@ namespace System.Diagnostics.Tracing // hasn't changed. // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions - Contract.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); + Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX); // Send the manifest if we are enabling an ETW session if (bSessionEnable && commandArgs.dispatcher == null) @@ -2737,7 +2706,7 @@ namespace System.Diagnostics.Tracing // things like log messages, or test if keywords are enabled in the callback. if (commandArgs.enable) { - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); m_eventSourceEnabled = true; } @@ -2825,9 +2794,9 @@ namespace System.Diagnostics.Tracing } // These are not used for non-update commands and thus should always be 'default' values - // Contract.Assert(enable == true); - // Contract.Assert(level == EventLevel.LogAlways); - // Contract.Assert(matchAnyKeyword == EventKeywords.None); + // Debug.Assert(enable == true); + // Debug.Assert(level == EventLevel.LogAlways); + // Debug.Assert(matchAnyKeyword == EventKeywords.None); this.OnEventCommand(commandArgs); var eventCommandCallback = m_eventCommandExecuted; @@ -3017,16 +2986,15 @@ namespace System.Diagnostics.Tracing return false; } - private bool IsDisposed + private bool IsDisposed { get { return m_eventSourceDisposed; } } - [SecuritySafeCritical] private void EnsureDescriptorsInitialized() { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (m_eventData == null) { @@ -3042,9 +3010,9 @@ namespace System.Diagnostics.Tracing if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null) { // GetMetadata failed, so we have to set it via reflection. - Contract.Assert(m_rawManifest == null); + Debug.Assert(m_rawManifest == null); m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this); - Contract.Assert(m_eventData != null); + Debug.Assert(m_eventData != null); } else @@ -3089,7 +3057,6 @@ namespace System.Diagnostics.Tracing // Send out the ETW manifest XML out to ETW // Today, we only send the manifest to ETW, custom listeners don't get it. - [SecuritySafeCritical] private unsafe bool SendManifest(byte[] rawManifest) { bool success = true; @@ -3097,7 +3064,7 @@ namespace System.Diagnostics.Tracing if (rawManifest == null) return false; - Contract.Assert(!SelfDescribingEvents); + Debug.Assert(!SelfDescribingEvents); #if FEATURE_MANAGED_ETW fixed (byte* dataPtr = rawManifest) @@ -3124,7 +3091,7 @@ namespace System.Diagnostics.Tracing dataDescrs[1].Reserved = 0; int chunkSize = ManifestEnvelope.MaxChunkSize; - TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE: + TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE: envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize); while (dataLeft > 0) { @@ -3153,10 +3120,10 @@ namespace System.Diagnostics.Tracing dataLeft -= chunkSize; dataDescrs[1].Ptr += (uint)chunkSize; envelope.ChunkNumber++; - + // For large manifests we want to not overflow any receiver's buffer. Most manifests will fit within // 5 chunks, so only the largest manifests will hit the pause. - if((envelope.ChunkNumber % 5) == 0) + if ((envelope.ChunkNumber % 5) == 0) Thread.Sleep(15); } } @@ -3201,7 +3168,7 @@ namespace System.Diagnostics.Tracing { Attribute attr = null; - Contract.Assert(data.ConstructorArguments.Count <= 1); + Debug.Assert(data.ConstructorArguments.Count <= 1); if (data.ConstructorArguments.Count == 1) { @@ -3236,7 +3203,7 @@ namespace System.Diagnostics.Tracing return null; #else // ES_BUILD_PCL && PROJECTN - throw new ArgumentException(Resources.GetResourceString("EventSource", "EventSource_PCLPlatformNotSupportedReflection")); + throw new ArgumentException(Resources.GetResourceString("EventSource", nameof(EventSource_PCLPlatformNotSupportedReflection))); #endif } @@ -3256,8 +3223,8 @@ namespace System.Diagnostics.Tracing attributeType == reflectedAttributeType || // are the full typenames equal? string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal) || - // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically - // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? + // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically + // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && attributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && (reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) @@ -3488,7 +3455,7 @@ namespace System.Diagnostics.Tracing int startEventId = eventAttribute.EventId - 1; if (eventData != null && startEventId < eventData.Length) { - Contract.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 + Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0 EventMetadata startEventMetadata = eventData[startEventId]; // If you remove the Stop and add a Start does that name match the Start Event's Name? @@ -3535,7 +3502,7 @@ namespace System.Diagnostics.Tracing { unchecked { - eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong) eventAttribute.Keywords); + eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong)eventAttribute.Keywords); } } #endif @@ -3658,7 +3625,7 @@ namespace System.Diagnostics.Tracing } #endif return; - Error: + Error: manifest.ManifestError(Resources.GetResourceString("EventSource_EnumKindMismatch", staticField.Name, staticField.FieldType.Name, providerEnumKind)); } @@ -3751,7 +3718,7 @@ namespace System.Diagnostics.Tracing // We give a task to things if they don't have one. // TODO this is moderately expensive (N*N). We probably should not even bother.... - Contract.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); + Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info); for (int idx = 0; idx < eventData.Length; ++idx) { // skip unused Event IDs. @@ -3821,7 +3788,6 @@ namespace System.Diagnostics.Tracing /// </summary> /// <param name="method">The method to probe.</param> /// <returns>The literal value or -1 if the value could not be determined. </returns> - [SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Switch statement is clearer than alternatives")] static private int GetHelperCallFirstArg(MethodInfo method) { @@ -3840,7 +3806,7 @@ namespace System.Diagnostics.Tracing (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert(); byte[] instrs = method.GetMethodBody().GetILAsByteArray(); int retVal = -1; - for (int idx = 0; idx < instrs.Length; ) + for (int idx = 0; idx < instrs.Length;) { switch (instrs[idx]) { @@ -3934,7 +3900,7 @@ namespace System.Diagnostics.Tracing goto default; break; default: - /* Contract.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + + /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] + " at " + idx + " in method " + method.Name); */ return -1; } @@ -3968,7 +3934,7 @@ namespace System.Diagnostics.Tracing { #if (!ES_BUILD_PCL && !PROJECTN) // send message to debugger without delay - System.Diagnostics.Debugger.Log(0, null, String.Format("EventSource Error: {0}{1}", msg , Environment.NewLine)); + System.Diagnostics.Debugger.Log(0, null, String.Format("EventSource Error: {0}{1}", msg, Environment.NewLine)); #endif // Send it to all listeners. @@ -4017,7 +3983,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != + Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) != ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0)); return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0; } @@ -4039,7 +4005,7 @@ namespace System.Diagnostics.Tracing #if FEATURE_ACTIVITYSAMPLING private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions) { - Contract.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0)); + Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0)); for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId) { @@ -4050,7 +4016,7 @@ namespace System.Diagnostics.Tracing if (listener == null) { EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId]; - Contract.Assert(etwSession != null); + Debug.Assert(etwSession != null); af = etwSession.m_activityFilter; } else @@ -4090,7 +4056,7 @@ namespace System.Diagnostics.Tracing private EventSourceSettings m_config; // configuration information private bool m_eventSourceDisposed; // has Dispose been called. - + // Enabling bits private bool m_eventSourceEnabled; // am I enabled (any of my events are enabled for any dispatcher) internal EventLevel m_level; // highest level enabled by any output dispatcher @@ -4229,7 +4195,7 @@ namespace System.Diagnostics.Tracing /// events for a particular eventSource to occur BEFORE the EventSourceCreatedCallback is issued. /// </summary> public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated - { + { add { CallBackForExistingEventSources(false, value); @@ -4255,7 +4221,7 @@ namespace System.Diagnostics.Tracing public EventListener() { // This will cause the OnEventSourceCreated callback to fire. - CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener(this) ); + CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener(this)); } /// <summary> @@ -4283,7 +4249,7 @@ namespace System.Diagnostics.Tracing { // Find 'this' from the s_Listeners linked list. EventListener prev = s_Listeners; - for (; ; ) + for (;;) { EventListener cur = prev.m_Next; if (cur == null) @@ -4397,7 +4363,7 @@ namespace System.Diagnostics.Tracing internal protected virtual void OnEventSourceCreated(EventSource eventSource) { EventHandler<EventSourceCreatedEventArgs> callBack = this._EventSourceCreated; - if(callBack != null) + if (callBack != null) { EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs(); args.EventSource = eventSource; @@ -4443,10 +4409,6 @@ namespace System.Diagnostics.Tracing if (!s_EventSourceShutdownRegistered) { s_EventSourceShutdownRegistered = true; -#if (!ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN) - AppDomain.CurrentDomain.ProcessExit += DisposeOnShutdown; - AppDomain.CurrentDomain.DomainUnload += DisposeOnShutdown; -#endif } @@ -4492,7 +4454,7 @@ namespace System.Diagnostics.Tracing // See bug 724140 for more private static void DisposeOnShutdown(object sender, EventArgs e) { - lock(EventListenersLock) + lock (EventListenersLock) { foreach (var esRef in s_EventSources) { @@ -4512,7 +4474,7 @@ namespace System.Diagnostics.Tracing private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // Foreach existing EventSource in the appdomain foreach (WeakReference eventSourceRef in s_EventSources) @@ -4527,12 +4489,12 @@ namespace System.Diagnostics.Tracing { // Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list. EventDispatcher prev = eventSource.m_Dispatchers; - for (; ; ) + for (;;) { EventDispatcher cur = prev.m_Next; if (cur == null) { - Contract.Assert(false, "EventSource did not have a registered EventListener!"); + Debug.Assert(false, "EventSource did not have a registered EventListener!"); break; } if (cur.m_Listener == listenerToRemove) @@ -4572,13 +4534,13 @@ namespace System.Diagnostics.Tracing EventSource eventSource = eventSourceRef.Target as EventSource; if (eventSource == null) continue; - Contract.Assert(eventSource.m_id == id, "Unexpected event source ID."); + Debug.Assert(eventSource.m_id == id, "Unexpected event source ID."); // None listeners on eventSources exist in the dispatcher list. EventDispatcher dispatcher = eventSource.m_Dispatchers; while (dispatcher != null) { - Contract.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); + Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list."); dispatcher = dispatcher.m_Next; } @@ -4586,9 +4548,9 @@ namespace System.Diagnostics.Tracing foreach (EventListener listener in allListeners.Keys) { dispatcher = eventSource.m_Dispatchers; - for (; ; ) + for (;;) { - Contract.Assert(dispatcher != null, "Listener is not on all eventSources."); + Debug.Assert(dispatcher != null, "Listener is not on all eventSources."); if (dispatcher.m_Listener == listener) break; dispatcher = dispatcher.m_Next; @@ -4818,7 +4780,6 @@ namespace System.Diagnostics.Tracing /// </summary> public Guid ActivityId { - [System.Security.SecurityCritical] get { return EventSource.CurrentThreadActivityId; } } @@ -4827,7 +4788,6 @@ namespace System.Diagnostics.Tracing /// </summary> public Guid RelatedActivityId { - [System.Security.SecurityCritical] get; internal set; } @@ -4848,7 +4808,7 @@ namespace System.Diagnostics.Tracing if (m_payloadNames == null) { // Self described events are identified by id -1. - Contract.Assert(EventId != -1); + Debug.Assert(EventId != -1); var names = new List<string>(); foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters) @@ -4893,7 +4853,7 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return m_opcode; return (EventOpcode)m_eventSource.m_eventData[EventId].Descriptor.Opcode; } @@ -4906,7 +4866,7 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return EventTask.None; return (EventTask)m_eventSource.m_eventData[EventId].Descriptor.Task; @@ -4920,20 +4880,20 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return m_tags; return m_eventSource.m_eventData[EventId].Tags; } } /// <summary> - /// Gets the message for the event. + /// Gets the message for the event. If the message has {N} parameters they are NOT substituted. /// </summary> public string Message { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return m_message; else return m_eventSource.m_eventData[EventId].Message; @@ -4953,7 +4913,7 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return EventChannel.None; return (EventChannel)m_eventSource.m_eventData[EventId].Descriptor.Channel; } @@ -4967,7 +4927,7 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return 0; return m_eventSource.m_eventData[EventId].Descriptor.Version; } @@ -4980,7 +4940,7 @@ namespace System.Diagnostics.Tracing { get { - if (EventId < 0) // TraceLogging convention EventID == -1 + if (EventId <= 0) // TraceLogging convention EventID == -1 return m_level; return (EventLevel)m_eventSource.m_eventData[EventId].Descriptor.Level; } @@ -5277,7 +5237,7 @@ namespace System.Diagnostics.Tracing public static void DisableFilter(ref ActivityFilter filterList, EventSource source) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif if (filterList == null) @@ -5345,7 +5305,7 @@ namespace System.Diagnostics.Tracing string startEvents) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // first remove all filters associated with 'source' @@ -5432,7 +5392,6 @@ namespace System.Diagnostics.Tracing /// If 'childActivityID' is present, it will be added to the active set if the /// current activity is active. /// </summary> - [SecurityCritical] unsafe public static bool PassesActivityFilter( ActivityFilter filterList, Guid* childActivityID, @@ -5440,7 +5399,7 @@ namespace System.Diagnostics.Tracing EventSource source, int eventId) { - Contract.Assert(filterList != null && filterList.m_activeActivities != null); + Debug.Assert(filterList != null && filterList.m_activeActivities != null); bool shouldBeLogged = false; if (triggeringEvent) { @@ -5513,7 +5472,6 @@ namespace System.Diagnostics.Tracing return shouldBeLogged; } - [System.Security.SecuritySafeCritical] public static bool IsCurrentActivityActive(ActivityFilter filterList) { var activeActivities = GetActiveActivities(filterList); @@ -5530,13 +5488,12 @@ namespace System.Diagnostics.Tracing /// value for 'currentActivityid' is an indication tha caller has already verified /// that the current activity is active. /// </summary> - [SecurityCritical] unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID) { - Contract.Assert(childActivityID != null); + Debug.Assert(childActivityID != null); var activeActivities = GetActiveActivities(filterList); - Contract.Assert(activeActivities != null); + Debug.Assert(activeActivities != null); // take currentActivityId == null to mean we *know* the current activity is "active" if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId)) @@ -5593,7 +5550,7 @@ namespace System.Diagnostics.Tracing public void Dispose() { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif // m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying). // Therefore we are ok to take a dependency on m_myActivityDelegate being valid even @@ -5620,7 +5577,7 @@ namespace System.Diagnostics.Tracing m_samplingFreq = samplingFreq; m_next = existingFilter; - Contract.Assert(existingFilter == null || + Debug.Assert(existingFilter == null || (existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null)); // if this is the first filter we add for this session, we need to create a new @@ -5694,10 +5651,10 @@ namespace System.Diagnostics.Tracing private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq) { #if !ES_BUILD_STANDALONE - Contract.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); + Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock)); #endif - Contract.Assert(samplingFreq > 0); - Contract.Assert(eventId >= 0); + Debug.Assert(samplingFreq > 0); + Debug.Assert(eventId >= 0); filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList); @@ -5828,7 +5785,7 @@ namespace System.Diagnostics.Tracing public static void RemoveEtwSession(EtwSession etwSession) { - Contract.Assert(etwSession != null); + Debug.Assert(etwSession != null); if (s_etwSessions == null || etwSession == null) return; @@ -5909,7 +5866,7 @@ namespace System.Diagnostics.Tracing public static SessionMask FromId(int perEventSourceSessionId) { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); return new SessionMask((uint)1 << perEventSourceSessionId); } @@ -5927,12 +5884,12 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); return (m_mask & (1 << perEventSourceSessionId)) != 0; } set { - Contract.Assert(perEventSourceSessionId < MAX); + Debug.Assert(perEventSourceSessionId < MAX); if (value) m_mask |= ((uint)1 << perEventSourceSessionId); else m_mask &= ~((uint)1 << perEventSourceSessionId); } @@ -6163,7 +6120,7 @@ namespace System.Diagnostics.Tracing private EventChannelType EventChannelToChannelType(EventChannel channel) { #if !ES_BUILD_STANDALONE - Contract.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); + Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug); #endif return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin); } @@ -6206,8 +6163,8 @@ namespace System.Diagnostics.Tracing #endif public void StartEvent(string eventName, EventAttribute eventAttribute) { - Contract.Assert(numParams == 0); - Contract.Assert(this.eventName == null); + Debug.Assert(numParams == 0); + Debug.Assert(this.eventName == null); this.eventName = eventName; numParams = 0; byteArrArgIndices = null; @@ -6311,7 +6268,7 @@ namespace System.Diagnostics.Tracing // otherwise we allocate a channel bit for the channel. // explicit channel bits are only used by WCF to mimic an existing manifest, // so we don't dont do error checking. - public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword=0) + public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword = 0) { // strip off any non-channel keywords, since we are only interested in channels here. channelKeyword &= ValidPredefinedChannelKeywords; @@ -6560,7 +6517,7 @@ namespace System.Diagnostics.Tracing // very early in the app domain creation, when _FusionStore is not set up yet, resulting in a failure to run the static constructory // for BinaryCompatibility. This failure is then cached and a TypeInitializationException is thrown every time some code attampts to // access BinaryCompatibility. - ArraySortHelper<string>.IntrospectiveSort(sortedStrings, 0, sortedStrings.Length, Comparer<string>.Default); + ArraySortHelper<string>.IntrospectiveSort(sortedStrings, 0, sortedStrings.Length, string.Compare); #endif foreach (var ci in cultures) { @@ -6642,13 +6599,7 @@ namespace System.Diagnostics.Tracing private static List<CultureInfo> GetSupportedCultures(ResourceManager resources) { var cultures = new List<CultureInfo>(); -#if !ES_BUILD_PCL && !FEATURE_CORECLR && !PROJECTN - foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.SpecificCultures /*| CultureTypes.NeutralCultures*/)) - { - if (resources.GetResourceSet(ci, true, false) != null) - cultures.Add(ci); - } -#endif // !ES_BUILD_PCL && !FEATURE_CORECLR + if (!cultures.Contains(CultureInfo.CurrentUICulture)) cultures.Insert(0, CultureInfo.CurrentUICulture); return cultures; @@ -6701,7 +6652,7 @@ namespace System.Diagnostics.Tracing ret = taskTab[(int)task] = eventName; return ret; } - + private string GetOpcodeName(EventOpcode opcode, string eventName) { switch (opcode) @@ -6738,12 +6689,12 @@ namespace System.Diagnostics.Tracing } return ret; } - + private string GetKeywords(ulong keywords, string eventName) { // ignore keywords associate with channels // See ValidPredefinedChannelKeywords def for more. - keywords &= ~ValidPredefinedChannelKeywords; + keywords &= ~ValidPredefinedChannelKeywords; string ret = ""; for (ulong bit = 1; bit != 0; bit <<= 1) @@ -6770,7 +6721,7 @@ namespace System.Diagnostics.Tracing } return ret; } - + private string GetTypeName(Type type) { if (type.IsEnum()) @@ -6779,7 +6730,7 @@ namespace System.Diagnostics.Tracing var typeName = GetTypeName(fields[0].FieldType); return typeName.Replace("win:Int", "win:UInt"); // ETW requires enums to be unsigned. } - + return GetTypeNameHelper(type); } @@ -6797,7 +6748,7 @@ namespace System.Diagnostics.Tracing StringBuilder stringBuilder = null; // We lazily create this int writtenSoFar = 0; int chIdx = -1; - for (int i = 0; ; ) + for (int i = 0; ;) { if (i >= eventMessage.Length) { diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs index 00bd0b7caa..0a689efe92 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs @@ -29,7 +29,6 @@ namespace System.Diagnostics.Tracing /// </summary> /// <param name="activityId">A Guid that represents the new activity with which to mark /// the current thread</param> - [System.Security.SecuritySafeCritical] public static void SetCurrentThreadActivityId(Guid activityId) { if (TplEtwProvider.Log != null) @@ -80,7 +79,6 @@ namespace System.Diagnostics.Tracing /// the current thread</param> /// <param name="oldActivityThatWillContinue">The Guid that represents the current activity /// which will continue at some point in the future, on the current thread</param> - [System.Security.SecuritySafeCritical] public static void SetCurrentThreadActivityId(Guid activityId, out Guid oldActivityThatWillContinue) { oldActivityThatWillContinue = activityId; @@ -104,7 +102,6 @@ namespace System.Diagnostics.Tracing /// </summary> public static Guid CurrentThreadActivityId { - [System.Security.SecuritySafeCritical] get { // We ignore errors to keep with the convention that EventSources do not throw @@ -186,7 +183,6 @@ namespace System.Diagnostics.Tracing internal partial class EventProvider { - [System.Security.SecurityCritical] internal unsafe int SetInformation( UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass, IntPtr data, diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs index d0d687e8d8..079d7f480b 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs @@ -22,7 +22,6 @@ namespace System.Diagnostics.Tracing /// EventWrite. The instance must be Disabled before the arrays referenced /// by the pointers are freed or unpinned. /// </summary> - [SecurityCritical] internal unsafe struct DataCollector { [ThreadStatic] diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs index be97447301..5967ad6ab5 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Collections; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -26,7 +27,7 @@ namespace System.Diagnostics.Tracing { internal EventPayload(List<string> payloadNames, List<object> payloadValues) { - Contract.Assert(payloadNames.Count == payloadValues.Count); + Debug.Assert(payloadNames.Count == payloadValues.Count); m_names = payloadNames; m_values = payloadValues; @@ -40,7 +41,7 @@ namespace System.Diagnostics.Tracing get { if (key == null) - throw new System.ArgumentNullException("key"); + throw new System.ArgumentNullException(nameof(key)); int position = 0; foreach(var name in m_names) @@ -83,7 +84,7 @@ namespace System.Diagnostics.Tracing public bool ContainsKey(string key) { if (key == null) - throw new System.ArgumentNullException("key"); + throw new System.ArgumentNullException(nameof(key)); foreach (var item in m_names) { @@ -129,7 +130,7 @@ namespace System.Diagnostics.Tracing public bool TryGetValue(string key, out object value) { if (key == null) - throw new System.ArgumentNullException("key"); + throw new System.ArgumentNullException(nameof(key)); int position = 0; foreach (var name in m_names) diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs index fccfd48721..38c1767462 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs @@ -35,7 +35,7 @@ namespace System.Diagnostics.Tracing public EventSourceActivity(EventSource eventSource) { if (eventSource == null) - throw new ArgumentNullException("eventSource"); + throw new ArgumentNullException(nameof(eventSource)); Contract.EndContractBlock(); this.eventSource = eventSource; diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs index 45673f7ab5..309226b84d 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs @@ -108,7 +108,7 @@ namespace System.Diagnostics.Tracing if (name == null) { throw new ArgumentNullException( - "name", + nameof(name), "This usually means that the object passed to Write is of a type that" + " does not support being used as the top-level object in an event," + " e.g. a primitive or built-in type."); diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs index 0f34d95648..3ea781252f 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs @@ -1,5 +1,6 @@ using System.Reflection; using System.Runtime.InteropServices; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -132,7 +133,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); + Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); return _reference; } } @@ -141,7 +142,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); + Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalar; } } @@ -150,7 +151,7 @@ namespace System.Diagnostics.Tracing { get { - Contract.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); + Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalarLength; } } diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs index e51aff0380..901a0ed1a2 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; @@ -269,7 +270,7 @@ namespace System.Diagnostics.Tracing : base(type) { var typeArgs = type.GenericTypeArguments; - Contract.Assert(typeArgs.Length == 1); + Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue")); this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs index fa0f79f58f..516c8ba19a 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs @@ -175,7 +175,7 @@ namespace System.Diagnostics.Tracing { if (name != null && 0 <= name.IndexOf('\0')) { - throw new ArgumentOutOfRangeException("name"); + throw new ArgumentOutOfRangeException(nameof(name)); } } diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs index 4b6e633487..04a047fb35 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs @@ -21,7 +21,6 @@ namespace System.Diagnostics.Tracing /// full-trust code, this abstraction is unnecessary (though it probably /// doesn't hurt anything). /// </summary> - [SecuritySafeCritical] internal unsafe class TraceLoggingDataCollector { internal static readonly TraceLoggingDataCollector Instance = new TraceLoggingDataCollector(); diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs index 963c492419..07a56751ea 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs @@ -100,7 +100,7 @@ namespace System.Diagnostics.Tracing { if (eventSourceName == null) { - throw new ArgumentNullException("eventSourceName"); + throw new ArgumentNullException(nameof(eventSourceName)); } Contract.EndContractBlock(); } @@ -110,12 +110,11 @@ namespace System.Diagnostics.Tracing /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> - [SecuritySafeCritical] public unsafe void Write(string eventName) { if (eventName == null) { - throw new ArgumentNullException("eventName"); + throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); @@ -138,12 +137,11 @@ namespace System.Diagnostics.Tracing /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> - [SecuritySafeCritical] public unsafe void Write(string eventName, EventSourceOptions options) { if (eventName == null) { - throw new ArgumentNullException("eventName"); + throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); @@ -175,7 +173,6 @@ namespace System.Diagnostics.Tracing /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> - [SecuritySafeCritical] public unsafe void Write<T>( string eventName, T data) @@ -212,7 +209,6 @@ namespace System.Diagnostics.Tracing /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> - [SecuritySafeCritical] public unsafe void Write<T>( string eventName, EventSourceOptions options, @@ -251,7 +247,6 @@ namespace System.Diagnostics.Tracing /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> - [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, @@ -297,7 +292,6 @@ namespace System.Diagnostics.Tracing /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> - [SecuritySafeCritical] public unsafe void Write<T>( string eventName, ref EventSourceOptions options, @@ -354,7 +348,6 @@ namespace System.Diagnostics.Tracing /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> - [SecuritySafeCritical] private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, @@ -415,7 +408,6 @@ namespace System.Diagnostics.Tracing /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> - [SecuritySafeCritical] private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, @@ -526,7 +518,6 @@ namespace System.Diagnostics.Tracing /// The number and types of the values must match the number and types of the /// fields described by the eventTypes parameter. /// </param> - [SecuritySafeCritical] internal unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, @@ -604,7 +595,6 @@ namespace System.Diagnostics.Tracing #endif // FEATURE_MANAGED_ETW } - [SecuritySafeCritical] private unsafe void WriteImpl( string eventName, ref EventSourceOptions options, @@ -721,7 +711,6 @@ namespace System.Diagnostics.Tracing } } - [SecurityCritical] private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); @@ -750,7 +739,6 @@ namespace System.Diagnostics.Tracing System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] #endif - [SecurityCritical] [NonEvent] private unsafe void WriteCleanup(GCHandle* pPins, int cPins) { diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs index 4e33e58a82..c2239671bb 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs @@ -94,7 +94,7 @@ namespace System.Diagnostics.Tracing { if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); @@ -132,7 +132,7 @@ namespace System.Diagnostics.Tracing { if (defaultName == null) { - throw new ArgumentNullException("defaultName"); + throw new ArgumentNullException(nameof(defaultName)); } Contract.EndContractBlock(); @@ -212,7 +212,7 @@ namespace System.Diagnostics.Tracing { if (paramInfos == null) { - throw new ArgumentNullException("paramInfos"); + throw new ArgumentNullException(nameof(paramInfos)); } Contract.EndContractBlock(); @@ -231,7 +231,7 @@ namespace System.Diagnostics.Tracing { if (types == null) { - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); } Contract.EndContractBlock(); @@ -251,7 +251,7 @@ namespace System.Diagnostics.Tracing { if (typeInfos == null) { - throw new ArgumentNullException("typeInfos"); + throw new ArgumentNullException(nameof(typeInfos)); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs index 0467ec43e5..41225c8626 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs @@ -156,7 +156,7 @@ namespace System.Diagnostics.Tracing size = 16; break; default: - throw new ArgumentOutOfRangeException("type"); + throw new ArgumentOutOfRangeException(nameof(type)); } this.impl.AddScalar(size); @@ -183,7 +183,7 @@ namespace System.Diagnostics.Tracing case TraceLoggingDataType.CountedUtf16String: break; default: - throw new ArgumentOutOfRangeException("type"); + throw new ArgumentOutOfRangeException(nameof(type)); } this.impl.AddScalar(2); @@ -227,7 +227,7 @@ namespace System.Diagnostics.Tracing case TraceLoggingDataType.Char8: break; default: - throw new ArgumentOutOfRangeException("type"); + throw new ArgumentOutOfRangeException(nameof(type)); } if (this.BeginningBufferedArray) diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs index 5815d12fb0..0cc17e02f3 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs @@ -36,7 +36,7 @@ namespace System.Diagnostics.Tracing { if (dataType == null) { - throw new ArgumentNullException("dataType"); + throw new ArgumentNullException(nameof(dataType)); } Contract.EndContractBlock(); @@ -56,7 +56,7 @@ namespace System.Diagnostics.Tracing { if (dataType == null) { - throw new ArgumentNullException("dataType"); + throw new ArgumentNullException(nameof(dataType)); } if (name == null) diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs index d7112fc81b..c96d2129f0 100644 --- a/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs +++ b/src/mscorlib/src/System/Diagnostics/Eventing/XplatEventLogger.cs @@ -73,9 +73,8 @@ namespace System.Diagnostics.Tracing } } - private static string Serialize(ReadOnlyCollection<string> payloadName, ReadOnlyCollection<object> payload, string sep = ", ") + private static string Serialize(ReadOnlyCollection<string> payloadName, ReadOnlyCollection<object> payload, string eventMessage) { - if (payloadName == null || payload == null ) return String.Empty; @@ -92,8 +91,22 @@ namespace System.Diagnostics.Tracing var sb = StringBuilderCache.Acquire(); sb.Append('{'); + + // If the event has a message, send that as well as a pseudo-field + if (!string.IsNullOrEmpty(eventMessage)) + { + sb.Append("\\\"EventSource_Message\\\":\\\""); + minimalJsonserializer(eventMessage,sb); + sb.Append("\\\""); + if (eventDataCount != 0) + sb.Append(", "); + } + for (int i = 0; i < eventDataCount; i++) { + if (i != 0) + sb.Append(", "); + var fieldstr = payloadName[i].ToString(); sb.Append("\\\""); @@ -114,14 +127,9 @@ namespace System.Diagnostics.Tracing sb.Append(payload[i].ToString()); } - sb.Append(sep); - } - - sb.Length -= sep.Length; - sb.Append('}'); - - return StringBuilderCache.GetStringAndRelease(sb); + sb.Append('}'); + return StringBuilderCache.GetStringAndRelease(sb); } internal protected override void OnEventSourceCreated(EventSource eventSource) @@ -149,7 +157,7 @@ namespace System.Diagnostics.Tracing if (eventData.Payload != null) { try{ - payload = Serialize(eventData.PayloadNames, eventData.Payload); + payload = Serialize(eventData.PayloadNames, eventData.Payload, eventData.Message); } catch (Exception ex) { |