Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,37 @@
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.Runtime.Diagnostics
{
/// <summary>
/// enum ActivityControl
/// </summary>
internal enum ActivityControl : uint
{
/// <summary>
/// Get the activity Id from the thread
/// </summary>
EVENT_ACTIVITY_CTRL_GET_ID = 1,
/// <summary>
/// Set the activity Id to the thread
/// </summary>
EVENT_ACTIVITY_CTRL_SET_ID = 2,
/// <summary>
/// Create the activity Id
/// </summary>
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
/// <summary>
/// Get the activity Id from the thread and set it
/// </summary>
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
/// <summary>
/// Create an activity Id and set it to the thread
/// </summary>
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
}
}

View File

@@ -0,0 +1,44 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System;
using System.Diagnostics;
class DiagnosticTraceSource : TraceSource
{
const string PropagateActivityValue = "propagateActivity";
internal DiagnosticTraceSource(string name)
: base(name)
{
}
protected override string[] GetSupportedAttributes()
{
return new string[] { DiagnosticTraceSource.PropagateActivityValue };
}
internal bool PropagateActivity
{
get
{
bool retval = false;
string attributeValue = this.Attributes[DiagnosticTraceSource.PropagateActivityValue];
if (!string.IsNullOrEmpty(attributeValue))
{
if (!bool.TryParse(attributeValue, out retval))
{
retval = false;
}
}
return retval;
}
set
{
this.Attributes[DiagnosticTraceSource.PropagateActivityValue] = value.ToString();
}
}
}
}

View File

@@ -0,0 +1,33 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System.Xml;
using System.Collections;
class DictionaryTraceRecord : TraceRecord
{
IDictionary dictionary;
internal DictionaryTraceRecord(IDictionary dictionary)
{
this.dictionary = dictionary;
}
internal override string EventId { get { return TraceRecord.EventIdBase + "Dictionary" + TraceRecord.NamespaceSuffix; } }
internal override void WriteTo(XmlWriter xml)
{
if (this.dictionary != null)
{
foreach (object key in this.dictionary.Keys)
{
object value = this.dictionary[key];
xml.WriteElementString(key.ToString(), value == null ? string.Empty : value.ToString());
}
}
}
}
}

View File

@@ -0,0 +1,163 @@
namespace System.Runtime.Diagnostics
{
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[StructLayout(LayoutKind.Explicit, Size = 16)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
internal struct EventDescriptor
{
[FieldOffset(0)]
private ushort m_id;
[FieldOffset(2)]
private byte m_version;
[FieldOffset(3)]
private byte m_channel;
[FieldOffset(4)]
private byte m_level;
[FieldOffset(5)]
private byte m_opcode;
[FieldOffset(6)]
private ushort m_task;
[FieldOffset(8)]
private long m_keywords;
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly",
MessageId = "opcode", Justification = "This is to align with the definition in System.Core.dll")]
public EventDescriptor(
int id,
byte version,
byte channel,
byte level,
byte opcode,
int task,
long keywords
)
{
if (id < 0)
{
throw Fx.Exception.ArgumentOutOfRange("id", id, InternalSR.ValueMustBeNonNegative);
}
if (id > ushort.MaxValue)
{
throw Fx.Exception.ArgumentOutOfRange("id", id, string.Empty);
}
m_id = (ushort)id;
m_version = version;
m_channel = channel;
m_level = level;
m_opcode = opcode;
m_keywords = keywords;
if (task < 0)
{
throw Fx.Exception.ArgumentOutOfRange("task", task, InternalSR.ValueMustBeNonNegative);
}
if (task > ushort.MaxValue)
{
throw Fx.Exception.ArgumentOutOfRange("task", task, string.Empty);
}
m_task = (ushort)task;
}
public int EventId
{
get
{
return m_id;
}
}
public byte Version
{
get
{
return m_version;
}
}
public byte Channel
{
get
{
return m_channel;
}
}
public byte Level
{
get
{
return m_level;
}
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly",
MessageId = "Opcode", Justification = "This is to align with the definition in System.Core.dll")]
public byte Opcode
{
get
{
return m_opcode;
}
}
public int Task
{
get
{
return m_task;
}
}
public long Keywords
{
get
{
return m_keywords;
}
}
public override bool Equals(object obj)
{
if (!(obj is EventDescriptor))
return false;
return Equals((EventDescriptor)obj);
}
public override int GetHashCode()
{
return m_id ^ m_version ^ m_channel ^ m_level ^ m_opcode ^ m_task ^ (int)m_keywords;
}
public bool Equals(EventDescriptor other)
{
if ((m_id != other.m_id) ||
(m_version != other.m_version) ||
(m_channel != other.m_channel) ||
(m_level != other.m_level) ||
(m_opcode != other.m_opcode) ||
(m_task != other.m_task) ||
(m_keywords != other.m_keywords))
{
return false;
}
return true;
}
public static bool operator ==(EventDescriptor event1, EventDescriptor event2)
{
return event1.Equals(event2);
}
public static bool operator !=(EventDescriptor event1, EventDescriptor event2)
{
return !event1.Equals(event2);
}
}
}

View File

@@ -0,0 +1,26 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
// Order is important here. The order must match the order of strings in src\ndp\cdf\src\WCF\EventLog\EventLog.mc
enum EventLogCategory : ushort
{
ServiceAuthorization = 1, // reserved
MessageAuthentication, // reserved
ObjectAccess, // reserved
Tracing,
WebHost,
FailFast,
MessageLogging,
PerformanceCounter,
Wmi,
ComPlus,
StateMachine,
Wsat,
SharingService,
ListenerAdapter
}
}

View File

@@ -0,0 +1,138 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
// When adding an EventLogEventId, an entry must also be added to src\ndp\cdf\src\WCF\EventLog\EventLog.mc.
// The hexadecimal representation of each EventId ('0xabbbcccc') can be broken down into 3 parts:
// Hex digit 1 ('a') : Severity : a=0 for Success, a=4 for Informational, a=8 for Warning, a=c for Error
// Hex digits 2-4 ('bbb') : Facility : bbb=001 for Tracing, bbb=002 for ServiceModel, bbb=003 for TransactionBridge, bbb=004 for SMSvcHost, bbb=005 for Info_Cards, bbb=006 for Security_Audit
// Hex digits 5-8 ('cccc') : Code : Each event within the same facility is assigned a unique "code".
// The EventId generated from EventLog.mc must match the EventId assigned here.
// Order is important: The order here must match the order of strings in src\ndp\cdf\src\WCF\EventLog\EventLog.mc so that the 'code' portions of the EventId's match.
// The "code" portions of the EventId's are generated by EventLog.mc as follows:
// - The first event for a given facility is assigned the code "0x0001".
// - Each subsequent event within this facility, regardless of severity, is assigned the value of the previous event incremented by 1.
// Thus, if you add an EventLogEventId below, you must ensure that its code is equal to the code of the previous EventLogEventId in its facility incremented by 1.
// The Severity and Facility assigned in EventLog.mc must match those assigned via the EventId here.
// If the EventId's do not match, the EventViewer will not be able to display the strings defined in EventLog.mc correctly. In this case, the following error message will be included in the logged event:
// "The description for Event ID XX from source System.ServiceModel 4.0.0.0 cannot be found..."
// To inspect the value ----igend to the enum elements below, build 'ndp\cdf\src\System.ServiceModel.Internals', and inspect System.ServiceModel.Internals\System.ServiceModel.Internals.asmmeta
// To inspect the EventId generated from EventLog.mc, build 'ndp\cdf\src\WCF\EventLog', and open ServiceModelEvents.dll.mui with \\indigofs\PrivateLabDebugShare\sarada\RPFRecorder\RPFRecorder.exe (convert EventId from decimal to hex).
// You could also use any other method of viewing ServiceModelEvents.dll.mui which would allow you to inspect the EventId
enum EventLogEventId : uint
{
// EventIDs from shared Diagnostics and Reliability code
// All EventId's beneath 'FailedToSetupTracing', until the next explicitly assigned one, inherit its severity and facility, via the enum's auto-incrememt
FailedToSetupTracing = EventSeverity.Error | EventFacility.Tracing | 0x0064,
FailedToInitializeTraceSource,
FailFast,
FailFastException,
FailedToTraceEvent,
FailedToTraceEventWithException,
InvariantAssertionFailed,
PiiLoggingOn,
PiiLoggingNotAllowed,
// ServiceModel EventIDs
// All EventId's beneath 'WebHostUnhandledException', until the next explicitly assigned one, inherit its severity and facility, via the enum's auto-incrememt
WebHostUnhandledException = EventSeverity.Error | EventFacility.ServiceModel | 0x0001,
WebHostHttpError,
WebHostFailedToProcessRequest,
WebHostFailedToListen,
FailedToLogMessage,
RemovedBadFilter,
FailedToCreateMessageLoggingTraceSource,
MessageLoggingOn,
MessageLoggingOff,
FailedToLoadPerformanceCounter,
FailedToRemovePerformanceCounter,
WmiGetObjectFailed,
WmiPutInstanceFailed,
WmiDeleteInstanceFailed,
WmiCreateInstanceFailed,
WmiExecQueryFailed,
WmiExecMethodFailed,
WmiRegistrationFailed,
WmiUnregistrationFailed,
WmiAdminTypeMismatch,
WmiPropertyMissing,
ComPlusServiceHostStartingServiceError,
ComPlusDllHostInitializerStartingError,
ComPlusTLBImportError,
ComPlusInvokingMethodFailed,
ComPlusInstanceCreationError,
ComPlusInvokingMethodFailedMismatchedTransactions,
// Assigning code 0x001c to this EventId because it is the 28th (0x001c) EventId with Facility = ServiceModel.
WebHostNotLoggingInsufficientMemoryExceptionsOnActivationForNextTimeInterval = EventSeverity.Warning | EventFacility.ServiceModel | 0x001c,
// TransactionBridge
// All EventId's beneath 'UnhandledStateMachineExceptionRecordDescription', until the next explicitly assigned one, inherit its severity and facility, via the enum's auto-incrememt
UnhandledStateMachineExceptionRecordDescription = EventSeverity.Error | EventFacility.TransactionBridge | 0x0001,
FatalUnexpectedStateMachineEvent,
ParticipantRecoveryLogEntryCorrupt,
CoordinatorRecoveryLogEntryCorrupt,
CoordinatorRecoveryLogEntryCreationFailure,
ParticipantRecoveryLogEntryCreationFailure,
ProtocolInitializationFailure,
ProtocolStartFailure,
ProtocolRecoveryBeginningFailure,
ProtocolRecoveryCompleteFailure,
TransactionBridgeRecoveryFailure,
ProtocolStopFailure,
NonFatalUnexpectedStateMachineEvent,
PerformanceCounterInitializationFailure,
ProtocolRecoveryComplete,
ProtocolStopped,
ThumbPrintNotFound,
ThumbPrintNotValidated,
SslNoPrivateKey,
SslNoAccessiblePrivateKey,
MissingNecessaryKeyUsage,
MissingNecessaryEnhancedKeyUsage,
// SMSvcHost
// All EventId's beneath 'StartErrorPublish', until the next explicitly assigned one, inherit its severity and facility, via the enum's auto-incrememt
StartErrorPublish = EventSeverity.Error | EventFacility.SMSvcHost | 0x0001,
BindingError,
LAFailedToListenForApp,
UnknownListenerAdapterError,
WasDisconnected,
WasConnectionTimedout,
ServiceStartFailed,
MessageQueueDuplicatedSocketLeak,
MessageQueueDuplicatedPipeLeak,
SharingUnhandledException,
// SecurityAudit
ServiceAuthorizationSuccess = EventSeverity.Informational | EventFacility.SecurityAudit | 0x0001,
ServiceAuthorizationFailure = EventSeverity.Error | EventFacility.SecurityAudit | 0x0002,
MessageAuthenticationSuccess = EventSeverity.Informational | EventFacility.SecurityAudit | 0x0003,
MessageAuthenticationFailure = EventSeverity.Error | EventFacility.SecurityAudit | 0x0004,
SecurityNegotiationSuccess = EventSeverity.Informational | EventFacility.SecurityAudit | 0x0005,
SecurityNegotiationFailure = EventSeverity.Error | EventFacility.SecurityAudit | 0x0006,
TransportAuthenticationSuccess = EventSeverity.Informational | EventFacility.SecurityAudit | 0x0007,
TransportAuthenticationFailure = EventSeverity.Error | EventFacility.SecurityAudit | 0x0008,
ImpersonationSuccess = EventSeverity.Informational | EventFacility.SecurityAudit | 0x0009,
ImpersonationFailure = EventSeverity.Error | EventFacility.SecurityAudit | 0x000a
}
enum EventSeverity : uint
{
Success = 0x00000000,
Informational = 0x40000000,
Warning = 0x80000000,
Error = 0xc0000000
}
enum EventFacility : uint
{
Tracing = 0x00010000,
ServiceModel = 0x00020000,
TransactionBridge = 0x00030000,
SMSvcHost = 0x00040000,
InfoCards = 0x00050000,
SecurityAudit = 0x00060000
}
}

View File

@@ -0,0 +1,408 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Interop;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Diagnostics.CodeAnalysis;
sealed class EventLogger
{
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - In PT log no more than 5 events.")]
const int MaxEventLogsInPT = 5;
[SecurityCritical]
static int logCountForPT;
static bool canLogEvent = true;
DiagnosticTraceBase diagnosticTrace;
[Fx.Tag.SecurityNote(Critical = "Protect the string that defines the event source name.",
Safe = "It demands UnmanagedCode=true so PT cannot call.")]
[SecurityCritical]
string eventLogSourceName;
bool isInPartialTrust;
EventLogger()
{
this.isInPartialTrust = IsInPartialTrust();
}
[Obsolete("For System.Runtime.dll use only. Call FxTrace.EventLog instead")]
public EventLogger(string eventLogSourceName, DiagnosticTraceBase diagnosticTrace)
{
try
{
this.diagnosticTrace = diagnosticTrace;
//set diagnostics trace prior to calling SafeSetLogSourceName
if (canLogEvent)
{
SafeSetLogSourceName(eventLogSourceName);
}
}
catch (SecurityException)
{
// running in PT, do not try to log events anymore
canLogEvent = false;
// not throwing exception on purpose
}
}
[Fx.Tag.SecurityNote(Critical = "Unsafe method to create event logger (sets the event source name).")]
[SecurityCritical]
public static EventLogger UnsafeCreateEventLogger(string eventLogSourceName, DiagnosticTraceBase diagnosticTrace)
{
EventLogger logger = new EventLogger();
logger.SetLogSourceName(eventLogSourceName, diagnosticTrace);
return logger;
}
[Fx.Tag.SecurityNote(Critical = "Logs event to the event log and asserts Unmanaged code.")]
[SecurityCritical]
public void UnsafeLogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, params string[] values)
{
if (logCountForPT < MaxEventLogsInPT)
{
try
{
// Vista introduces a new limitation: a much smaller max
// event log entry size that we need to track. All strings cannot
// exceed 31839 characters in length when totalled together.
// Choose a max length of 25600 characters (25k) to allow for
// buffer since this max length may be reduced without warning.
const int MaxEventLogEntryLength = 25600;
int eventLogEntryLength = 0;
string[] logValues = new string[values.Length + 2];
for (int i = 0; i < values.Length; ++i)
{
string stringValue = values[i];
if (!string.IsNullOrEmpty(stringValue))
{
stringValue = NormalizeEventLogParameter(stringValue);
}
else
{
stringValue = String.Empty;
}
logValues[i] = stringValue;
eventLogEntryLength += stringValue.Length + 1;
}
string normalizedProcessName = NormalizeEventLogParameter(UnsafeGetProcessName());
logValues[logValues.Length - 2] = normalizedProcessName;
eventLogEntryLength += (normalizedProcessName.Length + 1);
string invariantProcessId = UnsafeGetProcessId().ToString(CultureInfo.InvariantCulture);
logValues[logValues.Length - 1] = invariantProcessId;
eventLogEntryLength += (invariantProcessId.Length + 1);
// If current event log entry length is greater than max length
// need to truncate to max length. This probably means that we
// have a very long exception and stack trace in our parameter
// strings. Truncate each string by MaxEventLogEntryLength
// divided by number of strings in the entry.
// Truncation algorithm is overly aggressive by design to
// simplify the code change due to Product Cycle timing.
if (eventLogEntryLength > MaxEventLogEntryLength)
{
// logValues.Length is always > 0 (minimum value = 2)
// Subtract one to insure string ends in '\0'
int truncationLength = (MaxEventLogEntryLength / logValues.Length) - 1;
for (int i = 0; i < logValues.Length; i++)
{
if (logValues[i].Length > truncationLength)
{
logValues[i] = logValues[i].Substring(0, truncationLength);
}
}
}
SecurityIdentifier sid = WindowsIdentity.GetCurrent().User;
byte[] sidBA = new byte[sid.BinaryLength];
sid.GetBinaryForm(sidBA, 0);
IntPtr[] stringRoots = new IntPtr[logValues.Length];
GCHandle stringsRootHandle = new GCHandle();
GCHandle[] stringHandles = null;
try
{
stringsRootHandle = GCHandle.Alloc(stringRoots, GCHandleType.Pinned);
stringHandles = new GCHandle[logValues.Length];
for (int strIndex = 0; strIndex < logValues.Length; strIndex++)
{
stringHandles[strIndex] = GCHandle.Alloc(logValues[strIndex], GCHandleType.Pinned);
stringRoots[strIndex] = stringHandles[strIndex].AddrOfPinnedObject();
}
UnsafeWriteEventLog(type, eventLogCategory, eventId, logValues, sidBA, stringsRootHandle);
}
finally
{
if (stringsRootHandle.AddrOfPinnedObject() != IntPtr.Zero)
{
stringsRootHandle.Free();
}
if (stringHandles != null)
{
foreach (GCHandle gcHandle in stringHandles)
{
if (gcHandle != null)
{
gcHandle.Free();
}
}
}
}
if (shouldTrace && this.diagnosticTrace != null && this.diagnosticTrace.IsEnabled())
{
const int RequiredValueCount = 4;
Dictionary<string, string> eventValues = new Dictionary<string, string>(logValues.Length + RequiredValueCount);
eventValues["CategoryID.Name"] = "EventLogCategory";
eventValues["CategoryID.Value"] = eventLogCategory.ToString(CultureInfo.InvariantCulture);
eventValues["InstanceID.Name"] = "EventId";
eventValues["InstanceID.Value"] = eventId.ToString(CultureInfo.InvariantCulture);
for (int i = 0; i < values.Length; ++i)
{
eventValues.Add("Value" + i.ToString(CultureInfo.InvariantCulture), values[i] == null ? string.Empty : DiagnosticTraceBase.XmlEncode(values[i]));
}
this.diagnosticTrace.TraceEventLogEvent(type, new DictionaryTraceRecord((eventValues)));
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// If not fatal, just eat the exception
}
// In PT, we only limit 5 event logging per session
if (this.isInPartialTrust)
{
logCountForPT++;
}
}
}
public void LogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, params string[] values)
{
if (canLogEvent)
{
try
{
SafeLogEvent(type, eventLogCategory, eventId, shouldTrace, values);
}
catch (SecurityException ex)
{
// running in PT, do not try to log events anymore
canLogEvent = false;
// not throwing exception on purpose
if (shouldTrace)
{
Fx.Exception.TraceHandledException(ex, TraceEventType.Information);
}
}
}
}
public void LogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, params string[] values)
{
this.LogEvent(type, eventLogCategory, eventId, true, values);
}
// Converts incompatible serverity enumeration TraceEventType into EventLogEntryType
static EventLogEntryType EventLogEntryTypeFromEventType(TraceEventType type)
{
EventLogEntryType retval = EventLogEntryType.Information;
switch (type)
{
case TraceEventType.Critical:
case TraceEventType.Error:
retval = EventLogEntryType.Error;
break;
case TraceEventType.Warning:
retval = EventLogEntryType.Warning;
break;
}
return retval;
}
[Fx.Tag.SecurityNote(Critical = "Logs event to the event log by calling unsafe method.",
Safe = "Demands the same permission that is asserted by the unsafe method.")]
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
void SafeLogEvent(TraceEventType type, ushort eventLogCategory, uint eventId, bool shouldTrace, params string[] values)
{
UnsafeLogEvent(type, eventLogCategory, eventId, shouldTrace, values);
}
[Fx.Tag.SecurityNote(Critical = "Protect the string that defines the event source name.",
Safe = "It demands UnmanagedCode=true so PT cannot call.")]
[SecuritySafeCritical]
[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
void SafeSetLogSourceName(string eventLogSourceName)
{
this.eventLogSourceName = eventLogSourceName;
}
[Fx.Tag.SecurityNote(Critical = "Sets event source name.")]
[SecurityCritical]
void SetLogSourceName(string eventLogSourceName, DiagnosticTraceBase diagnosticTrace)
{
this.eventLogSourceName = eventLogSourceName;
this.diagnosticTrace = diagnosticTrace;
}
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource")]
[SecuritySafeCritical]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecuritySafeCritical method, Does not expose critical resources returned by methods with Link Demands")]
bool IsInPartialTrust()
{
bool retval = false;
try
{
using (Process process = Process.GetCurrentProcess())
{
retval = string.IsNullOrEmpty(process.ProcessName);
}
}
catch (SecurityException)
{
// we are just testing, ignore exception
retval = true;
}
return retval;
}
[SecurityCritical]
[Fx.Tag.SecurityNote(Critical = "Accesses security critical code RegisterEventSource and ReportEvent")]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
[ResourceConsumption(ResourceScope.Machine)]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts)]
void UnsafeWriteEventLog(TraceEventType type, ushort eventLogCategory, uint eventId, string[] logValues, byte[] sidBA, GCHandle stringsRootHandle)
{
using (SafeEventLogWriteHandle handle = SafeEventLogWriteHandle.RegisterEventSource(null, this.eventLogSourceName))
{
if (handle != null)
{
HandleRef data = new HandleRef(handle, stringsRootHandle.AddrOfPinnedObject());
UnsafeNativeMethods.ReportEvent(
handle,
(ushort)EventLogEntryTypeFromEventType(type),
eventLogCategory,
eventId,
sidBA,
(ushort)logValues.Length,
0,
data,
null);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
[MethodImpl(MethodImplOptions.NoInlining)]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts)]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecurityCritical method, Does not expose critical resources returned by methods with Link Demands")]
string UnsafeGetProcessName()
{
string retval = null;
using (Process process = Process.GetCurrentProcess())
{
retval = process.ProcessName;
}
return retval;
}
[Fx.Tag.SecurityNote(Critical = "Satisfies a LinkDemand for 'PermissionSetAttribute' on type 'Process' when calling method GetCurrentProcess",
Safe = "Does not leak any resource")]
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
[MethodImpl(MethodImplOptions.NoInlining)]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.SecureAsserts)]
[SuppressMessage(FxCop.Category.Security, FxCop.Rule.DoNotIndirectlyExposeMethodsWithLinkDemands,
Justification = "SecurityCritical method, Does not expose critical resources returned by methods with Link Demands")]
int UnsafeGetProcessId()
{
int retval = -1;
using (Process process = Process.GetCurrentProcess())
{
retval = process.Id;
}
return retval;
}
internal static string NormalizeEventLogParameter(string eventLogParameter)
{
if (eventLogParameter.IndexOf('%') < 0)
{
return eventLogParameter;
}
StringBuilder parameterBuilder = null;
int len = eventLogParameter.Length;
for (int i = 0; i < len; ++i)
{
char c = eventLogParameter[i];
// Not '%'
if (c != '%')
{
if (parameterBuilder != null) parameterBuilder.Append(c);
continue;
}
// Last char
if ((i + 1) >= len)
{
if (parameterBuilder != null) parameterBuilder.Append(c);
continue;
}
// Next char is not number
if (eventLogParameter[i + 1] < '0' || eventLogParameter[i + 1] > '9')
{
if (parameterBuilder != null) parameterBuilder.Append(c);
continue;
}
// initialize str builder
if (parameterBuilder == null)
{
parameterBuilder = new StringBuilder(len + 2);
for (int j = 0; j < i; ++j)
{
parameterBuilder.Append(eventLogParameter[j]);
}
}
parameterBuilder.Append(c);
parameterBuilder.Append(' ');
}
return parameterBuilder != null ? parameterBuilder.ToString() : eventLogParameter;
}
}
}

View File

@@ -0,0 +1,93 @@
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.Runtime.Diagnostics
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.Interop;
using System.Security;
internal class EventTraceActivity
{
// This field is public because it needs to be passed by reference for P/Invoke
public Guid ActivityId;
static EventTraceActivity empty;
public EventTraceActivity(bool setOnThread = false)
: this(Guid.NewGuid(), setOnThread)
{
}
public EventTraceActivity(Guid guid, bool setOnThread = false)
{
this.ActivityId = guid;
if (setOnThread)
{
SetActivityIdOnThread();
}
}
public static EventTraceActivity Empty
{
get
{
if (empty == null)
{
empty = new EventTraceActivity(Guid.Empty);
}
return empty;
}
}
public static string Name
{
get { return "E2EActivity"; }
}
[Fx.Tag.SecurityNote(Critical = "Critical because the CorrelationManager property has a link demand on UnmanagedCode.",
Safe = "We do not leak security data.")]
[SecuritySafeCritical]
public static EventTraceActivity GetFromThreadOrCreate(bool clearIdOnThread = false)
{
Guid guid = Trace.CorrelationManager.ActivityId;
if (guid == Guid.Empty)
{
guid = Guid.NewGuid();
}
else if (clearIdOnThread)
{
// Reset the ActivityId on the thread to avoid using the same Id again
Trace.CorrelationManager.ActivityId = Guid.Empty;
}
return new EventTraceActivity(guid);
}
[Fx.Tag.SecurityNote(Critical = "Critical because the CorrelationManager property has a link demand on UnmanagedCode.",
Safe = "We do not leak security data.")]
[SecuritySafeCritical]
public static Guid GetActivityIdFromThread()
{
return Trace.CorrelationManager.ActivityId;
}
public void SetActivityId(Guid guid)
{
this.ActivityId = guid;
}
[Fx.Tag.SecurityNote(Critical = "Critical because the CorrelationManager property has a link demand on UnmanagedCode.",
Safe = "We do not leak security data.")]
[SecuritySafeCritical]
void SetActivityIdOnThread()
{
Trace.CorrelationManager.ActivityId = this.ActivityId;
}
}
}

View File

@@ -0,0 +1,13 @@
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System;
interface ITraceSourceStringProvider
{
string GetSourceString();
}
}

View File

@@ -0,0 +1,22 @@
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System;
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
sealed class PerformanceCounterNameAttribute : Attribute
{
public PerformanceCounterNameAttribute(string name)
{
this.Name = name;
}
public string Name
{
get;
set;
}
}
}

View File

@@ -0,0 +1,31 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System;
using System.Xml;
class StringTraceRecord : TraceRecord
{
string elementName;
string content;
internal StringTraceRecord(string elementName, string content)
{
this.elementName = elementName;
this.content = content;
}
internal override string EventId
{
get { return BuildEventId("String"); }
}
internal override void WriteTo(XmlWriter writer)
{
writer.WriteElementString(elementName, content);
}
}
}

View File

@@ -0,0 +1,31 @@
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Diagnostics
{
using System.Xml;
[Serializable]
class TraceRecord
{
protected const string EventIdBase = "http://schemas.microsoft.com/2006/08/ServiceModel/";
protected const string NamespaceSuffix = "TraceRecord";
internal virtual string EventId { get { return BuildEventId("Empty"); } }
internal virtual void WriteTo(XmlWriter writer)
{
}
protected string BuildEventId(string eventId)
{
return TraceRecord.EventIdBase + eventId + TraceRecord.NamespaceSuffix;
}
protected string XmlEncode(string text)
{
return DiagnosticTraceBase.XmlEncode(text);
}
}
}