From 560b130b3cc691550aba2b3180865603a578b2ec Mon Sep 17 00:00:00 2001 From: Rasmus Kuusmann Date: Thu, 11 Aug 2022 10:13:40 +0300 Subject: [PATCH] Upstream sync 5f27ac2f26cd5d5069179a958ee60cddc1faecba..a5267be6402a22f7404acb9d88b7ad3aef059094 (#571) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Upstream sync 5f27ac2f26cd5d5069179a958ee60cddc1faecba..a5267be6402a22f7404acb9d88b7ad3aef059094 * Configuration Poller Implementation * Probes Configuration Updater & Comparer Probes Configuration Updater & Comparer implementation * Implemented the method probe instrumentation * Implemented the method probe instrumentation * Snapshot creator and object serialization for probes Adding snapshot creator and WIP on snapshot uploader Co-authored-by: Omer Raviv Co-authored-by: Alexander S. * Simplified the DebuggerTokens according to the refactoring of the CallTargetTokens Simplified the DebuggerTokens according to the refactoring of the CallTargetTokens * Discovery Service discovery service * Probe configuration fixes Probe configuration fixes + unit tests * Implemented the instrument-all mode for the Debugger * Added the Instrument All capability where we the Debugger instrumentation is being applied to every jit-compiled method (except predefined known set). * Added an environment variable named `DD_INTERNAL_DEBUGGER_INSTRUMENT_ALL` to control the instrumentation all mode. * Dropped non-ByRef support usages. * Fixed the signature of `LogException` - it is now accepting `DebuggerState`. * Added the ability to grab additional information about instrumented method during execution * Fix Configuration Poller in RCM mode * Add method probes snapshots tests * Fixed instrumentation info lookup for generic methods and methods in generic types * Fixed `InstrumentedMethodInfo` lookup for generic methods & methods (either generic/non-generic) in generic types. * Fixed issues we had in `SmokeTests`. * Added new smoke tests that covers the generics fixes. * Snapshot uploading * Implement Snapshot Uploader * Read local variable names from pdb and use them in snapshots * Add support for resolving Line Probe locations by reading sequence points from PDB * Support static methods (and extracting static fields) in Snapshot Probes * Fix json scheme for capture instance object * support static method in probe snapshot * Fix Snapshot uploading * Add snapshot summary * Add snapshot summary Co-authored-by: Matan Green Co-authored-by: Omer Raviv Co-authored-by: Omer Raviv * Implementation of Batch Uploading * Add tests to check if nothing happens when debugger disabled * implement live debugger tests * Implemented the Line Probe Instrumentation * Implemented the line probe instrumentation + allowing multiple line probes together with method probe to be set on the same method. * Keeping track of methods under instrumentation and updating them accordingly as new line probe / method probe requests arrive. * Activated reverts (aka undoing the instrumentation) for both Method Probes and Line Probes. * Passing ProbeId in Method Probes and Line Probes. * Got rid of assembly name in method probe requests. * Fixed issues in the structuring of the snapshots to adhere the correct format. * Extended the testing infrastructure to support multi*phase (`ProbeAttributeBase.Phase`) and customized (`ProbeAttributeBase.Unlisted`) tests to cover instrumentation of line probes and method probes with reverts. * Added several tests that utilize the new phasing mechanism that covers line probe together with method probe instrumentations. * Rebase Fixes * Allowing simple type names in method probes Allow simple type names in method probe requests. E.g `FooClass` instead of `The.Full.Name.Of.FooClass`. * Fix method probe snapshot without arguments * Remove Thread Sleep from integration tests * remove thread sleeps * Added support for overloads instrumentation in Method Probe * Added support for instrumenting overloads by providing a method probe without a signature. * Restore Live Debugger unit tests * restore live debugger tests * Reporting Probes Statuses Implemented the Probes Statuses. The following Probe Statuses are now emitted correctly: `Received`, `Active`, `Error`. - `Received`: The Agent received the probe but has not requested ReJIT yet (because the module is not loaded). - `Active`: _(*) At least_ `RequestReJIT` has been requested. - `Error`: Tried to apply the instrumentation on a method, but the instrumentation has failed for any reason (not supported types, failure to load metadata, etc...). * Adapt to change made in RCM request schema ('tracer_client' -> 'client_tracer') * Finalize Live Debugger codebase for public repo and address all .NET Team feedback * [Profiler] Fix Arm64 installer smoke tests (#3002) * Fix Amr64 installer smoke tests Profiler was not loaded because Arm64 is not currently supported. But the CodeHotspot feature was activated because it relies only on the env var DD_PROFILING_ENABLED * Check OS in addition to the architecture * Do not add x-datadog-tags header when vlaue is max header length is set to 0 (#3001) * [Test Package Versions Bump] Updating package versions (#2972) * [Test Package Versions Bump] * Exclude GraphQL 5.0 and 5.1.0 from testing There's no compatible combination of packages that works with our sample because GraphQL.Server.All requires minimum of 5.1.1. * Exclude 3.29.0+ from cosmosdb tests on Co-authored-by: Andrew Lock * Update vendored version of Newtonsoft.Json (#2980) * Add support for specifying files that should be dropped entirely from the vendored code We need this with Newtonsoft.Json because they define some attributes which we already declare internally * Allow specifying multiple transforms for transforming a content file * Update vendor definition for Newtonsoft.Json Added `#nullable enable` to source as now built with Nullable reference types. Also ignored all warnings related to incorrect annotations - these are primarily coming from the annotated base class libraries in .NET Core I think * Add horrible hacks - JsonSerializerInternalReader explicitly enables and disables some nullability warnings, which ends up conflicting with the global ignores we add. - Some targets were removed in the update, which means we now potentially hit other branches it seems. Working around it by patching the #if - TryGetValue is defined in netcoreapp2.1+. As newtonsoft doesn't target that, they don't have this conflict that we have to work around. Looks like this was manually worked around before, but I'm not sure the previous approach was actually correct. * Update vendored source * Update CoverageCollector to support new nullability in Newtonsoft.Json * Add new HAVE_REGEX_TIMEOUTS constant to constants defined in Datadog.Trace * Remove spurious $(AdditionalConstants) * [Profiler] Minor cleanup (#2977) * Ignore process_id in snapshots on Linux (#3003) When running in Docker, the pid of the main process is always 1.0, however, when we use `dd-trace` to instrument an app, the pid is sometimes _not_ 1.0. I'm not entirely sure why it's _sometimes_ 1.0, and sometimes not, but I would _guess_ that it's some sort of race. Either way, I think it's safe to ignore it in the snapshots. * Support Windows long paths * Fix tests * fix snk name * update configuration keys, values and doc Co-authored-by: Alexander S Co-authored-by: Matan Green Co-authored-by: Dudi Keleti Co-authored-by: Omer Raviv Co-authored-by: Omer Raviv Co-authored-by: Matan Green Co-authored-by: Alexander S Co-authored-by: Gregory LEOCADIE Co-authored-by: Pierre Bonet Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: dependabot[bot] Co-authored-by: Andrew Lock Co-authored-by: Kevin Gosse Co-authored-by: Piotr Kiełkowicz --- .github/workflows/ci.yml | 18 + Datadog.Trace.Debugger.slnf | 19 + Datadog.Trace.sln | 54 +- docker-compose.yml | 1 + docs/internal/internal-config.md | 10 + .../LinuxStackFramesCollector.cpp | 10 +- .../LinuxStackFramesCollector.h | 8 +- .../OsSpecificApi.cpp | 4 +- .../OsSpecificApi.cpp | 2 +- .../AdaptiveSampler.cpp | 4 +- .../Datadog.Profiler.Native/Configuration.cpp | 12 +- .../Datadog.Profiler.Native/Configuration.h | 8 +- .../DogstatsdService.cpp | 2 +- .../DogstatsdService.h | 4 +- .../ExceptionSampler.cpp | 6 +- .../ExceptionSampler.h | 4 +- .../Datadog.Profiler.Native/IConfiguration.h | 4 +- .../LibddprofExporter.cpp | 8 +- .../ManagedThreadInfo.h | 4 +- .../Datadog.Profiler.Native/OpSysTools.cpp | 8 +- .../Datadog.Profiler.Native/OpSysTools.h | 6 +- .../ProfilerEngineStatus.h | 6 +- .../StackSamplerLoop.cpp | 12 +- .../Datadog.Profiler.Native/Timer.Windows.cpp | 2 +- .../CodeHotspot/BuggyBitsTest.cs | 4 +- .../CpuProfiler/CpuProfilerTest.cs | 6 +- .../SmokeTests/BuggyBitsTest.cs | 2 +- .../SmokeTests/Computer01Test.cs | 8 +- .../SmokeTests/ExceptionGeneratorTest.cs | 2 +- .../SmokeTests/WebsiteAspNetCore01Test.cs | 2 +- .../HResultConverterTest.cpp | 2 +- .../IMetricsSenderFactoryTest.cpp | 8 +- shared/src/native-src/string.cpp | 5 + shared/src/native-src/string.h | 2 + tracer/Datadog.Trace.proj | 2 + .../PackageVersionsGeneratorDefinitions.json | 10 +- .../build/PackageVersionsLatestMajors.g.props | 92 +- .../build/PackageVersionsLatestMinors.g.props | 152 +- .../PackageVersionsLatestSpecific.g.props | 92 +- tracer/build/_build/Build.Steps.cs | 5 + tracer/build/_build/BuildVariables.cs | 1 + .../_build/UpdateVendors/UpdateVendors.cs | 15 +- .../UpdateVendors/VendoredDependency.cs | 76 +- .../Datadog.Dependabot.Integrations.csproj | 40 +- .../Datadog.Dependabot.Vendors.csproj | 4 +- .../CMakeLists.txt | 3 + .../Datadog.Trace.ClrProfiler.Native.def | 2 + .../Datadog.Trace.ClrProfiler.Native.vcxproj | 8 + ...g.Trace.ClrProfiler.Native.vcxproj.filters | 24 + .../calltarget_tokens.cpp | 24 +- .../calltarget_tokens.h | 14 +- .../cor_profiler.cpp | 38 +- .../cor_profiler.h | 10 + .../dd_profiler_constants.h | 3 + .../debugger_constants.h | 40 + .../debugger_environment_variables.h | 20 + .../debugger_environment_variables_util.cpp | 12 + .../debugger_environment_variables_util.h | 15 + .../debugger_members.h | 137 +- .../debugger_method_rewriter.cpp | 993 ++++++++++++- .../debugger_method_rewriter.h | 56 + ...ugger_probes_instrumentation_requester.cpp | 564 +++++++- ...ebugger_probes_instrumentation_requester.h | 28 +- .../debugger_rejit_handler_module_method.cpp | 33 +- .../debugger_rejit_handler_module_method.h | 9 +- .../debugger_rejit_preprocessor.cpp | 244 +++- .../debugger_rejit_preprocessor.h | 23 +- .../debugger_tokens.cpp | 1046 ++++++++++++++ .../debugger_tokens.h | 93 ++ .../il_rewriter.cpp | 5 + .../il_rewriter.h | 2 + .../il_rewriter_wrapper.cpp | 9 + .../il_rewriter_wrapper.h | 1 + .../integration.h | 47 + .../interop.cpp | 16 + .../module_metadata.h | 11 + .../probes_tracker.cpp | 108 ++ .../probes_tracker.h | 36 + .../rejit_handler.cpp | 55 +- .../rejit_handler.h | 6 +- .../rejit_preprocessor.cpp | 301 +++- .../rejit_preprocessor.h | 36 +- .../tracer_tokens.cpp | 2 +- .../CoverageCollector.cs | 17 +- .../DiscoveryService/DiscoveryService.cs | 94 ++ .../DiscoveryService/IDiscoveryService.cs | 23 + tracer/src/Datadog.Trace/Agent/IApiRequest.cs | 2 + .../Agent/Transports/ApiWebRequest.cs | 17 + .../Agent/Transports/HttpClientRequest.cs | 26 +- .../Agent/Transports/HttpStreamRequest.cs | 16 +- tracer/src/Datadog.Trace/Ci/CIVisibility.cs | 2 +- .../GraphQL/DocumentV5Struct.cs | 19 +- .../GraphQL/ExecuteAsyncV5Integration.cs | 127 +- .../GraphQL/GraphQLNameV5Struct.cs | 19 +- .../GraphQL/IExecutionContextV5.cs | 33 +- .../GraphQL/IValidationContext.cs | 17 +- .../GraphQL/OperationV5Struct.cs | 21 +- .../GraphQL/ValidateAsyncV5Integration.cs | 81 +- .../AsyncCallHandleFinishedInstrumentation.cs | 77 +- .../AutoInstrumentation/Testing/Common.cs | 2 +- .../Testing/MsTestV2/MsTestIntegration.cs | 2 +- .../Testing/NUnit/NUnitIntegration.cs | 2 +- .../Testing/XUnit/XUnitIntegration.cs | 2 +- .../ClrProfiler/Instrumentation.cs | 15 + .../ClrProfiler/NativeMethods.cs | 2 +- .../ConfigurationKeys.Debugger.cs | 78 ++ .../Configuration/ImmutableTracerSettings.cs | 4 + .../Configuration/TracerSettings.cs | 11 +- .../ContinuousProfiler/ProfilerStatus.cs | 8 +- tracer/src/Datadog.Trace/Datadog.Trace.csproj | 6 +- .../Configurations/ConfigurationPoller.cs | 109 ++ .../Configurations/ConfigurationUpdater.cs | 114 ++ .../FileProbeConfigurationApi.cs | 35 + .../Configurations/IConfigurationPoller.cs | 18 + .../Configurations/IProbeConfigurationApi.cs | 15 + .../Debugger/Configurations/Models/Capture.cs | 37 + .../Configurations/Models/FilterList.cs | 57 + .../Configurations/Models/IJsonApiObject.cs | 12 + .../Configurations/Models/MetricKind.cs | 14 + .../Configurations/Models/MetricProbe.cs | 58 + .../Configurations/Models/MetricValue.cs | 12 + .../Configurations/Models/OpsConfiguration.cs | 12 + .../Models/ProbeConfiguration.cs | 33 + .../Configurations/Models/ProbeDefinition.cs | 81 ++ .../Configurations/Models/Sampling.cs | 29 + .../Configurations/Models/SnapshotProbe.cs | 56 + .../Debugger/Configurations/Models/Tag.cs | 35 + .../Debugger/Configurations/Models/Where.cs | 64 + .../ProbeConfigurationApiFactory.cs | 26 + .../ProbeConfigurationComparer.cs | 45 + .../RcmProbeConfigurationApi.cs | 113 ++ .../Debugger/Configurations/Trie.cs | 161 +++ .../Debugger/DebuggerSettings.cs | 138 ++ .../Debugger/DebuggerTransportStrategy.cs | 29 + .../Debugger/Helpers/DisposableEnumerable.cs | 33 + .../Debugger/Helpers/EnumerableExtensions.cs | 28 + .../Debugger/Helpers/JTokenExtensions.cs | 42 + .../Debugger/Helpers/StringExtensions.cs | 31 + .../Debugger/ILineProbeResolver.cs | 21 + .../Debugger/ImmutableDebuggerSettings.cs | 129 ++ .../Instrumentation/DebuggerReturn.cs | 74 + .../Instrumentation/LineDebuggerInvoker.cs | 196 +++ .../Instrumentation/LineDebuggerState.cs | 109 ++ .../Instrumentation/MethodDebuggerInvoker.cs | 272 ++++ .../Instrumentation/MethodDebuggerState.cs | 93 ++ .../Instrumentation/MethodMetadataInfo.cs | 32 + .../MethodMetadataInfoFactory.cs | 92 ++ .../Instrumentation/MethodMetadataProvider.cs | 131 ++ .../Instrumentation/ProbeRateLimiter.cs | 40 + .../Debugger/LineProbeResolver.cs | 177 +++ .../Datadog.Trace/Debugger/LiveDebugger.cs | 303 ++++ .../Debugger/Models/LineProbeResolveResult.cs | 20 + .../Debugger/Models/LiveProbeResolveStatus.cs | 26 + .../Debugger/Models/ProbeSnapshot.cs | 194 +++ .../Datadog.Trace/Debugger/Models/Snapshot.cs | 46 + .../Debugger/PInvoke/DebuggerNativeMethods.cs | 91 ++ .../PInvoke/NativeLineProbeDefinition.cs | 44 + .../PInvoke/NativeMethodProbeDefinition.cs | 63 + .../Debugger/PInvoke/NativeProbeStatus.cs | 18 + .../PInvoke/NativeRemoveProbeRequest.cs | 22 + .../Debugger/PInvoke/ProbeStatus.cs | 24 + .../Debugger/ProbeLocationType.cs | 14 + .../src/Datadog.Trace/Debugger/ProbeMode.cs | 20 + .../ProbeStatuses/IProbeStatusPoller.cs | 22 + .../ProbeStatuses/ProbeStatusPoller.cs | 118 ++ .../Debugger/Sink/AgentBatchUploadApi.cs | 82 ++ .../Debugger/Sink/BatchUploadApiFactory.cs | 18 + .../Debugger/Sink/BatchUploader.cs | 120 ++ .../Debugger/Sink/DebuggerSink.cs | 150 ++ .../Debugger/Sink/IBatchUploadApi.cs | 15 + .../Debugger/Sink/IDebuggerSink.cs | 43 + .../Sink/Models/DebuggerDiagnostics.cs | 22 + .../Debugger/Sink/Models/Diagnostics.cs | 48 + .../Debugger/Sink/Models/ProbeException.cs | 16 + .../Debugger/Sink/Models/ProbeStatus.cs | 50 + .../Debugger/Sink/Models/Status.cs | 19 + .../Debugger/Sink/Models/TimedMessage.cs | 16 + .../Debugger/Sink/ProbeStatusSink.cs | 160 +++ .../Debugger/Sink/SnapshotSink.cs | 56 + .../Snapshots/DebuggerSnapshotCreator.cs | 326 +++++ .../Snapshots/DebuggerSnapshotSerializer.cs | 386 +++++ ...napshotSerializerFieldsAndPropsSelector.cs | 52 + ...napshotSerializerFieldsAndPropsSelector.cs | 38 + ...napshotSerializerFieldsAndPropsSelector.cs | 30 + ...napshotSerializerFieldsAndPropsSelector.cs | 79 ++ .../Debugger/Snapshots/SnapshotSummary.cs | 151 ++ .../Snapshots/SupportedTypesService.cs | 127 ++ ...napshotSerializerFieldsAndPropsSelector.cs | 45 + .../src/Datadog.Trace/FrameworkDescription.cs | 5 + .../Datadog.Trace/PDBs/DatadogPdbReader.cs | 34 +- .../PDBs/MethodSymbolResolver.cs | 2 +- .../PDBs/SymbolMethodExtensions.cs | 51 + .../DssSymbolReaderImpl.Additions.cs | 25 + .../dnlibAdditions/PdbReader.Additions.cs | 54 + .../PortablePdbReader.Additions.cs | 82 ++ .../Propagators/DatadogContextPropagator.cs | 2 +- .../src/Datadog.Trace/ReadOnlySpanContext.cs | 23 +- .../Models/RcmClient.cs | 33 + .../Models/RcmRequest.cs | 60 + .../Models/RcmResponse.cs | 15 + .../Models/RcmTargetFile.cs | 18 + .../Models/RcmTracerClient.cs | 30 + .../Datadog.Trace/SamplingPriorityValues.cs | 51 +- .../Telemetry/DTOs/TelemetryValue.cs | 19 +- .../Telemetry/TelemetryCircuitBreaker.cs | 95 +- .../Transports/JsonTelemetryTransport.cs | 111 +- .../BoundedConcurrentQueue.cs | 10 +- .../Newtonsoft.Json/Bson/BsonBinaryType.cs | 4 + .../Newtonsoft.Json/Bson/BsonBinaryWriter.cs | 4 + .../Newtonsoft.Json/Bson/BsonObjectId.cs | 4 + .../Newtonsoft.Json/Bson/BsonReader.cs | 4 + .../Vendors/Newtonsoft.Json/Bson/BsonToken.cs | 4 + .../Vendors/Newtonsoft.Json/Bson/BsonType.cs | 4 + .../Newtonsoft.Json/Bson/BsonWriter.cs | 4 + .../Newtonsoft.Json/ConstructorHandling.cs | 3 + .../Converters/BinaryConverter.cs | 19 +- .../Converters/BsonObjectIdConverter.cs | 4 + .../Converters/CustomCreationConverter.cs | 7 +- .../Converters/DataSetConverter.cs | 13 +- .../Converters/DataTableConverter.cs | 17 +- .../Converters/DateTimeConverterBase.cs | 3 + .../Converters/DiscriminatedUnionConverter.cs | 83 +- .../Converters/EntityKeyMemberConverter.cs | 36 +- .../Converters/ExpandoObjectConverter.cs | 19 +- .../Converters/IsoDateTimeConverter.cs | 27 +- .../Converters/JavaScriptDateTimeConverter.cs | 11 +- .../Converters/KeyValuePairConverter.cs | 23 +- .../Converters/RegexConverter.cs | 19 +- .../Converters/StringEnumConverter.cs | 17 +- .../Converters/UnixDateTimeConverter.cs | 11 +- .../Converters/VersionConverter.cs | 9 +- .../Converters/XmlNodeConverter.cs | 310 +++-- .../Newtonsoft.Json/DateFormatHandling.cs | 3 + .../Newtonsoft.Json/DateParseHandling.cs | 9 +- .../Newtonsoft.Json/DateTimeZoneHandling.cs | 3 + .../Newtonsoft.Json/DefaultJsonNameTable.cs | 7 +- .../Newtonsoft.Json/DefaultValueHandling.cs | 3 + .../Newtonsoft.Json/FloatFormatHandling.cs | 3 + .../Newtonsoft.Json/FloatParseHandling.cs | 3 + .../Newtonsoft.Json/FormatterAssemblyStyle.cs | 3 + .../Vendors/Newtonsoft.Json/Formatting.cs | 3 + .../Vendors/Newtonsoft.Json/IArrayPool.cs | 5 +- .../Vendors/Newtonsoft.Json/IJsonLineInfo.cs | 3 + .../Newtonsoft.Json/JsonArrayAttribute.cs | 3 + .../JsonConstructorAttribute.cs | 3 + .../Newtonsoft.Json/JsonContainerAttribute.cs | 23 +- .../Vendors/Newtonsoft.Json/JsonConvert.cs | 114 +- .../Vendors/Newtonsoft.Json/JsonConverter.cs | 21 +- .../Newtonsoft.Json/JsonConverterAttribute.cs | 5 +- .../JsonConverterCollection.cs | 3 + .../JsonDictionaryAttribute.cs | 3 + .../Vendors/Newtonsoft.Json/JsonException.cs | 5 +- .../JsonExtensionDataAttribute.cs | 3 + .../Newtonsoft.Json/JsonIgnoreAttribute.cs | 3 + .../Vendors/Newtonsoft.Json/JsonNameTable.cs | 5 +- .../Newtonsoft.Json/JsonObjectAttribute.cs | 16 +- .../Vendors/Newtonsoft.Json/JsonPosition.cs | 17 +- .../Newtonsoft.Json/JsonPropertyAttribute.cs | 17 +- .../Newtonsoft.Json/JsonReader.Async.cs | 13 +- .../Vendors/Newtonsoft.Json/JsonReader.cs | 95 +- .../Newtonsoft.Json/JsonReaderException.cs | 11 +- .../Newtonsoft.Json/JsonRequiredAttribute.cs | 3 + .../JsonSerializationException.cs | 11 +- .../Vendors/Newtonsoft.Json/JsonSerializer.cs | 95 +- .../Newtonsoft.Json/JsonSerializerSettings.cs | 30 +- .../Newtonsoft.Json/JsonTextReader.Async.cs | 59 +- .../Vendors/Newtonsoft.Json/JsonTextReader.cs | 99 +- .../Newtonsoft.Json/JsonTextWriter.Async.cs | 49 +- .../Vendors/Newtonsoft.Json/JsonTextWriter.cs | 42 +- .../Vendors/Newtonsoft.Json/JsonToken.cs | 3 + .../Newtonsoft.Json/JsonValidatingReader.cs | 4 + .../Newtonsoft.Json/JsonWriter.Async.cs | 29 +- .../Vendors/Newtonsoft.Json/JsonWriter.cs | 59 +- .../Newtonsoft.Json/JsonWriterException.cs | 11 +- .../Newtonsoft.Json/Linq/CommentHandling.cs | 3 + .../Linq/DuplicatePropertyNameHandling.cs | 3 + .../Newtonsoft.Json/Linq/Extensions.cs | 35 +- .../Newtonsoft.Json/Linq/IJEnumerable.cs | 3 + .../Newtonsoft.Json/Linq/JArray.Async.cs | 5 +- .../Vendors/Newtonsoft.Json/Linq/JArray.cs | 20 +- .../Linq/JConstructor.Async.cs | 9 +- .../Newtonsoft.Json/Linq/JConstructor.cs | 26 +- .../Newtonsoft.Json/Linq/JContainer.Async.cs | 22 +- .../Newtonsoft.Json/Linq/JContainer.cs | 149 +- .../Newtonsoft.Json/Linq/JEnumerable.cs | 5 +- .../Newtonsoft.Json/Linq/JObject.Async.cs | 5 +- .../Vendors/Newtonsoft.Json/Linq/JObject.cs | 121 +- .../Newtonsoft.Json/Linq/JProperty.Async.cs | 7 +- .../Vendors/Newtonsoft.Json/Linq/JProperty.cs | 57 +- .../Linq/JPropertyDescriptor.cs | 5 +- .../Linq/JPropertyKeyedCollection.cs | 23 +- .../Newtonsoft.Json/Linq/JRaw.Async.cs | 3 + .../Vendors/Newtonsoft.Json/Linq/JRaw.cs | 5 +- .../Newtonsoft.Json/Linq/JToken.Async.cs | 11 +- .../Vendors/Newtonsoft.Json/Linq/JToken.cs | 330 +++-- .../Linq/JTokenEqualityComparer.cs | 3 + .../Newtonsoft.Json/Linq/JTokenReader.cs | 47 +- .../Newtonsoft.Json/Linq/JTokenType.cs | 3 + .../Linq/JTokenWriter.Async.cs | 3 + .../Newtonsoft.Json/Linq/JTokenWriter.cs | 51 +- .../Newtonsoft.Json/Linq/JValue.Async.cs | 9 +- .../Vendors/Newtonsoft.Json/Linq/JValue.cs | 79 +- .../Newtonsoft.Json/Linq/JsonLoadSettings.cs | 6 +- .../Newtonsoft.Json/Linq/JsonMergeSettings.cs | 3 + .../Linq/JsonPath/ArrayIndexFilter.cs | 9 +- .../Linq/JsonPath/ArrayMultipleIndexFilter.cs | 14 +- .../Linq/JsonPath/ArraySliceFilter.cs | 9 +- .../Linq/JsonPath/FieldFilter.cs | 22 +- .../Linq/JsonPath/FieldMultipleFilter.cs | 18 +- .../Newtonsoft.Json/Linq/JsonPath/JPath.cs | 79 +- .../Linq/JsonPath/PathFilter.cs | 18 +- .../Linq/JsonPath/QueryExpression.cs | 73 +- .../Linq/JsonPath/QueryFilter.cs | 14 +- .../Linq/JsonPath/QueryScanFilter.cs | 16 +- .../Linq/JsonPath/RootFilter.cs | 5 +- .../Linq/JsonPath/ScanFilter.cs | 16 +- .../Linq/JsonPath/ScanMultipleFilter.cs | 19 +- .../Linq/JsonSelectSettings.cs | 35 + .../Newtonsoft.Json/Linq/LineInfoHandling.cs | 3 + .../Linq/MergeArrayHandling.cs | 3 + .../Linq/MergeNullValueHandling.cs | 3 + .../Newtonsoft.Json/MemberSerialization.cs | 3 + .../MetadataPropertyHandling.cs | 3 + .../Newtonsoft.Json/MissingMemberHandling.cs | 3 + .../Newtonsoft.Json.csproj.txt | 58 +- .../Newtonsoft.Json/Newtonsoft.Json.ruleset | 214 ++- .../Newtonsoft.Json/NullValueHandling.cs | 3 + .../Newtonsoft.Json/ObjectCreationHandling.cs | 3 + .../PreserveReferencesHandling.cs | 3 + .../Newtonsoft.Json/ReferenceLoopHandling.cs | 3 + .../Vendors/Newtonsoft.Json/Required.cs | 3 + .../Newtonsoft.Json/Schema/Extensions.cs | 4 + .../Newtonsoft.Json/Schema/JsonSchema.cs | 6 + .../Schema/JsonSchemaBuilder.cs | 6 +- .../Schema/JsonSchemaConstants.cs | 4 + .../Schema/JsonSchemaException.cs | 4 + .../Schema/JsonSchemaGenerator.cs | 12 +- .../Newtonsoft.Json/Schema/JsonSchemaModel.cs | 4 + .../Schema/JsonSchemaModelBuilder.cs | 4 + .../Newtonsoft.Json/Schema/JsonSchemaNode.cs | 4 + .../Schema/JsonSchemaNodeCollection.cs | 4 + .../Schema/JsonSchemaResolver.cs | 4 + .../Newtonsoft.Json/Schema/JsonSchemaType.cs | 4 + .../Schema/JsonSchemaWriter.cs | 4 + .../Schema/UndefinedSchemaIdHandling.cs | 4 + .../Schema/ValidationEventArgs.cs | 4 + .../Schema/ValidationEventHandler.cs | 4 + .../Serialization/CachedAttributeGetter.cs | 7 +- .../Serialization/CamelCaseNamingStrategy.cs | 3 + .../CamelCasePropertyNamesContractResolver.cs | 7 +- .../Serialization/DefaultContractResolver.cs | 152 +- .../Serialization/DefaultNamingStrategy.cs | 3 + .../Serialization/DefaultReferenceResolver.cs | 3 + .../DefaultSerializationBinder.cs | 27 +- .../Serialization/DiagnosticsTraceWriter.cs | 5 +- .../Serialization/DynamicValueProvider.cs | 11 +- .../Serialization/ErrorContext.cs | 9 +- .../Serialization/ErrorEventArgs.cs | 7 +- .../Serialization/ExpressionValueProvider.cs | 11 +- .../Serialization/FormatterConverter.cs | 3 + .../Serialization/IAttributeProvider.cs | 3 + .../Serialization/IContractResolver.cs | 3 + .../Serialization/IReferenceResolver.cs | 3 + .../Serialization/ISerializationBinder.cs | 7 +- .../Serialization/ITraceWriter.cs | 5 +- .../Serialization/IValueProvider.cs | 7 +- .../Serialization/JsonArrayContract.cs | 86 +- .../Serialization/JsonContainerContract.cs | 15 +- .../Serialization/JsonContract.cs | 33 +- .../Serialization/JsonDictionaryContract.cs | 75 +- .../Serialization/JsonDynamicContract.cs | 19 +- .../Serialization/JsonFormatterConverter.cs | 16 +- .../JsonISerializableContract.cs | 5 +- .../Serialization/JsonLinqContract.cs | 3 + .../Serialization/JsonObjectContract.cs | 29 +- .../Serialization/JsonPrimitiveContract.cs | 3 + .../Serialization/JsonProperty.cs | 58 +- .../Serialization/JsonPropertyCollection.cs | 26 +- .../JsonSerializerInternalBase.cs | 17 +- .../JsonSerializerInternalReader.cs | 406 +++--- .../JsonSerializerInternalWriter.cs | 130 +- .../Serialization/JsonSerializerProxy.cs | 21 +- .../Serialization/JsonStringContract.cs | 3 + .../Serialization/JsonTypeReflector.cs | 69 +- .../Serialization/KebabCaseNamingStrategy.cs | 91 ++ .../Serialization/MemoryTraceWriter.cs | 5 +- .../Serialization/NamingStrategy.cs | 44 + .../Serialization/ObjectConstructor.cs | 5 +- .../Serialization/OnErrorAttribute.cs | 3 + .../ReflectionAttributeProvider.cs | 3 + .../Serialization/ReflectionValueProvider.cs | 7 +- .../SerializationBinderAdapter.cs | 7 +- .../Serialization/SnakeCaseNamingStrategy.cs | 3 + .../Serialization/TraceJsonReader.cs | 15 +- .../Serialization/TraceJsonWriter.cs | 17 +- .../Newtonsoft.Json/SerializationBinder.cs | 7 +- .../Newtonsoft.Json/StringEscapeHandling.cs | 3 + .../Vendors/Newtonsoft.Json/TraceLevel.cs | 3 + .../TypeNameAssemblyFormatHandling.cs | 3 + .../Newtonsoft.Json/TypeNameHandling.cs | 3 + .../Newtonsoft.Json/Utilities/AsyncUtils.cs | 23 +- .../Utilities/Base64Encoder.cs | 7 +- .../Utilities/BidirectionalDictionary.cs | 7 +- .../Utilities/CollectionUtils.cs | 36 +- .../Utilities/CollectionWrapper.cs | 41 +- .../Newtonsoft.Json/Utilities/ConvertUtils.cs | 87 +- .../Utilities/DateTimeParser.cs | 3 + .../Utilities/DateTimeUtils.cs | 39 +- .../Utilities/DictionaryWrapper.cs | 88 +- .../Newtonsoft.Json/Utilities/DynamicProxy.cs | 19 +- .../Utilities/DynamicProxyMetaObject.cs | 9 +- .../DynamicReflectionDelegateFactory.cs | 38 +- .../Newtonsoft.Json/Utilities/DynamicUtils.cs | 26 +- .../Newtonsoft.Json/Utilities/EnumInfo.cs | 3 + .../Newtonsoft.Json/Utilities/EnumUtils.cs | 39 +- .../ExpressionReflectionDelegateFactory.cs | 50 +- .../Newtonsoft.Json/Utilities/FSharpUtils.cs | 139 +- .../Utilities/ILGeneratorExtensions.cs | 3 + .../Utilities/ImmutableCollectionsUtils.cs | 13 +- .../Utilities/JavaScriptUtils.cs | 52 +- .../Utilities/JsonTokenUtils.cs | 3 + .../LateBoundReflectionDelegateFactory.cs | 19 +- .../Newtonsoft.Json/Utilities/LinqBridge.cs | 12 +- .../Newtonsoft.Json/Utilities/MathUtils.cs | 3 + .../Newtonsoft.Json/Utilities/MethodBinder.cs | 7 +- .../Newtonsoft.Json/Utilities/MethodCall.cs | 5 +- .../Utilities/MiscellaneousUtils.cs | 28 +- .../Utilities/ReflectionDelegateFactory.cs | 17 +- .../Utilities/ReflectionObject.cs | 43 +- .../Utilities/ReflectionUtils.cs | 77 +- .../Newtonsoft.Json/Utilities/StringBuffer.cs | 23 +- .../Utilities/StringReference.cs | 3 + .../Newtonsoft.Json/Utilities/StringUtils.cs | 73 +- .../Utilities/StructMultiKey.cs | 3 + .../Utilities/ThreadSafeStore.cs | 3 + .../Utilities/TypeExtensions.cs | 39 +- .../Utilities/ValidationUtils.cs | 7 +- .../Vendors/Newtonsoft.Json/WriteState.cs | 3 + .../_last_downloaded_source_url.txt | 2 +- .../Vendors/Newtonsoft.Json/packageIcon.png | Bin 0 -> 8956 bytes .../dnlib/DotNet/Pdb/Dss/SymbolReaderImpl.cs | 2 +- .../dnlib/DotNet/Pdb/Managed/DbiScope.cs | 2 +- .../dnlib/DotNet/Pdb/Managed/PdbReader.cs | 2 +- .../DotNet/Pdb/Portable/PortablePdbReader.cs | 2 +- ....Trace.ClrProfiler.IntegrationTests.csproj | 5 +- .../Debugger/Assertions/DumpHeapLive.cs | 91 ++ .../Assertions/MemoryAssertionException.cs | 16 + .../Debugger/Assertions/MemoryAssertions.cs | 80 ++ .../Debugger/DebuggerSampleProcessHelper.cs | 44 + .../Debugger/DebuggerTestHelper.cs | 111 ++ .../Debugger/DeterministicGuidGenerator.cs | 35 + .../Debugger/JsonUtility.cs | 68 + .../Debugger/LiveDebuggerTests.cs | 91 ++ .../Debugger/LogEntryWatcher.cs | 106 ++ .../Debugger/ProbesTests.cs | 392 ++++++ ....OverloadAndSimpleNameTest#1..verified.txt | 1240 +++++++++++++++++ ...ts.GenericMethodWithArguments.verified.txt | 356 +++++ ...keTests.HasArgumentsAndLocals.verified.txt | 94 ++ ....HasFieldLazyValueInitialized.verified.txt | 116 ++ ...sFieldLazyValueNotInitialized.verified.txt | 106 ++ ...keTests.HasLocalListOfObjects.verified.txt | 553 ++++++++ ...dArgumentsInGenericNestedType.verified.txt | 563 ++++++++ ...Tests.HasLocalsAndReturnValue.verified.txt | 315 +++++ ...bes.SmokeTests.HasReturnValue.verified.txt | 80 ++ ...obes.SmokeTests.HasVarAndMvar.verified.txt | 127 ++ ...s.InstanceMethodWithArguments.verified.txt | 149 ++ ...SmokeTests.InstanceVoidMethod.verified.txt | 73 + ...s.LineProbesWithRevertTest#1..verified.txt | 344 +++++ ...s.LineProbesWithRevertTest#2..verified.txt | 422 ++++++ ...s.LineProbesWithRevertTest#3..verified.txt | 338 +++++ ...s.LineProbesWithRevertTest#4..verified.txt | 86 ++ ...s.LineProbesWithRevertTest#5..verified.txt | 254 ++++ ...s.LineProbesWithRevertTest#6..verified.txt | 1 + ...ests.MethodThrowExceptionTest.verified.txt | 188 +++ ...tiScopesWithSameLocalNameTest.verified.txt | 270 ++++ ...SmokeTests.MultipleLineProbes.verified.txt | 452 ++++++ ...ricMethodInDerivedGenericType.verified.txt | 141 ++ ...ests.SimpleNestedTypeNameTest.verified.txt | 112 ++ ...SmokeTests.SimpleTypeNameTest.verified.txt | 112 ++ ...sts.StaticMethodWithArguments.verified.txt | 149 ++ ....Probes.SmokeTests.StaticType.verified.txt | 182 +++ ...s.SmokeTests.StaticVoidMethod.verified.txt | 73 + ...TypeNameInGlobalNamespaceTest.verified.txt | 112 ++ ...TypeNameInGlobalNamespaceTest.verified.txt | 112 ++ ....OverloadAndSimpleNameTest#1..verified.txt | 14 + ...ts.GenericMethodWithArguments.verified.txt | 26 + ...keTests.HasArgumentsAndLocals.verified.txt | 14 + ....HasFieldLazyValueInitialized.verified.txt | 14 + ...sFieldLazyValueNotInitialized.verified.txt | 14 + ...keTests.HasLocalListOfObjects.verified.txt | 14 + ...dArgumentsInGenericNestedType.verified.txt | 14 + ...Tests.HasLocalsAndReturnValue.verified.txt | 50 + ...bes.SmokeTests.HasReturnValue.verified.txt | 14 + ...obes.SmokeTests.HasVarAndMvar.verified.txt | 14 + ...s.InstanceMethodWithArguments.verified.txt | 26 + ...SmokeTests.InstanceVoidMethod.verified.txt | 14 + ...s.LineProbesWithRevertTest#1..verified.txt | 50 + ...s.LineProbesWithRevertTest#2..verified.txt | 62 + ...s.LineProbesWithRevertTest#3..verified.txt | 26 + ...s.LineProbesWithRevertTest#4..verified.txt | 14 + ...s.LineProbesWithRevertTest#5..verified.txt | 14 + ...s.LineProbesWithRevertTest#6..verified.txt | 14 + ...ests.MethodThrowExceptionTest.verified.txt | 26 + ...tiScopesWithSameLocalNameTest.verified.txt | 26 + ...SmokeTests.MultipleLineProbes.verified.txt | 74 + ...nSupportedInstrumentationTest.verified.txt | 18 + ...ricMethodInDerivedGenericType.verified.txt | 14 + ...ests.SimpleNestedTypeNameTest.verified.txt | 14 + ...SmokeTests.SimpleTypeNameTest.verified.txt | 14 + ...sts.StaticMethodWithArguments.verified.txt | 26 + ....Probes.SmokeTests.StaticType.verified.txt | 26 + ...s.SmokeTests.StaticVoidMethod.verified.txt | 14 + ...TypeNameInGlobalNamespaceTest.verified.txt | 14 + ...TypeNameInGlobalNamespaceTest.verified.txt | 14 + .../PackageVersionsLatestMajors.g.cs | 92 +- .../PackageVersionsLatestMinors.g.cs | 80 +- .../PackageVersionsLatestSpecific.g.cs | 92 +- .../PdbReaderTests.cs | 5 +- .../TrieTests.cs | 72 + .../VerifyHelper.cs | 4 +- .../MockProbeSnapshot.cs | 39 + .../MockTracerAgent.cs | 134 +- .../Datadog.Trace.TestHelpers/TestHelper.cs | 2 +- .../Datadog.Trace.Tests.csproj | 4 - .../Debugger/BatchUploaderTests.cs | 169 +++ .../Debugger/DebuggerSettingsTests.cs | 172 +++ .../Debugger/LiveDebuggerTests.cs | 179 +++ .../ProbeConfigurationComparerTests.cs | 279 ++++ .../Debugger/ProbeStatusSinkTests.cs | 255 ++++ .../Debugger/SupportedTypesServiceTests.cs | 29 + .../Datadog.Trace.Tests/Debugger/TimeLord.cs | 34 + .../DirectSubmission/Sink/LogsApiTests.cs | 5 + .../BoundedConcurrentQueueTests.cs | 26 +- .../SpanContextPropagatorTests.cs | 5 +- .../Benchmarks.Trace/AgentWriterBenchmark.cs | 5 + .../debugger/Samples.Probes/IAsyncRun.cs | 8 + .../debugger/Samples.Probes/IRun.cs | 6 + .../LineProbeTestDataAttribute.cs | 17 + .../MethodProbeTestDataAttribute.cs | 21 + .../Samples.Probes/ProbeAttributeBase.cs | 21 + .../debugger/Samples.Probes/Program.cs | 83 ++ .../Properties/launchSettings.json | 21 + .../Samples.Probes/Samples.Probes.csproj | 17 + .../debugger/Samples.Probes/Shared/Address.cs | 31 + .../debugger/Samples.Probes/Shared/Generic.cs | 7 + .../Samples.Probes/Shared/IGeneric.cs | 7 + .../Shared/IntentionalDebuggerException.cs | 16 + .../debugger/Samples.Probes/Shared/Person.cs | 49 + .../Samples.Probes/SimpleHttpListener.cs | 56 + .../SmokeTests/AsyncInstanceMethod.cs | 28 + .../Emit100LineProbeSnapshotsTest.cs | 22 + .../GenericMethodWithArgumentsAndLocals.cs | 25 + .../SmokeTests/HasArgumentsAndLocals.cs | 23 + .../Samples.Probes/SmokeTests/HasException.cs | 22 + .../HasFieldLazyValueInitialized.cs | 23 + .../HasFieldLazyValueNotInitialized.cs | 23 + .../SmokeTests/HasLocalListOfObjects.cs | 26 + .../SmokeTests/HasLocalTaskCompleted.cs | 27 + .../SmokeTests/HasLocalTaskNotCompleted.cs | 34 + .../HasLocalsAndArgumentsInGenericType.cs | 42 + .../SmokeTests/HasLocalsAndReturnValue.cs | 28 + .../SmokeTests/HasReturnValue.cs | 23 + .../SmokeTests/HasVarAndMvar.cs | 31 + .../SmokeTests/InstanceMethodWithArguments.cs | 21 + .../SmokeTests/InstanceVoidMethod.cs | 22 + .../SmokeTests/LineProbesWithRevertTest.cs | 61 + .../SmokeTests/MethodThrowExceptionTest.cs | 32 + .../MultiScopesWithSameLocalNameTest.cs | 40 + .../SmokeTests/MultipleLineProbes.cs | 26 + .../NonSupportedInstrumentationTest.cs | 29 + .../OpenGenericMethodInDerivedGenericType.cs | 29 + .../SmokeTests/OverloadAndSimpleNameTest.cs | 140 ++ ...mpleNestedTypeNameInGlobalNamespaceTest.cs | 29 + .../SmokeTests/SimpleNestedTypeNameTest.cs | 29 + .../SimpleTypeNameInGlobalNamespaceTest.cs | 26 + .../SmokeTests/SimpleTypeNameTest.cs | 26 + .../SmokeTests/StaticMethodWithArguments.cs | 21 + .../Samples.Probes/SmokeTests/StaticType.cs | 26 + .../SmokeTests/StaticVoidMethod.cs | 22 + .../Samples.Probes/probes_definition.json | 92 ++ 580 files changed, 26892 insertions(+), 3131 deletions(-) create mode 100644 Datadog.Trace.Debugger.slnf create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_constants.h create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables.h create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.cpp create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.h create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.cpp create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.h create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.cpp create mode 100644 tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.h create mode 100644 tracer/src/Datadog.Trace/Agent/DiscoveryService/DiscoveryService.cs create mode 100644 tracer/src/Datadog.Trace/Agent/DiscoveryService/IDiscoveryService.cs create mode 100644 tracer/src/Datadog.Trace/Configuration/ConfigurationKeys.Debugger.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationPoller.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationUpdater.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/FileProbeConfigurationApi.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/IConfigurationPoller.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/IProbeConfigurationApi.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/Capture.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/FilterList.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/IJsonApiObject.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricKind.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricProbe.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricValue.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/OpsConfiguration.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeConfiguration.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeDefinition.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/Sampling.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/SnapshotProbe.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/Tag.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Models/Where.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationApiFactory.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationComparer.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/RcmProbeConfigurationApi.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Configurations/Trie.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/DebuggerSettings.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/DebuggerTransportStrategy.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Helpers/DisposableEnumerable.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Helpers/EnumerableExtensions.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Helpers/JTokenExtensions.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ILineProbeResolver.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ImmutableDebuggerSettings.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/DebuggerReturn.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerInvoker.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerState.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerInvoker.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerState.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfo.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfoFactory.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataProvider.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Instrumentation/ProbeRateLimiter.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/LineProbeResolver.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/LiveDebugger.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Models/LineProbeResolveResult.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Models/LiveProbeResolveStatus.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Models/ProbeSnapshot.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Models/Snapshot.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/DebuggerNativeMethods.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/NativeLineProbeDefinition.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/NativeMethodProbeDefinition.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/NativeProbeStatus.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/NativeRemoveProbeRequest.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/PInvoke/ProbeStatus.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ProbeLocationType.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ProbeMode.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ProbeStatuses/IProbeStatusPoller.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/ProbeStatuses/ProbeStatusPoller.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/AgentBatchUploadApi.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/BatchUploadApiFactory.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/BatchUploader.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/DebuggerSink.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/IBatchUploadApi.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/IDebuggerSink.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/DebuggerDiagnostics.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/Diagnostics.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeException.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeStatus.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/Status.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/Models/TimedMessage.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/ProbeStatusSink.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Sink/SnapshotSink.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotCreator.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotSerializer.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/ExceptionSnapshotSerializerFieldsAndPropsSelector.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/LazySnapshotSerializerFieldsAndPropsSelector.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/OldStyleTupleSnapshotSerializerFieldsAndPropsSelector.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSerializerFieldsAndPropsSelector.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSummary.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/SupportedTypesService.cs create mode 100644 tracer/src/Datadog.Trace/Debugger/Snapshots/TaskSnapshotSerializerFieldsAndPropsSelector.cs create mode 100644 tracer/src/Datadog.Trace/PDBs/SymbolMethodExtensions.cs create mode 100644 tracer/src/Datadog.Trace/PDBs/dnlibAdditions/DssSymbolReaderImpl.Additions.cs create mode 100644 tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PdbReader.Additions.cs create mode 100644 tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PortablePdbReader.Additions.cs create mode 100644 tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmClient.cs create mode 100644 tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmRequest.cs create mode 100644 tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmResponse.cs create mode 100644 tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTargetFile.cs create mode 100644 tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTracerClient.cs rename tracer/src/Datadog.Trace/{Logging/DirectSubmission/Sink/PeriodicBatching => Util}/BoundedConcurrentQueue.cs (93%) create mode 100644 tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonSelectSettings.cs create mode 100644 tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs create mode 100644 tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/packageIcon.png create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/DumpHeapLive.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertionException.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertions.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerSampleProcessHelper.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerTestHelper.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DeterministicGuidGenerator.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/JsonUtility.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LiveDebuggerTests.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LogEntryWatcher.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/ProbesTests.cs create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.NonSupportedInstrumentationTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt create mode 100644 tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/TrieTests.cs create mode 100644 tracer/test/Datadog.Trace.TestHelpers/MockProbeSnapshot.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/BatchUploaderTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/DebuggerSettingsTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/LiveDebuggerTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/ProbeConfigurationComparerTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/ProbeStatusSinkTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/SupportedTypesServiceTests.cs create mode 100644 tracer/test/Datadog.Trace.Tests/Debugger/TimeLord.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/IAsyncRun.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/IRun.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/LineProbeTestDataAttribute.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/MethodProbeTestDataAttribute.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/ProbeAttributeBase.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Program.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Properties/launchSettings.json create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Samples.Probes.csproj create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Shared/Address.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Shared/Generic.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Shared/IGeneric.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Shared/IntentionalDebuggerException.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/Shared/Person.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SimpleHttpListener.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/AsyncInstanceMethod.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/Emit100LineProbeSnapshotsTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/GenericMethodWithArgumentsAndLocals.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasArgumentsAndLocals.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasException.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueInitialized.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueNotInitialized.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalListOfObjects.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskCompleted.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskNotCompleted.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndArgumentsInGenericType.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndReturnValue.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasReturnValue.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasVarAndMvar.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceMethodWithArguments.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceVoidMethod.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/LineProbesWithRevertTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MethodThrowExceptionTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultiScopesWithSameLocalNameTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultipleLineProbes.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/NonSupportedInstrumentationTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OpenGenericMethodInDerivedGenericType.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OverloadAndSimpleNameTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameInGlobalNamespaceTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameInGlobalNamespaceTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameTest.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticMethodWithArguments.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticType.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticVoidMethod.cs create mode 100644 tracer/test/test-applications/debugger/Samples.Probes/probes_definition.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 946ab48eb..35737b5de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,9 @@ jobs: runs-on: ${{ matrix.machine }} timeout-minutes: 30 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: @@ -164,6 +167,9 @@ jobs: runs-on: ${{ matrix.machine }} timeout-minutes: 30 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: @@ -232,6 +238,9 @@ jobs: runs-on: ${{ matrix.machine }} timeout-minutes: 30 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: @@ -303,6 +312,9 @@ jobs: runs-on: ${{ matrix.machine }} timeout-minutes: 60 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: @@ -420,6 +432,9 @@ jobs: framework: [ net461, netcoreapp3.1 ] timeout-minutes: 60 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: @@ -466,6 +481,9 @@ jobs: framework: [ net461, netcoreapp3.1 ] timeout-minutes: 60 steps: + - name: Support Windows long paths + if: ${{ runner.os == 'Windows' }} + run: git config --system core.longpaths true - uses: actions/checkout@v3.0.2 - uses: actions/setup-dotnet@v2.1.0 with: diff --git a/Datadog.Trace.Debugger.slnf b/Datadog.Trace.Debugger.slnf new file mode 100644 index 000000000..514856280 --- /dev/null +++ b/Datadog.Trace.Debugger.slnf @@ -0,0 +1,19 @@ +{ + "solution": { + "path": "Datadog.Trace.sln", + "projects": [ + "tracer\\src\\Datadog.AutoInstrumentation.NativeLoader\\Datadog.AutoInstrumentation.NativeLoader.vcxproj", + "tracer\\src\\Datadog.Trace.ClrProfiler.Native\\Datadog.Trace.ClrProfiler.Native.DLL.vcxproj", + "tracer\\src\\Datadog.Trace.ClrProfiler.Native\\Datadog.Trace.ClrProfiler.Native.vcxproj", + "tracer\\src\\Datadog.Trace.SourceGenerators\\Datadog.Trace.SourceGenerators.csproj", + "tracer\\src\\Datadog.Trace.Tools.Analyzers\\Datadog.Trace.Tools.Analyzers.csproj", + "tracer\\src\\Datadog.Trace\\Datadog.Trace.csproj", + "tracer\\test\\Datadog.Trace.ClrProfiler.IntegrationTests\\Datadog.Trace.ClrProfiler.IntegrationTests.csproj", + "tracer\\test\\Datadog.Trace.TestHelpers\\Datadog.Trace.TestHelpers.csproj", + "tracer\\test\\Datadog.Trace.Tests\\Datadog.Trace.Tests.csproj", + "tracer\\test\\test-applications\\debugger\\Samples.Probes\\Samples.Probes.csproj", + "tracer\\build\\_build\\_build.csproj", + "tracer\\src\\Datadog.Trace.Tools.Analyzers\\Datadog.Trace.Tools.Analyzers.csproj" + ] + } +} \ No newline at end of file diff --git a/Datadog.Trace.sln b/Datadog.Trace.sln index 696a87aae..5bf7fbd6a 100644 --- a/Datadog.Trace.sln +++ b/Datadog.Trace.sln @@ -468,9 +468,23 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Datadog.InstrumentedAssembl EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Datadog.InstrumentedAssemblyVerification.Standalone", "tracer\src\Datadog.InstrumentedAssemblyVerification.Standalone\Datadog.InstrumentedAssemblyVerification.Standalone.csproj", "{61FD6A7E-38EB-4B90-A890-DE3205C041B1}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "debugger", "debugger", "{16427BFB-B4C6-46A9-A290-8EA51FF73FEA}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Samples.Probes", "tracer\test\test-applications\debugger\Samples.Probes\Samples.Probes.csproj", "{2BED2D88-0B51-468B-A559-DA7B4BACA00B}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Samples.AspNetMvc5CustomException", "tracer\test\test-applications\aspnet\Samples.AspNetMvc5CustomException\Samples.AspNetMvc5CustomException.csproj", "{F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}" EndProject Global + GlobalSection(SharedMSBuildProjectFiles) = preSolution + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{3c6dd42e-9214-4747-92ba-78de29aace59}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{6d86109f-b7c9-477d-86d7-45735a3a0818}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{7b0822f6-80de-4b49-8125-93975678d0d5}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{99a62ccf-8e7f-4d57-8383-d38c371c8087}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{b6a98887-4a47-4c19-9c6f-d833e24f4b1c}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{bbb60b0f-bf01-4499-936a-4a299a9acfd4}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{f71b1b2d-c3e0-49b6-ac29-b96f45e12d5e}*SharedItemsImports = 4 + tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{fab2b108-e5be-4647-869b-1dc5d362252e}*SharedItemsImports = 4 + EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 @@ -2304,18 +2318,30 @@ Global {61FD6A7E-38EB-4B90-A890-DE3205C041B1}.Release|x64.Build.0 = Release|Any CPU {61FD6A7E-38EB-4B90-A890-DE3205C041B1}.Release|x86.ActiveCfg = Release|Any CPU {61FD6A7E-38EB-4B90-A890-DE3205C041B1}.Release|x86.Build.0 = Release|Any CPU + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|Any CPU.ActiveCfg = Debug|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|Any CPU.Build.0 = Debug|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|x64.ActiveCfg = Debug|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|x64.Build.0 = Debug|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|x86.ActiveCfg = Debug|x86 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Debug|x86.Build.0 = Debug|x86 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|Any CPU.ActiveCfg = Release|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|Any CPU.Build.0 = Release|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|x64.ActiveCfg = Release|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|x64.Build.0 = Release|x64 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|x86.ActiveCfg = Release|x86 + {2BED2D88-0B51-468B-A559-DA7B4BACA00B}.Release|x86.Build.0 = Release|x86 {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x64.ActiveCfg = Debug|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x64.Build.0 = Debug|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x86.ActiveCfg = Debug|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x86.Build.0 = Debug|Any CPU + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x64.ActiveCfg = Debug|x64 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x64.Build.0 = Debug|x64 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x86.ActiveCfg = Debug|x86 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Debug|x86.Build.0 = Debug|x86 {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|Any CPU.ActiveCfg = Release|Any CPU {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|Any CPU.Build.0 = Release|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x64.ActiveCfg = Release|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x64.Build.0 = Release|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x86.ActiveCfg = Release|Any CPU - {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x86.Build.0 = Release|Any CPU + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x64.ActiveCfg = Release|x64 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x64.Build.0 = Release|x64 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x86.ActiveCfg = Release|x86 + {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2488,19 +2514,11 @@ Global {CD816C0C-D116-49A1-93A7-8095594224EB} = {9E5F0022-0A50-40BF-AC6A-C3078585ECAB} {FCE813DE-7BF2-4F63-8303-E92F90780C81} = {9E5F0022-0A50-40BF-AC6A-C3078585ECAB} {61FD6A7E-38EB-4B90-A890-DE3205C041B1} = {9E5F0022-0A50-40BF-AC6A-C3078585ECAB} + {16427BFB-B4C6-46A9-A290-8EA51FF73FEA} = {9518425A-36A5-4B8F-B0B8-6137DB88441D} + {2BED2D88-0B51-468B-A559-DA7B4BACA00B} = {16427BFB-B4C6-46A9-A290-8EA51FF73FEA} {F71B1B2D-C3E0-49B6-AC29-B96F45E12D5E} = {AFA0AB23-64F0-4AC1-9050-6CE8FE06F580} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {160A1D00-1F5B-40F8-A155-621B4459D78F} EndGlobalSection - GlobalSection(SharedMSBuildProjectFiles) = preSolution - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{3c6dd42e-9214-4747-92ba-78de29aace59}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{6d86109f-b7c9-477d-86d7-45735a3a0818}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{7b0822f6-80de-4b49-8125-93975678d0d5}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{99a62ccf-8e7f-4d57-8383-d38c371c8087}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{b6a98887-4a47-4c19-9c6f-d833e24f4b1c}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{bbb60b0f-bf01-4499-936a-4a299a9acfd4}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{f71b1b2d-c3e0-49b6-ac29-b96f45e12d5e}*SharedItemsImports = 4 - tracer\test\test-applications\Samples.Shared\Samples.Shared.projitems*{fab2b108-e5be-4647-869b-1dc5d362252e}*SharedItemsImports = 4 - EndGlobalSection EndGlobal diff --git a/docker-compose.yml b/docker-compose.yml index 85b95fa79..150806f1e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -712,6 +712,7 @@ services: - "8126:8126" environment: - SNAPSHOT_CI=1 + - SNAPSHOT_IGNORED_ATTRS=span_id,trace_id,parent_id,duration,start,metrics.system.pid,meta.runtime-id,metrics.process_id smoke-tests: build: diff --git a/docs/internal/internal-config.md b/docs/internal/internal-config.md index 8da47d24e..7448c3a4d 100644 --- a/docs/internal/internal-config.md +++ b/docs/internal/internal-config.md @@ -72,6 +72,16 @@ These settings should be never used by the users. | `SIGNALFX_LOG_LEVEL` | Sets the log level for serverless. | | | `_SIGNALFX_EXTENSION_PATH` | Sets the lambda extension path. | | | `SIGNALFX_TRACE_X_DATADOG_TAGS_MAX_LENGTH` | Configuration key for the maximum length of an outgoing propagation header's value ("x-datadog-tags") | `512` | +| `SIGNALFX_DEBUGGER_POLL_INTERVAL` | Sets the debugger poll interval (in seconds). | `1` | +| `SIGNALFX_DEBUGGER_SNAPSHOT_URL` | Sets the URL used to query our backend directly for the list of active probes. This can only be used if SIGNALFX_API_KEY is also available. | | +| `SIGNALFX_DEBUGGER_PROBE_FILE` | Sets the probe configuration file full path. Loads the probe configuration from a local file on disk. Useful for local development and testing. | | +| `SIGNALFX_DEBUGGER_ENABLED` | Enabling or disabling the Live Debugger | `false` | +| `SIGNALFX_DEBUGGER_MAX_DEPTH_TO_SERIALIZE` | Sets the max object depth to serialize for probe snapshots. | `1` | +| `SIGNALFX_DEBUGGER_MAX_TIME_TO_SERIALIZE` | Sets the maximum duration (in milliseconds) to run serialization for probe snapshots. | `150` | +| `SIGNALFX_DEBUGGER_UPLOAD_BATCH_SIZE` | Sets the maximum upload batch size. | `100` | +| `SIGNALFX_DEBUGGER_DIAGNOSTICS_INTERVAL` | Sets the interval (in seconds) between sending probe statuses. | `3600` | +| `SIGNALFX_DEBUGGER_UPLOAD_FLUSH_INTERVAL` | Sets the interval (in milliseconds) between flushing statuses. | `0` | +| `SIGNALFX_INTERNAL_DEBUGGER_INSTRUMENT_ALL` | Determine whether to enter "instrument all" mode where the Debugger instrumentation is applied to every jit compiled method. Only useful for testing purposes. | `false` | ## Unpublished settings diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.cpp index 09264161c..0387b8479 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.cpp @@ -31,7 +31,7 @@ using namespace std::chrono_literals; std::mutex LinuxStackFramesCollector::s_signalHandlerInitLock; std::mutex LinuxStackFramesCollector::s_stackWalkInProgressMutex; bool LinuxStackFramesCollector::s_isSignalHandlerSetup = false; -int LinuxStackFramesCollector::s_signalToSend = -1; +int32_t LinuxStackFramesCollector::s_signalToSend = -1; LinuxStackFramesCollector* LinuxStackFramesCollector::s_pInstanceCurrentlyStackWalking = nullptr; LinuxStackFramesCollector::LinuxStackFramesCollector(ICorProfilerInfo4* const _pCorProfilerInfo) : @@ -192,7 +192,7 @@ void LinuxStackFramesCollector::InitializeSignalHandler() s_isSignalHandlerSetup = SetupSignalHandler(); } -bool LinuxStackFramesCollector::TrySetHandlerForSignal(int signal, struct sigaction& action) +bool LinuxStackFramesCollector::TrySetHandlerForSignal(int32_t signal, struct sigaction& action) { struct sigaction oldAction; if (sigaction(signal, nullptr, &oldAction) < 0) @@ -209,7 +209,7 @@ bool LinuxStackFramesCollector::TrySetHandlerForSignal(int signal, struct sigact if (oldAction.sa_handler == SIG_DFL || oldAction.sa_handler == SIG_IGN) { sigaddset(&action.sa_mask, signal); - int result = sigaction(signal, &action, &oldAction); + int32_t result = sigaction(signal, &action, &oldAction); if (result == 0) { return true; @@ -258,7 +258,7 @@ bool LinuxStackFramesCollector::SetupSignalHandler() return false; } -char const* LinuxStackFramesCollector::ErrorCodeToString(int errorCode) +char const* LinuxStackFramesCollector::ErrorCodeToString(int32_t errorCode) { switch (errorCode) { @@ -349,7 +349,7 @@ std::int32_t LinuxStackFramesCollector::CollectCallStackCurrentThread() } } -void LinuxStackFramesCollector::CollectStackSampleSignalHandler(int signal) +void LinuxStackFramesCollector::CollectStackSampleSignalHandler(int32_t signal) { std::unique_lock stackWalkInProgressLock(s_stackWalkInProgressMutex); LinuxStackFramesCollector* pCollectorInstanceCurrentlyStackWalking = s_pInstanceCurrentlyStackWalking; diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.h index 5f44c0bbd..e49aafe34 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/LinuxStackFramesCollector.h @@ -68,14 +68,14 @@ class LinuxStackFramesCollector : public StackFramesCollectorBase ICorProfilerInfo4* const _pCorProfilerInfo; private: - static bool TrySetHandlerForSignal(int signal, struct sigaction& action); - static void CollectStackSampleSignalHandler(int signal); + static bool TrySetHandlerForSignal(int32_t signal, struct sigaction& action); + static void CollectStackSampleSignalHandler(int32_t signal); - static char const* ErrorCodeToString(int errorCode); + static char const* ErrorCodeToString(int32_t errorCode); static std::mutex s_stackWalkInProgressMutex; static std::mutex s_signalHandlerInitLock; static bool s_isSignalHandlerSetup; - static int s_signalToSend; + static int32_t s_signalToSend; static LinuxStackFramesCollector* s_pInstanceCurrentlyStackWalking; diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/OsSpecificApi.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/OsSpecificApi.cpp index c8fe5bf02..e1abb09c3 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/OsSpecificApi.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Linux/OsSpecificApi.cpp @@ -65,8 +65,8 @@ bool GetCpuInfo(pid_t tid, bool& isRunning, uint64_t& cpuTime) } char state = ' '; - int userTime = 0; - int kernelTime = 0; + int32_t userTime = 0; + int32_t kernelTime = 0; bool success = OpSysTools::ParseThreadInfo(sline, state, userTime, kernelTime); if (!success) { diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Windows/OsSpecificApi.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Windows/OsSpecificApi.cpp index a27d34626..ded5e4535 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Windows/OsSpecificApi.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native.Windows/OsSpecificApi.cpp @@ -138,7 +138,7 @@ bool IsRunning(ManagedThreadInfo* pThreadInfo, uint64_t& cpuTime) SYSTEM_THREAD_INFORMATION sti = {0}; auto size = sizeof(SYSTEM_THREAD_INFORMATION); ULONG buflen = 0; - NTSTATUS lResult = NtQueryInformationThread(pThreadInfo->GetOsThreadHandle(), SYSTEMTHREADINFORMATION, &sti, size, &buflen); + NTSTATUS lResult = NtQueryInformationThread(pThreadInfo->GetOsThreadHandle(), SYSTEMTHREADINFORMATION, &sti, static_cast(size), &buflen); if (lResult != 0) { // This always happens in 32 bit so uses another API to at least get the CPU consumption diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/AdaptiveSampler.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/AdaptiveSampler.cpp index 2b0be9e27..087f54b73 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/AdaptiveSampler.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/AdaptiveSampler.cpp @@ -162,11 +162,11 @@ void AdaptiveSampler::RollWindow() if (_totalCountRunningAverage == 0 || _emaAlpha <= 0.0) { - _totalCountRunningAverage = totalCount; + _totalCountRunningAverage = static_cast(totalCount); } else { - _totalCountRunningAverage = _totalCountRunningAverage + _emaAlpha * (totalCount - _totalCountRunningAverage); + _totalCountRunningAverage = _totalCountRunningAverage + _emaAlpha * (static_cast(totalCount) - _totalCountRunningAverage); } if (_totalCountRunningAverage <= 0) diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.cpp index 2ba15adb5..6f1e6cd94 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.cpp @@ -22,7 +22,7 @@ std::string const Configuration::DefaultProdSite = "datadoghq.com"; std::string const Configuration::DefaultVersion = "Unspecified-Version"; std::string const Configuration::DefaultEnvironment = "Unspecified-Environment"; std::string const Configuration::DefaultAgentHost = "localhost"; -int const Configuration::DefaultAgentPort = 8126; +int32_t const Configuration::DefaultAgentPort = 8126; std::string const Configuration::DefaultEmptyString = ""; std::chrono::seconds const Configuration::DefaultDevUploadInterval = 20s; std::chrono::seconds const Configuration::DefaultProdUploadInterval = 60s; @@ -105,7 +105,7 @@ bool Configuration::IsExceptionProfilingEnabled() const return _isExceptionProfilingEnabled; } -int Configuration::ExceptionSampleLimit() const +int32_t Configuration::ExceptionSampleLimit() const { return _exceptionSampleLimit; } @@ -150,7 +150,7 @@ std::string const& Configuration::GetAgentHost() const return _agentHost; } -int Configuration::GetAgentPort() const +int32_t Configuration::GetAgentPort() const { return _agentPort; } @@ -241,7 +241,7 @@ std::chrono::seconds Configuration::GetDefaultUploadInterval() // - replace shared::TryParse by this implementation // - add tests -bool TryParse(shared::WSTRING const& s, int& result) +bool TryParse(shared::WSTRING const& s, int32_t& result) { auto str = shared::ToString(s); if (str == "") @@ -266,7 +266,7 @@ bool TryParse(shared::WSTRING const& s, int& result) std::chrono::seconds Configuration::ExtractUploadInterval() { auto r = shared::GetEnvironmentValue(EnvironmentVariables::UploadInterval); - int interval; + int32_t interval; if (TryParse(r, interval)) { return std::chrono::seconds(interval); @@ -305,7 +305,7 @@ bool convert_to(shared::WSTRING const& s, shared::WSTRING& result) return true; } -bool convert_to(shared::WSTRING const& s, int& result) +bool convert_to(shared::WSTRING const& s, int32_t& result) { return TryParse(s, result); } diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.h index 882c91572..3973dcb93 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Configuration.h @@ -32,7 +32,7 @@ class Configuration final : public IConfiguration std::string const& GetHostname() const override; std::string const& GetAgentUrl() const override; std::string const& GetAgentHost() const override; - int GetAgentPort() const override; + int32_t GetAgentPort() const override; bool IsAgentless() const override; std::string const& GetSite() const override; std::string const& GetApiKey() const override; @@ -40,7 +40,7 @@ class Configuration final : public IConfiguration bool IsCpuProfilingEnabled() const override; bool IsWallTimeProfilingEnabled() const override; bool IsExceptionProfilingEnabled() const override; - int ExceptionSampleLimit() const override; + int32_t ExceptionSampleLimit() const override; private: static tags ExtractUserTags(); @@ -63,7 +63,7 @@ class Configuration final : public IConfiguration static std::string const DefaultEnvironment; static std::string const DefaultAgentHost; static std::string const DefaultEmptyString; - static int const DefaultAgentPort; + static int32_t const DefaultAgentPort; static std::chrono::seconds const DefaultDevUploadInterval; static std::chrono::seconds const DefaultProdUploadInterval; @@ -88,5 +88,5 @@ class Configuration final : public IConfiguration tags _userTags; bool _isNativeFrameEnabled; bool _isAgentLess; - int _exceptionSampleLimit; + int32_t _exceptionSampleLimit; }; diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.cpp index 72d3635a9..c6415587c 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.cpp @@ -17,7 +17,7 @@ /// - Add a conversion to DogFood::MetricType in the Convert function : /// Add a new `if constexpr(...)` statement in Convert() for the new metric type -DogstatsdService::DogstatsdService(const std::string& host, int port, const Tags& tags) : +DogstatsdService::DogstatsdService(const std::string& host, int32_t port, const Tags& tags) : _commonTags{tags}, _host{host}, _port{port} diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.h index 52ccc7a59..c8af118f7 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/DogstatsdService.h @@ -11,7 +11,7 @@ class DogstatsdService : public IMetricsSender { public: - DogstatsdService(const std::string& host, int port, const Tags& tags); + DogstatsdService(const std::string& host, int32_t port, const Tags& tags); ~DogstatsdService() override = default; bool Gauge(const std::string& name, double value) override; @@ -29,5 +29,5 @@ class DogstatsdService : public IMetricsSender private: const Tags _commonTags; const std::string _host; - int _port; + int32_t _port; }; \ No newline at end of file diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.cpp index b7c0224d8..0917b11d7 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.cpp @@ -35,14 +35,14 @@ void ExceptionSampler::RollWindow() _knownExceptions.clear(); } -int ExceptionSampler::SamplingWindowsPerRecording(const IConfiguration* configuration) +int32_t ExceptionSampler::SamplingWindowsPerRecording(const IConfiguration* configuration) { const auto uploadIntervalMs = std::chrono::duration_cast(configuration->GetUploadInterval()); const auto samplingWindowMs = std::chrono::duration_cast(SamplingWindow); - return static_cast(std::min(uploadIntervalMs / samplingWindowMs, INT32_MAX)); + return static_cast(std::min(uploadIntervalMs / samplingWindowMs, INT32_MAX)); } -int ExceptionSampler::SamplesPerWindow(const IConfiguration* configuration) +int32_t ExceptionSampler::SamplesPerWindow(const IConfiguration* configuration) { return configuration->ExceptionSampleLimit() / SamplingWindowsPerRecording(configuration); } diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.h index f1867c282..04871deaf 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ExceptionSampler.h @@ -20,6 +20,6 @@ class ExceptionSampler std::mutex _knownExceptionsMutex; void RollWindow(); - int SamplingWindowsPerRecording(const IConfiguration* configuration); - int SamplesPerWindow(const IConfiguration* configuration); + int32_t SamplingWindowsPerRecording(const IConfiguration* configuration); + int32_t SamplesPerWindow(const IConfiguration* configuration); }; diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/IConfiguration.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/IConfiguration.h index 1848b1eeb..064bdb4c0 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/IConfiguration.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/IConfiguration.h @@ -28,7 +28,7 @@ class IConfiguration virtual std::string const& GetHostname() const = 0; virtual std::string const& GetAgentUrl() const = 0; virtual std::string const& GetAgentHost() const = 0; - virtual int GetAgentPort() const = 0; + virtual int32_t GetAgentPort() const = 0; virtual bool IsAgentless() const = 0; virtual std::string const& GetSite() const = 0; virtual std::string const& GetApiKey() const = 0; @@ -37,5 +37,5 @@ class IConfiguration virtual bool IsCpuProfilingEnabled() const = 0; virtual bool IsWallTimeProfilingEnabled() const = 0; virtual bool IsExceptionProfilingEnabled() const = 0; - virtual int ExceptionSampleLimit() const = 0; + virtual int32_t ExceptionSampleLimit() const = 0; }; \ No newline at end of file diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/LibddprofExporter.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/LibddprofExporter.cpp index fa6a80147..ee9ab5f7e 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/LibddprofExporter.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/LibddprofExporter.cpp @@ -36,7 +36,7 @@ tags LibddprofExporter::CommonTags = { // need to be static so it leave longer for the shared library std::string const LibddprofExporter::ProcessId = std::to_string(OpSysTools::GetProcId()); -int const LibddprofExporter::RequestTimeOutMs = 10000; +int32_t const LibddprofExporter::RequestTimeOutMs = 10000; std::string const LibddprofExporter::LanguageFamily = "dotnet"; @@ -229,7 +229,7 @@ bool LibddprofExporter::Export() { bool exported = false; - int idx = 0; + int32_t idx = 0; for (auto& [runtimeId, profileInfo] : _perAppInfo) { auto samplesCount = profileInfo.samplesCount; @@ -292,7 +292,7 @@ bool LibddprofExporter::Export() return exported; } -std::string LibddprofExporter::GeneratePprofFilePath(const std::string& applicationName, int idx) const +std::string LibddprofExporter::GeneratePprofFilePath(const std::string& applicationName, int32_t idx) const { auto time = std::time(nullptr); struct tm buf = {}; @@ -313,7 +313,7 @@ std::string LibddprofExporter::GeneratePprofFilePath(const std::string& applicat return pprofFilePath.string(); } -void LibddprofExporter::ExportToDisk(const std::string& applicationName, SerializedProfile const& encodedProfile, int idx) +void LibddprofExporter::ExportToDisk(const std::string& applicationName, SerializedProfile const& encodedProfile, int32_t idx) { auto pprofFilePath = GeneratePprofFilePath(applicationName, idx); diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ManagedThreadInfo.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ManagedThreadInfo.h index 283eb6a91..3d2b9c87c 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ManagedThreadInfo.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ManagedThreadInfo.h @@ -13,8 +13,8 @@ #include "shared/src/native-src/string.h" -static constexpr int MinFieldAlignRequirement = 8; -static constexpr int FieldAlignRequirement = (MinFieldAlignRequirement >= alignof(std::uint64_t)) ? MinFieldAlignRequirement : alignof(std::uint64_t); +static constexpr int32_t MinFieldAlignRequirement = 8; +static constexpr int32_t FieldAlignRequirement = (MinFieldAlignRequirement >= alignof(std::uint64_t)) ? MinFieldAlignRequirement : alignof(std::uint64_t); struct alignas(FieldAlignRequirement) TraceContextTrackingInfo { diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.cpp index b9e704535..aee102938 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.cpp @@ -42,7 +42,7 @@ OpSysTools::SetThreadDescriptionDelegate_t OpSysTools::s_setThreadDescriptionDel OpSysTools::GetThreadDescriptionDelegate_t OpSysTools::s_getThreadDescriptionDelegate = nullptr; #endif -int OpSysTools::GetProcId() +int32_t OpSysTools::GetProcId() { #ifdef _WINDOWS return ::GetCurrentProcessId(); @@ -51,7 +51,7 @@ int OpSysTools::GetProcId() #endif } -int OpSysTools::GetThreadId() +int32_t OpSysTools::GetThreadId() { #ifdef _WINDOWS return ::GetCurrentThreadId(); @@ -97,7 +97,7 @@ std::int64_t OpSysTools::GetHighPrecisionNanosecondsFallback(void) { std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now(); - long long totalNanosecs = std::chrono::duration_cast(now.time_since_epoch()).count(); + int64_t totalNanosecs = std::chrono::duration_cast(now.time_since_epoch()).count(); return static_cast(totalNanosecs); } @@ -320,7 +320,7 @@ std::string OpSysTools::GetProcessName() const DWORD len = GetModuleFileNameA(nullptr, pathName, length); return fs::path(pathName).filename().string(); #elif MACOS - const int length = 260; + const int32_t length = 260; char* buffer = new char[length]; proc_name(getpid(), buffer, length); return std::string(buffer); diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.h index a07ce9dbd..d761e1e3f 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/OpSysTools.h @@ -16,8 +16,8 @@ class OpSysTools final { public: - static int GetProcId(); - static int GetThreadId(); + static int32_t GetProcId(); + static int32_t GetThreadId(); // static std::string UnicodeToAnsi(const WCHAR* str); /// @@ -48,7 +48,7 @@ class OpSysTools final static std::string GetHostname(); static std::string GetProcessName(); - static bool ParseThreadInfo(std::string line, char& state, int& userTime, int& kernelTime) + static bool ParseThreadInfo(std::string line, char& state, int32_t& userTime, int32_t& kernelTime) { // based on https://linux.die.net/man/5/proc // state = 3rd position and 'R' for Running diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ProfilerEngineStatus.h b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ProfilerEngineStatus.h index 932e3ab53..7786968d8 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ProfilerEngineStatus.h +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/ProfilerEngineStatus.h @@ -9,13 +9,13 @@ class ProfilerEngineStatus { private: // The memory for the IsProfilerEngineActive is allocated on the heap and must be properly aligned to ensure fast atomic operations. - static constexpr int MinimalAlignmentOf_IsProfilerEngineActive = 8; - static constexpr int ActualAlignmentOf_IsProfilerEngineActive = (MinimalAlignmentOf_IsProfilerEngineActive >= alignof(bool)) + static constexpr int32_t MinimalAlignmentOf_IsProfilerEngineActive = 8; + static constexpr int32_t ActualAlignmentOf_IsProfilerEngineActive = (MinimalAlignmentOf_IsProfilerEngineActive >= alignof(bool)) ? MinimalAlignmentOf_IsProfilerEngineActive : alignof(bool); // We will allocate a memory chunk that is at least as big as the alignment, even if we do not need all of that. - static constexpr int SizeOf_IsProfilerEngineActive = (ActualAlignmentOf_IsProfilerEngineActive >= sizeof(bool)) + static constexpr int32_t SizeOf_IsProfilerEngineActive = (ActualAlignmentOf_IsProfilerEngineActive >= sizeof(bool)) ? ActualAlignmentOf_IsProfilerEngineActive : sizeof(bool); diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackSamplerLoop.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackSamplerLoop.cpp index 89693f2fd..a61025bc4 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackSamplerLoop.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/StackSamplerLoop.cpp @@ -176,10 +176,10 @@ void StackSamplerLoop::MainLoopIteration(void) void StackSamplerLoop::WalltimeProfilingIteration(void) { - int managedThreadsCount = _pManagedThreadList->Count(); - int sampledThreadsCount = (std::min)(managedThreadsCount, MaxThreadsPerIterationForWallTime); + int32_t managedThreadsCount = _pManagedThreadList->Count(); + int32_t sampledThreadsCount = (std::min)(managedThreadsCount, MaxThreadsPerIterationForWallTime); - for (int i = 0; i < sampledThreadsCount && !_shutdownRequested; i++) + for (int32_t i = 0; i < sampledThreadsCount && !_shutdownRequested; i++) { _targetThread = _pManagedThreadList->LoopNext(_iteratorWallTime); if (_targetThread != nullptr) @@ -207,11 +207,11 @@ void StackSamplerLoop::WalltimeProfilingIteration(void) void StackSamplerLoop::CpuProfilingIteration(void) { - int managedThreadsCount = _pManagedThreadList->Count(); + int32_t managedThreadsCount = _pManagedThreadList->Count(); // TODO: as an optimization, don't scan more threads than nb logical cores - int sampledThreadsCount = (std::min)(managedThreadsCount, MaxThreadsPerIterationForCpuTime); + int32_t sampledThreadsCount = (std::min)(managedThreadsCount, MaxThreadsPerIterationForCpuTime); - for (int i = 0; i < sampledThreadsCount && !_shutdownRequested; i++) + for (int32_t i = 0; i < sampledThreadsCount && !_shutdownRequested; i++) { _targetThread = _pManagedThreadList->LoopNext(_iteratorCpuTime); if (_targetThread != nullptr) diff --git a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Timer.Windows.cpp b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Timer.Windows.cpp index bf731721c..055e2a2b7 100644 --- a/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Timer.Windows.cpp +++ b/profiler/src/ProfilerEngine/Datadog.Profiler.Native/Timer.Windows.cpp @@ -38,7 +38,7 @@ void Timer::Start() dueTime.dwHighDateTime = rawDueTime.HighPart; dueTime.dwLowDateTime = rawDueTime.LowPart; - SetThreadpoolTimer(_internalTimer, &dueTime, _period.count(), 100); + SetThreadpoolTimer(_internalTimer, &dueTime, static_cast(_period.count()), 100); } void NTAPI Timer::OnTick( diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/CodeHotspot/BuggyBitsTest.cs b/profiler/test/Datadog.Profiler.IntegrationTests/CodeHotspot/BuggyBitsTest.cs index 1194f54fa..dab2e383d 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/CodeHotspot/BuggyBitsTest.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/CodeHotspot/BuggyBitsTest.cs @@ -29,7 +29,7 @@ public BuggyBitsTest(ITestOutputHelper output) _output = output; } - [TestAppFact("Samples.BuggyBits", DisplayName = "BuggyBits")] + [TestAppFact("Samples.BuggyBits")] public void CheckSpanContextAreAttached(string appName, string framework, string appAssembly) { var runner = new TestApplicationRunner(appName, framework, appAssembly, _output, enableTracer: true); @@ -73,7 +73,7 @@ public void CheckSpanContextAreAttached(string appName, string framework, string // profiler was a subset. But this makes the test flacky: not flushed when the application is closing. } - [TestAppFact("Samples.BuggyBits", DisplayName = "BuggyBits")] + [TestAppFact("Samples.BuggyBits")] public void NoTraceContextAttachedIfFeatureDeactivated(string appName, string framework, string appAssembly) { var runner = new TestApplicationRunner(appName, framework, appAssembly, _output, enableTracer: true); diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/CpuProfiler/CpuProfilerTest.cs b/profiler/test/Datadog.Profiler.IntegrationTests/CpuProfiler/CpuProfilerTest.cs index 9b39c84fc..982b715a3 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/CpuProfiler/CpuProfilerTest.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/CpuProfiler/CpuProfilerTest.cs @@ -23,14 +23,14 @@ public CpuProfilerTest(ITestOutputHelper output) _output = output; } - [TestAppFact("Samples.Computer01", DisplayName = "Computer01")] + [TestAppFact("Samples.Computer01")] public void NoCpuSampleIfCpuProfilerIsNotActivatedByDefault(string appName, string framework, string appAssembly) { var runner = new TestApplicationRunner(appName, framework, appAssembly, _output, commandLine: CmdLine); CheckCpuProfiles(runner, false); } - [TestAppFact("Samples.Computer01", DisplayName = "Computer01")] + [TestAppFact("Samples.Computer01")] public void NoCpuSampleIfCpuProfilerIsDeactivated(string appName, string framework, string appAssembly) { var runner = new TestApplicationRunner(appName, framework, appAssembly, _output, commandLine: CmdLine); @@ -38,7 +38,7 @@ public void NoCpuSampleIfCpuProfilerIsDeactivated(string appName, string framewo CheckCpuProfiles(runner, false); } - [TestAppFact("Samples.Computer01", DisplayName = "Computer01")] + [TestAppFact("Samples.Computer01")] public void GetCpuSamplesIfCpuProfilerIsActivated(string appName, string framework, string appAssembly) { var runner = new TestApplicationRunner(appName, framework, appAssembly, _output, commandLine: CmdLine); diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/BuggyBitsTest.cs b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/BuggyBitsTest.cs index 03101a743..af9d3ae45 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/BuggyBitsTest.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/BuggyBitsTest.cs @@ -16,7 +16,7 @@ public BuggyBitsTest(ITestOutputHelper output) _output = output; } - [TestAppFact("Samples.BuggyBits", DisplayName = "BuggyBits")] + [TestAppFact("Samples.BuggyBits")] public void CheckSmoke(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, _output); diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/Computer01Test.cs b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/Computer01Test.cs index 801c0b9e4..011d4cc7f 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/Computer01Test.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/Computer01Test.cs @@ -26,28 +26,28 @@ public Computer01Test(ITestOutputHelper output) // 4: start a thread to compute pi at a certain precision(high CPU usage) // 5: start a to compute fibonacci (high CPU usage + deep stacks) // ----------------------------------------------------------------------------------------- - [TestAppFact("Samples.Computer01", DisplayName = "AppDomain")] + [TestAppFact("Samples.Computer01")] public void CheckAppDomain(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, commandLine: "--scenario 1", _output); runner.RunAndCheck(); } - [TestAppFact("Samples.Computer01", DisplayName = "Generics")] + [TestAppFact("Samples.Computer01")] public void CheckGenerics(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, commandLine: "--scenario 2", _output); runner.RunAndCheck(); } - [TestAppFact("Samples.Computer01", DisplayName = "Pi")] + [TestAppFact("Samples.Computer01")] public void CheckPi(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, commandLine: "--scenario 4", _output); runner.RunAndCheck(); } - [TestAppFact("Samples.Computer01", DisplayName = "Fibonacci")] + [TestAppFact("Samples.Computer01")] public void CheckFibonacci(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, commandLine: "--scenario 5", _output); diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/ExceptionGeneratorTest.cs b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/ExceptionGeneratorTest.cs index 76ba31236..44c6cf4a8 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/ExceptionGeneratorTest.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/ExceptionGeneratorTest.cs @@ -16,7 +16,7 @@ public ExceptionGeneratorTest(ITestOutputHelper output) _output = output; } - [TestAppFact("Samples.ExceptionGenerator", DisplayName = "ExceptionGenerator")] + [TestAppFact("Samples.ExceptionGenerator")] public void CheckSmoke(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, _output); diff --git a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/WebsiteAspNetCore01Test.cs b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/WebsiteAspNetCore01Test.cs index 463026e48..3c87fc7ee 100644 --- a/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/WebsiteAspNetCore01Test.cs +++ b/profiler/test/Datadog.Profiler.IntegrationTests/SmokeTests/WebsiteAspNetCore01Test.cs @@ -16,7 +16,7 @@ public WebsiteAspNetCore01Test(ITestOutputHelper output) _output = output; } - [TestAppFact("Samples.Website-AspNetCore01", DisplayName = "Website-AspNetCore01")] + [TestAppFact("Samples.Website-AspNetCore01")] public void CheckSmoke(string appName, string framework, string appAssembly) { var runner = new SmokeTestRunner(appName, framework, appAssembly, _output); diff --git a/profiler/test/Datadog.Profiler.Native.Tests/HResultConverterTest.cpp b/profiler/test/Datadog.Profiler.Native.Tests/HResultConverterTest.cpp index 893349016..c91434247 100644 --- a/profiler/test/Datadog.Profiler.Native.Tests/HResultConverterTest.cpp +++ b/profiler/test/Datadog.Profiler.Native.Tests/HResultConverterTest.cpp @@ -22,7 +22,7 @@ TEST_P(HResultConverterParametersTests, CheckMessageForHresult) EXPECT_STREQ(expectedMessage, HResultConverter::ToChars(code)); } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( HResultConverterTests, HResultConverterParametersTests, ::testing::Values( diff --git a/profiler/test/Datadog.Profiler.Native.Tests/IMetricsSenderFactoryTest.cpp b/profiler/test/Datadog.Profiler.Native.Tests/IMetricsSenderFactoryTest.cpp index 9a2142f3e..8e4e279f9 100644 --- a/profiler/test/Datadog.Profiler.Native.Tests/IMetricsSenderFactoryTest.cpp +++ b/profiler/test/Datadog.Profiler.Native.Tests/IMetricsSenderFactoryTest.cpp @@ -8,12 +8,12 @@ #include "IMetricsSender.h" #include "IMetricsSenderFactory.h" -#include "string.h" +#include "shared/src/native-src/util.h" TEST(IMetricsSenderFactoryTest, MustReturnNullIfEnvVarNotSet) -{ - auto envVarValue = std::getenv(shared::ToString(EnvironmentVariables::OperationalMetricsEnabled).c_str()); - EXPECT_TRUE(envVarValue == nullptr); +{ + auto envVarValue = shared::GetEnvironmentValue(EnvironmentVariables::OperationalMetricsEnabled); + EXPECT_TRUE(envVarValue.length() == 0); auto metricsSender = IMetricsSenderFactory::Create(); EXPECT_TRUE(metricsSender == nullptr); diff --git a/shared/src/native-src/string.cpp b/shared/src/native-src/string.cpp index d0a98d3b8..e2c0e887b 100644 --- a/shared/src/native-src/string.cpp +++ b/shared/src/native-src/string.cpp @@ -78,4 +78,9 @@ namespace shared { return false; } + bool EndsWith(const std::string& str, const std::string& suffix) + { + return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; + } + } // namespace trace \ No newline at end of file diff --git a/shared/src/native-src/string.h b/shared/src/native-src/string.h index b0ce69467..53ca11198 100644 --- a/shared/src/native-src/string.h +++ b/shared/src/native-src/string.h @@ -31,6 +31,8 @@ namespace shared { bool TryParse(WSTRING const& s, int& result); + bool EndsWith(const std::string& str, const std::string& suffix); + template std::basic_string ReplaceString(std::basic_string subject, const std::basic_string& search, const std::basic_string& replace) { size_t pos = 0; diff --git a/tracer/Datadog.Trace.proj b/tracer/Datadog.Trace.proj index f97810615..fef70e5f8 100644 --- a/tracer/Datadog.Trace.proj +++ b/tracer/Datadog.Trace.proj @@ -19,6 +19,7 @@ + @@ -62,6 +63,7 @@ + diff --git a/tracer/build/PackageVersionsGeneratorDefinitions.json b/tracer/build/PackageVersionsGeneratorDefinitions.json index 6b4fd8b5f..81535d18d 100644 --- a/tracer/build/PackageVersionsGeneratorDefinitions.json +++ b/tracer/build/PackageVersionsGeneratorDefinitions.json @@ -81,6 +81,10 @@ "5.*.*" ], "VersionConditions": [{ + "MinVersion": "5.0.0", + "MaxVersionExclusive": "5.1.1", + "ExcludeTargetFrameworks": ["net461", "netcoreapp2.1", "netcoreapp3.0", "netcoreapp3.1", "net5.0", "net6.0"] + },{ "MaxVersionExclusive": "6.0.0", "ExcludeTargetFrameworks": ["net461", "netcoreapp2.1", "netcoreapp3.0"] }] @@ -266,7 +270,11 @@ "SpecificVersions": [ "3.6.*", "3.*.*" - ] + ], + "VersionConditions": [{ + "MinVersion": "3.29.0", + "ExcludeTargetFrameworks": ["netcoreapp2.1", "netcoreapp3.0"] + }] }, { "IntegrationName": "Serilog", diff --git a/tracer/build/PackageVersionsLatestMajors.g.props b/tracer/build/PackageVersionsLatestMajors.g.props index b2eb4c13c..770d1fffe 100644 --- a/tracer/build/PackageVersionsLatestMajors.g.props +++ b/tracer/build/PackageVersionsLatestMajors.g.props @@ -13,62 +13,62 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net461 True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net5.0 True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net6.0 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net461 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -168,7 +168,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -178,7 +178,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -188,7 +188,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -738,7 +738,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -753,7 +753,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -768,7 +768,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -783,7 +783,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -798,7 +798,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -813,7 +813,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -823,7 +823,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -833,7 +833,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -843,7 +843,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -853,7 +853,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -863,7 +863,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -873,7 +873,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -883,7 +883,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -893,7 +893,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -903,7 +903,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -913,7 +913,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -923,7 +923,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -933,7 +933,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1058,7 +1058,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -1073,17 +1073,17 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1243,7 +1243,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -1253,7 +1253,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -1263,7 +1263,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -1273,7 +1273,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -1283,7 +1283,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -1318,7 +1318,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -1333,17 +1333,17 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 True diff --git a/tracer/build/PackageVersionsLatestMinors.g.props b/tracer/build/PackageVersionsLatestMinors.g.props index 5dd04add8..150c3d9de 100644 --- a/tracer/build/PackageVersionsLatestMinors.g.props +++ b/tracer/build/PackageVersionsLatestMinors.g.props @@ -28,7 +28,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -43,7 +43,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -58,7 +58,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -73,7 +73,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -88,7 +88,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -103,7 +103,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -192,6 +192,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net461 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + net461 + True + ApiVersion=2.3.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 @@ -262,6 +267,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp2.1 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp2.1 + True + ApiVersion=2.3.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 @@ -332,6 +342,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.0 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp3.0 + True + ApiVersion=2.3.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 @@ -402,6 +417,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.1 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp3.1 + True + ApiVersion=2.3.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 @@ -472,6 +492,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net5.0 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + net5.0 + True + ApiVersion=2.3.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 @@ -542,6 +567,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net6.0 True + + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false + net6.0 + True + ApiVersion=7.0.1;RestoreRecursive=false;BuildProjectReferences=false net461 @@ -1512,11 +1542,6 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.1 False - - ApiVersion=5.0.0;RestoreRecursive=false;BuildProjectReferences=false - netcoreapp3.1 - False - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 @@ -1528,7 +1553,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -1572,11 +1597,6 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net5.0 False - - ApiVersion=5.0.0;RestoreRecursive=false;BuildProjectReferences=false - net5.0 - False - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false net5.0 @@ -1588,7 +1608,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -1632,11 +1652,6 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net6.0 False - - ApiVersion=5.0.0;RestoreRecursive=false;BuildProjectReferences=false - net6.0 - False - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false net6.0 @@ -1648,7 +1663,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -3428,7 +3443,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -3503,7 +3518,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -3578,7 +3593,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -3653,7 +3668,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -3728,7 +3743,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -3803,7 +3818,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -3828,7 +3843,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -3838,7 +3853,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -3863,7 +3878,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -3873,7 +3888,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -3898,7 +3913,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -3908,7 +3923,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -3933,7 +3948,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -3943,7 +3958,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -3968,7 +3983,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -3978,7 +3993,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -4003,7 +4018,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -4013,7 +4028,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -4732,6 +4747,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net461 False + + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false + net461 + False + ApiVersion=3.6.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 @@ -5077,6 +5097,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.1 False + + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp3.1 + False + ApiVersion=3.6.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 @@ -5192,6 +5217,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net5.0 False + + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false + net5.0 + False + ApiVersion=3.6.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 @@ -5307,6 +5337,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net6.0 False + + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false + net6.0 + False + ApiVersion=1.0.3;RestoreRecursive=false;BuildProjectReferences=false net461 @@ -5947,6 +5982,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp2.1 True + + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp2.1 + True + ApiVersion=4.0.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 @@ -5972,6 +6012,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.0 True + + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp3.0 + True + ApiVersion=4.0.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 @@ -5997,6 +6042,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely netcoreapp3.1 True + + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false + netcoreapp3.1 + True + ApiVersion=4.0.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 @@ -6022,6 +6072,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net5.0 True + + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false + net5.0 + True + ApiVersion=4.0.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 @@ -6047,6 +6102,11 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely net6.0 True + + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false + net6.0 + True + ApiVersion=2.4.8;RestoreRecursive=false;BuildProjectReferences=false net461 @@ -6183,7 +6243,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -6233,7 +6293,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -6253,7 +6313,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -6273,7 +6333,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 True diff --git a/tracer/build/PackageVersionsLatestSpecific.g.props b/tracer/build/PackageVersionsLatestSpecific.g.props index c2bcc29bb..b174ed0bd 100644 --- a/tracer/build/PackageVersionsLatestSpecific.g.props +++ b/tracer/build/PackageVersionsLatestSpecific.g.props @@ -23,7 +23,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -33,7 +33,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -43,7 +43,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -53,7 +53,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -63,7 +63,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -73,7 +73,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.7.2.74;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.7.2.80;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -93,7 +93,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -108,7 +108,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -123,7 +123,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -138,7 +138,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -153,7 +153,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -168,7 +168,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.16.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.17.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -428,7 +428,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -448,7 +448,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -468,7 +468,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=5.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1118,7 +1118,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -1138,7 +1138,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -1158,7 +1158,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -1178,7 +1178,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -1198,7 +1198,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -1218,7 +1218,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=2.1.10;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=2.1.11;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -1228,7 +1228,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -1238,7 +1238,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -1248,7 +1248,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -1258,7 +1258,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 False @@ -1268,7 +1268,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -1278,7 +1278,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 False @@ -1288,7 +1288,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -1298,7 +1298,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -1308,7 +1308,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -1318,7 +1318,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -1328,7 +1328,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.1.26;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.1.27;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1338,7 +1338,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=6.0.6;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=6.0.7;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1618,7 +1618,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net461 False @@ -1648,7 +1648,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 False @@ -1658,7 +1658,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 False @@ -1668,7 +1668,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely False - ApiVersion=3.28.0;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.29.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 False @@ -1843,7 +1843,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp2.1 True @@ -1858,7 +1858,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.0 True @@ -1873,7 +1873,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -1888,7 +1888,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -1903,7 +1903,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=5.1.1;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=5.2.0;RestoreRecursive=false;BuildProjectReferences=false net6.0 True @@ -1973,7 +1973,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net461 True @@ -2003,7 +2003,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false netcoreapp3.1 True @@ -2013,7 +2013,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net5.0 True @@ -2023,7 +2023,7 @@ NOTE: This code was generated by the GeneratePackageVersions tool. To safely True - ApiVersion=3.3.2;RestoreRecursive=false;BuildProjectReferences=false + ApiVersion=3.3.3;RestoreRecursive=false;BuildProjectReferences=false net6.0 True diff --git a/tracer/build/_build/Build.Steps.cs b/tracer/build/_build/Build.Steps.cs index b16a13413..bdbb62044 100644 --- a/tracer/build/_build/Build.Steps.cs +++ b/tracer/build/_build/Build.Steps.cs @@ -926,11 +926,13 @@ _ when path.Contains("dependency-libs") => false, var includeIntegration = TracerDirectory.GlobFiles("test/test-applications/integrations/**/*.csproj"); // Don't build aspnet full framework sample in this step var includeSecurity = TracerDirectory.GlobFiles("test/test-applications/security/*/*.csproj"); + var includeDebugger = TracerDirectory.GlobFiles("test/test-applications/debugger/*/*.csproj"); var exclude = TracerDirectory.GlobFiles("test/test-applications/integrations/dependency-libs/**/*.csproj"); var projects = includeIntegration .Concat(includeSecurity) + .Concat(includeDebugger) .Select(x => Solution.GetProject(x)) .Where(project => (project, project.TryGetTargetFrameworks(), project.RequiresDockerDependency()) switch @@ -1169,6 +1171,7 @@ void RunWindowsIisIntegrationTests(Project project) var securitySampleProjects = TracerDirectory.GlobFiles("test/test-applications/security/*/*.csproj"); var regressionProjects = TracerDirectory.GlobFiles("test/test-applications/regression/*/*.csproj"); var instrumentationProjects = TracerDirectory.GlobFiles("test/test-applications/instrumentation/*/*.csproj"); + var debuggerProjects = TracerDirectory.GlobFiles("test/test-applications/debugger/*/*.csproj"); // These samples are currently skipped. var projectsToSkip = new List @@ -1222,12 +1225,14 @@ void RunWindowsIisIntegrationTests(Project project) .Concat(securitySampleProjects) .Concat(regressionProjects) .Concat(instrumentationProjects) + .Concat(debuggerProjects) .Select(path => (path, project: Solution.GetProject(path))) .Where(x => (IncludeTestsRequiringDocker, x.project) switch { // filter out or to integration tests that have docker dependencies (null, _) => true, (_, null) => true, + (_, { } p) when p.Name.Contains("Samples.Probes") => true, // always have to build this one (_, { } p) when p.Name.Contains("Samples.AspNetCoreRazorPages") => true, // always have to build this one (_, { } p) when !string.IsNullOrWhiteSpace(SampleName) && p.Name.Contains(SampleName) => true, (var required, { } p) => p.RequiresDockerDependency() == required, diff --git a/tracer/build/_build/BuildVariables.cs b/tracer/build/_build/BuildVariables.cs index 13cc9217c..8afcbd8f8 100644 --- a/tracer/build/_build/BuildVariables.cs +++ b/tracer/build/_build/BuildVariables.cs @@ -10,6 +10,7 @@ public static void AddDebuggerEnvironmentVariables(this Dictionary envVars, AbsolutePath tracerHomeDirectory) diff --git a/tracer/build/_build/UpdateVendors/UpdateVendors.cs b/tracer/build/_build/UpdateVendors/UpdateVendors.cs index dc574acde..82f5909b1 100644 --- a/tracer/build/_build/UpdateVendors/UpdateVendors.cs +++ b/tracer/build/_build/UpdateVendors/UpdateVendors.cs @@ -85,7 +85,7 @@ private static async Task UpdateVendor(VendoredDependency dependency, AbsolutePa foreach (var file in files) { - if (ShouldDropFile(file)) + if (ShouldDropFile(dependency, sourceLocation, file)) { File.Delete(file); } @@ -105,16 +105,13 @@ private static async Task UpdateVendor(VendoredDependency dependency, AbsolutePa Console.WriteLine($"Finished {libraryName} upgrade."); } - private static bool ShouldDropFile(string filePath) + private static bool ShouldDropFile(VendoredDependency dependency, string basePath, string filePath) { - var drops = new List() + var normalizedFilePath = filePath.Replace('/', '\\'); + foreach (var relativeFileToDrop in dependency.RelativePathsToExclude) { - // No active exclusions - }; - - foreach (var drop in drops) - { - if (filePath.Contains(drop, StringComparison.OrdinalIgnoreCase)) + var absolutePath = Path.Combine(basePath, relativeFileToDrop).Replace('/', '\\'); + if (normalizedFilePath.Equals(absolutePath, StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/tracer/build/_build/UpdateVendors/VendoredDependency.cs b/tracer/build/_build/UpdateVendors/VendoredDependency.cs index 2dfb9feec..d10c75f27 100644 --- a/tracer/build/_build/UpdateVendors/VendoredDependency.cs +++ b/tracer/build/_build/UpdateVendors/VendoredDependency.cs @@ -53,11 +53,12 @@ static VendoredDependency() Add( libraryName: "Newtonsoft.Json", - version: "12.0.1", - downloadUrl: "https://github.com/JamesNK/Newtonsoft.Json/archive/12.0.1.zip", - pathToSrc: new[] { "Newtonsoft.Json-12.0.1", "src", "Newtonsoft.Json" }, - transform: filePath => RewriteCsFileWithStandardTransform(filePath, originalNamespace: "Newtonsoft.Json")); - + version: "13.0.1", + downloadUrl: "https://github.com/JamesNK/Newtonsoft.Json/archive/13.0.1.zip", + pathToSrc: new[] { "Newtonsoft.Json-13.0.1", "src", "Newtonsoft.Json" }, + transform: filePath => RewriteCsFileWithStandardTransform(filePath, originalNamespace: "Newtonsoft.Json", AddNullableDirectiveTransform, AddIgnoreNullabilityWarningDisablePragma), + relativePathsToExclude: new[] { "Utilities/NullableAttributes.cs" }); + Add( libraryName: "dnlib", version: "3.4.0", @@ -84,13 +85,16 @@ static VendoredDependency() public string[] PathToSrc { get; set; } public Action Transform { get; set; } + + public string[] RelativePathsToExclude { get; set; } private static void Add( string libraryName, string version, string downloadUrl, string[] pathToSrc, - Action transform) + Action transform, + string[] relativePathsToExclude = null) { All.Add(new VendoredDependency() { @@ -99,6 +103,7 @@ private static void Add( DownloadUrl = downloadUrl, PathToSrc = pathToSrc, Transform = transform, + RelativePathsToExclude = relativePathsToExclude ?? Array.Empty(), }); } @@ -112,7 +117,7 @@ private static string AddNullableDirectiveTransform(string filePath, string cont return content; } - private static void RewriteCsFileWithStandardTransform(string filePath, string originalNamespace, Func extraTransform = null) + private static void RewriteCsFileWithStandardTransform(string filePath, string originalNamespace, params Func[] extraTransform) { if (string.Equals(Path.GetExtension(filePath), ".cs", StringComparison.OrdinalIgnoreCase)) { @@ -120,9 +125,12 @@ private static void RewriteCsFileWithStandardTransform(string filePath, string o filePath, content => { - if (extraTransform != null) + foreach (var transform in extraTransform) { - content = extraTransform(filePath, content); + if (transform != null) + { + content = transform(filePath, content); + } } // Disable analyzer @@ -140,13 +148,40 @@ private static void RewriteCsFileWithStandardTransform(string filePath, string o builder.Replace($"Func<", $"System.Func<"); builder.Replace($"Action<", $"System.Action<"); } + + var filename = Path.GetFileName(filePath); + if (filename == "JsonSerializerInternalReader.cs") + { + builder.Replace("#pragma warning restore CS8600, CS8602, CS8603, CS8604", string.Empty); + } + + builder.Replace("#if !(PORTABLE40 || PORTABLE || DOTNET || NETSTANDARD2_0)", "#if NETFRAMEWORK"); + + if (filename == "JsonPropertyCollection.cs") + { + // eww + builder.Replace( + @" private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item)", + @"#if NETCOREAPP + private new bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) +#else + private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) +#endif"); + } } + if (originalNamespace.Equals("dnlib")) { // dnlib's only targets net461 and netstandard2.0. // For our needs, it's more correct to consider `NETSTANDARD` as 'everything not .NET Framework' builder.Replace("#if NETSTANDARD", "#if !NETFRAMEWORK"); + + // Make certain classes partial so we can extend them. + foreach (var className in new[] { "SymbolReaderImpl", "PdbReader", "PortablePdbReader" }) + { + builder.Replace($"class {className}", $"partial class {className}"); + } } // Special ProtoBuf handling @@ -166,6 +201,10 @@ private static void RewriteCsFileWithStandardTransform(string filePath, string o builder.Replace("\"ProtoBuf.ProtoMemberAttribute\"", "\"Datadog.Trace.Vendors.ProtoBuf.ProtoMemberAttribute\""); } + // Debugger.Break() is a dangerous method that may crash the process. We don't + // want to take any risk of calling it, ever, so replace it with a noop. + builder.Replace("Debugger.Break();", "{}"); + // Prevent namespace conflicts builder.Replace($"using {originalNamespace}", $"using Datadog.Trace.Vendors.{originalNamespace}"); builder.Replace($"namespace {originalNamespace}", $"namespace Datadog.Trace.Vendors.{originalNamespace}"); @@ -204,6 +243,25 @@ static string GenerateWarningDisablePragma() => "SYSLIB0011, " + // BinaryFormatter serialization is obsolete and should not be used. "SYSLIB0032"; // Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored." + static string AddIgnoreNullabilityWarningDisablePragma(string filePath, string content) => + "#pragma warning disable " + + "CS8600, " + // Converting null literal or possible null value to non-nullable type. + "CS8601, " + // Possible null reference assignment + "CS8602, " + // Dereference of a possibly null reference + "CS8603, " + // Possible null reference return + "CS8604, " + // Possible null reference argument for parameter 'x' in 'y' + "CS8618, " + // Non-nullable field 'x' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. + "CS8620, " + // Argument of type 'x' cannot be used for parameter 'y' of type 'z[]' in 'a' due to differences in the nullability of reference types. + "CS8714, " + // The type 'x' cannot be used as type parameter 'y' in the generic type or method 'z'. Nullability of type argument 'x' doesn't match 'notnull' constraint. + "CS8762, " + // Parameter 'x' must have a non-null value when exiting with 'true' + "CS8765, " + // Nullability of type of parameter 'x' doesn't match overridden member (possibly because of nullability attributes) + "CS8766, " + // Nullability of reference types in return type of 'x' doesn't match implicitly implemented member 'y' (possibly because of nullability attributes) + "CS8767, " + // Nullability of reference types in type of parameter 'x' of 'y' doesn't match implicitly implemented member 'z' (possibly because of nullability attributes) + "CS8768, " + // Nullability of reference types in return type doesn't match implemented member 'x' (possibly because of nullability attributes) + "CS8769, " + // Nullability of reference types in type of parameter 'x' doesn't match implemented member 'y' (possibly because of nullability attributes) + "CS8612" + // Nullability of reference types in type of 'x' doesn't match implicitly implemented member 'y'. + Environment.NewLine + content; + private static void RewriteFileWithTransform(string filePath, Func transform) { var fileContent = File.ReadAllText(filePath); diff --git a/tracer/dependabot/Datadog.Dependabot.Integrations.csproj b/tracer/dependabot/Datadog.Dependabot.Integrations.csproj index 61e79f7eb..2c8aa0e07 100644 --- a/tracer/dependabot/Datadog.Dependabot.Integrations.csproj +++ b/tracer/dependabot/Datadog.Dependabot.Integrations.csproj @@ -18,8 +18,8 @@ - - + + @@ -28,23 +28,23 @@ - - + + - - + + - - + + - - + + @@ -53,8 +53,8 @@ - - + + @@ -98,13 +98,13 @@ - - + + - - + + @@ -123,8 +123,8 @@ - - + + @@ -178,8 +178,8 @@ - - + + diff --git a/tracer/dependabot/Datadog.Dependabot.Vendors.csproj b/tracer/dependabot/Datadog.Dependabot.Vendors.csproj index efb704915..09b529b5f 100644 --- a/tracer/dependabot/Datadog.Dependabot.Vendors.csproj +++ b/tracer/dependabot/Datadog.Dependabot.Vendors.csproj @@ -18,8 +18,8 @@ - - + + diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt b/tracer/src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt index 76b239aed..edc459788 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt @@ -235,6 +235,7 @@ add_library("SignalFx.Tracing.ClrProfiler.Native.static" STATIC debugger_probes_instrumentation_requester.cpp debugger_rejit_handler_module_method.cpp debugger_rejit_preprocessor.cpp + debugger_tokens.cpp rejit_preprocessor.cpp rejit_work_offloader.cpp environment_variables_util.cpp @@ -242,6 +243,8 @@ add_library("SignalFx.Tracing.ClrProfiler.Native.static" STATIC always_on_profiler_clr_helpers.cpp always_on_profiler.cpp tracer_tokens.cpp + debugger_environment_variables_util.cpp + probes_tracker.cpp ${DOTNET_TRACER_REPO_ROOT_PATH}/shared/src/native-lib/coreclr/src/pal/prebuilt/idl/corprof_i.cpp ${GENERATED_OBJ_FILES} ) diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.def b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.def index 5c301f0b7..6cef09b79 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.def +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.def @@ -11,5 +11,7 @@ EXPORTS AddDerivedInstrumentations AddTraceAttributeInstrumentation InitializeTraceMethods + InstrumentProbes + GetProbesStatuses SignalFxReadThreadSamples SignalFxSetNativeContext diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj index 89d1ae9c6..756e53fa8 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj @@ -200,14 +200,19 @@ + + + + + @@ -235,6 +240,8 @@ + + @@ -242,6 +249,7 @@ + diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj.filters b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj.filters index 1f74f9794..0f1912031 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj.filters +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/Datadog.Trace.ClrProfiler.Native.vcxproj.filters @@ -40,6 +40,15 @@ shared + + Debugger + + + Debugger + + + Debugger + @@ -97,6 +106,21 @@ shared + + Debugger + + + Debugger + + + Debugger + + + Debugger + + + Debugger + diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.cpp index 451f8c3d1..98a931d47 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.cpp @@ -367,7 +367,8 @@ HRESULT CallTargetTokens::ModifyLocalSig(ILRewriter* reWriter, TypeSignature* me } } - ULONG newLocalsCount = 3; + const auto additionalLocalsCount = GetAdditionalLocalsCount(); + ULONG newLocalsCount = 3 + additionalLocalsCount; // Gets the calltarget state type buffer and size unsigned callTargetStateTypeRefBuffer; @@ -454,7 +455,7 @@ HRESULT CallTargetTokens::ModifyLocalSig(ILRewriter* reWriter, TypeSignature* me } // Add new locals - + // Return value local if (returnSignatureType != nullptr) { @@ -480,6 +481,8 @@ HRESULT CallTargetTokens::ModifyLocalSig(ILRewriter* reWriter, TypeSignature* me newSignatureOffset += callTargetReturnSize; } + AddAdditionalLocals(newSignatureBuffer, newSignatureOffset, newSignatureSize); + // CallTarget state value newSignatureBuffer[newSignatureOffset++] = ELEMENT_TYPE_VALUETYPE; memcpy(&newSignatureBuffer[newSignatureOffset], &callTargetStateTypeRefBuffer, callTargetStateTypeRefSize); @@ -500,15 +503,15 @@ HRESULT CallTargetTokens::ModifyLocalSig(ILRewriter* reWriter, TypeSignature* me *callTargetReturnToken = callTargetReturn; if (returnSignatureType != nullptr) { - *returnValueIndex = newLocalsCount - 4; + *returnValueIndex = newLocalsCount - 4 - additionalLocalsCount; } else { *returnValueIndex = static_cast(ULONG_MAX); } - *exceptionIndex = newLocalsCount - 3; - *callTargetReturnIndex = newLocalsCount - 2; - *callTargetStateIndex = newLocalsCount - 1; + *exceptionIndex = newLocalsCount - 3 - additionalLocalsCount; + *callTargetReturnIndex = newLocalsCount - 2 - additionalLocalsCount; + *callTargetStateIndex = newLocalsCount - 1; // Must be the last local. return hr; } @@ -739,6 +742,15 @@ mdToken CallTargetTokens::GetCurrentTypeRef(const TypeInfo* currentType, bool& i } +int CallTargetTokens::GetAdditionalLocalsCount() +{ + return 0; +} + +void CallTargetTokens::AddAdditionalLocals(COR_SIGNATURE (&signatureBuffer)[500], ULONG& signatureOffset, ULONG& signatureSize) +{ +} + CallTargetTokens::CallTargetTokens(ModuleMetadata* moduleMetadataPtr, const bool enableByRefInstrumentation, const bool enableCallTargetStateByRef) : module_metadata_ptr(moduleMetadataPtr), diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.h index 725900bc6..e78c16566 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/calltarget_tokens.h @@ -29,12 +29,7 @@ class CallTargetTokens mdAssemblyRef corLibAssemblyRef = mdAssemblyRefNil; mdTypeRef objectTypeRef = mdTypeRefNil; mdTypeRef typeRef = mdTypeRefNil; - mdTypeRef runtimeTypeHandleRef = mdTypeRefNil; mdToken getTypeFromHandleToken = mdTokenNil; - mdTypeRef runtimeMethodHandleRef = mdTypeRefNil; - - // CallTarget tokens - mdAssemblyRef profilerAssemblyRef = mdAssemblyRefNil; mdMemberRef callTargetStateTypeGetDefault = mdMemberRefNil; mdMemberRef callTargetReturnVoidTypeGetDefault = mdMemberRefNil; @@ -53,6 +48,9 @@ class CallTargetTokens mdToken* callTargetStateToken, mdToken* exceptionToken, mdToken* callTargetReturnToken); protected: + // CallTarget tokens + mdAssemblyRef profilerAssemblyRef = mdAssemblyRefNil; + const bool enable_by_ref_instrumentation = false; const bool enable_calltarget_state_by_ref = false; mdTypeRef callTargetTypeRef = mdTypeRefNil; @@ -60,15 +58,19 @@ class CallTargetTokens mdTypeRef callTargetReturnVoidTypeRef = mdTypeRefNil; mdTypeRef callTargetReturnTypeRef = mdTypeRefNil; mdTypeRef exTypeRef = mdTypeRefNil; + mdTypeRef runtimeTypeHandleRef = mdTypeRefNil; + mdTypeRef runtimeMethodHandleRef = mdTypeRefNil; ModuleMetadata* GetMetadata(); - HRESULT EnsureBaseCalltargetTokens(); + virtual HRESULT EnsureBaseCalltargetTokens(); mdTypeSpec GetTargetReturnValueTypeRef(TypeSignature* returnArgument); virtual const shared::WSTRING& GetCallTargetType() = 0; virtual const shared::WSTRING& GetCallTargetStateType() = 0; virtual const shared::WSTRING& GetCallTargetReturnType() = 0; virtual const shared::WSTRING& GetCallTargetReturnGenericType() = 0; + virtual int GetAdditionalLocalsCount(); + virtual void AddAdditionalLocals(COR_SIGNATURE (&signatureBuffer)[500], ULONG& signatureOffset, ULONG& signatureSize); CallTargetTokens(ModuleMetadata* moduleMetadataPtr, const bool enableByRefInstrumentation, const bool enableCallTargetStateByRef); diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.cpp index e488b45fa..031d8f606 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.cpp @@ -182,6 +182,8 @@ HRESULT STDMETHODCALLTYPE CorProfiler::Initialize(IUnknown* cor_profiler_info_un : std::make_shared(this->info_, work_offloader); tracer_integration_preprocessor = std::make_unique(rejit_handler, work_offloader); + debugger_instrumentation_requester = std::make_unique(rejit_handler, work_offloader); + DWORD event_mask = COR_PRF_MONITOR_JIT_COMPILATION | COR_PRF_DISABLE_TRANSPARENCY_CHECKS_UNDER_FULL_TRUST | COR_PRF_MONITOR_MODULE_LOADS | COR_PRF_MONITOR_ASSEMBLY_LOADS | COR_PRF_MONITOR_APPDOMAIN_LOADS | COR_PRF_ENABLE_REJIT; @@ -723,8 +725,10 @@ HRESULT CorProfiler::TryRejitModule(ModuleID module_id) Logger::Info("ModuleLoadFinished: ", managed_profiler_name, " v", assemblyVersion, " - Fix PInvoke maps"); #ifdef _WIN32 RewritingPInvokeMaps(module_metadata, windows_nativemethods_type); + RewritingPInvokeMaps(module_metadata, debugger_windows_nativemethods_type); #else RewritingPInvokeMaps(module_metadata, nonwindows_nativemethods_type); + RewritingPInvokeMaps(module_metadata, debugger_nonwindows_nativemethods_type); #endif // _WIN32 auto native_loader_library_path = GetNativeLoaderFilePath(); @@ -1002,7 +1006,17 @@ HRESULT CorProfiler::TryRejitModule(ModuleID module_id) if (tracer_integration_preprocessor != nullptr && !integration_definitions_.empty()) { const auto numReJITs = tracer_integration_preprocessor->RequestRejitForLoadedModules(std::vector{module_id}, integration_definitions_); - Logger::Debug("Total number of ReJIT Requested: ", numReJITs); + Logger::Debug("[Tracer] Total number of ReJIT Requested: ", numReJITs); + } + + if (debugger_instrumentation_requester != nullptr) + { + const auto& probes = debugger_instrumentation_requester->GetProbes(); + if (!probes.empty()) + { + const auto numReJITs = debugger_instrumentation_requester->RequestRejitForLoadedModule(module_id); + Logger::Debug("[Debugger] Total number of ReJIT Requested: ", numReJITs); + } } } @@ -1144,6 +1158,7 @@ HRESULT STDMETHODCALLTYPE CorProfiler::JITCompilationStarted(FunctionID function // In case is True we create a local ModuleMetadata to inject the loader. if (!shared::Contains(module_ids_, module_id)) { + debugger_instrumentation_requester->PerformInstrumentAllIfNeeded(module_id, function_token); return S_OK; } @@ -1156,6 +1171,9 @@ HRESULT STDMETHODCALLTYPE CorProfiler::JITCompilationStarted(FunctionID function if (has_loader_injected_in_appdomain) { // Loader was already injected in a calltarget scenario, we don't need to do anything else here + + debugger_instrumentation_requester->PerformInstrumentAllIfNeeded(module_id, function_token); + return S_OK; } @@ -1550,6 +1568,19 @@ void CorProfiler::InitializeTraceMethods(WCHAR* id, WCHAR* integration_assembly_ } } +void CorProfiler::InstrumentProbes(debugger::DebuggerMethodProbeDefinition* methodProbes, int methodProbesLength, + debugger::DebuggerLineProbeDefinition* lineProbes, int lineProbesLength, + debugger::DebuggerRemoveProbesDefinition* removeProbes, int revertProbesLength) const +{ + debugger_instrumentation_requester->InstrumentProbes(methodProbes, methodProbesLength, lineProbes, lineProbesLength, + removeProbes, revertProbesLength); +} + +int CorProfiler::GetProbesStatuses(WCHAR** probeIds, int probeIdsLength, debugger::DebuggerProbeStatus* probeStatuses) +{ + return debugger_instrumentation_requester->GetProbesStatuses(probeIds, probeIdsLength, probeStatuses); +} + // // ICorProfilerCallback6 methods // @@ -3189,9 +3220,10 @@ HRESULT STDMETHODCALLTYPE CorProfiler::ReJITError(ModuleID moduleId, mdMethodDef { Logger::Warn("ReJITError: [functionId: ", functionId, ", moduleId: ", moduleId, ", methodId: ", methodId, ", hrStatus: ", hrStatus, "]"); + return S_OK; } - return S_OK; + return debugger_instrumentation_requester->NotifyReJITError(moduleId, methodId, functionId, hrStatus); } HRESULT STDMETHODCALLTYPE CorProfiler::JITCachedFunctionSearchStarted(FunctionID functionId, BOOL* pbUseCachedFunction) @@ -3218,7 +3250,7 @@ HRESULT STDMETHODCALLTYPE CorProfiler::JITCachedFunctionSearchStarted(FunctionID return S_OK; } - // Call RequestRejit for register inliners and current NGEN module. + // Call RequestRejitOrRevert for register inliners and current NGEN module. if (rejit_handler != nullptr) { // Process the current module to detect inliners. diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.h index 2d9b6951b..3ecaa7975 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/cor_profiler.h @@ -69,6 +69,11 @@ class CorProfiler : public CorProfilerBase std::unique_ptr tracer_integration_preprocessor = nullptr; bool trace_annotations_enabled = false; + // + // Debugger Members + // + std::unique_ptr debugger_instrumentation_requester = nullptr; + // Cor assembly properties AssemblyProperty corAssemblyProperty{}; AssemblyReference* managed_profiler_assembly_reference; @@ -179,10 +184,15 @@ class CorProfiler : public CorProfilerBase WCHAR* integration_type_name_ptr); void InitializeTraceMethods(WCHAR* id, WCHAR* integration_assembly_name_ptr, WCHAR* integration_type_name_ptr, WCHAR* configuration_string_ptr); + void InstrumentProbes(debugger::DebuggerMethodProbeDefinition* methodProbes, int methodProbesLength, + debugger::DebuggerLineProbeDefinition* lineProbes, int lineProbesLength, + debugger::DebuggerRemoveProbesDefinition* revertProbes, int revertProbesLength) const; + int GetProbesStatuses(WCHAR** probeIds, int probeIdsLength, debugger::DebuggerProbeStatus* probeStatuses); friend class debugger::DebuggerProbesInstrumentationRequester; friend class debugger::DebuggerMethodRewriter; friend class TracerMethodRewriter; + friend class MethodRewriter; }; // Note: Generally you should not have a single, global callback implementation, diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/dd_profiler_constants.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/dd_profiler_constants.h index affcaa3c9..95a93ec54 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/dd_profiler_constants.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/dd_profiler_constants.h @@ -93,6 +93,9 @@ const shared::WSTRING windows_nativemethods_type = WStr("Datadog.Trace.ClrProfil const shared::WSTRING profiler_nativemethods_type = WStr("Datadog.Trace.ContinuousProfiler.NativeInterop+NativeMethods"); const shared::WSTRING native_loader_nativemethods_type = WStr("Datadog.Trace.NativeLoader+NativeMethods"); +const shared::WSTRING debugger_nonwindows_nativemethods_type = WStr("Datadog.Trace.Debugger.PInvoke.DebuggerNativeMethods+NonWindows"); +const shared::WSTRING debugger_windows_nativemethods_type = WStr("Datadog.Trace.Debugger.PInvoke.DebuggerNativeMethods+Windows"); + const shared::WSTRING calltarget_modification_action = WStr("CallTargetModification"); const shared::WSTRING distributed_tracer_type_name = WStr("Datadog.Trace.ClrProfiler.DistributedTracer"); diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_constants.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_constants.h new file mode 100644 index 000000000..4a860061d --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_constants.h @@ -0,0 +1,40 @@ +#ifndef DEBUGGER_CONSTANTS_H +#define DEBUGGER_CONSTANTS_H + +#include "cor_profiler.h" + +using namespace trace; +using namespace shared; + +namespace debugger +{ + +const WSTRING skip_assembly_prefixes[]{ + WStr("System"), + WStr("Microsoft"), + WStr("Windows"), + WStr("runtime"), + WStr("RefEmit_"), + WStr("vstest"), + WStr("testhost"), + WStr("dotnet"), + WStr("SOS"), + WStr("NuGet"), + WStr("VBCSCompiler"), + WStr("csc"), + WStr("DuckTypeNotVisibleAssembly"), + WStr("Datadog.Trace")}; + +const WSTRING skip_assemblies[]{WStr("mscorlib"), + WStr("netstandard"), + WStr("System.Configuration"), + WStr("Microsoft.AspNetCore.Razor.Language"), + WStr("Microsoft.AspNetCore.Mvc.RazorPages"), + WStr("Anonymously Hosted DynamicMethods Assembly"), + WStr("Datadog.AutoInstrumentation.ManagedLoader"), + WStr("ISymWrapper"), + WStr("Datadog.Trace")}; + +} + +#endif // DEBUGGER_CONSTANTS_H diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables.h new file mode 100644 index 000000000..c0972a293 --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables.h @@ -0,0 +1,20 @@ +#ifndef DD_CLR_PROFILER_DEBUGGER_ENVIRONMENT_VARIABLES_H_ +#define DD_CLR_PROFILER_DEBUGGER_ENVIRONMENT_VARIABLES_H_ + +#include "../../../shared/src/native-src/string.h" // NOLINT + +using namespace shared; + +namespace debugger +{ +namespace environment +{ + + // Determine whether to enter "instrument all" mode where the Debugger instrumentation + // is applied to every jit compiled method. Only useful for testing purposes. Default is false. + const WSTRING internal_instrument_all_enabled = WStr("SIGNALFX_INTERNAL_DEBUGGER_INSTRUMENT_ALL"); + +} // namespace environment +} // namespace debugger + +#endif diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.cpp new file mode 100644 index 000000000..07b0e1332 --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.cpp @@ -0,0 +1,12 @@ +#include "debugger_environment_variables_util.h" +#include "environment_variables_util.h" + +namespace debugger +{ + +bool IsDebuggerInstrumentAllEnabled() +{ + CheckIfTrue(GetEnvironmentValue(environment::internal_instrument_all_enabled)); +} + +} // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.h new file mode 100644 index 000000000..06dc91b34 --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_environment_variables_util.h @@ -0,0 +1,15 @@ +#ifndef DD_CLR_PROFILER_DEBUGGER_ENVIRONMENT_VARIABLES_UTIL_H_ +#define DD_CLR_PROFILER_DEBUGGER_ENVIRONMENT_VARIABLES_UTIL_H_ + +#include "debugger_environment_variables.h" +#include "string.h" +#include "../../../shared/src/native-src/util.h" + +namespace debugger +{ + +bool IsDebuggerInstrumentAllEnabled(); + +} // namespace debugger + +#endif // DD_CLR_PROFILER_DEBUGGER_ENVIRONMENT_VARIABLES_UTIL_H_ \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_members.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_members.h index 4689f8b56..20fbc0a02 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_members.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_members.h @@ -23,32 +23,155 @@ namespace debugger typedef struct _DebuggerMethodProbeDefinition { - WCHAR* targetAssembly; + WCHAR* probeId; WCHAR* targetType; WCHAR* targetMethod; WCHAR** targetParameterTypes; USHORT targetParameterTypesLength; } DebuggerMethodProbeDefinition; -struct MethodProbeDefinition +typedef struct _DebuggerLineProbeDefinition { - const trace::MethodReference target_method; + WCHAR* probeId; + GUID mvid; + mdMethodDef methodId; + int bytecodeOffset; + int lineNumber; + WCHAR* probeFilePath; + +} DebuggerLineProbeDefinition; + +typedef struct _DebuggerRemoveProbesDefinition +{ + WCHAR* probeId; +} DebuggerRemoveProbesDefinition; + +struct ProbeDefinition +{ + shared::WSTRING probeId; + + ProbeDefinition(shared::WSTRING&& probeId) + : probeId(std::move(probeId)) + { + } - MethodProbeDefinition() + inline bool operator==(const ProbeDefinition& other) const { + return probeId == other.probeId; } - MethodProbeDefinition(trace::MethodReference target_method) : - target_method(target_method) + virtual ~ProbeDefinition() = default; +}; + +typedef std::shared_ptr ProbeDefinition_S; + +struct MethodProbeDefinition : public ProbeDefinition +{ + const trace::MethodReference target_method; + const bool is_exact_signature_match = true; + + MethodProbeDefinition(shared::WSTRING probeId, trace::MethodReference&& targetMethod, bool is_exact_signature_match) : + ProbeDefinition(std::move(probeId)), + target_method(targetMethod), + is_exact_signature_match(is_exact_signature_match) { } + MethodProbeDefinition(const MethodProbeDefinition& other) : + ProbeDefinition(other), + target_method(other.target_method), + is_exact_signature_match(other.is_exact_signature_match) + {} + inline bool operator==(const MethodProbeDefinition& other) const { - return target_method == other.target_method; + return probeId == other.probeId && target_method == other.target_method && is_exact_signature_match == other.is_exact_signature_match; } }; +typedef std::vector> MethodProbeDefinitions; + +struct LineProbeDefinition : public ProbeDefinition +{ + int bytecodeOffset; + int lineNumber; + GUID mvid; + mdMethodDef methodId; + shared::WSTRING probeFilePath; + + LineProbeDefinition(shared::WSTRING probeId, int bytecodeOffset, int lineNumber, GUID mvid, mdMethodDef methodId, + shared::WSTRING probeFilePath) : + ProbeDefinition(std::move(probeId)), bytecodeOffset(bytecodeOffset), lineNumber(lineNumber), mvid(mvid), methodId(methodId), + probeFilePath(std::move(probeFilePath)) + { + } + + LineProbeDefinition(const LineProbeDefinition& other) : + ProbeDefinition(other), bytecodeOffset(other.bytecodeOffset), lineNumber(other.lineNumber), mvid(other.mvid), methodId(other.methodId), + probeFilePath(other.probeFilePath) + { + } + + inline bool operator==(const LineProbeDefinition& other) const + { + return probeId == other.probeId && + bytecodeOffset == other.bytecodeOffset && + lineNumber == other.lineNumber && + mvid == other.mvid && + methodId == other.methodId && + probeFilePath == other.probeFilePath; + } +}; + +typedef std::vector> LineProbeDefinitions; + +enum class ProbeStatus +{ + RECEIVED, + INSTALLED, + BLOCKED, + /** + * \brief Preceding with underscore because ERROR is a widely used preprocessor constant. + */ + // ReSharper disable once CppInconsistentNaming + _ERROR // NOLINT(clang-diagnostic-reserved-identifier, bugprone-reserved-identifier) +}; + +struct ProbeMetadata +{ + shared::WSTRING probeId; + std::set methods; + ProbeStatus status; + + ProbeMetadata() = default; + ProbeMetadata(const ProbeMetadata& other) = default; + ProbeMetadata(ProbeMetadata&& other) = default; + + ProbeMetadata(shared::WSTRING probeId, std::set&& methods, ProbeStatus initialStatus) : probeId(probeId), methods(std::move(methods)), status(initialStatus) + { + } + + + inline bool operator==(const ProbeMetadata& other) const + { + return probeId == other.probeId; + } + + virtual ~ProbeMetadata() = default; +}; + +typedef struct _ProbeStatusesRequest +{ + WCHAR** probeIds; + int probeIdsLength; +} ProbeStatusesRequest; + +typedef struct _DebuggerProbeStatus +{ + const WCHAR* probeId; + ProbeStatus status; +} DebuggerProbeStatus; + } // namespace debugger #endif // DD_CLR_PROFILER_LIVE_DEBUGGER_H_ \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.cpp index 1a13c597a..c4107e0f2 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.cpp @@ -6,13 +6,1004 @@ #include "stats.h" #include "version.h" #include "environment_variables_util.h" +#include "probes_tracker.h" namespace debugger { +int DebuggerMethodRewriter::GetNextInstrumentedMethodIndex() +{ + return std::atomic_fetch_add(&_nextInstrumentedMethodIndex, 1); +} + +// Get function locals +HRESULT DebuggerMethodRewriter::GetFunctionLocalSignature(const ModuleMetadata& module_metadata, ILRewriter& rewriter, FunctionLocalSignature& localSignature) +{ + PCCOR_SIGNATURE local_signature{nullptr}; + ULONG local_signature_len = 0; + mdToken localVarSig = rewriter.GetTkLocalVarSig(); + + if (localVarSig == 0) // No locals. + { + localSignature = {}; + return S_OK; + } + + HRESULT hr = module_metadata.metadata_import->GetSigFromToken(localVarSig, &local_signature, + &local_signature_len); + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::GetFunctionLocalSignature Failed in GetSigFromToken using localVarSig = ",localVarSig); + return hr; + } + + std::vector locals; + hr = FunctionLocalSignature::TryParse(local_signature, local_signature_len, locals); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::GetFunctionLocalSignature Failed to parse local signature"); + return E_FAIL; + } + + localSignature = FunctionLocalSignature(local_signature, local_signature_len, std::move(locals)); + return S_OK; +} + +HRESULT DebuggerMethodRewriter::LoadArgument(CorProfiler* corProfiler, bool isStatic, const ILRewriterWrapper& rewriterWrapper, int argumentIndex, const TypeSignature& argument) +{ + // Load the argument into the stack + const auto [elementType, argTypeFlags] = argument.GetElementTypeAndFlags(); + if (argTypeFlags & TypeFlagByRef) + { + rewriterWrapper.LoadArgument(argumentIndex + (isStatic ? 0 : 1)); + } + else + { + rewriterWrapper.LoadArgumentRef(argumentIndex + (isStatic ? 0 : 1)); + } + + return S_OK; +} + +HRESULT DebuggerMethodRewriter::LoadLocal(CorProfiler* corProfiler, const ILRewriterWrapper& rewriterWrapper, int localIndex, const TypeSignature& local) +{ + // Load the argument into the stack + const auto [elementType, localTypeFlags] = local.GetElementTypeAndFlags(); + if (localTypeFlags & TypeFlagByRef) + { + rewriterWrapper.LoadLocal(localIndex); + } + else + { + rewriterWrapper.LoadLocalAddress(localIndex); + } + + return S_OK; +} + +HRESULT DebuggerMethodRewriter::WriteCallsToLogArgOrLocal( + CorProfiler* corProfiler, + DebuggerTokens* debuggerTokens, + bool isStatic, + const std::vector& methodArgsOrLocals, + int numArgsOrLocals, + ILRewriterWrapper& rewriterWrapper, + ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, + bool isArgs, + bool isMethodProbe) +{ + for (auto argOrLocalIndex = 0; argOrLocalIndex < numArgsOrLocals; argOrLocalIndex++) + { + const auto argOrLocal = methodArgsOrLocals[argOrLocalIndex]; + HRESULT hr; + + if (isArgs) + { + hr = LoadArgument(corProfiler, isStatic, rewriterWrapper, argOrLocalIndex, argOrLocal); + } + else + { + hr = LoadLocal(corProfiler, rewriterWrapper, argOrLocalIndex, argOrLocal); + } + + if (FAILED(hr)) + { + Logger::Warn("DebuggerRewriter: Failed load ", isArgs ? "argument" : "local", " index = ", argOrLocalIndex, + " into the stack."); + return E_FAIL; + } + + // Load the index of the argument/local + rewriterWrapper.LoadInt32(argOrLocalIndex); + + // Load the DebuggerState + rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + + if (isArgs) + { + hr = debuggerTokens->WriteLogArg(&rewriterWrapper, methodArgsOrLocals[argOrLocalIndex], beginCallInstruction, isMethodProbe); + } + else + { + hr = debuggerTokens->WriteLogLocal(&rewriterWrapper, methodArgsOrLocals[argOrLocalIndex], beginCallInstruction, isMethodProbe); + } + + if (FAILED(hr)) + { + Logger::Warn("DebuggerRewriter: Failed in ", isArgs ? "WriteLogArg" : "WriteLogLocal", " with index=", argOrLocalIndex); + return E_FAIL; + } + } + return false; +} + +HRESULT +DebuggerMethodRewriter::WriteCallsToLogArg(CorProfiler* corProfiler, DebuggerTokens* debuggerTokens, bool isStatic, + const std::vector& args, + int numArgs, ILRewriterWrapper& rewriterWrapper, ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, bool isMethodProbe) +{ + return WriteCallsToLogArgOrLocal(corProfiler, debuggerTokens, isStatic, args, numArgs, rewriterWrapper, + callTargetStateIndex, beginCallInstruction, /* IsArgs */ true, isMethodProbe); +} + +HRESULT +DebuggerMethodRewriter::WriteCallsToLogLocal(CorProfiler* corProfiler, DebuggerTokens* debuggerTokens, bool isStatic, + const std::vector& locals, + int numLocals, ILRewriterWrapper& rewriterWrapper, ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, bool isMethodProbe) +{ + return WriteCallsToLogArgOrLocal(corProfiler, debuggerTokens, isStatic, locals, numLocals, rewriterWrapper, + callTargetStateIndex, beginCallInstruction, /* IsArgs */ false, isMethodProbe); +} + +HRESULT DebuggerMethodRewriter::LoadInstanceIntoStack(FunctionInfo* caller, bool isStatic, const ILRewriterWrapper& rewriterWrapper, ILInstr** outLoadArgumentInstr) +{ + // *** Load instance into the stack (if not static) + if (isStatic) + { + if (caller->type.valueType) + { + // Static methods in a ValueType can't be instrumented. + // In the future this can be supported by adding a local for the valuetype and initialize it to the default + // value. After the signature modification we need to emit the following IL to initialize and load into the + // stack. + // ldloca.s [localIndex] + // initobj [valueType] + // ldloc.s [localIndex] + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() Static methods in a ValueType cannot be instrumented. "); + return E_FAIL; + } + *outLoadArgumentInstr = rewriterWrapper.LoadNull(); + } + else + { + *outLoadArgumentInstr = rewriterWrapper.LoadArgument(0); + if (caller->type.valueType) + { + if (caller->type.type_spec != mdTypeSpecNil) + { + rewriterWrapper.LoadObj(caller->type.type_spec); + } + else if (!caller->type.isGeneric) + { + rewriterWrapper.LoadObj(caller->type.id); + } + else + { + // Generic struct instrumentation is not supported + // IMetaDataImport::GetMemberProps and IMetaDataImport::GetMemberRefProps returns + // The parent token as mdTypeDef and not as a mdTypeSpec + // that's because the method definition is stored in the mdTypeDef + // This problem doesn't occur on reference types because in that scenario, + // we can always rely on the object's type. + // This problem doesn't occur on a class type because we can always relay in the + // object type. + return E_FAIL; + } + } + } + + return S_OK; +} + HRESULT DebuggerMethodRewriter::Rewrite(RejitHandlerModule* moduleHandler, RejitHandlerModuleMethod* methodHandler) { - return E_NOTIMPL; + const auto debuggerMethodHandler = dynamic_cast(methodHandler); + + if (debuggerMethodHandler->GetProbes().empty()) + { + Logger::Warn("NotifyReJITCompilationStarted: Probes are missing for " + "MethodDef: ", + methodHandler->GetMethodDef()); + + return S_FALSE; + } + + auto _ = trace::Stats::Instance()->CallTargetRewriterCallbackMeasure(); + + MethodProbeDefinitions methodProbes; + LineProbeDefinitions lineProbes; + + const auto& probes = debuggerMethodHandler->GetProbes(); + + if (probes.empty()) + { + Logger::Info("There are no probes for methodDef: ", methodHandler->GetMethodDef()); + return S_OK; + } + + Logger::Info("About to apply debugger instrumentation on ", probes.size(), " probes for methodDef: ", methodHandler->GetMethodDef()); + + for (const auto& probe : probes) + { + const auto methodProbe = std::dynamic_pointer_cast(probe); + if (methodProbe != nullptr) + { + methodProbes.emplace_back(methodProbe); + continue; + } + + const auto lineProbe = std::dynamic_pointer_cast(probe); + if (lineProbe != nullptr) + { + lineProbes.emplace_back(lineProbe); + } + } + + if (methodProbes.empty() && lineProbes.empty()) + { + // No lines probes & method probes. Should not happen unless the user requested to undo the instrumentation while the method got executed. + Logger::Info("There are no method probes and lines probes for methodDef", methodHandler->GetMethodDef()); + return S_OK; + } + else + { + Logger::Info("Applying ", methodProbes.size(), " method probes and ", lineProbes.size(), + " line probes on methodDef: ", methodHandler->GetMethodDef()); + + const auto hr = Rewrite(moduleHandler, methodHandler, methodProbes, lineProbes); + + if (FAILED(hr)) + { + // Mark all probes as Error + for (const auto& probe : probes) + { + ProbesMetadataTracker::Instance()->SetProbeStatus(probe->probeId, ProbeStatus::_ERROR); + } + } + } + + return S_OK; +} + +/// +/// Performs the following instrumentation on the requested bytecode offset: +///try +///{ +/// - Invoke LineDebuggerInvoker.BeginLine with object instance (or null if static method) +/// - Calls to LineDebuggerInvoker.LogArg with original method arguments +/// - Calls to LineDebuggerInvoker.LogLocal with method locals +/// - LineDebuggerInvoker.EndLine +///} +///catch (Exception) +///{ +/// - Store exception into Exception local +///} +/// - Executing the selected sequence point (from the selected bytecode offset) +/// +HRESULT DebuggerMethodRewriter::CallLineProbe( + const int instrumentedMethodIndex, + CorProfiler* corProfiler, + ModuleID module_id, + ModuleMetadata& module_metadata, + FunctionInfo* caller, + DebuggerTokens* debuggerTokens, + mdToken function_token, + bool isStatic, + std::vector& methodArguments, + int numArgs, + ILRewriter& rewriter, + std::vector& methodLocals, + int numLocals, + ILRewriterWrapper& rewriterWrapper, + ULONG lineProbeCallTargetStateIndex, + std::vector& lineProbesEHClauses, + const std::vector& branchTargets, + const std::shared_ptr& lineProbe) +{ + const auto& lineProbeId = lineProbe->probeId; + const auto& bytecodeOffset = lineProbe->bytecodeOffset; + const auto& probeLineNumber = lineProbe->lineNumber; + const auto& probeFilePath = lineProbe->probeFilePath; + + ILInstr* lineProbeFirstInstruction; + auto hr = rewriter.GetInstrFromOffset(bytecodeOffset, &lineProbeFirstInstruction); + + if (FAILED(hr)) + { + // Note we are not sabotaging the whole rewriting upon failure to lookup for a specific bytecode offset. + // TODO Upon implementing the Probe Statuses, we'll need to reflect that. + return S_OK; + } + + if (lineProbeFirstInstruction->m_opcode == CEE_NOP || lineProbeFirstInstruction->m_opcode == CEE_BR_S || + lineProbeFirstInstruction->m_opcode == CEE_BR) + { + lineProbeFirstInstruction = lineProbeFirstInstruction->m_pNext; + } + + const auto prevInstruction = lineProbeFirstInstruction->m_pPrev; + + rewriterWrapper.SetILPosition(lineProbeFirstInstruction); + + // *** + // BEGIN LINE PART + // *** + + // Define ProbeId as string + mdString lineProbeIdToken; + hr = module_metadata.metadata_emit->DefineUserString( + lineProbeId.data(), static_cast(lineProbeId.length()), &lineProbeIdToken); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() DefineUserStringFailed. MethodProbeId = ", lineProbeId, + " module_id= ", module_id, ", functon_token=", function_token); + return E_FAIL; + } + + // Define ProbeLocation as string + mdString lineProbeFilePathToken; + hr = module_metadata.metadata_emit->DefineUserString( + probeFilePath.data(), static_cast(probeFilePath.length()), &lineProbeFilePathToken); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() DefineUserStringFailed. MethodProbeId = ", lineProbeId, + " module_id= ", module_id, ", functon_token=", function_token); + return hr; + } + + rewriterWrapper.LoadStr(lineProbeIdToken); + + ILInstr* loadInstanceInstr; + hr = LoadInstanceIntoStack(caller, isStatic, rewriterWrapper, &loadInstanceInstr); + + IfFailRet(hr); + + rewriterWrapper.LoadToken(function_token); + rewriterWrapper.LoadToken(caller->type.id); + rewriterWrapper.LoadInt32(instrumentedMethodIndex); + rewriterWrapper.LoadInt32(probeLineNumber); + rewriterWrapper.LoadStr(lineProbeFilePathToken); + + // *** Emit BeginLine call + + ILInstr* beginLineCallInstruction; + hr = debuggerTokens->WriteBeginLine(&rewriterWrapper, &caller->type, &beginLineCallInstruction); + + IfFailRet(hr); + + rewriterWrapper.StLocal(lineProbeCallTargetStateIndex); + + // *** Emit LogLocal call(s) + hr = WriteCallsToLogLocal(corProfiler, debuggerTokens, isStatic, methodLocals, numLocals, rewriterWrapper, + lineProbeCallTargetStateIndex, &beginLineCallInstruction, + /* isMethodProbe */ false); + + IfFailRet(hr); + + // *** Emit LogArg call(s) + hr = WriteCallsToLogArg(corProfiler, debuggerTokens, isStatic, methodArguments, numArgs, rewriterWrapper, + lineProbeCallTargetStateIndex, &beginLineCallInstruction, /* isMethodProbe */ false); + + IfFailRet(hr); + + // Load the DebuggerState + rewriterWrapper.LoadLocalAddress(lineProbeCallTargetStateIndex); + hr = debuggerTokens->WriteEndLine(&rewriterWrapper, &beginLineCallInstruction); + + IfFailRet(hr); + + AdjustBranchTargets(lineProbeFirstInstruction, prevInstruction->m_pNext, branchTargets); + AdjustExceptionHandlingClauses(lineProbeFirstInstruction, prevInstruction->m_pNext, &rewriter); + + ILInstr* pStateLeaveToBeginLineOriginalMethodInstr = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + // *** BeginMethod call catch + ILInstr* beginLineCatchFirstInstr = rewriterWrapper.LoadLocalAddress(lineProbeCallTargetStateIndex); + debuggerTokens->WriteLogException(&rewriterWrapper, &caller->type, /* isMethodProbe */ false); + ILInstr* beginLineCatchLeaveInstr = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + // *** BeginMethod exception handling clause + EHClause beginLineExClause{}; + beginLineExClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE; + beginLineExClause.m_pTryBegin = prevInstruction->m_pNext; + beginLineExClause.m_pTryEnd = beginLineCatchFirstInstr; + beginLineExClause.m_pHandlerBegin = beginLineCatchFirstInstr; + beginLineExClause.m_pHandlerEnd = beginLineCatchLeaveInstr; + beginLineExClause.m_ClassToken = debuggerTokens->GetExceptionTypeRef(); + + ILInstr* beginOriginalLineInstr = rewriterWrapper.GetCurrentILInstr(); + pStateLeaveToBeginLineOriginalMethodInstr->m_pTarget = beginOriginalLineInstr; + beginLineCatchLeaveInstr->m_pTarget = beginOriginalLineInstr; + + lineProbesEHClauses.emplace_back(beginLineExClause); + return S_OK; +} + +HRESULT DebuggerMethodRewriter::ApplyLineProbes( + const int instrumentedMethodIndex, + const LineProbeDefinitions& lineProbes, + CorProfiler* corProfiler, + ModuleID module_id, + ModuleMetadata& module_metadata, + FunctionInfo* caller, + DebuggerTokens* debuggerTokens, + mdToken function_token, + bool isStatic, + std::vector& methodArguments, + int numArgs, + ILRewriter& rewriter, + std::vector& methodLocals, + int numLocals, + ILRewriterWrapper& rewriterWrapper, + ULONG lineProbeCallTargetStateIndex, + std::vector& newClauses) const +{ + Logger::Info("Applying ", lineProbes.size(), " line probe(s) instrumentation."); + + const auto branchTargets = std::move(GetBranchTargets(&rewriter)); + + for (const auto& lineProbe : lineProbes) + { + HRESULT hr = CallLineProbe(instrumentedMethodIndex, corProfiler, module_id, module_metadata, caller, debuggerTokens, + function_token, isStatic, methodArguments, numArgs, rewriter, methodLocals, numLocals, + rewriterWrapper, lineProbeCallTargetStateIndex, newClauses, branchTargets, lineProbe); + if (FAILED(hr)) + { + // Appropriate error message is already logged in CallLineProbe. + return S_FALSE; + } + } + + return S_OK; +} + +HRESULT DebuggerMethodRewriter::ApplyMethodProbe( + CorProfiler* corProfiler, + ModuleID module_id, + ModuleMetadata& module_metadata, + FunctionInfo* caller, + DebuggerTokens* debuggerTokens, + mdToken function_token, + TypeSignature retFuncArg, + bool isVoid, + bool isStatic, + std::vector methodArguments, + int numArgs, + const shared::WSTRING& methodProbeId, + ILRewriter& rewriter, + std::vector& methodLocals, + int numLocals, + ILRewriterWrapper& rewriterWrapper, + ULONG callTargetStateIndex, + ULONG exceptionIndex, + ULONG callTargetReturnIndex, + ULONG returnValueIndex, + mdToken callTargetReturnToken, + ILInstr* firstInstruction, + const int instrumentedMethodIndex, + ILInstr* const& beforeLineProbe, + std::vector& newClauses) const +{ + rewriterWrapper.SetILPosition(beforeLineProbe); + + // *** + // BEGIN METHOD PART + // *** + + // Define ProbeId as string + mdString methodProbeIdToken; + HRESULT hr = module_metadata.metadata_emit->DefineUserString(methodProbeId.data(), static_cast(methodProbeId.length()), &methodProbeIdToken); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() DefineUserStringFailed. MethodProbeId = ", methodProbeId, + " module_id= ", module_id, ", functon_token=", + function_token); + return hr; + } + + rewriterWrapper.LoadStr(methodProbeIdToken); + + ILInstr* loadInstanceInstr; + hr = LoadInstanceIntoStack(caller, isStatic, rewriterWrapper, &loadInstanceInstr); + + IfFailRet(hr); + + rewriterWrapper.LoadToken(function_token); + rewriterWrapper.LoadToken(caller->type.id); + rewriterWrapper.LoadInt32(instrumentedMethodIndex); + + // *** Emit BeginMethod call + if (IsDebugEnabled()) + { + Logger::Debug("Caller InstrumentedMethodInfo: ", instrumentedMethodIndex); + Logger::Debug("Caller Type.Id: ", HexStr(&caller->type.id, sizeof(mdToken))); + Logger::Debug("Caller Type.IsGeneric: ", caller->type.isGeneric); + Logger::Debug("Caller Type.IsValid: ", caller->type.IsValid()); + Logger::Debug("Caller Type.Name: ", caller->type.name); + Logger::Debug("Caller Type.TokenType: ", caller->type.token_type); + Logger::Debug("Caller Type.Spec: ", HexStr(&caller->type.type_spec, sizeof(mdTypeSpec))); + Logger::Debug("Caller Type.ValueType: ", caller->type.valueType); + + if (caller->type.extend_from != nullptr) + { + Logger::Debug("Caller Type Extend From.Id: ", HexStr(&caller->type.extend_from->id, sizeof(mdToken))); + Logger::Debug("Caller Type Extend From.IsGeneric: ", caller->type.extend_from->isGeneric); + Logger::Debug("Caller Type Extend From.IsValid: ", caller->type.extend_from->IsValid()); + Logger::Debug("Caller Type Extend From.Name: ", caller->type.extend_from->name); + Logger::Debug("Caller Type Extend From.TokenType: ", caller->type.extend_from->token_type); + Logger::Debug("Caller Type Extend From.Spec: ", + HexStr(&caller->type.extend_from->type_spec, sizeof(mdTypeSpec))); + Logger::Debug("Caller Type Extend From.ValueType: ", caller->type.extend_from->valueType); + } + // + if (caller->type.parent_type != nullptr) + { + Logger::Debug("Caller ParentType.Id: ", HexStr(&caller->type.parent_type->id, sizeof(mdToken))); + Logger::Debug("Caller ParentType.IsGeneric: ", caller->type.parent_type->isGeneric); + Logger::Debug("Caller ParentType.IsValid: ", caller->type.parent_type->IsValid()); + Logger::Debug("Caller ParentType.Name: ", caller->type.parent_type->name); + Logger::Debug("Caller ParentType.TokenType: ", caller->type.parent_type->token_type); + Logger::Debug("Caller ParentType.Spec: ", HexStr(&caller->type.parent_type->type_spec, sizeof(mdTypeSpec))); + Logger::Debug("Caller ParentType.ValueType: ", caller->type.parent_type->valueType); + } + } + + ILInstr* beginCallInstruction; + hr = debuggerTokens->WriteBeginMethod_StartMarker(&rewriterWrapper, &caller->type, &beginCallInstruction); + + IfFailRet(hr); + + rewriterWrapper.StLocal(callTargetStateIndex); + + // *** Emit LogArg call(s) + hr = WriteCallsToLogArg(corProfiler, debuggerTokens, isStatic, methodArguments, numArgs, rewriterWrapper, + callTargetStateIndex, &beginCallInstruction, /* isMethodProbe */ true); + + IfFailRet(hr); + + // Load the DebuggerState + rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + hr = debuggerTokens->WriteBeginMethod_EndMarker(&rewriterWrapper, &beginCallInstruction); + + IfFailRet(hr); + + ILInstr* pStateLeaveToBeginOriginalMethodInstr = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + // *** BeginMethod call catch + ILInstr* beginMethodCatchFirstInstr = rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + debuggerTokens->WriteLogException(&rewriterWrapper, &caller->type, /* isMethodProbe */ true); + ILInstr* beginMethodCatchLeaveInstr = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + EHClause beginMethodExClause = {}; + beginMethodExClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE; + beginMethodExClause.m_pTryBegin = firstInstruction; + beginMethodExClause.m_pTryEnd = beginMethodCatchFirstInstr; + beginMethodExClause.m_pHandlerBegin = beginMethodCatchFirstInstr; + beginMethodExClause.m_pHandlerEnd = beginMethodCatchLeaveInstr; + beginMethodExClause.m_ClassToken = debuggerTokens->GetExceptionTypeRef(); + + // *** + // METHOD EXECUTION + // *** + ILInstr* beginOriginalMethodInstr = rewriterWrapper.GetCurrentILInstr(); + pStateLeaveToBeginOriginalMethodInstr->m_pTarget = beginOriginalMethodInstr; + beginMethodCatchLeaveInstr->m_pTarget = beginOriginalMethodInstr; + + // *** + // ENDING OF THE METHOD EXECUTION + // *** + + // *** Create return instruction and insert it at the end + ILInstr* methodReturnInstr = rewriter.NewILInstr(); + methodReturnInstr->m_opcode = CEE_RET; + rewriter.InsertAfter(rewriter.GetILList()->m_pPrev, methodReturnInstr); + rewriterWrapper.SetILPosition(methodReturnInstr); + + // *** + // EXCEPTION CATCH + // *** + ILInstr* startExceptionCatch = rewriterWrapper.StLocal(exceptionIndex); + rewriterWrapper.SetILPosition(methodReturnInstr); + ILInstr* rethrowInstr = rewriterWrapper.Rethrow(); + + // *** + // EXCEPTION FINALLY / END METHOD PART + // *** + ILInstr* endMethodTryStartInstr; + hr = LoadInstanceIntoStack(caller, isStatic, rewriterWrapper, &endMethodTryStartInstr); + + IfFailRet(hr); + + // *** Load the return value is is not void + if (!isVoid) + { + rewriterWrapper.LoadLocal(returnValueIndex); + } + + rewriterWrapper.LoadLocal(exceptionIndex); + // Load the DebuggerState + rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + + ILInstr* endMethodCallInstr; + if (isVoid) + { + debuggerTokens->WriteEndVoidReturnMemberRef(&rewriterWrapper, &caller->type, &endMethodCallInstr); + } + else + { + debuggerTokens->WriteEndReturnMemberRef(&rewriterWrapper, &caller->type, &retFuncArg, &endMethodCallInstr); + } + rewriterWrapper.StLocal(callTargetReturnIndex); + + // *** Emit LogLocal call(s) + hr = WriteCallsToLogLocal(corProfiler, debuggerTokens, isStatic, methodLocals, numLocals, rewriterWrapper, + callTargetStateIndex, &endMethodCallInstr, /* isMethodProbe */ true); + + IfFailRet(hr); + + // *** Emit LogArg call(s) + hr = WriteCallsToLogArg(corProfiler, debuggerTokens, isStatic, methodArguments, numArgs, rewriterWrapper, + callTargetStateIndex, &endMethodCallInstr, /* isMethodProbe */ true); + + IfFailRet(hr); + + // Load the DebuggerState + rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + hr = debuggerTokens->WriteEndMethod_EndMarker(&rewriterWrapper, &endMethodCallInstr); + + IfFailRet(hr); + + if (!isVoid) + { + ILInstr* callTargetReturnGetReturnInstr; + rewriterWrapper.LoadLocalAddress(callTargetReturnIndex); + debuggerTokens->WriteCallTargetReturnGetReturnValue(&rewriterWrapper, callTargetReturnToken, + &callTargetReturnGetReturnInstr); + rewriterWrapper.StLocal(returnValueIndex); + } + + ILInstr* endMethodTryLeave = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + // *** EndMethod call catch + + // Load the DebuggerState + ILInstr* endMethodCatchFirstInstr = rewriterWrapper.LoadLocalAddress(callTargetStateIndex); + debuggerTokens->WriteLogException(&rewriterWrapper, &caller->type, /* isMethodProbe */ true); + ILInstr* endMethodCatchLeaveInstr = rewriterWrapper.CreateInstr(CEE_LEAVE_S); + + EHClause endMethodExClause = {}; + endMethodExClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE; + endMethodExClause.m_pTryBegin = endMethodTryStartInstr; + endMethodExClause.m_pTryEnd = endMethodCatchFirstInstr; + endMethodExClause.m_pHandlerBegin = endMethodCatchFirstInstr; + endMethodExClause.m_pHandlerEnd = endMethodCatchLeaveInstr; + endMethodExClause.m_ClassToken = debuggerTokens->GetExceptionTypeRef(); + + // *** EndMethod leave to finally + ILInstr* endFinallyInstr = rewriterWrapper.EndFinally(); + endMethodTryLeave->m_pTarget = endFinallyInstr; + endMethodCatchLeaveInstr->m_pTarget = endFinallyInstr; + + // *** + // METHOD RETURN + // *** + + // Load the current return value from the local var + if (!isVoid) + { + rewriterWrapper.LoadLocal(returnValueIndex); + } + + // Changes all returns to a LEAVE.S + for (ILInstr* pInstr = rewriter.GetILList()->m_pNext; pInstr != rewriter.GetILList(); pInstr = pInstr->m_pNext) + { + switch (pInstr->m_opcode) + { + case CEE_RET: + { + if (pInstr != methodReturnInstr) + { + if (!isVoid) + { + rewriterWrapper.SetILPosition(pInstr); + rewriterWrapper.StLocal(returnValueIndex); + } + pInstr->m_opcode = CEE_LEAVE_S; + pInstr->m_pTarget = endFinallyInstr->m_pNext; + } + break; + } + default: + break; + } + } + + EHClause exClause = {}; + exClause.m_Flags = COR_ILEXCEPTION_CLAUSE_NONE; + exClause.m_pTryBegin = firstInstruction; + exClause.m_pTryEnd = startExceptionCatch; + exClause.m_pHandlerBegin = startExceptionCatch; + exClause.m_pHandlerEnd = rethrowInstr; + exClause.m_ClassToken = debuggerTokens->GetExceptionTypeRef(); + + EHClause finallyClause = {}; + finallyClause.m_Flags = COR_ILEXCEPTION_CLAUSE_FINALLY; + finallyClause.m_pTryBegin = firstInstruction; + finallyClause.m_pTryEnd = rethrowInstr->m_pNext; + finallyClause.m_pHandlerBegin = rethrowInstr->m_pNext; + finallyClause.m_pHandlerEnd = endFinallyInstr; + + newClauses.push_back(beginMethodExClause); + newClauses.push_back(endMethodExClause); + newClauses.push_back(exClause); + newClauses.push_back(finallyClause); + + return S_OK; +} + +HRESULT DebuggerMethodRewriter::Rewrite(RejitHandlerModule* moduleHandler, + RejitHandlerModuleMethod* methodHandler, + MethodProbeDefinitions& methodProbes, + LineProbeDefinitions& lineProbes) const +{ + auto corProfiler = trace::profiler; + + ModuleID module_id = moduleHandler->GetModuleId(); + ModuleMetadata& module_metadata = *moduleHandler->GetModuleMetadata(); + FunctionInfo* caller = methodHandler->GetFunctionInfo(); + DebuggerTokens* debuggerTokens = module_metadata.GetDebuggerTokens(); + mdToken function_token = caller->id; + TypeSignature retFuncArg = caller->method_signature.GetReturnValue(); + const auto [retFuncElementType, retTypeFlags] = retFuncArg.GetElementTypeAndFlags(); + bool isVoid = (retTypeFlags & TypeFlagVoid) > 0; + bool isStatic = !(caller->method_signature.CallingConvention() & IMAGE_CEE_CS_CALLCONV_HASTHIS); + std::vector methodArguments = caller->method_signature.GetMethodArguments(); + int numArgs = caller->method_signature.NumberOfArguments(); + + // First we check if the managed profiler has not been loaded yet + if (!corProfiler->ProfilerAssemblyIsLoadedIntoAppDomain(module_metadata.app_domain_id)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() skipping method: The managed profiler has " + "not yet been loaded into AppDomain with id=", + module_metadata.app_domain_id, " token=", function_token, " caller_name=", caller->type.name, ".", + caller->name, "()"); + return S_FALSE; + } + + // *** Create rewriter + ILRewriter rewriter(corProfiler->info_, methodHandler->GetFunctionControl(), module_id, function_token); + auto hr = rewriter.Import(); + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() Call to ILRewriter.Import() failed for ", module_id, " ", + function_token); + return E_FAIL; + } + + // *** Store the original il code text if the dump_il option is enabled. + std::string original_code; + if (IsDumpILRewriteEnabled()) + { + original_code = corProfiler->GetILCodes("*** DebuggerMethodRewriter::Rewrite() Original Code: ", &rewriter, + *caller, module_metadata.metadata_import); + } + + // *** Get the locals signature. + FunctionLocalSignature localSignature; + hr = GetFunctionLocalSignature(module_metadata, rewriter, localSignature); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() failed to parse locals signature for ", module_id, " ", + function_token); + return E_FAIL; + } + + std::vector methodLocals = localSignature.GetMethodLocals(); + int numLocals = localSignature.NumberOfLocals(); + + if (trace::Logger::IsDebugEnabled()) + { + Logger::Debug("*** DebuggerMethodRewriter::Rewrite() Start: ", caller->type.name, ".", caller->name, + "() [IsVoid=", isVoid, ", IsStatic=", isStatic, ", Arguments=", numArgs, "]"); + } + + // *** Create the rewriter wrapper helper + ILRewriterWrapper rewriterWrapper(&rewriter); + rewriterWrapper.SetILPosition(rewriter.GetILList()->m_pNext); + // *** Modify the Local Var Signature of the method and initialize the new local vars + ULONG callTargetStateIndex = static_cast(ULONG_MAX); + ULONG exceptionIndex = static_cast(ULONG_MAX); + ULONG callTargetReturnIndex = static_cast(ULONG_MAX); + ULONG returnValueIndex = static_cast(ULONG_MAX); + mdToken callTargetStateToken = mdTokenNil; + mdToken exceptionToken = mdTokenNil; + mdToken callTargetReturnToken = mdTokenNil; + ILInstr* firstInstruction; + hr = debuggerTokens->ModifyLocalSigAndInitialize(&rewriterWrapper, caller, &callTargetStateIndex, &exceptionIndex, + &callTargetReturnIndex, &returnValueIndex, &callTargetStateToken, + &exceptionToken, &callTargetReturnToken, &firstInstruction); + + if (FAILED(hr)) + { + // Error message is already written in ModifyLocalSigAndInitialize + return S_FALSE; // TODO https://datadoghq.atlassian.net/browse/DEBUG-706 + } + + ULONG lineProbeCallTargetStateIndex = static_cast(ULONG_MAX); + mdToken lineProbeCallTargetStateToken = mdTokenNil; + hr = debuggerTokens->GetDebuggerLocals(&rewriterWrapper, &lineProbeCallTargetStateIndex, + &lineProbeCallTargetStateToken); + + if (FAILED(hr)) + { + Logger::Error("Failed to get DebuggerLocals for ", module_id, " ", function_token); + return E_FAIL; + } + + const auto instrumentedMethodIndex = GetNextInstrumentedMethodIndex(); + std::vector newClauses; + + // *** + // BEGIN LINE PROBES PART + // *** + + const auto& beforeLineProbe = rewriterWrapper.GetCurrentILInstr(); + + // TODO support multiple line probes & multiple line probes on the same bytecode offset (by deduplicating the probe ids) + + if (!lineProbes.empty()) + { + hr = ApplyLineProbes(instrumentedMethodIndex, lineProbes, corProfiler, module_id, module_metadata, caller, + debuggerTokens, function_token, isStatic, methodArguments, numArgs, rewriter, methodLocals, + numLocals, rewriterWrapper, lineProbeCallTargetStateIndex, newClauses); + if (FAILED(hr)) + { + // Appropriate error message is already logged in ApplyLineProbes. + return E_FAIL; + } + } + + // *** + // BEGIN METHOD PROBE PART + // *** + + if (!methodProbes.empty()) + { + const auto& methodProbeId = methodProbes[0]->probeId; // TODO accept multiple probeIds + + Logger::Info("Applying Method Probe instrumentation with probeId.", methodProbeId); + + hr = ApplyMethodProbe(corProfiler, module_id, module_metadata, caller, debuggerTokens, function_token, + retFuncArg, isVoid, isStatic, methodArguments, numArgs, methodProbeId, rewriter, + methodLocals, numLocals, rewriterWrapper, callTargetStateIndex, exceptionIndex, + callTargetReturnIndex, returnValueIndex, callTargetReturnToken, firstInstruction, + instrumentedMethodIndex, beforeLineProbe, newClauses); + if (FAILED(hr)) + { + // Appropriate error message is already logged in ApplyMethodProbe. + return E_FAIL; + } + } + + // *** + // Update and Add exception clauses + // *** + + auto ehCount = rewriter.GetEHCount(); + auto ehPointer = rewriter.GetEHPointer(); + auto newClausesCount = static_cast(newClauses.size()); + auto newEHClauses = new EHClause[ehCount + newClausesCount]; + for (unsigned i = 0; i < ehCount; i++) + { + newEHClauses[i] = ehPointer[i]; + } + + // *** Add the new EH clauses + ehCount += newClausesCount; + + std::sort(newClauses.begin(), newClauses.end(), + [](EHClause a, EHClause b) { return a.m_pTryBegin->m_offset < b.m_pTryBegin->m_offset; }); + + for (auto ehClauseIndex = 0; ehClauseIndex < newClausesCount; ehClauseIndex++) + { + newEHClauses[ehCount - newClausesCount + ehClauseIndex] = newClauses[ehClauseIndex]; + } + + rewriter.SetEHClause(newEHClauses, ehCount); + + if (IsDumpILRewriteEnabled()) + { + Logger::Info(original_code); + Logger::Info(corProfiler->GetILCodes("*** Rewriter(): Modified Code: ", &rewriter, *caller, + module_metadata.metadata_import)); + } + + hr = rewriter.Export(); + + if (FAILED(hr)) + { + Logger::Warn("*** DebuggerMethodRewriter::Rewrite() Call to ILRewriter.Export() failed for " + "ModuleID=", + module_id, " ", function_token); + return E_FAIL; + } + + Logger::Info("*** DebuggerMethodRewriter::Rewrite() Finished: ", caller->type.name, ".", caller->name, + "() [IsVoid=", isVoid, ", IsStatic=", isStatic, ", Arguments=", numArgs, "]"); + return S_OK; +} + +void DebuggerMethodRewriter::AdjustExceptionHandlingClauses(ILInstr* pFromInstr, ILInstr* pToInstr, + ILRewriter* pRewriter) +{ + const auto& ehClauses = pRewriter->GetEHPointer(); + const auto ehCount = pRewriter->GetEHCount(); + + for (unsigned ehIndex = 0; ehIndex < ehCount; ehIndex++) + { + if (ehClauses[ehIndex].m_pTryBegin == pFromInstr) + { + // TODO log + ehClauses[ehIndex].m_pTryEnd = pToInstr; + } + + if (ehClauses[ehIndex].m_pHandlerBegin == pFromInstr) + { + // TODO log + ehClauses[ehIndex].m_pHandlerBegin = pToInstr; + } + + if (ehClauses[ehIndex].m_pFilter == pFromInstr) + { + // TODO log + ehClauses[ehIndex].m_pFilter = pToInstr; + } + } +} + +std::vector DebuggerMethodRewriter::GetBranchTargets(ILRewriter* pRewriter) +{ + std::vector branchTargets{}; + + for (auto pInstr = pRewriter->GetILList()->m_pNext; pInstr != pRewriter->GetILList(); pInstr = pInstr->m_pNext) + { + if (ILRewriter::IsBranchTarget(pInstr)) + { + branchTargets.emplace_back(pInstr); + } + } + + return branchTargets; +} + +void DebuggerMethodRewriter::AdjustBranchTargets(ILInstr* pFromInstr, ILInstr* pToInstr, + const std::vector& branchTargets) +{ + for (const auto& branchInstr : branchTargets) + { + if (branchInstr->m_pTarget == pFromInstr) + { + branchInstr->m_pTarget = pToInstr; + } + } } } // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.h index 9276ded15..b3d852674 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_method_rewriter.h @@ -1,7 +1,10 @@ #ifndef DD_CLR_PROFILER_DEBUGGER_METHOD_REWRITER_H_ #define DD_CLR_PROFILER_DEBUGGER_METHOD_REWRITER_H_ +#include "cor_profiler.h" +#include "il_rewriter_wrapper.h" #include "method_rewriter.h" +#include "module_metadata.h" #include "../../../shared/src/native-src/util.h" using namespace trace; @@ -16,6 +19,59 @@ class DebuggerMethodRewriter : public MethodRewriter, public shared::Singleton _nextInstrumentedMethodIndex{0}; + + static int GetNextInstrumentedMethodIndex(); + + static HRESULT GetFunctionLocalSignature(const ModuleMetadata& module_metadata, ILRewriter& rewriter, FunctionLocalSignature& localSignature); + static HRESULT LoadArgument(CorProfiler* corProfiler, bool isStatic, const ILRewriterWrapper& rewriterWrapper, int argumentIndex, + const TypeSignature& argument); + static HRESULT LoadLocal(CorProfiler* corProfiler, const ILRewriterWrapper& rewriterWrapper, int localIndex, + const TypeSignature& argument); + static HRESULT WriteCallsToLogArgOrLocal(CorProfiler* corProfiler, DebuggerTokens* debuggerTokens, bool isStatic, + const std::vector& methodArgsOrLocals, int numArgsOrLocals, + ILRewriterWrapper& rewriterWrapper, ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, bool isArgs, bool isMethodProbe); + static HRESULT WriteCallsToLogArg(CorProfiler* corProfiler, DebuggerTokens* debuggerTokens, bool isStatic, + const std::vector& args, int numArgs, ILRewriterWrapper& rewriterWrapper, + ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, bool isMethodProbe); + static HRESULT WriteCallsToLogLocal(CorProfiler* corProfiler, DebuggerTokens* debuggerTokens, bool isStatic, + const std::vector& locals, int numLocals, + ILRewriterWrapper& rewriterWrapper, ULONG callTargetStateIndex, + ILInstr** beginCallInstruction, bool isMethodProbe); + static HRESULT LoadInstanceIntoStack(FunctionInfo* caller, bool isStatic, const ILRewriterWrapper& rewriterWrapper, ILInstr** outLoadArgumentInstr); + static HRESULT CallLineProbe(int instrumentedMethodIndex, CorProfiler* corProfiler, ModuleID module_id, + ModuleMetadata& module_metadata, FunctionInfo* caller, DebuggerTokens* debuggerTokens, + mdToken function_token, bool isStatic, std::vector& methodArguments, + int numArgs, ILRewriter& rewriter, std::vector& methodLocals, + int numLocals, ILRewriterWrapper& rewriterWrapper, ULONG lineProbeCallTargetStateIndex, + std::vector& lineProbesEHClauses, const std::vector& branchTargets, + const std::shared_ptr& lineProbe); + HRESULT ApplyLineProbes(int instrumentedMethodIndex, const LineProbeDefinitions& lineProbes, + CorProfiler* corProfiler, ModuleID module_id, ModuleMetadata& module_metadata, + FunctionInfo* caller, DebuggerTokens* debuggerTokens, mdToken function_token, bool isStatic, + std::vector& methodArguments, int numArgs, ILRewriter& rewriter, + std::vector& methodLocals, int numLocals, ILRewriterWrapper& rewriterWrapper, + ULONG lineProbeCallTargetStateIndex, std::vector& lineProbesEHClauses) const; + HRESULT ApplyMethodProbe(CorProfiler* corProfiler, ModuleID module_id, ModuleMetadata& module_metadata, + FunctionInfo* caller, DebuggerTokens* debuggerTokens, mdToken function_token, + TypeSignature retFuncArg, bool isVoid, bool isStatic, + std::vector methodArguments, + int numArgs, const shared::WSTRING& methodProbeId, ILRewriter& rewriter, + std::vector& methodLocals, int numLocals, ILRewriterWrapper& rewriterWrapper, + ULONG callTargetStateIndex, ULONG exceptionIndex, ULONG callTargetReturnIndex, + ULONG returnValueIndex, mdToken callTargetReturnToken, ILInstr* firstInstruction, + int instrumentedMethodIndex, ILInstr* const& beforeLineProbe, std::vector& newClauses) const; + + HRESULT Rewrite(RejitHandlerModule* moduleHandler, RejitHandlerModuleMethod* methodHandler, + MethodProbeDefinitions& methodProbes, + LineProbeDefinitions& lineProbes) const; + static std::vector GetBranchTargets(ILRewriter* pRewriter); + static void AdjustBranchTargets(ILInstr* pFromInstr, ILInstr* pToInstr, const std::vector& branchTargets); + static void AdjustExceptionHandlingClauses(ILInstr* pFromInstr, ILInstr* pToInstr, ILRewriter* pRewriter); + public: HRESULT Rewrite(RejitHandlerModule* moduleHandler, RejitHandlerModuleMethod* methodHandler) override; }; diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.cpp index ccfa24ca6..47ad09a42 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.cpp @@ -7,34 +7,268 @@ #include "stats.h" #include "version.h" #include "debugger_rejit_preprocessor.h" +#include "debugger_constants.h" +#include "debugger_environment_variables_util.h" +#include "debugger_rejit_handler_module_method.h" +#include "probes_tracker.h" namespace debugger { -DebuggerProbesInstrumentationRequester::DebuggerProbesInstrumentationRequester(std::shared_ptr rejit_handler, std::shared_ptr work_offloader) +/** + * \brief For testing purposes only. This method is used to determine if we are in "instrument-all mode", in which case we should instrument every single method on the given assembly. + * \This mode is enabled when the environment variable `SIGNALFX_INTERNAL_DEBUGGER_INSTRUMENT_ALL` is set to true. + * \param assemblyName the name of the assembly we're trying to rewrite using Debugger's Instrumentation + * \return true if the given assembly is viable for instrument-all, false otherwise. + */ +bool DebuggerProbesInstrumentationRequester::ShouldPerformInstrumentAll(const WSTRING& assemblyName) { - debugger_rejit_preprocessor = std::make_unique(std::move(rejit_handler), std::move(work_offloader)); + for (auto&& skip_assembly_pattern : skip_assembly_prefixes) + { + if (assemblyName.rfind(skip_assembly_pattern, 0) == 0) + { + Logger::Debug("DebuggerInstrumentAllHelper::ShouldPerformInstrumentAll skipping module by pattern: Name=", + assemblyName); + return false; + } + } + + for (auto&& skip_assembly : skip_assemblies) + { + if (assemblyName == skip_assembly) + { + Logger::Debug("DebuggerInstrumentAllHelper::ShouldPerformInstrumentAll skipping module by exact name: Name= ", + assemblyName); + return false; + } + } + + return true; } -void DebuggerProbesInstrumentationRequester::InstrumentProbes(WCHAR* id, DebuggerMethodProbeDefinition* items, int size, - CorProfiler* corProfiler) +/** + * \brief For Testing-Purposes. Requests ReJIT for the given method if certain checks are met. Relevant when the environment variable `SIGNALFX_INTERNAL_DEBUGGER_INSTRUMENT_ALL` is set to true. + * \param module_info the ModuleInfo of the module entering into instrumentation-all. + * \param module_id the ModuleID of the module entering into instrumentation-all. + * \param function_token the mdToken of the method entering into instrumentation-all. + */ +void DebuggerProbesInstrumentationRequester::PerformInstrumentAllIfNeeded(const ModuleID& module_id, const mdToken& function_token) { - // TODO: - //auto _ = trace::Stats::Instance()->InitializeLiveDebuggerMeasure(); + if (!IsDebuggerInstrumentAllEnabled()) + { + return; + } - shared::WSTRING definitionsId = shared::WSTRING(id); - Logger::Info("InitializeLiveDebugger: received id: ", definitionsId, " from managed side with ", size, - " integrations."); + const auto corProfiler = trace::profiler; + const auto& module_info = GetModuleInfo(corProfiler->info_, module_id); + const auto assembly_name = module_info.assembly.name; - if (items != nullptr) + if (ShouldPerformInstrumentAll(assembly_name)) { + ComPtr metadataInterfaces; + auto hr = corProfiler->info_->GetModuleMetaData(module_id, ofRead | ofWrite, IID_IMetaDataImport2, + metadataInterfaces.GetAddressOf()); + + auto metadataImport = metadataInterfaces.As(IID_IMetaDataImport); + auto metadataEmit = metadataInterfaces.As(IID_IMetaDataEmit); + auto assemblyImport = metadataInterfaces.As(IID_IMetaDataAssemblyImport); + auto assemblyEmit = metadataInterfaces.As(IID_IMetaDataAssemblyEmit); + + Logger::Debug("Temporaly allocating the ModuleMetadata for injection. ModuleId=", module_id, + " ModuleName=", module_info.assembly.name); + + std::unique_ptr module_metadata = std::make_unique( + metadataImport, metadataEmit, assemblyImport, assemblyEmit, module_info.assembly.name, + module_info.assembly.app_domain_id, &corProfiler->corAssemblyProperty, + corProfiler->enable_by_ref_instrumentation, corProfiler->enable_calltarget_state_by_ref); + + // get function info + auto caller = GetFunctionInfo(module_metadata->metadata_import, function_token); + if (!caller.IsValid()) + { + return; + } + + hr = caller.method_signature.TryParse(); + if (FAILED(hr)) + { + Logger::Warn(" * DebuggerProbesInstrumentationRequester::PerformInstrumentAllIfNeeded: The method signature: ", caller.method_signature.str(), " cannot be parsed."); + return; + } + + Logger::Debug("About to perform instrument all for ModuleId=", module_id, + " ModuleName=", module_info.assembly.name, + " MethodName=", caller.name, " TypeName=", caller.type.name); + + // In the Debugger product, we don't care about module versioning. Thus we intentionally avoid it. + const static Version& minVersion = Version(0, 0, 0, 0); + const static Version& maxVersion = Version(65535, 65535, 65535, 0); + + const auto targetAssembly = module_info.assembly.name; + + const auto numOfArgs = caller.method_signature.NumberOfArguments(); + const auto& methodArguments = caller.method_signature.GetMethodArguments(); + std::vector signatureTypes; + + // We should ALWAYS push something in front of the arguments list as the Preprocessor requires the return value to be there, + // even if there are none (in which case, it should be System.Void). + // The Preprocessor is not using the return value at all (and merely skipping it), so we insert an empty string. + signatureTypes.push_back(WSTRING()); + + Logger::Debug(" * Comparing signature for method: ", caller.type.name, ".", caller.name); + for (unsigned int i = 0; i < numOfArgs; i++) + { + signatureTypes.push_back(methodArguments[i].GetTypeTokName(metadataImport)); + } + + const auto& methodProbe = MethodProbeDefinition( + WStr("ProbeId"), + MethodReference(targetAssembly, caller.type.name, caller.name, minVersion, maxVersion, signatureTypes), + /* is_exact_signature_match */ false); + + const auto numReJITs = m_debugger_rejit_preprocessor->RequestRejitForLoadedModules( + std::vector{module_id}, + std::vector{methodProbe}, + /* enqueueInSameThread */ true); + Logger::Debug("Instrument-All: Total number of ReJIT Requested: ", numReJITs); + } +} + + +DebuggerProbesInstrumentationRequester::DebuggerProbesInstrumentationRequester( + std::shared_ptr rejit_handler, + std::shared_ptr work_offloader) : + m_rejit_handler(rejit_handler), m_work_offloader(work_offloader) +{ + m_debugger_rejit_preprocessor = std::make_unique(rejit_handler, work_offloader); +} + +void DebuggerProbesInstrumentationRequester::RemoveProbes(debugger::DebuggerRemoveProbesDefinition* removeProbes, + int removeProbesLength, + std::set& revertRequests) +{ + if (removeProbes != nullptr) + { + Logger::Info("LiveDebugger: received request to remove ", removeProbesLength, " probes from the managed side."); + + if (removeProbesLength <= 0) return; + + std::vector probeIdsToRemove; + + for (int i = 0; i < removeProbesLength; i++) + { + const DebuggerRemoveProbesDefinition& current = removeProbes[i]; + probeIdsToRemove.emplace_back(WSTRING(current.probeId)); + } + + for (const auto& probeIdToRemove : probeIdsToRemove) + { + // Remove from `DebuggerRejitHandlerModuleMethod` + std::shared_ptr probeMetadata; + if (ProbesMetadataTracker::Instance()->TryGetMetadata(probeIdToRemove, probeMetadata)) + { + for (const auto& method : probeMetadata->methods) + { + const auto moduleHandler = m_rejit_handler->GetOrAddModule(method.moduleId); + if (moduleHandler == nullptr) + { + Logger::Warn("Module handler is returned as null while tried to RemoveProbes, this only " + "happens if the RejitHandler has been shutdown. Exiting early from RemoveProbes."); + return; // Exit from RemoveProbes + } + + if (moduleHandler->GetModuleMetadata() == nullptr) + { + Logger::Error("Could not find the module metadata of method mdToken", method.methodToken, + ", probeId: ", probeIdToRemove, " while trying to remove a probe"); + continue; + } + + RejitHandlerModuleMethod* methodHandler = nullptr; + if (!moduleHandler->TryGetMethod(method.methodToken, &methodHandler)) + { + Logger::Error("Could not find the correct method mdToken", method.methodToken, + ", probeId: ", probeIdToRemove, " while trying to remove a probe"); + continue; + } + + const auto debuggerMethodHandler = dynamic_cast(methodHandler); + + if (debuggerMethodHandler == nullptr) + { + Logger::Error("The method handler of the probe Id we're trying to remove is not of the correct " + "type. Probe Id: ", + probeIdToRemove); + continue; + } + + if (!debuggerMethodHandler->RemoveProbe(probeIdToRemove)) + { + Logger::Error("Could not remove from the method handler Probe Id: ", probeIdToRemove); + continue; + } + else + { + Logger::Info("Removed from the method handler Probe Id: ", probeIdToRemove); + } + + revertRequests.emplace(method); + } + } + else + { + Logger::Error("Received probeId that does not exist in MethodIdentifier mapping. Probe Id: ", probeIdToRemove); + continue; + } + + // Remove from probes_ + + auto removedFromProbes_ = false; + for (auto probeIter = m_probes.begin(); probeIter != m_probes.end(); ++probeIter) + { + if ((*probeIter)->probeId == probeIdToRemove) + { + probeIter->reset(); + m_probes.erase(probeIter); + removedFromProbes_ = true; + break; + } + } + + if (!removedFromProbes_) + { + Logger::Error("Could not find Probe Id", probeIdToRemove, " in probes_."); + } + } + + // Remove from ProbesTracker + const auto removedProbesCount = ProbesMetadataTracker::Instance()->RemoveProbes(probeIdsToRemove); + Logger::Info("Successfully removed ", removedProbesCount, " probes from the ProbesTracker."); + } +} + + +void DebuggerProbesInstrumentationRequester::AddMethodProbes( + debugger::DebuggerMethodProbeDefinition* methodProbes, + int methodProbesLength, + std::set& rejitRequests) +{ + if (methodProbes != nullptr) + { + Logger::Info("InitializeLiveDebugger: received ", methodProbesLength, " integrations from managed side."); + + if (methodProbesLength <= 0) + return; + + const auto corProfiler = trace::profiler; + std::vector methodProbeDefinitions; - for (int i = 0; i < size; i++) + for (int i = 0; i < methodProbesLength; i++) { - const DebuggerMethodProbeDefinition& current = items[i]; + const DebuggerMethodProbeDefinition& current = methodProbes[i]; - const shared::WSTRING& targetAssembly = shared::WSTRING(current.targetAssembly); + const shared::WSTRING& probeId = shared::WSTRING(current.probeId); const shared::WSTRING& targetType = shared::WSTRING(current.targetType); const shared::WSTRING& targetMethod = shared::WSTRING(current.targetMethod); @@ -48,49 +282,315 @@ void DebuggerProbesInstrumentationRequester::InstrumentProbes(WCHAR* id, Debugge } } - const auto methodProbe = MethodProbeDefinition( - MethodReference(targetAssembly, targetType, targetMethod, {}, {}, signatureTypes)); + // If the Method Probe request has a signature associated with it, then find that exact match. + // Otherwise, instrument all overloads of that method regardless of their signature. + bool isExactSignatureMatch = current.targetParameterTypesLength > 0; + + // In the Debugger product, we don't care about module versioning. Thus we intentionally avoid it. + const static Version& minVersion = Version(0, 0, 0, 0); + const static Version& maxVersion = Version(65535, 65535, 65535, 0); + + const auto& methodProbe = MethodProbeDefinition( + probeId, + MethodReference({}, targetType, targetMethod, minVersion, maxVersion, signatureTypes), + isExactSignatureMatch); if (Logger::IsDebugEnabled()) { - Logger::Debug(" * Target: ", targetAssembly, " | ", targetType, ".", targetMethod, "(", + Logger::Debug(" * Target: ", targetType, ".", targetMethod, "(", signatureTypes.size(), ")"); } methodProbeDefinitions.push_back(methodProbe); + ProbesMetadataTracker::Instance()->CreateNewProbeIfNotExists(probeId); } - std::scoped_lock moduleLock(corProfiler->module_ids_lock_); - - Logger::Info("Total number of modules to analyze: ", corProfiler->module_ids_.size()); + std::scoped_lock moduleLock(trace::profiler->module_ids_lock_); - std::promise promise; - std::future future = promise.get_future(); - debugger_rejit_preprocessor->EnqueueRequestRejitForLoadedModules(corProfiler->module_ids_, - methodProbeDefinitions, &promise); + std::promise> promise; + std::future> future = promise.get_future(); + m_debugger_rejit_preprocessor->EnqueuePreprocessRejitRequests(corProfiler->module_ids_, methodProbeDefinitions, &promise); - // wait and get the value from the future - const auto& numReJITs = future.get(); - Logger::Debug("Total number of ReJIT Requested: ", numReJITs); + const auto& methodProbeRequests = future.get(); - method_probes_.reserve(method_probes_.size() + methodProbeDefinitions.size()); + if (!methodProbeRequests.empty()) + { + rejitRequests.insert(methodProbeRequests.begin(), methodProbeRequests.end()); + } + else + { + Logger::Warn( + "Received empty list of method probe requests from EnqueuePreprocessRejitRequests after enqueuing ", + methodProbesLength, " method probes."); + } + + m_probes.reserve(m_probes.size() + methodProbeDefinitions.size()); for (const auto& methodProbe : methodProbeDefinitions) { - method_probes_.push_back(methodProbe); + m_probes.push_back(std::make_shared(methodProbe)); + } + } +} + +void DebuggerProbesInstrumentationRequester::AddLineProbes( + debugger::DebuggerLineProbeDefinition* lineProbes, + int lineProbesLength, + std::set& rejitRequests) +{ + if (lineProbes != nullptr) + { + Logger::Info("InitializeLiveDebugger: received ", lineProbesLength, " integrations from managed side."); + + if (lineProbesLength <= 0) + return; + + const auto corProfiler = trace::profiler; + + LineProbeDefinitions lineProbeDefinitions; + + for (int i = 0; i < lineProbesLength; i++) + { + const DebuggerLineProbeDefinition& current = lineProbes[i]; + + const shared::WSTRING& probeId = shared::WSTRING(current.probeId); + const shared::WSTRING& probeFilePath = shared::WSTRING(current.probeFilePath); + const auto& lineProbe = std::make_shared(LineProbeDefinition(probeId, current.bytecodeOffset, current.lineNumber, current.mvid, current.methodId, probeFilePath)); + + lineProbeDefinitions.push_back(lineProbe); + } + + std::scoped_lock moduleLock(trace::profiler->module_ids_lock_); + + std::promise> promise; + std::future> future = promise.get_future(); + m_debugger_rejit_preprocessor->EnqueuePreprocessLineProbes(corProfiler->module_ids_, lineProbeDefinitions, &promise); + + const auto& lineProbeRequests = future.get(); + + if (!lineProbeRequests.empty()) + { + rejitRequests.insert(lineProbeRequests.begin(), lineProbeRequests.end()); + } + else + { + Logger::Warn( + "Received empty list of line probe requests from EnqueuePreprocessLineProbes after enqueuing ", + lineProbesLength, " line probes."); + } + + m_probes.reserve(m_probes.size() + lineProbeDefinitions.size()); + for (const auto& lineProbe : lineProbeDefinitions) + { + m_probes.push_back(lineProbe); } - Logger::Info("InitializeLiveDebugger: Total startup method probes: ", method_probes_.size()); + Logger::Info("LiveDebugger: Total method probes added: ", m_probes.size()); } } -const std::vector& DebuggerProbesInstrumentationRequester::GetProbes() const +/// +/// Re-Instrument is the practice of requesting revert & reijt to restore method(s) to their original form and then re-instrument them. +/// In case a revert was requested for a method, we need to determine if that method have other probes associated with them, +/// in which case we should re-instrument them. +/// +/// Methods to revert. +/// [OUT] Gets populated with methods that needs to go through re-instrumentation. +void DebuggerProbesInstrumentationRequester::DetermineReInstrumentProbes(std::set& revertRequests, + std::set& reInstrumentRequests) const { - return method_probes_; + if (revertRequests.empty()) + return; + + for (const auto& request : revertRequests) + { + const auto moduleHandler = m_rejit_handler->GetOrAddModule(request.moduleId); + if (moduleHandler == nullptr) + { + Logger::Warn("Module handler is returned as null while tried to RemoveProbes, this only happens if " + "the RejitHandler has been shutdown. Exiting early from RemoveProbes."); + return; // Exit from RemoveProbes + } + + if (moduleHandler->GetModuleMetadata() == nullptr) + { + Logger::Error("Could not find the module metadata of method mdToken ", request.methodToken, " while trying to remove a probe"); + continue; + } + + RejitHandlerModuleMethod* methodHandler = nullptr; + if (!moduleHandler->TryGetMethod(request.methodToken, &methodHandler)) + { + Logger::Error("Could not find the correct method mdToken ", request.methodToken, " while trying to remove a probe"); + continue; + } + + const auto debuggerMethodHandler = dynamic_cast(methodHandler); + + if (debuggerMethodHandler == nullptr) + { + Logger::Error("The method handler of the probe Id we're trying to remove is not of the correct type"); + continue; + } + + if (!debuggerMethodHandler->GetProbes().empty()) + { + reInstrumentRequests.emplace(request); + } + } +} + +void DebuggerProbesInstrumentationRequester::InstrumentProbes(debugger::DebuggerMethodProbeDefinition* methodProbes, + int methodProbesLength, + debugger::DebuggerLineProbeDefinition* lineProbes, + int lineProbesLength, + debugger::DebuggerRemoveProbesDefinition* removeProbes, + int removeProbesLength) +{ + std::lock_guard lock(m_probes_mutex); + + std::set revertRequests{}; + RemoveProbes(removeProbes, removeProbesLength, revertRequests); + + std::set rejitRequests{}; + AddMethodProbes(methodProbes, methodProbesLength, rejitRequests); + AddLineProbes(lineProbes, lineProbesLength, rejitRequests); + + std::set reInstrumentRequests{}; + DetermineReInstrumentProbes(revertRequests, reInstrumentRequests); + + if (!rejitRequests.empty()) + { + // Treat instrumentation requests as 're-instrument'. + // Meaning, for each instrumentation request of a method we first request a revert. + // We do that to restore methods to their original form, as our rejit logic assumes we are rewriting the method + // from scratch. If a method was never instrumented before then it's NoOp. + // In other words, calling revert on a method that was never rejitted before makes our lives easier, and doesn't + // cause any harm. + revertRequests.insert(rejitRequests.begin(), rejitRequests.end()); + } + + if (!reInstrumentRequests.empty()) + { + rejitRequests.insert(reInstrumentRequests.begin(), reInstrumentRequests.end()); + } + + // We offload the actual `RequestRejit` & `RequestRevert` to a separate thread because they are not permitted + // to be called from managed land. + + if (!revertRequests.empty()) + { + Logger::Info("About to RequestRevert for ", revertRequests.size(), " methods."); + + // RequestRevert + std::vector requests(revertRequests.size()); + std::copy(revertRequests.begin(), revertRequests.end(), requests.begin()); + std::promise promise; + std::future future = promise.get_future(); + m_debugger_rejit_preprocessor->EnqueueRequestRevert(requests, &promise); + // wait and get the value from the future + future.get(); + } + + if (!rejitRequests.empty()) + { + Logger::Info("About to RequestRejit for ", rejitRequests.size(), " methods."); + + // RequestRejit + std::promise promise; + std::future future = promise.get_future(); + std::vector requests(rejitRequests.size()); + std::copy(rejitRequests.begin(), rejitRequests.end(), requests.begin()); + m_debugger_rejit_preprocessor->EnqueueRequestRejit(requests, &promise); + // wait and get the value from the future + future.get(); + } +} + +int DebuggerProbesInstrumentationRequester::GetProbesStatuses(WCHAR** probeIds, int probeIdsLength, debugger::DebuggerProbeStatus* probeStatuses) +{ + if (probeIds == nullptr) + { + return 0; + } + + Logger::Info("Received ", probeIdsLength, " probes (ids) from managed side for status."); + + if (probeIdsLength <= 0) + { + return 0; + } + + int probeStatusesCount = 0; + + for (auto probeIndex = 0; probeIndex < probeIdsLength; probeIndex++) + { + const auto& probeId = shared::WSTRING(probeIds[probeIndex]); + std::shared_ptr probeMetadata; + if (ProbesMetadataTracker::Instance()->TryGetMetadata(probeId, probeMetadata)) + { + probeStatuses[probeStatusesCount] = + {probeMetadata->probeId.c_str(), probeMetadata->status}; + probeStatusesCount++; + } + else + { + Logger::Warn("Failed to get probe metadata for probeId = ", probeId, + " while trying to obtain its probe status."); + } + } + + return probeStatusesCount; +} + +const std::vector>& DebuggerProbesInstrumentationRequester::GetProbes() const +{ + return m_probes; } DebuggerRejitPreprocessor* DebuggerProbesInstrumentationRequester::GetPreprocessor() { - return debugger_rejit_preprocessor.get(); + return m_debugger_rejit_preprocessor.get(); +} + +ULONG DebuggerProbesInstrumentationRequester::RequestRejitForLoadedModule(const ModuleID moduleId) +{ + std::vector methodProbes; + + std::lock_guard lock(m_probes_mutex); + + for (const auto& probe : m_probes) + { + const auto methodProbe = std::dynamic_pointer_cast(probe); + if (methodProbe != nullptr) + { + methodProbes.emplace_back(*methodProbe); + } + } + + if (methodProbes.empty()) + { + return 0; + } + + return m_debugger_rejit_preprocessor->RequestRejitForLoadedModules(std::vector{moduleId}, methodProbes); + // TODO do it also for line probes (scenario: module loaded (line probe request arrived) & unloaded & loaded) +} + +HRESULT DebuggerProbesInstrumentationRequester::NotifyReJITError(ModuleID moduleId, mdMethodDef methodId, + FunctionID functionId, HRESULT hrStatus) +{ + const auto probeIds = ProbesMetadataTracker::Instance()->GetProbeIds(moduleId, methodId); + if (!probeIds.empty()) + { + Logger::Info("Marking ", probeIds.size(), " probes as failed due to ReJITError notification."); + for (const auto& probeId : probeIds) + { + Logger::Info("Marking ", probeId, " as Error."); + ProbesMetadataTracker::Instance()->SetProbeStatus(probeId, ProbeStatus::_ERROR); + } + } + + return S_OK; } } // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.h index e742b40eb..30db92656 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_probes_instrumentation_requester.h @@ -12,16 +12,36 @@ namespace debugger class DebuggerProbesInstrumentationRequester { private: - std::vector method_probes_; - std::unique_ptr debugger_rejit_preprocessor = nullptr; + std::recursive_mutex m_probes_mutex; + std::vector m_probes; + std::unique_ptr m_debugger_rejit_preprocessor = nullptr; + std::shared_ptr m_rejit_handler = nullptr; + std::shared_ptr m_work_offloader = nullptr; + + static bool ShouldPerformInstrumentAll(const WSTRING& assemblyName); + + void RemoveProbes(debugger::DebuggerRemoveProbesDefinition* removeProbes, int removeProbesLength, + std::set& revertRequests); + void AddMethodProbes(debugger::DebuggerMethodProbeDefinition* methodProbes, int methodProbesLength, + std::set& rejitRequests); + void AddLineProbes(debugger::DebuggerLineProbeDefinition* lineProbes, int lineProbesLength, + std::set& rejitRequests); + void DetermineReInstrumentProbes(std::set& revertRequests, std::set& reInstrumentRequests) const; public: DebuggerProbesInstrumentationRequester(std::shared_ptr rejit_handler, std::shared_ptr work_offloader); - void InstrumentProbes(WCHAR* id, DebuggerMethodProbeDefinition* items, int size, trace::CorProfiler* corProfiler); - const std::vector& GetProbes() const; + void InstrumentProbes(debugger::DebuggerMethodProbeDefinition* methodProbes, int methodProbesLength, + debugger::DebuggerLineProbeDefinition* lineProbes, int lineProbesLength, + debugger::DebuggerRemoveProbesDefinition* removeProbes, int removeProbesLength); + static int GetProbesStatuses(WCHAR** probeIds, int probeIdsLength, debugger::DebuggerProbeStatus* probeStatuses); + void PerformInstrumentAllIfNeeded(const ModuleID& module_id, const mdToken& function_token); + const std::vector>& GetProbes() const; DebuggerRejitPreprocessor* GetPreprocessor(); + ULONG RequestRejitForLoadedModule(const ModuleID moduleId); + + static HRESULT NotifyReJITError(ModuleID moduleId, mdMethodDef methodId, FunctionID functionId, HRESULT hrStatus); }; } // namespace debugger diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.cpp index 64a3c4f66..3f1e369bd 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.cpp @@ -7,21 +7,38 @@ namespace debugger DebuggerRejitHandlerModuleMethod::DebuggerRejitHandlerModuleMethod( mdMethodDef methodDef, RejitHandlerModule* module, - const FunctionInfo& functionInfo, - const MethodProbeDefinition& methodProbe) : - RejitHandlerModuleMethod(methodDef, module, functionInfo), - m_methodProbeDefinition(std::make_unique(methodProbe)) + const FunctionInfo& functionInfo) : + RejitHandlerModuleMethod(methodDef, module, functionInfo) { } -MethodProbeDefinition* DebuggerRejitHandlerModuleMethod::GetMethodProbeDefinition() +MethodRewriter* DebuggerRejitHandlerModuleMethod::GetMethodRewriter() { - return m_methodProbeDefinition.get(); + return DebuggerMethodRewriter::Instance(); } -MethodRewriter* DebuggerRejitHandlerModuleMethod::GetMethodRewriter() +void DebuggerRejitHandlerModuleMethod::AddProbe(ProbeDefinition_S probe) { - return DebuggerMethodRewriter::Instance(); + m_probes.push_back(probe); +} + +bool DebuggerRejitHandlerModuleMethod::RemoveProbe(const shared::WSTRING& probeId) +{ + for (auto probe = m_probes.begin(); probe != m_probes.end(); ++probe) + { + if ((*probe)->probeId == probeId) + { + m_probes.erase(probe); + return true; + } + } + + return false; +} + +std::vector& DebuggerRejitHandlerModuleMethod::GetProbes() +{ + return m_probes; } } // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.h index e32a93d6a..be3b87aa3 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_handler_module_method.h @@ -15,16 +15,17 @@ namespace debugger class DebuggerRejitHandlerModuleMethod : public RejitHandlerModuleMethod { private: - std::unique_ptr m_methodProbeDefinition; + std::vector m_probes; public: DebuggerRejitHandlerModuleMethod(mdMethodDef methodDef, RejitHandlerModule* module, - const FunctionInfo& functionInfo, - const MethodProbeDefinition& methodProbe); + const FunctionInfo& functionInfo); - MethodProbeDefinition* GetMethodProbeDefinition(); MethodRewriter* GetMethodRewriter() override; + void AddProbe(ProbeDefinition_S probe); + bool RemoveProbe(const shared::WSTRING& probeId); + std::vector& GetProbes(); }; } // namespace debugger diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.cpp index 33edebcb9..dfa4fc0d5 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.cpp @@ -1,33 +1,263 @@ #include "debugger_rejit_preprocessor.h" #include "debugger_rejit_handler_module_method.h" +#include "logger.h" +#include "probes_tracker.h" namespace debugger { // DebuggerRejitPreprocessor -const MethodReference& DebuggerRejitPreprocessor::GetTargetMethod(const debugger::MethodProbeDefinition& methodProbe) +ULONG DebuggerRejitPreprocessor::PreprocessLineProbes(const std::vector& modules, + const LineProbeDefinitions& lineProbes, std::vector& rejitRequests) const +{ + if (m_rejit_handler->IsShutdownRequested()) + { + return 0; + } + + auto corProfilerInfo = m_rejit_handler->GetCorProfilerInfo(); + auto pCorAssemblyProperty = m_rejit_handler->GetCorAssemblyProperty(); + auto enable_by_ref_instrumentation = m_rejit_handler->GetEnableByRefInstrumentation(); + auto enable_calltarget_state_by_ref = m_rejit_handler->GetEnableCallTargetStateByRef(); + + for (const auto& module : modules) + { + const ModuleInfo& moduleInfo = GetModuleInfo(corProfilerInfo, module); + Logger::Debug("Requesting Rejit for Module: ", moduleInfo.assembly.name); + + ComPtr metadataInterfaces; + ComPtr metadataImport; + ComPtr metadataEmit; + ComPtr assemblyImport; + ComPtr assemblyEmit; + std::unique_ptr assemblyMetadata = nullptr; + + Logger::Debug(" Loading Assembly Metadata..."); + auto hr = corProfilerInfo->GetModuleMetaData(moduleInfo.id, ofRead | ofWrite, IID_IMetaDataImport2, + metadataInterfaces.GetAddressOf()); + if (FAILED(hr)) + { + Logger::Warn("CallTarget_RequestRejitForModule failed to get metadata interface for ", moduleInfo.id, + " ", moduleInfo.assembly.name); + break; + } + + metadataImport = metadataInterfaces.As(IID_IMetaDataImport); + metadataEmit = metadataInterfaces.As(IID_IMetaDataEmit); + assemblyImport = metadataInterfaces.As(IID_IMetaDataAssemblyImport); + assemblyEmit = metadataInterfaces.As(IID_IMetaDataAssemblyEmit); + assemblyMetadata = std::make_unique(GetAssemblyImportMetadata(assemblyImport)); + Logger::Debug(" Assembly Metadata loaded for: ", assemblyMetadata->name, "(", + assemblyMetadata->version.str(), ")."); + + WCHAR moduleName[MAX_PACKAGE_NAME]; + ULONG nSize; + GUID analyzingModuleMvid; + hr = metadataImport->GetScopeProps(moduleName, MAX_PACKAGE_NAME, &nSize, &analyzingModuleMvid); + + if (FAILED(hr)) + { + // TODO Log + continue; + } + + for (const auto& lineProbe : lineProbes) + { + if (lineProbe->mvid != analyzingModuleMvid) + { + continue; + } + + const auto methodDef = lineProbe->methodId; + + const auto caller = GetFunctionInfo(metadataImport, methodDef); + if (!caller.IsValid()) + { + Logger::Warn(" * The caller for the methoddef: ", shared::TokenStr(&methodDef), " is not valid!"); + continue; + } + + // We create a new function info into the heap from the caller functionInfo in the stack, to + // be used later in the ReJIT process + auto functionInfo = FunctionInfo(caller); + auto hr = functionInfo.method_signature.TryParse(); + if (FAILED(hr)) + { + Logger::Warn(" * The method signature: ", functionInfo.method_signature.str(), " cannot be parsed."); + continue; + } + + auto moduleHandler = m_rejit_handler->GetOrAddModule(moduleInfo.id); + if (moduleHandler == nullptr) + { + Logger::Warn("Module handler is null, this only happens if the RejitHandler has been shutdown."); + break; + } + if (moduleHandler->GetModuleMetadata() == nullptr) + { + Logger::Debug("Creating ModuleMetadata..."); + + const auto moduleMetadata = new ModuleMetadata( + metadataImport, metadataEmit, assemblyImport, assemblyEmit, moduleInfo.assembly.name, + moduleInfo.assembly.app_domain_id, pCorAssemblyProperty, enable_by_ref_instrumentation, + enable_calltarget_state_by_ref); + + Logger::Info("ReJIT handler stored metadata for ", moduleInfo.id, " ", moduleInfo.assembly.name, + " AppDomain ", moduleInfo.assembly.app_domain_id, " ", + moduleInfo.assembly.app_domain_name); + + moduleHandler->SetModuleMetadata(moduleMetadata); + } + + RejitHandlerModuleMethodCreatorFunc creator = [=, functionInfo = functionInfo]( + const mdMethodDef method, RejitHandlerModule* moduleInScope) { + return CreateMethod(method, moduleInScope, functionInfo); + }; + + RejitHandlerModuleMethodUpdaterFunc updater = [=, request = lineProbe](RejitHandlerModuleMethod* method) { + return UpdateMethod(method, request); + }; + + moduleHandler->CreateMethodIfNotExists(methodDef, creator, updater); + + rejitRequests.emplace_back(MethodIdentifier(moduleInfo.id, methodDef)); + } + } + + const auto rejitCount = (ULONG) rejitRequests.size(); + + return rejitCount; +} + +void DebuggerRejitPreprocessor::EnqueuePreprocessLineProbes(const std::vector& modulesVector, + const LineProbeDefinitions& lineProbes, + std::promise>* promise) const +{ + std::vector rejitRequests; + + if (m_rejit_handler->IsShutdownRequested()) + { + if (promise != nullptr) + { + promise->set_value(rejitRequests); + } + + return; + } + + if (modulesVector.size() == 0 || lineProbes.size() == 0) + { + return; + } + + Logger::Debug("RejitHandler::EnqueuePreprocessRejitRequests"); + + std::function action = [=, modules = std::move(modulesVector), definitions = std::move(lineProbes), + rejitRequests = rejitRequests, promise = promise]() mutable { + // Process modules for rejit + const auto rejitCount = PreprocessLineProbes(modules, definitions, rejitRequests); + + // Resolve promise + if (promise != nullptr) + { + promise->set_value(rejitRequests); + } + }; + + // Enqueue + m_work_offloader->Enqueue(std::make_unique(std::move(action))); +} + +void DebuggerRejitPreprocessor::ProcessTypesForRejit( + std::vector& rejitRequests, const ModuleInfo& moduleInfo, ComPtr metadataImport, + ComPtr metadataEmit, ComPtr assemblyImport, + ComPtr assemblyEmit, const MethodProbeDefinition& definition, + const MethodReference& targetMethod) +{ + const auto instrumentationTargetTypeName = definition.target_method.type.name; + + // Is full name requested? + auto nameParts = shared::Split(instrumentationTargetTypeName, '.'); + + if (nameParts.size() > 1) + { + RejitPreprocessor::ProcessTypesForRejit(rejitRequests, moduleInfo, metadataImport, metadataEmit, assemblyImport, + assemblyEmit, definition, targetMethod); + return; + } + + // We received a single identifier as the class name. Find every class that has this name, while searching through all namespaces, + // and also taking into account the possibility that it's a nested class. + const auto asAnyNamespace = shared::ToString(WStr(".") + instrumentationTargetTypeName); + const auto asNestedType = shared::ToString(WStr("+") + instrumentationTargetTypeName); + + // Enumerate the types of the module + auto typeDefEnum = EnumTypeDefs(metadataImport); + auto typeDefIterator = typeDefEnum.begin(); + for (; typeDefIterator != typeDefEnum.end(); typeDefIterator = ++typeDefIterator) + { + auto typeDef = *typeDefIterator; + const auto typeInfo = GetTypeInfo(metadataImport, typeDef); + + if (typeInfo.name == instrumentationTargetTypeName || + EndsWith(shared::ToString(typeInfo.name), asAnyNamespace) || + EndsWith(shared::ToString(typeInfo.name), asNestedType)) + { + // Now that we found the type, look for the methods within that type we want to instrument + RejitPreprocessor::ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, + assemblyEmit, moduleInfo, typeDef, rejitRequests); + } + } +} + +const MethodReference& DebuggerRejitPreprocessor::GetTargetMethod(const MethodProbeDefinition& methodProbe) { return methodProbe.target_method; } -const bool DebuggerRejitPreprocessor::GetIsDerived(const debugger::MethodProbeDefinition& methodProbe) +const bool DebuggerRejitPreprocessor::GetIsDerived(const MethodProbeDefinition& methodProbe) { return false; // TODO } -const bool DebuggerRejitPreprocessor::GetIsExactSignatureMatch(const debugger::MethodProbeDefinition& methodProbe) +const bool DebuggerRejitPreprocessor::GetIsExactSignatureMatch(const MethodProbeDefinition& methodProbe) { - return true; // TODO + return methodProbe.is_exact_signature_match; } const std::unique_ptr DebuggerRejitPreprocessor::CreateMethod( const mdMethodDef methodDef, RejitHandlerModule* module, - const FunctionInfo& functionInfo, - const MethodProbeDefinition& methodProbeDefinition) + const FunctionInfo& functionInfo, + const MethodProbeDefinition& methodProbe) +{ + return std::make_unique(methodDef, module, functionInfo); +} + +const std::unique_ptr +DebuggerRejitPreprocessor::CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module, const FunctionInfo& functionInfo) const +{ + return std::make_unique(methodDef, module, functionInfo); +} + +void DebuggerRejitPreprocessor::UpdateMethod(RejitHandlerModuleMethod* methodHandler, const MethodProbeDefinition& methodProbe) +{ + UpdateMethod(methodHandler, std::make_shared(methodProbe)); +} + +void DebuggerRejitPreprocessor::UpdateMethod(RejitHandlerModuleMethod* methodHandler, const ProbeDefinition_S& probe) +{ + const auto debuggerMethodHandler = dynamic_cast(methodHandler); + debuggerMethodHandler->AddProbe(probe); + ProbesMetadataTracker::Instance()->AddMethodToProbe(probe->probeId, + debuggerMethodHandler->GetModule()->GetModuleId(), + debuggerMethodHandler->GetMethodDef()); +} + +bool DebuggerRejitPreprocessor::ShouldSkipModule(const ModuleInfo& moduleInfo, const MethodProbeDefinition& methodProbe) { - return std::make_unique(methodDef, module, functionInfo, methodProbeDefinition); + return false; } } // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.h index a1ee12b28..9f1028721 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_rejit_preprocessor.h @@ -16,12 +16,31 @@ class DebuggerRejitPreprocessor : public RejitPreprocessor& modules, + const LineProbeDefinitions& lineProbes, + std::vector& rejitRequests) const; + void EnqueuePreprocessLineProbes(const std::vector& modules, + const LineProbeDefinitions& lineProbes, + std::promise>* promise) const; + protected: + virtual void ProcessTypesForRejit(std::vector& rejitRequests, const ModuleInfo& moduleInfo, + ComPtr metadataImport, ComPtr metadataEmit, + ComPtr assemblyImport, + ComPtr assemblyEmit, + const MethodProbeDefinition& definition, + const MethodReference& targetMethod) final; virtual const MethodReference& GetTargetMethod(const MethodProbeDefinition& methodProbe) final; virtual const bool GetIsDerived(const MethodProbeDefinition& definition) final; virtual const bool GetIsExactSignatureMatch(const MethodProbeDefinition& definition) final; - virtual const std::unique_ptr CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module, const FunctionInfo& functionInfo, - const MethodProbeDefinition& methodProbeDefinition) final; + virtual const std::unique_ptr + CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module, const FunctionInfo& functionInfo, + const MethodProbeDefinition& methodProbe) final; + const std::unique_ptr + CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module, const FunctionInfo& functionInfo) const; + void UpdateMethod(RejitHandlerModuleMethod* methodHandler, const MethodProbeDefinition& methodProbe) override; + static void UpdateMethod(RejitHandlerModuleMethod* methodHandler, const ProbeDefinition_S& probe); + bool ShouldSkipModule(const ModuleInfo& moduleInfo, const MethodProbeDefinition& methodProbe) final; }; } // namespace debugger diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.cpp new file mode 100644 index 000000000..a9c04ef8c --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.cpp @@ -0,0 +1,1046 @@ +#include "debugger_tokens.h" + +#include "dd_profiler_constants.h" +#include "il_rewriter_wrapper.h" +#include "logger.h" +#include "module_metadata.h" + +using namespace shared; + +namespace debugger +{ + +const int signatureBufferSize = 500; + +/** + * CALLTARGET CONSTANTS + **/ + +static const WSTRING managed_profiler_debugger_beginmethod_startmarker_name = WStr("BeginMethod_StartMarker"); +static const WSTRING managed_profiler_debugger_beginmethod_endmarker_name = WStr("BeginMethod_EndMarker"); +static const WSTRING managed_profiler_debugger_endmethod_startmarker_name = WStr("EndMethod_StartMarker"); +static const WSTRING managed_profiler_debugger_endmethod_endmarker_name = WStr("EndMethod_EndMarker"); +static const WSTRING managed_profiler_debugger_logexception_name = WStr("LogException"); +static const WSTRING managed_profiler_debugger_logarg_name = WStr("LogArg"); +static const WSTRING managed_profiler_debugger_loglocal_name = WStr("LogLocal"); +static const WSTRING managed_profiler_debugger_method_type = WStr("Datadog.Trace.Debugger.Instrumentation.MethodDebuggerInvoker"); +static const WSTRING managed_profiler_debugger_methodstatetype = WStr("Datadog.Trace.Debugger.Instrumentation.MethodDebuggerState"); +static const WSTRING managed_profiler_debugger_returntype = WStr("Datadog.Trace.Debugger.Instrumentation.DebuggerReturn"); +static const WSTRING managed_profiler_debugger_returntype_generics = WStr("Datadog.Trace.Debugger.Instrumentation.DebuggerReturn`1"); + +// Line Probe Methods & Types +static const WSTRING managed_profiler_debugger_line_type = WStr("Datadog.Trace.Debugger.Instrumentation.LineDebuggerInvoker"); +static const WSTRING managed_profiler_debugger_linestatetype = WStr("Datadog.Trace.Debugger.Instrumentation.LineDebuggerState"); +static const WSTRING managed_profiler_debugger_beginline_name = WStr("BeginLine"); +static const WSTRING managed_profiler_debugger_endline_name = WStr("EndLine"); + +/** + * PRIVATE + **/ + +HRESULT DebuggerTokens::WriteLogArgOrLocal(void* rewriterWrapperPtr, const TypeSignature& argOrLocal, + ILInstr** instruction, bool isArg, bool isMethodProbe) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + mdMemberRef logArgOrLocalRef; + mdTypeRef stateTypeRef; + mdTypeRef methodOrLineTypeRef; + + if (isMethodProbe) + { + logArgOrLocalRef = isArg ? methodLogArgRef : methodLogLocalRef; + stateTypeRef = callTargetStateTypeRef; // MethodDebuggerState + methodOrLineTypeRef = callTargetTypeRef; // MethodDebuggerInvoker + } + else + { + logArgOrLocalRef = isArg ? lineLogArgRef : lineLogLocalRef; + stateTypeRef = lineDebuggerStateTypeRef; // LineDebuggerState + methodOrLineTypeRef = lineInvokerTypeRef; // LineDebuggerInvoker + } + + if (logArgOrLocalRef == mdMemberRefNil) + { + auto targetMemberName = + isArg ? managed_profiler_debugger_logarg_name.data() : managed_profiler_debugger_loglocal_name.data(); + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(stateTypeRef, &callTargetStateBuffer); + + unsigned long signatureLength = 10 + callTargetStateSize; + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x01; // one generic argOrLocal (of the argOrLocal) + signature[offset++] = 0x03; // (argumentIndex, argOrLocal, DebuggerState) + + signature[offset++] = ELEMENT_TYPE_VOID; + + // the argOrLocal + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x00; + + // argumentIndex + signature[offset++] = ELEMENT_TYPE_I4; + + // DebuggerState + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + auto hr = module_metadata->metadata_emit->DefineMemberRef(methodOrLineTypeRef, targetMemberName, signature, + signatureLength, &logArgOrLocalRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper ", isArg ? "methodLogArgRef" : "methodLogLocalRef", " could not be defined."); + return hr; + } + + // Set the appropriate field + if (isMethodProbe) + { + if (isArg) + { + methodLogArgRef = logArgOrLocalRef; + } + else + { + methodLogLocalRef = logArgOrLocalRef; + } + } + else + { + if (isArg) + { + lineLogArgRef = logArgOrLocalRef; + } + else + { + lineLogLocalRef = logArgOrLocalRef; + } + } + } + + mdMethodSpec logArgMethodSpec = mdMethodSpecNil; + + auto signatureLength = 2; + + PCCOR_SIGNATURE argumentSignatureBuffer; + ULONG argumentSignatureSize; + const auto [elementType, argTypeFlags] = argOrLocal.GetElementTypeAndFlags(); + if (argTypeFlags & TypeFlagByRef) + { + PCCOR_SIGNATURE argSigBuff; + auto signatureSize = argOrLocal.GetSignature(argSigBuff); + if (argSigBuff[0] == ELEMENT_TYPE_BYREF) + { + argumentSignatureBuffer = argSigBuff + 1; + argumentSignatureSize = signatureSize - 1; + signatureLength += signatureSize - 1; + } + else + { + argumentSignatureBuffer = argSigBuff; + argumentSignatureSize = signatureSize; + signatureLength += signatureSize; + } + } + else + { + auto signatureSize = argOrLocal.GetSignature(argumentSignatureBuffer); + argumentSignatureSize = signatureSize; + signatureLength += signatureSize; + } + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x01; + + memcpy(&signature[offset], argumentSignatureBuffer, argumentSignatureSize); + offset += argumentSignatureSize; + + hr = module_metadata->metadata_emit->DefineMethodSpec(logArgOrLocalRef, signature, signatureLength, + &logArgMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating log exception method spec."); + return hr; + } + + *instruction = rewriterWrapper->CallMember(logArgMethodSpec, false); + return S_OK; +} + +HRESULT DebuggerTokens::EnsureBaseCalltargetTokens() +{ + auto hr = CallTargetTokens::EnsureBaseCalltargetTokens(); + + IfFailRet(hr); + + ModuleMetadata* module_metadata = GetMetadata(); + + // *** Ensure lineInvoker type ref + if (lineInvokerTypeRef == mdTypeRefNil) + { + hr = module_metadata->metadata_emit->DefineTypeRefByName( + profilerAssemblyRef, managed_profiler_debugger_line_type.data(), &lineInvokerTypeRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper lineInvokerTypeRef could not be defined."); + return hr; + } + } + + // *** Ensure lineDebuggerState type ref + if (lineDebuggerStateTypeRef == mdTypeRefNil) + { + hr = module_metadata->metadata_emit->DefineTypeRefByName( + profilerAssemblyRef, managed_profiler_debugger_linestatetype.data(), &lineDebuggerStateTypeRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper lineDebuggerStateTypeRef could not be defined."); + return hr; + } + } + + return S_OK; +} + +/** + * PROTECTED + **/ + +const WSTRING& DebuggerTokens::GetCallTargetType() +{ + return managed_profiler_debugger_method_type; +} + +const WSTRING& DebuggerTokens::GetCallTargetStateType() +{ + return managed_profiler_debugger_methodstatetype; +} + +const WSTRING& DebuggerTokens::GetCallTargetReturnType() +{ + return managed_profiler_debugger_returntype; +} + +const WSTRING& DebuggerTokens::GetCallTargetReturnGenericType() +{ + return managed_profiler_debugger_returntype_generics; +} + +int DebuggerTokens::GetAdditionalLocalsCount() +{ + return 1; +} + +void DebuggerTokens::AddAdditionalLocals(COR_SIGNATURE (&signatureBuffer)[500], ULONG& signatureOffset, ULONG& signatureSize) +{ + // Gets the calltarget state of line probe type buffer and size + unsigned callTargetStateTypeRefBuffer; + auto callTargetStateTypeRefSize = CorSigCompressToken(lineDebuggerStateTypeRef, &callTargetStateTypeRefBuffer); + + // Enlarge the *new* signature size + signatureSize += (1 + callTargetStateTypeRefSize); + + // CallTarget state of line probe + signatureBuffer[signatureOffset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signatureBuffer[signatureOffset], &callTargetStateTypeRefBuffer, callTargetStateTypeRefSize); + signatureOffset += callTargetStateTypeRefSize; +} + +/** + * PUBLIC + **/ + +DebuggerTokens::DebuggerTokens(ModuleMetadata* module_metadata_ptr) : + CallTargetTokens(module_metadata_ptr, true, true) +{ +} + +HRESULT DebuggerTokens::WriteBeginMethod_StartMarker(void* rewriterWrapperPtr, const TypeInfo* currentType, + ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + if (beginMethodStartMarkerRef == mdMemberRefNil) + { + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(callTargetStateTypeRef, &callTargetStateBuffer); + + unsigned runtimeMethodHandleBuffer; + auto runtimeMethodHandleSize = CorSigCompressToken(runtimeMethodHandleRef, &runtimeMethodHandleBuffer); + + unsigned runtimeTypeHandleBuffer; + auto runtimeTypeHandleSize = CorSigCompressToken(runtimeTypeHandleRef, &runtimeTypeHandleBuffer); + + unsigned long signatureLength = 10 + callTargetStateSize + runtimeMethodHandleSize + runtimeTypeHandleSize; + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x01; // generic arguments count + signature[offset++] = 0x05; // arguments count + + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + signature[offset++] = ELEMENT_TYPE_STRING; + + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x00; + + // RuntimeMethodHandle + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &runtimeMethodHandleBuffer, runtimeMethodHandleSize); + offset += runtimeMethodHandleSize; + + // RuntimeTypeHandle + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &runtimeTypeHandleBuffer, runtimeTypeHandleSize); + offset += runtimeTypeHandleSize; + + signature[offset++] = ELEMENT_TYPE_I4; // methodMetadataIndex + + auto hr = module_metadata->metadata_emit->DefineMemberRef( + callTargetTypeRef, managed_profiler_debugger_beginmethod_startmarker_name.data(), signature, + signatureLength, &beginMethodStartMarkerRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper beginMethod could not be defined."); + return hr; + } + } + + mdMethodSpec beginMethodSpec = mdMethodSpecNil; + + bool isValueType = currentType->valueType; + mdToken currentTypeRef = GetCurrentTypeRef(currentType, isValueType); + + unsigned currentTypeBuffer; + ULONG currentTypeSize = CorSigCompressToken(currentTypeRef, ¤tTypeBuffer); + + auto signatureLength = 3 + currentTypeSize; + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x01; + + if (isValueType) + { + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + } + else + { + signature[offset++] = ELEMENT_TYPE_CLASS; + } + memcpy(&signature[offset], ¤tTypeBuffer, currentTypeSize); + offset += currentTypeSize; + + hr = module_metadata->metadata_emit->DefineMethodSpec(beginMethodStartMarkerRef, signature, signatureLength, + &beginMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating begin method spec."); + return hr; + } + + *instruction = rewriterWrapper->CallMember(beginMethodSpec, false); + return S_OK; +} + +// endmethod with void return +HRESULT DebuggerTokens::WriteEndVoidReturnMemberRef(void* rewriterWrapperPtr, const TypeInfo* currentType, + ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + if (endVoidMemberRef == mdMemberRefNil) + { + unsigned callTargetReturnVoidBuffer; + auto callTargetReturnVoidSize = CorSigCompressToken(callTargetReturnVoidTypeRef, &callTargetReturnVoidBuffer); + + unsigned exTypeRefBuffer; + auto exTypeRefSize = CorSigCompressToken(exTypeRef, &exTypeRefBuffer); + + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(callTargetStateTypeRef, &callTargetStateBuffer); + + auto signatureLength = 8 + callTargetReturnVoidSize + exTypeRefSize + callTargetStateSize; + signatureLength++; // ByRef + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x01; + signature[offset++] = 0x03; + + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetReturnVoidBuffer, callTargetReturnVoidSize); + offset += callTargetReturnVoidSize; + + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x00; + + signature[offset++] = ELEMENT_TYPE_CLASS; + memcpy(&signature[offset], &exTypeRefBuffer, exTypeRefSize); + offset += exTypeRefSize; + + signature[offset++] = ELEMENT_TYPE_BYREF; + + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + auto hr = module_metadata->metadata_emit->DefineMemberRef( + callTargetTypeRef, managed_profiler_debugger_endmethod_startmarker_name.data(), signature, signatureLength, + &endVoidMemberRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper endVoidMemberRef could not be defined."); + return hr; + } + } + + mdMethodSpec endVoidMethodSpec = mdMethodSpecNil; + + bool isValueType = currentType->valueType; + mdToken currentTypeRef = GetCurrentTypeRef(currentType, isValueType); + + unsigned currentTypeBuffer; + ULONG currentTypeSize = CorSigCompressToken(currentTypeRef, ¤tTypeBuffer); + + auto signatureLength = 3 + currentTypeSize; + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x01; + + if (isValueType) + { + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + } + else + { + signature[offset++] = ELEMENT_TYPE_CLASS; + } + + memcpy(&signature[offset], ¤tTypeBuffer, currentTypeSize); + offset += currentTypeSize; + + hr = module_metadata->metadata_emit->DefineMethodSpec(endVoidMemberRef, signature, signatureLength, + &endVoidMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating end void method method spec."); + return hr; + } + + *instruction = rewriterWrapper->CallMember(endVoidMethodSpec, false); + return S_OK; +} + +// endmethod with return type +HRESULT DebuggerTokens::WriteEndReturnMemberRef(void* rewriterWrapperPtr, const TypeInfo* currentType, + TypeSignature* returnArgument, ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + GetTargetReturnValueTypeRef(returnArgument); + + // *** Define base MethodMemberRef for the type + + mdMemberRef endMethodMemberRef = mdMemberRefNil; + + unsigned callTargetReturnTypeRefBuffer; + auto callTargetReturnTypeRefSize = CorSigCompressToken(callTargetReturnTypeRef, &callTargetReturnTypeRefBuffer); + + unsigned exTypeRefBuffer; + auto exTypeRefSize = CorSigCompressToken(exTypeRef, &exTypeRefBuffer); + + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(callTargetStateTypeRef, &callTargetStateBuffer); + + auto signatureLength = 14 + callTargetReturnTypeRefSize + exTypeRefSize + callTargetStateSize; + signatureLength++; // ByRef + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x02; + signature[offset++] = 0x04; + + signature[offset++] = ELEMENT_TYPE_GENERICINST; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetReturnTypeRefBuffer, callTargetReturnTypeRefSize); + offset += callTargetReturnTypeRefSize; + signature[offset++] = 0x01; + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x01; + + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x00; + + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x01; + + signature[offset++] = ELEMENT_TYPE_CLASS; + memcpy(&signature[offset], &exTypeRefBuffer, exTypeRefSize); + offset += exTypeRefSize; + + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + hr = module_metadata->metadata_emit->DefineMemberRef(callTargetTypeRef, + managed_profiler_debugger_endmethod_startmarker_name.data(), + signature, signatureLength, &endMethodMemberRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper endMethodMemberRef could not be defined."); + return hr; + } + + // *** Define Method Spec + + mdMethodSpec endMethodSpec = mdMethodSpecNil; + + bool isValueType = currentType->valueType; + mdToken currentTypeRef = GetCurrentTypeRef(currentType, isValueType); + + unsigned currentTypeBuffer; + ULONG currentTypeSize = CorSigCompressToken(currentTypeRef, ¤tTypeBuffer); + + PCCOR_SIGNATURE returnSignatureBuffer; + auto returnSignatureLength = returnArgument->GetSignature(returnSignatureBuffer); + + signatureLength = 3 + currentTypeSize + returnSignatureLength; + offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x02; + + if (isValueType) + { + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + } + else + { + signature[offset++] = ELEMENT_TYPE_CLASS; + } + memcpy(&signature[offset], ¤tTypeBuffer, currentTypeSize); + offset += currentTypeSize; + + memcpy(&signature[offset], returnSignatureBuffer, returnSignatureLength); + offset += returnSignatureLength; + + hr = module_metadata->metadata_emit->DefineMethodSpec(endMethodMemberRef, signature, signatureLength, + &endMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating end method member spec."); + return hr; + } + + *instruction = rewriterWrapper->CallMember(endMethodSpec, false); + return S_OK; +} + +// write log exception +HRESULT DebuggerTokens::WriteLogException(void* rewriterWrapperPtr, const TypeInfo* currentType, bool isMethodProbe) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + mdTypeRef stateTypeRef = isMethodProbe ? callTargetStateTypeRef : lineDebuggerStateTypeRef; // MethodDebuggerState / LineDebuggerState + mdTypeRef methodOrLineTypeRef = isMethodProbe ? callTargetTypeRef : lineInvokerTypeRef; // MethodDebuggerInvoker / LineDebuggerInvoker + mdMemberRef logExceptionRef = isMethodProbe ? methodLogExceptionRef : lineLogExceptionRef; // MethodDebuggerInvoker.LogException / LineDebuggerInvoker.LogException + + if (logExceptionRef == mdMemberRefNil) + { + unsigned exTypeRefBuffer; + auto exTypeRefSize = CorSigCompressToken(exTypeRef, &exTypeRefBuffer); + + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(stateTypeRef, &callTargetStateBuffer); + + auto signatureLength = 7 + exTypeRefSize + callTargetStateSize; + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x01; // One generic argument: TTarget + signature[offset++] = 0x02; // (Exception, DebuggerState) + + signature[offset++] = ELEMENT_TYPE_VOID; + signature[offset++] = ELEMENT_TYPE_CLASS; + memcpy(&signature[offset], &exTypeRefBuffer, exTypeRefSize); + offset += exTypeRefSize; + + // DebuggerState + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + auto hr = module_metadata->metadata_emit->DefineMemberRef(methodOrLineTypeRef, + managed_profiler_debugger_logexception_name.data(), + signature, signatureLength, &logExceptionRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper methodLogExceptionRef could not be defined."); + return hr; + } + + if (isMethodProbe) + { + methodLogExceptionRef = logExceptionRef; + } + else + { + lineLogExceptionRef = logExceptionRef; + } + } + + mdMethodSpec logExceptionMethodSpec = mdMethodSpecNil; + + bool isValueType = currentType->valueType; + mdToken currentTypeRef = GetCurrentTypeRef(currentType, isValueType); + + unsigned currentTypeBuffer; + ULONG currentTypeSize = CorSigCompressToken(currentTypeRef, ¤tTypeBuffer); + + auto signatureLength = 3 + currentTypeSize; + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x01; + + if (isValueType) + { + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + } + else + { + signature[offset++] = ELEMENT_TYPE_CLASS; + } + memcpy(&signature[offset], ¤tTypeBuffer, currentTypeSize); + offset += currentTypeSize; + + hr = module_metadata->metadata_emit->DefineMethodSpec(logExceptionRef, signature, signatureLength, + &logExceptionMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating log exception method spec."); + return hr; + } + + rewriterWrapper->CallMember(logExceptionMethodSpec, false); + return S_OK; +} + +HRESULT DebuggerTokens::WriteLogArg(void* rewriterWrapperPtr, const TypeSignature& argument, ILInstr** instruction, bool isMethodProbe) +{ + return WriteLogArgOrLocal(rewriterWrapperPtr, argument, instruction, true /* isArg */, isMethodProbe); +} + +HRESULT DebuggerTokens::WriteLogLocal(void* rewriterWrapperPtr, const TypeSignature& local, ILInstr** instruction, bool isMethodProbe) +{ + return WriteLogArgOrLocal(rewriterWrapperPtr, local, instruction, false /* isArg */, isMethodProbe); +} + +HRESULT DebuggerTokens::WriteBeginOrEndMethod_EndMarker(void* rewriterWrapperPtr, bool isBeginMethod, + ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + mdMemberRef beginOrEndMethodRef = isBeginMethod ? beginMethodEndMarkerRef : endMethodEndMarkerRef; + const auto beginOrEndMethodName = isBeginMethod ? managed_profiler_debugger_beginmethod_endmarker_name.data() + : managed_profiler_debugger_endmethod_endmarker_name.data(); + + if (beginOrEndMethodRef == mdMemberRefNil) + { + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(callTargetStateTypeRef, &callTargetStateBuffer); + + unsigned long signatureLength = 4 + callTargetStateSize; + + signatureLength += 1; // ByRef + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_DEFAULT; + signature[offset++] = 0x01; // arguments count + signature[offset++] = ELEMENT_TYPE_VOID; + + // DebuggerState + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + auto hr = module_metadata->metadata_emit->DefineMemberRef(callTargetTypeRef, beginOrEndMethodName, signature, + signatureLength, &beginOrEndMethodRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper beginMethod could not be defined."); + return hr; + } + + if (isBeginMethod) + { + beginMethodEndMarkerRef = beginOrEndMethodRef; + } + else + { + endMethodEndMarkerRef = beginOrEndMethodRef; + } + } + + *instruction = rewriterWrapper->CallMember(beginOrEndMethodRef, false); + return S_OK; +} + +HRESULT DebuggerTokens::WriteBeginMethod_EndMarker(void* rewriterWrapperPtr, ILInstr** instruction) +{ + return WriteBeginOrEndMethod_EndMarker(rewriterWrapperPtr, true /* isBeginMethod */, instruction); +} + +HRESULT DebuggerTokens::WriteEndMethod_EndMarker(void* rewriterWrapperPtr, ILInstr** instruction) +{ + return WriteBeginOrEndMethod_EndMarker(rewriterWrapperPtr, false /* isBeginMethod */, instruction); +} + +HRESULT DebuggerTokens::WriteBeginLine(void* rewriterWrapperPtr, const TypeInfo* currentType, + ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + if (beginLineRef == mdMemberRefNil) + { + unsigned callTargetStateBuffer; + auto lineStateSize = CorSigCompressToken(lineDebuggerStateTypeRef, &callTargetStateBuffer); + + unsigned runtimeMethodHandleBuffer; + auto runtimeMethodHandleSize = CorSigCompressToken(runtimeMethodHandleRef, &runtimeMethodHandleBuffer); + + unsigned runtimeTypeHandleBuffer; + auto runtimeTypeHandleSize = CorSigCompressToken(runtimeTypeHandleRef, &runtimeTypeHandleBuffer); + + unsigned long signatureLength = 12 + lineStateSize + runtimeMethodHandleSize + runtimeTypeHandleSize; + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERIC; + signature[offset++] = 0x01; // generic arguments count + signature[offset++] = 0x07; // arguments count + + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, lineStateSize); + offset += lineStateSize; + + signature[offset++] = ELEMENT_TYPE_STRING; + + signature[offset++] = ELEMENT_TYPE_MVAR; + signature[offset++] = 0x00; + + // RuntimeMethodHandle + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &runtimeMethodHandleBuffer, runtimeMethodHandleSize); + offset += runtimeMethodHandleSize; + + // RuntimeTypeHandle + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &runtimeTypeHandleBuffer, runtimeTypeHandleSize); + offset += runtimeTypeHandleSize; + + signature[offset++] = ELEMENT_TYPE_I4; // methodMetadataIndex + signature[offset++] = ELEMENT_TYPE_I4; // lineNumber + signature[offset++] = ELEMENT_TYPE_STRING; // probeFilePath + + auto hr = module_metadata->metadata_emit->DefineMemberRef( + lineInvokerTypeRef, managed_profiler_debugger_beginline_name.data(), signature, signatureLength, &beginLineRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper beginMethod could not be defined."); + return hr; + } + } + + mdMethodSpec beginMethodSpec = mdMethodSpecNil; + + bool isValueType = currentType->valueType; + mdToken currentTypeRef = GetCurrentTypeRef(currentType, isValueType); + + unsigned currentTypeBuffer; + ULONG currentTypeSize = CorSigCompressToken(currentTypeRef, ¤tTypeBuffer); + + auto signatureLength = 3 + currentTypeSize; + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_GENERICINST; + signature[offset++] = 0x01; + + if (isValueType) + { + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + } + else + { + signature[offset++] = ELEMENT_TYPE_CLASS; + } + memcpy(&signature[offset], ¤tTypeBuffer, currentTypeSize); + offset += currentTypeSize; + + hr = module_metadata->metadata_emit->DefineMethodSpec(beginLineRef, signature, signatureLength, + &beginMethodSpec); + if (FAILED(hr)) + { + Logger::Warn("Error creating begin method spec."); + return hr; + } + + *instruction = rewriterWrapper->CallMember(beginMethodSpec, false); + return S_OK; +} + +HRESULT DebuggerTokens::WriteEndLine(void* rewriterWrapperPtr, ILInstr** instruction) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + ModuleMetadata* module_metadata = GetMetadata(); + + if (endLineRef == mdMemberRefNil) + { + unsigned callTargetStateBuffer; + auto callTargetStateSize = CorSigCompressToken(lineDebuggerStateTypeRef, &callTargetStateBuffer); + + unsigned long signatureLength = 4 + callTargetStateSize; + + signatureLength += 1; // ByRef + + COR_SIGNATURE signature[signatureBufferSize]; + unsigned offset = 0; + + signature[offset++] = IMAGE_CEE_CS_CALLCONV_DEFAULT; + signature[offset++] = 0x01; // arguments count + signature[offset++] = ELEMENT_TYPE_VOID; + + // DebuggerState + signature[offset++] = ELEMENT_TYPE_BYREF; + signature[offset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&signature[offset], &callTargetStateBuffer, callTargetStateSize); + offset += callTargetStateSize; + + auto hr = module_metadata->metadata_emit->DefineMemberRef( + lineInvokerTypeRef, managed_profiler_debugger_endline_name.data(), signature, signatureLength, &endLineRef); + if (FAILED(hr)) + { + Logger::Warn("Wrapper beginMethod could not be defined."); + return hr; + } + } + + *instruction = rewriterWrapper->CallMember(endLineRef, false); + return S_OK; +} + +HRESULT DebuggerTokens::ModifyLocalSigForLineProbe(ILRewriter* reWriter, ULONG* callTargetStateIndex, mdToken* callTargetStateToken) +{ + auto hr = EnsureBaseCalltargetTokens(); + if (FAILED(hr)) + { + return hr; + } + + ModuleMetadata* module_metadata = GetMetadata(); + + PCCOR_SIGNATURE originalSignature = nullptr; + ULONG originalSignatureSize = 0; + mdToken localVarSig = reWriter->GetTkLocalVarSig(); + + if (localVarSig != mdTokenNil) + { + IfFailRet( + module_metadata->metadata_import->GetSigFromToken(localVarSig, &originalSignature, &originalSignatureSize)); + + // Check if the localvarsig has been already rewritten (the last local + // should be the LineDebuggerState) + unsigned temp = 0; + const auto len = CorSigCompressToken(lineDebuggerStateTypeRef, &temp); + if (originalSignatureSize - len > 0) + { + if (originalSignature[originalSignatureSize - len - 1] == ELEMENT_TYPE_VALUETYPE) + { + if (memcmp(&originalSignature[originalSignatureSize - len], &temp, len) == 0) + { + Logger::Warn("The signature for this method has been already modified."); + return E_FAIL; + } + } + } + } + + ULONG newLocalsCount = 1; + + // Gets the calltarget state type buffer and size + unsigned callTargetStateTypeRefBuffer; + auto callTargetStateTypeRefSize = CorSigCompressToken(lineDebuggerStateTypeRef, &callTargetStateTypeRefBuffer); + + // New signature size + ULONG newSignatureSize = originalSignatureSize + (1 + callTargetStateTypeRefSize); + ULONG newSignatureOffset = 0; + + ULONG oldLocalsBuffer; + ULONG oldLocalsLen = 0; + unsigned newLocalsBuffer; + ULONG newLocalsLen; + + // Calculate the new locals count + if (originalSignatureSize == 0) + { + newSignatureSize += 2; + newLocalsLen = CorSigCompressData(newLocalsCount, &newLocalsBuffer); + } + else + { + oldLocalsLen = CorSigUncompressData(originalSignature + 1, &oldLocalsBuffer); + newLocalsCount += oldLocalsBuffer; + newLocalsLen = CorSigCompressData(newLocalsCount, &newLocalsBuffer); + newSignatureSize += newLocalsLen - oldLocalsLen; + } + + // New signature declaration + COR_SIGNATURE newSignatureBuffer[signatureBufferSize]; + newSignatureBuffer[newSignatureOffset++] = IMAGE_CEE_CS_CALLCONV_LOCAL_SIG; + + // Set the locals count + memcpy(&newSignatureBuffer[newSignatureOffset], &newLocalsBuffer, newLocalsLen); + newSignatureOffset += newLocalsLen; + + // Copy previous locals to the signature + if (originalSignatureSize > 0) + { + const auto copyLength = originalSignatureSize - 1 - oldLocalsLen; + memcpy(&newSignatureBuffer[newSignatureOffset], originalSignature + 1 + oldLocalsLen, copyLength); + newSignatureOffset += copyLength; + } + + // Add new locals + + // CallTarget state value + newSignatureBuffer[newSignatureOffset++] = ELEMENT_TYPE_VALUETYPE; + memcpy(&newSignatureBuffer[newSignatureOffset], &callTargetStateTypeRefBuffer, callTargetStateTypeRefSize); + newSignatureOffset += callTargetStateTypeRefSize; + + // Get new locals token + mdToken newLocalVarSig; + hr = module_metadata->metadata_emit->GetTokenFromSig(newSignatureBuffer, newSignatureSize, &newLocalVarSig); + if (FAILED(hr)) + { + Logger::Warn("Error creating new locals var signature."); + return hr; + } + + reWriter->SetTkLocalVarSig(newLocalVarSig); + *callTargetStateToken = lineDebuggerStateTypeRef; + *callTargetStateIndex = newLocalsCount - 1; + return hr; +} + +HRESULT DebuggerTokens::GetDebuggerLocals(void* rewriterWrapperPtr, ULONG* callTargetStateIndex, mdToken* callTargetStateToken) +{ + ILRewriterWrapper* rewriterWrapper = (ILRewriterWrapper*) rewriterWrapperPtr; + const auto reWriter = rewriterWrapper->GetILRewriter(); + + PCCOR_SIGNATURE originalSignature = nullptr; + ULONG originalSignatureSize = 0; + const mdToken localVarSig = reWriter->GetTkLocalVarSig(); + + if (localVarSig == mdTokenNil) + { + // There must be local signature as the modification of the CallTarget already took place. + Logger::Error("localVarSig is mdTokenNil in GetDebuggerLocals."); + return E_FAIL; + } + + HRESULT hr; + ModuleMetadata* module_metadata = GetMetadata(); + IfFailRet(module_metadata->metadata_import->GetSigFromToken(localVarSig, &originalSignature, &originalSignatureSize)); + + ULONG localsLen; + auto bytesRead = CorSigUncompressData(originalSignature + 1, &localsLen); + + const auto debuggerAdditionalLocalsCount = GetAdditionalLocalsCount(); + *callTargetStateToken = lineDebuggerStateTypeRef; + *callTargetStateIndex = localsLen - /* Accounting for MethodDebuggerState */ 1 - debuggerAdditionalLocalsCount; + + return S_OK; +} + +} // namespace debugger \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.h new file mode 100644 index 000000000..f9a060f33 --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/debugger_tokens.h @@ -0,0 +1,93 @@ +#ifndef DD_CLR_PROFILER_DEBUGGER_TOKENS_H_ +#define DD_CLR_PROFILER_DEBUGGER_TOKENS_H_ + +#include "calltarget_tokens.h" + +#include + +#include +#include +#include + +#include "clr_helpers.h" +#include "../../../shared/src/native-src/com_ptr.h" +#include "il_rewriter.h" +#include "integration.h" +#include "../../../shared/src/native-src/string.h" // NOLINT + +using namespace shared; +using namespace trace; + +namespace debugger +{ + +/// +/// Class to control all the token references of the module where the Debugger will be called. +/// Also provides useful helpers for the rewriting process +/// +class DebuggerTokens : public CallTargetTokens +{ +private: + + // Method probe members: + mdMemberRef beginMethodStartMarkerRef = mdMemberRefNil; + mdMemberRef beginMethodEndMarkerRef = mdMemberRefNil; + mdMemberRef endMethodEndMarkerRef = mdMemberRefNil; + mdMemberRef methodLogArgRef = mdMemberRefNil; + mdMemberRef methodLogLocalRef = mdMemberRefNil; + mdMemberRef endVoidMemberRef = mdMemberRefNil; + mdMemberRef methodLogExceptionRef = mdMemberRefNil; + mdMemberRef beginLineRef = mdMemberRefNil; + mdMemberRef endLineRef = mdMemberRefNil; + + // Line probe members: + mdMemberRef lineDebuggerStateTypeRef = mdTypeRefNil; + mdMemberRef lineInvokerTypeRef = mdTypeRefNil; + mdMemberRef lineLogExceptionRef = mdMemberRefNil; + mdMemberRef lineLogArgRef = mdMemberRefNil; + mdMemberRef lineLogLocalRef = mdMemberRefNil; + + HRESULT WriteLogArgOrLocal(void* rewriterWrapperPtr, const TypeSignature& argOrLocal, ILInstr** instruction, + bool isArg, bool isMethodProbe); + +protected: + virtual HRESULT EnsureBaseCalltargetTokens() override; + + const WSTRING& GetCallTargetType() override; + const WSTRING& GetCallTargetStateType() override; + const WSTRING& GetCallTargetReturnType() override; + const WSTRING& GetCallTargetReturnGenericType() override; + + int GetAdditionalLocalsCount() override; + void AddAdditionalLocals(COR_SIGNATURE (&signatureBuffer)[500], ULONG& signatureOffset, ULONG& signatureSize) override; + +public: + DebuggerTokens(ModuleMetadata* module_metadata_ptr); + + HRESULT WriteBeginMethod_StartMarker(void* rewriterWrapperPtr, const TypeInfo* currentType, ILInstr** instruction); + + HRESULT WriteEndVoidReturnMemberRef(void* rewriterWrapperPtr, const TypeInfo* currentType, ILInstr** instruction); + + HRESULT WriteEndReturnMemberRef(void* rewriterWrapperPtr, const TypeInfo* currentType, + TypeSignature* returnArgument, ILInstr** instruction); + + HRESULT WriteLogException(void* rewriterWrapperPtr, const TypeInfo* currentType, bool isMethodProbe); + + HRESULT WriteLogArg(void* rewriterWrapperPtr, const TypeSignature& argument, ILInstr** instruction, bool isMethodProbe); + + HRESULT WriteLogLocal(void* rewriterWrapperPtr, const TypeSignature& local, ILInstr** instruction, bool isMethodProbe); + + HRESULT WriteBeginOrEndMethod_EndMarker(void* rewriterWrapperPtr, bool isBeginMethod, ILInstr** instruction); + HRESULT WriteBeginMethod_EndMarker(void* rewriterWrapperPtr, ILInstr** instruction); + HRESULT WriteEndMethod_EndMarker(void* rewriterWrapperPtr, ILInstr** instruction); + + HRESULT WriteBeginLine(void* rewriterWrapperPtr, const TypeInfo* currentType, ILInstr** instruction); + HRESULT WriteEndLine(void* rewriterWrapperPtr, ILInstr** instruction); + + HRESULT ModifyLocalSigForLineProbe(ILRewriter* reWriter, ULONG* callTargetStateIndex, mdToken* callTargetStateToken); + HRESULT GetDebuggerLocals(void* rewriterWrapperPtr, ULONG* callTargetStateIndex, mdToken* callTargetStateToken); +}; + +} // namespace debugger + +#endif // DD_CLR_PROFILER_DEBUGGER_TOKENS_H_ \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.cpp index 15f5c2cfe..fe7852713 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.cpp @@ -735,3 +735,8 @@ unsigned ILRewriter::GetMaxStackValue() { return m_maxStack; } + +bool ILRewriter::IsBranchTarget(ILInstr* pInstr) +{ + return s_OpCodeFlags[pInstr->m_opcode] & OPCODEFLAGS_BranchTarget; +} diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.h index 179965630..7ce93cdb2 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter.h @@ -140,6 +140,8 @@ class ILRewriter void DeallocateILMemory(LPBYTE pBody); unsigned GetMaxStackValue(); + + static bool IsBranchTarget(ILInstr* pInstr); }; #endif // DD_CLR_PROFILER_IL_REWRITER_H_ diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.cpp index 1728f9428..82dc0a6c8 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.cpp @@ -228,6 +228,15 @@ ILInstr* ILRewriterWrapper::LoadObj(mdToken token) const return pNewInstr; } +ILInstr* ILRewriterWrapper::LoadStr(mdString token) const +{ + ILInstr* pNewInstr = m_ILRewriter->NewILInstr(); + pNewInstr->m_opcode = CEE_LDSTR; + pNewInstr->m_Arg32 = token; + m_ILRewriter->InsertBefore(m_ILInstr, pNewInstr); + return pNewInstr; +} + ILInstr* ILRewriterWrapper::StLocal(unsigned index) const { static const std::vector opcodes = { diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.h index cffbbc94d..9f242f152 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/il_rewriter_wrapper.h @@ -36,6 +36,7 @@ class ILRewriterWrapper bool ReplaceMethodCalls(mdMemberRef old_method_ref, mdMemberRef new_method_ref) const; ILInstr* LoadToken(mdToken token) const; ILInstr* LoadObj(mdToken token) const; + ILInstr* LoadStr(mdString token) const; ILInstr* StLocal(unsigned index) const; ILInstr* LoadLocal(unsigned index) const; ILInstr* LoadLocalAddress(unsigned index) const; diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/integration.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/integration.h index 695ddd6b2..63ec57eaa 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/integration.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/integration.h @@ -6,6 +6,8 @@ #include #include #include +#include "cor.h" +#include "corprof.h" #include "../../../shared/src/native-src/string.h" @@ -357,6 +359,35 @@ typedef struct _CallTargetDefinition WCHAR* integrationType; } CallTargetDefinition; +struct MethodIdentifier +{ + ModuleID moduleId; + mdMethodDef methodToken; + + MethodIdentifier() : moduleId(0), methodToken(0) + { + } + + MethodIdentifier(ModuleID moduleId, mdMethodDef methodToken) : moduleId(moduleId), methodToken(methodToken) + { + } + + MethodIdentifier(const MethodIdentifier& copyFrom) : moduleId(copyFrom.moduleId), methodToken(copyFrom.methodToken) + { + } + + // Need it to use std::map + bool operator<(const MethodIdentifier& rhs) const + { + return moduleId < rhs.moduleId || (moduleId == rhs.moduleId && methodToken < rhs.methodToken); + } + + bool operator==(const MethodIdentifier& other) const + { + return (moduleId == other.moduleId && methodToken == other.methodToken); + } +}; + namespace { @@ -372,4 +403,20 @@ namespace } // namespace trace +namespace std +{ +template <> +struct hash +{ + size_t operator()(const trace::MethodIdentifier& k) const noexcept + { + // Compute individual hash values for first, + // second and combine them using XOR + // and bit shifting: + + return ((k.moduleId) ^ static_cast(k.methodToken) << 1) >> 1; + } +}; +} // namespace std + #endif // DD_CLR_PROFILER_INTEGRATION_H_ diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/interop.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/interop.cpp index f1563747d..faeb4005b 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/interop.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/interop.cpp @@ -57,6 +57,22 @@ EXTERN_C VOID STDAPICALLTYPE InitializeTraceMethods(WCHAR* id, WCHAR* integratio configuration_string_ptr); } +EXTERN_C VOID STDAPICALLTYPE InstrumentProbes( + debugger::DebuggerMethodProbeDefinition* methodProbes, + int methodProbesLength, + debugger::DebuggerLineProbeDefinition* lineProbes, + int lineProbesLength, + debugger::DebuggerRemoveProbesDefinition* revertProbes, + int revertProbesLength) +{ + return trace::profiler->InstrumentProbes(methodProbes, methodProbesLength, lineProbes, lineProbesLength, revertProbes, revertProbesLength); +} + +EXTERN_C int STDAPICALLTYPE GetProbesStatuses(WCHAR** probeIds, int probeIdsLength, debugger::DebuggerProbeStatus* probeStatuses) +{ + return trace::profiler->GetProbesStatuses(probeIds, probeIdsLength, probeStatuses); +} + #ifndef _WIN32 EXTERN_C void *dddlopen (const char *__file, int __mode) { diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/module_metadata.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/module_metadata.h index 43217b7fd..7248f6827 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/module_metadata.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/module_metadata.h @@ -8,6 +8,7 @@ #include "calltarget_tokens.h" #include "clr_helpers.h" +#include "debugger_tokens.h" #include "integration.h" #include "tracer_tokens.h" #include "../../../shared/src/native-src/com_ptr.h" @@ -22,6 +23,7 @@ class ModuleMetadata std::mutex wrapper_mutex; std::unique_ptr> integration_types = nullptr; std::unique_ptr tracerTokens = nullptr; + std::unique_ptr debuggerTokens = nullptr; std::unique_ptr> integrations = nullptr; public: @@ -111,6 +113,15 @@ class ModuleMetadata } return tracerTokens.get(); } + + debugger::DebuggerTokens* GetDebuggerTokens() + { + if (debuggerTokens == nullptr) + { + debuggerTokens = std::make_unique(this); + } + return debuggerTokens.get(); + } }; } // namespace trace diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.cpp new file mode 100644 index 000000000..78d190bf0 --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.cpp @@ -0,0 +1,108 @@ +#include "probes_tracker.h" + + bool debugger::ProbesMetadataTracker::TryGetMetadata(const shared::WSTRING& probeId, /* out */ std::shared_ptr& probeMetadata) + { + std::lock_guard lock(_probeMetadataMapMutex); + + if (!_probeMetadataMap.empty()) + { + const auto iter = _probeMetadataMap.find(probeId); + + if (iter != _probeMetadataMap.end()) + { + probeMetadata = iter->second; + return true; + } + } + + return false; + } + + std::set debugger::ProbesMetadataTracker::GetProbeIds(const ModuleID moduleId, const mdMethodDef methodId) + { + std::lock_guard lock(_probeMetadataMapMutex); + + const auto lookupMethodIdentifier = trace::MethodIdentifier(moduleId, methodId); + std::set probeIds; + + auto probeMetadataMapIterator = _probeMetadataMap.begin(); + while (probeMetadataMapIterator != _probeMetadataMap.end()) + { + auto probeMetadataPair = *probeMetadataMapIterator; + const auto methods = probeMetadataPair.second->methods; + + if (methods.find(lookupMethodIdentifier) != methods.end()) + { + probeIds.emplace(probeMetadataPair.first); + } + + probeMetadataMapIterator = ++probeMetadataMapIterator; + } + + return probeIds; + } + + void debugger::ProbesMetadataTracker::CreateNewProbeIfNotExists(const shared::WSTRING& probeId) + { + std::lock_guard lock(_probeMetadataMapMutex); + + if (_probeMetadataMap.find(probeId) == _probeMetadataMap.end()) + { + auto methods = std::set(); + _probeMetadataMap[probeId] = std::make_shared(probeId, std::move(methods), ProbeStatus::RECEIVED); + } + } + + void debugger::ProbesMetadataTracker::AddMethodToProbe(const shared::WSTRING& probeId, const ModuleID moduleId, const mdMethodDef methodId) +{ + std::lock_guard lock(_probeMetadataMapMutex); + + const auto methodIdentifierToAdd = trace::MethodIdentifier(moduleId, methodId); + CreateNewProbeIfNotExists(probeId); + + _probeMetadataMap[probeId]->methods.emplace(methodIdentifierToAdd); + + // Mark the probe as Installed (if it was not marked as Error before) + if (_probeMetadataMap[probeId]->status != ProbeStatus::_ERROR) + { + _probeMetadataMap[probeId]->status = ProbeStatus::INSTALLED; + } +} + +bool debugger::ProbesMetadataTracker::SetProbeStatus(const shared::WSTRING& probeId, ProbeStatus newStatus) +{ + std::shared_ptr probeMetadata; + if (TryGetMetadata(probeId, probeMetadata)) + { + if (probeMetadata->status != ProbeStatus::_ERROR) + { + probeMetadata->status = newStatus; + } + return true; + } + + return false; +} + +int debugger::ProbesMetadataTracker::RemoveProbes(const std::vector& probes) + { + std::lock_guard lock(_probeMetadataMapMutex); + + auto removedProbesCount = 0; + + if (!_probeMetadataMap.empty()) + { + for (const auto& probe : probes) + { + const auto iter = _probeMetadataMap.find(probe); + + if (iter != _probeMetadataMap.end()) + { + removedProbesCount++; + _probeMetadataMap.erase(iter); + } + } + } + + return removedProbesCount; + } diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.h new file mode 100644 index 000000000..82538925f --- /dev/null +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/probes_tracker.h @@ -0,0 +1,36 @@ +#ifndef DD_CLR_PROFILER_DEBUGGER_INSTRUMENTED_METHOD_INFO_TRACKER_H_ +#define DD_CLR_PROFILER_DEBUGGER_INSTRUMENTED_METHOD_INFO_TRACKER_H_ + +#include "corhlpr.h" +#include "integration.h" +#include +#include +#include +#include "../../../shared/src/native-src/util.h" +#include "../../../shared/src/native-src/string.h" +#include "debugger_members.h" + +namespace debugger +{ + class ProbesMetadataTracker : public shared::Singleton + { + friend class shared::Singleton; + + private: + std::recursive_mutex _probeMetadataMapMutex; + std::unordered_map> _probeMetadataMap{}; + + public: + ProbesMetadataTracker() = default; + + bool TryGetMetadata(const shared::WSTRING& probeId, std::shared_ptr& probeMetadata); + std::set GetProbeIds(const ModuleID moduleId, const mdMethodDef methodId); + void CreateNewProbeIfNotExists(const shared::WSTRING& probeId); + void AddMethodToProbe(const shared::WSTRING& probeId, const ModuleID moduleId, const mdMethodDef methodId); + bool SetProbeStatus(const shared::WSTRING& probeId, ProbeStatus newStatus); + int RemoveProbes(const std::vector& probes); + }; + +} // namespace debugger + +#endif \ No newline at end of file diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.cpp index abfbf7aa0..2f5360c0e 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.cpp @@ -182,17 +182,21 @@ void RejitHandlerModule::SetModuleMetadata(ModuleMetadata* metadata) } bool RejitHandlerModule::CreateMethodIfNotExists(const mdMethodDef methodDef, - RejitHandlerModuleMethodCreatorFunc creator) + RejitHandlerModuleMethodCreatorFunc creator, + RejitHandlerModuleMethodUpdaterFunc updater) { std::lock_guard guard(m_methods_lock); auto find_res = m_methods.find(methodDef); if (find_res != m_methods.end()) { + updater(find_res->second.get()); return false; // already exist and was not created } - m_methods[methodDef] = creator(methodDef, this); + auto newModuleInfo = creator(methodDef, this); + updater(newModuleInfo.get()); + m_methods[methodDef] = std::move(newModuleInfo); return true; } @@ -298,6 +302,35 @@ void RejitHandler::RequestRejit(std::vector& modulesVector, } } +void RejitHandler::RequestRevert(std::vector& modulesVector, std::vector& modulesMethodDef) +{ + if (IsShutdownRequested()) + { + return; + } + + HRESULT hr; + + if (!modulesVector.empty()) + { + // ************************************* + // Request Revert + // ************************************* + + HRESULT* status = nullptr; + hr = m_profilerInfo->RequestRevert((ULONG) modulesVector.size(), &modulesVector[0], &modulesMethodDef[0], status); + + if (SUCCEEDED(hr)) + { + Logger::Info("Request Revert done for ", modulesVector.size(), " methods"); + } + else + { + Logger::Warn("Error requesting Revert for ", modulesVector.size(), " methods"); + } + } +} + RejitHandler::RejitHandler(ICorProfilerInfo7* pInfo, std::shared_ptr work_offloader) { m_profilerInfo = pInfo; @@ -432,6 +465,24 @@ void RejitHandler::EnqueueForRejit(std::vector& modulesVector, std::ve m_work_offloader->Enqueue(std::make_unique(std::move(action))); } +void RejitHandler::EnqueueForRevert(std::vector& modulesVector, std::vector& modulesMethodDef) +{ + if (IsShutdownRequested() || modulesVector.size() == 0 || modulesMethodDef.size() == 0) + { + return; + } + + Logger::Debug("RejitHandler::EnqueueForRevert"); + + std::function action = [=, modules = std::move(modulesVector), methods = std::move(modulesMethodDef)]() mutable { + // Request Revert + RequestRevert(modules, methods); + }; + + // Enqueue + m_work_offloader->Enqueue(std::make_unique(std::move(action))); +} + void RejitHandler::Shutdown() { Logger::Debug("RejitHandler::Shutdown"); diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.h index 25532fd2d..6eedf69b6 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_handler.h @@ -75,6 +75,7 @@ class TracerRejitHandlerModuleMethod : public RejitHandlerModuleMethod }; using RejitHandlerModuleMethodCreatorFunc = std::function(const mdMethodDef, RejitHandlerModule*)>; +using RejitHandlerModuleMethodUpdaterFunc = std::function; /// /// Rejit handler representation of a module @@ -100,7 +101,8 @@ class RejitHandlerModule ModuleMetadata* GetModuleMetadata(); void SetModuleMetadata(ModuleMetadata* metadata); - bool CreateMethodIfNotExists(const mdMethodDef methodDef, RejitHandlerModuleMethodCreatorFunc creator); + bool CreateMethodIfNotExists(const mdMethodDef methodDef, RejitHandlerModuleMethodCreatorFunc creator, + RejitHandlerModuleMethodUpdaterFunc updater); bool ContainsMethod(mdMethodDef methodDef); bool TryGetMethod(mdMethodDef methodDef, /* OUT */ RejitHandlerModuleMethod** methodHandler); @@ -149,6 +151,8 @@ class RejitHandler void EnqueueForRejit(std::vector& modulesVector, std::vector& modulesMethodDef); void RequestRejit(std::vector& modulesVector, std::vector& modulesMethodDef); + void RequestRevert(std::vector& modulesVector, std::vector& modulesMethodDef); + void EnqueueForRevert(std::vector& modulesVector, std::vector& modulesMethodDef); void Shutdown(); bool IsShutdownRequested(); diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.cpp index 57603a205..16a02338c 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.cpp @@ -21,8 +21,7 @@ void RejitPreprocessor::ProcessTypeDefForRejit(const Rej ComPtr& metadataEmit, ComPtr& assemblyImport, ComPtr& assemblyEmit, const ModuleInfo& moduleInfo, - const mdTypeDef typeDef, std::vector& vtModules, - std::vector& vtMethodDefs) + const mdTypeDef typeDef, std::vector& rejitRequests) { auto target_method = GetTargetMethod(definition); const bool wildcard_enabled = target_method.method_name == tracemethodintegration_wildcardmethodname; @@ -95,7 +94,7 @@ void RejitPreprocessor::ProcessTypeDefForRejit(const Rej if (numOfArgs != target_method.signature_types.size() - 1) { Logger::Debug(" * The caller for the methoddef: ", caller.name, - " doesn't have the right number of arguments (", numOfArgs, " arguments)."); + " doesn't have the right number of arguments (", numOfArgs, " arguments)."); continue; } @@ -118,7 +117,7 @@ void RejitPreprocessor::ProcessTypeDefForRejit(const Rej if (argumentsMismatch) { Logger::Debug(" * The caller for the methoddef: ", target_method.method_name, - " doesn't have the right type of arguments."); + " doesn't have the right type of arguments."); continue; } } @@ -151,11 +150,14 @@ void RejitPreprocessor::ProcessTypeDefForRejit(const Rej return CreateMethod(method, module, functionInfo, request); }; - moduleHandler->CreateMethodIfNotExists(methodDef, creator); + RejitHandlerModuleMethodUpdaterFunc updater = [=, request = definition](RejitHandlerModuleMethod* method) { + return UpdateMethod(method, request); + }; + + moduleHandler->CreateMethodIfNotExists(methodDef, creator, updater); // Store module_id and methodDef to request the ReJIT after analyzing all integrations. - vtModules.push_back(moduleInfo.id); - vtMethodDefs.push_back(methodDef); + rejitRequests.emplace_back(MethodIdentifier(moduleInfo.id, methodDef)); Logger::Debug(" * Enqueue for ReJIT [ModuleId=", moduleInfo.id, ", MethodDef=", shared::TokenStr(&methodDef), ", AppDomainId=", moduleHandler->GetModuleMetadata()->app_domain_id, @@ -164,26 +166,219 @@ void RejitPreprocessor::ProcessTypeDefForRejit(const Rej } } +template +void RejitPreprocessor::ProcessTypesForRejit( + std::vector& rejitRequests, const ModuleInfo& moduleInfo, ComPtr metadataImport, + ComPtr metadataEmit, ComPtr assemblyImport, + ComPtr assemblyEmit, const RejitRequestDefinition& definition, + const MethodReference& targetMethod) +{ + // We are in the right module, so we try to load the mdTypeDef from the integration target type name. + mdTypeDef typeDef = mdTypeDefNil; + auto foundType = FindTypeDefByName(targetMethod.type.name, moduleInfo.assembly.name, metadataImport, typeDef); + if (!foundType) + { + return; + } + + // + // Looking for the method to rewrite + // + ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, assemblyEmit, moduleInfo, typeDef, + rejitRequests); +} + template ULONG RejitPreprocessor::RequestRejitForLoadedModules( const std::vector& modules, const std::vector& definitions, bool enqueueInSameThread) +{ + std::vector rejitRequests {}; + const auto rejitCount = PreprocessRejitRequests(modules, definitions, rejitRequests); + RequestRejit(rejitRequests, enqueueInSameThread); + return rejitCount; +} + +template +void RejitPreprocessor::RequestRejit(std::vector& rejitRequests, bool enqueueInSameThread) +{ + if (!rejitRequests.empty()) + { + std::vector vtModules; + std::vector vtMethodDefs; + + const auto rejitCount = rejitRequests.size(); + vtModules.reserve(rejitCount); + vtMethodDefs.reserve(rejitCount); + + for (const auto& rejitRequest : rejitRequests) + { + vtModules.push_back(rejitRequest.moduleId); + vtMethodDefs.push_back(rejitRequest.methodToken); + } + + if (enqueueInSameThread) + { + m_rejit_handler->RequestRejit(vtModules, vtMethodDefs); + } + else + { + m_rejit_handler->EnqueueForRejit(vtModules, vtMethodDefs); + } + } +} + +template +void RejitPreprocessor::RequestRevert(std::vector& revertRequests, bool enqueueInSameThread) +{ + if (!revertRequests.empty()) + { + std::vector vtModules; + std::vector vtMethodDefs; + + const auto rejitCount = revertRequests.size(); + vtModules.reserve(rejitCount); + vtMethodDefs.reserve(rejitCount); + + for (const auto& rejitRequest : revertRequests) + { + vtModules.push_back(rejitRequest.moduleId); + vtMethodDefs.push_back(rejitRequest.methodToken); + } + + if (enqueueInSameThread) + { + m_rejit_handler->RequestRevert(vtModules, vtMethodDefs); + } + else + { + m_rejit_handler->EnqueueForRevert(vtModules, vtMethodDefs); + } + } +} + +template +void RejitPreprocessor::EnqueueRequestRejit(std::vector& rejitRequests, + std::promise* promise) { if (m_rejit_handler->IsShutdownRequested()) { - return 0; + if (promise != nullptr) + { + promise->set_value(); + } + + return; } - auto corProfilerInfo = m_rejit_handler->GetCorProfilerInfo(); + if (rejitRequests.size() == 0) + { + return; + } + + Logger::Debug("RejitHandler::EnqueueRequestRejit"); + + std::function action = [=, requests = std::move(rejitRequests), promise = promise]() mutable { + // Process modules for rejit + RequestRejit(requests, true); + + // Resolve promise + if (promise != nullptr) + { + promise->set_value(); + } + }; + + // Enqueue + m_work_offloader->Enqueue(std::make_unique(std::move(action))); +} + +template +void RejitPreprocessor::EnqueueRequestRevert(std::vector& revertRequests, + std::promise* promise) +{ + if (m_rejit_handler->IsShutdownRequested()) + { + if (promise != nullptr) + { + promise->set_value(); + } + + return; + } + + if (revertRequests.size() == 0) + { + return; + } + + Logger::Debug("RejitHandler::EnqueueRequestRevert"); - std::vector vtModules; - std::vector vtMethodDefs; + std::function action = [=, requests = std::move(revertRequests), promise = promise]() mutable { + // Process modules for rejit + RequestRevert(requests, true); + + // Resolve promise + if (promise != nullptr) + { + promise->set_value(); + } + }; + + // Enqueue + m_work_offloader->Enqueue(std::make_unique(std::move(action))); +} + +template +void RejitPreprocessor::EnqueueRequestRejitForLoadedModules( + const std::vector& modulesVector, const std::vector& definitions, + std::promise* promise) +{ + if (m_rejit_handler->IsShutdownRequested()) + { + if (promise != nullptr) + { + promise->set_value(0); + } + + return; + } + + if (modulesVector.size() == 0 || definitions.size() == 0) + { + return; + } + + Logger::Debug("RejitHandler::EnqueueRequestRejitForLoadedModules"); + + std::function action = [=, modules = std::move(modulesVector), definitions = std::move(definitions), + promise = promise]() mutable { + // Process modules for rejit + const auto rejitCount = RequestRejitForLoadedModules(modules, definitions, true); + + // Resolve promise + if (promise != nullptr) + { + promise->set_value(rejitCount); + } + }; - // Preallocate with size => 15 due this is the current max of method interceptions in a single module - // (see InstrumentationDefinitions.Generated.cs) - vtModules.reserve(15); - vtMethodDefs.reserve(15); + // Enqueue + m_work_offloader->Enqueue(std::make_unique(std::move(action))); +} + +template +ULONG RejitPreprocessor::PreprocessRejitRequests( + const std::vector& modules, const std::vector& definitions, + std::vector& rejitRequests) +{ + if (m_rejit_handler->IsShutdownRequested()) + { + return 0; + } + + auto corProfilerInfo = m_rejit_handler->GetCorProfilerInfo(); for (const auto& module : modules) { @@ -210,7 +405,7 @@ ULONG RejitPreprocessor::RequestRejitForLoadedModules( { Logger::Debug(" Loading Assembly Metadata..."); auto hr = corProfilerInfo->GetModuleMetaData(moduleInfo.id, ofRead | ofWrite, IID_IMetaDataImport2, - metadataInterfaces.GetAddressOf()); + metadataInterfaces.GetAddressOf()); if (FAILED(hr)) { Logger::Warn("CallTarget_RequestRejitForModule failed to get metadata interface for ", @@ -284,8 +479,7 @@ ULONG RejitPreprocessor::RequestRejitForLoadedModules( // We check the assembly name and version if (ancestorAssemblyMetadata.name == target_method.type.assembly.name && - target_method.type.min_version <= - ancestorAssemblyMetadata.version && + target_method.type.min_version <= ancestorAssemblyMetadata.version && target_method.type.max_version >= ancestorAssemblyMetadata.version) { rewriteType = true; @@ -331,15 +525,13 @@ ULONG RejitPreprocessor::RequestRejitForLoadedModules( // Looking for the method to rewrite // ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, assemblyEmit, - moduleInfo, typeDef, vtModules, vtMethodDefs); + moduleInfo, typeDef, rejitRequests); } } } else { - // If the integration is not for the current assembly we skip. - if (target_method.type.assembly.name != tracemethodintegration_assemblyname && - target_method.type.assembly.name != moduleInfo.assembly.name) + if (ShouldSkipModule(moduleInfo, definition)) { continue; } @@ -348,7 +540,7 @@ ULONG RejitPreprocessor::RequestRejitForLoadedModules( { Logger::Debug(" Loading Assembly Metadata..."); auto hr = corProfilerInfo->GetModuleMetaData(moduleInfo.id, ofRead | ofWrite, IID_IMetaDataImport2, - metadataInterfaces.GetAddressOf()); + metadataInterfaces.GetAddressOf()); if (FAILED(hr)) { Logger::Warn("CallTarget_RequestRejitForModule failed to get metadata interface for ", @@ -377,52 +569,27 @@ ULONG RejitPreprocessor::RequestRejitForLoadedModules( continue; } - // We are in the right module, so we try to load the mdTypeDef from the integration target type name. - mdTypeDef typeDef = mdTypeDefNil; - auto foundType = FindTypeDefByName(target_method.type.name, moduleInfo.assembly.name, - metadataImport, typeDef); - if (!foundType) - { - continue; - } - - // - // Looking for the method to rewrite - // - ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, assemblyEmit, - moduleInfo, typeDef, vtModules, vtMethodDefs); + ProcessTypesForRejit(rejitRequests, moduleInfo, metadataImport, metadataEmit, assemblyImport, assemblyEmit, definition, target_method); } } } - const auto rejitCount = (ULONG) vtMethodDefs.size(); - - // Request the ReJIT for all integrations found in the module. - if (rejitCount > 0) - { - if (enqueueInSameThread) - { - m_rejit_handler->RequestRejit(vtModules, vtMethodDefs); - } - else - { - m_rejit_handler->EnqueueForRejit(vtModules, vtMethodDefs); - } - } + const auto rejitCount = (ULONG) rejitRequests.size(); return rejitCount; } template -void RejitPreprocessor::EnqueueRequestRejitForLoadedModules( - const std::vector& modulesVector, const std::vector& definitions, - std::promise* promise) +void RejitPreprocessor::EnqueuePreprocessRejitRequests(const std::vector& modulesVector, const std::vector& definitions, + std::promise>* promise) { + std::vector rejitRequests; + if (m_rejit_handler->IsShutdownRequested()) { if (promise != nullptr) { - promise->set_value(0); + promise->set_value(rejitRequests); } return; @@ -433,17 +600,19 @@ void RejitPreprocessor::EnqueueRequestRejitForLoadedModu return; } - Logger::Debug("RejitHandler::EnqueueRequestRejitForLoadedModules"); + Logger::Debug("RejitHandler::EnqueuePreprocessRejitRequests"); std::function action = [=, modules = std::move(modulesVector), definitions = std::move(definitions), + rejitRequests = rejitRequests, promise = promise]() mutable { + // Process modules for rejit - const auto rejitCount = RequestRejitForLoadedModules(modules, definitions, true); + const auto rejitCount = PreprocessRejitRequests(modules, definitions, rejitRequests); // Resolve promise if (promise != nullptr) { - promise->set_value(rejitCount); + promise->set_value(rejitRequests); } }; @@ -451,6 +620,12 @@ void RejitPreprocessor::EnqueueRequestRejitForLoadedModu m_work_offloader->Enqueue(std::make_unique(std::move(action))); } +template +void RejitPreprocessor::UpdateMethod(RejitHandlerModuleMethod* method, + const RejitRequestDefinition& definition) +{ +} + // TraceIntegrationRejitPreprocessor const MethodReference& TracerRejitPreprocessor::GetTargetMethod(const IntegrationDefinition& integrationDefinition) @@ -478,6 +653,16 @@ const std::unique_ptr TracerRejitPreprocessor::CreateM integrationDefinition); } +bool TracerRejitPreprocessor::ShouldSkipModule(const ModuleInfo& moduleInfo, const IntegrationDefinition& integrationDefinition) +{ + // If the integration is not for the current assembly we skip. + + const auto target_method = GetTargetMethod(integrationDefinition); + + return target_method.type.assembly.name != tracemethodintegration_assemblyname && + target_method.type.assembly.name != moduleInfo.assembly.name; +} + template class RejitPreprocessor; template class RejitPreprocessor; diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.h b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.h index 26f516ffc..11d4cb2bb 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.h +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/rejit_preprocessor.h @@ -21,17 +21,21 @@ struct FunctionInfo; template class RejitPreprocessor { -private: - void ProcessTypeDefForRejit(const RejitRequestDefinition& definition, ComPtr& metadataImport, - ComPtr& metadataEmit, ComPtr& assemblyImport, - ComPtr& assemblyEmit, const ModuleInfo& moduleInfo, - const mdTypeDef typeDef, std::vector& vtModules, - std::vector& vtMethodDefs); - protected: std::shared_ptr m_rejit_handler = nullptr; std::shared_ptr m_work_offloader = nullptr; + void ProcessTypeDefForRejit(const RejitRequestDefinition& definition, ComPtr& metadataImport, + ComPtr& metadataEmit, ComPtr& assemblyImport, + ComPtr& assemblyEmit, const ModuleInfo& moduleInfo, + const mdTypeDef typeDef, std::vector& rejitRequests); + + virtual void ProcessTypesForRejit(std::vector& rejitRequests, const ModuleInfo& moduleInfo, + ComPtr metadataImport, ComPtr metadataEmit, + ComPtr assemblyImport, + ComPtr assemblyEmit, const RejitRequestDefinition& definition, + const MethodReference& targetMethod); + virtual const MethodReference& GetTargetMethod(const RejitRequestDefinition& definition) = 0; virtual const bool GetIsDerived(const RejitRequestDefinition& definition) = 0; virtual const bool GetIsExactSignatureMatch(const RejitRequestDefinition& definition) = 0; @@ -39,6 +43,9 @@ class RejitPreprocessor RejitHandlerModule* module, const FunctionInfo& functionInfo, const RejitRequestDefinition& definition) = 0; + virtual bool ShouldSkipModule(const ModuleInfo& moduleInfo, const RejitRequestDefinition& definition) = 0; + + virtual void UpdateMethod(RejitHandlerModuleMethod* method, const RejitRequestDefinition& definition); public: RejitPreprocessor(std::shared_ptr rejit_handler, std::shared_ptr work_offloader); @@ -50,6 +57,20 @@ class RejitPreprocessor void EnqueueRequestRejitForLoadedModules(const std::vector& modulesVector, const std::vector& requests, std::promise* promise); + + ULONG PreprocessRejitRequests(const std::vector& modules, + const std::vector& definitions, + std::vector& rejitRequests); + + void EnqueuePreprocessRejitRequests(const std::vector& modules, + const std::vector& definitions, + std::promise>* promise); + + void RequestRejit(std::vector& rejitRequests, bool enqueueInSameThread = false); + void RequestRevert(std::vector& revertRequests, bool enqueueInSameThread = false); + + void EnqueueRequestRejit(std::vector& rejitRequests, std::promise* promise); + void EnqueueRequestRevert(std::vector& revertRequests, std::promise* promise); }; /// @@ -67,6 +88,7 @@ class TracerRejitPreprocessor : public RejitPreprocessor virtual const std::unique_ptr CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module, const FunctionInfo& functionInfo, const IntegrationDefinition& integrationDefinition) final; + bool ShouldSkipModule(const ModuleInfo& moduleInfo, const IntegrationDefinition& integrationDefinition) final; }; } // namespace trace diff --git a/tracer/src/Datadog.Trace.ClrProfiler.Native/tracer_tokens.cpp b/tracer/src/Datadog.Trace.ClrProfiler.Native/tracer_tokens.cpp index d223f8262..05ce89fc7 100644 --- a/tracer/src/Datadog.Trace.ClrProfiler.Native/tracer_tokens.cpp +++ b/tracer/src/Datadog.Trace.ClrProfiler.Native/tracer_tokens.cpp @@ -613,7 +613,7 @@ HRESULT TracerTokens::WriteLogException(void* rewriterWrapperPtr, mdTypeRef inte signature, signatureLength, &logExceptionRef); if (FAILED(hr)) { - Logger::Warn("Wrapper logExceptionRef could not be defined."); + Logger::Warn("Wrapper methodLogExceptionRef could not be defined."); return hr; } } diff --git a/tracer/src/Datadog.Trace.Coverage.collector/CoverageCollector.cs b/tracer/src/Datadog.Trace.Coverage.collector/CoverageCollector.cs index 9294052c2..78df6f37a 100644 --- a/tracer/src/Datadog.Trace.Coverage.collector/CoverageCollector.cs +++ b/tracer/src/Datadog.Trace.Coverage.collector/CoverageCollector.cs @@ -198,18 +198,23 @@ private void ProcessFolder(string folder, SearchOption searchOption) try { var json = JObject.Parse(File.ReadAllText(depsJsonPath)); - var libraries = (JObject)json["libraries"]; + var propertyName = $"Datadog.Trace/{version}"; var isDirty = false; - if (!libraries.ContainsKey(propertyName)) + if (json["libraries"] is JObject libraries) { - libraries.Add(propertyName, JObject.FromObject(new { type = "reference", serviceable = false, sha512 = string.Empty })); - isDirty = true; + if (!libraries.ContainsKey(propertyName)) + { + libraries.Add(propertyName, JObject.FromObject(new { type = "reference", serviceable = false, sha512 = string.Empty })); + isDirty = true; + } } - var targets = (JObject)json["targets"]; - foreach (var targetProperty in targets.Properties()) + var targetProperties = json["targets"] is JObject targets + ? targets.Properties() + : Array.Empty(); + foreach (var targetProperty in targetProperties) { var target = (JObject)targetProperty.Value; if (!target.ContainsKey(propertyName)) diff --git a/tracer/src/Datadog.Trace/Agent/DiscoveryService/DiscoveryService.cs b/tracer/src/Datadog.Trace/Agent/DiscoveryService/DiscoveryService.cs new file mode 100644 index 000000000..a549f7ea2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Agent/DiscoveryService/DiscoveryService.cs @@ -0,0 +1,94 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Threading.Tasks; +using Datadog.Trace.Configuration; +using Datadog.Trace.Logging; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; + +namespace Datadog.Trace.Agent.DiscoveryService +{ + internal class DiscoveryService : IDiscoveryService + { + private static readonly string[] SupportedDebuggerEndpoints = new[] { "debugger/v1/input" }; + private static readonly string[] SupportedProbeConfigurationEndpoints = new[] { "v0.7/config" }; + + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly IApiRequestFactory _apiRequestFactory; + private readonly Uri _agentUri; + + private DiscoveryService( + Uri agentUri, + IApiRequestFactory apiRequestFactory) + { + _agentUri = agentUri; + _apiRequestFactory = apiRequestFactory; + } + + public static string[] AllSupportedEndpoints => SupportedDebuggerEndpoints.Concat(SupportedProbeConfigurationEndpoints).ToArray(); + + public string ProbeConfigurationEndpoint { get; private set; } + + public string DebuggerEndpoint { get; private set; } + + public string AgentVersion { get; private set; } + + public static DiscoveryService Create(IConfigurationSource configurationSource, IApiRequestFactory apiRequestFactory) + { + var exporterSettings = new ExporterSettings(configurationSource); + return new DiscoveryService(exporterSettings.AgentUri, apiRequestFactory); + } + + public async Task DiscoverAsync() + { + try + { + var api = _apiRequestFactory.Create(new Uri($"{_agentUri}/info")); + using var response = await api.GetAsync().ConfigureAwait(false); + if (response.StatusCode != 200) + { + Log.Error("Failed to discover services"); + return false; + } + + var content = await response.ReadAsStringAsync().ConfigureAwait(false); + ProcessDiscoveryResponse(content); + + return true; + } + catch (Exception exception) + { + Log.Error(exception, "Failed to discover services"); + return false; + } + } + + private void ProcessDiscoveryResponse(string content) + { + var jObject = JsonConvert.DeserializeObject(content); + AgentVersion = jObject["version"]?.Value(); + + var discoveredEndpoints = (jObject["endpoints"] as JArray)?.Values().ToArray(); + if (discoveredEndpoints == null || discoveredEndpoints.Length == 0) + { + return; + } + + ProbeConfigurationEndpoint = SupportedProbeConfigurationEndpoints + .FirstOrDefault( + supportedEndpoint => discoveredEndpoints.Any( + endpoint => endpoint.Trim('/').Equals(supportedEndpoint, StringComparison.OrdinalIgnoreCase))); + + DebuggerEndpoint = SupportedDebuggerEndpoints + .FirstOrDefault( + supportedEndpoint => discoveredEndpoints.Any( + endpoint => endpoint.Trim('/').Equals(supportedEndpoint, StringComparison.OrdinalIgnoreCase))); + } + } +} diff --git a/tracer/src/Datadog.Trace/Agent/DiscoveryService/IDiscoveryService.cs b/tracer/src/Datadog.Trace/Agent/DiscoveryService/IDiscoveryService.cs new file mode 100644 index 000000000..367e5d904 --- /dev/null +++ b/tracer/src/Datadog.Trace/Agent/DiscoveryService/IDiscoveryService.cs @@ -0,0 +1,23 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Threading.Tasks; + +namespace Datadog.Trace.Agent.DiscoveryService +{ + /// + /// Queries datadog-agent and discovers which version we are running against and what endpoints it supports. + /// + internal interface IDiscoveryService + { + string ProbeConfigurationEndpoint { get; } + + string DebuggerEndpoint { get; } + + string AgentVersion { get; } + + Task DiscoverAsync(); + } +} diff --git a/tracer/src/Datadog.Trace/Agent/IApiRequest.cs b/tracer/src/Datadog.Trace/Agent/IApiRequest.cs index 6b81ff11a..aaaa226a1 100644 --- a/tracer/src/Datadog.Trace/Agent/IApiRequest.cs +++ b/tracer/src/Datadog.Trace/Agent/IApiRequest.cs @@ -12,6 +12,8 @@ internal interface IApiRequest { void AddHeader(string name, string value); + Task GetAsync(); + Task PostAsync(ArraySegment bytes, string contentType); } } diff --git a/tracer/src/Datadog.Trace/Agent/Transports/ApiWebRequest.cs b/tracer/src/Datadog.Trace/Agent/Transports/ApiWebRequest.cs index b8a8c360f..da6f9469e 100644 --- a/tracer/src/Datadog.Trace/Agent/Transports/ApiWebRequest.cs +++ b/tracer/src/Datadog.Trace/Agent/Transports/ApiWebRequest.cs @@ -36,6 +36,23 @@ public void AddHeader(string name, string value) _request.Headers.Add(name, value); } + public async Task GetAsync() + { + _request.Method = "GET"; + + try + { + var httpWebResponse = (HttpWebResponse)await _request.GetResponseAsync().ConfigureAwait(false); + return new ApiWebResponse(httpWebResponse); + } + catch (WebException exception) + when (exception.Status == WebExceptionStatus.ProtocolError && exception.Response != null) + { + // If the exception is caused by an error status code, swallow the exception and let the caller handle the result + return new ApiWebResponse((HttpWebResponse)exception.Response); + } + } + public async Task PostAsync(ArraySegment bytes, string contentType) { _request.Method = "POST"; diff --git a/tracer/src/Datadog.Trace/Agent/Transports/HttpClientRequest.cs b/tracer/src/Datadog.Trace/Agent/Transports/HttpClientRequest.cs index a9a989d8c..1c7d32c55 100644 --- a/tracer/src/Datadog.Trace/Agent/Transports/HttpClientRequest.cs +++ b/tracer/src/Datadog.Trace/Agent/Transports/HttpClientRequest.cs @@ -21,17 +21,29 @@ internal class HttpClientRequest : IApiRequest, IMultipartApiRequest private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); private readonly HttpClient _client; - private readonly HttpRequestMessage _request; + private readonly HttpRequestMessage _postRequest; + private readonly HttpRequestMessage _getRequest; + private readonly Uri _uri; public HttpClientRequest(HttpClient client, Uri endpoint) { _client = client; - _request = new HttpRequestMessage(HttpMethod.Post, endpoint); + _postRequest = new HttpRequestMessage(HttpMethod.Post, endpoint); + _getRequest = new HttpRequestMessage(HttpMethod.Get, endpoint); + _uri = endpoint; } public void AddHeader(string name, string value) { - _request.Headers.Add(name, value); + _postRequest.Headers.Add(name, value); + _getRequest.Headers.Add(name, value); + } + + public async Task GetAsync() + { + _getRequest.Content = null; + + return new HttpClientResponse(await _client.SendAsync(_getRequest).ConfigureAwait(false)); } public async Task PostAsync(ArraySegment bytes, string contentType) @@ -40,9 +52,9 @@ public async Task PostAsync(ArraySegment bytes, string conte using (var content = new ByteArrayContent(bytes.Array, bytes.Offset, bytes.Count)) { content.Headers.ContentType = new MediaTypeHeaderValue(contentType); - _request.Content = content; + _postRequest.Content = content; - var response = await _client.SendAsync(_request).ConfigureAwait(false); + var response = await _client.SendAsync(_postRequest).ConfigureAwait(false); return new HttpClientResponse(response); } @@ -58,7 +70,7 @@ public async Task PostAsync(params MultipartFormItem[] items) Log.Debug("Sending multipart form request with {Count} items.", items.Length); using var formDataContent = new MultipartFormDataContent(boundary: Boundary); - _request.Content = formDataContent; + _postRequest.Content = formDataContent; foreach (var item in items) { @@ -79,7 +91,7 @@ public async Task PostAsync(params MultipartFormItem[] items) } } - var response = await _client.SendAsync(_request).ConfigureAwait(false); + var response = await _client.SendAsync(_postRequest).ConfigureAwait(false); return new HttpClientResponse(response); } } diff --git a/tracer/src/Datadog.Trace/Agent/Transports/HttpStreamRequest.cs b/tracer/src/Datadog.Trace/Agent/Transports/HttpStreamRequest.cs index dc6102f83..5f49a6b18 100644 --- a/tracer/src/Datadog.Trace/Agent/Transports/HttpStreamRequest.cs +++ b/tracer/src/Datadog.Trace/Agent/Transports/HttpStreamRequest.cs @@ -5,6 +5,7 @@ using System; using System.IO; +using System.Net; using System.Threading.Tasks; using Datadog.Trace.HttpOverStreams; using Datadog.Trace.HttpOverStreams.HttpContent; @@ -31,15 +32,20 @@ public void AddHeader(string name, string value) _headers.Add(name, value); } - public async Task PostAsync(ArraySegment bytes, string contentType) => (await PostSegmentAsync(bytes, contentType).ConfigureAwait(false)).Item1; + public async Task GetAsync() => (await SendAsync(WebRequestMethods.Http.Get, null, null).ConfigureAwait(false)).Item1; - private async Task> PostSegmentAsync(ArraySegment segment, string contentType) + public async Task PostAsync(ArraySegment bytes, string contentType) => (await SendAsync(WebRequestMethods.Http.Post, contentType, new BufferContent(bytes)).ConfigureAwait(false)).Item1; + + private async Task> SendAsync(string verb, string contentType, IHttpContent content) { using (var bidirectionalStream = _streamFactory.GetBidirectionalStream()) { - var content = new BufferContent(segment); - _headers.Add("Content-Type", contentType); - var request = new HttpRequest("POST", _uri.Host, _uri.PathAndQuery, _headers, content); + if (contentType != null) + { + _headers.Add("Content-Type", contentType); + } + + var request = new HttpRequest(verb, _uri.Host, _uri.PathAndQuery, _headers, content); // send request, get response var response = await _client.SendAsync(request, bidirectionalStream, bidirectionalStream).ConfigureAwait(false); diff --git a/tracer/src/Datadog.Trace/Ci/CIVisibility.cs b/tracer/src/Datadog.Trace/Ci/CIVisibility.cs index ff6531f14..ae10ec81f 100644 --- a/tracer/src/Datadog.Trace/Ci/CIVisibility.cs +++ b/tracer/src/Datadog.Trace/Ci/CIVisibility.cs @@ -13,7 +13,7 @@ using Datadog.Trace.Ci.Configuration; using Datadog.Trace.Configuration; using Datadog.Trace.Logging; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; namespace Datadog.Trace.Ci { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/DocumentV5Struct.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/DocumentV5Struct.cs index 5d965021c..db1af5949 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/DocumentV5Struct.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/DocumentV5Struct.cs @@ -5,14 +5,15 @@ using Datadog.Trace.DuckTyping; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQLParser.AST.GraphQLDocument proxy for ducktyping -/// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/GraphQLDocument.cs -/// -[DuckCopy] -internal struct DocumentV5Struct +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { - public object Source; + /// + /// GraphQLParser.AST.GraphQLDocument proxy for ducktyping + /// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/GraphQLDocument.cs + /// + [DuckCopy] + internal struct DocumentV5Struct + { + public object Source; + } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ExecuteAsyncV5Integration.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ExecuteAsyncV5Integration.cs index 5a379bb13..d3bbd8539 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ExecuteAsyncV5Integration.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ExecuteAsyncV5Integration.cs @@ -7,81 +7,82 @@ using System.ComponentModel; using Datadog.Trace.ClrProfiler.CallTarget; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQL.Execution.ExecutionStrategy calltarget instrumentation -/// -[InstrumentMethod( - IntegrationName = GraphQLCommon.IntegrationName, - MethodName = GraphQLCommon.ExecuteAsyncMethodName, - ReturnTypeName = GraphQLCommon.ReturnTypeName, - ParameterTypeNames = new[] { GraphQLCommon.ExecutionContextTypeName }, - AssemblyName = GraphQLCommon.GraphQLAssembly, - TypeName = "GraphQL.Execution.ExecutionStrategy", - MinimumVersion = GraphQLCommon.Major5, - MaximumVersion = GraphQLCommon.Major5)] -[InstrumentMethod( - IntegrationName = GraphQLCommon.IntegrationName, - MethodName = GraphQLCommon.ExecuteAsyncMethodName, - ReturnTypeName = GraphQLCommon.ReturnTypeName, - ParameterTypeNames = new[] { GraphQLCommon.ExecutionContextTypeName }, - AssemblyName = GraphQLCommon.GraphQLAssembly, - TypeName = "GraphQL.Execution.SubscriptionExecutionStrategy", - MinimumVersion = GraphQLCommon.Major5, - MaximumVersion = GraphQLCommon.Major5)] -[Browsable(false)] -[EditorBrowsable(EditorBrowsableState.Never)] -public class ExecuteAsyncV5Integration +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { /// - /// OnMethodBegin callback - /// - /// Type of the target - /// Type of the execution context - /// Instance value, aka `this` of the instrumented method. - /// The execution context of the GraphQL operation. - /// Calltarget state value - internal static CallTargetState OnMethodBegin(TTarget instance, TContext context) - where TContext : IExecutionContextV5 - { - return new CallTargetState(scope: GraphQLCommon.CreateScopeFromExecuteAsyncV5(Tracer.Instance, context), state: context); - } - - /// - /// OnAsyncMethodEnd callback + /// GraphQL.Execution.ExecutionStrategy calltarget instrumentation /// - /// Type of the target - /// Type of the execution result value - /// Instance value, aka `this` of the instrumented method. - /// ExecutionResult instance - /// Exception instance in case the original code threw an exception. - /// Calltarget state value - /// A response value, in an async scenario will be T of Task of T - internal static TExecutionResult OnAsyncMethodEnd(TTarget instance, TExecutionResult executionResult, Exception exception, in CallTargetState state) + [InstrumentMethod( + IntegrationName = GraphQLCommon.IntegrationName, + MethodName = GraphQLCommon.ExecuteAsyncMethodName, + ReturnTypeName = GraphQLCommon.ReturnTypeName, + ParameterTypeNames = new[] { GraphQLCommon.ExecutionContextTypeName }, + AssemblyName = GraphQLCommon.GraphQLAssembly, + TypeName = "GraphQL.Execution.ExecutionStrategy", + MinimumVersion = GraphQLCommon.Major5, + MaximumVersion = GraphQLCommon.Major5)] + [InstrumentMethod( + IntegrationName = GraphQLCommon.IntegrationName, + MethodName = GraphQLCommon.ExecuteAsyncMethodName, + ReturnTypeName = GraphQLCommon.ReturnTypeName, + ParameterTypeNames = new[] { GraphQLCommon.ExecutionContextTypeName }, + AssemblyName = GraphQLCommon.GraphQLAssembly, + TypeName = "GraphQL.Execution.SubscriptionExecutionStrategy", + MinimumVersion = GraphQLCommon.Major5, + MaximumVersion = GraphQLCommon.Major5)] + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public class ExecuteAsyncV5Integration { - Scope scope = state.Scope; - if (state.Scope is null) + /// + /// OnMethodBegin callback + /// + /// Type of the target + /// Type of the execution context + /// Instance value, aka `this` of the instrumented method. + /// The execution context of the GraphQL operation. + /// Calltarget state value + internal static CallTargetState OnMethodBegin(TTarget instance, TContext context) + where TContext : IExecutionContextV5 { - return executionResult; + return new CallTargetState(scope: GraphQLCommon.CreateScopeFromExecuteAsyncV5(Tracer.Instance, context), state: context); } - try + /// + /// OnAsyncMethodEnd callback + /// + /// Type of the target + /// Type of the execution result value + /// Instance value, aka `this` of the instrumented method. + /// ExecutionResult instance + /// Exception instance in case the original code threw an exception. + /// Calltarget state value + /// A response value, in an async scenario will be T of Task of T + internal static TExecutionResult OnAsyncMethodEnd(TTarget instance, TExecutionResult executionResult, Exception exception, in CallTargetState state) { - if (exception != null) + Scope scope = state.Scope; + if (state.Scope is null) { - scope.Span?.SetException(exception); + return executionResult; } - else if (state.State is IExecutionContextV5 context) + + try { - GraphQLCommon.RecordExecutionErrorsIfPresent(scope.Span, GraphQLCommon.ExecuteErrorType, context.Errors); + if (exception != null) + { + scope.Span?.SetException(exception); + } + else if (state.State is IExecutionContextV5 context) + { + GraphQLCommon.RecordExecutionErrorsIfPresent(scope.Span, GraphQLCommon.ExecuteErrorType, context.Errors); + } + } + finally + { + scope.Dispose(); } - } - finally - { - scope.Dispose(); - } - return executionResult; + return executionResult; + } } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/GraphQLNameV5Struct.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/GraphQLNameV5Struct.cs index 949d574f4..0e47df9cc 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/GraphQLNameV5Struct.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/GraphQLNameV5Struct.cs @@ -5,14 +5,15 @@ using Datadog.Trace.DuckTyping; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQLParser.AST.GraphQLName -/// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/GraphQLName.cs -/// -[DuckCopy] -internal struct GraphQLNameV5Struct +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { - public string StringValue; + /// + /// GraphQLParser.AST.GraphQLName + /// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/GraphQLName.cs + /// + [DuckCopy] + internal struct GraphQLNameV5Struct + { + public string StringValue; + } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IExecutionContextV5.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IExecutionContextV5.cs index 87b7ac0a8..ddf113102 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IExecutionContextV5.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IExecutionContextV5.cs @@ -3,25 +3,26 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQL.Execution.ExecutionContext interface for ducktyping -/// -internal interface IExecutionContextV5 +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { /// - /// Gets the document associated with the execution context + /// GraphQL.Execution.ExecutionContext interface for ducktyping /// - DocumentV5Struct Document { get; } + internal interface IExecutionContextV5 + { + /// + /// Gets the document associated with the execution context + /// + DocumentV5Struct Document { get; } - /// - /// Gets the operation associated with the execution context - /// - OperationV5Struct Operation { get; } + /// + /// Gets the operation associated with the execution context + /// + OperationV5Struct Operation { get; } - /// - /// Gets the execution errors - /// - IExecutionErrors Errors { get; } + /// + /// Gets the execution errors + /// + IExecutionErrors Errors { get; } + } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IValidationContext.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IValidationContext.cs index 0965ad8a1..32efd00af 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IValidationContext.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/IValidationContext.cs @@ -3,13 +3,14 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQL.Validation.ValidationContext proxy -/// https://github.com/graphql-dotnet/graphql-dotnet/blob/ff28dccd9f318ceb4bcfb421428fb2324e6270f3/src/GraphQL/Validation/ValidationContext.cs -/// -internal interface IValidationContext +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { - DocumentV5Struct Document { get; } + /// + /// GraphQL.Validation.ValidationContext proxy + /// https://github.com/graphql-dotnet/graphql-dotnet/blob/ff28dccd9f318ceb4bcfb421428fb2324e6270f3/src/GraphQL/Validation/ValidationContext.cs + /// + internal interface IValidationContext + { + DocumentV5Struct Document { get; } + } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/OperationV5Struct.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/OperationV5Struct.cs index 0c19a3b5b..57196d91e 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/OperationV5Struct.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/OperationV5Struct.cs @@ -5,15 +5,16 @@ using Datadog.Trace.DuckTyping; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQLParser.AST.GraphQLOperationDefinition -/// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/Definitions/GraphQLOperationDefinition.cs -/// -[DuckCopy] -internal struct OperationV5Struct +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { - public GraphQLNameV5Struct Name; - public OperationTypeProxy Operation; + /// + /// GraphQLParser.AST.GraphQLOperationDefinition + /// https://github.com/graphql-dotnet/parser/blob/efb83a9f4054c0752cfeaac1e3c6b7cde5fa5607/src/GraphQLParser/AST/Definitions/GraphQLOperationDefinition.cs + /// + [DuckCopy] + internal struct OperationV5Struct + { + public GraphQLNameV5Struct Name; + public OperationTypeProxy Operation; + } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ValidateAsyncV5Integration.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ValidateAsyncV5Integration.cs index 157ad971f..840a7e31b 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ValidateAsyncV5Integration.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/GraphQL/ValidateAsyncV5Integration.cs @@ -6,56 +6,57 @@ using System.ComponentModel; using Datadog.Trace.ClrProfiler.CallTarget; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL; - -/// -/// GraphQL.Validation.DocumentValidator calltarget instrumentation for GraphQL 4 -/// -[InstrumentMethod( - AssemblyName = GraphQLCommon.GraphQLAssembly, - TypeName = "GraphQL.Validation.DocumentValidator", - MethodName = "ValidateAsyncCoreAsync", - ReturnTypeName = ClrNames.GenericParameterTask, - ParameterTypeNames = new[] { "GraphQL.Validation.ValidationContext", "System.Collections.Generic.IEnumerable`1[GraphQL.Validation.IValidationRule]" }, - MinimumVersion = GraphQLCommon.Major5, - MaximumVersion = GraphQLCommon.Major5, - IntegrationName = GraphQLCommon.IntegrationName)] -[Browsable(false)] -[EditorBrowsable(EditorBrowsableState.Never)] -public class ValidateAsyncV5Integration +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.GraphQL { - internal static CallTargetState OnMethodBegin(TTarget instance, TValidationContext validationContext, TRules rules) - where TValidationContext : IValidationContext - { - return new CallTargetState(GraphQLCommon.CreateScopeFromValidate(Tracer.Instance, validationContext.Document.Source?.ToString())); - } - - internal static TValidationResult OnAsyncMethodEnd(TTarget instance, TValidationResult validationResult, Exception exception, in CallTargetState state) - where TValidationResult : IValidationResultTuple + /// + /// GraphQL.Validation.DocumentValidator calltarget instrumentation for GraphQL 4 + /// + [InstrumentMethod( + AssemblyName = GraphQLCommon.GraphQLAssembly, + TypeName = "GraphQL.Validation.DocumentValidator", + MethodName = "ValidateAsyncCoreAsync", + ReturnTypeName = ClrNames.GenericParameterTask, + ParameterTypeNames = new[] { "GraphQL.Validation.ValidationContext", "System.Collections.Generic.IEnumerable`1[GraphQL.Validation.IValidationRule]" }, + MinimumVersion = GraphQLCommon.Major5, + MaximumVersion = GraphQLCommon.Major5, + IntegrationName = GraphQLCommon.IntegrationName)] + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public class ValidateAsyncV5Integration { - var scope = state.Scope; - - if (state.Scope is null) + internal static CallTargetState OnMethodBegin(TTarget instance, TValidationContext validationContext, TRules rules) + where TValidationContext : IValidationContext { - return validationResult; + return new CallTargetState(GraphQLCommon.CreateScopeFromValidate(Tracer.Instance, validationContext.Document.Source?.ToString())); } - try + internal static TValidationResult OnAsyncMethodEnd(TTarget instance, TValidationResult validationResult, Exception exception, in CallTargetState state) + where TValidationResult : IValidationResultTuple { - if (exception != null) + var scope = state.Scope; + + if (state.Scope is null) { - scope.Span?.SetException(exception); + return validationResult; } - else + + try { - GraphQLCommon.RecordExecutionErrorsIfPresent(scope.Span, GraphQLCommon.ValidationErrorType, validationResult.Item1.Errors); + if (exception != null) + { + scope.Span?.SetException(exception); + } + else + { + GraphQLCommon.RecordExecutionErrorsIfPresent(scope.Span, GraphQLCommon.ValidationErrorType, validationResult.Item1.Errors); + } + } + finally + { + scope.Dispose(); } - } - finally - { - scope.Dispose(); - } - return validationResult; + return validationResult; + } } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Grpc/GrpcLegacy/Client/AsyncCallHandleFinishedInstrumentation.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Grpc/GrpcLegacy/Client/AsyncCallHandleFinishedInstrumentation.cs index fe4917695..cabc3a93f 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Grpc/GrpcLegacy/Client/AsyncCallHandleFinishedInstrumentation.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Grpc/GrpcLegacy/Client/AsyncCallHandleFinishedInstrumentation.cs @@ -13,54 +13,55 @@ using Datadog.Trace.ExtensionMethods; using Datadog.Trace.Tagging; -namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Grpc.GrpcLegacy.Client; - -/// -/// Grpc.Core.Internal calltarget instrumentation -/// -[InstrumentMethod( - AssemblyName = "Grpc.Core", - TypeName = "Grpc.Core.Internal.AsyncCall`2", - MethodName = "HandleFinished", - ReturnTypeName = ClrNames.Void, - ParameterTypeNames = new[] { ClrNames.Bool, "Grpc.Core.Internal.ClientSideStatus" }, - MinimumVersion = "2.0.0", - MaximumVersion = "2.*.*", - IntegrationName = nameof(Grpc))] -[Browsable(false)] -[EditorBrowsable(EditorBrowsableState.Never)] -public static class AsyncCallHandleFinishedInstrumentation +namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Grpc.GrpcLegacy.Client { - internal static CallTargetState OnMethodBegin(TTarget instance, bool success, in TStatus clientSideStatus) + /// + /// Grpc.Core.Internal calltarget instrumentation + /// + [InstrumentMethod( + AssemblyName = "Grpc.Core", + TypeName = "Grpc.Core.Internal.AsyncCall`2", + MethodName = "HandleFinished", + ReturnTypeName = ClrNames.Void, + ParameterTypeNames = new[] { ClrNames.Bool, "Grpc.Core.Internal.ClientSideStatus" }, + MinimumVersion = "2.0.0", + MaximumVersion = "2.*.*", + IntegrationName = nameof(Grpc))] + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static class AsyncCallHandleFinishedInstrumentation { - var tracer = Tracer.Instance; - if (GrpcCoreApiVersionHelper.IsSupported && tracer.Settings.IsIntegrationEnabled(IntegrationId.Grpc)) + internal static CallTargetState OnMethodBegin(TTarget instance, bool success, in TStatus clientSideStatus) { - var asyncCall = instance.DuckCast(); - - // using CreateFrom to avoid boxing ClientSideStatus struct - var receivedStatus = DuckType.CreateCache.CreateFrom(clientSideStatus); - var status = receivedStatus.Status; - var scope = GrpcLegacyClientCommon.CreateClientSpan(tracer, in asyncCall.Details, in status); - if (scope?.Span is { } span) + var tracer = Tracer.Instance; + if (GrpcCoreApiVersionHelper.IsSupported && tracer.Settings.IsIntegrationEnabled(IntegrationId.Grpc)) { - if (receivedStatus.Trailers is { Count: > 0 }) - { - span.SetHeaderTags(new MetadataHeadersCollection(receivedStatus.Trailers), tracer.Settings.GrpcTags, defaultTagPrefix: GrpcCommon.ResponseMetadataTagPrefix); - } - else if (asyncCall.ResponseHeadersAsync is { IsCompleted: true } task) + var asyncCall = instance.DuckCast(); + + // using CreateFrom to avoid boxing ClientSideStatus struct + var receivedStatus = DuckType.CreateCache.CreateFrom(clientSideStatus); + var status = receivedStatus.Status; + var scope = GrpcLegacyClientCommon.CreateClientSpan(tracer, in asyncCall.Details, in status); + if (scope?.Span is { } span) { - var metadata = task.DuckCast().Result; - if (metadata?.Count > 0) + if (receivedStatus.Trailers is { Count: > 0 }) { - span.SetHeaderTags(new MetadataHeadersCollection(metadata), tracer.Settings.GrpcTags, defaultTagPrefix: GrpcCommon.ResponseMetadataTagPrefix); + span.SetHeaderTags(new MetadataHeadersCollection(receivedStatus.Trailers), tracer.Settings.GrpcTags, defaultTagPrefix: GrpcCommon.ResponseMetadataTagPrefix); + } + else if (asyncCall.ResponseHeadersAsync is { IsCompleted: true } task) + { + var metadata = task.DuckCast().Result; + if (metadata?.Count > 0) + { + span.SetHeaderTags(new MetadataHeadersCollection(metadata), tracer.Settings.GrpcTags, defaultTagPrefix: GrpcCommon.ResponseMetadataTagPrefix); + } } } + + scope?.Dispose(); } - scope?.Dispose(); + return CallTargetState.GetDefault(); } - - return CallTargetState.GetDefault(); } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/Common.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/Common.cs index 08ead96ec..2046be6e2 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/Common.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/Common.cs @@ -9,7 +9,7 @@ using Datadog.Trace.Ci.Tags; using Datadog.Trace.Configuration; using Datadog.Trace.Logging; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/MsTestV2/MsTestIntegration.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/MsTestV2/MsTestIntegration.cs index c72f79bd6..60c07f98c 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/MsTestV2/MsTestIntegration.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/MsTestV2/MsTestIntegration.cs @@ -13,7 +13,7 @@ using Datadog.Trace.DuckTyping; using Datadog.Trace.ExtensionMethods; using Datadog.Trace.Logging; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.MsTestV2 { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/NUnit/NUnitIntegration.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/NUnit/NUnitIntegration.cs index 0f34b4f79..5fc493058 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/NUnit/NUnitIntegration.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/NUnit/NUnitIntegration.cs @@ -12,7 +12,7 @@ using Datadog.Trace.Configuration; using Datadog.Trace.ExtensionMethods; using Datadog.Trace.Logging; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.NUnit { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/XUnit/XUnitIntegration.cs b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/XUnit/XUnitIntegration.cs index 192446f98..855f7cbcb 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/XUnit/XUnitIntegration.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/Testing/XUnit/XUnitIntegration.cs @@ -10,7 +10,7 @@ using Datadog.Trace.Ci.Tags; using Datadog.Trace.Configuration; using Datadog.Trace.ExtensionMethods; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.Testing.XUnit { diff --git a/tracer/src/Datadog.Trace/ClrProfiler/Instrumentation.cs b/tracer/src/Datadog.Trace/ClrProfiler/Instrumentation.cs index 3dbee96ec..954327462 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/Instrumentation.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/Instrumentation.cs @@ -13,6 +13,7 @@ using Datadog.Trace.Ci; using Datadog.Trace.ClrProfiler.ServerlessInstrumentation; using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger; using Datadog.Trace.DiagnosticListeners; using Datadog.Trace.Logging; using Datadog.Trace.ServiceFabric; @@ -152,6 +153,7 @@ public static void Initialize() InitializeNoNativeParts(); var tracer = Tracer.Instance; + InitializeLiveDebugger(); // before this line you should not call anything related to TracerManager.Instance // otherwise you can have multiple instances of Tracer @@ -333,5 +335,18 @@ private static void StartDiagnosticManager() DiagnosticManager.Instance = diagnosticManager; } #endif + + internal static void InitializeLiveDebugger() + { + try + { + Log.Debug("Initializing live debugger singleton instance."); + _ = LiveDebugger.Instance; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to initialize Live Debugger"); + } + } } } diff --git a/tracer/src/Datadog.Trace/ClrProfiler/NativeMethods.cs b/tracer/src/Datadog.Trace/ClrProfiler/NativeMethods.cs index b5f920525..d3a0c01da 100644 --- a/tracer/src/Datadog.Trace/ClrProfiler/NativeMethods.cs +++ b/tracer/src/Datadog.Trace/ClrProfiler/NativeMethods.cs @@ -13,7 +13,7 @@ namespace Datadog.Trace.ClrProfiler { internal static class NativeMethods { - private static readonly bool IsWindows = string.Equals(FrameworkDescription.Instance.OSPlatform, "Windows", StringComparison.OrdinalIgnoreCase); + private static readonly bool IsWindows = FrameworkDescription.Instance.IsWindows(); public static bool IsProfilerAttached() { diff --git a/tracer/src/Datadog.Trace/Configuration/ConfigurationKeys.Debugger.cs b/tracer/src/Datadog.Trace/Configuration/ConfigurationKeys.Debugger.cs new file mode 100644 index 000000000..f3f1280b1 --- /dev/null +++ b/tracer/src/Datadog.Trace/Configuration/ConfigurationKeys.Debugger.cs @@ -0,0 +1,78 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Debugger; +using Datadog.Trace.Logging.DirectSubmission; + +namespace Datadog.Trace.Configuration +{ + internal static partial class ConfigurationKeys + { + internal static class Debugger + { + /// + /// Configuration key for debugger poll interval (in seconds). + /// + /// + public const string PollInterval = "SIGNALFX_DEBUGGER_POLL_INTERVAL"; + + /// + /// Configuration key for the URL used to query our backend directly for the list of active probes. + /// This can only be used if SIGNALFX_API_KEY is also available. + /// + /// + public const string SnapshotUrl = "SIGNALFX_DEBUGGER_SNAPSHOT_URL"; + + /// + /// Configuration key for probe configuration file full path. + /// Loads the probe configuration from a local file on disk. Useful for local development and testing. + /// + /// + public const string ProbeFile = "SIGNALFX_DEBUGGER_PROBE_FILE"; + + /// + /// Configuration key for enabling or disabling Live Debugger. + /// Default value is false (disabled). + /// + /// + public const string Enabled = "SIGNALFX_DEBUGGER_ENABLED"; + + /// + /// Configuration key for the max object depth to serialize for probe snapshots. + /// Default value is 1. + /// + /// + public const string MaxDepthToSerialize = "SIGNALFX_DEBUGGER_MAX_DEPTH_TO_SERIALIZE"; + + /// + /// Configuration key for the maximum duration (in milliseconds) to run serialization for probe snapshots. + /// Default value is 150 ms. + /// + /// + public const string MaxTimeToSerialize = "SIGNALFX_DEBUGGER_MAX_TIME_TO_SERIALIZE"; + + /// + /// Configuration key for the maximum upload batch size. + /// Default value is 100. + /// + /// + public const string UploadBatchSize = "SIGNALFX_DEBUGGER_UPLOAD_BATCH_SIZE"; + + /// + /// Configuration key for the interval (in seconds) between sending probe statuses. + /// Default value is 3600. + /// + /// + public const string DiagnosticsInterval = "SIGNALFX_DEBUGGER_DIAGNOSTICS_INTERVAL"; + + /// + /// Configuration key for the interval (in milliseconds) between flushing statuses. + /// Default value is 0 (dynamic). + /// + /// + public const string UploadFlushInterval = "SIGNALFX_DEBUGGER_UPLOAD_FLUSH_INTERVAL"; + } + } +} diff --git a/tracer/src/Datadog.Trace/Configuration/ImmutableTracerSettings.cs b/tracer/src/Datadog.Trace/Configuration/ImmutableTracerSettings.cs index 2445b8c3e..e7e106d0a 100644 --- a/tracer/src/Datadog.Trace/Configuration/ImmutableTracerSettings.cs +++ b/tracer/src/Datadog.Trace/Configuration/ImmutableTracerSettings.cs @@ -8,6 +8,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using Datadog.Trace.Debugger; using Datadog.Trace.Logging.DirectSubmission; using Datadog.Trace.Util; @@ -83,6 +84,7 @@ public ImmutableTracerSettings(TracerSettings settings) LogSubmissionSettings = ImmutableDirectLogSubmissionSettings.Create(settings.LogSubmissionSettings); // Logs injection is enabled by default if direct log submission is enabled, otherwise disabled by default LogsInjectionEnabled = settings.LogSubmissionSettings.LogsInjectionEnabled ?? LogSubmissionSettings.IsEnabled; + DebuggerSettings = ImmutableDebuggerSettings.Create(settings.DebuggerSettings); PropagationStyleInject = settings.PropagationStyleInject; PropagationStyleExtract = settings.PropagationStyleExtract; @@ -271,6 +273,8 @@ public ImmutableTracerSettings(TracerSettings settings) internal ImmutableDirectLogSubmissionSettings LogSubmissionSettings { get; } + internal ImmutableDebuggerSettings DebuggerSettings { get; } + /// /// Gets a value indicating whether MongoDb integration should tag the command BsonDocument as db.statement. /// diff --git a/tracer/src/Datadog.Trace/Configuration/TracerSettings.cs b/tracer/src/Datadog.Trace/Configuration/TracerSettings.cs index e0b2ca2f7..92fdfaf53 100644 --- a/tracer/src/Datadog.Trace/Configuration/TracerSettings.cs +++ b/tracer/src/Datadog.Trace/Configuration/TracerSettings.cs @@ -10,13 +10,11 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using Datadog.Trace.AlwaysOnProfiler; using Datadog.Trace.Configuration.Helpers; -using Datadog.Trace.Configuration.Types; +using Datadog.Trace.Debugger; using Datadog.Trace.ExtensionMethods; using Datadog.Trace.Logging.DirectSubmission; using Datadog.Trace.PlatformHelpers; -using Datadog.Trace.SignalFx.Metrics; using Datadog.Trace.Vendors.Serilog; namespace Datadog.Trace.Configuration @@ -229,6 +227,8 @@ public TracerSettings(IConfigurationSource source) PropagationStyleInject = PropagationStyleInject.Concat(nameof(Propagators.ContextPropagators.Names.W3C)); } } + + DebuggerSettings = new DebuggerSettings(source); } /// @@ -529,6 +529,11 @@ public bool DiagnosticSourceEnabled /// internal bool ExpandRouteTemplatesEnabled { get; } + /// + /// Gets or sets the debugger settings. + /// + internal DebuggerSettings DebuggerSettings { get; set; } + /// /// Gets or sets the direct log submission settings. /// diff --git a/tracer/src/Datadog.Trace/ContinuousProfiler/ProfilerStatus.cs b/tracer/src/Datadog.Trace/ContinuousProfiler/ProfilerStatus.cs index 09f0fe382..57a0e8a0b 100644 --- a/tracer/src/Datadog.Trace/ContinuousProfiler/ProfilerStatus.cs +++ b/tracer/src/Datadog.Trace/ContinuousProfiler/ProfilerStatus.cs @@ -22,7 +22,13 @@ internal class ProfilerStatus : IProfilerStatus public ProfilerStatus() { - _isProfilingEnabled = EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.ProfilingEnabled)?.ToBoolean() ?? false; + var fd = FrameworkDescription.Instance; + var isSupported = + (fd.OSPlatform == OSPlatformName.Windows && (fd.ProcessArchitecture == ProcessArchitecture.X64 || fd.ProcessArchitecture == ProcessArchitecture.X86)) || + (fd.OSPlatform == OSPlatformName.Linux && fd.ProcessArchitecture == ProcessArchitecture.X64); + + _isProfilingEnabled = (EnvironmentHelpers.GetEnvironmentVariable(ConfigurationKeys.ProfilingEnabled)?.ToBoolean() ?? false) && isSupported; + Log.Information("Continuous Profiler is {IsEnabled}.", _isProfilingEnabled ? "enabled" : "disabled"); _lockObj = new(); _isInitialized = false; diff --git a/tracer/src/Datadog.Trace/Datadog.Trace.csproj b/tracer/src/Datadog.Trace/Datadog.Trace.csproj index fb20f5bfc..777253152 100644 --- a/tracer/src/Datadog.Trace/Datadog.Trace.csproj +++ b/tracer/src/Datadog.Trace/Datadog.Trace.csproj @@ -62,11 +62,11 @@ - $(DefineConstants);HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY + $(DefineConstants);HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY - $(DefineConstants);HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY + $(DefineConstants);HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS @@ -111,4 +111,4 @@ $(DefineConstants);THREAD_SAFE - \ No newline at end of file + diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationPoller.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationPoller.cs new file mode 100644 index 000000000..1c4699253 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationPoller.cs @@ -0,0 +1,109 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Threading; +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal class ConfigurationPoller : IConfigurationPoller + { + private const int MaxPollIntervalSeconds = 25; + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly IProbeConfigurationApi _probeConfigurationApi; + private readonly ConfigurationUpdater _configurationUpdater; + private readonly CancellationTokenSource _cancellationSource; + private readonly int _pollIntervalSeconds; + + private ConfigurationPoller( + IProbeConfigurationApi probeConfigurationApi, + ConfigurationUpdater configurationUpdater, + int pollIntervalSeconds) + { + _configurationUpdater = configurationUpdater; + _pollIntervalSeconds = pollIntervalSeconds; + _probeConfigurationApi = probeConfigurationApi; + + _cancellationSource = new CancellationTokenSource(); + } + + public static ConfigurationPoller Create( + IProbeConfigurationApi probeConfigurationApi, + ConfigurationUpdater configurationUpdater, + ImmutableDebuggerSettings settings) + { + return new ConfigurationPoller(probeConfigurationApi, configurationUpdater, settings.ProbeConfigurationsPollIntervalSeconds); + } + + public async Task StartPollingAsync() + { + var retryCount = 1; + ProbeConfiguration probeConfiguration = null; + + while (!_cancellationSource.IsCancellationRequested) + { + try + { + probeConfiguration = await _probeConfigurationApi.GetConfigurationsAsync().ConfigureAwait(false); + if (probeConfiguration != null) + { + retryCount = 1; + ApplySettings(probeConfiguration); + } + else + { + retryCount++; + } + + await Delay(retryCount, probeConfiguration).ConfigureAwait(false); + } + catch (ThreadAbortException) + { + throw; + } + catch (Exception e) + { + Log.Error(e, "Failed to poll probes settings"); + retryCount++; + await Delay(retryCount, probeConfiguration).ConfigureAwait(false); + } + } + + async Task Delay(int count, ProbeConfiguration config) + { + if (_cancellationSource.IsCancellationRequested) + { + return; + } + + var seconds = config?.OpsConfiguration?.PollInterval ?? _pollIntervalSeconds; + + try + { + var delay = Math.Min(seconds * count, MaxPollIntervalSeconds); + await Task.Delay(TimeSpan.FromSeconds(delay), _cancellationSource.Token).ConfigureAwait(false); + } + catch (TaskCanceledException) + { + // We are shutting down, so don't do anything about it + } + } + } + + private void ApplySettings(ProbeConfiguration configuration) + { + _configurationUpdater.Accept(configuration); + } + + public void Dispose() + { + _cancellationSource.Cancel(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationUpdater.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationUpdater.cs new file mode 100644 index 000000000..884d8bd62 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/ConfigurationUpdater.cs @@ -0,0 +1,114 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Vendors.Serilog; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal class ConfigurationUpdater + { + private const int MaxAllowedSnapshotProbes = 100; + private const int MaxAllowedMetricProbes = 100; + private readonly ImmutableDebuggerSettings _settings; + private ProbeConfiguration _currentConfiguration; + + private ConfigurationUpdater(ImmutableDebuggerSettings settings) + { + _settings = settings; + _currentConfiguration = new ProbeConfiguration(); + } + + public static ConfigurationUpdater Create(ImmutableDebuggerSettings settings) + { + return new ConfigurationUpdater(settings); + } + + public bool Accept(ProbeConfiguration configuration) + { + try + { + var filteredConfiguration = ApplyConfigurationFilters(configuration); + var comparer = new ProbeConfigurationComparer(_currentConfiguration, filteredConfiguration); + + if (comparer.HasProbeRelatedChanges) + { + HandleProbesChanges(comparer); + } + + if (comparer.HasRateLimitChanged) + { + HandleRateLimitChanged(comparer); + } + + _currentConfiguration = configuration; + + return true; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to accept configurations"); + return false; + } + } + + private ProbeConfiguration ApplyConfigurationFilters(ProbeConfiguration configuration) + { + return new ProbeConfiguration() + { + Id = configuration.Id, + AllowList = configuration.AllowList, + DenyList = configuration.DenyList, + OpsConfiguration = configuration.OpsConfiguration, + SnapshotProbes = Filter(configuration.SnapshotProbes, MaxAllowedSnapshotProbes), + MetricProbes = Filter(configuration.MetricProbes, MaxAllowedMetricProbes) + }; + + T[] Filter(T[] probes, int maxAllowedProbes) + where T : ProbeDefinition + { + return + probes + .Where(probe => probe.Active) + .Where(probe => probe.Language == TracerConstants.Language) + .Where(IsEnvAndVersionMatch) + .Take(maxAllowedProbes) + .ToArray(); + + bool IsEnvAndVersionMatch(ProbeDefinition probe) + { + if (probe.Tags == null || probe.Tags.Length == 0) + { + return true; + } + + var tagMap = + probe.Tags + .Distinct() + .Select(Tag.FromString) + .ToDictionary(tag => tag.Key, tag => tag.Value) + ; + + var envNotExistsOrMatch = !tagMap.TryGetValue("env", out var probeEnv) || probeEnv == _settings.Environment; + var versionNotExistsOrMatch = !tagMap.TryGetValue("version", out var probeVersion) || probeVersion == _settings.ServiceVersion; + + return envNotExistsOrMatch && versionNotExistsOrMatch; + } + } + } + + private void HandleProbesChanges(ProbeConfigurationComparer comparer) + { + LiveDebugger.Instance.UpdateProbeInstrumentations(comparer.AddedDefinitions, comparer.RemovedDefinitions); + } + + private void HandleRateLimitChanged(ProbeConfigurationComparer comparer) + { + // todo handle rate limited changes + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/FileProbeConfigurationApi.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/FileProbeConfigurationApi.cs new file mode 100644 index 000000000..035f4c026 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/FileProbeConfigurationApi.cs @@ -0,0 +1,35 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.IO; +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal class FileProbeConfigurationApi : IProbeConfigurationApi + { + private readonly string _targetPath; + + private FileProbeConfigurationApi(string targetPath) + { + _targetPath = targetPath; + } + + public static FileProbeConfigurationApi Create(ImmutableDebuggerSettings debuggerSettings) + { + return new FileProbeConfigurationApi(debuggerSettings.ProbeConfigurationsPath); + } + + public Task GetConfigurationsAsync() + { + var content = File.ReadAllText(_targetPath); + var config = JsonConvert.DeserializeObject(content); + + return Task.FromResult(config); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/IConfigurationPoller.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/IConfigurationPoller.cs new file mode 100644 index 000000000..a0d94ad29 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/IConfigurationPoller.cs @@ -0,0 +1,18 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Threading.Tasks; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal interface IConfigurationPoller : IDisposable + { + /// + /// Start polling configurations asynchronously in an endless loop. + /// + Task StartPollingAsync(); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/IProbeConfigurationApi.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/IProbeConfigurationApi.cs new file mode 100644 index 000000000..fb36e7d16 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/IProbeConfigurationApi.cs @@ -0,0 +1,15 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Configurations.Models; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal interface IProbeConfigurationApi + { + Task GetConfigurationsAsync(); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Capture.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Capture.cs new file mode 100644 index 000000000..be11428c4 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Capture.cs @@ -0,0 +1,37 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal struct Capture : IEquatable + { + public int MaxReferenceDepth { get; set; } + + public int MaxCollectionSize { get; set; } + + public int MaxLength { get; set; } + + public int MaxFieldDepth { get; set; } + + public int MaxFieldCount { get; set; } + + public bool Equals(Capture other) + { + return MaxReferenceDepth == other.MaxReferenceDepth && MaxCollectionSize == other.MaxCollectionSize && MaxLength == other.MaxLength && MaxFieldDepth == other.MaxFieldDepth && MaxFieldCount == other.MaxFieldCount; + } + + public override bool Equals(object obj) + { + return obj is Capture other && Equals(other); + } + + public override int GetHashCode() + { + return HashCode.Combine(MaxReferenceDepth, MaxCollectionSize, MaxLength, MaxFieldDepth, MaxFieldCount); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/FilterList.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/FilterList.cs new file mode 100644 index 000000000..9ba0ba2f3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/FilterList.cs @@ -0,0 +1,57 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Debugger.Helpers; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class FilterList : IEquatable + { + public string[] PackagePrefixes { get; set; } + + public string[] Classes { get; set; } + + public bool Equals(FilterList other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return PackagePrefixes.NullableSequentialEquals(other.PackagePrefixes) && Classes.NullableSequentialEquals(other.Classes); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((FilterList)obj); + } + + public override int GetHashCode() + { + return HashCode.Combine(PackagePrefixes, Classes); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/IJsonApiObject.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/IJsonApiObject.cs new file mode 100644 index 000000000..86818b025 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/IJsonApiObject.cs @@ -0,0 +1,12 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal interface IJsonApiObject + { + string Id { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricKind.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricKind.cs new file mode 100644 index 000000000..3caf4b2c8 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricKind.cs @@ -0,0 +1,14 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal enum MetricKind + { + COUNT, + GAUGE, + HISTOGRAM + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricProbe.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricProbe.cs new file mode 100644 index 000000000..971ac7fcb --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricProbe.cs @@ -0,0 +1,58 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class MetricProbe : ProbeDefinition, IEquatable + { + public MetricKind Kind { get; set; } + + public string MetricName { get; set; } + + public MetricValue Value { get; set; } + + public bool Equals(MetricProbe other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return base.Equals(other) && Kind == other.Kind && MetricName == other.MetricName && Value == other.Value; + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((MetricProbe)obj); + } + + public override int GetHashCode() + { + return HashCode.Combine(base.GetHashCode(), (int)Kind, MetricName); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricValue.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricValue.cs new file mode 100644 index 000000000..3c6548a5a --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/MetricValue.cs @@ -0,0 +1,12 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal record MetricValue + { + public string Expr { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/OpsConfiguration.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/OpsConfiguration.cs new file mode 100644 index 000000000..87775ff32 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/OpsConfiguration.cs @@ -0,0 +1,12 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class OpsConfiguration + { + public int PollInterval { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeConfiguration.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeConfiguration.cs new file mode 100644 index 000000000..f4e5bffdb --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeConfiguration.cs @@ -0,0 +1,33 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class ProbeConfiguration : IJsonApiObject + { + public string Id { get; set; } + + public SnapshotProbe[] SnapshotProbes { get; set; } = Array.Empty(); + + public MetricProbe[] MetricProbes { get; set; } = Array.Empty(); + + public FilterList AllowList { get; set; } + + public FilterList DenyList { get; set; } + + public Sampling? Sampling { get; set; } + + public OpsConfiguration OpsConfiguration { get; set; } + + public IEnumerable GetProbeDefinitions() + { + return SnapshotProbes.Cast().Concat(MetricProbes); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeDefinition.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeDefinition.cs new file mode 100644 index 000000000..7ab6da459 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/ProbeDefinition.cs @@ -0,0 +1,81 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Debugger.Helpers; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal abstract class ProbeDefinition : IJsonApiObject, IEquatable + { + public string Language { get; set; } + + public string Id { get; set; } + + public long? OrgId { get; set; } + + public string AppId { get; set; } + + public bool Active { get; set; } + + public string[] Tags { get; set; } + + public Where Where { get; set; } + + public string[] AdditionalIds { get; set; } + + public int? Version { get; set; } + + public bool Equals(ProbeDefinition other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return Language == other.Language && Id == other.Id && OrgId == other.OrgId && AppId == other.AppId && Active == other.Active && Equals(Where, other.Where) && Tags.NullableSequentialEquals(other.Tags) && Version == other.Version && AdditionalIds.NullableSequentialEquals(other.AdditionalIds); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((ProbeDefinition)obj); + } + + public override int GetHashCode() + { + var hashCode = new HashCode(); + hashCode.Add(Language); + hashCode.Add(Id); + hashCode.Add(OrgId); + hashCode.Add(AppId); + hashCode.Add(Active); + hashCode.Add(Tags); + hashCode.Add(Where); + hashCode.Add(AdditionalIds); + hashCode.Add(Version); + return hashCode.ToHashCode(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Sampling.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Sampling.cs new file mode 100644 index 000000000..184a678df --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Sampling.cs @@ -0,0 +1,29 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal struct Sampling : IEquatable + { + public double SnapshotsPerSecond { get; set; } + + public bool Equals(Sampling other) + { + return SnapshotsPerSecond.Equals(other.SnapshotsPerSecond); + } + + public override bool Equals(object obj) + { + return obj is Sampling other && Equals(other); + } + + public override int GetHashCode() + { + return SnapshotsPerSecond.GetHashCode(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/SnapshotProbe.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/SnapshotProbe.cs new file mode 100644 index 000000000..2f3ad8267 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/SnapshotProbe.cs @@ -0,0 +1,56 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class SnapshotProbe : ProbeDefinition, IEquatable + { + public Capture? Capture { get; set; } + + public Sampling? Sampling { get; set; } + + public bool Equals(SnapshotProbe other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return base.Equals(other) && Capture.Equals(other.Capture) && Sampling.Equals(other.Sampling); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((SnapshotProbe)obj); + } + + public override int GetHashCode() + { + return HashCode.Combine(base.GetHashCode(), Capture, Sampling); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Tag.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Tag.cs new file mode 100644 index 000000000..d23cdde6e --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Tag.cs @@ -0,0 +1,35 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal record Tag + { + public string Key { get; set; } + + public string Value { get; set; } + + public override string ToString() + { + return $"{Key}:{Value}"; + } + + public static Tag FromString(string str) + { + var index = str?.IndexOf(':'); + if (index is null or -1) + { + return null; + } + + var key = str.Substring(0, index.Value + 1); + var value = str.Substring(index.Value + 1); + + return new Tag() { Key = key, Value = value }; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Where.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Where.cs new file mode 100644 index 000000000..bddac70fa --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Models/Where.cs @@ -0,0 +1,64 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using Datadog.Trace.Debugger.Helpers; + +namespace Datadog.Trace.Debugger.Configurations.Models +{ + internal class Where : IEquatable + { + public string TypeName { get; set; } + + public string MethodName { get; set; } + + public string SourceFile { get; set; } + + public string Signature { get; set; } + + public string[] Lines { get; set; } + + public bool Equals(Where other) + { + if (ReferenceEquals(null, other)) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + + return TypeName == other.TypeName && MethodName == other.MethodName && SourceFile == other.SourceFile && Signature == other.Signature && Lines.NullableSequentialEquals(other.Lines); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((Where)obj); + } + + public override int GetHashCode() + { + return HashCode.Combine(TypeName, MethodName, SourceFile, Signature, Lines); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationApiFactory.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationApiFactory.cs new file mode 100644 index 000000000..5bb21acbe --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationApiFactory.cs @@ -0,0 +1,26 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.DiscoveryService; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal static class ProbeConfigurationApiFactory + { + public static IProbeConfigurationApi Create(ImmutableDebuggerSettings settings, IApiRequestFactory apiRequestFactory, IDiscoveryService discoveryService) + { + IProbeConfigurationApi api = settings.ProbeMode switch + { + ProbeMode.File => FileProbeConfigurationApi.Create(settings), + ProbeMode.Agent => RcmProbeConfigurationApi.Create(settings, apiRequestFactory, discoveryService), + _ => throw new ArgumentOutOfRangeException() + }; + + return api; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationComparer.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationComparer.cs new file mode 100644 index 000000000..e193a9ed3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/ProbeConfigurationComparer.cs @@ -0,0 +1,45 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Debugger.Configurations.Models; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal class ProbeConfigurationComparer + { + public ProbeConfigurationComparer( + ProbeConfiguration currentConfiguration, + ProbeConfiguration incomingConfiguration) + { + var addedSnapshots = incomingConfiguration.SnapshotProbes.Where(ip => !currentConfiguration.SnapshotProbes.Contains(ip)); + var removedSnapshots = currentConfiguration.SnapshotProbes.Where(ip => !incomingConfiguration.SnapshotProbes.Contains(ip)); + + var addedMetrics = incomingConfiguration.MetricProbes.Where(ip => !currentConfiguration.MetricProbes.Contains(ip)); + var removedMetrics = currentConfiguration.MetricProbes.Where(ip => !incomingConfiguration.MetricProbes.Contains(ip)); + + AddedDefinitions = addedSnapshots.Cast().Concat(addedMetrics).ToList(); + RemovedDefinitions = removedSnapshots.Cast().Concat(removedMetrics).ToList(); + + var isFilteredListChanged = + (!currentConfiguration.AllowList?.Equals(incomingConfiguration.AllowList) ?? incomingConfiguration.AllowList != null) + || (!currentConfiguration.DenyList?.Equals(incomingConfiguration.DenyList) ?? incomingConfiguration.DenyList != null); + + HasProbeRelatedChanges = AddedDefinitions.Any() || RemovedDefinitions.Any() || isFilteredListChanged; + HasRateLimitChanged = + (!currentConfiguration.Sampling?.Equals(incomingConfiguration.Sampling) ?? incomingConfiguration.Sampling != null) + || HasProbeRelatedChanges; + } + + public IReadOnlyList AddedDefinitions { get; } + + public IReadOnlyList RemovedDefinitions { get; } + + public bool HasProbeRelatedChanges { get; } + + public bool HasRateLimitChanged { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/RcmProbeConfigurationApi.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/RcmProbeConfigurationApi.cs new file mode 100644 index 000000000..a6fc758fc --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/RcmProbeConfigurationApi.cs @@ -0,0 +1,113 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.DiscoveryService; +using Datadog.Trace.Agent.Transports; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Debugger.Helpers; +using Datadog.Trace.Logging; +using Datadog.Trace.RemoteConfigurationManagement.Models; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Configurations +{ + internal class RcmProbeConfigurationApi : IProbeConfigurationApi + { + private const string ProductType = "LIVE_DEBUGGING"; + + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly IApiRequestFactory _apiRequestFactory; + private readonly string _targetPath; + private readonly IDiscoveryService _discoveryService; + private readonly ArraySegment _rcmRequestBody; + private readonly string _rcmTargetPath; + private Uri _uri; + + private RcmProbeConfigurationApi( + string targetPath, + IApiRequestFactory apiRequestFactory, + IDiscoveryService discoveryService, + ArraySegment rcmRequestBodyBody = new(), + string rcmTargetPath = null) + { + _apiRequestFactory = apiRequestFactory; + _targetPath = targetPath; + _discoveryService = discoveryService; + _rcmRequestBody = rcmRequestBodyBody; + _rcmTargetPath = rcmTargetPath; + } + + public static RcmProbeConfigurationApi Create( + ImmutableDebuggerSettings settings, + IApiRequestFactory apiRequestFactory, + IDiscoveryService discoveryService) + { + var rcmRequestBody = + RcmRequest + .Create( + products: new[] { ProductType }, + serviceName: settings.ServiceName, + serviceVersion: settings.ServiceVersion, + environment: settings.Environment, + runtimeId: settings.RuntimeId) + .AsArraySegment(); + + var rcmTargetPath = $"datadog/2/{ProductType}/{settings.ServiceName.ToUUID()}/config"; + + return new RcmProbeConfigurationApi(settings.ProbeConfigurationsPath, apiRequestFactory, discoveryService, rcmRequestBody, rcmTargetPath); + } + + public async Task GetConfigurationsAsync() + { + _uri ??= new Uri($"{_targetPath}/{_discoveryService.ProbeConfigurationEndpoint}"); + var request = _apiRequestFactory.Create(_uri); + + using var response = await request.PostAsync(_rcmRequestBody, MimeTypes.Json).ConfigureAwait(false); + var content = await response.ReadAsStringAsync().ConfigureAwait(false); + // TODO: validate certificate + + if (response.StatusCode is not (>= 200 and <= 299)) + { + Log.Warning("Failed to get configurations with status code {StatusCode} and message: {ResponseContent}", response.StatusCode, content); + return null; + } + + var config = ParseRcmResponse(content); + return config; + } + + private ProbeConfiguration ParseRcmResponse(string content) + { + if (string.IsNullOrWhiteSpace(content)) + { + return null; + } + + var rcmResponse = JsonConvert.DeserializeObject(content); + if (rcmResponse.TargetFiles == null || rcmResponse.TargetFiles.Length == 0) + { + return null; + } + + var path = rcmResponse.TargetFiles.FirstOrDefault(file => file.Path.Equals(_rcmTargetPath, StringComparison.OrdinalIgnoreCase)); + if (path == null) + { + Log.Warning("No matching probe configurations found in target paths."); + return null; + } + + var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(path.Raw)); + var config = JsonConvert.DeserializeObject(decoded); + + return config; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Configurations/Trie.cs b/tracer/src/Datadog.Trace/Debugger/Configurations/Trie.cs new file mode 100644 index 000000000..35e239076 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Configurations/Trie.cs @@ -0,0 +1,161 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Datadog.Trace.Debugger.Configurations +{ + /// + /// This Trie implementation is a direct translation of the Java debugger-agent implementation. + /// There are 2 ways to use this Trie: + /// 1. Insert full strings and match an exact string or a prefix on them + /// 2. Insert prefix strings and match a full string on them (HasMatchingPrefix). + /// 'prefixMode' indicates we have inserted prefixes inside the trie (usage 2.) + /// + internal class Trie + { + private readonly TrieNode _root; + + public Trie() + { + _root = new TrieNode((char)0); + } + + public Trie(List collection) + { + foreach (var str in collection) + { + Insert(str); + } + } + + public void Insert(string str) + { + var children = _root.Children; + for (var i = 0; i < str.Length; i++) + { + var c = str[i]; + TrieNode node; + if (children.ContainsKey(c)) + { + node = children[c]; + } + else + { + node = new TrieNode(c); + children[c] = node; + } + + children = node.Children; + node.IsLeaf = i == str.Length - 1; + if (node.IsLeaf) + { + node.Str = str; + } + } + } + + /// True if the string exists in the trie. + public bool Contains(string str) + { + var t = SearchNode(str, prefixMode: false); + return t is { IsLeaf: true }; + } + + // True if there is any word in the trie that starts with the given prefix + public bool ContainsPrefix(string prefix) + { + return SearchNode(prefix, prefixMode: false) != null; + } + + // True if str matches one of the prefixes stored into the trie + public bool HasMatchingPrefix(string str) + { + return SearchNode(str, prefixMode: true) != null; + } + + // true is there is no string inserted into the Trie, otherwise false + public bool IsEmpty() + { + return _root.Children.Count == 0; + } + + /// prefix to search into the trie + /// the string if unique that matches the given prefix, otherwise null + public string GetStringStartingWith(string prefix) + { + var node = SearchNode(prefix, prefixMode: false); + if (node == null) + { + return null; + } + + // while there is a unique path to the leaf, move forward + while (!node.IsLeaf && node.Children.Count == 1) + { + node = node.Children.Values.First(); + } + + return node.Str; + } + + /// String to search into the trie + /// prefixMode indicates String in the trie are prefixed and when reaching the leaf node we return it + /// last node that matches the whole given string or any prefix if prefixMode is true + private TrieNode SearchNode(string str, bool prefixMode) + { + var children = _root.Children; + TrieNode node = null; + for (var i = 0; i < str.Length; i++) + { + var c = str[i]; + if (children.ContainsKey(c)) + { + node = children[c]; + children = node.Children; + if (prefixMode && node.IsLeaf) + { + return node; + } + } + else + { + return null; + } + } + + return node; + } + + public static string ReverseStr(string str) + { + if (str == null) + { + return null; + } + + return new string(new StringBuilder(str).ToString().Reverse().ToArray()); + } + + private class TrieNode + { + public TrieNode(char c) + { + Children = new Dictionary(); + C = c; + } + + public char C { get; set; } + + public Dictionary Children { get; set; } + + public bool IsLeaf { get; set; } + + public string Str { get; set; } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/DebuggerSettings.cs b/tracer/src/Datadog.Trace/Debugger/DebuggerSettings.cs new file mode 100644 index 000000000..1e3ba3bc7 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/DebuggerSettings.cs @@ -0,0 +1,138 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Agent; +using Datadog.Trace.Configuration; + +namespace Datadog.Trace.Debugger +{ + internal class DebuggerSettings + { + private const int DefaultMaxDepthToSerialize = 1; + private const int DefaultSerializationTimeThreshold = 150; + private const int DefaultConfigurationsPollIntervalSeconds = 1; + private const int DefaultUploadBatchSize = 100; + private const int DefaultDiagnosticsIntervalSeconds = 3600; + private const int DefaultUploadFlushIntervalMilliseconds = 0; + + public DebuggerSettings() + : this(configurationSource: null) + { + } + + public DebuggerSettings(IConfigurationSource configurationSource) + { + ApiKey = configurationSource?.GetString(ConfigurationKeys.ApiKey); + RuntimeId = Util.RuntimeId.Get(); + ServiceName = configurationSource?.GetString(ConfigurationKeys.ServiceName); + + var exporterSettings = new ExporterSettings(configurationSource); + TransportType = exporterSettings.TracesTransport; + + var agentUri = exporterSettings.AgentUri.ToString().TrimEnd('/'); + AgentUri = exporterSettings.AgentUri; + SnapshotsPath = configurationSource?.GetString(ConfigurationKeys.Debugger.SnapshotUrl)?.TrimEnd('/') ?? agentUri; + + var probeFileLocation = configurationSource?.GetString(ConfigurationKeys.Debugger.ProbeFile); + var isFileModeMode = !string.IsNullOrWhiteSpace(probeFileLocation); + if (isFileModeMode) + { + ProbeMode = ProbeMode.File; + ProbeConfigurationsPath = probeFileLocation; + } + else + { + ProbeMode = ProbeMode.Agent; + ProbeConfigurationsPath = agentUri; + } + + var pollInterval = configurationSource?.GetInt32(ConfigurationKeys.Debugger.PollInterval); + ProbeConfigurationsPollIntervalSeconds = + pollInterval is null or <= 0 + ? DefaultConfigurationsPollIntervalSeconds + : pollInterval.Value; + + ServiceVersion = configurationSource?.GetString(ConfigurationKeys.ServiceVersion); + Environment = configurationSource?.GetString(ConfigurationKeys.Environment); + + Enabled = configurationSource?.GetBool(ConfigurationKeys.Debugger.Enabled) ?? false; + + var maxDepth = configurationSource?.GetInt32(ConfigurationKeys.Debugger.MaxDepthToSerialize); + MaximumDepthOfMembersToCopy = + maxDepth is null or <= 0 + ? DefaultMaxDepthToSerialize + : maxDepth.Value; + + var serializationTimeThreshold = configurationSource?.GetInt32(ConfigurationKeys.Debugger.MaxTimeToSerialize); + MaxSerializationTimeInMilliseconds = + serializationTimeThreshold is null or <= 0 + ? DefaultSerializationTimeThreshold + : serializationTimeThreshold.Value; + + var batchSize = configurationSource?.GetInt32(ConfigurationKeys.Debugger.UploadBatchSize); + UploadBatchSize = + batchSize is null or <= 0 + ? DefaultUploadBatchSize + : batchSize.Value; + + var interval = configurationSource?.GetInt32(ConfigurationKeys.Debugger.DiagnosticsInterval); + DiagnosticsIntervalSeconds = + interval is null or <= 0 + ? DefaultDiagnosticsIntervalSeconds + : interval.Value; + + var flushInterval = configurationSource?.GetInt32(ConfigurationKeys.Debugger.UploadFlushInterval); + UploadFlushIntervalMilliseconds = + flushInterval is null or < 0 + ? DefaultUploadFlushIntervalMilliseconds + : flushInterval.Value; + } + + public ProbeMode ProbeMode { get; } + + public string ApiKey { get; } + + public string RuntimeId { get; } + + public string ServiceName { get; } + + public string ServiceVersion { get; } + + public int ProbeConfigurationsPollIntervalSeconds { get; } + + public string ProbeConfigurationsPath { get; } + + public string SnapshotsPath { get; } + + public string Environment { get; } + + public bool Enabled { get; } + + public int MaxSerializationTimeInMilliseconds { get; } + + public int MaximumDepthOfMembersToCopy { get; } + + public int UploadBatchSize { get; } + + public int DiagnosticsIntervalSeconds { get; } + + public int UploadFlushIntervalMilliseconds { get; } + + public TracesTransportType TransportType { get; } + + public Uri AgentUri { get; } + + public static DebuggerSettings FromSource(IConfigurationSource source) + { + return new DebuggerSettings(source); + } + + public static DebuggerSettings FromDefaultSource() + { + return FromSource(GlobalSettings.CreateDefaultConfigurationSource()); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/DebuggerTransportStrategy.cs b/tracer/src/Datadog.Trace/Debugger/DebuggerTransportStrategy.cs new file mode 100644 index 000000000..866506de2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/DebuggerTransportStrategy.cs @@ -0,0 +1,29 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// +#nullable enable + +using System; +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.Transports; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger +{ + internal static class DebuggerTransportStrategy + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(DebuggerTransportStrategy)); + + public static IApiRequestFactory Get(Uri baseEndpoint) + { +#if NETCOREAPP + Log.Information("Using {FactoryType} for debugger transport.", nameof(HttpClientRequestFactory)); + return new HttpClientRequestFactory(baseEndpoint, AgentHttpHeaderNames.DefaultHeaders); +#else + Log.Information("Using {FactoryType} for debugger transport.", nameof(ApiWebRequestFactory)); + return new ApiWebRequestFactory(baseEndpoint, AgentHttpHeaderNames.DefaultHeaders); +#endif + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Helpers/DisposableEnumerable.cs b/tracer/src/Datadog.Trace/Debugger/Helpers/DisposableEnumerable.cs new file mode 100644 index 000000000..efc363f5f --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Helpers/DisposableEnumerable.cs @@ -0,0 +1,33 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; + +namespace Datadog.Trace.Debugger.Helpers +{ + internal readonly struct DisposableEnumerable : IDisposable + where T : IDisposable + { + private readonly List _items; + + public DisposableEnumerable(List items) => _items = items; + + public void Dispose() + { + foreach (var item in _items) + { + try + { + item.Dispose(); + } + catch + { + // ignored + } + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Helpers/EnumerableExtensions.cs b/tracer/src/Datadog.Trace/Debugger/Helpers/EnumerableExtensions.cs new file mode 100644 index 000000000..381656866 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Helpers/EnumerableExtensions.cs @@ -0,0 +1,28 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; + +namespace Datadog.Trace.Debugger.Helpers +{ + internal static class EnumerableExtensions + { + public static bool NullableSequentialEquals(this IEnumerable @this, IEnumerable other) + { + if (ReferenceEquals(null, @this)) + { + return ReferenceEquals(null, other); + } + + if (ReferenceEquals(null, other)) + { + return false; + } + + return @this.SequenceEqual(other); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Helpers/JTokenExtensions.cs b/tracer/src/Datadog.Trace/Debugger/Helpers/JTokenExtensions.cs new file mode 100644 index 000000000..309b7c8bf --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Helpers/JTokenExtensions.cs @@ -0,0 +1,42 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; + +namespace Datadog.Trace.Debugger.Helpers +{ + internal static class JTokenExtensions + { + public static bool IsNullOrEmpty(this JToken token) + { + return token == null || !token.HasValues; + } + + public static T ParseJsonApiObject(this JToken token) + where T : IJsonApiObject + { + var obj = token["attributes"].ToObject(); + if (obj != null) + { + obj.Id = token["id"].Value(); + } + + return obj; + } + + public static T[] ParseJsonApiObjects(this JToken token, string relationshipType, Dictionary objectMap) + where T : IJsonApiObject + { + return + token["relationships"]?[relationshipType]?["data"]? + .Select(t => t["id"].Value()) + .Select(id => ParseJsonApiObject(objectMap[id])) + .ToArray(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs b/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs new file mode 100644 index 000000000..9205fd344 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Helpers/StringExtensions.cs @@ -0,0 +1,31 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Security.Cryptography; +using System.Text; + +namespace Datadog.Trace.Debugger.Helpers +{ + internal static class StringExtensions + { + // https://stackoverflow.com/questions/18021808/uuid-interop-with-c-sharp-code + public static string ToUUID(this string input) + { + byte[] hash; + using (var md5 = MD5.Create()) + { + hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input)); + } + + hash[6] &= 0x0f; + hash[6] |= 0x30; + hash[8] &= 0x3f; + hash[8] |= 0x80; + var hex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower(); + return hex.Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-"); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ILineProbeResolver.cs b/tracer/src/Datadog.Trace/Debugger/ILineProbeResolver.cs new file mode 100644 index 000000000..11dacf66f --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ILineProbeResolver.cs @@ -0,0 +1,21 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Debugger.Models; + +namespace Datadog.Trace.Debugger +{ + /// + /// Matches a source file path with the assembly and pdb files that correlate to it, + /// and resolves the line probe's line number to a byte code offset. + /// + internal interface ILineProbeResolver + { + void OnDomainUnloaded(); + + LineProbeResolveResult TryResolveLineProbe(ProbeDefinition probe, out BoundLineProbeLocation location); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ImmutableDebuggerSettings.cs b/tracer/src/Datadog.Trace/Debugger/ImmutableDebuggerSettings.cs new file mode 100644 index 000000000..3fb6d7397 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ImmutableDebuggerSettings.cs @@ -0,0 +1,129 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Agent; +using Datadog.Trace.Configuration; + +namespace Datadog.Trace.Debugger +{ + internal class ImmutableDebuggerSettings + { + public ImmutableDebuggerSettings(bool enabled, ProbeMode probeMode, string apiKey, string runtimeId, string serviceName, string serviceVersion, int probeConfigurationsPollIntervalSeconds, string probeConfigurationsPath, string environment, int maxSerializationTimeInMilliseconds, int maximumDepthOfMembersToCopy, string snapshotsPath, int uploadBatchSize, int diagnosticsIntervalSeconds, int uploadFlushIntervalMilliseconds, TracesTransportType transportType, Uri agentUri) + { + Enabled = enabled; + ProbeMode = probeMode; + ApiKey = apiKey; + RuntimeId = runtimeId; + ServiceName = serviceName; + ServiceVersion = serviceVersion; + ProbeConfigurationsPollIntervalSeconds = probeConfigurationsPollIntervalSeconds; + ProbeConfigurationsPath = probeConfigurationsPath; + Environment = environment; + MaxSerializationTimeInMilliseconds = maxSerializationTimeInMilliseconds; + MaximumDepthOfMembersOfMembersToCopy = maximumDepthOfMembersToCopy; + SnapshotsPath = snapshotsPath; + UploadBatchSize = uploadBatchSize; + DiagnosticsIntervalSeconds = diagnosticsIntervalSeconds; + UploadFlushIntervalMilliseconds = uploadFlushIntervalMilliseconds; + TransportType = transportType; + AgentUri = agentUri; + } + + public bool Enabled { get; } + + public ProbeMode ProbeMode { get; } + + public string ApiKey { get; } + + public string RuntimeId { get; } + + public string ServiceName { get; } + + public string ServiceVersion { get; } + + public string ProbeConfigurationsPath { get; } + + public string SnapshotsPath { get; set; } + + public int ProbeConfigurationsPollIntervalSeconds { get; } + + public string Environment { get; } + + public int MaxSerializationTimeInMilliseconds { get; } + + public int MaximumDepthOfMembersOfMembersToCopy { get; } + + public int UploadBatchSize { get; } + + public int DiagnosticsIntervalSeconds { get; } + + public int UploadFlushIntervalMilliseconds { get; } + + public TracesTransportType TransportType { get; } + + public Uri AgentUri { get; } + + public static ImmutableDebuggerSettings Create(TracerSettings tracerSettings) => + Create(tracerSettings.DebuggerSettings); + + public static ImmutableDebuggerSettings Create(DebuggerSettings debuggerSettings) => + Create( + debuggerSettings.Enabled, + debuggerSettings.ProbeMode, + debuggerSettings.ApiKey, + debuggerSettings.RuntimeId, + debuggerSettings.ServiceName, + debuggerSettings.ServiceVersion, + debuggerSettings.ProbeConfigurationsPollIntervalSeconds, + debuggerSettings.ProbeConfigurationsPath, + debuggerSettings.Environment, + debuggerSettings.MaxSerializationTimeInMilliseconds, + debuggerSettings.MaximumDepthOfMembersToCopy, + debuggerSettings.SnapshotsPath, + debuggerSettings.UploadBatchSize, + debuggerSettings.DiagnosticsIntervalSeconds, + debuggerSettings.UploadFlushIntervalMilliseconds, + debuggerSettings.TransportType, + debuggerSettings.AgentUri); + + public static ImmutableDebuggerSettings Create( + bool enabled, + ProbeMode probeMode, + string apiKey, + string runtimeId, + string serviceName, + string serviceVersion, + int probeConfigurationsPollIntervalSeconds, + string probeConfigurationsPath, + string environment, + int maxSerializationTimeInMilliseconds, + int maximumDepthOfMembersOfMembersToCopy, + string snapshotsPath, + int uploadBatchSize, + int diagnosticsIntervalSeconds, + int uploadFlushIntervalMilliseconds, + TracesTransportType transportType, + Uri agentUri) => + new ImmutableDebuggerSettings( + enabled, + probeMode, + apiKey, + runtimeId, + serviceName, + serviceVersion, + probeConfigurationsPollIntervalSeconds, + probeConfigurationsPath, + environment, + maxSerializationTimeInMilliseconds, + maximumDepthOfMembersOfMembersToCopy, + snapshotsPath, + uploadBatchSize, + diagnosticsIntervalSeconds, + uploadFlushIntervalMilliseconds, + transportType, + agentUri); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/DebuggerReturn.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/DebuggerReturn.cs new file mode 100644 index 000000000..d89fe8321 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/DebuggerReturn.cs @@ -0,0 +1,74 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Live debugger return value + /// + /// Type of the return value + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public readonly ref struct DebuggerReturn + { + private readonly T _returnValue; + + /// + /// Initializes a new instance of the struct. + /// + /// Return value + public DebuggerReturn(T returnValue) + { + _returnValue = returnValue; + } + + /// + /// Gets the default live debugger return value (used by the native side to initialize the locals) + /// + /// Default live debugger return value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static DebuggerReturn GetDefault() + { + return default; + } + + /// + /// Gets the return value + /// + /// Return value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public T GetReturnValue() => _returnValue; + + /// + /// ToString override + /// + /// String value + public override string ToString() + { + return $"{typeof(DebuggerReturn).FullName}({_returnValue})"; + } + } + + /// + /// Live debugger return value + /// + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public readonly ref struct DebuggerReturn + { + /// + /// Gets the default live debugger return value (used by the native side to initialize the locals) + /// + /// Default live debugger return value + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static DebuggerReturn GetDefault() + { + return default; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerInvoker.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerInvoker.cs new file mode 100644 index 000000000..e80a7defa --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerInvoker.cs @@ -0,0 +1,196 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// LineDebuggerInvoker Invoker + /// + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static class LineDebuggerInvoker + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(LineDebuggerInvoker)); + private static readonly ImmutableDebuggerSettings Settings = ImmutableDebuggerSettings.Create(DebuggerSettings.FromDefaultSource()); + + private static LineDebuggerState CreateInvalidatedLineDebuggerState() + { + var defaultState = LineDebuggerState.GetDefault(); + defaultState.IsActive = false; + return defaultState; + } + + /// + /// Logs the given ByRef. + /// + /// Type of argument. + /// The argument to be logged. + /// index of given argument. + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogArg(ref TArg arg, int index, ref LineDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var paramName = state.MethodMetadaInfo.ParameterNames[index]; + state.SnapshotCreator.CaptureArgument(arg, paramName, index == 0, state.HasLocalsOrReturnValue); + state.HasLocalsOrReturnValue = false; + } + + /// + /// Logs the given ByRef. + /// + /// Type of local. + /// The local to be logged. + /// index of given argument. + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogLocal(ref TLocal local, int index, ref LineDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var localNamesFromPdb = state.MethodMetadaInfo.LocalVariableNames; + if (localNamesFromPdb != null) + { + if (index >= localNamesFromPdb.Length) + { + // This is an extra local that does not appear in the PDB. This should only happen if the customer + // is using an IL weaving or obfuscation tool that neglects to update the PDB. + // There's nothing we can do, so let's just ignore it. + return; + } + + if (localNamesFromPdb[index] == null) + { + // If the local does not appear in the PDB, then it is a compiler generated local and we shouldn't capture it. + return; + } + } + + string localName = localNamesFromPdb?[index] ?? "local_" + index; + state.SnapshotCreator.CaptureLocal(local, localName, index == 0 && !state.HasLocalsOrReturnValue); + state.HasLocalsOrReturnValue = true; + } + + /// + /// Log exception + /// + /// Target type + /// Exception instance + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogException(Exception exception, ref LineDebuggerState state) + { + Log.Error(exception, "Error caused by our instrumentation"); + state.IsActive = false; + } + + /// + /// Gets the default value of a type + /// + /// Type to get the default value + /// Default value of T + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetDefaultValue() => default; + + /// + /// Begin Line Invoker + /// + /// Target type + /// The id of the probe + /// Instance value + /// The handle of the executing method + /// The handle of the type + /// The index used to lookup for the associated with the executing method + /// The line instrumented + /// The path to the file of the probe + /// Live debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static LineDebuggerState BeginLine(string probeId, TTarget instance, RuntimeMethodHandle methodHandle, RuntimeTypeHandle typeHandle, int methodMetadataIndex, int lineNumber, string probeFilePath) + { + if (ProbeRateLimiter.Instance.IsLimitReached) + { + return CreateInvalidatedLineDebuggerState(); + } + + if (!MethodMetadataProvider.TryCreateIfNotExists(methodMetadataIndex, in methodHandle, in typeHandle)) + { + Log.Warning($"BeginMethod_StartMarker: Failed to receive the InstrumentedMethodInfo associated with the executing method. type = {typeof(TTarget)}, instance type name = {instance?.GetType().Name}, methodMetadaId = {methodMetadataIndex}"); + return CreateInvalidatedLineDebuggerState(); + } + + var state = new LineDebuggerState(probeId, scope: default, DateTimeOffset.UtcNow, methodMetadataIndex, lineNumber, probeFilePath); + state.SnapshotCreator.StartDebugger(); + state.SnapshotCreator.StartSnapshot(); + state.SnapshotCreator.StartCaptures(); + state.SnapshotCreator.StartLines(lineNumber); + state.SnapshotCreator.CaptureInstance(instance, state.MethodMetadaInfo.DeclaringType); + return state; + } + + /// + /// End Line + /// + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void EndLine(ref LineDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var duration = DateTimeOffset.UtcNow - state.StartTime; + state.SnapshotCreator.LineProbeEndReturn(); + FinalizeSnapshot(ref state, duration); + } + + private static void FinalizeSnapshot(ref LineDebuggerState state, TimeSpan? duration) + { + using (state.SnapshotCreator) + { + var frames = new StackTrace(skipFrames: 2, true).GetFrames() ?? Array.Empty(); + MethodBase method = null; + if (frames.Length > 0) + { + method = frames[0]?.GetMethod(); + } + + var probeId = state.ProbeId; + var probeFilePath = state.ProbeFilePath; + var methodName = method?.Name; + var type = method?.DeclaringType?.FullName; + var lineNumber = state.LineNumber; + + state.SnapshotCreator + .AddLineProbeInfo(probeId, probeFilePath, lineNumber) + .AddStackInfo(frames) + .EndSnapshot(duration) + .EndDebugger() + .AddLoggerInfo(methodName, type) + .AddGeneralInfo(Settings.ServiceName, null, null) // todo + .AddMessage() + ; + + var snapshot = state.SnapshotCreator.GetSnapshotJson(); + LiveDebugger.Instance.AddSnapshot(snapshot); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerState.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerState.cs new file mode 100644 index 000000000..f5a987e91 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/LineDebuggerState.cs @@ -0,0 +1,109 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using Datadog.Trace.Debugger.Snapshots; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Live debugger execution state + /// + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public ref struct LineDebuggerState + { + private readonly string _probeId; + private readonly Scope _scope; + private readonly DateTimeOffset? _startTime; + private readonly string _probeFilePath; + private readonly int _lineNumber; + + /// + /// Used to perform a fast lookup to grab the proper . + /// This index is hard-coded into the method's instrumented bytecode. + /// + private readonly int _methodMetadataIndex; + + // Determines whether we should still be capturing values, or halt for any reason (e.g an exception was caused by our instrumentation, rate limiter threshold reached). + internal bool IsActive = true; + + internal bool HasLocalsOrReturnValue; + + /// + /// Initializes a new instance of the struct. + /// + /// The id of the probe + /// Scope instance + /// The intended start time of the scope, intended for scopes created in the OnMethodEnd handler + /// The unique index of the method's + /// The line number where the probe is located on + /// The path to the file of the probe + internal LineDebuggerState(string probeId, Scope scope, DateTimeOffset? startTime, int methodMetadataIndex, int lineNumber, string probeFilePath) + { + _probeId = probeId; + _scope = scope; + _startTime = startTime; + _methodMetadataIndex = methodMetadataIndex; + _lineNumber = lineNumber; + _probeFilePath = probeFilePath; + HasLocalsOrReturnValue = false; + SnapshotCreator = new DebuggerSnapshotCreator(); + } + + internal ref MethodMetadataInfo MethodMetadaInfo => ref MethodMetadataProvider.Get(_methodMetadataIndex); + + /// + /// Gets the LiveDebugger SnapshotCreator + /// + internal DebuggerSnapshotCreator SnapshotCreator { get; } + + /// + /// Gets the LiveDebugger BeginMethod scope + /// + internal Scope Scope => _scope; + + /// + /// Gets the LiveDebugger state StartTime + /// + internal DateTimeOffset? StartTime => _startTime; + + /// + /// Gets the Id of the probe + /// + internal string ProbeId => _probeId; + + /// + /// Gets the location of the probe + /// + internal string ProbeFilePath => _probeFilePath; + + /// + /// Gets the Line Number + /// + internal int LineNumber => _lineNumber; + + /// + /// Gets the default live debugger state (used by the native side to initialize the locals) + /// + /// Default live debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static LineDebuggerState GetDefault() + { + return new LineDebuggerState(); + } + + /// + /// ToString override + /// + /// String value + public override string ToString() + { + return $"{typeof(LineDebuggerState).FullName}({_scope})"; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerInvoker.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerInvoker.cs new file mode 100644 index 000000000..db7686c79 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerInvoker.cs @@ -0,0 +1,272 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// MethodDebuggerInvoker + /// + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public static class MethodDebuggerInvoker + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(MethodDebuggerInvoker)); + private static readonly ImmutableDebuggerSettings Settings = ImmutableDebuggerSettings.Create(DebuggerSettings.FromDefaultSource()); + + /// + /// Begin Method Invoker + /// + /// Target type + /// The id of the probe + /// Instance value + /// The handle of the executing method + /// The handle of the type + /// The index used to lookup for the associated with the executing method + /// Live debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static MethodDebuggerState BeginMethod_StartMarker(string probeId, TTarget instance, RuntimeMethodHandle methodHandle, RuntimeTypeHandle typeHandle, int methodMetadataIndex) + { + if (ProbeRateLimiter.Instance.IsLimitReached) + { + return CreateInvalidatedDebuggerState(); + } + + if (!MethodMetadataProvider.TryCreateIfNotExists(methodMetadataIndex, in methodHandle, in typeHandle)) + { + Log.Warning($"BeginMethod_StartMarker: Failed to receive the InstrumentedMethodInfo associated with the executing method. type = {typeof(TTarget)}, instance type name = {instance?.GetType().Name}, methodMetadaId = {methodMetadataIndex}"); + return CreateInvalidatedDebuggerState(); + } + + var state = new MethodDebuggerState(probeId, scope: default, DateTimeOffset.UtcNow, methodMetadataIndex); + state.SnapshotCreator.StartDebugger(); + + state.SnapshotCreator.StartSnapshot(); + state.SnapshotCreator.StartCaptures(); + state.SnapshotCreator.StartEntry(); + state.SnapshotCreator.CaptureInstance(instance, state.MethodMetadaInfo.DeclaringType); + return state; + } + + private static MethodDebuggerState CreateInvalidatedDebuggerState() + { + var defaultState = MethodDebuggerState.GetDefault(); + defaultState.IsActive = false; + return defaultState; + } + + /// + /// Ends the markering of BeginMethod. + /// + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void BeginMethod_EndMarker(ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var hasArgumentsOrLocals = state.HasLocalsOrReturnValue || + state.MethodMetadaInfo.ParameterNames.Length > 0; + state.HasLocalsOrReturnValue = false; + state.SnapshotCreator.EndEntry(hasArgumentsOrLocals); + } + + /// + /// Logs the given ByRef. + /// + /// Type of argument. + /// The argument to be logged. + /// index of given argument. + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogArg(ref TArg arg, int index, ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var paramName = state.MethodMetadaInfo.ParameterNames[index]; + state.SnapshotCreator.CaptureArgument(arg, paramName, index == 0, state.HasLocalsOrReturnValue); + state.HasLocalsOrReturnValue = false; + } + + /// + /// Logs the given ByRef. + /// + /// Type of local. + /// The local to be logged. + /// index of given argument. + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogLocal(ref TLocal local, int index, ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var localNamesFromPdb = state.MethodMetadaInfo.LocalVariableNames; + if (localNamesFromPdb != null) + { + if (index >= localNamesFromPdb.Length) + { + // This is an extra local that does not appear in the PDB. This should only happen if the customer + // is using an IL weaving or obfuscation tool that neglects to update the PDB. + // There's nothing we can do, so let's just ignore it. + return; + } + + if (localNamesFromPdb[index] == null) + { + // If the local does not appear in the PDB, then it is a compiler generated local and we shouldn't capture it. + return; + } + } + + string localName = localNamesFromPdb?[index] ?? "local_" + index; + state.SnapshotCreator.CaptureLocal(local, localName, index == 0 && !state.HasLocalsOrReturnValue); + state.HasLocalsOrReturnValue = true; + } + + /// + /// End Method with Void return value invoker + /// + /// Target type + /// Instance value + /// Exception value + /// Debugger state + /// CallTarget return structure + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static DebuggerReturn EndMethod_StartMarker(TTarget instance, Exception exception, ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return DebuggerReturn.GetDefault(); + } + + state.SnapshotCreator.StartReturn(); + state.SnapshotCreator.CaptureInstance(instance, state.MethodMetadaInfo.DeclaringType); + if (exception != null) + { + state.SnapshotCreator.CaptureException(exception); + } + + return DebuggerReturn.GetDefault(); + } + + /// + /// End Method with Return value invoker + /// + /// Target type + /// Return type + /// Instance value + /// Return value + /// Exception value + /// Debugger state + /// LiveDebugger return structure + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static DebuggerReturn EndMethod_StartMarker(TTarget instance, TReturn returnValue, Exception exception, ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return new DebuggerReturn(returnValue); + } + + state.SnapshotCreator.StartReturn(); + state.SnapshotCreator.CaptureInstance(instance, state.MethodMetadaInfo.DeclaringType); + if (exception != null) + { + state.SnapshotCreator.CaptureException(exception); + } + else + { + state.SnapshotCreator.CaptureLocal(returnValue, "@return", true); + state.HasLocalsOrReturnValue = true; + } + + return new DebuggerReturn(returnValue); + } + + /// + /// End Method with Void return value invoker + /// + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void EndMethod_EndMarker(ref MethodDebuggerState state) + { + if (!state.IsActive) + { + return; + } + + var hasArgumentsOrLocals = state.HasLocalsOrReturnValue || + state.MethodMetadaInfo.ParameterNames.Length > 0; + state.SnapshotCreator.MethodProbeEndReturn(hasArgumentsOrLocals); + FinalizeSnapshot(ref state); + } + + /// + /// Log exception + /// + /// Target type + /// Exception instance + /// Debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void LogException(Exception exception, ref MethodDebuggerState state) + { + Log.Error(exception, "Error caused by our instrumentation"); + state.IsActive = false; + } + + /// + /// Gets the default value of a type + /// + /// Type to get the default value + /// Default value of T + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetDefaultValue() => default; + + private static void FinalizeSnapshot(ref MethodDebuggerState state) + { + using (state.SnapshotCreator) + { + var frames = new StackTrace(skipFrames: 2, true).GetFrames() ?? Array.Empty(); + MethodBase method = null; + if (frames.Length > 0) + { + method = frames[0]?.GetMethod(); + } + + var probeId = state.ProbeId; + var methodName = method?.Name; + var type = method?.DeclaringType?.FullName; + var duration = DateTimeOffset.UtcNow - state.StartTime; + + state.SnapshotCreator + .AddMethodProbeInfo(probeId, methodName, type) + .AddStackInfo(frames) + .EndSnapshot(duration) + .EndDebugger() + .AddLoggerInfo(methodName, type) + .AddGeneralInfo(Settings.ServiceName, null, null) // todo + .AddMessage() + ; + + var snapshot = state.SnapshotCreator.GetSnapshotJson(); + LiveDebugger.Instance.AddSnapshot(snapshot); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerState.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerState.cs new file mode 100644 index 000000000..5a103a41d --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodDebuggerState.cs @@ -0,0 +1,93 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using Datadog.Trace.Debugger.Snapshots; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Live debugger execution state + /// + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + public ref struct MethodDebuggerState + { + private readonly string _probeId; + private readonly Scope _scope; + private readonly DateTimeOffset? _startTime; + + /// + /// Used to perform a fast lookup to grab the proper . + /// This index is hard-coded into the method's instrumented bytecode. + /// + private readonly int _methodMetadataIndex; + + // Determines whether we should still be capturing values, or halt for any reason (e.g an exception was caused by our instrumentation, rate limiter threshold reached). + internal bool IsActive = true; + + internal bool HasLocalsOrReturnValue; + + /// + /// Initializes a new instance of the struct. + /// + /// The id of the probe + /// Scope instance + /// The intended start time of the scope, intended for scopes created in the OnMethodEnd handler + /// The unique index of the method's + internal MethodDebuggerState(string probeId, Scope scope, DateTimeOffset? startTime, int methodMetadataIndex) + { + _probeId = probeId; + _scope = scope; + _startTime = startTime; + _methodMetadataIndex = methodMetadataIndex; + HasLocalsOrReturnValue = false; + SnapshotCreator = new DebuggerSnapshotCreator(); + } + + internal ref MethodMetadataInfo MethodMetadaInfo => ref MethodMetadataProvider.Get(_methodMetadataIndex); + + /// + /// Gets the LiveDebugger SnapshotCreator + /// + internal DebuggerSnapshotCreator SnapshotCreator { get; } + + /// + /// Gets the LiveDebugger BeginMethod scope + /// + internal Scope Scope => _scope; + + /// + /// Gets the LiveDebugger state StartTime + /// + internal DateTimeOffset? StartTime => _startTime; + + /// + /// Gets the Id of the probe + /// + internal string ProbeId => _probeId; + + /// + /// Gets the default live debugger state (used by the native side to initialize the locals) + /// + /// Default live debugger state + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static MethodDebuggerState GetDefault() + { + return new MethodDebuggerState(); + } + + /// + /// ToString override + /// + /// String value + public override string ToString() + { + return $"{typeof(MethodDebuggerState).FullName}({_scope})"; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfo.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfo.cs new file mode 100644 index 000000000..c81971dce --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfo.cs @@ -0,0 +1,32 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Holds data needed during Debugger instrumentation execution. + /// + internal readonly record struct MethodMetadataInfo + { + public MethodMetadataInfo(string[] parameterNames, string[] localVariableNames, Type type) + { + ParameterNames = parameterNames; + LocalVariableNames = localVariableNames; + DeclaringType = type; + } + + public string[] ParameterNames { get; } + + /// + /// Gets the names of the method's local variable, in the same order as they appear in the method's LocalVarSig. + /// May contain null entries to denote compiler generated locals whose names are meaningless. + /// + public string[] LocalVariableNames { get; } + + public Type DeclaringType { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfoFactory.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfoFactory.cs new file mode 100644 index 000000000..def5496a0 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataInfoFactory.cs @@ -0,0 +1,92 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Reflection; +using Datadog.Trace.Logging; +using Datadog.Trace.Pdb; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Responsible to create structures. + /// + internal static class MethodMetadataInfoFactory + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + public static MethodMetadataInfo Create(MethodBase method, Type type) + { + return new MethodMetadataInfo(GetParameterNames(method), GetLocalVariableNames(method), type); + } + + private static string[] GetParameterNames(MethodBase method) + { + return method.GetParameters()?.Select(parameter => parameter.Name).ToArray() ?? Array.Empty(); + } + + /// + /// Gets the local variable names from the PDB. + /// + /// The method for which we are requesting the local variables + /// + /// The names of the method's local variable, in the same order as they appear in the method's LocalVarSig. + /// May contain null entries to denote compiler generated locals whose names are meaningless. + /// + private static string[] GetLocalVariableNames(MethodBase method) + { + try + { + using var pdbReader = DatadogPdbReader.CreatePdbReader(method.Module.Assembly); + if (pdbReader == null) + { + return null; // PDB file could not be loaded + } + + var symbolMethod = pdbReader.ReadMethodSymbolInfo(method.MetadataToken); + if (symbolMethod == null) + { + return null; // Method was not found in PDB file + } + + var methodBody = method.GetMethodBody(); + if (methodBody == null) + { + return null; // Could not read method body, so we can't verify locals + } + + var localVariables = symbolMethod.GetLocalVariables(); + int localVariablesCount = methodBody.LocalVariables.Count; + string[] localNames = new string[localVariablesCount]; + foreach (var local in localVariables) + { + if (local.Attributes.HasFlag(PdbLocalAttributes.DebuggerHidden)) + { + continue; + } + + if (local.Index > localVariablesCount) + { + // PDB information is inconsistent with the locals that are actually in the metadata. + // This might be caused by code obfuscation tools that try to remove/modify locals, and neglect to update the PDB. + // We'll simply ignore these additional locals in the hope that things will work out for the best. + continue; + } + + localNames[local.Index] = local.Name; + } + + return localNames; + } + catch (Exception e) + { + Log.Error(e, $"Failed to obtain local variable names from PDB for {method.Name}"); + return null; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataProvider.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataProvider.cs new file mode 100644 index 000000000..df5e14596 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/MethodMetadataProvider.cs @@ -0,0 +1,131 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + /// + /// Acts as a registry of indexed . + /// Each debugger-instrumented method is given an index (hard-coded into the instrumented bytecode), + /// and this index is used to perform O(1) lookup for the corresponding instance. + /// The reason the index is incremented and dictated by the native side is to support multi-AppDomain scenarios. + /// In these scenario, there will be multiple arrays, one for each AppDomain. + /// In order for us to grab the same across all of them, we need to dereference the same index, + /// because the same instrumented bytecode could execute in different AppDomains, and static fields are not shared across AppDomains. + /// + internal static class MethodMetadataProvider + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(MethodMetadataProvider)); + private static readonly object ItemsLocker = new object(); + + private static MethodMetadataInfo[] _items = new MethodMetadataInfo[16]; + + private static int Capacity + { + set + { + if (value != _items.Length) + { + var newItems = new MethodMetadataInfo[value]; + + // ReSharper disable once InconsistentlySynchronizedField + Array.Copy(_items, 0, newItems, 0, _items.Length); + + // ReSharper disable once InconsistentlySynchronizedField + _items = newItems; + } + } + } + + private static void EnsureCapacity(int min) + { + // Enlarge the _items array as needed. Note that there is an implicit by-design memory-leak here, + // in the sense that this unbounded collection can only grow and is never shrunk. + // This is fine, for the time being, because we are limited to 100 simultaneous probes anyhow, so it is extremely unlikely + // we will ever reach any substantial memory usage here. + if (_items.Length < min) + { + var newCapacity = _items.Length * 2; + if (newCapacity < min) + { + newCapacity = min + 1; + } + + Capacity = newCapacity; + } + } + + public static void Remove(int index) + { + lock (ItemsLocker) + { + _items[index] = default; + } + } + + /// + /// Tries to create a new at . + /// + /// The index of the method inside + /// The handle of the executing method + /// The handle of the type + /// true if succeeded (either existed before or just created), false if fails to create + public static bool TryCreateIfNotExists(int index, in RuntimeMethodHandle methodHandle, in RuntimeTypeHandle typeHandle) + { + // Check if there's a MetadataMethodInfo associated with the given index + if (index < _items.Length) + { + // ReSharper disable once InconsistentlySynchronizedField + ref var methodMetadataInfo = ref _items[index]; + + if (methodMetadataInfo != default) + { + return true; + } + } + + // Create a new one at the given index + lock (ItemsLocker) + { + if (index == _items.Length) + { + EnsureCapacity(index + 1); + } + else if (index > _items.Length) + { + EnsureCapacity(index); + } + + var method = MethodBase.GetMethodFromHandle(methodHandle, typeHandle); + var type = Type.GetTypeFromHandle(typeHandle); + + if (Log.IsEnabled(Vendors.Serilog.Events.LogEventLevel.Debug)) + { + Log.Debug($"{nameof(MethodMetadataProvider)}.{nameof(TryCreateIfNotExists)}: Creating a new metadata info for method = {method}, index = {index}, Items.Length = {_items.Length}"); + } + + if (method == null) + { + return false; + } + + var methodMetadataInfo = MethodMetadataInfoFactory.Create(method, type); + _items[index] = methodMetadataInfo; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref MethodMetadataInfo Get(int index) + { + return ref _items[index]; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Instrumentation/ProbeRateLimiter.cs b/tracer/src/Datadog.Trace/Debugger/Instrumentation/ProbeRateLimiter.cs new file mode 100644 index 000000000..f9233be64 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Instrumentation/ProbeRateLimiter.cs @@ -0,0 +1,40 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Threading; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Instrumentation +{ + internal class ProbeRateLimiter + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(ProbeRateLimiter)); + private static object _globalInstanceLock = new(); + private static bool _globalInstanceInitialized; + private static ProbeRateLimiter _instance; + + public ProbeRateLimiter() + { + } + + internal bool IsLimitReached { get; private set; } + + public static ProbeRateLimiter Instance + { + get + { + return LazyInitializer.EnsureInitialized( + ref _instance, + ref _globalInstanceInitialized, + ref _globalInstanceLock); + } + } + + internal void UpdateLimitReached(bool value) + { + IsLimitReached = value; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/LineProbeResolver.cs b/tracer/src/Datadog.Trace/Debugger/LineProbeResolver.cs new file mode 100644 index 000000000..23c8f7852 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/LineProbeResolver.cs @@ -0,0 +1,177 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using Datadog.Trace.Debugger.Configurations; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Debugger.Models; +using Datadog.Trace.ExtensionMethods; +using Datadog.Trace.Logging; +using Datadog.Trace.Pdb; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; + +namespace Datadog.Trace.Debugger +{ + internal class LineProbeResolver : ILineProbeResolver + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly object _locker; + private readonly Dictionary _loadedAssemblies; + + private LineProbeResolver() + { + _locker = new object(); + _loadedAssemblies = new Dictionary(); + } + + public static LineProbeResolver Create() + { + return new LineProbeResolver(); + } + + private static IList GetDocumentsFromPDB(Assembly loadedAssembly) + { + try + { + if (loadedAssembly.IsDynamic || + loadedAssembly.ManifestModule.IsResource() || + string.IsNullOrWhiteSpace(loadedAssembly.Location) || + IsThirdPartyCode(loadedAssembly)) + { + return null; + } + + using var reader = DatadogPdbReader.CreatePdbReader(loadedAssembly); + if (reader != null) + { + return reader.GetDocuments(); + } + } + catch (Exception e) + { + Log.Warning(e, $"Failed to retrieve documents from PDB for {loadedAssembly.Location}"); + } + + return null; + } + + private static bool IsThirdPartyCode(Assembly loadedAssembly) + { + // This implementation is just a stub - we will need to replace it + // with a proper implementation in the future. + string[] thirdPartyStartsWith = { "Microsoft", "System" }; + + var assemblyName = loadedAssembly.GetName().Name; + return thirdPartyStartsWith.Any(t => assemblyName.StartsWith(t)); + } + + private static string GetReversePath(string documentFullPath) + { + var partsReverse = documentFullPath.Split(' ', Path.PathSeparator).Reverse(); + return string.Join(Path.PathSeparator.ToString(), partsReverse); + } + + private Trie GetSourceFilePathForAssembly(Assembly loadedAssembly) + { + if (_loadedAssemblies.TryGetValue(loadedAssembly, out var trie)) + { + return trie; + } + + return _loadedAssemblies[loadedAssembly] = CreateTrieForSourceFilePaths(loadedAssembly); + } + + private Trie CreateTrieForSourceFilePaths(Assembly loadedAssembly) + { + var documents = GetDocumentsFromPDB(loadedAssembly); + if (documents == null) + { + return null; // No PDB available or unsupported assembly + } + + var trie = new Trie(); + foreach (var symbolDocument in documents) + { + trie.Insert(GetReversePath(symbolDocument.URL)); + } + + return trie; + } + + private Assembly FindAssemblyContainingFile(string sourceFileFullPath) + { + lock (_locker) + { + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + var trie = GetSourceFilePathForAssembly(assembly); + + if (trie != null && trie.ContainsPrefix(GetReversePath(sourceFileFullPath))) + { + return assembly; + } + } + } + + return null; + } + + public LineProbeResolveResult TryResolveLineProbe(ProbeDefinition probe, out BoundLineProbeLocation location) + { + location = null; + var assembly = FindAssemblyContainingFile(probe.Where.SourceFile); + if (assembly == null) + { + var message = $"Could not find a source file location for probe {probe.Id}."; + Log.Information(message); + return new LineProbeResolveResult(LiveProbeResolveStatus.Unbound, message); + } + + using var pdbReader = DatadogPdbReader.CreatePdbReader(assembly); + if (pdbReader == null) + { + var message = $"Failed to read from PDB for probe ID {probe.Id}"; + Log.Information(message); + + return new LineProbeResolveResult(LiveProbeResolveStatus.Error, message); + } + + if (probe.Where.Lines?.Length != 1 || !int.TryParse(probe.Where.Lines[0], out var lineNum)) + { + var message = $"Failed to parse line number for Line Probe {probe.Id}. " + + $"The Lines collection contains {PrintContents(probe.Where.Lines)}."; + Log.Error(message); + + return new LineProbeResolveResult(LiveProbeResolveStatus.Error, message); + } + + var method = pdbReader.GetContainingMethodAndOffset(probe.Where.SourceFile, lineNum, column: 0, out var bytecodeOffset); + location = new BoundLineProbeLocation(probe, assembly.ManifestModule.ModuleVersionId, method.Token, bytecodeOffset, lineNum); + return new LineProbeResolveResult(LiveProbeResolveStatus.Bound); + + string PrintContents(T[] array) + { + const string separator = ", "; + return array == null ? "null" : $"[{string.Join(separator, array)}]"; + } + } + + public void OnDomainUnloaded() + { + lock (_locker) + { + foreach (var unloadedAssembly in AppDomain.CurrentDomain.GetAssemblies()) + { + _loadedAssemblies.Remove(unloadedAssembly); + } + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/LiveDebugger.cs b/tracer/src/Datadog.Trace/Debugger/LiveDebugger.cs new file mode 100644 index 000000000..c490a3649 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/LiveDebugger.cs @@ -0,0 +1,303 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.DiscoveryService; +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger.Configurations; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Debugger.Helpers; +using Datadog.Trace.Debugger.Models; +using Datadog.Trace.Debugger.PInvoke; +using Datadog.Trace.Debugger.ProbeStatuses; +using Datadog.Trace.Debugger.Sink; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger +{ + internal class LiveDebugger + { + private static readonly Lazy LazyInstance = new Lazy(Create, isThreadSafe: true); + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(LiveDebugger)); + + private readonly ImmutableDebuggerSettings _settings; + private readonly IDiscoveryService _discoveryService; + private readonly IConfigurationPoller _configurationPoller; + private readonly IDebuggerSink _debuggerSink; + private readonly ILineProbeResolver _lineProbeResolver; + private readonly List _unboundProbes; + private readonly IProbeStatusPoller _probeStatusPoller; + private readonly object _locker = new(); + + private LiveDebugger(ImmutableDebuggerSettings settings, IDiscoveryService discoveryService, IConfigurationPoller configurationPoller, ILineProbeResolver lineProbeResolver, IDebuggerSink debuggerSink, IProbeStatusPoller probeStatusPoller) + { + _settings = settings; + _discoveryService = discoveryService; + _configurationPoller = configurationPoller; + _lineProbeResolver = lineProbeResolver; + _debuggerSink = debuggerSink; + _probeStatusPoller = probeStatusPoller; + _unboundProbes = new List(); + } + + public static LiveDebugger Instance => LazyInstance.Value; + + private static LiveDebugger Create() + { + var source = GlobalSettings.CreateDefaultConfigurationSource(); + var settings = ImmutableDebuggerSettings.Create(DebuggerSettings.FromSource(source)); + if (!settings.Enabled) + { + return Create(settings, null, null, null, null, null); + } + + var apiFactory = DebuggerTransportStrategy.Get(settings.AgentUri); + IDiscoveryService discoveryService = DiscoveryService.Create(source, apiFactory); + + var probeConfigurationApi = ProbeConfigurationApiFactory.Create(settings, apiFactory, discoveryService); + var updater = ConfigurationUpdater.Create(settings); + IConfigurationPoller configurationPoller = ConfigurationPoller.Create(probeConfigurationApi, updater, settings); + + var snapshotStatusSink = SnapshotSink.Create(settings); + var probeStatusSink = ProbeStatusSink.Create(settings); + + var batchApi = BatchUploadApiFactory.Create(settings, apiFactory, discoveryService); + var batchUploader = BatchUploader.Create(batchApi); + var debuggerSink = DebuggerSink.Create(snapshotStatusSink, probeStatusSink, settings, batchUploader); + + var lineProbeResolver = LineProbeResolver.Create(); + var probeStatusPoller = ProbeStatusPoller.Create(settings, probeStatusSink); + + return Create(settings, discoveryService, configurationPoller, lineProbeResolver, debuggerSink, probeStatusPoller); + } + + // for tests + internal static LiveDebugger Create(ImmutableDebuggerSettings settings, IDiscoveryService discoveryService, IConfigurationPoller configurationPoller, ILineProbeResolver lineProbeResolver, IDebuggerSink debuggerSink, IProbeStatusPoller probeStatusPoller) + { + var debugger = new LiveDebugger(settings, discoveryService, configurationPoller, lineProbeResolver, debuggerSink, probeStatusPoller); + debugger.Initialize(); + + return debugger; + } + + private void Initialize() + { + if (!_settings.Enabled) + { + Log.Information("Live Debugger is disabled. To enable it, please set SIGNALFX_DEBUGGER_ENABLED environment variable to 'true'."); + return; + } + + if (_settings.TransportType != TracesTransportType.Default) + { + Log.Information("Live Debugger is not supported on UDS or named pipelines."); + return; + } + + Log.Information("Live Debugger initialization started"); + + Task.Run(() => InitializeAsync()); + + AppDomain.CurrentDomain.AssemblyLoad += (sender, args) => CheckUnboundProbes(); + AppDomain.CurrentDomain.DomainUnload += (sender, args) => _lineProbeResolver.OnDomainUnloaded(); + + Log.Information("Live Debugger initialization completed"); + } + + private async Task InitializeAsync() + { + try + { + var isDiscoverySuccessful = await _discoveryService.DiscoverAsync().ConfigureAwait(false); + var isProbeConfigurationSupported = isDiscoverySuccessful && !string.IsNullOrWhiteSpace(_discoveryService.ProbeConfigurationEndpoint); + if (_settings.ProbeMode == ProbeMode.Agent && !isProbeConfigurationSupported) + { + Log.Warning("You must upgrade datadog-agent in order to leverage the Live Debugger. All debugging features will be disabled."); + return; + } + + await StartAsync().ConfigureAwait(false); + } + catch (Exception e) + { + Log.Error(e, "Initializing Live Debugger failed."); + } + + Task StartAsync() + { + LifetimeManager.Instance.AddShutdownTask(OnShutdown); + + _probeStatusPoller.StartPolling(); + return Task.WhenAll(_configurationPoller.StartPollingAsync(), _debuggerSink.StartFlushingAsync()); + } + } + + private void OnShutdown() + { + _configurationPoller.Dispose(); + _debuggerSink.Dispose(); + _probeStatusPoller.Dispose(); + } + + internal void UpdateProbeInstrumentations(IReadOnlyList addedProbes, IReadOnlyList removedProbes) + { + lock (_locker) + { + if (addedProbes.Count == 0 && removedProbes.Count == 0) + { + return; + } + + Log.Information($"Live Debugger.InstrumentProbes: Request to instrument {addedProbes.Count} probes definitions and remove {removedProbes.Count} definitions"); + + var methodProbes = new List(); + var lineProbes = new List(); + foreach (var probe in addedProbes) + { + switch (GetProbeLocationType(probe)) + { + case ProbeLocationType.Line: + var lineProbeResult = _lineProbeResolver.TryResolveLineProbe(probe, out var location); + + var status = lineProbeResult.Status; + var message = lineProbeResult.Message; + + switch (status) + { + case LiveProbeResolveStatus.Bound: + lineProbes.Add(new NativeLineProbeDefinition(location.ProbeDefinition.Id, location.MVID, location.MethodToken, (int)(location.BytecodeOffset), location.LineNumber, location.ProbeDefinition.Where.SourceFile)); + break; + case LiveProbeResolveStatus.Unbound: + Log.Information(message); + _unboundProbes.Add(probe); + break; + case LiveProbeResolveStatus.Error: + Log.Error(message); + AddErrorProbeStatus(probe.Id, errorMessage: message); + break; + } + + break; + case ProbeLocationType.Method: + var nativeDefinition = new NativeMethodProbeDefinition(probe.Id, probe.Where.TypeName, probe.Where.MethodName, probe.Where.Signature?.Split(separator: ',')); + methodProbes.Add(nativeDefinition); + break; + case ProbeLocationType.Unrecognized: + break; + } + } + + var revertProbes = removedProbes.Select(probe => new NativeRemoveProbeRequest(probe.Id)); + RemoveUnboundProbes(removedProbes); + using var disposable = new DisposableEnumerable(methodProbes); + DebuggerNativeMethods.InstrumentProbes(methodProbes.ToArray(), lineProbes.ToArray(), revertProbes.ToArray()); + + _probeStatusPoller.AddProbes(addedProbes.Select(probe => probe.Id).ToArray()); + _probeStatusPoller.RemoveProbes(removedProbes.Select(probe => probe.Id).ToArray()); + + // This log is checked in integration test + Log.Information("Live Debugger.InstrumentProbes: Request to instrument probes definitions completed."); + } + } + + private ProbeLocationType GetProbeLocationType(ProbeDefinition probe) + { + if (!string.IsNullOrEmpty(probe.Where.MethodName)) + { + return ProbeLocationType.Method; + } + + if (!string.IsNullOrEmpty(probe.Where.SourceFile)) + { + return ProbeLocationType.Line; + } + + return ProbeLocationType.Unrecognized; + } + + private void RemoveUnboundProbes(IReadOnlyList removedDefinitions) + { + lock (_locker) + { + foreach (var probeDefinition in removedDefinitions) + { + _unboundProbes.RemoveAll(m => m.Id == probeDefinition.Id); + } + } + } + + private void CheckUnboundProbes() + { + // A new assembly was loaded, so re-examine whether the probe can now be resolved. + lock (_locker) + { + if (_unboundProbes.Count == 0) + { + return; + } + + foreach (var unboundProbe in _unboundProbes) + { + var result = _lineProbeResolver.TryResolveLineProbe(unboundProbe, out var bytecodeLocation); + if (result.Status == LiveProbeResolveStatus.Bound) + { + // TODO: Install the line probe. + } + } + } + } + + internal void AddSnapshot(string snapshot) + { + _debuggerSink.AddSnapshot(snapshot); + } + + internal void AddReceivedProbeStatus(string probeId) + { + _debuggerSink.AddReceivedProbeStatus(probeId); + } + + internal void AddInstalledProbeStatus(string probeId) + { + _debuggerSink.AddInstalledProbeStatus(probeId); + } + + internal void AddBlockedProbeStatus(string probeId) + { + _debuggerSink.AddBlockedProbeStatus(probeId); + } + + internal void AddErrorProbeStatus(string probeId, Exception exception = null, string errorMessage = null) + { + _debuggerSink.AddErrorProbeStatus(probeId, exception, errorMessage); + } + } +} + +internal record BoundLineProbeLocation +{ + public BoundLineProbeLocation(ProbeDefinition probe, Guid mvid, int methodToken, int? bytecodeOffset, int lineNumber) + { + ProbeDefinition = probe; + MVID = mvid; + MethodToken = methodToken; + BytecodeOffset = bytecodeOffset; + LineNumber = lineNumber; + } + + public ProbeDefinition ProbeDefinition { get; set; } + + public Guid MVID { get; set; } + + public int MethodToken { get; set; } + + public int? BytecodeOffset { get; set; } + + public int LineNumber { get; set; } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Models/LineProbeResolveResult.cs b/tracer/src/Datadog.Trace/Debugger/Models/LineProbeResolveResult.cs new file mode 100644 index 000000000..ba5db5e43 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Models/LineProbeResolveResult.cs @@ -0,0 +1,20 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Models +{ + internal record LineProbeResolveResult + { + public LineProbeResolveResult(LiveProbeResolveStatus status, string message = null) + { + Status = status; + Message = message; + } + + public LiveProbeResolveStatus Status { get; } + + public string Message { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Models/LiveProbeResolveStatus.cs b/tracer/src/Datadog.Trace/Debugger/Models/LiveProbeResolveStatus.cs new file mode 100644 index 000000000..3dc595094 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Models/LiveProbeResolveStatus.cs @@ -0,0 +1,26 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Models +{ + internal enum LiveProbeResolveStatus + { + /// + /// The Line Probe was successfully bound to a bytecode offset. + /// + Bound, + + /// + /// The Line Probe location did not map out to any loaded module. + /// The probe will be re-examined whenever a new module is loaded. + /// + Unbound, + + /// + /// The probe could not be resolved due to an error. + /// + Error + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Models/ProbeSnapshot.cs b/tracer/src/Datadog.Trace/Debugger/Models/ProbeSnapshot.cs new file mode 100644 index 000000000..0fe198597 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Models/ProbeSnapshot.cs @@ -0,0 +1,194 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; + +namespace Datadog.Trace.Debugger +{ + internal record struct ProbeSnapshot + { + public ProbeMethodCapture Captures { get; set; } + + public ProbeInfo Probe { get; set; } + + public ThreadInfo Thread { get; set; } + + public StackInfo[] Stack { get; set; } + + public string Id { get; set; } + + public long Timestamp { get; set; } + + public string Duration { get; set; } + + public string Language { get; set; } + } + + internal record struct ProbeInfo + { + public string Id { get; set; } + + public ProbeLocation Location { get; set; } + } + + internal record struct ThreadInfo + { + public int Id { get; set; } + + public string Name { get; set; } + } + + internal record struct StackInfo + { + public string Function { get; set; } + + public string FileName { get; set; } + + public int LineNumber { get; set; } + } + + internal record struct ProbeLocation + { + public string Method { get; set; } + + public string Type { get; set; } + + public string File { get; set; } + + public string[] Lines { get; set; } + } + + internal record struct ProbeMethodCapture + { + public CapturedContext Entry { get; set; } + + public CapturedContext Return { get; set; } + + public CapturedLines Lines { get; set; } + } + + internal record struct Throwable + { + public string Message { get; set; } + + public string Type { get; set; } + + public StackInfo[] Stacktrace { get; set; } + } + + internal record CapturedValue : IComparable + { + [JsonExtensionData] + private IDictionary _additionalData = new Dictionary(); + + public string Name { get; set; } + + public string Type { get; set; } + + public string Value { get; set; } + + [JsonIgnore] + public CapturedValue[] Fields { get; set; } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + if (_additionalData.TryGetValue("fields", out var fields)) + { + Fields = fields.Children().Select(c => + { + var jsonObject = c.Children().FirstOrDefault(); + if (jsonObject == null) + { + return default; + } + + if (jsonObject.Type == JTokenType.String) + { + return new CapturedValue { Name = c.Name, Value = jsonObject.ToString() }; + } + + var co = jsonObject.ToObject(); + co.Name = c.Name; + return co; + }).ToArray(); + } + } + + public int CompareTo(CapturedValue other) + { + if (ReferenceEquals(this, other)) + { + return 0; + } + + if (ReferenceEquals(null, other)) + { + return 1; + } + + return string.Compare(Name, other.Name, StringComparison.Ordinal); + } + } + + internal record CapturedLines + { + [JsonExtensionData] + private IDictionary _additionalData = new Dictionary(); + + public CapturedContext Captured { get; set; } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + Captured = _additionalData.FirstOrDefault().Value.ToObject(); + } + } + + internal record CapturedContext + { + [JsonExtensionData] + private IDictionary _additionalData = new Dictionary(); + + public CapturedValue Fields { get; set; } + + [JsonIgnore] + public CapturedValue[] Arguments { get; set; } + + [JsonIgnore] + public CapturedValue[] Locals { get; set; } + + public Throwable Throwable { get; set; } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + if (_additionalData.TryGetValue("arguments", out var arguments)) + { + Arguments = arguments.Children().Select(c => + { + var co = c.Children().First().ToObject(); + co.Name = c.Name; + return co; + }).ToArray(); + } + + if (_additionalData.TryGetValue("locals", out var locals)) + { + Locals = locals.Children().Select(c => + { + var co = c.Children().First().ToObject(); + co.Name = c.Name; + return co; + }).ToArray(); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Models/Snapshot.cs b/tracer/src/Datadog.Trace/Debugger/Models/Snapshot.cs new file mode 100644 index 000000000..77c617eee --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Models/Snapshot.cs @@ -0,0 +1,46 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger +{ + internal record struct Snapshot + { + public DebuggerSnapshot Debugger { get; set; } + + public LoggerInfo Logger { get; set; } + + public int? Version { get; set; } + + public string Service { get; set; } + + public string DDSource { get; set; } + + public string DDTags { get; set; } + + public string TraceId { get; set; } + + public string SpanId { get; set; } + + public string Message { get; set; } + } + + internal record struct LoggerInfo + { + public int ThreadId { get; set; } + + public string ThreadName { get; set; } + + public string Version { get; set; } + + public string Name { get; set; } + + public string Method { get; set; } + } + + internal record struct DebuggerSnapshot + { + public ProbeSnapshot Snapshot { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/DebuggerNativeMethods.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/DebuggerNativeMethods.cs new file mode 100644 index 000000000..068e1e0b2 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/DebuggerNativeMethods.cs @@ -0,0 +1,91 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Runtime.InteropServices; +using Datadog.Trace.Debugger.ProbeStatuses; + +namespace Datadog.Trace.Debugger.PInvoke +{ + internal static class DebuggerNativeMethods + { + public static void InstrumentProbes(NativeMethodProbeDefinition[] methodProbes, NativeLineProbeDefinition[] lineProbes, NativeRemoveProbeRequest[] revertProbes) + { + if (FrameworkDescription.Instance.IsWindows()) + { + Windows.InstrumentProbes(methodProbes, methodProbes.Length, lineProbes, lineProbes.Length, revertProbes, revertProbes.Length); + } + else + { + NonWindows.InstrumentProbes(methodProbes, methodProbes.Length, lineProbes, lineProbes.Length, revertProbes, revertProbes.Length); + } + } + + public static ProbeStatus[] GetProbesStatuses(string[] probeIds) + { + if (probeIds is null || probeIds.Length == 0) + { + return Array.Empty(); + } + + var probesStatuses = new NativeProbeStatus[probeIds.Length]; + int probesLength = FrameworkDescription.Instance.IsWindows() ? + Windows.GetProbesStatuses(probeIds, probeIds.Length, probesStatuses) : + NonWindows.GetProbesStatuses(probeIds, probeIds.Length, probesStatuses); + + if (probesLength == 0) + { + return Array.Empty(); + } + + return probesStatuses.Take(probesLength) + .Select( + nativeProbeStatus => + new ProbeStatus( + Marshal.PtrToStringUni(nativeProbeStatus.ProbeId), nativeProbeStatus.Status)) + .ToArray(); + } + + // the "dll" extension is required on .NET Framework + // and optional on .NET Core + private static partial class Windows + { + [DllImport("SignalFx.Tracing.ClrProfiler.Native.dll")] + public static extern void InstrumentProbes( + [In] NativeMethodProbeDefinition[] methodProbes, + int methodProbesLength, + [In] NativeLineProbeDefinition[] lineProbes, + int lineProbesLength, + [In] NativeRemoveProbeRequest[] revertProbes, + int revertProbesLength); + + [DllImport("SignalFx.Tracing.ClrProfiler.Native.dll", CharSet = CharSet.Unicode)] + public static extern int GetProbesStatuses( + [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] probeIds, + int probeIdsLength, + [In, Out] NativeProbeStatus[] probeStatuses); + } + + // assume .NET Core if not running on Windows + private static partial class NonWindows + { + [DllImport("SignalFx.Tracing.ClrProfiler.Native")] + public static extern void InstrumentProbes( + [In] NativeMethodProbeDefinition[] methodProbes, + int methodProbesLength, + [In] NativeLineProbeDefinition[] lineProbes, + int lineProbesLength, + [In] NativeRemoveProbeRequest[] revertProbes, + int revertProbesLength); + + [DllImport("SignalFx.Tracing.ClrProfiler.Native")] + public static extern int GetProbesStatuses( + [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] probeIds, + int probeIdsLength, + [In, Out] NativeProbeStatus[] probeStatuses); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeLineProbeDefinition.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeLineProbeDefinition.cs new file mode 100644 index 000000000..11c75a164 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeLineProbeDefinition.cs @@ -0,0 +1,44 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Runtime.InteropServices; + +namespace Datadog.Trace.Debugger.PInvoke +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct NativeLineProbeDefinition + { + [MarshalAs(UnmanagedType.LPWStr)] + public string ProbeId; + + public Guid MVID; + + public int MethodToken; + + public int BytecodeOffset; + + public int LineNumber; + + [MarshalAs(UnmanagedType.LPWStr)] + public string ProbeFilePath; + + public NativeLineProbeDefinition( + string probeId, + Guid mvid, + int methodToken, + int bytecodeOffset, + int lineNumber, + string probeFilePath) + { + ProbeId = probeId; + MVID = mvid; + MethodToken = methodToken; + BytecodeOffset = bytecodeOffset; + LineNumber = lineNumber; + ProbeFilePath = probeFilePath; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeMethodProbeDefinition.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeMethodProbeDefinition.cs new file mode 100644 index 000000000..e5966b205 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeMethodProbeDefinition.cs @@ -0,0 +1,63 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Runtime.InteropServices; + +namespace Datadog.Trace.Debugger.PInvoke +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct NativeMethodProbeDefinition : IDisposable + { + [MarshalAs(UnmanagedType.LPWStr)] + public string ProbeId; + + [MarshalAs(UnmanagedType.LPWStr)] + public string TargetType; + + [MarshalAs(UnmanagedType.LPWStr)] + public string TargetMethod; + + public IntPtr TargetParameterTypes; + + public ushort TargetSignatureTypesLength; + + public NativeMethodProbeDefinition( + string probeId, + string targetTypeFullName, + string targetMethodName, + string[] targetParameterTypesFullName) + { + ProbeId = probeId; + TargetType = targetTypeFullName; + TargetMethod = targetMethodName; + TargetParameterTypes = IntPtr.Zero; + if (targetParameterTypesFullName?.Length > 0) + { + TargetParameterTypes = Marshal.AllocHGlobal(targetParameterTypesFullName.Length * Marshal.SizeOf(typeof(IntPtr))); + var ptr = TargetParameterTypes; + for (var i = 0; i < targetParameterTypesFullName.Length; i++) + { + Marshal.WriteIntPtr(ptr, Marshal.StringToHGlobalUni(targetParameterTypesFullName[i])); + ptr += Marshal.SizeOf(typeof(IntPtr)); + } + } + + TargetSignatureTypesLength = (ushort)(targetParameterTypesFullName?.Length ?? 0); + } + + public void Dispose() + { + var ptr = TargetParameterTypes; + for (var i = 0; i < TargetSignatureTypesLength; i++) + { + Marshal.FreeHGlobal(Marshal.ReadIntPtr(ptr)); + ptr += Marshal.SizeOf(typeof(IntPtr)); + } + + Marshal.FreeHGlobal(TargetParameterTypes); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeProbeStatus.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeProbeStatus.cs new file mode 100644 index 000000000..905a189b1 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeProbeStatus.cs @@ -0,0 +1,18 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Runtime.InteropServices; +using Datadog.Trace.Debugger.Sink.Models; + +namespace Datadog.Trace.Debugger.PInvoke +{ + [StructLayout(LayoutKind.Sequential)] + internal struct NativeProbeStatus + { + public IntPtr ProbeId; + public Status Status; + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeRemoveProbeRequest.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeRemoveProbeRequest.cs new file mode 100644 index 000000000..d8760e2ba --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/NativeRemoveProbeRequest.cs @@ -0,0 +1,22 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Runtime.InteropServices; + +namespace Datadog.Trace.Debugger.PInvoke +{ + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct NativeRemoveProbeRequest + { + [MarshalAs(UnmanagedType.LPWStr)] + public string ProbeId; + + public NativeRemoveProbeRequest( + string probeId) + { + ProbeId = probeId; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/PInvoke/ProbeStatus.cs b/tracer/src/Datadog.Trace/Debugger/PInvoke/ProbeStatus.cs new file mode 100644 index 000000000..f4af5dc0a --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/PInvoke/ProbeStatus.cs @@ -0,0 +1,24 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Runtime.InteropServices; +using Datadog.Trace.Debugger.Sink.Models; + +namespace Datadog.Trace.Debugger.PInvoke +{ + internal record ProbeStatus + { + public ProbeStatus(string probeId, Status status) + { + ProbeId = probeId; + Status = status; + } + + public string ProbeId { get; } + + public Status Status { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ProbeLocationType.cs b/tracer/src/Datadog.Trace/Debugger/ProbeLocationType.cs new file mode 100644 index 000000000..d7eb5813a --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ProbeLocationType.cs @@ -0,0 +1,14 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger +{ + internal enum ProbeLocationType + { + Line, + Method, + Unrecognized + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ProbeMode.cs b/tracer/src/Datadog.Trace/Debugger/ProbeMode.cs new file mode 100644 index 000000000..9b882975a --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ProbeMode.cs @@ -0,0 +1,20 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger +{ + internal enum ProbeMode + { + /// + /// Read the probe configuration from datadog-agent via Remote Configuration Management. + /// + Agent, + + /// + /// Read the probe configuration from a local file on disk. Useful for local development and testing scenarios. + /// + File + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/IProbeStatusPoller.cs b/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/IProbeStatusPoller.cs new file mode 100644 index 000000000..79ef728c0 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/IProbeStatusPoller.cs @@ -0,0 +1,22 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Datadog.Trace.Debugger.ProbeStatuses +{ + internal interface IProbeStatusPoller : IDisposable + { + void StartPolling(); + + void AddProbes(string[] newProbes); + + void RemoveProbes(string[] newProbes); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/ProbeStatusPoller.cs b/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/ProbeStatusPoller.cs new file mode 100644 index 000000000..3c55186e1 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/ProbeStatuses/ProbeStatusPoller.cs @@ -0,0 +1,118 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using Datadog.Trace.Debugger.PInvoke; +using Datadog.Trace.Debugger.Sink; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.ProbeStatuses +{ + internal class ProbeStatusPoller : IProbeStatusPoller + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(ProbeStatusPoller)); + + private readonly ProbeStatusSink _probeStatusSink; + private readonly TimeSpan _period; + private readonly HashSet _probes = new(); + private readonly object _locker = new object(); + private Timer _pollerTimer; + private bool _isPolling; + + private ProbeStatusPoller(ProbeStatusSink probeStatusSink, TimeSpan period) + { + _probeStatusSink = probeStatusSink; + _period = period; + } + + internal static ProbeStatusPoller Create(ImmutableDebuggerSettings settings, ProbeStatusSink probeStatusSink) + { + return new ProbeStatusPoller(probeStatusSink, TimeSpan.FromSeconds(settings.DiagnosticsIntervalSeconds)); + } + + private void PollerCallback(object state) + { + _pollerTimer?.Change(Timeout.Infinite, Timeout.Infinite); + try + { + OnProbeStatusesPoll(); + } + catch (Exception ex) + { + Log.Error(ex, "Polling probe status has failed."); + } + finally + { + _pollerTimer?.Change(_period, _period); + } + } + + private void OnProbeStatusesPoll() + { + lock (_locker) + { + if (_probes.Count == 0) + { + return; + } + + var probeStatuses = DebuggerNativeMethods.GetProbesStatuses(_probes.ToArray()); + + foreach (var probeStatus in probeStatuses) + { + _probeStatusSink.AddProbeStatus(probeStatus.ProbeId, probeStatus.Status); + } + } + } + + public void StartPolling() + { + if (_isPolling) + { + return; + } + + lock (_locker) + { + if (_isPolling) + { + return; + } + + _pollerTimer = new Timer(PollerCallback, state: null, dueTime: TimeSpan.Zero, _period); + _isPolling = true; + } + } + + public void AddProbes(string[] newProbes) + { + lock (_locker) + { + _probes.UnionWith(newProbes); + } + } + + public void RemoveProbes(string[] removedProbes) + { + lock (_locker) + { + _probes.ExceptWith(removedProbes); + + foreach (var rmProbe in removedProbes) + { + _probeStatusSink.Remove(rmProbe); + } + } + } + + public void Dispose() + { + _pollerTimer?.Dispose(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/AgentBatchUploadApi.cs b/tracer/src/Datadog.Trace/Debugger/Sink/AgentBatchUploadApi.cs new file mode 100644 index 000000000..0acc25e36 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/AgentBatchUploadApi.cs @@ -0,0 +1,82 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.DiscoveryService; +using Datadog.Trace.Agent.Transports; +using Datadog.Trace.Debugger.Helpers; +using Datadog.Trace.Logging; +using Datadog.Trace.Util; + +namespace Datadog.Trace.Debugger.Sink +{ + internal class AgentBatchUploadApi : IBatchUploadApi + { + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly IApiRequestFactory _apiRequestFactory; + private readonly IDiscoveryService _discoveryService; + private readonly string _targetPath; + private string _environment; + private string _version; + private Uri _uri; + + private AgentBatchUploadApi(IApiRequestFactory apiRequestFactory, IDiscoveryService discoveryService, string targetPath, string environment, string version) + { + _version = version; + _environment = environment; + _apiRequestFactory = apiRequestFactory; + _discoveryService = discoveryService; + _targetPath = targetPath; + } + + public static AgentBatchUploadApi Create(ImmutableDebuggerSettings settings, IApiRequestFactory apiRequestFactory, IDiscoveryService discoveryService) + { + return new AgentBatchUploadApi(apiRequestFactory, discoveryService, settings.SnapshotsPath, settings.Environment, settings.ServiceVersion); + } + + public async Task SendBatchAsync(ArraySegment snapshots) + { + var tags = new Dictionary { { "env", _environment }, { "version", _version }, { "agent_version", _discoveryService.AgentVersion }, { "debugger_version", TracerConstants.AssemblyVersion } }; + _uri ??= new Uri($"{_targetPath}/{_discoveryService.DebuggerEndpoint}{ToDDTagsQueryString(tags)}"); + + var request = _apiRequestFactory.Create(_uri); + using var response = await request.PostAsync(snapshots, MimeTypes.Json).ConfigureAwait(false); + + if (response.StatusCode is not (>= 200 and <= 299)) + { + var content = await response.ReadAsStringAsync().ConfigureAwait(false); + Log.Warning("Failed to upload snapshot with status code {StatusCode} and message: {ResponseContent}", response.StatusCode, content); + return false; + } + + return true; + } + + private string ToDDTagsQueryString(IDictionary keyValues) + { + if (keyValues.Count == 0) + { + return string.Empty; + } + + var sb = StringBuilderCache.Acquire(StringBuilderCache.MaxBuilderSize); + sb.Append("?ddtags="); + foreach (var keyValue in keyValues) + { + sb.Append(keyValue.Key); + sb.Append(':'); + sb.Append(keyValue.Value ?? "null"); + sb.Append(','); + } + + sb.Remove(sb.Length - 1, 1); + return StringBuilderCache.GetStringAndRelease(sb); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploadApiFactory.cs b/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploadApiFactory.cs new file mode 100644 index 000000000..82934a144 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploadApiFactory.cs @@ -0,0 +1,18 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Agent; +using Datadog.Trace.Agent.DiscoveryService; + +namespace Datadog.Trace.Debugger.Sink +{ + internal static class BatchUploadApiFactory + { + public static IBatchUploadApi Create(ImmutableDebuggerSettings settings, IApiRequestFactory apiRequestFactory, IDiscoveryService discoveryService) + { + return AgentBatchUploadApi.Create(settings, apiRequestFactory, discoveryService); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploader.cs b/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploader.cs new file mode 100644 index 000000000..17a6d40c8 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/BatchUploader.cs @@ -0,0 +1,120 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.Debugger.Sink +{ + internal class BatchUploader + { + private const int MaxSinglePayloadSize = 1 * 1024 * 1024; + private const int MaxTotalPayloadSize = 5 * 1024 * 1024; + private const int InitialBuilderSizeBytes = 10 * 1024; + internal const int InitialPayloadSizeBytes = 100 * 1024; + + private const int InitialClosingBracketsLength = 2; + private const int SeparatorLength = 1; + + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + + private readonly IBatchUploadApi _api; + private readonly StringBuilder _sb; + + private byte[] _serializedPayloads = new byte[InitialPayloadSizeBytes]; + + private BatchUploader(IBatchUploadApi api) + { + _api = api; + _sb = new StringBuilder(InitialBuilderSizeBytes); + } + + public static BatchUploader Create(IBatchUploadApi api) + { + return new BatchUploader(api); + } + + public async Task Upload(IEnumerable payloads) + { + try + { + foreach (var batch in GetBatches(payloads)) + { + await _api.SendBatchAsync(batch).ConfigureAwait(false); + } + } + catch (Exception e) + { + Log.Error(e, "Failed to upload batch"); + } + finally + { + _sb.Clear(); + } + } + + private IEnumerable> GetBatches(IEnumerable payloads) + { + _sb.Clear(); + _sb.Append('['); + + var totalBatchSize = InitialClosingBracketsLength; + foreach (var payload in payloads) + { + var payloadSize = Encoding.UTF8.GetByteCount(payload); + if (payloadSize >= MaxSinglePayloadSize) + { + Log.Warning("Big payload detected, skipping"); + continue; + } + + if (totalBatchSize + payloadSize > MaxTotalPayloadSize) + { + yield return FinalizeBatch(totalBatchSize); + + totalBatchSize = InitialClosingBracketsLength; + _sb.Clear(); + _sb.Append('['); + } + + _sb.Append(payload); + _sb.Append(','); + totalBatchSize += payloadSize + SeparatorLength; + } + + var noPayloadsAdded = _sb.Length == 1; + if (noPayloadsAdded) + { + yield break; + } + + yield return FinalizeBatch(totalBatchSize); + } + + private ArraySegment FinalizeBatch(int totalBatchSize) + { + OverwriteSeparator(); + + if (_serializedPayloads.Length < totalBatchSize) + { + Array.Resize(ref _serializedPayloads, totalBatchSize); + } + + var message = _sb.ToString(); + Encoding.UTF8.GetBytes(_sb.ToString(), 0, message.Length, _serializedPayloads, 0); + var finalizeBatch = new ArraySegment(_serializedPayloads, 0, totalBatchSize); + return finalizeBatch; + + void OverwriteSeparator() + { + _sb[_sb.Length - 1] = ']'; + totalBatchSize--; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/DebuggerSink.cs b/tracer/src/Datadog.Trace/Debugger/Sink/DebuggerSink.cs new file mode 100644 index 000000000..46d2f747c --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/DebuggerSink.cs @@ -0,0 +1,150 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Sink.Models; +using Datadog.Trace.Logging; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Sink +{ + internal class DebuggerSink : IDebuggerSink + { + private const double FreeCapacityLowerThreshold = 0.25; + private const double FreeCapacityUpperThreshold = 0.75; + + private const int MinFlushInterval = 100; + private const int MaxFlushInterval = 2000; + private const int InitialFlushInterval = 1000; + private const int Capacity = 1000; + + private const int StepSize = 200; + + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(DebuggerSink)); + + private readonly CancellationTokenSource _cancellationSource; + private readonly SnapshotSink _snapshotSink; + private readonly ProbeStatusSink _probeStatusSink; + private readonly int _uploadFlushInterval; + private readonly int _initialFlushInterval; + private readonly BatchUploader _batchUploader; + + private DebuggerSink(SnapshotSink snapshotSink, ProbeStatusSink probeStatusSink, BatchUploader batchUploader, int uploadFlushInterval, int initialFlushInterval) + { + _batchUploader = batchUploader; + _uploadFlushInterval = uploadFlushInterval; + _initialFlushInterval = initialFlushInterval; + + _probeStatusSink = probeStatusSink; + _snapshotSink = snapshotSink; + + _cancellationSource = new CancellationTokenSource(); + } + + public static DebuggerSink Create(SnapshotSink snapshotSink, ProbeStatusSink probeStatusSink, ImmutableDebuggerSettings settings, BatchUploader batchUploader) + { + var uploadInterval = settings.UploadFlushIntervalMilliseconds; + var initialInterval = + uploadInterval != 0 + ? Math.Max(MinFlushInterval, Math.Min(uploadInterval, MaxFlushInterval)) + : InitialFlushInterval; + + return new DebuggerSink(snapshotSink, probeStatusSink, batchUploader, uploadInterval, initialInterval); + } + + public async Task StartFlushingAsync() + { + while (!_cancellationSource.IsCancellationRequested) + { + var currentInterval = _initialFlushInterval; + try + { + var snapshots = _snapshotSink.GetSnapshots(); + if (snapshots.Count > 0) + { + await _batchUploader.Upload(snapshots).ConfigureAwait(continueOnCapturedContext: false); + } + + var diagnostics = _probeStatusSink.GetDiagnostics(); + if (diagnostics.Count > 0) + { + await _batchUploader.Upload(diagnostics.Select(JsonConvert.SerializeObject)).ConfigureAwait(continueOnCapturedContext: false); + } + } + catch (ThreadAbortException) + { + throw; + } + catch (Exception e) + { + Log.Error(e, "Failed to upload debugger snapshot and/or diagnostics."); + } + finally + { + currentInterval = ReconsiderFlushInterval(currentInterval); + await Delay(currentInterval).ConfigureAwait(false); + } + } + + async Task Delay(int delay) + { + if (_cancellationSource.IsCancellationRequested) + { + return; + } + + try + { + await Task.Delay(TimeSpan.FromMilliseconds(delay), _cancellationSource.Token).ConfigureAwait(false); + } + catch (TaskCanceledException) + { + // We are shutting down, so don't do anything about it + } + } + } + + private int ReconsiderFlushInterval(int currentInterval) + { + if (_uploadFlushInterval != 0) + { + return currentInterval; + } + + var remainingPercent = _snapshotSink.RemainingCapacity() * 1D / Capacity; + var newInterval = remainingPercent switch + { + <= FreeCapacityLowerThreshold => Math.Max(currentInterval - StepSize, MinFlushInterval), + >= FreeCapacityUpperThreshold => Math.Min(currentInterval + StepSize, MaxFlushInterval), + _ => currentInterval + }; + + if (newInterval != currentInterval) + { + Log.Debug($"Changing flush interval. Remaining available capacity in upload queue {remainingPercent * 100}%, new flush interval {newInterval}ms"); + } + + return newInterval; + } + + public void AddSnapshot(string snapshot) + { + _snapshotSink.Add(snapshot); + } + + public void AddProbeStatus(string probeId, Status status, Exception exception = null, string errorMessage = null) + { + _probeStatusSink.AddProbeStatus(probeId, status, exception, errorMessage); + } + + public void Dispose() + { + _cancellationSource.Cancel(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/IBatchUploadApi.cs b/tracer/src/Datadog.Trace/Debugger/Sink/IBatchUploadApi.cs new file mode 100644 index 000000000..2525b09e8 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/IBatchUploadApi.cs @@ -0,0 +1,15 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Threading.Tasks; + +namespace Datadog.Trace.Debugger.Sink +{ + internal interface IBatchUploadApi + { + Task SendBatchAsync(ArraySegment snapshots); + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/IDebuggerSink.cs b/tracer/src/Datadog.Trace/Debugger/Sink/IDebuggerSink.cs new file mode 100644 index 000000000..2f1478bac --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/IDebuggerSink.cs @@ -0,0 +1,43 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Sink.Models; + +namespace Datadog.Trace.Debugger.Sink +{ + internal interface IDebuggerSink : IDisposable + { + Task StartFlushingAsync(); + + void AddSnapshot(string snapshot); + + void AddProbeStatus(string probeId, Status status, Exception exception = null, string errorMessage = null); + } + + internal static class DebuggerSinkExtensions + { + internal static void AddReceivedProbeStatus(this IDebuggerSink debuggerSink, string probeId) + { + debuggerSink.AddProbeStatus(probeId, Status.RECEIVED); + } + + internal static void AddInstalledProbeStatus(this IDebuggerSink debuggerSink, string probeId) + { + debuggerSink.AddProbeStatus(probeId, Status.INSTALLED); + } + + internal static void AddBlockedProbeStatus(this IDebuggerSink debuggerSink, string probeId) + { + debuggerSink.AddProbeStatus(probeId, Status.BLOCKED); + } + + internal static void AddErrorProbeStatus(this IDebuggerSink debuggerSink, string probeId, Exception exception, string errorMessage) + { + debuggerSink.AddProbeStatus(probeId, Status.ERROR, exception, errorMessage); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/DebuggerDiagnostics.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/DebuggerDiagnostics.cs new file mode 100644 index 000000000..9ac73d55c --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/DebuggerDiagnostics.cs @@ -0,0 +1,22 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Converters; + +namespace Datadog.Trace.Debugger.Sink.Models +{ + internal record DebuggerDiagnostics + { + public DebuggerDiagnostics(Diagnostics diagnostics) + { + Diagnostics = diagnostics; + } + + [JsonProperty("diagnostics")] + public Diagnostics Diagnostics { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/Diagnostics.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/Diagnostics.cs new file mode 100644 index 000000000..acbe34c73 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/Diagnostics.cs @@ -0,0 +1,48 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Converters; + +namespace Datadog.Trace.Debugger.Sink.Models +{ + internal record Diagnostics + { + public Diagnostics(string probeId, Status status) + { + ProbeId = probeId; + Status = status; + } + + [JsonProperty("probeId")] + public string ProbeId { get; } + + [JsonProperty("status")] + public Status Status { get; } + + public ProbeException Exception { get; private set; } + + public void SetException(Exception exception, string errorMessage) + { + Exception = new ProbeException(); + + if (exception != null) + { + Exception = new ProbeException() + { + Type = exception.GetType().Name, + Message = exception.Message, + StackTrace = exception.StackTrace + }; + } + + if (!string.IsNullOrWhiteSpace(errorMessage)) + { + Exception.Message = errorMessage; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeException.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeException.cs new file mode 100644 index 000000000..06f7b4a4f --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeException.cs @@ -0,0 +1,16 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +namespace Datadog.Trace.Debugger.Sink.Models +{ + internal record ProbeException + { + public string Type { get; set; } + + public string Message { get; set; } + + public string StackTrace { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeStatus.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeStatus.cs new file mode 100644 index 000000000..0462647f4 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/ProbeStatus.cs @@ -0,0 +1,50 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Sink.Models +{ + internal record ProbeStatus + { + public ProbeStatus(string service, string probeId, Status status, Exception exception = null, string errorMessage = null) + { + Message = GetMessage(); + Service = service; + + DebuggerDiagnostics = new DebuggerDiagnostics(new Diagnostics(probeId, status)); + + if (status == Status.ERROR) + { + DebuggerDiagnostics.Diagnostics.SetException(exception, errorMessage); + } + + string GetMessage() + { + return status switch + { + Status.RECEIVED => $"Received probe {probeId}.", + Status.INSTALLED => $"Installed probe {probeId}.", + Status.BLOCKED => $"Blocked probe {probeId}.", + Status.ERROR => $"Error installing probe {probeId}.", + _ => throw new ArgumentOutOfRangeException(nameof(status), $"Not expected status value: {status}"), + }; + } + } + + [JsonProperty("ddsource")] + public string DdSource { get; } = "dd_debugger"; + + [JsonProperty("service")] + public string Service { get; } + + [JsonProperty("message")] + public string Message { get; } + + [JsonProperty("debugger")] + public DebuggerDiagnostics DebuggerDiagnostics { get; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/Status.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/Status.cs new file mode 100644 index 000000000..8faea2b08 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/Status.cs @@ -0,0 +1,19 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Converters; + +namespace Datadog.Trace.Debugger.Sink.Models +{ + [JsonConverter(typeof(StringEnumConverter))] + internal enum Status + { + RECEIVED, + INSTALLED, + BLOCKED, + ERROR + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/Models/TimedMessage.cs b/tracer/src/Datadog.Trace/Debugger/Sink/Models/TimedMessage.cs new file mode 100644 index 000000000..8aa5b9972 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/Models/TimedMessage.cs @@ -0,0 +1,16 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.Debugger.Sink.Models +{ + internal class TimedMessage + { + public DateTime LastEmit { get; set; } + + public ProbeStatus Message { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/ProbeStatusSink.cs b/tracer/src/Datadog.Trace/Debugger/Sink/ProbeStatusSink.cs new file mode 100644 index 000000000..781d4dd27 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/ProbeStatusSink.cs @@ -0,0 +1,160 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using Datadog.Trace.Debugger.Sink.Models; +using Datadog.Trace.Util; + +namespace Datadog.Trace.Debugger.Sink +{ + internal class ProbeStatusSink + { + private const int QueueLimit = 1000; + private readonly ConcurrentDictionary _diagnostics; + + private readonly string _service; + private readonly int _batchSize; + private readonly TimeSpan _interval; + + private BoundedConcurrentQueue _queue; + + private ProbeStatusSink(string service, int batchSize, TimeSpan interval) + { + _service = service; + _batchSize = batchSize; + _interval = interval; + + _diagnostics = new ConcurrentDictionary(); + _queue = new BoundedConcurrentQueue(QueueLimit); + } + + public static ProbeStatusSink Create(ImmutableDebuggerSettings settings) + { + return new ProbeStatusSink(settings.ServiceName, settings.UploadBatchSize, TimeSpan.FromSeconds(settings.DiagnosticsIntervalSeconds)); + } + + internal void AddReceived(string probeId) + { + AddProbeStatus(probeId, Status.RECEIVED); + } + + internal void AddInstalled(string probeId) + { + AddProbeStatus(probeId, Status.INSTALLED); + } + + internal void AddBlocked(string probeId) + { + AddProbeStatus(probeId, Status.BLOCKED); + } + + internal void AddError(string probeId, Exception e) + { + AddProbeStatus(probeId, Status.ERROR, e); + } + + public void AddProbeStatus(string probeId, Status status, Exception exception = null, string errorMessage = null) + { + var shouldSkip = + _diagnostics.TryGetValue(probeId, out var current) && + !ShouldOverwrite(current.Message.DebuggerDiagnostics.Diagnostics.Status, status); + + if (shouldSkip) + { + return; + } + + var next = new ProbeStatus(_service, probeId, status, exception, errorMessage); + var timedMessage = new TimedMessage + { + LastEmit = Clock.UtcNow, + Message = next + }; + + _diagnostics.AddOrUpdate(probeId, timedMessage, (_, _) => (timedMessage)); + Enqueue(next); + + bool ShouldOverwrite(Status currentStatus, Status nextStatus) + { + return nextStatus == Status.ERROR || currentStatus != nextStatus; + } + } + + private void Enqueue(ProbeStatus probe) + { + if (_queue.TryEnqueue(probe)) + { + return; + } + + if (_queue.Count <= _diagnostics.Count) + { + return; + } + + _queue = RecreateQueue(); + } + + private BoundedConcurrentQueue RecreateQueue() + { + var queue = new BoundedConcurrentQueue(QueueLimit); + var now = Clock.UtcNow; + foreach (var timedMessage in _diagnostics.Values) + { + timedMessage.LastEmit = now; + if (!queue.TryEnqueue(timedMessage.Message)) + { + break; + } + } + + return queue; + } + + public void Remove(string probeId) + { + _diagnostics.TryRemove(probeId, out _); + } + + public List GetDiagnostics() + { + var now = Clock.UtcNow; + foreach (var timedMessage in _diagnostics.Values) + { + if (!ShouldEmitAgain(timedMessage.LastEmit)) + { + continue; + } + + timedMessage.LastEmit = now; + Enqueue(timedMessage.Message); + } + + var probeStatusList = new List(); + var counter = 0; + while (!_queue.IsEmpty && counter <= _batchSize) + { + if (_queue.TryDequeue(out var probe)) + { + if (_diagnostics.ContainsKey(probe.DebuggerDiagnostics.Diagnostics.ProbeId)) + { + probeStatusList.Add(probe); + } + } + + counter++; + } + + return probeStatusList; + + bool ShouldEmitAgain(DateTime latEmit) + { + return now - latEmit >= _interval; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Sink/SnapshotSink.cs b/tracer/src/Datadog.Trace/Debugger/Sink/SnapshotSink.cs new file mode 100644 index 000000000..bde0ba949 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Sink/SnapshotSink.cs @@ -0,0 +1,56 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using Datadog.Trace.Util; + +namespace Datadog.Trace.Debugger.Sink +{ + internal class SnapshotSink + { + private const int DefaultQueueLimit = 1000; + + private readonly BoundedConcurrentQueue _queue; + private readonly int _batchSize; + + private SnapshotSink(int batchSize) + { + _batchSize = batchSize; + _queue = new BoundedConcurrentQueue(DefaultQueueLimit); + } + + public static SnapshotSink Create(ImmutableDebuggerSettings settings) + { + return new SnapshotSink(settings.UploadBatchSize); + } + + public void Add(string snapshot) + { + _queue.TryEnqueue(snapshot); + } + + public List GetSnapshots() + { + var snapshots = new List(); + var counter = 0; + while (!_queue.IsEmpty && counter < _batchSize) + { + if (_queue.TryDequeue(out var snapshot)) + { + snapshots.Add(snapshot); + } + + counter++; + } + + return snapshots; + } + + public int RemainingCapacity() + { + return DefaultQueueLimit - _queue.Count; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotCreator.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotCreator.cs new file mode 100644 index 000000000..996b8f5d8 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotCreator.cs @@ -0,0 +1,326 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +using Datadog.Trace.Util; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal readonly ref struct DebuggerSnapshotCreator + { + private const string LoggerVersion = "2"; + private const string DDSource = "dd_debugger"; + private const string UnknownValue = "Unknown"; + + private readonly JsonTextWriter _jsonWriter; + private readonly StringBuilder _jsonUnderlyingString; + + public DebuggerSnapshotCreator() + { + _jsonUnderlyingString = StringBuilderCache.Acquire(StringBuilderCache.MaxBuilderSize); + _jsonWriter = new JsonTextWriter(new StringWriter(_jsonUnderlyingString)); + + _jsonWriter.WriteStartObject(); + } + + internal void StartDebugger() + { + _jsonWriter.WritePropertyName("debugger"); + _jsonWriter.WriteStartObject(); + } + + internal void StartSnapshot() + { + _jsonWriter.WritePropertyName("snapshot"); + _jsonWriter.WriteStartObject(); + } + + internal void StartCaptures() + { + _jsonWriter.WritePropertyName("captures"); + _jsonWriter.WriteStartObject(); + } + + internal void StartEntry() + { + _jsonWriter.WritePropertyName("entry"); + _jsonWriter.WriteStartObject(); + } + + internal void StartLines(int lineNumber) + { + _jsonWriter.WritePropertyName("lines"); + _jsonWriter.WriteStartObject(); + + _jsonWriter.WritePropertyName(lineNumber.ToString()); + _jsonWriter.WriteStartObject(); + } + + internal void EndEntry(bool hasArgumentsOrLocals) + { + if (hasArgumentsOrLocals) + { + // end arguments or locals + _jsonWriter.WriteEndObject(); + } + + // end entry + _jsonWriter.WriteEndObject(); + } + + internal void StartReturn() + { + _jsonWriter.WritePropertyName("return"); + _jsonWriter.WriteStartObject(); + } + + internal void MethodProbeEndReturn(bool hasArgumentsOrLocals) + { + if (hasArgumentsOrLocals) + { + // end arguments or locals + _jsonWriter.WriteEndObject(); + } + + // end return + _jsonWriter.WriteEndObject(); + // end capture + _jsonWriter.WriteEndObject(); + } + + internal void LineProbeEndReturn() + { + // end arguments or locals + _jsonWriter.WriteEndObject(); + // end line number + _jsonWriter.WriteEndObject(); + // end lines + _jsonWriter.WriteEndObject(); + // end captures + _jsonWriter.WriteEndObject(); + } + + internal DebuggerSnapshotCreator EndSnapshot(TimeSpan? duration) + { + _jsonWriter.WritePropertyName("id"); + _jsonWriter.WriteValue(Guid.NewGuid()); + + _jsonWriter.WritePropertyName("timestamp"); + _jsonWriter.WriteValue(DateTimeOffset.Now.ToUnixTimeMilliseconds()); + + _jsonWriter.WritePropertyName("duration"); + _jsonWriter.WriteValue(duration.HasValue ? duration.Value.TotalMilliseconds : UnknownValue); + + _jsonWriter.WritePropertyName("language"); + _jsonWriter.WriteValue(TracerConstants.Language); + + _jsonWriter.WriteEndObject(); + return this; + } + + internal DebuggerSnapshotCreator EndDebugger() + { + _jsonWriter.WriteEndObject(); + return this; + } + + internal void CaptureInstance(TInstance instance, Type type) + { + DebuggerSnapshotSerializer.SerializeObjectFields(instance, type, _jsonWriter); + } + + internal void CaptureArgument(TArg argument, string name, bool isFirstArgument, bool shouldEndLocals) + { + StartLocalsOrArgs(isFirstArgument, shouldEndLocals, "arguments"); + DebuggerSnapshotSerializer.Serialize(argument, typeof(TArg), name, _jsonWriter); + } + + internal void CaptureLocal(TLocal local, string name, bool isFirstLocal) + { + StartLocalsOrArgs(isFirstLocal, false, "locals"); + DebuggerSnapshotSerializer.Serialize(local, typeof(TLocal), name, _jsonWriter); + } + + internal void CaptureException(Exception ex) + { + _jsonWriter.WritePropertyName("throwable"); + _jsonWriter.WriteStartObject(); + _jsonWriter.WritePropertyName("message"); + _jsonWriter.WriteValue(ex.Message); + _jsonWriter.WritePropertyName("type"); + _jsonWriter.WriteValue(ex.GetType().FullName); + _jsonWriter.WritePropertyName("stacktrace"); + _jsonWriter.WriteStartArray(); + AddFrames(new StackTrace(ex).GetFrames() ?? Array.Empty()); + _jsonWriter.WriteEndArray(); + _jsonWriter.WriteEndObject(); + } + + private void AddFrames(StackFrame[] frames) + { + foreach (var frame in frames) + { + _jsonWriter.WriteStartObject(); + _jsonWriter.WritePropertyName("function"); + var frameMethod = frame.GetMethod(); + _jsonWriter.WriteValue($"{frameMethod?.DeclaringType?.FullName ?? UnknownValue}.{frameMethod?.Name ?? UnknownValue}"); + + var fileName = frame.GetFileName(); + if (fileName != null) + { + _jsonWriter.WritePropertyName("fileName"); + _jsonWriter.WriteValue(frame.GetFileName()); + } + + _jsonWriter.WritePropertyName("lineNumber"); + _jsonWriter.WriteValue(frame.GetFileLineNumber()); + _jsonWriter.WriteEndObject(); + } + } + + internal DebuggerSnapshotCreator AddMethodProbeInfo(string probeId, string methodName, string type) + { + _jsonWriter.WritePropertyName("probe"); + _jsonWriter.WriteStartObject(); + + _jsonWriter.WritePropertyName("id"); + _jsonWriter.WriteValue(probeId); + + _jsonWriter.WritePropertyName("location"); + _jsonWriter.WriteStartObject(); + + _jsonWriter.WritePropertyName("method"); + _jsonWriter.WriteValue(methodName ?? UnknownValue); + + _jsonWriter.WritePropertyName("type"); + _jsonWriter.WriteValue(type ?? UnknownValue); + + _jsonWriter.WriteEndObject(); + _jsonWriter.WriteEndObject(); + + return this; + } + + internal DebuggerSnapshotCreator AddLineProbeInfo(string probeId, string probeFilePath, int lineNumber) + { + _jsonWriter.WritePropertyName("probe"); + _jsonWriter.WriteStartObject(); + + _jsonWriter.WritePropertyName("id"); + _jsonWriter.WriteValue(probeId); + + _jsonWriter.WritePropertyName("location"); + _jsonWriter.WriteStartObject(); + + _jsonWriter.WritePropertyName("file"); + _jsonWriter.WriteValue(probeFilePath.Replace('\\', '/')); + + _jsonWriter.WritePropertyName("lines"); + _jsonWriter.WriteStartArray(); + _jsonWriter.WriteValue(lineNumber); + _jsonWriter.WriteEndArray(); + + _jsonWriter.WriteEndObject(); + _jsonWriter.WriteEndObject(); + + return this; + } + + internal DebuggerSnapshotCreator AddStackInfo(StackFrame[] stackFrames) + { + _jsonWriter.WritePropertyName("stack"); + _jsonWriter.WriteStartArray(); + AddFrames(stackFrames); + _jsonWriter.WriteEndArray(); + + return this; + } + + internal DebuggerSnapshotCreator AddLoggerInfo(string name, string method) + { + _jsonWriter.WritePropertyName("logger"); + _jsonWriter.WriteStartObject(); + + var thread = Thread.CurrentThread; + _jsonWriter.WritePropertyName("thread_id"); + _jsonWriter.WriteValue(thread.ManagedThreadId); + + _jsonWriter.WritePropertyName("thread_name"); + _jsonWriter.WriteValue(thread.Name); + + _jsonWriter.WritePropertyName("version"); + _jsonWriter.WriteValue(LoggerVersion); + + _jsonWriter.WritePropertyName("name"); + _jsonWriter.WriteValue(name); + + _jsonWriter.WritePropertyName("method"); + _jsonWriter.WriteValue(method); + + _jsonWriter.WriteEndObject(); + + return this; + } + + internal DebuggerSnapshotCreator AddGeneralInfo(string service, string traceId, string spanId) + { + _jsonWriter.WritePropertyName("service"); + _jsonWriter.WriteValue(service ?? UnknownValue); + + _jsonWriter.WritePropertyName("ddsource"); + _jsonWriter.WriteValue(DDSource); + + // todo + _jsonWriter.WritePropertyName("ddtags"); + _jsonWriter.WriteValue(UnknownValue); + + _jsonWriter.WritePropertyName("dd.trace_id"); + _jsonWriter.WriteValue(traceId); + + _jsonWriter.WritePropertyName("dd.span_id"); + _jsonWriter.WriteValue(spanId); + + return this; + } + + public void AddMessage() + { + var snapshotObject = JsonConvert.DeserializeObject(_jsonUnderlyingString.ToString() + "}"); + var message = SnapshotSummary.FormatMessage(snapshotObject); + _jsonWriter.WritePropertyName("message"); + _jsonWriter.WriteValue(message); + } + + private void StartLocalsOrArgs(bool isFirstLocalOrArg, bool shouldEndObject, string name) + { + if (shouldEndObject) + { + _jsonWriter.WriteEndObject(); + } + + if (isFirstLocalOrArg) + { + _jsonWriter.WritePropertyName(name); + _jsonWriter.WriteStartObject(); + } + } + + internal string GetSnapshotJson() + { + _jsonWriter.WriteEndObject(); + return StringBuilderCache.GetStringAndRelease(_jsonUnderlyingString); + } + + internal void Dispose() + { + _jsonWriter?.Close(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotSerializer.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotSerializer.cs new file mode 100644 index 000000000..57ae7626d --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/DebuggerSnapshotSerializer.cs @@ -0,0 +1,386 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections; +using System.Reflection; +using System.Text.RegularExpressions; +using System.Threading; +using Datadog.Trace.Logging; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal static class DebuggerSnapshotSerializer + { + private const string ReachedTimeoutMessage = "Reached timeout"; + private const string ReachedNumberOfObjectsMessage = "Reached the maximum number of objects"; + private const string ReachedNumberOfItemsMessage = "Reached the maximum number of items"; + private const int MaximumNumberOfItemsInCollectionToCopy = 100; + private const int MaximumNumberOfFieldsToCopy = 1000; + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(typeof(DebuggerSnapshotSerializer)); + private static readonly ImmutableDebuggerSettings DebuggerSettings = ImmutableDebuggerSettings.Create(Debugger.DebuggerSettings.FromDefaultSource()); + private static readonly int MaximumDepthOfMembersToCopy = DebuggerSettings.MaximumDepthOfMembersOfMembersToCopy; + private static readonly int MillisecondsToCancel = DebuggerSettings.MaxSerializationTimeInMilliseconds; + + /// + /// Note: implemented recursively. We might want to consider an iterative approach for performance gain (Serialize takes part in the MethodDebuggerInvoker process). + /// + internal static void Serialize( + object source, + Type type, + string name, + JsonWriter jsonWriter) + { + var totalObjects = 0; + using var cts = CreateCancellationTimeout(); + SerializeInternal(source, type, jsonWriter, cts, currentDepth: 0, ref totalObjects, name, fieldsOnly: false); + } + + internal static void SerializeObjectFields( + object source, + Type type, + JsonWriter jsonWriter) + { + var totalObjects = 0; + using var cts = CreateCancellationTimeout(); + SerializeInternal(source, type, jsonWriter, cts, currentDepth: 0, ref totalObjects, variableName: null, fieldsOnly: true); + } + + private static bool SerializeInternal( + object source, + Type type, + JsonWriter jsonWriter, + CancellationTokenSource cts, + int currentDepth, + ref int totalObjects, + string variableName, + bool fieldsOnly) + { + try + { + if (source is IEnumerable enumerable && SupportedTypesService.IsSupportedCollection(source)) + { + jsonWriter.WritePropertyName(variableName); + jsonWriter.WriteStartObject(); + SerializeEnumerable(source, type, jsonWriter, enumerable, currentDepth, ref totalObjects, cts); + jsonWriter.WriteEndObject(); + return true; + } + + if (SupportedTypesService.IsDenied(type)) + { + jsonWriter.WritePropertyName(variableName); + jsonWriter.WriteStartObject(); + jsonWriter.WritePropertyName("type"); + jsonWriter.WriteValue(type.Name); + jsonWriter.WritePropertyName("value"); + jsonWriter.WriteValue("********"); + jsonWriter.WriteEndObject(); + return true; + } + + return SerializeObject( + source, + type, + jsonWriter, + cts, + currentDepth, + ref totalObjects, + variableName, + fieldsOnly); + } + catch (Exception e) + { + Log.Error(e.ToString()); + } + + return false; + } + + private static bool SerializeObject( + object source, + Type type, + JsonWriter jsonWriter, + CancellationTokenSource cts, + int currentDepth, + ref int totalObjects, + string variableName, + bool fieldsOnly) + { + totalObjects++; + if (!fieldsOnly) + { + WriteTypeAndValue(source, type, jsonWriter, variableName); + } + + try + { + SerializeFieldsInternal(source, type, jsonWriter, cts, currentDepth, ref totalObjects); + if (!fieldsOnly) + { + jsonWriter.WriteEndObject(); + } + + return true; + } + catch (OperationCanceledException) + { + WriteLimitReachedNotification(jsonWriter, variableName ?? type.Name, ReachedTimeoutMessage, !fieldsOnly); + } + catch (Exception e) + { + Log.Error(e.ToString()); + } + + return false; + } + + private static void WriteTypeAndValue( + object source, + Type type, + JsonWriter jsonWriter, + string variableName) + { + if (variableName != null) + { + jsonWriter.WritePropertyName(variableName); + } + + jsonWriter.WriteStartObject(); + jsonWriter.WritePropertyName("type"); + jsonWriter.WriteValue(type.Name); + jsonWriter.WritePropertyName("value"); + + if (source == null) + { + jsonWriter.WriteValue("null"); + } + else if (SupportedTypesService.IsSafeToCallToString(type)) + { + jsonWriter.WriteValue(source.ToString()); + } + else + { + jsonWriter.WriteValue(type.Name); + } + } + + private static void SerializeFieldsInternal( + object source, + Type type, + JsonWriter jsonWriter, + CancellationTokenSource cts, + int currentDepth, + ref int totalObjects) + { + if (currentDepth >= MaximumDepthOfMembersToCopy || SupportedTypesService.IsSafeToCallToString(type)) + { + jsonWriter.WritePropertyName("fields"); + jsonWriter.WriteNull(); + return; + } + + int index = 0; + var selector = SnapshotSerializerFieldsAndPropsSelector.CreateDeepClonerFieldsAndPropsSelector(type); + var fields = selector.GetFieldsAndProps(type, source, MaximumDepthOfMembersToCopy, MaximumNumberOfFieldsToCopy, cts); + + foreach (var field in fields) + { + var fieldOrPropertyName = GetAutoPropertyOrFieldName(field.Name); + + if (totalObjects >= MaximumNumberOfFieldsToCopy) + { + WriteLimitReachedNotification(jsonWriter, fieldOrPropertyName ?? type.Name, ReachedNumberOfObjectsMessage, index > 0); + return; + } + + if (!TryGetValue(field, source, out var value, out type)) + { + continue; + } + + if (index == 0) + { + jsonWriter.WritePropertyName("fields"); + jsonWriter.WriteStartObject(); + } + + index++; + var serialized = SerializeInternal( + value, + type, + jsonWriter, + cts, + currentDepth + 1, + ref totalObjects, + fieldOrPropertyName, + fieldsOnly: false); + + if (!serialized) + { + break; + } + } + + if (index > 0) + { + jsonWriter.WriteEndObject(); + } + else + { + jsonWriter.WritePropertyName("fields"); + jsonWriter.WriteNull(); + } + } + + private static void SerializeEnumerable( + object source, + Type type, + JsonWriter jsonWriter, + IEnumerable enumerable, + int currentDepth, + ref int totalObjects, + CancellationTokenSource cts) + { + try + { + if (source is ICollection collection) + { + jsonWriter.WritePropertyName("type"); + jsonWriter.WriteValue(type.Name); + jsonWriter.WritePropertyName("value"); + jsonWriter.WriteValue($"count: {collection.Count}"); + jsonWriter.WritePropertyName("Collection"); + jsonWriter.WriteStartArray(); + + var itemIndex = 0; + var enumerator = enumerable.GetEnumerator(); + + while (itemIndex < MaximumNumberOfItemsInCollectionToCopy && + totalObjects < MaximumNumberOfFieldsToCopy && + enumerator.MoveNext()) + { + cts.Token.ThrowIfCancellationRequested(); + if (enumerator.Current == null) + { + break; + } + + totalObjects++; + var serialized = SerializeInternal( + enumerator.Current, + enumerator.Current.GetType(), + jsonWriter, + cts, + currentDepth, + ref totalObjects, + variableName: null, + fieldsOnly: false); + + itemIndex++; + if (!serialized) + { + break; + } + } + + if (enumerator.MoveNext()) + { + jsonWriter.WriteStartObject(); + jsonWriter.WritePropertyName("type"); + jsonWriter.WriteValue("[...]"); + WriteLimitReachedNotification(jsonWriter, "value", ReachedNumberOfItemsMessage, true); + } + + totalObjects++; + jsonWriter.WriteEndArray(); + } + } + catch (OperationCanceledException) + { + WriteLimitReachedNotification(jsonWriter, type.Name, ReachedTimeoutMessage, false); + jsonWriter.WriteEndArray(); + } + catch (Exception e) + { + Log.Error(e.ToString()); + } + } + + private static void WriteLimitReachedNotification(JsonWriter writer, string objectName, string message, bool shouldCloseObject) + { + Log.Debug($"{nameof(DebuggerSnapshotSerializer)}.{nameof(WriteLimitReachedNotification)}: {objectName} {message}"); + writer.WritePropertyName(objectName); + writer.WriteValue(message); + if (shouldCloseObject) + { + writer.WriteEndObject(); + } + } + + private static string GetAutoPropertyOrFieldName(string fieldName) + { + const string prefix = "<"; + const string suffix = ">k__BackingField"; + var match = Regex.Match(fieldName, $"{prefix}(.+?){suffix}"); + return match.Success ? match.Groups[1].Value : fieldName; + } + + internal static bool TryGetValue(MemberInfo fieldOrProp, object source, out object value, out Type type) + { + value = null; + type = null; + try + { + switch (fieldOrProp) + { + case FieldInfo field: + { + type = field.FieldType; + if (source != null || field.IsStatic) + { + value = field.GetValue(source); + return true; + } + + break; + } + + case PropertyInfo property: + { + type = property.PropertyType; + if (source != null || property.GetMethod?.IsStatic == true) + { + value = property.GetMethod.Invoke(source, Array.Empty()); + return true; + } + + break; + } + + default: + { + Log.Error($"{nameof(DebuggerSnapshotSerializer)}.{nameof(TryGetValue)}: Can't get value of {fieldOrProp.Name}. Unsupported member info {fieldOrProp.GetType()}"); + break; + } + } + } + catch (Exception e) + { + Log.Error($"{nameof(DebuggerSnapshotSerializer)}.{nameof(TryGetValue)}: {e}"); + } + + return false; + } + + private static CancellationTokenSource CreateCancellationTimeout() + { + var cts = new CancellationTokenSource(); + cts.CancelAfter(MillisecondsToCancel); + return cts; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/ExceptionSnapshotSerializerFieldsAndPropsSelector.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/ExceptionSnapshotSerializerFieldsAndPropsSelector.cs new file mode 100644 index 000000000..6548bc2f6 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/ExceptionSnapshotSerializerFieldsAndPropsSelector.cs @@ -0,0 +1,52 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class ExceptionSnapshotSerializerFieldsAndPropsSelector : SnapshotSerializerFieldsAndPropsSelector + { + private readonly string[] _interestingProperties = + { + nameof(Exception.StackTrace), + nameof(Exception.Message), + nameof(Exception.InnerException), + nameof(Exception.HResult), + nameof(Exception.HelpLink), + nameof(Exception.Source) + }; + + internal override bool IsApplicable(Type type) + { + return typeof(Exception).IsAssignableFrom(type); + } + + internal override IEnumerable GetFieldsAndProps( + Type type, + object source, + int maximumDepthOfHierarchyToCopy, + int maximumNumberOfFieldsToCopy, + CancellationTokenSource cts) + { + // Include the interesting (side-effect-free) properties from System.Exception + var regularProps = + typeof(Exception) + .GetProperties() + .Where(p => _interestingProperties.Contains(p.Name)) + .Select(p => p); + + // Remove the fields declared on System.Exception - they are not interesting. + var fields = base.GetFieldsAndProps(type, source, maximumDepthOfHierarchyToCopy, maximumNumberOfFieldsToCopy, cts) + .Where(b => b.DeclaringType != typeof(Exception)); + + return regularProps.Concat(fields); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/LazySnapshotSerializerFieldsAndPropsSelector.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/LazySnapshotSerializerFieldsAndPropsSelector.cs new file mode 100644 index 000000000..94f9f9ce4 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/LazySnapshotSerializerFieldsAndPropsSelector.cs @@ -0,0 +1,38 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class LazySnapshotSerializerFieldsAndPropsSelector : SnapshotSerializerFieldsAndPropsSelector + { + internal override bool IsApplicable(Type type) + { + return type.Name == "Lazy`1" && type.Namespace == "System"; + } + + internal override IEnumerable GetFieldsAndProps( + Type type, + object source, + int maximumDepthOfHierarchyToCopy, + int maximumNumberOfFieldsToCopy, + CancellationTokenSource cts) + { + var isValueCreatedProp = type.GetProperty("IsValueCreated"); + if (DebuggerSnapshotSerializer.TryGetValue(isValueCreatedProp, source, out var isValueCreated, out var _)) + { + yield return isValueCreatedProp; + if (true.Equals(isValueCreated)) + { + yield return type.GetProperty("Value"); + } + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/OldStyleTupleSnapshotSerializerFieldsAndPropsSelector.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/OldStyleTupleSnapshotSerializerFieldsAndPropsSelector.cs new file mode 100644 index 000000000..9e106da8c --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/OldStyleTupleSnapshotSerializerFieldsAndPropsSelector.cs @@ -0,0 +1,30 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class OldStyleTupleSnapshotSerializerFieldsAndPropsSelector : SnapshotSerializerFieldsAndPropsSelector + { + internal override bool IsApplicable(Type type) + { + return type.Name.StartsWith("Tuple`") && type.Namespace == "System"; + } + + internal override IEnumerable GetFieldsAndProps( + Type type, + object source, + int maximumDepthOfHierarchyToCopy, + int maximumNumberOfFieldsToCopy, + CancellationTokenSource cts) + { + return type.GetProperties(); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSerializerFieldsAndPropsSelector.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSerializerFieldsAndPropsSelector.cs new file mode 100644 index 000000000..ab5843d64 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSerializerFieldsAndPropsSelector.cs @@ -0,0 +1,79 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class SnapshotSerializerFieldsAndPropsSelector + { + private const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly; + private static readonly SnapshotSerializerFieldsAndPropsSelector Instance = new(); + private static readonly List CustomSelectors = + new() + { + new LazySnapshotSerializerFieldsAndPropsSelector(), + new ExceptionSnapshotSerializerFieldsAndPropsSelector(), + new TaskSnapshotSerializerFieldsAndPropsSelector(), + new OldStyleTupleSnapshotSerializerFieldsAndPropsSelector() + }; + + protected SnapshotSerializerFieldsAndPropsSelector() + { + } + + internal static SnapshotSerializerFieldsAndPropsSelector CreateDeepClonerFieldsAndPropsSelector(Type type) + { + return CustomSelectors.FirstOrDefault(c => c.IsApplicable(type)) ?? Instance; + } + + internal virtual bool IsApplicable(Type type) => true; + + /// + /// Gets all fields and auto properties e.g. property with a backing field + /// + /// Object type + /// Object + /// Max depth of hierarchy + /// Max fields + /// Cancellation token source + /// Collection of fields and auto properties + internal virtual IEnumerable GetFieldsAndProps( + Type type, + object source, + int maximumDepthOfHierarchyToCopy, + int maximumNumberOfFieldsToCopy, + CancellationTokenSource cts) + { + return GetAllFields(type, maximumDepthOfHierarchyToCopy, cts).Take(maximumNumberOfFieldsToCopy).ToArray(); + } + + private static IEnumerable GetAllFields(Type type, int maximumDepthOfHierarchyToCopy, CancellationTokenSource cts) + { + int depth = 0; + while (maximumDepthOfHierarchyToCopy == -1 || depth < maximumDepthOfHierarchyToCopy) + { + cts.Token.ThrowIfCancellationRequested(); + + if (type == null) + { + yield break; + } + + foreach (var field in type.GetFields(Flags)) + { + yield return field; + } + + depth++; + type = type.BaseType; + } + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSummary.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSummary.cs new file mode 100644 index 000000000..12aac5c85 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/SnapshotSummary.cs @@ -0,0 +1,151 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Util; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class SnapshotSummary + { + public static string FormatMessage(Snapshot snapshot) + { + var sb = StringBuilderCache.Acquire(StringBuilderCache.MaxBuilderSize); + sb.Append(FormatMethod(snapshot.Debugger.Snapshot.Stack, snapshot.Debugger.Snapshot.Probe.Location)); + sb.Append('(') + .Append(FormatCapturedValues(GetArguments(snapshot)) ?? string.Empty) + .Append(')'); + var returnValue = GetReturnValue(snapshot); + if (returnValue != null) + { + sb.Append(": ").Append(returnValue); + } + + var locals = FormatCapturedValues(GetLocals(snapshot)) ?? string.Empty; + if (!string.IsNullOrEmpty(locals)) + { + sb.Append(Environment.NewLine).Append(locals); + } + + return StringBuilderCache.GetStringAndRelease(sb); + } + + private static string FormatMethod(IReadOnlyList frames, ProbeLocation probeLocation) + { + if (frames?.Count > 0) + { + // we first try to use the top frame on the stacktrace, if available + return FormatMethod(frames[0]); + } + + // if the stacktrace is not available we use the probe location + return FormatMethod(probeLocation); + } + + private static string FormatMethod(StackInfo stackFrame) + { + if (stackFrame.Function != null) + { + var classAndMethod = GetClassAndMethod(stackFrame.Function); + if (classAndMethod.Count == 2) + { + return classAndMethod[1] + "." + classAndMethod[0]; + } + else if (classAndMethod.Count == 1) + { + return classAndMethod[0]; + } + else + { + return stackFrame.Function; + } + } + else + { + return stackFrame.FileName; + } + } + + private static string FormatMethod(ProbeLocation probeLocation) + { + if (probeLocation.Type != null && probeLocation.Method != null) + { + // parse out the class name + var fqn = probeLocation.Type; + var className = fqn.Substring(fqn.LastIndexOf('.') + 1); + return className + "." + probeLocation.Method; + } + + if (probeLocation.Method != null) + { + return probeLocation.Method; + } + + return probeLocation.File + ":" + probeLocation.Lines; + } + + private static List GetClassAndMethod(string stackFrameFunction) + { + int firstParenIdx = stackFrameFunction.IndexOf('('); + if (firstParenIdx >= 0) + { + stackFrameFunction = stackFrameFunction.Substring(0, firstParenIdx); + } + + int lastDotIdx = stackFrameFunction.LastIndexOf('.'); + if (lastDotIdx == -1) + { + return new List { stackFrameFunction }; + } + + var results = new List(); + while (lastDotIdx > -1 && results.Count < 2) + { + var part = stackFrameFunction.Substring(lastDotIdx + 1); + results.Add(part); + stackFrameFunction = stackFrameFunction.Substring(0, lastDotIdx); + lastDotIdx = stackFrameFunction.LastIndexOf('.'); + } + + return results; + } + + private static CapturedValue[] GetArguments(Snapshot snapshot) + { + return snapshot.Debugger.Snapshot.Captures.Entry?.Arguments ?? + snapshot.Debugger.Snapshot.Captures.Lines?.Captured?.Arguments; + } + + private static string GetReturnValue(Snapshot snapshot) + { + return snapshot.Debugger.Snapshot.Captures.Return?.Locals?.FirstOrDefault(local => local.Name == "@return")?.Value; + } + + private static CapturedValue[] GetLocals(Snapshot snapshot) + { + return GetLastCapture(snapshot)?.Locals; + } + + private static string FormatCapturedValues(CapturedValue[] capturedValues) + { + if (capturedValues == null || capturedValues.Length == 0) + { + return null; + } + + Array.Sort(capturedValues); + return string.Join(", ", capturedValues.Select(cv => cv?.Name + "=" + cv?.Value)); + } + + private static CapturedContext GetLastCapture(Snapshot snapshot) + { + return snapshot.Debugger.Snapshot.Captures.Return ?? + snapshot.Debugger.Snapshot.Captures.Lines?.Captured ?? + snapshot.Debugger.Snapshot.Captures.Entry; + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/SupportedTypesService.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/SupportedTypesService.cs new file mode 100644 index 000000000..1c5d1c974 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/SupportedTypesService.cs @@ -0,0 +1,127 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Security; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal static class SupportedTypesService + { + private static readonly Type[] AllowedCollectionTypes = + { + typeof(List<>), + typeof(ArrayList), + typeof(LinkedList<>), + typeof(SortedList), + typeof(SortedList<,>), + typeof(Dictionary<,>), + typeof(SortedDictionary<,>), + typeof(ConcurrentDictionary<,>), + typeof(Stack), + typeof(Stack<>), + typeof(ConcurrentStack<>), + typeof(Queue), + typeof(Queue<>), + typeof(ConcurrentQueue<>), + typeof(HashSet<>), + typeof(Hashtable), + typeof(SortedSet<>), + typeof(ConcurrentBag<>), + typeof(BlockingCollection<>), + typeof(ConditionalWeakTable<,>), + }; + + private static readonly string[] AllowedSpecialCasedCollectionTypeNames = { }; // "RangeIterator" + + private static readonly Type[] AllowedTypesSafeToCallToString = + { + typeof(DateTime), + typeof(TimeSpan), + typeof(DateTimeOffset), + typeof(Uri), + typeof(Guid), + typeof(Version), + typeof(StackTrace) + }; + + private static readonly Type[] DeniedTypes = + { + typeof(SecureString), + }; + + internal static bool IsSafeToCallToString(Type type) + { + return IsSimple(type) || + AllowedTypesSafeToCallToString.Contains(type) || + IsSupportedCollection(type); + } + + private static bool IsSimple(Type type) + { + if (type == null) + { + return false; + } + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return IsSimple(type.GetGenericArguments()[0]); + } + + return type.IsPrimitive + || type.IsEnum + || type.Equals(typeof(string)) + || type.Equals(typeof(decimal)); + } + + internal static bool IsSupportedCollection(string reflectionFullName) + { + return AllowedCollectionTypes.Any(t => t.FullName == reflectionFullName); + } + + internal static bool IsSupportedCollection(object o) + { + if (o == null) + { + return false; + } + + return IsSupportedCollection(o.GetType()); + } + + internal static bool IsSupportedCollection(Type type) + { + if (type == null) + { + return false; + } + + if (type.IsArray) + { + return true; + } + + return AllowedCollectionTypes.Any(whiteType => whiteType == type || (type.IsGenericType && whiteType == type.GetGenericTypeDefinition())) || + AllowedSpecialCasedCollectionTypeNames.Any(white => white.Equals(type.Name, StringComparison.OrdinalIgnoreCase)); + } + + internal static bool IsDenied(Type type) + { + if (type == null) + { + return false; + } + + return DeniedTypes.Any(deniedType => deniedType == type || (type.IsGenericType && deniedType == type.GetGenericTypeDefinition())); + } + } +} diff --git a/tracer/src/Datadog.Trace/Debugger/Snapshots/TaskSnapshotSerializerFieldsAndPropsSelector.cs b/tracer/src/Datadog.Trace/Debugger/Snapshots/TaskSnapshotSerializerFieldsAndPropsSelector.cs new file mode 100644 index 000000000..9fede0cd3 --- /dev/null +++ b/tracer/src/Datadog.Trace/Debugger/Snapshots/TaskSnapshotSerializerFieldsAndPropsSelector.cs @@ -0,0 +1,45 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; + +namespace Datadog.Trace.Debugger.Snapshots +{ + internal class TaskSnapshotSerializerFieldsAndPropsSelector : SnapshotSerializerFieldsAndPropsSelector + { + internal override bool IsApplicable(Type type) + { + return type.Name == "Task`1" && type.Namespace == "System.Threading.Tasks"; + } + + internal override IEnumerable GetFieldsAndProps( + Type type, + object source, + int maximumDepthOfHierarchyToCopy, + int maximumNumberOfFieldsToCopy, + CancellationTokenSource cts) + { + yield return type.GetProperty("Id"); + var statusProp = type.GetProperty("Status"); + + if (DebuggerSnapshotSerializer.TryGetValue(statusProp, source, out var status, out var _)) + { + yield return statusProp; + if (TaskStatus.RanToCompletion.Equals(status)) + { + yield return type.GetProperty("Result"); + } + else if (TaskStatus.Faulted.Equals(status)) + { + yield return type.GetProperty("Exception"); + } + } + } + } +} diff --git a/tracer/src/Datadog.Trace/FrameworkDescription.cs b/tracer/src/Datadog.Trace/FrameworkDescription.cs index b84f636fa..7bb7d5f89 100644 --- a/tracer/src/Datadog.Trace/FrameworkDescription.cs +++ b/tracer/src/Datadog.Trace/FrameworkDescription.cs @@ -76,6 +76,11 @@ public static bool IsNet5() return Environment.Version.Major >= 5; } + public bool IsWindows() + { + return string.Equals(OSPlatform, OSPlatformName.Windows, StringComparison.OrdinalIgnoreCase); + } + public override string ToString() { // examples: diff --git a/tracer/src/Datadog.Trace/PDBs/DatadogPdbReader.cs b/tracer/src/Datadog.Trace/PDBs/DatadogPdbReader.cs index deba92430..f820517b8 100644 --- a/tracer/src/Datadog.Trace/PDBs/DatadogPdbReader.cs +++ b/tracer/src/Datadog.Trace/PDBs/DatadogPdbReader.cs @@ -4,14 +4,19 @@ // using System; +using System.Collections.Generic; using System.IO; +using System.Reflection; using Datadog.Trace.Vendors.dnlib.DotNet; using Datadog.Trace.Vendors.dnlib.DotNet.MD; -using Datadog.Trace.Vendors.dnlib.DotNet.Pdb; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Dss; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Managed; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Portable; using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; using Datadog.Trace.Vendors.dnlib.IO; +using SymbolReaderFactory = Datadog.Trace.Vendors.dnlib.DotNet.Pdb.SymbolReaderFactory; -namespace Datadog.Trace.PDBs +namespace Datadog.Trace.Pdb { /// /// Reads both Windows and Portable PDBs. @@ -28,14 +33,13 @@ private DatadogPdbReader(SymbolReader symbolReader, ModuleDefMD module) _module = module; } - public static DatadogPdbReader CreatePdbReader(string assemblyFullPath) + public static DatadogPdbReader CreatePdbReader(Assembly assembly) { - var module = ModuleDefMD.Load(File.ReadAllBytes(assemblyFullPath)); - var metadata = MetadataFactory.Load(assemblyFullPath, CLRRuntimeReaderKind.CLR); + string assemblyFullPath = assembly.Location; + var module = ModuleDefMD.Load(assembly.ManifestModule); string pdbFullPath = Path.ChangeExtension(assemblyFullPath, "pdb"); var pdbStream = DataReaderFactoryFactory.Create(pdbFullPath, false); - var options = new ModuleCreationOptions(CLRRuntimeReaderKind.CLR); - var dnlibReader = SymbolReaderFactory.Create(options.PdbOptions, metadata, pdbStream); + var dnlibReader = SymbolReaderFactory.Create(ModuleCreationOptions.DefaultPdbReaderOptions, module.Metadata, pdbStream); if (dnlibReader == null) { return null; @@ -52,6 +56,22 @@ public SymbolMethod ReadMethodSymbolInfo(int methodMetadataToken) return _symbolReader.GetMethod(mdMethod, version: 1); } + public SymbolMethod GetContainingMethodAndOffset(string filePath, int line, int column, out int? bytecodeOffset) + { + return _symbolReader switch + { + PortablePdbReader portablePdbReader => portablePdbReader.GetContainingMethod(filePath, line, column, out bytecodeOffset), + PdbReader managedPdbReader => managedPdbReader.GetContainingMethod(filePath, line, column, out bytecodeOffset), + SymbolReaderImpl symUnmanagedReader => symUnmanagedReader.GetContainingMethod(filePath, line, column, out bytecodeOffset), + _ => throw new ArgumentOutOfRangeException(nameof(filePath), $"Reader type {_symbolReader.GetType().FullName} is not supported") + }; + } + + public IList GetDocuments() + { + return _symbolReader.Documents; + } + public void Dispose() { _symbolReader.Dispose(); diff --git a/tracer/src/Datadog.Trace/PDBs/MethodSymbolResolver.cs b/tracer/src/Datadog.Trace/PDBs/MethodSymbolResolver.cs index bea6ba0d1..6c968eec1 100644 --- a/tracer/src/Datadog.Trace/PDBs/MethodSymbolResolver.cs +++ b/tracer/src/Datadog.Trace/PDBs/MethodSymbolResolver.cs @@ -13,7 +13,7 @@ using Datadog.Trace.Vendors.dnlib.DotNet.Emit; using Datadog.Trace.Vendors.dnlib.DotNet.Pdb; -namespace Datadog.Trace.PDBs +namespace Datadog.Trace.Pdb { internal class MethodSymbolResolver { diff --git a/tracer/src/Datadog.Trace/PDBs/SymbolMethodExtensions.cs b/tracer/src/Datadog.Trace/PDBs/SymbolMethodExtensions.cs new file mode 100644 index 000000000..36bc0c74c --- /dev/null +++ b/tracer/src/Datadog.Trace/PDBs/SymbolMethodExtensions.cs @@ -0,0 +1,51 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; + +namespace Datadog.Trace.Pdb +{ + internal static class SymbolMethodExtensions + { + public static IEnumerable GetLocalVariablesInScope(this SymbolMethod method, int offset) + { + return + GetAllScopes(method) + .Where(s => s.StartOffset <= offset && s.EndOffset >= offset) + .SelectMany(s => s.Locals); + } + + public static IEnumerable GetLocalVariables(this SymbolMethod method) + { + return + GetAllScopes(method) + .SelectMany(s => s.Locals); + } + + private static IList GetAllScopes(SymbolMethod method) + { + var result = new List(); + RetrieveAllNestedScopes(method.RootScope, result); + return result; + } + + private static void RetrieveAllNestedScopes(SymbolScope scope, List result) + { + // Recursively extract all nested scopes in method + if (scope == null) + { + return; + } + + result.Add(scope); + foreach (var innerScope in scope.Children) + { + RetrieveAllNestedScopes(innerScope, result); + } + } + } +} diff --git a/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/DssSymbolReaderImpl.Additions.cs b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/DssSymbolReaderImpl.Additions.cs new file mode 100644 index 000000000..58e39792b --- /dev/null +++ b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/DssSymbolReaderImpl.Additions.cs @@ -0,0 +1,25 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; + +#pragma warning disable SA1300 +namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Dss +{ + internal sealed partial class SymbolReaderImpl + { + internal SymbolMethod GetContainingMethod(string documentUrl, int line, int column, out int? bytecodeOffset) + { + reader.GetDocument(documentUrl, language: default, languageVendor: default, documentType: default, out var document); + reader.GetMethodFromDocumentPosition(document, (uint)line, (uint)column, out var method); + method.GetOffset(document, (uint)line, (uint)column, out var offset); + method.GetToken(out var token); + + bytecodeOffset = (int?)offset; + return new SymbolMethodImpl(this, method); + } + } +} diff --git a/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PdbReader.Additions.cs b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PdbReader.Additions.cs new file mode 100644 index 000000000..70b5f91fd --- /dev/null +++ b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PdbReader.Additions.cs @@ -0,0 +1,54 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; + +#pragma warning disable SA1300 +namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Managed +{ + internal partial class PdbReader + { + internal SymbolMethod GetContainingMethod(string documentUrl, int line, int column, out int? bytecodeOffset) + { + var candidateSequencePoints = new List(); + foreach (var function in functions.Values) + { + var methodIsInDocument = function.SequencePoints.Any(s => s.Document.URL == documentUrl); + + if (methodIsInDocument) + { + var method = GetMethod(((ModuleDefMD)module).ResolveMethod(MDToken.ToRID(function.token)), version: 1); + foreach (var sp in method.SequencePoints) + { + if (sp.Line <= line && sp.EndLine >= line && + sp.Column >= column && sp.EndColumn >= column) + { + candidateSequencePoints.Add(new ResolvedSequencePoint(method, sp)); + } + } + } + } + + var matchingSequencePoint = candidateSequencePoints.FirstOrDefault(); + bytecodeOffset = matchingSequencePoint.SequencePoint.Offset; + return matchingSequencePoint.Method; // TODO - find shortest sequence point + } + + private record ResolvedSequencePoint + { + public ResolvedSequencePoint(SymbolMethod method, SymbolSequencePoint sequencePoint) + { + Method = method; + SequencePoint = sequencePoint; + } + + public SymbolMethod Method { get; } + + public SymbolSequencePoint SequencePoint { get; } + } + } +} diff --git a/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PortablePdbReader.Additions.cs b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PortablePdbReader.Additions.cs new file mode 100644 index 000000000..1a7302f95 --- /dev/null +++ b/tracer/src/Datadog.Trace/PDBs/dnlibAdditions/PortablePdbReader.Additions.cs @@ -0,0 +1,82 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Symbols; + +#pragma warning disable SA1300 +namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Portable +{ + internal sealed partial class PortablePdbReader + { + internal SymbolMethod GetContainingMethod(string documentUrl, int line, int column, out int? bytecodeOffset) + { + foreach (var methodRid in GetMethodRIDsContainedInDocument(documentUrl)) + { + var method = ((ModuleDefMD)module).ResolveMethod(methodRid); + var symbolMethod = GetMethod(method, version: 1); + foreach (var sp in symbolMethod.SequencePoints) + { + if (sp.Line <= line && + sp.EndLine >= line && + sp.Column >= column && + sp.EndColumn >= column) + { + bytecodeOffset = sp.Offset; + return symbolMethod; + } + } + } + + bytecodeOffset = null; + return null; + } + + private IEnumerable GetMethodRIDsContainedInDocument(string documentUrl) + { + var requestedDocumentRid = GetDocumentRid(documentUrl); + + for (uint methodRid = 1; methodRid <= pdbMetadata.TablesStream.MethodDebugInformationTable.Rows; methodRid++) + { + if (!pdbMetadata.TablesStream.TryReadMethodDebugInformationRow(methodRid, out var row)) + { + continue; + } + + if (row.SequencePoints == 0) + { + continue; + } + + if (row.Document == requestedDocumentRid) + { + yield return methodRid; + } + } + } + + private int GetDocumentRid(string documentUrl) + { + var docTbl = pdbMetadata.TablesStream.DocumentTable; + var docs = new SymbolDocument[docTbl.Rows]; + var nameReader = new DocumentNameReader(pdbMetadata.BlobStream); + for (var i = 1; i <= docs.Length; i++) + { + if (!pdbMetadata.TablesStream.TryReadDocumentRow((uint)i, out var row)) + { + continue; + } + + var url = nameReader.ReadDocumentName(row.Name); + if (url == documentUrl) + { + return i; + } + } + + return -1; + } + } +} diff --git a/tracer/src/Datadog.Trace/Propagators/DatadogContextPropagator.cs b/tracer/src/Datadog.Trace/Propagators/DatadogContextPropagator.cs index ede6764b5..43d502b7b 100644 --- a/tracer/src/Datadog.Trace/Propagators/DatadogContextPropagator.cs +++ b/tracer/src/Datadog.Trace/Propagators/DatadogContextPropagator.cs @@ -49,7 +49,7 @@ public void Inject(SpanContext context, TCarrier carri var propagationHeaderMaxLength = context.TraceContext?.Tracer.Settings.TagPropagationHeaderMaxLength ?? TagPropagation.OutgoingPropagationHeaderMaxLength; var propagatedTraceTags = context.TraceContext?.Tags.ToPropagationHeader(propagationHeaderMaxLength) ?? context.PropagatedTags; - if (propagatedTraceTags != null) + if (!string.IsNullOrEmpty(propagatedTraceTags)) { carrierSetter.Set(carrier, DDHttpHeaderNames.PropagatedTags, propagatedTraceTags); } diff --git a/tracer/src/Datadog.Trace/ReadOnlySpanContext.cs b/tracer/src/Datadog.Trace/ReadOnlySpanContext.cs index 2f72e7a13..a4db7b717 100644 --- a/tracer/src/Datadog.Trace/ReadOnlySpanContext.cs +++ b/tracer/src/Datadog.Trace/ReadOnlySpanContext.cs @@ -5,20 +5,21 @@ // Modified by Splunk Inc. -namespace Datadog.Trace; - -internal class ReadOnlySpanContext : ISpanContext +namespace Datadog.Trace { - public ReadOnlySpanContext(TraceId traceId, ulong spanId, string serviceName) + internal class ReadOnlySpanContext : ISpanContext { - TraceId = traceId; - SpanId = spanId; - ServiceName = serviceName; - } + public ReadOnlySpanContext(TraceId traceId, ulong spanId, string serviceName) + { + TraceId = traceId; + SpanId = spanId; + ServiceName = serviceName; + } - public TraceId TraceId { get; } + public TraceId TraceId { get; } - public ulong SpanId { get; } + public ulong SpanId { get; } - public string ServiceName { get; } + public string ServiceName { get; } + } } diff --git a/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmClient.cs b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmClient.cs new file mode 100644 index 000000000..86fb19f34 --- /dev/null +++ b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmClient.cs @@ -0,0 +1,33 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.RemoteConfigurationManagement.Models +{ + internal class RcmClient + { + [JsonProperty("id")] + public string Id { get; set; } + + [JsonProperty("name")] + public string Name { get; set; } + + [JsonProperty("products")] + public string[] Products { get; set; } + + [JsonProperty("version")] + public string Version { get; set; } + + [JsonProperty("state")] + public object State { get; set; } + + [JsonProperty("is_tracer")] + public bool IsTracer { get; set; } + + [JsonProperty("client_tracer")] + public RcmTracerClient ClientTracer { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmRequest.cs b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmRequest.cs new file mode 100644 index 000000000..5e686051a --- /dev/null +++ b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmRequest.cs @@ -0,0 +1,60 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Text; +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.RemoteConfigurationManagement.Models +{ + internal class RcmRequest + { + private RcmRequest() + { + } + + [JsonProperty("client")] + public RcmClient Client { get; set; } + + [JsonProperty("cached_target_files")] + public string[] CachedTargetFiles { get; set; } + + public static RcmRequest Create( + string[] products, + string serviceName, + string serviceVersion, + string environment, + string runtimeId) + { + return new RcmRequest() + { + Client = new RcmClient() + { + Id = runtimeId, + IsTracer = true, + Name = serviceName, + Products = products, + State = new { }, + Version = TracerConstants.AssemblyVersion, + ClientTracer = new RcmTracerClient() + { + Language = TracerConstants.Language, + Env = environment, + RuntimeId = runtimeId, + Service = serviceName, + AppVersion = serviceVersion, + TracerVersion = TracerConstants.AssemblyVersion + }, + }, + CachedTargetFiles = Array.Empty() + }; + } + + public ArraySegment AsArraySegment() + { + return new ArraySegment(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(this))); + } + } +} diff --git a/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmResponse.cs b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmResponse.cs new file mode 100644 index 000000000..b4ba79eb8 --- /dev/null +++ b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmResponse.cs @@ -0,0 +1,15 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.RemoteConfigurationManagement.Models +{ + internal class RcmResponse + { + [JsonProperty("target_files")] + public RcmTargetFile[] TargetFiles { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTargetFile.cs b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTargetFile.cs new file mode 100644 index 000000000..17dbeeb76 --- /dev/null +++ b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTargetFile.cs @@ -0,0 +1,18 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.RemoteConfigurationManagement.Models +{ + internal class RcmTargetFile + { + [JsonProperty("path")] + public string Path { get; set; } + + [JsonProperty("raw")] + public string Raw { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTracerClient.cs b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTracerClient.cs new file mode 100644 index 000000000..b1c170859 --- /dev/null +++ b/tracer/src/Datadog.Trace/RemoteConfigurationManagement/Models/RcmTracerClient.cs @@ -0,0 +1,30 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Vendors.Newtonsoft.Json; + +namespace Datadog.Trace.RemoteConfigurationManagement.Models +{ + internal class RcmTracerClient + { + [JsonProperty("runtime_id")] + public string RuntimeId { get; set; } + + [JsonProperty("language")] + public string Language { get; set; } + + [JsonProperty("tracer_version")] + public string TracerVersion { get; set; } + + [JsonProperty("service")] + public string Service { get; set; } + + [JsonProperty("env")] + public string Env { get; set; } + + [JsonProperty("app_version")] + public string AppVersion { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/SamplingPriorityValues.cs b/tracer/src/Datadog.Trace/SamplingPriorityValues.cs index 1fbc5ed83..f9cc710c0 100644 --- a/tracer/src/Datadog.Trace/SamplingPriorityValues.cs +++ b/tracer/src/Datadog.Trace/SamplingPriorityValues.cs @@ -3,33 +3,34 @@ // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // -namespace Datadog.Trace; - -internal static class SamplingPriorityValues +namespace Datadog.Trace { - /// - /// Trace should be dropped (not sampled). - /// Sampling decision made explicitly by user through - /// code or configuration (e.g. the rules sampler). - /// - public const int UserReject = -1; + internal static class SamplingPriorityValues + { + /// + /// Trace should be dropped (not sampled). + /// Sampling decision made explicitly by user through + /// code or configuration (e.g. the rules sampler). + /// + public const int UserReject = -1; - /// - /// Trace should be dropped (not sampled). - /// Sampling decision made by the built-in sampler. - /// - public const int AutoReject = 0; + /// + /// Trace should be dropped (not sampled). + /// Sampling decision made by the built-in sampler. + /// + public const int AutoReject = 0; - /// - /// Trace should be kept (sampled). - /// Sampling decision made by the built-in sampler. - /// - public const int AutoKeep = 1; + /// + /// Trace should be kept (sampled). + /// Sampling decision made by the built-in sampler. + /// + public const int AutoKeep = 1; - /// - /// Trace should be kept (sampled). - /// Sampling decision made explicitly by user through - /// code or configuration (e.g. the rules sampler). - /// - public const int UserKeep = 2; + /// + /// Trace should be kept (sampled). + /// Sampling decision made explicitly by user through + /// code or configuration (e.g. the rules sampler). + /// + public const int UserKeep = 2; + } } diff --git a/tracer/src/Datadog.Trace/Telemetry/DTOs/TelemetryValue.cs b/tracer/src/Datadog.Trace/Telemetry/DTOs/TelemetryValue.cs index 1b7c6bfa6..0e46191ab 100644 --- a/tracer/src/Datadog.Trace/Telemetry/DTOs/TelemetryValue.cs +++ b/tracer/src/Datadog.Trace/Telemetry/DTOs/TelemetryValue.cs @@ -4,17 +4,18 @@ // #nullable enable -namespace Datadog.Trace.Telemetry; - -internal readonly struct TelemetryValue +namespace Datadog.Trace.Telemetry { - public TelemetryValue(string name, object? value) + internal readonly struct TelemetryValue { - Name = name; - Value = value; - } + public TelemetryValue(string name, object? value) + { + Name = name; + Value = value; + } - public string Name { get; } + public string Name { get; } - public object? Value { get; } + public object? Value { get; } + } } diff --git a/tracer/src/Datadog.Trace/Telemetry/TelemetryCircuitBreaker.cs b/tracer/src/Datadog.Trace/Telemetry/TelemetryCircuitBreaker.cs index 2c93cc290..fce6b5616 100644 --- a/tracer/src/Datadog.Trace/Telemetry/TelemetryCircuitBreaker.cs +++ b/tracer/src/Datadog.Trace/Telemetry/TelemetryCircuitBreaker.cs @@ -5,67 +5,68 @@ using System.Collections.Generic; -namespace Datadog.Trace.Telemetry; - -internal class TelemetryCircuitBreaker +namespace Datadog.Trace.Telemetry { - internal const int MaxFatalErrors = 2; - internal const int MaxTransientErrors = 5; + internal class TelemetryCircuitBreaker + { + internal const int MaxFatalErrors = 2; + internal const int MaxTransientErrors = 5; - private bool _hasSentSuccessfully = false; - private int _initialFatalCount = 0; - private int _failureCount = 0; + private bool _hasSentSuccessfully = false; + private int _initialFatalCount = 0; + private int _failureCount = 0; - public ICollection PreviousConfiguration { get; private set; } + public ICollection PreviousConfiguration { get; private set; } - public ICollection PreviousDependencies { get; private set; } + public ICollection PreviousDependencies { get; private set; } - public ICollection PreviousIntegrations { get; private set; } + public ICollection PreviousIntegrations { get; private set; } - public TelemetryPushResult Evaluate( - TelemetryPushResult result, - ICollection config, - ICollection dependencies, - ICollection integrations) - { - if (result == TelemetryPushResult.Success) + public TelemetryPushResult Evaluate( + TelemetryPushResult result, + ICollection config, + ICollection dependencies, + ICollection integrations) { - _hasSentSuccessfully = true; - _failureCount = 0; - PreviousConfiguration = null; - PreviousDependencies = null; - PreviousIntegrations = null; - return result; - } - else if (result == TelemetryPushResult.FatalError && !_hasSentSuccessfully) - { - _initialFatalCount++; - if (_initialFatalCount >= MaxFatalErrors) + if (result == TelemetryPushResult.Success) { - // we've had MaxFatalErrors 404s, 1 minute apart, prob never going to work. + _hasSentSuccessfully = true; + _failureCount = 0; PreviousConfiguration = null; PreviousDependencies = null; PreviousIntegrations = null; - return TelemetryPushResult.FatalError; + return result; } - } - else - { - _failureCount++; - if (_failureCount >= MaxTransientErrors) + else if (result == TelemetryPushResult.FatalError && !_hasSentSuccessfully) { - // we've had MaxTransientErrors in a row, 1 minute apart, probably something bigger wrong - PreviousConfiguration = null; - PreviousDependencies = null; - PreviousIntegrations = null; - return TelemetryPushResult.FatalError; + _initialFatalCount++; + if (_initialFatalCount >= MaxFatalErrors) + { + // we've had MaxFatalErrors 404s, 1 minute apart, prob never going to work. + PreviousConfiguration = null; + PreviousDependencies = null; + PreviousIntegrations = null; + return TelemetryPushResult.FatalError; + } + } + else + { + _failureCount++; + if (_failureCount >= MaxTransientErrors) + { + // we've had MaxTransientErrors in a row, 1 minute apart, probably something bigger wrong + PreviousConfiguration = null; + PreviousDependencies = null; + PreviousIntegrations = null; + return TelemetryPushResult.FatalError; + } } - } - // We should retry next time - PreviousConfiguration = config; - PreviousDependencies = dependencies; - PreviousIntegrations = integrations; - return TelemetryPushResult.TransientFailure; + // We should retry next time + PreviousConfiguration = config; + PreviousDependencies = dependencies; + PreviousIntegrations = integrations; + return TelemetryPushResult.TransientFailure; + } } } diff --git a/tracer/src/Datadog.Trace/Telemetry/Transports/JsonTelemetryTransport.cs b/tracer/src/Datadog.Trace/Telemetry/Transports/JsonTelemetryTransport.cs index a58eb407c..1f2385039 100644 --- a/tracer/src/Datadog.Trace/Telemetry/Transports/JsonTelemetryTransport.cs +++ b/tracer/src/Datadog.Trace/Telemetry/Transports/JsonTelemetryTransport.cs @@ -13,82 +13,83 @@ using Datadog.Trace.Vendors.Newtonsoft.Json; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; -namespace Datadog.Trace.Telemetry.Transports; - -internal class JsonTelemetryTransport : ITelemetryTransport +namespace Datadog.Trace.Telemetry.Transports { - private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); - internal static readonly JsonSerializerSettings SerializerSettings = new() + internal class JsonTelemetryTransport : ITelemetryTransport { - NullValueHandling = NullValueHandling.Ignore, - ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy(), } - }; + private static readonly IDatadogLogger Log = DatadogLogging.GetLoggerFor(); + internal static readonly JsonSerializerSettings SerializerSettings = new() + { + NullValueHandling = NullValueHandling.Ignore, + ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy(), } + }; - private readonly IApiRequestFactory _requestFactory; - private readonly Uri _endpoint; + private readonly IApiRequestFactory _requestFactory; + private readonly Uri _endpoint; - public JsonTelemetryTransport(IApiRequestFactory requestFactory) - { - _requestFactory = requestFactory; - _endpoint = _requestFactory.GetEndpoint(TelemetryConstants.TelemetryPath); - } + public JsonTelemetryTransport(IApiRequestFactory requestFactory) + { + _requestFactory = requestFactory; + _endpoint = _requestFactory.GetEndpoint(TelemetryConstants.TelemetryPath); + } - public async Task PushTelemetry(TelemetryData data) - { - try + public async Task PushTelemetry(TelemetryData data) { - // have to buffer in memory so we know the content length - var serializedData = SerializeTelemetry(data); - var bytes = Encoding.UTF8.GetBytes(serializedData); + try + { + // have to buffer in memory so we know the content length + var serializedData = SerializeTelemetry(data); + var bytes = Encoding.UTF8.GetBytes(serializedData); - var request = _requestFactory.Create(_endpoint); + var request = _requestFactory.Create(_endpoint); - request.AddHeader(TelemetryConstants.ApiVersionHeader, data.ApiVersion); - request.AddHeader(TelemetryConstants.RequestTypeHeader, data.RequestType); + request.AddHeader(TelemetryConstants.ApiVersionHeader, data.ApiVersion); + request.AddHeader(TelemetryConstants.RequestTypeHeader, data.RequestType); - using var response = await request.PostAsync(new ArraySegment(bytes), "application/json").ConfigureAwait(false); - if (response.StatusCode is >= 200 and < 300) - { - Log.Debug("Telemetry sent successfully"); - return TelemetryPushResult.Success; + using var response = await request.PostAsync(new ArraySegment(bytes), "application/json").ConfigureAwait(false); + if (response.StatusCode is >= 200 and < 300) + { + Log.Debug("Telemetry sent successfully"); + return TelemetryPushResult.Success; + } + else if (response.StatusCode == 404) + { + Log.Debug("Error sending telemetry: 404. Disabling further telemetry, as endpoint '{Endpoint}' not found", _requestFactory.Info(_endpoint)); + return TelemetryPushResult.FatalError; + } + else + { + Log.Debug("Error sending telemetry to '{Endpoint}' {StatusCode} ", _requestFactory.Info(_endpoint), response.StatusCode); + return TelemetryPushResult.TransientFailure; + } } - else if (response.StatusCode == 404) + catch (Exception ex) when (IsFatalException(ex)) { - Log.Debug("Error sending telemetry: 404. Disabling further telemetry, as endpoint '{Endpoint}' not found", _requestFactory.Info(_endpoint)); + Log.Warning(ex, "Error sending telemetry data, unable to communicate with '{Endpoint}'", _requestFactory.Info(_endpoint)); return TelemetryPushResult.FatalError; } - else + catch (Exception ex) { - Log.Debug("Error sending telemetry to '{Endpoint}' {StatusCode} ", _requestFactory.Info(_endpoint), response.StatusCode); + Log.Warning(ex, "Error sending telemetry data to '{Endpoint}'", _requestFactory.Info(_endpoint)); return TelemetryPushResult.TransientFailure; } } - catch (Exception ex) when (IsFatalException(ex)) - { - Log.Warning(ex, "Error sending telemetry data, unable to communicate with '{Endpoint}'", _requestFactory.Info(_endpoint)); - return TelemetryPushResult.FatalError; - } - catch (Exception ex) + + // Internal for testing + internal static string SerializeTelemetry(TelemetryData data) { - Log.Warning(ex, "Error sending telemetry data to '{Endpoint}'", _requestFactory.Info(_endpoint)); - return TelemetryPushResult.TransientFailure; + return JsonConvert.SerializeObject(data, Formatting.None, SerializerSettings); } - } - // Internal for testing - internal static string SerializeTelemetry(TelemetryData data) - { - return JsonConvert.SerializeObject(data, Formatting.None, SerializerSettings); - } - - private static bool IsFatalException(Exception ex) - { - return ex is SocketException + private static bool IsFatalException(Exception ex) + { + return ex is SocketException #if !NETFRAMEWORK - or WebException { InnerException: System.Net.Http.HttpRequestException { InnerException: SocketException } } - or System.Net.Http.HttpRequestException { InnerException: SocketException } + or WebException { InnerException: System.Net.Http.HttpRequestException { InnerException: SocketException } } + or System.Net.Http.HttpRequestException { InnerException: SocketException } #endif - or WebException { Response: HttpWebResponse { StatusCode: HttpStatusCode.NotFound } } - or WebException { InnerException: SocketException }; + or WebException { Response: HttpWebResponse { StatusCode: HttpStatusCode.NotFound } } + or WebException { InnerException: SocketException }; + } } } diff --git a/tracer/src/Datadog.Trace/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueue.cs b/tracer/src/Datadog.Trace/Util/BoundedConcurrentQueue.cs similarity index 93% rename from tracer/src/Datadog.Trace/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueue.cs rename to tracer/src/Datadog.Trace/Util/BoundedConcurrentQueue.cs index 7fe483880..14444194b 100644 --- a/tracer/src/Datadog.Trace/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueue.cs +++ b/tracer/src/Datadog.Trace/Util/BoundedConcurrentQueue.cs @@ -1,4 +1,4 @@ -// +// // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // @@ -19,13 +19,11 @@ // limitations under the License. #nullable enable -using System; using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Threading; -using Datadog.Trace.Util; -namespace Datadog.Trace.Logging.DirectSubmission.Sink.PeriodicBatching +namespace Datadog.Trace.Util { internal class BoundedConcurrentQueue { @@ -49,6 +47,10 @@ public BoundedConcurrentQueue(int? queueLimit = null) // Internal for testing internal ConcurrentQueue InnerQueue => _queue; + public int Count => _queue.Count; + + public bool IsEmpty => _queue.IsEmpty; + public bool TryDequeue([NotNullWhen(returnValue: true)] out T? item) { if (_queueLimit == Unbounded) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryType.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryType.cs index 27ef492b3..1daf8b667 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryType.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryType.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -29,6 +31,8 @@ using System; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { internal enum BsonBinaryType : byte diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryWriter.cs index 0dc2cb63a..58da9ae5f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonBinaryWriter.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -33,6 +35,8 @@ using System.Text; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { internal class BsonBinaryWriter diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonObjectId.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonObjectId.cs index 5828d90d8..c546c83d0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonObjectId.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonObjectId.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonReader.cs index 877dbb6c3..23978c03b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonReader.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -36,6 +38,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonToken.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonToken.cs index 998a4f5ca..33d8eb04f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonToken.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonToken.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System.Collections; using System.Collections.Generic; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { internal abstract class BsonToken diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonType.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonType.cs index 4629abf8e..352f44f50 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonType.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonType.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -27,6 +29,8 @@ // OTHER DEALINGS IN THE SOFTWARE. #endregion +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { internal enum BsonType : sbyte diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonWriter.cs index afa7b66a7..5dd9057b8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Bson/BsonWriter.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -39,6 +41,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using System.Globalization; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Bson { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ConstructorHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ConstructorHandling.cs index 4cbb87232..80428b4b2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ConstructorHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ConstructorHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BinaryConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BinaryConverter.cs index 195c5c8e9..4648e34e5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +35,7 @@ using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Collections.Generic; +using System.Diagnostics; #if HAVE_ADO_NET using System.Data.SqlTypes; #endif @@ -46,7 +50,7 @@ internal class BinaryConverter : JsonConverter #if HAVE_LINQ private const string BinaryTypeName = "System.Data.Linq.Binary"; private const string BinaryToArrayName = "ToArray"; - private static ReflectionObject _reflectionObject; + private static ReflectionObject? _reflectionObject; #endif /// @@ -55,7 +59,7 @@ internal class BinaryConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -74,7 +78,9 @@ private byte[] GetByteArray(object value) if (value.GetType().FullName == BinaryTypeName) { EnsureReflectionObject(value.GetType()); - return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName); + MiscellaneousUtils.Assert(_reflectionObject != null); + + return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!; } #endif #if HAVE_ADO_NET @@ -105,7 +111,7 @@ private static void EnsureReflectionObject(Type t) /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -127,7 +133,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { // current token is already at base64 string // unable to call ReadAsBytes so do it the old fashion way - string encodedData = reader.Value.ToString(); + string encodedData = reader.Value!.ToString(); data = Convert.FromBase64String(encodedData); } else @@ -143,8 +149,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist if (t.FullName == BinaryTypeName) { EnsureReflectionObject(t); + MiscellaneousUtils.Assert(_reflectionObject != null); - return _reflectionObject.Creator(data); + return _reflectionObject.Creator!(data); } #endif diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs index 29a7db169..87cc47fce 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +34,8 @@ using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Converters { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/CustomCreationConverter.cs index 938188341..1ce9d2645 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -45,7 +48,7 @@ internal abstract class CustomCreationConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { throw new NotSupportedException("CustomCreationConverter should only be used while deserializing."); } @@ -58,7 +61,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataSetConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataSetConverter.cs index 5afe63ef4..8c5c58aa5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -45,7 +48,7 @@ internal class DataSetConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -54,7 +57,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } DataSet dataSet = (DataSet)value; - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; DataTableConverter converter = new DataTableConverter(); @@ -78,7 +81,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -96,10 +99,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist while (reader.TokenType == JsonToken.PropertyName) { - DataTable dt = ds.Tables[(string)reader.Value]; + DataTable dt = ds.Tables[(string)reader.Value!]; bool exists = (dt != null); - dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer); + dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!; if (!exists) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataTableConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataTableConverter.cs index 0281cfa5a..615bb2a91 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -49,7 +52,7 @@ internal class DataTableConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -58,7 +61,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } DataTable table = (DataTable)value; - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartArray(); @@ -91,7 +94,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -110,7 +113,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist // populate the name from the property name if (reader.TokenType == JsonToken.PropertyName) { - dt.TableName = (string)reader.Value; + dt.TableName = (string)reader.Value!; reader.ReadAndAssert(); @@ -144,7 +147,7 @@ private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer se while (reader.TokenType == JsonToken.PropertyName) { - string columnName = (string)reader.Value; + string columnName = (string)reader.Value!; reader.ReadAndAssert(); @@ -181,7 +184,7 @@ private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer se reader.ReadAndAssert(); } - List o = new List(); + List o = new List(); while (reader.TokenType != JsonToken.EndArray) { @@ -222,7 +225,7 @@ private static Type GetColumnDataType(JsonReader reader) case JsonToken.String: case JsonToken.Date: case JsonToken.Bytes: - return reader.ValueType; + return reader.ValueType!; case JsonToken.Null: case JsonToken.Undefined: case JsonToken.EndArray: diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DateTimeConverterBase.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DateTimeConverterBase.cs index 9c0ed17c2..545d46692 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DateTimeConverterBase.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DateTimeConverterBase.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index 0560e1115..4ea91fc4b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -52,17 +55,32 @@ internal class DiscriminatedUnionConverter : JsonConverter #region UnionDefinition internal class Union { - public List Cases; - public FSharpFunction TagReader { get; set; } + public readonly FSharpFunction TagReader; + public readonly List Cases; + + public Union(FSharpFunction tagReader, List cases) + { + TagReader = tagReader; + Cases = cases; + } } internal class UnionCase { - public int Tag; - public string Name; - public PropertyInfo[] Fields; - public FSharpFunction FieldReader; - public FSharpFunction Constructor; + public readonly int Tag; + public readonly string Name; + public readonly PropertyInfo[] Fields; + public readonly FSharpFunction FieldReader; + public readonly FSharpFunction Constructor; + + public UnionCase(int tag, string name, PropertyInfo[] fields, FSharpFunction fieldReader, FSharpFunction constructor) + { + Tag = tag; + Name = name; + Fields = fields; + FieldReader = fieldReader; + Constructor = constructor; + } } #endregion @@ -78,31 +96,28 @@ private static Type CreateUnionTypeLookup(Type t) // need to get declaring type to avoid duplicate Unions in cache // hacky but I can't find an API to get the declaring type without GetUnionCases - object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); + object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!; object caseInfo = cases.First(); - Type unionType = (Type)FSharpUtils.GetUnionCaseInfoDeclaringType(caseInfo); + Type unionType = (Type)FSharpUtils.Instance.GetUnionCaseInfoDeclaringType(caseInfo)!; return unionType; } private static Union CreateUnion(Type t) { - Union u = new Union(); - - u.TagReader = (FSharpFunction)FSharpUtils.PreComputeUnionTagReader(null, t, null); - u.Cases = new List(); + Union u = new Union((FSharpFunction)FSharpUtils.Instance.PreComputeUnionTagReader(null, t, null), new List()); - object[] cases = (object[])FSharpUtils.GetUnionCases(null, t, null); + object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!; foreach (object unionCaseInfo in cases) { - UnionCase unionCase = new UnionCase(); - unionCase.Tag = (int)FSharpUtils.GetUnionCaseInfoTag(unionCaseInfo); - unionCase.Name = (string)FSharpUtils.GetUnionCaseInfoName(unionCaseInfo); - unionCase.Fields = (PropertyInfo[])FSharpUtils.GetUnionCaseInfoFields(unionCaseInfo); - unionCase.FieldReader = (FSharpFunction)FSharpUtils.PreComputeUnionReader(null, unionCaseInfo, null); - unionCase.Constructor = (FSharpFunction)FSharpUtils.PreComputeUnionConstructor(null, unionCaseInfo, null); + UnionCase unionCase = new UnionCase( + (int)FSharpUtils.Instance.GetUnionCaseInfoTag(unionCaseInfo), + (string)FSharpUtils.Instance.GetUnionCaseInfoName(unionCaseInfo), + (PropertyInfo[])FSharpUtils.Instance.GetUnionCaseInfoFields(unionCaseInfo)!, + (FSharpFunction)FSharpUtils.Instance.PreComputeUnionReader(null, unionCaseInfo, null), + (FSharpFunction)FSharpUtils.Instance.PreComputeUnionConstructor(null, unionCaseInfo, null)); u.Cases.Add(unionCase); } @@ -116,9 +131,15 @@ private static Union CreateUnion(Type t) /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + if (value == null) + { + writer.WriteNull(); + return; + } + + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; Type unionType = UnionTypeLookupCache.Get(value.GetType()); Union union = UnionCache.Get(unionType); @@ -131,7 +152,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteValue(caseInfo.Name); if (caseInfo.Fields != null && caseInfo.Fields.Length > 0) { - object[] fields = (object[])caseInfo.FieldReader.Invoke(value); + object[] fields = (object[])caseInfo.FieldReader.Invoke(value)!; writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName); writer.WriteStartArray(); @@ -152,30 +173,30 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } - UnionCase caseInfo = null; - string caseName = null; - JArray fields = null; + UnionCase? caseInfo = null; + string? caseName = null; + JArray? fields = null; // start object reader.ReadAndAssert(); while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadAndAssert(); Union union = UnionCache.Get(objectType); - caseName = reader.Value.ToString(); + caseName = reader.Value!.ToString(); caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName); @@ -207,7 +228,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName)); } - object[] typedFieldValues = new object[caseInfo.Fields.Length]; + object?[] typedFieldValues = new object?[caseInfo.Fields.Length]; if (caseInfo.Fields.Length > 0 && fields == null) { @@ -276,7 +297,7 @@ public override bool CanConvert(Type objectType) return false; } - return (bool)FSharpUtils.IsUnion(null, objectType, null); + return (bool)FSharpUtils.Instance.IsUnion(null, objectType, null); } } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index d1ab8dc3d..15bb8f964 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +35,7 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Converters { @@ -46,7 +50,7 @@ internal class EntityKeyMemberConverter : JsonConverter private const string TypePropertyName = "Type"; private const string ValuePropertyName = "Value"; - private static ReflectionObject _reflectionObject; + private static ReflectionObject? _reflectionObject; /// /// Writes the JSON representation of the object. @@ -54,16 +58,23 @@ internal class EntityKeyMemberConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { + if (value == null) + { + writer.WriteNull(); + return; + } + EnsureReflectionObject(value.GetType()); + MiscellaneousUtils.Assert(_reflectionObject != null); - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; - string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName); - object keyValue = _reflectionObject.GetValue(value, ValuePropertyName); + string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName)!; + object? keyValue = _reflectionObject.GetValue(value, ValuePropertyName); - Type keyValueType = keyValue?.GetType(); + Type? keyValueType = keyValue?.GetType(); writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName); @@ -75,7 +86,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s if (keyValueType != null) { - if (JsonSerializerInternalWriter.TryConvertToString(keyValue, keyValueType, out string valueJson)) + if (JsonSerializerInternalWriter.TryConvertToString(keyValue!, keyValueType, out string? valueJson)) { writer.WriteValue(valueJson); } @@ -96,7 +107,7 @@ private static void ReadAndAssertProperty(JsonReader reader, string propertyName { reader.ReadAndAssert(); - if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) + if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value?.ToString(), propertyName, StringComparison.OrdinalIgnoreCase)) { throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } @@ -110,19 +121,20 @@ private static void ReadAndAssertProperty(JsonReader reader, string propertyName /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { EnsureReflectionObject(objectType); + MiscellaneousUtils.Assert(_reflectionObject != null); - object entityKeyMember = _reflectionObject.Creator(); + object entityKeyMember = _reflectionObject.Creator!(); ReadAndAssertProperty(reader, KeyPropertyName); reader.ReadAndAssert(); - _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value.ToString()); + _reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value?.ToString()); ReadAndAssertProperty(reader, TypePropertyName); reader.ReadAndAssert(); - string type = reader.Value.ToString(); + string? type = reader.Value?.ToString(); Type t = Type.GetType(type); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index cb5f5ccf4..9ebcb269f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -50,7 +53,7 @@ internal class ExpandoObjectConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { // can write is set to false } @@ -63,12 +66,12 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { return ReadValue(reader); } - private object ReadValue(JsonReader reader) + private object? ReadValue(JsonReader reader) { if (!reader.MoveToContent()) { @@ -93,7 +96,7 @@ private object ReadValue(JsonReader reader) private object ReadList(JsonReader reader) { - IList list = new List(); + IList list = new List(); while (reader.Read()) { @@ -102,7 +105,7 @@ private object ReadList(JsonReader reader) case JsonToken.Comment: break; default: - object v = ReadValue(reader); + object? v = ReadValue(reader); list.Add(v); break; @@ -116,21 +119,21 @@ private object ReadList(JsonReader reader) private object ReadObject(JsonReader reader) { - IDictionary expandoObject = new ExpandoObject(); + IDictionary expandoObject = new ExpandoObject(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); } - object v = ReadValue(reader); + object? v = ReadValue(reader); expandoObject[propertyName] = v; break; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index 7b87fdc94..7b4a380f0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -41,8 +44,8 @@ internal class IsoDateTimeConverter : DateTimeConverterBase private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind; - private string _dateTimeFormat; - private CultureInfo _culture; + private string? _dateTimeFormat; + private CultureInfo? _culture; /// /// Gets or sets the date time styles used when converting a date to and from JSON. @@ -58,10 +61,10 @@ public DateTimeStyles DateTimeStyles /// Gets or sets the date time format used when converting a date to and from JSON. /// /// The date time format used when converting a date to and from JSON. - public string DateTimeFormat + public string? DateTimeFormat { get => _dateTimeFormat ?? string.Empty; - set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value; + set => _dateTimeFormat = (StringUtils.IsNullOrEmpty(value)) ? null : value; } /// @@ -80,7 +83,7 @@ public CultureInfo Culture /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { string text; @@ -108,7 +111,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s #endif else { - throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); + throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)!)); } writer.WriteValue(text); @@ -122,7 +125,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool nullable = ReflectionUtils.IsNullableType(objectType); if (reader.TokenType == JsonToken.Null) @@ -146,7 +149,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { - return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value); + return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value!); } // converter is expected to return a DateTime @@ -164,9 +167,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - string dateText = reader.Value.ToString(); + string? dateText = reader.Value?.ToString(); - if (string.IsNullOrEmpty(dateText) && nullable) + if (StringUtils.IsNullOrEmpty(dateText) && nullable) { return null; } @@ -174,7 +177,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist #if HAVE_DATE_TIME_OFFSET if (t == typeof(DateTimeOffset)) { - if (!string.IsNullOrEmpty(_dateTimeFormat)) + if (!StringUtils.IsNullOrEmpty(_dateTimeFormat)) { return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } @@ -185,7 +188,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } #endif - if (!string.IsNullOrEmpty(_dateTimeFormat)) + if (!StringUtils.IsNullOrEmpty(_dateTimeFormat)) { return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index d91183a99..cc1da2519 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal class JavaScriptDateTimeConverter : DateTimeConverterBase /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { long ticks; @@ -78,7 +81,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -90,12 +93,12 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return null; } - if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) { throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); } - if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string errorMessage)) + if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string? errorMessage)) { throw JsonSerializationException.Create(reader, errorMessage); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 65f65faf4..397a17e8c 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -60,11 +63,17 @@ private static ReflectionObject InitializeReflectionObject(Type t) /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { + if (value == null) + { + writer.WriteNull(); + return; + } + ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType()); - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName); @@ -82,7 +91,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -94,8 +103,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return null; } - object key = null; - object value = null; + object? key = null; + object? value = null; reader.ReadAndAssert(); @@ -109,7 +118,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist while (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase)) { reader.ReadForTypeAndAssert(keyContract, false); @@ -130,7 +139,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist reader.ReadAndAssert(); } - return reflectionObject.Creator(key, value); + return reflectionObject.Creator!(key, value); } /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/RegexConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/RegexConverter.cs index 9b2a14639..a0d9beff8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/RegexConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -51,7 +54,7 @@ internal class RegexConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -88,7 +91,7 @@ private void WriteBson(BsonWriter writer, Regex regex) // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode. - string options = null; + string? options = null; if (HasFlag(regex.Options, RegexOptions.IgnoreCase)) { @@ -118,7 +121,7 @@ private void WriteBson(BsonWriter writer, Regex regex) private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer) { - DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver; + DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver; writer.WriteStartObject(); writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName); @@ -136,7 +139,7 @@ private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { switch (reader.TokenType) { @@ -153,7 +156,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist private object ReadRegexString(JsonReader reader) { - string regexText = (string)reader.Value; + string regexText = (string)reader.Value!; if (regexText.Length > 0 && regexText[0] == '/') { @@ -175,7 +178,7 @@ private object ReadRegexString(JsonReader reader) private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) { - string pattern = null; + string? pattern = null; RegexOptions? options = null; while (reader.Read()) @@ -183,7 +186,7 @@ private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) switch (reader.TokenType) { case JsonToken.PropertyName: - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (!reader.Read()) { @@ -192,7 +195,7 @@ private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer) if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase)) { - pattern = (string)reader.Value; + pattern = (string?)reader.Value; } else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase)) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/StringEnumConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/StringEnumConverter.cs index ee720f630..7c9c5e146 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King @@ -86,7 +89,7 @@ public bool CamelCaseText /// Gets or sets the naming strategy used to resolve how enum text is written. /// /// The naming strategy used to resolve how enum text is written. - public NamingStrategy NamingStrategy { get; set; } + public NamingStrategy? NamingStrategy { get; set; } /// /// Gets or sets a value indicating whether integer values are allowed when serializing and deserializing. @@ -179,7 +182,7 @@ public StringEnumConverter(Type namingStrategyType, object[] namingStrategyParam /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -189,7 +192,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s Enum e = (Enum)value; - if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string enumName)) + if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string? enumName)) { if (!AllowIntegerValues) { @@ -213,7 +216,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -232,14 +235,14 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { if (reader.TokenType == JsonToken.String) { - string enumText = reader.Value.ToString(); + string? enumText = reader.Value?.ToString(); - if (enumText == string.Empty && isNullable) + if (StringUtils.IsNullOrEmpty(enumText) && isNullable) { return null; } - return EnumUtils.ParseEnum(t, NamingStrategy, enumText, !AllowIntegerValues); + return EnumUtils.ParseEnum(t, NamingStrategy, enumText!, !AllowIntegerValues); } if (reader.TokenType == JsonToken.Integer) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs index 36d84a50a..9f7a474c2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/UnixDateTimeConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -46,7 +49,7 @@ internal class UnixDateTimeConverter : DateTimeConverterBase /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { long seconds; @@ -81,7 +84,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool nullable = ReflectionUtils.IsNullable(objectType); if (reader.TokenType == JsonToken.Null) @@ -98,11 +101,11 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist if (reader.TokenType == JsonToken.Integer) { - seconds = (long)reader.Value; + seconds = (long)reader.Value!; } else if (reader.TokenType == JsonToken.String) { - if (!long.TryParse((string)reader.Value, out seconds)) + if (!long.TryParse((string)reader.Value!, out seconds)) { throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/VersionConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/VersionConverter.cs index 7657f16e7..2b16699af 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/VersionConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/VersionConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal class VersionConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -68,7 +71,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s /// The existing property value of the JSON that is being converted. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { @@ -80,7 +83,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { try { - Version v = new Version((string)reader.Value); + Version v = new Version((string)reader.Value!); return v; } catch (Exception ex) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 57d808e4a..46aa94dd2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -42,6 +45,7 @@ #endif using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Converters { @@ -57,44 +61,44 @@ public XmlDocumentWrapper(XmlDocument document) _document = document; } - public IXmlNode CreateComment(string data) + public IXmlNode CreateComment(string? data) { return new XmlNodeWrapper(_document.CreateComment(data)); } - public IXmlNode CreateTextNode(string text) + public IXmlNode CreateTextNode(string? text) { return new XmlNodeWrapper(_document.CreateTextNode(text)); } - public IXmlNode CreateCDataSection(string data) + public IXmlNode CreateCDataSection(string? data) { return new XmlNodeWrapper(_document.CreateCDataSection(data)); } - public IXmlNode CreateWhitespace(string text) + public IXmlNode CreateWhitespace(string? text) { return new XmlNodeWrapper(_document.CreateWhitespace(text)); } - public IXmlNode CreateSignificantWhitespace(string text) + public IXmlNode CreateSignificantWhitespace(string? text) { return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text)); } - public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) + public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) { return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone)); } #if HAVE_XML_DOCUMENT_TYPE - public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) + public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) { return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null)); } #endif - public IXmlNode CreateProcessingInstruction(string target, string data) + public IXmlNode CreateProcessingInstruction(string target, string? data) { return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data)); } @@ -109,7 +113,7 @@ public IXmlElement CreateElement(string qualifiedName, string namespaceUri) return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri)); } - public IXmlNode CreateAttribute(string name, string value) + public IXmlNode CreateAttribute(string name, string? value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name)); attribute.Value = value; @@ -117,7 +121,7 @@ public IXmlNode CreateAttribute(string name, string value) return attribute; } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) { XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri)); attribute.Value = value; @@ -125,7 +129,7 @@ public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, strin return attribute; } - public IXmlElement DocumentElement + public IXmlElement? DocumentElement { get { @@ -153,7 +157,7 @@ public void SetAttributeNode(IXmlNode attribute) { XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute; - _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode); + _element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode!); } public string GetPrefixOfNamespace(string namespaceUri) @@ -208,26 +212,26 @@ public XmlDocumentTypeWrapper(XmlDocumentType documentType) public string InternalSubset => _documentType.InternalSubset; - public override string LocalName => "DOCTYPE"; + public override string? LocalName => "DOCTYPE"; } #endif internal class XmlNodeWrapper : IXmlNode { private readonly XmlNode _node; - private List _childNodes; - private List _attributes; + private List? _childNodes; + private List? _attributes; public XmlNodeWrapper(XmlNode node) { _node = node; } - public object WrappedNode => _node; + public object? WrappedNode => _node; public XmlNodeType NodeType => _node.NodeType; - public virtual string LocalName => _node.LocalName; + public virtual string? LocalName => _node.LocalName; public List ChildNodes { @@ -313,7 +317,7 @@ private bool HasAttributes } } - public IXmlNode ParentNode + public IXmlNode? ParentNode { get { @@ -328,7 +332,7 @@ public IXmlNode ParentNode } } - public string Value + public string? Value { get => _node.Value; set => _node.Value = value; @@ -344,7 +348,7 @@ public IXmlNode AppendChild(IXmlNode newChild) return newChild; } - public string NamespaceUri => _node.NamespaceURI; + public string? NamespaceUri => _node.NamespaceURI; } #endif #endregion @@ -352,22 +356,22 @@ public IXmlNode AppendChild(IXmlNode newChild) #region Interfaces internal interface IXmlDocument : IXmlNode { - IXmlNode CreateComment(string text); - IXmlNode CreateTextNode(string text); - IXmlNode CreateCDataSection(string data); - IXmlNode CreateWhitespace(string text); - IXmlNode CreateSignificantWhitespace(string text); - IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone); + IXmlNode CreateComment(string? text); + IXmlNode CreateTextNode(string? text); + IXmlNode CreateCDataSection(string? data); + IXmlNode CreateWhitespace(string? text); + IXmlNode CreateSignificantWhitespace(string? text); + IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone); #if HAVE_XML_DOCUMENT_TYPE - IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset); + IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset); #endif - IXmlNode CreateProcessingInstruction(string target, string data); + IXmlNode CreateProcessingInstruction(string target, string? data); IXmlElement CreateElement(string elementName); IXmlElement CreateElement(string qualifiedName, string namespaceUri); - IXmlNode CreateAttribute(string name, string value); - IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value); + IXmlNode CreateAttribute(string name, string? value); + IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value); - IXmlElement DocumentElement { get; } + IXmlElement? DocumentElement { get; } } internal interface IXmlDeclaration : IXmlNode @@ -395,14 +399,14 @@ internal interface IXmlElement : IXmlNode internal interface IXmlNode { XmlNodeType NodeType { get; } - string LocalName { get; } + string? LocalName { get; } List ChildNodes { get; } List Attributes { get; } - IXmlNode ParentNode { get; } - string Value { get; set; } + IXmlNode? ParentNode { get; } + string? Value { get; set; } IXmlNode AppendChild(IXmlNode newChild); - string NamespaceUri { get; } - object WrappedNode { get; } + string? NamespaceUri { get; } + object? WrappedNode { get; } } #endregion @@ -453,12 +457,12 @@ public XDocumentTypeWrapper(XDocumentType documentType) public string InternalSubset => _documentType.InternalSubset; - public override string LocalName => "DOCTYPE"; + public override string? LocalName => "DOCTYPE"; } internal class XDocumentWrapper : XContainerWrapper, IXmlDocument { - private XDocument Document => (XDocument)WrappedNode; + private XDocument Document => (XDocument)WrappedNode!; public XDocumentWrapper(XDocument document) : base(document) @@ -492,42 +496,42 @@ protected override bool HasChildNodes } } - public IXmlNode CreateComment(string text) + public IXmlNode CreateComment(string? text) { return new XObjectWrapper(new XComment(text)); } - public IXmlNode CreateTextNode(string text) + public IXmlNode CreateTextNode(string? text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateCDataSection(string data) + public IXmlNode CreateCDataSection(string? data) { return new XObjectWrapper(new XCData(data)); } - public IXmlNode CreateWhitespace(string text) + public IXmlNode CreateWhitespace(string? text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateSignificantWhitespace(string text) + public IXmlNode CreateSignificantWhitespace(string? text) { return new XObjectWrapper(new XText(text)); } - public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone) + public IXmlNode CreateXmlDeclaration(string? version, string? encoding, string? standalone) { return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone)); } - public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset) + public IXmlNode CreateXmlDocumentType(string? name, string? publicId, string? systemId, string? internalSubset) { return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset)); } - public IXmlNode CreateProcessingInstruction(string target, string data) + public IXmlNode CreateProcessingInstruction(string target, string? data) { return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data)); } @@ -543,18 +547,18 @@ public IXmlElement CreateElement(string qualifiedName, string namespaceUri) return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri))); } - public IXmlNode CreateAttribute(string name, string value) + public IXmlNode CreateAttribute(string name, string? value) { return new XAttributeWrapper(new XAttribute(name, value)); } - public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value) + public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string? value) { string localName = MiscellaneousUtils.GetLocalName(qualifiedName); return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value)); } - public IXmlElement DocumentElement + public IXmlElement? DocumentElement { get { @@ -583,20 +587,20 @@ public override IXmlNode AppendChild(IXmlNode newChild) internal class XTextWrapper : XObjectWrapper { - private XText Text => (XText)WrappedNode; + private XText Text => (XText)WrappedNode!; public XTextWrapper(XText text) : base(text) { } - public override string Value + public override string? Value { get => Text.Value; set => Text.Value = value; } - public override IXmlNode ParentNode + public override IXmlNode? ParentNode { get { @@ -612,20 +616,20 @@ public override IXmlNode ParentNode internal class XCommentWrapper : XObjectWrapper { - private XComment Text => (XComment)WrappedNode; + private XComment Text => (XComment)WrappedNode!; public XCommentWrapper(XComment text) : base(text) { } - public override string Value + public override string? Value { get => Text.Value; set => Text.Value = value; } - public override IXmlNode ParentNode + public override IXmlNode? ParentNode { get { @@ -641,16 +645,16 @@ public override IXmlNode ParentNode internal class XProcessingInstructionWrapper : XObjectWrapper { - private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode; + private XProcessingInstruction ProcessingInstruction => (XProcessingInstruction)WrappedNode!; public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction) : base(processingInstruction) { } - public override string LocalName => ProcessingInstruction.Target; + public override string? LocalName => ProcessingInstruction.Target; - public override string Value + public override string? Value { get => ProcessingInstruction.Data; set => ProcessingInstruction.Data = value; @@ -659,9 +663,9 @@ public override string Value internal class XContainerWrapper : XObjectWrapper { - private List _childNodes; + private List? _childNodes; - private XContainer Container => (XContainer)WrappedNode; + private XContainer Container => (XContainer)WrappedNode!; public XContainerWrapper(XContainer container) : base(container) @@ -696,7 +700,7 @@ public override List ChildNodes protected virtual bool HasChildNodes => Container.LastNode != null; - public override IXmlNode ParentNode + public override IXmlNode? ParentNode { get { @@ -765,26 +769,26 @@ public override IXmlNode AppendChild(IXmlNode newChild) internal class XObjectWrapper : IXmlNode { - private readonly XObject _xmlObject; + private readonly XObject? _xmlObject; - public XObjectWrapper(XObject xmlObject) + public XObjectWrapper(XObject? xmlObject) { _xmlObject = xmlObject; } - public object WrappedNode => _xmlObject; + public object? WrappedNode => _xmlObject; - public virtual XmlNodeType NodeType => _xmlObject.NodeType; + public virtual XmlNodeType NodeType => _xmlObject?.NodeType ?? XmlNodeType.None; - public virtual string LocalName => null; + public virtual string? LocalName => null; public virtual List ChildNodes => XmlNodeConverter.EmptyChildNodes; public virtual List Attributes => XmlNodeConverter.EmptyChildNodes; - public virtual IXmlNode ParentNode => null; + public virtual IXmlNode? ParentNode => null; - public virtual string Value + public virtual string? Value { get => null; set => throw new InvalidOperationException(); @@ -795,29 +799,29 @@ public virtual IXmlNode AppendChild(IXmlNode newChild) throw new InvalidOperationException(); } - public virtual string NamespaceUri => null; + public virtual string? NamespaceUri => null; } internal class XAttributeWrapper : XObjectWrapper { - private XAttribute Attribute => (XAttribute)WrappedNode; + private XAttribute Attribute => (XAttribute)WrappedNode!; public XAttributeWrapper(XAttribute attribute) : base(attribute) { } - public override string Value + public override string? Value { get => Attribute.Value; set => Attribute.Value = value; } - public override string LocalName => Attribute.Name.LocalName; + public override string? LocalName => Attribute.Name.LocalName; - public override string NamespaceUri => Attribute.Name.NamespaceName; + public override string? NamespaceUri => Attribute.Name.NamespaceName; - public override IXmlNode ParentNode + public override IXmlNode? ParentNode { get { @@ -833,9 +837,9 @@ public override IXmlNode ParentNode internal class XElementWrapper : XContainerWrapper, IXmlElement { - private List _attributes; + private List? _attributes; - private XElement Element => (XElement)WrappedNode; + private XElement Element => (XElement)WrappedNode!; public XElementWrapper(XElement element) : base(element) @@ -857,7 +861,7 @@ public override List Attributes // cache results to prevent multiple reads which kills perf in large documents if (_attributes == null) { - if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri)) + if (!Element.HasAttributes && !HasImplicitNamespaceAttribute(NamespaceUri!)) { _attributes = XmlNodeConverter.EmptyChildNodes; } @@ -871,7 +875,7 @@ public override List Attributes // ensure elements created with a namespace but no namespace attribute are converted correctly // e.g. new XElement("{http://example.com}MyElement"); - string namespaceUri = NamespaceUri; + string namespaceUri = NamespaceUri!; if (HasImplicitNamespaceAttribute(namespaceUri)) { _attributes.Insert(0, new XAttributeWrapper(new XAttribute("xmlns", namespaceUri))); @@ -885,9 +889,9 @@ public override List Attributes private bool HasImplicitNamespaceAttribute(string namespaceUri) { - if (!string.IsNullOrEmpty(namespaceUri) && namespaceUri != ParentNode?.NamespaceUri) + if (!StringUtils.IsNullOrEmpty(namespaceUri) && namespaceUri != ParentNode?.NamespaceUri) { - if (string.IsNullOrEmpty(GetPrefixOfNamespace(namespaceUri))) + if (StringUtils.IsNullOrEmpty(GetPrefixOfNamespace(namespaceUri))) { bool namespaceDeclared = false; @@ -895,7 +899,7 @@ private bool HasImplicitNamespaceAttribute(string namespaceUri) { foreach (XAttribute attribute in Element.Attributes()) { - if (attribute.Name.LocalName == "xmlns" && string.IsNullOrEmpty(attribute.Name.NamespaceName) && attribute.Value == namespaceUri) + if (attribute.Name.LocalName == "xmlns" && StringUtils.IsNullOrEmpty(attribute.Name.NamespaceName) && attribute.Value == namespaceUri) { namespaceDeclared = true; } @@ -919,15 +923,15 @@ public override IXmlNode AppendChild(IXmlNode newChild) return result; } - public override string Value + public override string? Value { get => Element.Value; set => Element.Value = value; } - public override string LocalName => Element.Name.LocalName; + public override string? LocalName => Element.Name.LocalName; - public override string NamespaceUri => Element.Name.NamespaceName; + public override string? NamespaceUri => Element.Name.NamespaceName; public string GetPrefixOfNamespace(string namespaceUri) { @@ -958,7 +962,7 @@ internal class XmlNodeConverter : JsonConverter /// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produced multiple root elements. /// /// The name of the deserialized root element. - public string DeserializeRootElementName { get; set; } + public string? DeserializeRootElementName { get; set; } /// /// Gets or sets a value to indicate whether to write the Json.NET array attribute. @@ -989,7 +993,7 @@ internal class XmlNodeConverter : JsonConverter /// The to write to. /// The calling serializer. /// The value. - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value == null) { @@ -1035,9 +1039,9 @@ private IXmlNode WrapXml(object value) private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) { - List parentElements = null; + List? parentElements = null; - IXmlNode parent = node; + IXmlNode? parent = node; while ((parent = parent.ParentNode) != null) { if (parent.NodeType == XmlNodeType.Element) @@ -1071,11 +1075,11 @@ private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager) private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager) { - string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) + string? prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/")) ? null : manager.LookupPrefix(node.NamespaceUri); - if (!string.IsNullOrEmpty(prefix)) + if (!StringUtils.IsNullOrEmpty(prefix)) { return prefix + ":" + XmlConvert.DecodeName(node.LocalName); } @@ -1164,9 +1168,9 @@ private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespac // value of dictionary will be a single IXmlNode when there is one for a name, // or a List when there are multiple - Dictionary nodesGroupedByName = null; + Dictionary? nodesGroupedByName = null; - string nodeName = null; + string? nodeName = null; for (int i = 0; i < node.ChildNodes.Count; i++) { @@ -1212,7 +1216,7 @@ private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespac { if (!(value is List nodes)) { - nodes = new List {(IXmlNode)value}; + nodes = new List {(IXmlNode)value!}; nodesGroupedByName[currentNodeName] = nodes; } @@ -1223,7 +1227,7 @@ private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespac if (nodesGroupedByName == null) { - WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName); + WriteGroupedNodes(writer, manager, writePropertyName, node.ChildNodes, nodeName!); } else { @@ -1319,7 +1323,11 @@ private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager string namespacePrefix = (attribute.LocalName != "xmlns") ? XmlConvert.DecodeName(attribute.LocalName) : string.Empty; - string namespaceUri = attribute.Value; + string? namespaceUri = attribute.Value; + if (namespaceUri == null) + { + throw new JsonSerializationException("Namespace attribute must have a value."); + } manager.AddNamespace(namespacePrefix, namespaceUri); } @@ -1404,17 +1412,17 @@ private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); - if (!string.IsNullOrEmpty(declaration.Version)) + if (!StringUtils.IsNullOrEmpty(declaration.Version)) { writer.WritePropertyName("@version"); writer.WriteValue(declaration.Version); } - if (!string.IsNullOrEmpty(declaration.Encoding)) + if (!StringUtils.IsNullOrEmpty(declaration.Encoding)) { writer.WritePropertyName("@encoding"); writer.WriteValue(declaration.Encoding); } - if (!string.IsNullOrEmpty(declaration.Standalone)) + if (!StringUtils.IsNullOrEmpty(declaration.Standalone)) { writer.WritePropertyName("@standalone"); writer.WriteValue(declaration.Standalone); @@ -1427,22 +1435,22 @@ private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager writer.WritePropertyName(GetPropertyName(node, manager)); writer.WriteStartObject(); - if (!string.IsNullOrEmpty(documentType.Name)) + if (!StringUtils.IsNullOrEmpty(documentType.Name)) { writer.WritePropertyName("@name"); writer.WriteValue(documentType.Name); } - if (!string.IsNullOrEmpty(documentType.Public)) + if (!StringUtils.IsNullOrEmpty(documentType.Public)) { writer.WritePropertyName("@public"); writer.WriteValue(documentType.Public); } - if (!string.IsNullOrEmpty(documentType.System)) + if (!StringUtils.IsNullOrEmpty(documentType.System)) { writer.WritePropertyName("@system"); writer.WriteValue(documentType.System); } - if (!string.IsNullOrEmpty(documentType.InternalSubset)) + if (!StringUtils.IsNullOrEmpty(documentType.InternalSubset)) { writer.WritePropertyName("@internalSubset"); writer.WriteValue(documentType.InternalSubset); @@ -1477,7 +1485,7 @@ private static bool AllSameName(IXmlNode node) /// The existing value of object being read. /// The calling serializer. /// The object value. - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { switch (reader.TokenType) { @@ -1490,8 +1498,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist } XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); - IXmlDocument document = null; - IXmlNode rootNode = null; + IXmlDocument? document = null; + IXmlNode? rootNode = null; #if HAVE_XLINQ if (typeof(XObject).IsAssignableFrom(objectType)) @@ -1536,7 +1544,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist throw JsonSerializationException.Create(reader, "Unexpected type when converting XML: " + objectType); } - if (!string.IsNullOrEmpty(DeserializeRootElementName)) + if (!StringUtils.IsNullOrEmpty(DeserializeRootElementName)) { ReadElement(reader, document, rootNode, DeserializeRootElementName, manager); } @@ -1549,7 +1557,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist #if HAVE_XLINQ if (objectType == typeof(XElement)) { - XElement element = (XElement)document.DocumentElement.WrappedNode; + XElement element = (XElement)document.DocumentElement!.WrappedNode!; element.Remove(); return element; @@ -1558,7 +1566,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist #if HAVE_XML_DOCUMENT if (objectType == typeof(XmlElement)) { - return document.DocumentElement.WrappedNode; + return document.DocumentElement!.WrappedNode; } #endif @@ -1585,7 +1593,7 @@ private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNames return; default: // processing instructions and the xml declaration start with ? - if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?') + if (!StringUtils.IsNullOrEmpty(propertyName) && propertyName[0] == '?') { CreateInstruction(reader, document, currentNode, propertyName); return; @@ -1615,13 +1623,13 @@ private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNames private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager) { - if (string.IsNullOrEmpty(propertyName)) + if (StringUtils.IsNullOrEmpty(propertyName)) { throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML."); } - Dictionary attributeNameValues = null; - string elementPrefix = null; + Dictionary? attributeNameValues = null; + string? elementPrefix = null; if (!EncodeSpecialCharacters) { @@ -1633,7 +1641,7 @@ private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode curr if (propertyName.StartsWith('@')) { string attributeName = propertyName.Substring(1); - string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); + string? attributePrefix = MiscellaneousUtils.GetPrefix(attributeName); AddAttribute(reader, document, currentNode, propertyName, attributeName, manager, attributePrefix); return; @@ -1670,7 +1678,7 @@ private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode curr CreateElement(reader, document, currentNode, propertyName, manager, elementPrefix, attributeNameValues); } - private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string elementPrefix, Dictionary attributeNameValues) + private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string elementName, XmlNamespaceManager manager, string? elementPrefix, Dictionary? attributeNameValues) { IXmlElement element = CreateElement(elementName, document, elementPrefix, manager); @@ -1679,12 +1687,12 @@ private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode cu if (attributeNameValues != null) { // add attributes to newly created element - foreach (KeyValuePair nameValue in attributeNameValues) + foreach (KeyValuePair nameValue in attributeNameValues) { string encodedName = XmlConvert.EncodeName(nameValue.Key); - string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); + string? attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key); - IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); + IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value) : document.CreateAttribute(encodedName, nameValue.Value); element.SetAttributeNode(attribute); } @@ -1698,7 +1706,7 @@ private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode cu case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: - string text = ConvertTokenToXmlValue(reader); + string? text = ConvertTokenToXmlValue(reader); if (text != null) { element.AppendChild(document.CreateTextNode(text)); @@ -1722,7 +1730,7 @@ private void CreateElement(JsonReader reader, IXmlDocument document, IXmlNode cu } } - private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string attributePrefix) + private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, string attributeName, XmlNamespaceManager manager, string? attributePrefix) { if (currentNode.NodeType == XmlNodeType.Document) { @@ -1730,16 +1738,16 @@ private static void AddAttribute(JsonReader reader, IXmlDocument document, IXmlN } string encodedName = XmlConvert.EncodeName(attributeName); - string attributeValue = ConvertTokenToXmlValue(reader); + string? attributeValue = ConvertTokenToXmlValue(reader); - IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix)) + IXmlNode attribute = (!StringUtils.IsNullOrEmpty(attributePrefix)) ? document.CreateAttribute(encodedName, manager.LookupNamespace(attributePrefix), attributeValue) : document.CreateAttribute(encodedName, attributeValue); ((IXmlElement)currentNode).SetAttributeNode(attribute); } - private static string ConvertTokenToXmlValue(JsonReader reader) + private static string? ConvertTokenToXmlValue(JsonReader reader) { switch (reader.TokenType) { @@ -1786,7 +1794,7 @@ private static string ConvertTokenToXmlValue(JsonReader reader) #endif } case JsonToken.Bytes: - return Convert.ToBase64String((byte[])reader.Value); + return Convert.ToBase64String((byte[])reader.Value!); case JsonToken.Null: return null; default: @@ -1796,7 +1804,7 @@ private static string ConvertTokenToXmlValue(JsonReader reader) private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager) { - string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); + string? elementPrefix = MiscellaneousUtils.GetPrefix(propertyName); IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager); @@ -1862,9 +1870,9 @@ private bool ShouldReadInto(JsonReader reader) return true; } - private Dictionary ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) + private Dictionary? ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager) { - Dictionary attributeNameValues = null; + Dictionary? attributeNameValues = null; bool finished = false; // read properties until first non-attribute is encountered @@ -1873,19 +1881,19 @@ private Dictionary ReadAttributeElements(JsonReader reader, XmlN switch (reader.TokenType) { case JsonToken.PropertyName: - string attributeName = reader.Value.ToString(); + string attributeName = reader.Value!.ToString(); - if (!string.IsNullOrEmpty(attributeName)) + if (!StringUtils.IsNullOrEmpty(attributeName)) { char firstChar = attributeName[0]; - string attributeValue; + string? attributeValue; switch (firstChar) { case '@': if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } attributeName = attributeName.Substring(1); @@ -1893,7 +1901,7 @@ private Dictionary ReadAttributeElements(JsonReader reader, XmlN attributeValue = ConvertTokenToXmlValue(reader); attributeNameValues.Add(attributeName, attributeValue); - if (IsNamespaceAttribute(attributeName, out string namespacePrefix)) + if (IsNamespaceAttribute(attributeName, out string? namespacePrefix)) { manager.AddNamespace(namespacePrefix, attributeValue); } @@ -1913,7 +1921,7 @@ private Dictionary ReadAttributeElements(JsonReader reader, XmlN { if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } // ensure that the prefix used is free @@ -1945,7 +1953,7 @@ private Dictionary ReadAttributeElements(JsonReader reader, XmlN if (attributeNameValues == null) { - attributeNameValues = new Dictionary(); + attributeNameValues = new Dictionary(); } attributeValue = reader.Value?.ToString(); @@ -1983,12 +1991,12 @@ private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNod { if (propertyName == DeclarationName) { - string version = null; - string encoding = null; - string standalone = null; + string? version = null; + string? encoding = null; + string? standalone = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { - switch (reader.Value.ToString()) + switch (reader.Value?.ToString()) { case "@version": reader.ReadAndAssert(); @@ -2020,13 +2028,13 @@ private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNod #if HAVE_XML_DOCUMENT_TYPE private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode) { - string name = null; - string publicId = null; - string systemId = null; - string internalSubset = null; + string? name = null; + string? publicId = null; + string? systemId = null; + string? internalSubset = null; while (reader.Read() && reader.TokenType != JsonToken.EndObject) { - switch (reader.Value.ToString()) + switch (reader.Value?.ToString()) { case "@name": reader.ReadAndAssert(); @@ -2054,12 +2062,12 @@ private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNo } #endif - private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager) + private IXmlElement CreateElement(string elementName, IXmlDocument document, string? elementPrefix, XmlNamespaceManager manager) { string encodeName = EncodeSpecialCharacters ? XmlConvert.EncodeLocalName(elementName) : XmlConvert.EncodeName(elementName); - string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); - IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); + IXmlElement element = (!StringUtils.IsNullOrEmpty(ns)) ? document.CreateElement(encodeName, ns) : document.CreateElement(encodeName); return element; } @@ -2076,7 +2084,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp throw JsonSerializationException.Create(reader, "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifying a DeserializeRootElementName."); } - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); reader.ReadAndAssert(); if (reader.TokenType == JsonToken.StartArray) @@ -2090,8 +2098,8 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp if (count == 1 && WriteArrayAttribute) { - MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string elementPrefix, out string localName); - string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); + MiscellaneousUtils.GetQualifiedNameParts(propertyName, out string? elementPrefix, out string localName); + string ns = StringUtils.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix); foreach (IXmlNode childNode in currentNode.ChildNodes) { @@ -2109,7 +2117,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp } continue; case JsonToken.StartConstructor: - string constructorName = reader.Value.ToString(); + string constructorName = reader.Value!.ToString(); while (reader.Read() && reader.TokenType != JsonToken.EndConstructor) { @@ -2117,7 +2125,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp } break; case JsonToken.Comment: - currentNode.AppendChild(document.CreateComment((string)reader.Value)); + currentNode.AppendChild(document.CreateComment((string)reader.Value!)); break; case JsonToken.EndObject: case JsonToken.EndArray: @@ -2135,7 +2143,7 @@ private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamesp /// Attribute name to test. /// The attribute name prefix if it has one, otherwise an empty string. /// true if attribute name is for a namespace attribute, otherwise false. - private bool IsNamespaceAttribute(string attributeName, out string prefix) + private bool IsNamespaceAttribute(string attributeName, [NotNullWhen(true)]out string? prefix) { if (attributeName.StartsWith("xmlns", StringComparison.Ordinal)) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateFormatHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateFormatHandling.cs index 00c341010..14f8fe9b8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateFormatHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateFormatHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateParseHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateParseHandling.cs index 11bcd79f2..c306d24f5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateParseHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateParseHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,14 +43,14 @@ internal enum DateParseHandling None = 0, /// - /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . /// DateTime = 1, #if HAVE_DATE_TIME_OFFSET /// - /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . + /// Date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed to . /// DateTimeOffset = 2 #endif } -} \ No newline at end of file +} diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateTimeZoneHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateTimeZoneHandling.cs index f6ad6b792..fab2166c9 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateTimeZoneHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DateTimeZoneHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultJsonNameTable.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultJsonNameTable.cs index 0d68f7c20..9df246226 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultJsonNameTable.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultJsonNameTable.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -63,7 +66,7 @@ public DefaultJsonNameTable() /// The zero-based index into the array specifying the first character of the name. /// The number of characters in the name. /// A string containing the same characters as the specified range of characters in the given array. - public override string Get(char[] key, int start, int length) + public override string? Get(char[] key, int start, int length) { if (length == 0) { @@ -125,7 +128,7 @@ public string Add(string key) hashCode -= hashCode >> 5; for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next) { - if (entry.HashCode == hashCode && entry.Value.Equals(key)) + if (entry.HashCode == hashCode && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultValueHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultValueHandling.cs index c62c65b60..b72b4cbbc 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultValueHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/DefaultValueHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatFormatHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatFormatHandling.cs index decd47711..dce53e28a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatFormatHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatFormatHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatParseHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatParseHandling.cs index f5b52816a..07f2b6535 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatParseHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FloatParseHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FormatterAssemblyStyle.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FormatterAssemblyStyle.cs index 70ddf6adb..bee7c519e 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FormatterAssemblyStyle.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/FormatterAssemblyStyle.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #if HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Formatting.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Formatting.cs index 03e69d344..8c7830881 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Formatting.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Formatting.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IArrayPool.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IArrayPool.cs index 1a48d5105..ebd0ac923 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IArrayPool.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IArrayPool.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable namespace Datadog.Trace.Vendors.Newtonsoft.Json { /// @@ -21,6 +24,6 @@ internal interface IArrayPool /// Return an array to the pool. /// /// The array that is being returned. - void Return(T[] array); + void Return(T[]? array); } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IJsonLineInfo.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IJsonLineInfo.cs index aa71b0716..0aba21594 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IJsonLineInfo.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/IJsonLineInfo.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonArrayAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonArrayAttribute.cs index 8cc35c7b5..f0eea4d65 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonArrayAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonArrayAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConstructorAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConstructorAttribute.cs index 536005af1..cf9b9814c 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConstructorAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConstructorAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonContainerAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonContainerAttribute.cs index 91082dffd..882b7376f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonContainerAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonContainerAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -42,25 +45,25 @@ internal abstract class JsonContainerAttribute : Attribute /// Gets or sets the id. /// /// The id. - public string Id { get; set; } + public string? Id { get; set; } /// /// Gets or sets the title. /// /// The title. - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the description. /// /// The description. - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the collection's items converter. /// /// The collection's items converter. - public Type ItemConverterType { get; set; } + public Type? ItemConverterType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -73,13 +76,13 @@ internal abstract class JsonContainerAttribute : Attribute /// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// /// - public object[] ItemConverterParameters { get; set; } + public object[]? ItemConverterParameters { get; set; } /// /// Gets or sets the of the . /// /// The of the . - public Type NamingStrategyType + public Type? NamingStrategyType { get => _namingStrategyType; set @@ -100,7 +103,7 @@ public Type NamingStrategyType /// [JsonContainer(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })] /// /// - public object[] NamingStrategyParameters + public object[]? NamingStrategyParameters { get => _namingStrategyParameters; set @@ -110,7 +113,7 @@ public object[] NamingStrategyParameters } } - internal NamingStrategy NamingStrategyInstance { get; set; } + internal NamingStrategy? NamingStrategyInstance { get; set; } // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state @@ -118,8 +121,8 @@ public object[] NamingStrategyParameters internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; - private Type _namingStrategyType; - private object[] _namingStrategyParameters; + private Type? _namingStrategyType; + private object[]? _namingStrategyParameters; /// /// Gets or sets a value that indicates whether to preserve object references. diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConvert.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConvert.cs index ef8b626b3..bacd3895e 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConvert.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConvert.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,9 +43,10 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; using System.Text; using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if HAVE_XLINQ using System.Xml.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json @@ -62,7 +66,7 @@ internal static class JsonConvert /// To serialize without using any default settings create a with /// . /// - public static System.Func DefaultSettings { get; set; } + public static System.Func? DefaultSettings { get; set; } /// /// Represents JavaScript's boolean value true as a string. This field is read-only. @@ -348,7 +352,7 @@ public static string ToString(sbyte value) /// Converts the to its JSON string representation. /// /// The value to convert. - /// A JSON string representation of the . + /// A JSON string representation of the . public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); @@ -399,7 +403,7 @@ internal static string ToString(TimeSpan value, char quoteChar) /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(Uri value) + public static string ToString(Uri? value) { if (value == null) { @@ -419,7 +423,7 @@ internal static string ToString(Uri value, char quoteChar) /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(string value) + public static string ToString(string? value) { return ToString(value, '"'); } @@ -430,7 +434,7 @@ public static string ToString(string value) /// The value to convert. /// The string delimiter character. /// A JSON string representation of the . - public static string ToString(string value, char delimiter) + public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } @@ -442,7 +446,7 @@ public static string ToString(string value, char delimiter) /// The string delimiter character. /// The string escape handling. /// A JSON string representation of the . - public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) + public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { @@ -457,7 +461,7 @@ public static string ToString(string value, char delimiter, StringEscapeHandling /// /// The value to convert. /// A JSON string representation of the . - public static string ToString(object value) + public static string ToString(object? value) { if (value == null) { @@ -528,9 +532,9 @@ public static string ToString(object value) /// The object to serialize. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object value) + public static string SerializeObject(object? value) { - return SerializeObject(value, null, (JsonSerializerSettings)null); + return SerializeObject(value, null, (JsonSerializerSettings?)null); } /// @@ -542,9 +546,9 @@ public static string SerializeObject(object value) /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object value, Formatting formatting) + public static string SerializeObject(object? value, Formatting formatting) { - return SerializeObject(value, formatting, (JsonSerializerSettings)null); + return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } /// @@ -554,9 +558,9 @@ public static string SerializeObject(object value, Formatting formatting) /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object value, params JsonConverter[] converters) + public static string SerializeObject(object? value, params JsonConverter[] converters) { - JsonSerializerSettings settings = (converters != null && converters.Length > 0) + JsonSerializerSettings? settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -571,9 +575,9 @@ public static string SerializeObject(object value, params JsonConverter[] conver /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] - public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) + public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { - JsonSerializerSettings settings = (converters != null && converters.Length > 0) + JsonSerializerSettings? settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -590,7 +594,7 @@ public static string SerializeObject(object value, Formatting formatting, params /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object value, JsonSerializerSettings settings) + public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } @@ -610,7 +614,7 @@ public static string SerializeObject(object value, JsonSerializerSettings settin /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object value, Type type, JsonSerializerSettings settings) + public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -628,7 +632,7 @@ public static string SerializeObject(object value, Type type, JsonSerializerSett /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) + public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } @@ -649,7 +653,7 @@ public static string SerializeObject(object value, Formatting formatting, JsonSe /// A JSON string representation of the object. /// [DebuggerStepThrough] - public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) + public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; @@ -657,7 +661,7 @@ public static string SerializeObject(object value, Type type, Formatting formatt return SerializeObjectInternal(value, type, jsonSerializer); } - private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer) + private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringBuilder sb = new StringBuilder(256); StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); @@ -679,9 +683,9 @@ private static string SerializeObjectInternal(object value, Type type, JsonSeria /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object DeserializeObject(string value) + public static object? DeserializeObject(string value) { - return DeserializeObject(value, null, (JsonSerializerSettings)null); + return DeserializeObject(value, null, (JsonSerializerSettings?)null); } /// @@ -694,7 +698,7 @@ public static object DeserializeObject(string value) /// /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object DeserializeObject(string value, JsonSerializerSettings settings) + public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } @@ -706,9 +710,9 @@ public static object DeserializeObject(string value, JsonSerializerSettings sett /// The of object being deserialized. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object DeserializeObject(string value, Type type) + public static object? DeserializeObject(string value, Type type) { - return DeserializeObject(value, type, (JsonSerializerSettings)null); + return DeserializeObject(value, type, (JsonSerializerSettings?)null); } /// @@ -718,9 +722,9 @@ public static object DeserializeObject(string value, Type type) /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T DeserializeObject(string value) + public static T? DeserializeObject(string value) { - return DeserializeObject(value, (JsonSerializerSettings)null); + return DeserializeObject(value, (JsonSerializerSettings?)null); } /// @@ -735,7 +739,7 @@ public static T DeserializeObject(string value) /// The anonymous type object. /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] - public static T DeserializeAnonymousType(string value, T anonymousTypeObject) + public static T? DeserializeAnonymousType(string value, T anonymousTypeObject) { return DeserializeObject(value); } @@ -756,7 +760,7 @@ public static T DeserializeAnonymousType(string value, T anonymousTypeObject) /// /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] - public static T DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) + public static T? DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject(value, settings); } @@ -769,9 +773,9 @@ public static T DeserializeAnonymousType(string value, T anonymousTypeObject, /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T DeserializeObject(string value, params JsonConverter[] converters) + public static T? DeserializeObject(string value, params JsonConverter[] converters) { - return (T)DeserializeObject(value, typeof(T), converters); + return (T?)DeserializeObject(value, typeof(T), converters); } /// @@ -785,9 +789,9 @@ public static T DeserializeObject(string value, params JsonConverter[] conver /// /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static T DeserializeObject(string value, JsonSerializerSettings settings) + public static T? DeserializeObject(string value, JsonSerializerSettings? settings) { - return (T)DeserializeObject(value, typeof(T), settings); + return (T?)DeserializeObject(value, typeof(T), settings); } /// @@ -798,9 +802,9 @@ public static T DeserializeObject(string value, JsonSerializerSettings settin /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] - public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) + public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { - JsonSerializerSettings settings = (converters != null && converters.Length > 0) + JsonSerializerSettings? settings = (converters != null && converters.Length > 0) ? new JsonSerializerSettings { Converters = converters } : null; @@ -817,7 +821,7 @@ public static object DeserializeObject(string value, Type type, params JsonConve /// If this is null, default serialization settings will be used. /// /// The deserialized object from the JSON string. - public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) + public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -857,7 +861,7 @@ public static void PopulateObject(string value, object target) /// The used to deserialize the object. /// If this is null, default serialization settings will be used. /// - public static void PopulateObject(string value, object target, JsonSerializerSettings settings) + public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -886,7 +890,7 @@ public static void PopulateObject(string value, object target, JsonSerializerSet /// /// The node to serialize. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode node) + public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } @@ -897,7 +901,7 @@ public static string SerializeXmlNode(XmlNode node) /// The node to serialize. /// Indicates how the output should be formatted. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode node, Formatting formatting) + public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter converter = new XmlNodeConverter(); @@ -911,7 +915,7 @@ public static string SerializeXmlNode(XmlNode node, Formatting formatting) /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . - public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject) + public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -923,7 +927,7 @@ public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool /// /// The JSON string. /// The deserialized . - public static XmlDocument DeserializeXmlNode(string value) + public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } @@ -934,7 +938,7 @@ public static XmlDocument DeserializeXmlNode(string value) /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . - public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName) + public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, false); } @@ -950,7 +954,7 @@ public static XmlDocument DeserializeXmlNode(string value, string deserializeRoo /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . - public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute) + public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false); } @@ -972,14 +976,14 @@ public static XmlDocument DeserializeXmlNode(string value, string deserializeRoo /// as part of the XML element name. /// /// The deserialized . - public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) + public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; converter.EncodeSpecialCharacters = encodeSpecialCharacters; - return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), converter); + return (XmlDocument?)DeserializeObject(value, typeof(XmlDocument), converter); } #endif @@ -989,7 +993,7 @@ public static XmlDocument DeserializeXmlNode(string value, string deserializeRoo /// /// The node to convert to JSON. /// A JSON string of the . - public static string SerializeXNode(XObject node) + public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } @@ -1000,7 +1004,7 @@ public static string SerializeXNode(XObject node) /// The node to convert to JSON. /// Indicates how the output should be formatted. /// A JSON string of the . - public static string SerializeXNode(XObject node, Formatting formatting) + public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, false); } @@ -1012,7 +1016,7 @@ public static string SerializeXNode(XObject node, Formatting formatting) /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . - public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject) + public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -1024,7 +1028,7 @@ public static string SerializeXNode(XObject node, Formatting formatting, bool om /// /// The JSON string. /// The deserialized . - public static XDocument DeserializeXNode(string value) + public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } @@ -1035,7 +1039,7 @@ public static XDocument DeserializeXNode(string value) /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . - public static XDocument DeserializeXNode(string value, string deserializeRootElementName) + public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, false); } @@ -1051,7 +1055,7 @@ public static XDocument DeserializeXNode(string value, string deserializeRootEle /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . - public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute) + public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false); } @@ -1073,16 +1077,16 @@ public static XDocument DeserializeXNode(string value, string deserializeRootEle /// as part of the XML element name. /// /// The deserialized . - public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) + public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); converter.DeserializeRootElementName = deserializeRootElementName; converter.WriteArrayAttribute = writeArrayAttribute; converter.EncodeSpecialCharacters = encodeSpecialCharacters; - return (XDocument)DeserializeObject(value, typeof(XDocument), converter); + return (XDocument?)DeserializeObject(value, typeof(XDocument), converter); } #endif #endregion } -} \ No newline at end of file +} diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverter.cs index c7693ecd5..35049d458 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +33,8 @@ using System; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json { @@ -44,7 +49,7 @@ internal abstract class JsonConverter /// The to write to. /// The value. /// The calling serializer. - public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer); + public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); /// /// Reads the JSON representation of the object. @@ -54,7 +59,7 @@ internal abstract class JsonConverter /// The existing value of object being read. /// The calling serializer. /// The object value. - public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer); + public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); /// /// Determines whether this instance can convert the specified object type. @@ -90,13 +95,13 @@ internal abstract class JsonConverter : JsonConverter /// The to write to. /// The value. /// The calling serializer. - public sealed override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!(value != null ? value is T : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } - WriteJson(writer, (T)value, serializer); + WriteJson(writer, (T?)value, serializer); } /// @@ -105,7 +110,7 @@ public sealed override void WriteJson(JsonWriter writer, object value, JsonSeria /// The to write to. /// The value. /// The calling serializer. - public abstract void WriteJson(JsonWriter writer, T value, JsonSerializer serializer); + public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); /// /// Reads the JSON representation of the object. @@ -115,14 +120,14 @@ public sealed override void WriteJson(JsonWriter writer, object value, JsonSeria /// The existing value of object being read. /// The calling serializer. /// The object value. - public sealed override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool existingIsNull = existingValue == null; if (!(existingIsNull || existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } - return ReadJson(reader, objectType, existingIsNull ? default : (T)existingValue, !existingIsNull, serializer); + return ReadJson(reader, objectType, existingIsNull ? default : (T?)existingValue, !existingIsNull, serializer); } /// @@ -134,7 +139,7 @@ public sealed override object ReadJson(JsonReader reader, Type objectType, objec /// The existing value has a value. /// The calling serializer. /// The object value. - public abstract T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer); + public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); /// /// Determines whether this instance can convert the specified object type. diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterAttribute.cs index c0151ff22..f338189c8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -51,7 +54,7 @@ internal sealed class JsonConverterAttribute : Attribute /// The parameter list to use when constructing the described by . /// If null, the default constructor is used. /// - public object[] ConverterParameters { get; } + public object[]? ConverterParameters { get; } /// /// Initializes a new instance of the class. diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterCollection.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterCollection.cs index fd9f6da89..9adde39c9 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterCollection.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonConverterCollection.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonDictionaryAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonDictionaryAttribute.cs index 258a15eea..bd6163c35 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonDictionaryAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonDictionaryAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonException.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonException.cs index 0ef74c6a7..56df1866a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonException.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonException.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -67,7 +70,7 @@ public JsonException(string message) /// /// The error message that explains the reason for the exception. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonException(string message, Exception innerException) + public JsonException(string message, Exception? innerException) : base(message, innerException) { } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonExtensionDataAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonExtensionDataAttribute.cs index 33e670911..b30d567e1 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonExtensionDataAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonExtensionDataAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; namespace Datadog.Trace.Vendors.Newtonsoft.Json diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonIgnoreAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonIgnoreAttribute.cs index ff8fb703c..582d4ba66 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonIgnoreAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonIgnoreAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonNameTable.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonNameTable.cs index bdfa9db0d..f0c45b6e2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonNameTable.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonNameTable.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable namespace Datadog.Trace.Vendors.Newtonsoft.Json { /// @@ -16,6 +19,6 @@ internal abstract class JsonNameTable /// The zero-based index into the array specifying the first character of the name. /// The number of characters in the name. /// A string containing the same characters as the specified range of characters in the given array. - public abstract string Get(char[] key, int start, int length); + public abstract string? Get(char[] key, int start, int length); } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonObjectAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonObjectAttribute.cs index 2229a7d2a..66f520d83 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonObjectAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonObjectAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -38,7 +41,8 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json internal sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization = MemberSerialization.OptOut; - + internal MissingMemberHandling? _missingMemberHandling; + // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state internal Required? _itemRequired; @@ -54,6 +58,16 @@ public MemberSerialization MemberSerialization set => _memberSerialization = value; } + /// + /// Gets or sets the missing member handling used when deserializing this object. + /// + /// The missing member handling. + public MissingMemberHandling MissingMemberHandling + { + get => _missingMemberHandling ?? default; + set => _missingMemberHandling = value; + } + /// /// Gets or sets how the object's properties with null values are handled during serialization and deserialization. /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPosition.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPosition.cs index 4388261f4..8f2eac7c5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPosition.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPosition.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -50,7 +53,7 @@ internal struct JsonPosition internal JsonContainerType Type; internal int Position; - internal string PropertyName; + internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) @@ -66,7 +69,7 @@ internal int CalculateLength() switch (Type) { case JsonContainerType.Object: - return PropertyName.Length + 5; + return PropertyName!.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; @@ -75,12 +78,12 @@ internal int CalculateLength() } } - internal void WriteTo(StringBuilder sb, ref StringWriter writer, ref char[] buffer) + internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: - string propertyName = PropertyName; + string propertyName = PropertyName!; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append(@"['"); @@ -134,8 +137,8 @@ internal static string BuildPath(List positions, JsonPosition? cur } StringBuilder sb = new StringBuilder(capacity); - StringWriter writer = null; - char[] buffer = null; + StringWriter? writer = null; + char[]? buffer = null; if (positions != null) { foreach (JsonPosition state in positions) @@ -151,7 +154,7 @@ internal static string BuildPath(List positions, JsonPosition? cur return sb.ToString(); } - internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message) + internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { // don't add a fullstop and space when message ends with a new line if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPropertyAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPropertyAttribute.cs index dbae81f73..508c0d683 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPropertyAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonPropertyAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -36,7 +39,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json /// Instructs the to always serialize the member with the specified name. /// [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)] - internal class JsonPropertyAttribute : Attribute + internal sealed class JsonPropertyAttribute : Attribute { // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state @@ -56,7 +59,7 @@ internal class JsonPropertyAttribute : Attribute /// Gets or sets the type used when serializing the property's collection items. /// /// The collection's items type. - public Type ItemConverterType { get; set; } + public Type? ItemConverterType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -69,13 +72,13 @@ internal class JsonPropertyAttribute : Attribute /// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// /// - public object[] ItemConverterParameters { get; set; } + public object[]? ItemConverterParameters { get; set; } /// /// Gets or sets the of the . /// /// The of the . - public Type NamingStrategyType { get; set; } + public Type? NamingStrategyType { get; set; } /// /// The parameter list to use when constructing the described by . @@ -88,7 +91,7 @@ internal class JsonPropertyAttribute : Attribute /// [JsonProperty(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })] /// /// - public object[] NamingStrategyParameters { get; set; } + public object[]? NamingStrategyParameters { get; set; } /// /// Gets or sets the null value handling used when serializing this property. @@ -176,7 +179,7 @@ public Required Required /// Gets or sets the name of the property. /// /// The name of the property. - public string PropertyName { get; set; } + public string? PropertyName { get; set; } /// /// Gets or sets the reference loop handling used when serializing the property's collection items. @@ -224,4 +227,4 @@ public JsonPropertyAttribute(string propertyName) PropertyName = propertyName; } } -} +} \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.Async.cs index a1585b14e..8965fa7c6 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -105,12 +108,12 @@ internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken /// property returns the []. This result will be null at the end of an array. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task ReadAsBytesAsync(CancellationToken cancellationToken = default) + public virtual Task ReadAsBytesAsync(CancellationToken cancellationToken = default) { - return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsBytes()); + return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsBytes()); } - internal async Task ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) + internal async Task ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List buffer = new List(); @@ -203,9 +206,9 @@ internal async Task ReadArrayIntoByteArrayAsync(CancellationToken cancel /// property returns the . This result will be null at the end of an array. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task ReadAsStringAsync(CancellationToken cancellationToken = default) + public virtual Task ReadAsStringAsync(CancellationToken cancellationToken = default) { - return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsString()); + return cancellationToken.CancelIfRequestedAsync() ?? Task.FromResult(ReadAsString()); } internal async Task ReadAndMoveToContentAsync(CancellationToken cancellationToken) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.cs index 23e159288..5fe335605 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReader.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -117,18 +120,18 @@ protected internal enum State // current Token data private JsonToken _tokenType; - private object _value; + private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; - private CultureInfo _culture; + private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; - private string _dateFormatString; - private List _stack; + private string? _dateFormatString; + private List? _stack; /// /// Gets the current reader state. @@ -223,7 +226,7 @@ public FloatParseHandling FloatParseHandling /// /// Gets or sets how custom date formatted strings are parsed when reading JSON. /// - public string DateFormatString + public string? DateFormatString { get => _dateFormatString; set => _dateFormatString = value; @@ -231,6 +234,8 @@ public string DateFormatString /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . + /// A null value means there is no maximum. + /// The default value is 128. /// public int? MaxDepth { @@ -254,12 +259,12 @@ public int? MaxDepth /// /// Gets the text value of the current JSON token. /// - public virtual object Value => _value; + public virtual object? Value => _value; /// /// Gets the .NET type for the current JSON token. /// - public virtual Type ValueType => _value?.GetType(); + public virtual Type? ValueType => _value?.GetType(); /// /// Gets the depth of the current token in the JSON document. @@ -299,7 +304,7 @@ public virtual string Path JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; - return JsonPosition.BuildPath(_stack, current); + return JsonPosition.BuildPath(_stack!, current); } } @@ -331,6 +336,7 @@ protected JsonReader() _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; + _maxDepth = 64; CloseInput = true; } @@ -412,7 +418,7 @@ private JsonContainerType Peek() return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value; + object v = Value!; if (v is int i) { return i; @@ -440,16 +446,16 @@ private JsonContainerType Peek() SetToken(JsonToken.Integer, i, false); return i; case JsonToken.String: - string s = (string)Value; + string? s = (string?)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal int? ReadInt32String(string s) + internal int? ReadInt32String(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -471,7 +477,7 @@ private JsonContainerType Peek() /// Reads the next JSON token from the source as a . /// /// A . This method will return null at the end of an array. - public virtual string ReadAsString() + public virtual string? ReadAsString() { JsonToken t = GetContentToken(); @@ -482,12 +488,12 @@ public virtual string ReadAsString() case JsonToken.EndArray: return null; case JsonToken.String: - return (string)Value; + return (string?)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { - object v = Value; + object? v = Value; if (v != null) { string s; @@ -512,7 +518,7 @@ public virtual string ReadAsString() /// Reads the next JSON token from the source as a []. /// /// A [] or null if the next JSON token is null. This method will return null at the end of an array. - public virtual byte[] ReadAsBytes() + public virtual byte[]? ReadAsBytes() { JsonToken t = GetContentToken(); @@ -522,7 +528,7 @@ public virtual byte[] ReadAsBytes() { ReadIntoWrappedTypeObject(); - byte[] data = ReadAsBytes(); + byte[]? data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) @@ -537,7 +543,7 @@ public virtual byte[] ReadAsBytes() { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 - string s = (string)Value; + string s = (string)Value!; byte[] data; @@ -569,7 +575,7 @@ public virtual byte[] ReadAsBytes() return data; } - return (byte[])Value; + return (byte[]?)Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } @@ -631,7 +637,7 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value; + object v = Value!; if (v is double d) { return d; @@ -652,15 +658,15 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) return (double)d; case JsonToken.String: - return ReadDoubleString((string)Value); + return ReadDoubleString((string?)Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal double? ReadDoubleString(string s) + internal double? ReadDoubleString(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -709,17 +715,17 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: - return ReadBooleanString((string)Value); + return ReadBooleanString((string?)Value); case JsonToken.Boolean: - return (bool)Value; + return (bool)Value!; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal bool? ReadBooleanString(string s) + internal bool? ReadBooleanString(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -753,7 +759,7 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) return null; case JsonToken.Integer: case JsonToken.Float: - object v = Value; + object v = Value!; if (v is decimal d) { @@ -782,15 +788,15 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) SetToken(JsonToken.Float, d, false); return d; case JsonToken.String: - return ReadDecimalString((string)Value); + return ReadDecimalString((string?)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } - internal decimal? ReadDecimalString(string s) + internal decimal? ReadDecimalString(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -834,18 +840,17 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) } #endif - return (DateTime)Value; + return (DateTime)Value!; case JsonToken.String: - string s = (string)Value; - return ReadDateTimeString(s); + return ReadDateTimeString((string?)Value); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } - internal DateTime? ReadDateTimeString(string s) + internal DateTime? ReadDateTimeString(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -889,18 +894,18 @@ private bool ReadArrayElementIntoByteArrayReportDone(List buffer) SetToken(JsonToken.Date, new DateTimeOffset(time), false); } - return (DateTimeOffset)Value; + return (DateTimeOffset)Value!; case JsonToken.String: - string s = (string)Value; + string? s = (string?)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } - internal DateTimeOffset? ReadDateTimeOffsetString(string s) + internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; @@ -989,7 +994,7 @@ protected void SetToken(JsonToken newToken) /// /// The new token. /// The value. - protected void SetToken(JsonToken newToken, object value) + protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, true); } @@ -1000,7 +1005,7 @@ protected void SetToken(JsonToken newToken, object value) /// The new token. /// The value. /// A flag indicating whether the position index inside an array should be updated. - protected void SetToken(JsonToken newToken, object value, bool updateIndex) + protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; @@ -1031,7 +1036,7 @@ protected void SetToken(JsonToken newToken, object value, bool updateIndex) case JsonToken.PropertyName: _currentState = State.Property; - _currentPosition.PropertyName = (string)value; + _currentPosition.PropertyName = (string)value!; break; case JsonToken.Undefined: case JsonToken.Integer: @@ -1174,7 +1179,7 @@ internal void ReadAndAssert() } } - internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter) + internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { @@ -1182,7 +1187,7 @@ internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter) } } - internal bool ReadForType(JsonContract contract, bool hasConverter) + internal bool ReadForType(JsonContract? contract, bool hasConverter) { // don't read properties with converters as a specific value // the value might be a string which will then get converted which will error if read as date for example diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReaderException.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReaderException.cs index 9c8d8715b..c468db032 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReaderException.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonReaderException.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -58,7 +61,7 @@ internal class JsonReaderException : JsonException /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string Path { get; } + public string? Path { get; } /// /// Initializes a new instance of the class. @@ -111,7 +114,7 @@ public JsonReaderException(SerializationInfo info, StreamingContext context) /// The line number indicating where the error occurred. /// The line position indicating where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception innerException) + public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; @@ -124,12 +127,12 @@ internal static JsonReaderException Create(JsonReader reader, string message) return Create(reader, message, null); } - internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) + internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } - internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonRequiredAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonRequiredAttribute.cs index 6d6a9bf9a..d28385634 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonRequiredAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonRequiredAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializationException.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializationException.cs index 9cbe355a0..a249e0ac7 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializationException.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializationException.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -58,7 +61,7 @@ internal class JsonSerializationException : JsonException /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string Path { get; } + public string? Path { get; } /// /// Initializes a new instance of the class. @@ -111,7 +114,7 @@ public JsonSerializationException(SerializationInfo info, StreamingContext conte /// The line number indicating where the error occurred. /// The line position indicating where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception innerException) + public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; @@ -124,12 +127,12 @@ internal static JsonSerializationException Create(JsonReader reader, string mess return Create(reader, message, null); } - internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) + internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } - internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializer.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializer.cs index e471f6b42..970b93d32 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializer.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializer.cs @@ -2,7 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ -#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011,SYSLIB0032 +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,6 +42,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Runtime.Serialization; using ErrorEventArgs = Datadog.Trace.Vendors.Newtonsoft.Json.Serialization.ErrorEventArgs; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json { @@ -59,13 +63,13 @@ internal class JsonSerializer internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; - internal JsonConverterCollection _converters; + internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; - internal ITraceWriter _traceWriter; - internal IEqualityComparer _equalityComparer; + internal ITraceWriter? _traceWriter; + internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; - private IReferenceResolver _referenceResolver; + private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; @@ -78,18 +82,18 @@ internal class JsonSerializer private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; - private string _dateFormatString; + private string? _dateFormatString; private bool _dateFormatStringSet; /// /// Occurs when the errors during serialization and deserialization. /// - public virtual event EventHandler Error; + public virtual event EventHandler? Error; /// /// Gets or sets the used by the serializer when resolving references. /// - public virtual IReferenceResolver ReferenceResolver + public virtual IReferenceResolver? ReferenceResolver { get => GetReferenceResolver(); set @@ -111,11 +115,6 @@ public virtual SerializationBinder Binder { get { - if (_serializationBinder == null) - { - return null; - } - if (_serializationBinder is SerializationBinder legacySerializationBinder) { return legacySerializationBinder; @@ -160,7 +159,7 @@ public virtual ISerializationBinder SerializationBinder /// Gets or sets the used by the serializer when writing trace messages. /// /// The trace writer. - public virtual ITraceWriter TraceWriter + public virtual ITraceWriter? TraceWriter { get => _traceWriter; set => _traceWriter = value; @@ -170,7 +169,7 @@ public virtual ITraceWriter TraceWriter /// Gets or sets the equality comparer used by the serializer when comparing references. /// /// The equality comparer. - public virtual IEqualityComparer EqualityComparer + public virtual IEqualityComparer? EqualityComparer { get => _equalityComparer; set => _equalityComparer = value; @@ -522,7 +521,7 @@ public virtual CultureInfo Culture /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is null. + /// The default value is 128. /// public virtual int? MaxDepth { @@ -604,7 +603,7 @@ public static JsonSerializer Create() /// The will not use default settings /// from . /// - public static JsonSerializer Create(JsonSerializerSettings settings) + public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer serializer = Create(); @@ -629,7 +628,7 @@ public static JsonSerializer Create(JsonSerializerSettings settings) public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues - JsonSerializerSettings defaultSettings = JsonConvert.DefaultSettings?.Invoke(); + JsonSerializerSettings? defaultSettings = JsonConvert.DefaultSettings?.Invoke(); return Create(defaultSettings); } @@ -645,7 +644,7 @@ public static JsonSerializer CreateDefault() /// The will use default settings /// from as well as the specified . /// - public static JsonSerializer CreateDefault(JsonSerializerSettings settings) + public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) @@ -819,14 +818,14 @@ internal virtual void PopulateInternal(JsonReader reader, object target) SetupReader( reader, - out CultureInfo previousCulture, + out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, - out string previousDateFormatString); + out string? previousDateFormatString); - TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; @@ -835,7 +834,7 @@ internal virtual void PopulateInternal(JsonReader reader, object target) if (traceJsonReader != null) { - TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); @@ -847,20 +846,20 @@ internal virtual void PopulateInternal(JsonReader reader, object target) /// The that contains the JSON structure to deserialize. /// The being deserialized. [DebuggerStepThrough] - public object Deserialize(JsonReader reader) + public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// - /// Deserializes the JSON structure contained by the specified + /// Deserializes the JSON structure contained by the specified /// into an instance of the specified type. /// /// The containing the object. /// The of object being deserialized. /// The instance of being deserialized. [DebuggerStepThrough] - public object Deserialize(TextReader reader, Type objectType) + public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } @@ -873,9 +872,9 @@ public object Deserialize(TextReader reader, Type objectType) /// The type of the object to deserialize. /// The instance of being deserialized. [DebuggerStepThrough] - public T Deserialize(JsonReader reader) + public T? Deserialize(JsonReader reader) { - return (T)Deserialize(reader, typeof(T)); + return (T?)Deserialize(reader, typeof(T)); } /// @@ -886,34 +885,34 @@ public T Deserialize(JsonReader reader) /// The of object being deserialized. /// The instance of being deserialized. [DebuggerStepThrough] - public object Deserialize(JsonReader reader, Type objectType) + public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } - internal virtual object DeserializeInternal(JsonReader reader, Type objectType) + internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); SetupReader( reader, - out CultureInfo previousCulture, + out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, - out string previousDateFormatString); + out string? previousDateFormatString); - TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonReader? traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); - object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); + object? value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { - TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); + TraceWriter!.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); @@ -921,7 +920,7 @@ internal virtual object DeserializeInternal(JsonReader reader, Type objectType) return value; } - private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) + private void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { @@ -992,7 +991,7 @@ private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out } } - private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) + private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { // reset reader back to previous options if (previousCulture != null) @@ -1033,7 +1032,7 @@ private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTim /// /// The used to write the JSON structure. /// The to serialize. - public void Serialize(TextWriter textWriter, object value) + public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } @@ -1049,7 +1048,7 @@ public void Serialize(TextWriter textWriter, object value) /// This parameter is used when is to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// - public void Serialize(JsonWriter jsonWriter, object value, Type objectType) + public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } @@ -1065,7 +1064,7 @@ public void Serialize(JsonWriter jsonWriter, object value, Type objectType) /// This parameter is used when is Auto to write out the type name if the type of the value does not match. /// Specifying the type is optional. /// - public void Serialize(TextWriter textWriter, object value, Type objectType) + public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } @@ -1076,7 +1075,7 @@ public void Serialize(TextWriter textWriter, object value, Type objectType) /// /// The used to write the JSON structure. /// The to serialize. - public void Serialize(JsonWriter jsonWriter, object value) + public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } @@ -1092,7 +1091,7 @@ private TraceJsonReader CreateTraceJsonReader(JsonReader reader) return traceReader; } - internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) + internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); @@ -1132,21 +1131,21 @@ internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Typ jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } - CultureInfo previousCulture = null; + CultureInfo? previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } - string previousDateFormatString = null; + string? previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } - TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) + TraceJsonWriter? traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; @@ -1155,7 +1154,7 @@ internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Typ if (traceJsonWriter != null) { - TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); + TraceWriter!.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } // reset writer back to previous options @@ -1199,12 +1198,12 @@ internal IReferenceResolver GetReferenceResolver() return _referenceResolver; } - internal JsonConverter GetMatchingConverter(Type type) + internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } - internal static JsonConverter GetMatchingConverter(IList converters, Type objectType) + internal static JsonConverter? GetMatchingConverter(IList? converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializerSettings.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializerSettings.cs index 5a9ce531c..5fb08b96f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializerSettings.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonSerializerSettings.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -65,6 +68,7 @@ internal class JsonSerializerSettings internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; + internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; @@ -73,11 +77,11 @@ internal class JsonSerializerSettings internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; - internal CultureInfo _culture; + internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; - internal string _dateFormatString; + internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; @@ -229,27 +233,27 @@ public ConstructorHandling ConstructorHandling /// serializing .NET objects to JSON and vice versa. /// /// The contract resolver. - public IContractResolver ContractResolver { get; set; } + public IContractResolver? ContractResolver { get; set; } /// /// Gets or sets the equality comparer used by the serializer when comparing references. /// /// The equality comparer. - public IEqualityComparer EqualityComparer { get; set; } + public IEqualityComparer? EqualityComparer { get; set; } /// /// Gets or sets the used by the serializer when resolving references. /// /// The reference resolver. [Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] - public IReferenceResolver ReferenceResolver + public IReferenceResolver? ReferenceResolver { get => ReferenceResolverProvider?.Invoke(); set { ReferenceResolverProvider = (value != null) ? () => value - : (System.Func)null; + : (System.Func?)null; } } @@ -257,20 +261,20 @@ public IReferenceResolver ReferenceResolver /// Gets or sets a function that creates the used by the serializer when resolving references. /// /// A function that creates the used by the serializer when resolving references. - public System.Func ReferenceResolverProvider { get; set; } + public System.Func? ReferenceResolverProvider { get; set; } /// /// Gets or sets the used by the serializer when writing trace messages. /// /// The trace writer. - public ITraceWriter TraceWriter { get; set; } + public ITraceWriter? TraceWriter { get; set; } /// /// Gets or sets the used by the serializer when resolving type names. /// /// The binder. [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] - public SerializationBinder Binder + public SerializationBinder? Binder { get { @@ -293,13 +297,13 @@ public SerializationBinder Binder /// Gets or sets the used by the serializer when resolving type names. /// /// The binder. - public ISerializationBinder SerializationBinder { get; set; } + public ISerializationBinder? SerializationBinder { get; set; } /// /// Gets or sets the error handler called during serialization and deserialization. /// /// The error handler called during serialization and deserialization. - public EventHandler Error { get; set; } + public EventHandler? Error { get; set; } /// /// Gets or sets the used by the serializer when invoking serialization callback methods. @@ -329,11 +333,11 @@ public string DateFormatString /// /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a . /// A null value means there is no maximum. - /// The default value is null. + /// The default value is 128. /// public int? MaxDepth { - get => _maxDepth; + get => _maxDepthSet ? _maxDepth : DefaultMaxDepth; set { if (value <= 0) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.Async.cs index 4bd97799a..c1d43ac05 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -38,6 +41,7 @@ using System.Threading.Tasks; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json { @@ -114,6 +118,8 @@ private async Task DoReadAsync(Task task, CancellationToken cancella private async Task ParsePostValueAsync(bool ignoreComments, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -197,6 +203,8 @@ private async Task ParsePostValueAsync(bool ignoreComments, CancellationTo private async Task ReadFromFinishedAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -226,6 +234,8 @@ private Task ReadDataAsync(bool append, CancellationToken cancellationToken private async Task ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + if (_isEndOfFile) { return 0; @@ -248,6 +258,8 @@ private async Task ReadDataAsync(bool append, int charsRequired, Cancellati private async Task ParseValueAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -377,6 +389,8 @@ private async Task ParseValueAsync(CancellationToken cancellationToken) private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; @@ -593,6 +607,8 @@ private async Task ReadCharsAsync(int relativePosition, bool append, Cance private async Task ParseObjectAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -650,6 +666,8 @@ private async Task ParseObjectAsync(CancellationToken cancellationToken) private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + // should have already parsed / character before reaching this method _charPos++; @@ -746,6 +764,8 @@ private async Task ParseCommentAsync(bool setToken, CancellationToken cancellati private async Task EatWhitespaceAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -802,6 +822,8 @@ private async Task MatchValueAsync(string value, CancellationToken cancell private async Task MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + // will match value and then move to the next character, checking that it is a separator character if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false)) { @@ -816,7 +838,7 @@ private async Task MatchValueWithTrailingSeparatorAsync(string value, Canc return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0'; } - private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken) + private async Task MatchAndSetAsync(string value, JsonToken newToken, object? tokenValue, CancellationToken cancellationToken) { if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false)) { @@ -845,6 +867,8 @@ private Task ParseNullAsync(CancellationToken cancellationToken) private async Task ParseConstructorAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -943,6 +967,8 @@ private async Task ParseNumberNegativeInfinityAsync(ReadType readType, C private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + ShiftBufferIfNeeded(); char firstChar = _chars[_charPos]; @@ -960,6 +986,8 @@ private Task ParseUndefinedAsync(CancellationToken cancellationToken) private async Task ParsePropertyAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + char firstChar = _chars[_charPos]; char quoteChar; @@ -1012,6 +1040,8 @@ private async Task ParsePropertyAsync(CancellationToken cancellationToken) private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + int charPos = _charPos; while (true) @@ -1046,6 +1076,8 @@ private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + int initialPosition = _charPos; // parse unquoted property name until whitespace or colon @@ -1095,6 +1127,8 @@ private async Task ReadNullCharAsync(CancellationToken cancellationToken) private async Task HandleNullAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false)) { if (_chars[_charPos + 1] == 'u') @@ -1113,6 +1147,8 @@ private async Task HandleNullAsync(CancellationToken cancellationToken) private async Task ReadFinishedAsync(CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_chars != null); + if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false)) { await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false); @@ -1135,9 +1171,10 @@ private async Task ReadFinishedAsync(CancellationToken cancellationToken) SetToken(JsonToken.None); } - private async Task ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken) + private async Task ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1270,9 +1307,10 @@ private async Task ReadStringValueAsync(ReadType readType, CancellationT } } - private async Task ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken) + private async Task ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1399,6 +1437,7 @@ private async Task ReadNumberValueAsync(ReadType readType, CancellationT internal async Task DoReadAsBooleanAsync(CancellationToken cancellationToken) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1526,14 +1565,16 @@ private async Task ReadNumberValueAsync(ReadType readType, CancellationT /// property returns the []. This result will be null at the end of an array. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task ReadAsBytesAsync(CancellationToken cancellationToken = default) + public override Task ReadAsBytesAsync(CancellationToken cancellationToken = default) { return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken); } - internal async Task DoReadAsBytesAsync(CancellationToken cancellationToken) + internal async Task DoReadAsBytesAsync(CancellationToken cancellationToken) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); + bool isWrapped = false; switch (_currentState) @@ -1567,7 +1608,7 @@ internal async Task DoReadAsBytesAsync(CancellationToken cancellationTok case '"': case '\'': await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false); - byte[] data = (byte[])Value; + byte[]? data = (byte[]?)Value; if (isWrapped) { await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false); @@ -1757,14 +1798,14 @@ private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellation /// property returns the . This result will be null at the end of an array. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task ReadAsStringAsync(CancellationToken cancellationToken = default) + public override Task ReadAsStringAsync(CancellationToken cancellationToken = default) { return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken); } - internal async Task DoReadAsStringAsync(CancellationToken cancellationToken) + internal async Task DoReadAsStringAsync(CancellationToken cancellationToken) { - return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); + return (string?)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false); } } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.cs index dd2b3e8f3..8a1bab4ee 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextReader.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -31,6 +34,7 @@ using System.Runtime.CompilerServices; using System.IO; using System.Globalization; +using System.Diagnostics; #if HAVE_BIG_INTEGER using System.Numerics; #endif @@ -60,8 +64,9 @@ internal enum ReadType internal partial class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\uFFFD'; +#if HAVE_BIG_INTEGER private const int MaximumJavascriptIntegerCharacterLength = 380; - +#endif #if DEBUG internal int LargeBufferLength { get; set; } = int.MaxValue / 2; #else @@ -69,7 +74,7 @@ internal partial class JsonTextReader : JsonReader, IJsonLineInfo #endif private readonly TextReader _reader; - private char[] _chars; + private char[]? _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; @@ -77,7 +82,7 @@ internal partial class JsonTextReader : JsonReader, IJsonLineInfo private bool _isEndOfFile; private StringBuffer _stringBuffer; private StringReference _stringReference; - private IArrayPool _arrayPool; + private IArrayPool? _arrayPool; /// /// Initializes a new instance of the class with the specified . @@ -99,7 +104,7 @@ public JsonTextReader(TextReader reader) } #if DEBUG - internal char[] CharBuffer + internal char[]? CharBuffer { get => _chars; set => _chars = value; @@ -111,12 +116,12 @@ internal char[] CharBuffer /// /// Gets or sets the reader's property name table. /// - public JsonNameTable PropertyNameTable { get; set; } + public JsonNameTable? PropertyNameTable { get; set; } /// /// Gets or sets the reader's character buffer pool. /// - public IArrayPool ArrayPool + public IArrayPool? ArrayPool { get => _arrayPool; set @@ -140,6 +145,8 @@ private void EnsureBufferNotEmpty() private void SetNewLine(bool hasNextChar) { + MiscellaneousUtils.Assert(_chars != null); + if (hasNextChar && _chars[_charPos] == StringUtils.LineFeed) { _charPos++; @@ -252,6 +259,8 @@ private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int ds private void ShiftBufferIfNeeded() { + MiscellaneousUtils.Assert(_chars != null); + // once in the last 10% of the buffer, or buffer is already very large then // shift the remaining content to the start to avoid unnecessarily increasing // the buffer size when reading numbers/strings @@ -278,6 +287,8 @@ private int ReadData(bool append) private void PrepareBufferForReadData(bool append, int charsRequired) { + MiscellaneousUtils.Assert(_chars != null); + // char buffer is full if (_charsUsed + charsRequired >= _chars.Length - 1) { @@ -341,6 +352,7 @@ private int ReadData(bool append, int charsRequired) } PrepareBufferForReadData(append, charsRequired); + MiscellaneousUtils.Assert(_chars != null); int attemptCharReadCount = _chars.Length - _charsUsed - 1; @@ -409,6 +421,7 @@ private bool ReadChars(int relativePosition, bool append) public override bool Read() { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); while (true) { @@ -479,18 +492,20 @@ public override bool Read() /// Reads the next JSON token from the underlying as a . /// /// A . This method will return null at the end of an array. - public override string ReadAsString() + public override string? ReadAsString() { - return (string)ReadStringValue(ReadType.ReadAsString); + return (string?)ReadStringValue(ReadType.ReadAsString); } /// /// Reads the next JSON token from the underlying as a []. /// /// A [] or null if the next JSON token is null. This method will return null at the end of an array. - public override byte[] ReadAsBytes() + public override byte[]? ReadAsBytes() { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); + bool isWrapped = false; switch (_currentState) @@ -523,7 +538,7 @@ public override byte[] ReadAsBytes() case '"': case '\'': ParseString(currentChar, ReadType.ReadAsBytes); - byte[] data = (byte[])Value; + byte[]? data = (byte[]?)Value; if (isWrapped) { ReaderReadAndAssert(); @@ -592,9 +607,10 @@ public override byte[] ReadAsBytes() } } - private object ReadStringValue(ReadType readType) + private object? ReadStringValue(ReadType readType) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -721,7 +737,7 @@ private object ReadStringValue(ReadType readType) } } - private object FinishReadQuotedStringValue(ReadType readType) + private object? FinishReadQuotedStringValue(ReadType readType) { switch (readType) { @@ -734,7 +750,7 @@ private object FinishReadQuotedStringValue(ReadType readType) return time; } - return ReadDateTimeString((string)Value); + return ReadDateTimeString((string?)Value); #if HAVE_DATE_TIME_OFFSET case ReadType.ReadAsDateTimeOffset: if (Value is DateTimeOffset offset) @@ -742,7 +758,7 @@ private object FinishReadQuotedStringValue(ReadType readType) return offset; } - return ReadDateTimeOffsetString((string)Value); + return ReadDateTimeOffsetString((string?)Value); #endif default: throw new ArgumentOutOfRangeException(nameof(readType)); @@ -761,6 +777,7 @@ private JsonReaderException CreateUnexpectedCharacterException(char c) public override bool? ReadAsBoolean() { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -895,9 +912,10 @@ private void ProcessValueComma() SetStateBasedOnCurrent(); } - private object ReadNumberValue(ReadType readType) + private object? ReadNumberValue(ReadType readType) { EnsureBuffer(); + MiscellaneousUtils.Assert(_chars != null); switch (_currentState) { @@ -1005,7 +1023,7 @@ private object ReadNumberValue(ReadType readType) } } - private object FinishReadQuotedNumber(ReadType readType) + private object? FinishReadQuotedNumber(ReadType readType) { switch (readType) { @@ -1051,6 +1069,8 @@ private object FinishReadQuotedNumber(ReadType readType) private void HandleNull() { + MiscellaneousUtils.Assert(_chars != null); + if (EnsureChars(1, true)) { char next = _chars[_charPos + 1]; @@ -1071,6 +1091,8 @@ private void HandleNull() private void ReadFinished() { + MiscellaneousUtils.Assert(_chars != null); + if (EnsureChars(0, false)) { EatWhitespace(); @@ -1120,6 +1142,8 @@ private void EnsureBuffer() private void ReadStringIntoBuffer(char quote) { + MiscellaneousUtils.Assert(_chars != null); + int charPos = _charPos; int initialPosition = _charPos; int lastWritePosition = _charPos; @@ -1273,6 +1297,8 @@ private void ReadStringIntoBuffer(char quote) private void FinishReadStringIntoBuffer(int charPos, int initialPosition, int lastWritePosition) { + MiscellaneousUtils.Assert(_chars != null); + if (initialPosition == lastWritePosition) { _stringReference = new StringReference(_chars, initialPosition, charPos - initialPosition); @@ -1286,7 +1312,7 @@ private void FinishReadStringIntoBuffer(int charPos, int initialPosition, int la _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, charPos - lastWritePosition); } - _stringReference = new StringReference(_stringBuffer.InternalBuffer, 0, _stringBuffer.Position); + _stringReference = new StringReference(_stringBuffer.InternalBuffer!, 0, _stringBuffer.Position); } _charPos = charPos + 1; @@ -1294,6 +1320,8 @@ private void FinishReadStringIntoBuffer(int charPos, int initialPosition, int la private void WriteCharToBuffer(char writeChar, int lastWritePosition, int writeToPosition) { + MiscellaneousUtils.Assert(_chars != null); + if (writeToPosition > lastWritePosition) { _stringBuffer.Append(_arrayPool, _chars, lastWritePosition, writeToPosition - lastWritePosition); @@ -1304,6 +1332,8 @@ private void WriteCharToBuffer(char writeChar, int lastWritePosition, int writeT private char ConvertUnicode(bool enoughChars) { + MiscellaneousUtils.Assert(_chars != null); + if (enoughChars) { if (ConvertUtils.TryHexTextToInt(_chars, _charPos, _charPos + 4, out int value)) @@ -1330,6 +1360,8 @@ private char ParseUnicode() private void ReadNumberIntoBuffer() { + MiscellaneousUtils.Assert(_chars != null); + int charPos = _charPos; while (true) @@ -1414,6 +1446,8 @@ private void ClearRecentString() private bool ParsePostValue(bool ignoreComments) { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -1494,6 +1528,8 @@ private bool ParsePostValue(bool ignoreComments) private bool ParseObject() { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -1548,6 +1584,8 @@ private bool ParseObject() private bool ParseProperty() { + MiscellaneousUtils.Assert(_chars != null); + char firstChar = _chars[_charPos]; char quoteChar; @@ -1569,7 +1607,7 @@ private bool ParseProperty() throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } - string propertyName; + string? propertyName; if (PropertyNameTable != null) { @@ -1609,6 +1647,8 @@ private bool ValidIdentifierChar(char value) private void ParseUnquotedProperty() { + MiscellaneousUtils.Assert(_chars != null); + int initialPosition = _charPos; // parse unquoted property name until whitespace or colon @@ -1640,6 +1680,8 @@ private void ParseUnquotedProperty() private bool ReadUnquotedPropertyReportIfDone(char currentChar, int initialPosition) { + MiscellaneousUtils.Assert(_chars != null); + if (ValidIdentifierChar(currentChar)) { _charPos++; @@ -1657,6 +1699,8 @@ private bool ReadUnquotedPropertyReportIfDone(char currentChar, int initialPosit private bool ParseValue() { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -1797,6 +1841,8 @@ private void ProcessCarriageReturn(bool append) private void EatWhitespace() { + MiscellaneousUtils.Assert(_chars != null); + while (true) { char currentChar = _chars[_charPos]; @@ -1838,6 +1884,8 @@ private void EatWhitespace() private void ParseConstructor() { + MiscellaneousUtils.Assert(_chars != null); + if (MatchValueWithTrailingSeparator("new")) { EatWhitespace(); @@ -1922,6 +1970,7 @@ private void ParseConstructor() private void ParseNumber(ReadType readType) { ShiftBufferIfNeeded(); + MiscellaneousUtils.Assert(_chars != null); char firstChar = _chars[_charPos]; int initialPosition = _charPos; @@ -1932,7 +1981,9 @@ private void ParseNumber(ReadType readType) } private void ParseReadNumber(ReadType readType, char firstChar, int initialPosition) - { + { + MiscellaneousUtils.Assert(_chars != null); + // set state to PostValue now so that if there is an error parsing the number then the reader can continue SetPostValueState(true); @@ -2193,7 +2244,7 @@ private void ParseReadNumber(ReadType readType, char firstChar, int initialPosit SetToken(numberType, numberValue, false); } - private JsonReaderException ThrowReaderError(string message, Exception ex = null) + private JsonReaderException ThrowReaderError(string message, Exception? ex = null) { SetToken(JsonToken.Undefined, null, false); return JsonReaderException.Create(this, message, ex); @@ -2213,6 +2264,8 @@ private static object BigIntegerParse(string number, CultureInfo culture) private void ParseComment(bool setToken) { + MiscellaneousUtils.Assert(_chars != null); + // should have already parsed / character before reaching this method _charPos++; @@ -2318,6 +2371,8 @@ private bool MatchValue(string value) private bool MatchValue(bool enoughChars, string value) { + MiscellaneousUtils.Assert(_chars != null); + if (!enoughChars) { _charPos = _charsUsed; @@ -2340,6 +2395,8 @@ private bool MatchValue(bool enoughChars, string value) private bool MatchValueWithTrailingSeparator(string value) { + MiscellaneousUtils.Assert(_chars != null); + // will match value and then move to the next character, checking that it is a separator character bool match = MatchValue(value); @@ -2358,6 +2415,8 @@ private bool MatchValueWithTrailingSeparator(string value) private bool IsSeparator(char c) { + MiscellaneousUtils.Assert(_chars != null); + switch (c) { case '}': diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.Async.cs index cb7b58acf..0e7c910f2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -37,6 +40,7 @@ #endif using System.Threading.Tasks; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json { @@ -168,6 +172,7 @@ internal Task DoWriteIndentAsync(CancellationToken cancellationToken) int currentIndentCount = Top * _indentation; int newLineLen = SetIndentChars(); + MiscellaneousUtils.Assert(_indentChars != null); if (currentIndentCount <= IndentCharBufferSize) { @@ -179,6 +184,8 @@ internal Task DoWriteIndentAsync(CancellationToken cancellationToken) private async Task WriteIndentAsync(int currentIndentCount, int newLineLen, CancellationToken cancellationToken) { + MiscellaneousUtils.Assert(_indentChars != null); + await _writer.WriteAsync(_indentChars, 0, newLineLen + Math.Min(currentIndentCount, IndentCharBufferSize), cancellationToken).ConfigureAwait(false); while ((currentIndentCount -= IndentCharBufferSize) > 0) @@ -229,12 +236,12 @@ internal Task DoWriteIndentSpaceAsync(CancellationToken cancellationToken) /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteRawAsync(string json, CancellationToken cancellationToken = default) + public override Task WriteRawAsync(string? json, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteRawAsync(json, cancellationToken) : base.WriteRawAsync(json, cancellationToken); } - internal Task DoWriteRawAsync(string json, CancellationToken cancellationToken) + internal Task DoWriteRawAsync(string? json, CancellationToken cancellationToken) { return _writer.WriteAsync(json, cancellationToken); } @@ -264,7 +271,7 @@ private Task WriteDigitsAsync(ulong uvalue, bool negative, CancellationToken can } int length = WriteNumberToBuffer(uvalue, negative); - return _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken); + return _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken); } private Task WriteIntegerValueAsync(ulong uvalue, bool negative, CancellationToken cancellationToken) @@ -302,7 +309,7 @@ internal Task WriteIntegerValueAsync(ulong uvalue, CancellationToken cancellatio private Task WriteEscapedStringAsync(string value, bool quote, CancellationToken cancellationToken) { - return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, this, _writeBuffer, cancellationToken); + return JavaScriptUtils.WriteEscapedJavaScriptStringAsync(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, this, _writeBuffer!, cancellationToken); } /// @@ -589,7 +596,7 @@ internal Task DoWriteValueAsync(byte? value, CancellationToken cancellationToken /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default) { return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNonNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken); } @@ -657,11 +664,11 @@ internal async Task DoWriteValueAsync(DateTime value, CancellationToken cancella await InternalWriteValueAsync(JsonToken.Date, cancellationToken).ConfigureAwait(false); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); - if (string.IsNullOrEmpty(DateFormatString)) + if (StringUtils.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); - await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false); } else { @@ -706,11 +713,11 @@ internal async Task DoWriteValueAsync(DateTimeOffset value, CancellationToken ca { await InternalWriteValueAsync(JsonToken.Date, cancellationToken).ConfigureAwait(false); - if (string.IsNullOrEmpty(DateFormatString)) + if (StringUtils.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); - await _writer.WriteAsync(_writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(_writeBuffer!, 0, length, cancellationToken).ConfigureAwait(false); } else { @@ -957,7 +964,7 @@ internal Task WriteValueAsync(BigInteger value, CancellationToken cancellationTo /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(object value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(object? value, CancellationToken cancellationToken = default) { if (_safeAsync) { @@ -1050,12 +1057,12 @@ internal Task DoWriteValueAsync(short? value, CancellationToken cancellationToke /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(string value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(string? value, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteValueAsync(value, cancellationToken) : base.WriteValueAsync(value, cancellationToken); } - internal Task DoWriteValueAsync(string value, CancellationToken cancellationToken) + internal Task DoWriteValueAsync(string? value, CancellationToken cancellationToken) { Task task = InternalWriteValueAsync(JsonToken.String, cancellationToken); if (task.IsCompletedSucessfully()) @@ -1066,7 +1073,7 @@ internal Task DoWriteValueAsync(string value, CancellationToken cancellationToke return DoWriteValueAsync(task, value, cancellationToken); } - private async Task DoWriteValueAsync(Task task, string value, CancellationToken cancellationToken) + private async Task DoWriteValueAsync(Task task, string? value, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await (value == null ? _writer.WriteAsync(JsonConvert.Null, cancellationToken) : WriteEscapedStringAsync(value, true, cancellationToken)).ConfigureAwait(false); @@ -1185,7 +1192,7 @@ internal Task DoWriteValueAsync(ulong? value, CancellationToken cancellationToke /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default) + public override Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default) { return _safeAsync ? (value == null ? WriteNullAsync(cancellationToken) : WriteValueNotNullAsync(value, cancellationToken)) : base.WriteValueAsync(value, cancellationToken); } @@ -1248,16 +1255,16 @@ internal Task DoWriteValueAsync(ushort? value, CancellationToken cancellationTok /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteCommentAsync(string text, CancellationToken cancellationToken = default) + public override Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteCommentAsync(text, cancellationToken) : base.WriteCommentAsync(text, cancellationToken); } - internal async Task DoWriteCommentAsync(string text, CancellationToken cancellationToken) + internal async Task DoWriteCommentAsync(string? text, CancellationToken cancellationToken) { await InternalWriteCommentAsync(cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("/*", cancellationToken).ConfigureAwait(false); - await _writer.WriteAsync(text, cancellationToken).ConfigureAwait(false); + await _writer.WriteAsync(text ?? string.Empty, cancellationToken).ConfigureAwait(false); await _writer.WriteAsync("*/", cancellationToken).ConfigureAwait(false); } @@ -1305,12 +1312,12 @@ public override Task WriteEndObjectAsync(CancellationToken cancellationToken = d /// A that represents the asynchronous operation. /// Derived classes must override this method to get asynchronous behaviour. Otherwise it will /// execute synchronously, returning an already-completed task. - public override Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default) + public override Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default) { return _safeAsync ? DoWriteRawValueAsync(json, cancellationToken) : base.WriteRawValueAsync(json, cancellationToken); } - internal Task DoWriteRawValueAsync(string json, CancellationToken cancellationToken) + internal Task DoWriteRawValueAsync(string? json, CancellationToken cancellationToken) { UpdateScopeWithFinishedValue(); Task task = AutoCompleteAsync(JsonToken.Undefined, cancellationToken); @@ -1322,7 +1329,7 @@ internal Task DoWriteRawValueAsync(string json, CancellationToken cancellationTo return DoWriteRawValueAsync(task, json, cancellationToken); } - private async Task DoWriteRawValueAsync(Task task, string json, CancellationToken cancellationToken) + private async Task DoWriteRawValueAsync(Task task, string? json, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await WriteRawAsync(json, cancellationToken).ConfigureAwait(false); @@ -1335,7 +1342,7 @@ internal char[] EnsureWriteBuffer(int length, int copyTo) length = 35; } - char[] buffer = _writeBuffer; + char[]? buffer = _writeBuffer; if (buffer == null) { return _writeBuffer = BufferUtils.RentBuffer(_arrayPool, length); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.cs index 3f2d96f48..439374030 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonTextWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -37,6 +40,7 @@ using System.IO; using System.Xml; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json { @@ -47,15 +51,15 @@ internal partial class JsonTextWriter : JsonWriter { private const int IndentCharBufferSize = 12; private readonly TextWriter _writer; - private Base64Encoder _base64Encoder; + private Base64Encoder? _base64Encoder; private char _indentChar; private int _indentation; private char _quoteChar; private bool _quoteName; - private bool[] _charEscapeFlags; - private char[] _writeBuffer; - private IArrayPool _arrayPool; - private char[] _indentChars; + private bool[]? _charEscapeFlags; + private char[]? _writeBuffer; + private IArrayPool? _arrayPool; + private char[]? _indentChars; private Base64Encoder Base64Encoder { @@ -73,7 +77,7 @@ private Base64Encoder Base64Encoder /// /// Gets or sets the writer's character array pool. /// - public IArrayPool ArrayPool + public IArrayPool? ArrayPool { get => _arrayPool; set @@ -346,7 +350,7 @@ private int SetIndentChars() { for (int i = 0; i != newLineLen; ++i) { - if (writerNewLine[i] != _indentChars[i]) + if (writerNewLine[i] != _indentChars![i]) { match = false; break; @@ -391,7 +395,7 @@ private void WriteValueInternal(string value, JsonToken token) /// An error will raised if the value cannot be written as a single JSON token. /// /// The value to write. - public override void WriteValue(object value) + public override void WriteValue(object? value) { #if HAVE_BIG_INTEGER if (value is BigInteger i) @@ -428,7 +432,7 @@ public override void WriteUndefined() /// Writes raw JSON. /// /// The raw JSON to write. - public override void WriteRaw(string json) + public override void WriteRaw(string? json) { InternalWriteRaw(); @@ -439,7 +443,7 @@ public override void WriteRaw(string json) /// Writes a value. /// /// The value to write. - public override void WriteValue(string value) + public override void WriteValue(string? value) { InternalWriteValue(JsonToken.String); @@ -456,7 +460,7 @@ public override void WriteValue(string value) private void WriteEscapedString(string value, bool quote) { EnsureWriteBuffer(); - JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags, StringEscapeHandling, _arrayPool, ref _writeBuffer); + JavaScriptUtils.WriteEscapedJavaScriptString(_writer, value, _quoteChar, quote, _charEscapeFlags!, StringEscapeHandling, _arrayPool, ref _writeBuffer); } /// @@ -636,7 +640,7 @@ public override void WriteValue(DateTime value) InternalWriteValue(JsonToken.Date); value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling); - if (string.IsNullOrEmpty(DateFormatString)) + if (StringUtils.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); @@ -653,6 +657,7 @@ public override void WriteValue(DateTime value) private int WriteValueToBuffer(DateTime value) { EnsureWriteBuffer(); + MiscellaneousUtils.Assert(_writeBuffer != null); int pos = 0; _writeBuffer[pos++] = _quoteChar; @@ -665,7 +670,7 @@ private int WriteValueToBuffer(DateTime value) /// Writes a [] value. /// /// The [] value to write. - public override void WriteValue(byte[] value) + public override void WriteValue(byte[]? value) { if (value == null) { @@ -690,7 +695,7 @@ public override void WriteValue(DateTimeOffset value) { InternalWriteValue(JsonToken.Date); - if (string.IsNullOrEmpty(DateFormatString)) + if (StringUtils.IsNullOrEmpty(DateFormatString)) { int length = WriteValueToBuffer(value); @@ -707,6 +712,7 @@ public override void WriteValue(DateTimeOffset value) private int WriteValueToBuffer(DateTimeOffset value) { EnsureWriteBuffer(); + MiscellaneousUtils.Assert(_writeBuffer != null); int pos = 0; _writeBuffer[pos++] = _quoteChar; @@ -724,7 +730,7 @@ public override void WriteValue(Guid value) { InternalWriteValue(JsonToken.String); - string text = null; + string text; #if HAVE_CHAR_TO_STRING_WITH_CULTURE text = value.ToString("D", CultureInfo.InvariantCulture); @@ -761,7 +767,7 @@ public override void WriteValue(TimeSpan value) /// Writes a value. /// /// The value to write. - public override void WriteValue(Uri value) + public override void WriteValue(Uri? value) { if (value == null) { @@ -779,7 +785,7 @@ public override void WriteValue(Uri value) /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public override void WriteComment(string text) + public override void WriteComment(string? text) { InternalWriteComment(); @@ -843,6 +849,7 @@ private int WriteNumberToBuffer(ulong value, bool negative) } EnsureWriteBuffer(); + MiscellaneousUtils.Assert(_writeBuffer != null); int totalLength = MathUtils.IntLength(value); @@ -894,6 +901,7 @@ private void WriteIntegerValue(uint value, bool negative) private int WriteNumberToBuffer(uint value, bool negative) { EnsureWriteBuffer(); + MiscellaneousUtils.Assert(_writeBuffer != null); int totalLength = MathUtils.IntLength(value); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonToken.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonToken.cs index 1280c7094..8e7761685 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonToken.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonToken.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonValidatingReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonValidatingReader.cs index 8a7568185..58367710f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonValidatingReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonValidatingReader.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -45,6 +47,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.Async.cs index 79dd1ab94..3d89c508f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -229,7 +232,7 @@ protected virtual Task WriteIndentSpaceAsync(CancellationToken cancellationToken /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteRawAsync(string json, CancellationToken cancellationToken = default) + public virtual Task WriteRawAsync(string? json, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -550,7 +553,7 @@ internal async Task InternalWriteStartAsync(JsonToken token, JsonContainerType c /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteCommentAsync(string text, CancellationToken cancellationToken = default) + public virtual Task WriteCommentAsync(string? text, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -574,7 +577,7 @@ internal Task InternalWriteCommentAsync(CancellationToken cancellationToken) /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteRawValueAsync(string json, CancellationToken cancellationToken = default) + public virtual Task WriteRawValueAsync(string? json, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -677,7 +680,7 @@ public Task WriteTokenAsync(JsonToken token, CancellationToken cancellationToken /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public Task WriteTokenAsync(JsonToken token, object value, CancellationToken cancellationToken = default) + public Task WriteTokenAsync(JsonToken token, object? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -759,7 +762,7 @@ public Task WriteTokenAsync(JsonToken token, object value, CancellationToken can return WriteValueAsync(guid, cancellationToken); } - return WriteValueAsync((byte[])value, cancellationToken); + return WriteValueAsync((byte[]?)value, cancellationToken); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type."); } @@ -772,7 +775,7 @@ internal virtual async Task WriteTokenAsync(JsonReader reader, bool writeChildre do { // write a JValue date when the constructor is for a date - if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) { await WriteConstructorDateAsync(reader, cancellationToken).ConfigureAwait(false); } @@ -789,7 +792,7 @@ internal virtual async Task WriteTokenAsync(JsonReader reader, bool writeChildre && writeChildren && await reader.ReadAsync(cancellationToken).ConfigureAwait(false)); - if (initialDepth < CalculateWriteTokenFinalDepth(reader)) + if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } @@ -805,7 +808,7 @@ internal async Task WriteTokenSyncReadingAsync(JsonReader reader, CancellationTo do { // write a JValue date when the constructor is for a date - if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + if (reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } @@ -835,7 +838,7 @@ private async Task WriteConstructorDateAsync(JsonReader reader, CancellationToke throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); } - DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value); + DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime((long)reader.Value!); if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) { @@ -933,7 +936,7 @@ public virtual Task WriteValueAsync(byte? value, CancellationToken cancellationT /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(byte[] value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(byte[]? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1294,7 +1297,7 @@ public virtual Task WriteValueAsync(long? value, CancellationToken cancellationT /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(object value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(object? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1391,7 +1394,7 @@ public virtual Task WriteValueAsync(short? value, CancellationToken cancellation /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(string value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(string? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -1528,7 +1531,7 @@ public virtual Task WriteValueAsync(ulong? value, CancellationToken cancellation /// A that represents the asynchronous operation. /// The default behaviour is to execute synchronously, returning an already-completed task. Derived /// classes can override this behaviour for true asynchronicity. - public virtual Task WriteValueAsync(Uri value, CancellationToken cancellationToken = default) + public virtual Task WriteValueAsync(Uri? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.cs index ed1e325bf..e2024c6c9 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -66,7 +69,7 @@ internal enum State // array that gives a new state based on the current state an the token being written private static readonly State[][] StateArray; - internal static readonly State[][] StateArrayTempate = new[] + internal static readonly State[][] StateArrayTemplate = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // @@ -82,9 +85,9 @@ internal enum State internal static State[][] BuildStateArray() { - List allStates = StateArrayTempate.ToList(); - State[] errorStates = StateArrayTempate[0]; - State[] valueStates = StateArrayTempate[7]; + List allStates = StateArrayTemplate.ToList(); + State[] errorStates = StateArrayTemplate[0]; + State[] valueStates = StateArrayTemplate[7]; EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken)); @@ -120,7 +123,7 @@ static JsonWriter() StateArray = BuildStateArray(); } - private List _stack; + private List? _stack; private JsonPosition _currentPosition; private State _currentState; private Formatting _formatting; @@ -222,7 +225,7 @@ public string Path JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; - return JsonPosition.BuildPath(_stack, current); + return JsonPosition.BuildPath(_stack!, current); } } @@ -230,8 +233,8 @@ public string Path private DateTimeZoneHandling _dateTimeZoneHandling; private StringEscapeHandling _stringEscapeHandling; private FloatFormatHandling _floatFormatHandling; - private string _dateFormatString; - private CultureInfo _culture; + private string? _dateFormatString; + private CultureInfo? _culture; /// /// Gets or sets a value indicating how JSON text output should be formatted. @@ -329,7 +332,7 @@ public FloatFormatHandling FloatFormatHandling /// /// Gets or sets how and values are formatted when writing JSON text. /// - public string DateFormatString + public string? DateFormatString { get => _dateFormatString; set => _dateFormatString = value; @@ -526,7 +529,7 @@ public void WriteToken(JsonReader reader, bool writeChildren) /// A value is only required for tokens that have an associated value, e.g. the property name for . /// null can be passed to the method for tokens that don't have a value, e.g. . /// - public void WriteToken(JsonToken token, object value) + public void WriteToken(JsonToken token, object? value) { switch (token) { @@ -583,8 +586,9 @@ public void WriteToken(JsonToken token, object value) } break; case JsonToken.String: - ValidationUtils.ArgumentNotNull(value, nameof(value)); - WriteValue(value.ToString()); + // Allow for a null string. This matches JTokenReader behavior which can read + // a JsonToken.String with a null value. + WriteValue(value?.ToString()); break; case JsonToken.Boolean: ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -629,7 +633,7 @@ public void WriteToken(JsonToken token, object value) } else { - WriteValue((byte[])value); + WriteValue((byte[])value!); } break; default: @@ -653,7 +657,7 @@ internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool wri do { // write a JValue date when the constructor is for a date - if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) + if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } @@ -670,12 +674,19 @@ internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool wri && writeChildren && reader.Read()); - if (initialDepth < CalculateWriteTokenFinalDepth(reader)) + if (IsWriteTokenIncomplete(reader, writeChildren, initialDepth)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } } + private bool IsWriteTokenIncomplete(JsonReader reader, bool writeChildren, int initialDepth) + { + int finalDepth = CalculateWriteTokenFinalDepth(reader); + return initialDepth < finalDepth || + (writeChildren && initialDepth == finalDepth && JsonTokenUtils.IsStartToken(reader.TokenType)); + } + private int CalculateWriteTokenInitialDepth(JsonReader reader) { JsonToken type = reader.TokenType; @@ -700,7 +711,7 @@ private int CalculateWriteTokenFinalDepth(JsonReader reader) private void WriteConstructorDate(JsonReader reader) { - if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string errorMessage)) + if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime dateTime, out string? errorMessage)) { throw JsonWriterException.Create(this, errorMessage, null); } @@ -791,7 +802,7 @@ private int CalculateLevelsToComplete(JsonContainerType type) { int currentLevel = top - i; - if (_stack[currentLevel].Type == type) + if (_stack![currentLevel].Type == type) { levelsToComplete = i + 2; break; @@ -913,7 +924,7 @@ public virtual void WriteUndefined() /// Writes raw JSON without changing the writer's state. /// /// The raw JSON to write. - public virtual void WriteRaw(string json) + public virtual void WriteRaw(string? json) { InternalWriteRaw(); } @@ -922,7 +933,7 @@ public virtual void WriteRaw(string json) /// Writes raw JSON where a value is expected and updates the writer's state. /// /// The raw JSON to write. - public virtual void WriteRawValue(string json) + public virtual void WriteRawValue(string? json) { // hack. want writer to change state as if a value had been written UpdateScopeWithFinishedValue(); @@ -934,7 +945,7 @@ public virtual void WriteRawValue(string json) /// Writes a value. /// /// The value to write. - public virtual void WriteValue(string value) + public virtual void WriteValue(string? value) { InternalWriteValue(JsonToken.String); } @@ -1380,7 +1391,7 @@ public virtual void WriteValue(TimeSpan? value) /// Writes a [] value. /// /// The [] value to write. - public virtual void WriteValue(byte[] value) + public virtual void WriteValue(byte[]? value) { if (value == null) { @@ -1396,7 +1407,7 @@ public virtual void WriteValue(byte[] value) /// Writes a value. /// /// The value to write. - public virtual void WriteValue(Uri value) + public virtual void WriteValue(Uri? value) { if (value == null) { @@ -1413,7 +1424,7 @@ public virtual void WriteValue(Uri value) /// An error will raised if the value cannot be written as a single JSON token. /// /// The value to write. - public virtual void WriteValue(object value) + public virtual void WriteValue(object? value) { if (value == null) { @@ -1439,7 +1450,7 @@ public virtual void WriteValue(object value) /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public virtual void WriteComment(string text) + public virtual void WriteComment(string? text) { InternalWriteComment(); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriterException.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriterException.cs index 7ad3ae9af..471622d7d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriterException.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/JsonWriterException.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -46,7 +49,7 @@ internal class JsonWriterException : JsonException /// Gets the path to the JSON where the error occurred. /// /// The path to the JSON where the error occurred. - public string Path { get; } + public string? Path { get; } /// /// Initializes a new instance of the class. @@ -97,18 +100,18 @@ public JsonWriterException(SerializationInfo info, StreamingContext context) /// The error message that explains the reason for the exception. /// The path to the JSON where the error occurred. /// The exception that is the cause of the current exception, or null if no inner exception is specified. - public JsonWriterException(string message, string path, Exception innerException) + public JsonWriterException(string message, string path, Exception? innerException) : base(message, innerException) { Path = path; } - internal static JsonWriterException Create(JsonWriter writer, string message, Exception ex) + internal static JsonWriterException Create(JsonWriter writer, string message, Exception? ex) { return Create(writer.ContainerPath, message, ex); } - internal static JsonWriterException Create(string path, string message, Exception ex) + internal static JsonWriterException Create(string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(null, path, message); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/CommentHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/CommentHandling.cs index e13990ab6..1bbc85039 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/CommentHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/CommentHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/DuplicatePropertyNameHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/DuplicatePropertyNameHandling.cs index aac5987ca..7dd104f7f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/DuplicatePropertyNameHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/DuplicatePropertyNameHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/Extensions.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/Extensions.cs index fed9c2c0b..65cf44973 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/Extensions.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/Extensions.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -31,6 +34,8 @@ using System.Collections.Generic; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -115,9 +120,9 @@ public static IJEnumerable Properties(this IEnumerable sourc /// An of that contains the source collection. /// The token key. /// An of that contains the values of every token in the source collection with the given key. - public static IJEnumerable Values(this IEnumerable source, object key) + public static IJEnumerable Values(this IEnumerable source, object? key) { - return Values(source, key).AsJEnumerable(); + return Values(source, key)!.AsJEnumerable(); } /// @@ -137,7 +142,7 @@ public static IJEnumerable Values(this IEnumerable source) /// An of that contains the source collection. /// The token key. /// An that contains the converted values of every token in the source collection with the given key. - public static IEnumerable Values(this IEnumerable source, object key) + public static IEnumerable Values(this IEnumerable source, object key) { return Values(source, key); } @@ -148,7 +153,7 @@ public static IEnumerable Values(this IEnumerable source, object k /// The type to convert the values to. /// An of that contains the source collection. /// An that contains the converted values of every token in the source collection. - public static IEnumerable Values(this IEnumerable source) + public static IEnumerable Values(this IEnumerable source) { return Values(source, null); } @@ -159,7 +164,7 @@ public static IEnumerable Values(this IEnumerable source) /// The type to convert the value to. /// A cast as a of . /// A converted value. - public static U Value(this IEnumerable value) + public static U? Value(this IEnumerable value) { return value.Value(); } @@ -171,7 +176,7 @@ public static U Value(this IEnumerable value) /// The type to convert the value to. /// A cast as a of . /// A converted value. - public static U Value(this IEnumerable value) where T : JToken + public static U? Value(this IEnumerable value) where T : JToken { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -183,7 +188,7 @@ public static U Value(this IEnumerable value) where T : JToken return token.Convert(); } - internal static IEnumerable Values(this IEnumerable source, object key) where T : JToken + internal static IEnumerable Values(this IEnumerable source, object? key) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); @@ -208,7 +213,7 @@ internal static IEnumerable Values(this IEnumerable source, object k { foreach (T token in source) { - JToken value = token[key]; + JToken? value = token[key]; if (value != null) { yield return value.Convert(); @@ -228,7 +233,7 @@ internal static IEnumerable Values(this IEnumerable source, object k /// An of that contains the values of every token in the source collection. public static IJEnumerable Children(this IEnumerable source) where T : JToken { - return Children(source).AsJEnumerable(); + return Children(source)!.AsJEnumerable(); } /// @@ -238,14 +243,14 @@ public static IJEnumerable Children(this IEnumerable source) where /// The type to convert the values to. /// The source collection type. /// An that contains the converted values of every token in the source collection. - public static IEnumerable Children(this IEnumerable source) where T : JToken + public static IEnumerable Children(this IEnumerable source) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); return source.SelectMany(c => c.Children()).Convert(); } - internal static IEnumerable Convert(this IEnumerable source) where T : JToken + internal static IEnumerable Convert(this IEnumerable source) where T : JToken { ValidationUtils.ArgumentNotNull(source, nameof(source)); @@ -255,11 +260,13 @@ internal static IEnumerable Convert(this IEnumerable source) where T } } - internal static U Convert(this T token) where T : JToken + internal static U? Convert(this T token) where T : JToken? { if (token == null) { +#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. return default; +#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } if (token is U castValue @@ -286,7 +293,9 @@ internal static U Convert(this T token) where T : JToken { if (value.Value == null) { +#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. return default; +#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. } targetType = Nullable.GetUnderlyingType(targetType); @@ -319,7 +328,7 @@ public static IJEnumerable AsJEnumerable(this IEnumerable source) where { if (source == null) { - return null; + return null!; } else if (source is IJEnumerable customEnumerable) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/IJEnumerable.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/IJEnumerable.cs index dd3e05099..61b14d886 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/IJEnumerable.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/IJEnumerable.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.Async.cs index 5e3ade86b..ea374f8be 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -77,7 +80,7 @@ public override async Task WriteToAsync(JsonWriter writer, CancellationToken can /// If this is null, default load settings will be used. /// The token to monitor for cancellation requests. The default value is . /// A representing the asynchronous load. The property contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.cs index d36a41f3c..a47d705fe 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JArray.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -119,7 +122,7 @@ internal override JToken CloneToken() /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JArray Load(JsonReader reader, JsonLoadSettings settings) + public new static JArray Load(JsonReader reader, JsonLoadSettings? settings) { if (reader.TokenType == JsonToken.None) { @@ -167,7 +170,7 @@ internal override JToken CloneToken() /// /// /// - public new static JArray Parse(string json, JsonLoadSettings settings) + public new static JArray Parse(string json, JsonLoadSettings? settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -231,7 +234,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter /// Gets the with the specified key. /// /// The with the specified key. - public override JToken this[object key] + public override JToken? this[object key] { get { @@ -267,14 +270,19 @@ public JToken this[int index] set => SetItem(index, value); } - internal override int IndexOfItem(JToken item) + internal override int IndexOfItem(JToken? item) { + if (item == null) + { + return -1; + } + return _values.IndexOfReference(item); } - internal override void MergeItem(object content, JsonMergeSettings settings) + internal override void MergeItem(object content, JsonMergeSettings? settings) { - IEnumerable a = (IsMultiContent(content) || content is JArray) + IEnumerable? a = (IsMultiContent(content) || content is JArray) ? (IEnumerable)content : null; if (a == null) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.Async.cs index c95b0739c..10c7dbc78 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -47,7 +50,7 @@ internal partial class JConstructor /// A that represents the asynchronous write operation. public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { - await writer.WriteStartConstructorAsync(_name, cancellationToken).ConfigureAwait(false); + await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false); for (int i = 0; i < _values.Count; i++) { @@ -80,7 +83,7 @@ public override async Task WriteToAsync(JsonWriter writer, CancellationToken can /// /// A that represents the asynchronous load. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { @@ -97,7 +100,7 @@ public override async Task WriteToAsync(JsonWriter writer, CancellationToken can throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JConstructor c = new JConstructor((string)reader.Value); + JConstructor c = new JConstructor((string)reader.Value!); c.SetLineInfo(reader as IJsonLineInfo, settings); await c.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.cs index a4c69e872..2f27f9cd0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JConstructor.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,7 +43,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq /// internal partial class JConstructor : JContainer { - private string _name; + private string? _name; private readonly List _values = new List(); /// @@ -49,12 +52,17 @@ internal partial class JConstructor : JContainer /// The container's children tokens. protected override IList ChildrenTokens => _values; - internal override int IndexOfItem(JToken item) + internal override int IndexOfItem(JToken? item) { + if (item == null) + { + return -1; + } + return _values.IndexOfReference(item); } - internal override void MergeItem(object content, JsonMergeSettings settings) + internal override void MergeItem(object content, JsonMergeSettings? settings) { if (!(content is JConstructor c)) { @@ -72,7 +80,7 @@ internal override void MergeItem(object content, JsonMergeSettings settings) /// Gets or sets the name of this constructor. /// /// The constructor name. - public string Name + public string? Name { get => _name; set => _name = value; @@ -158,7 +166,7 @@ internal override JToken CloneToken() /// A collection of which will be used when writing the token. public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { - writer.WriteStartConstructor(_name); + writer.WriteStartConstructor(_name!); int count = _values.Count; for (int i = 0; i < count; i++) @@ -173,7 +181,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter /// Gets the with the specified key. /// /// The with the specified key. - public override JToken this[object key] + public override JToken? this[object key] { get { @@ -201,7 +209,7 @@ public override JToken this[object key] internal override int GetDeepHashCode() { - return _name.GetHashCode() ^ ContentsHashCode(); + return (_name?.GetHashCode() ?? 0) ^ ContentsHashCode(); } /// @@ -221,7 +229,7 @@ internal override int GetDeepHashCode() /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JConstructor Load(JsonReader reader, JsonLoadSettings settings) + public new static JConstructor Load(JsonReader reader, JsonLoadSettings? settings) { if (reader.TokenType == JsonToken.None) { @@ -238,7 +246,7 @@ internal override int GetDeepHashCode() throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JConstructor c = new JConstructor((string)reader.Value); + JConstructor c = new JConstructor((string)reader.Value!); c.SetLineInfo(reader as IJsonLineInfo, settings); c.ReadTokenFrom(reader, settings); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.Async.cs index b2fcbe02f..8147647e2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +33,7 @@ #if HAVE_ASYNC using System; +using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -39,7 +43,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq { internal abstract partial class JContainer { - internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings options, CancellationToken cancellationToken = default) + internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings? options, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); int startDepth = reader.Depth; @@ -57,11 +61,11 @@ internal async Task ReadTokenFromAsync(JsonReader reader, JsonLoadSettings optio } } - private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { - IJsonLineInfo lineInfo = reader as IJsonLineInfo; + IJsonLineInfo? lineInfo = reader as IJsonLineInfo; - JContainer parent = this; + JContainer? parent = this; do { @@ -75,6 +79,8 @@ private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings sett parent = parent.Parent; } + MiscellaneousUtils.Assert(parent != null); + switch (reader.TokenType) { case JsonToken.None: @@ -110,7 +116,7 @@ private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings sett parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(reader.Value.ToString()); + JConstructor constructor = new JConstructor(reader.Value!.ToString()); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -136,7 +142,7 @@ private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings sett case JsonToken.Comment: if (settings != null && settings.CommentHandling == CommentHandling.Load) { - v = JValue.CreateComment(reader.Value.ToString()); + v = JValue.CreateComment(reader.Value!.ToString()); v.SetLineInfo(lineInfo, settings); parent.Add(v); } @@ -152,14 +158,14 @@ private async Task ReadContentFromAsync(JsonReader reader, JsonLoadSettings sett parent.Add(v); break; case JsonToken.PropertyName: - JProperty property = ReadProperty(reader, settings, lineInfo, parent); + JProperty? property = ReadProperty(reader, settings, lineInfo, parent); if (property != null) { parent = property; } else { - await reader.SkipAsync(); + await reader.SkipAsync().ConfigureAwait(false); } break; default: diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.cs index 168453f37..d4e4879f0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JContainer.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -37,11 +40,13 @@ using System.Collections; using System.Globalization; using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq @@ -59,8 +64,8 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq #endif { #if HAVE_COMPONENT_MODEL - internal ListChangedEventHandler _listChanged; - internal AddingNewEventHandler _addingNew; + internal ListChangedEventHandler? _listChanged; + internal AddingNewEventHandler? _addingNew; /// /// Occurs when the list changes or an item in the list changes. @@ -81,7 +86,7 @@ public event AddingNewEventHandler AddingNew } #endif #if HAVE_INOTIFY_COLLECTION_CHANGED - internal NotifyCollectionChangedEventHandler _collectionChanged; + internal NotifyCollectionChangedEventHandler? _collectionChanged; /// /// Occurs when the items list of the collection has changed, or the collection is reset. @@ -99,7 +104,7 @@ public event NotifyCollectionChangedEventHandler CollectionChanged /// The container's children tokens. protected abstract IList ChildrenTokens { get; } - private object _syncRoot; + private object? _syncRoot; #if (HAVE_COMPONENT_MODEL || HAVE_INOTIFY_COLLECTION_CHANGED) private bool _busy; #endif @@ -116,9 +121,11 @@ internal JContainer(JContainer other) int i = 0; foreach (JToken child in other) { - AddInternal(i, child, false); + TryAddInternal(i, child, false); i++; } + + CopyAnnotations(this, other); } internal void CheckReentrancy() @@ -152,7 +159,7 @@ protected virtual void OnAddingNew(AddingNewEventArgs e) /// The instance containing the event data. protected virtual void OnListChanged(ListChangedEventArgs e) { - ListChangedEventHandler handler = _listChanged; + ListChangedEventHandler? handler = _listChanged; if (handler != null) { @@ -175,7 +182,7 @@ protected virtual void OnListChanged(ListChangedEventArgs e) /// The instance containing the event data. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { - NotifyCollectionChangedEventHandler handler = _collectionChanged; + NotifyCollectionChangedEventHandler? handler = _collectionChanged; if (handler != null) { @@ -232,7 +239,7 @@ internal bool ContentsEqual(JContainer container) /// /// A containing the first child token of the . /// - public override JToken First + public override JToken? First { get { @@ -247,7 +254,7 @@ public override JToken First /// /// A containing the last child token of the . /// - public override JToken Last + public override JToken? Last { get { @@ -275,7 +282,7 @@ public override JEnumerable Children() /// /// A containing the child values of this , in document order. /// - public override IEnumerable Values() + public override IEnumerable Values() where T : default { return ChildrenTokens.Convert(); } @@ -318,12 +325,12 @@ internal IEnumerable GetDescendants(bool self) } } - internal bool IsMultiContent(object content) + internal bool IsMultiContent([NotNullWhen(true)]object? content) { return (content is IEnumerable && !(content is string) && !(content is JToken) && !(content is byte[])); } - internal JToken EnsureParentToken(JToken item, bool skipParentCheck) + internal JToken EnsureParentToken(JToken? item, bool skipParentCheck) { if (item == null) { @@ -347,9 +354,9 @@ internal JToken EnsureParentToken(JToken item, bool skipParentCheck) return item; } - internal abstract int IndexOfItem(JToken item); + internal abstract int IndexOfItem(JToken? item); - internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) + internal virtual bool InsertItem(int index, JToken? item, bool skipParentCheck) { IList children = ChildrenTokens; @@ -362,9 +369,9 @@ internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) item = EnsureParentToken(item, skipParentCheck); - JToken previous = (index == 0) ? null : children[index - 1]; + JToken? previous = (index == 0) ? null : children[index - 1]; // haven't inserted new token yet so next token is still at the inserting index - JToken next = (index == children.Count) ? null : children[index]; + JToken? next = (index == children.Count) ? null : children[index]; ValidateToken(item, null); @@ -396,6 +403,8 @@ internal virtual void InsertItem(int index, JToken item, bool skipParentCheck) OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index)); } #endif + + return true; } internal virtual void RemoveItemAt(int index) @@ -414,8 +423,8 @@ internal virtual void RemoveItemAt(int index) CheckReentrancy(); JToken item = children[index]; - JToken previous = (index == 0) ? null : children[index - 1]; - JToken next = (index == children.Count - 1) ? null : children[index + 1]; + JToken? previous = (index == 0) ? null : children[index - 1]; + JToken? next = (index == children.Count - 1) ? null : children[index + 1]; if (previous != null) { @@ -446,13 +455,16 @@ internal virtual void RemoveItemAt(int index) #endif } - internal virtual bool RemoveItem(JToken item) + internal virtual bool RemoveItem(JToken? item) { - int index = IndexOfItem(item); - if (index >= 0) + if (item != null) { - RemoveItemAt(index); - return true; + int index = IndexOfItem(item); + if (index >= 0) + { + RemoveItemAt(index); + return true; + } } return false; @@ -463,7 +475,7 @@ internal virtual JToken GetItem(int index) return ChildrenTokens[index]; } - internal virtual void SetItem(int index, JToken item) + internal virtual void SetItem(int index, JToken? item) { IList children = ChildrenTokens; @@ -489,8 +501,8 @@ internal virtual void SetItem(int index, JToken item) ValidateToken(item, existing); - JToken previous = (index == 0) ? null : children[index - 1]; - JToken next = (index == children.Count - 1) ? null : children[index + 1]; + JToken? previous = (index == 0) ? null : children[index - 1]; + JToken? next = (index == children.Count - 1) ? null : children[index + 1]; item.Parent = this; @@ -566,7 +578,7 @@ internal virtual void ReplaceItem(JToken existing, JToken replacement) SetItem(index, replacement); } - internal virtual bool ContainsItem(JToken item) + internal virtual bool ContainsItem(JToken? item) { return (IndexOfItem(item) != -1); } @@ -598,14 +610,14 @@ internal virtual void CopyItemsTo(Array array, int arrayIndex) } } - internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue) + internal static bool IsTokenUnchanged(JToken currentValue, JToken? newValue) { if (currentValue is JValue v1) { - // null will get turned into a JValue of type null - if (v1.Type == JTokenType.Null && newValue == null) + if (newValue == null) { - return true; + // null will get turned into a JValue of type null + return v1.Type == JTokenType.Null; } return v1.Equals(newValue); @@ -614,7 +626,7 @@ internal static bool IsTokenUnchanged(JToken currentValue, JToken newValue) return false; } - internal virtual void ValidateToken(JToken o, JToken existing) + internal virtual void ValidateToken(JToken o, JToken? existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); @@ -628,26 +640,31 @@ internal virtual void ValidateToken(JToken o, JToken existing) /// Adds the specified content as children of this . /// /// The content to be added. - public virtual void Add(object content) + public virtual void Add(object? content) { - AddInternal(ChildrenTokens.Count, content, false); + TryAddInternal(ChildrenTokens.Count, content, false); + } + + internal bool TryAdd(object? content) + { + return TryAddInternal(ChildrenTokens.Count, content, false); } internal void AddAndSkipParentCheck(JToken token) { - AddInternal(ChildrenTokens.Count, token, true); + TryAddInternal(ChildrenTokens.Count, token, true); } /// /// Adds the specified content as the first children of this . /// /// The content to be added. - public void AddFirst(object content) + public void AddFirst(object? content) { - AddInternal(0, content, false); + TryAddInternal(0, content, false); } - internal void AddInternal(int index, object content, bool skipParentCheck) + internal bool TryAddInternal(int index, object? content, bool skipParentCheck) { if (IsMultiContent(content)) { @@ -656,19 +673,21 @@ internal void AddInternal(int index, object content, bool skipParentCheck) int multiIndex = index; foreach (object c in enumerable) { - AddInternal(multiIndex, c, skipParentCheck); + TryAddInternal(multiIndex, c, skipParentCheck); multiIndex++; } + + return true; } else { JToken item = CreateFromContent(content); - InsertItem(index, item, skipParentCheck); + return InsertItem(index, item, skipParentCheck); } } - internal static JToken CreateFromContent(object content) + internal static JToken CreateFromContent(object? content) { if (content is JToken token) { @@ -705,7 +724,7 @@ public void RemoveAll() ClearItems(); } - internal abstract void MergeItem(object content, JsonMergeSettings settings); + internal abstract void MergeItem(object content, JsonMergeSettings? settings); /// /// Merge the specified content into this . @@ -713,7 +732,7 @@ public void RemoveAll() /// The content to be merged. public void Merge(object content) { - MergeItem(content, new JsonMergeSettings()); + MergeItem(content, null); } /// @@ -721,12 +740,12 @@ public void Merge(object content) /// /// The content to be merged. /// The used to merge the content. - public void Merge(object content, JsonMergeSettings settings) + public void Merge(object content, JsonMergeSettings? settings) { MergeItem(content, settings); } - internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options) + internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings? options) { int startDepth = reader.Depth; @@ -745,12 +764,12 @@ internal void ReadTokenFrom(JsonReader reader, JsonLoadSettings options) } } - internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) + internal void ReadContentFrom(JsonReader r, JsonLoadSettings? settings) { ValidationUtils.ArgumentNotNull(r, nameof(r)); - IJsonLineInfo lineInfo = r as IJsonLineInfo; + IJsonLineInfo? lineInfo = r as IJsonLineInfo; - JContainer parent = this; + JContainer? parent = this; do { @@ -764,6 +783,8 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) parent = parent.Parent; } + MiscellaneousUtils.Assert(parent != null); + switch (r.TokenType) { case JsonToken.None: @@ -799,7 +820,7 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) parent = parent.Parent; break; case JsonToken.StartConstructor: - JConstructor constructor = new JConstructor(r.Value.ToString()); + JConstructor constructor = new JConstructor(r.Value!.ToString()); constructor.SetLineInfo(lineInfo, settings); parent.Add(constructor); parent = constructor; @@ -825,7 +846,7 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) case JsonToken.Comment: if (settings != null && settings.CommentHandling == CommentHandling.Load) { - v = JValue.CreateComment(r.Value.ToString()); + v = JValue.CreateComment(r.Value!.ToString()); v.SetLineInfo(lineInfo, settings); parent.Add(v); } @@ -841,7 +862,7 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) parent.Add(v); break; case JsonToken.PropertyName: - JProperty property = ReadProperty(r, settings, lineInfo, parent); + JProperty? property = ReadProperty(r, settings, lineInfo, parent); if (property != null) { parent = property; @@ -857,13 +878,13 @@ internal void ReadContentFrom(JsonReader r, JsonLoadSettings settings) } while (r.Read()); } - private static JProperty ReadProperty(JsonReader r, JsonLoadSettings settings, IJsonLineInfo lineInfo, JContainer parent) + private static JProperty? ReadProperty(JsonReader r, JsonLoadSettings? settings, IJsonLineInfo? lineInfo, JContainer parent) { DuplicatePropertyNameHandling duplicatePropertyNameHandling = settings?.DuplicatePropertyNameHandling ?? DuplicatePropertyNameHandling.Replace; JObject parentObject = (JObject)parent; - string propertyName = r.Value.ToString(); - JProperty existingPropertyWithName = parentObject.Property(propertyName); + string propertyName = r.Value!.ToString(); + JProperty? existingPropertyWithName = parentObject.Property(propertyName, StringComparison.Ordinal); if (existingPropertyWithName != null) { if (duplicatePropertyNameHandling == DuplicatePropertyNameHandling.Ignore) @@ -907,9 +928,9 @@ string ITypedList.GetListName(PropertyDescriptor[] listAccessors) return string.Empty; } - PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) + PropertyDescriptorCollection? ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { - ICustomTypeDescriptor d = First as ICustomTypeDescriptor; + ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; return d?.GetProperties(); } #endif @@ -966,7 +987,7 @@ bool ICollection.Remove(JToken item) } #endregion - private JToken EnsureValue(object value) + private JToken? EnsureValue(object value) { if (value == null) { @@ -1112,7 +1133,7 @@ void IBindingList.RemoveSort() ListSortDirection IBindingList.SortDirection => ListSortDirection.Ascending; - PropertyDescriptor IBindingList.SortProperty => null; + PropertyDescriptor? IBindingList.SortProperty => null; bool IBindingList.SupportsChangeNotification => true; @@ -1122,9 +1143,9 @@ void IBindingList.RemoveSort() #endif #endregion - internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings settings) + internal static void MergeEnumerableContent(JContainer target, IEnumerable content, JsonMergeSettings? settings) { - switch (settings.MergeArrayHandling) + switch (settings?.MergeArrayHandling ?? MergeArrayHandling.Concat) { case MergeArrayHandling.Concat: foreach (JToken item in content) @@ -1161,6 +1182,10 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte #endif break; case MergeArrayHandling.Replace: + if (target == content) + { + break; + } target.ClearItems(); foreach (JToken item in content) { @@ -1173,7 +1198,7 @@ internal static void MergeEnumerableContent(JContainer target, IEnumerable conte { if (i < target.Count) { - JToken sourceItem = target[i]; + JToken? sourceItem = target[i]; if (sourceItem is JContainer existingContainer) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JEnumerable.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JEnumerable.cs index 4992e0fb9..1070e1044 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JEnumerable.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JEnumerable.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -92,7 +95,7 @@ public IJEnumerable this[object key] return JEnumerable.Empty; } - return new JEnumerable(_enumerable.Values(key)); + return new JEnumerable(_enumerable.Values(key)!); } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.Async.cs index aa06d1a15..cc71430e2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -101,7 +104,7 @@ async Task AwaitProperties(Task task, int i, JsonWriter Writer, CancellationToke /// /// A that represents the asynchronous load. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.cs index 68d3f744c..819a015ca 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JObject.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -41,6 +44,8 @@ using System.IO; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -55,7 +60,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq /// /// /// - internal partial class JObject : JContainer, IDictionary, INotifyPropertyChanged + internal partial class JObject : JContainer, IDictionary, INotifyPropertyChanged #if HAVE_COMPONENT_MODEL , ICustomTypeDescriptor #endif @@ -74,13 +79,13 @@ internal partial class JObject : JContainer, IDictionary, INotif /// /// Occurs when a property value changes. /// - public event PropertyChangedEventHandler PropertyChanged; + public event PropertyChangedEventHandler? PropertyChanged; #if HAVE_INOTIFY_PROPERTY_CHANGING /// /// Occurs when a property value is changing. /// - public event PropertyChangingEventHandler PropertyChanging; + public event PropertyChangingEventHandler? PropertyChanging; #endif /// @@ -127,23 +132,28 @@ internal override bool DeepEquals(JToken node) return _properties.Compare(t._properties); } - internal override int IndexOfItem(JToken item) + internal override int IndexOfItem(JToken? item) { + if (item == null) + { + return -1; + } + return _properties.IndexOfReference(item); } - internal override void InsertItem(int index, JToken item, bool skipParentCheck) + internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) { - return; + return false; } - base.InsertItem(index, item, skipParentCheck); + return base.InsertItem(index, item, skipParentCheck); } - internal override void ValidateToken(JToken o, JToken existing) + internal override void ValidateToken(JToken o, JToken? existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); @@ -170,16 +180,16 @@ internal override void ValidateToken(JToken o, JToken existing) } } - internal override void MergeItem(object content, JsonMergeSettings settings) + internal override void MergeItem(object content, JsonMergeSettings? settings) { if (!(content is JObject o)) { return; } - foreach (KeyValuePair contentItem in o) + foreach (KeyValuePair contentItem in o) { - JProperty existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal); + JProperty? existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal); if (existingProperty == null) { @@ -266,7 +276,7 @@ public IEnumerable Properties() /// /// The property name. /// A with the specified name or null. - public JProperty Property(string name) + public JProperty? Property(string name) { return Property(name, StringComparison.Ordinal); } @@ -279,14 +289,14 @@ public JProperty Property(string name) /// The property name. /// One of the enumeration values that specifies how the strings will be compared. /// A matched with the specified name or null. - public JProperty Property(string name, StringComparison comparison) + public JProperty? Property(string name, StringComparison comparison) { if (name == null) { return null; } - if (_properties.TryGetValue(name, out JToken property)) + if (_properties.TryGetValue(name, out JToken? property)) { return (JProperty)property; } @@ -320,7 +330,7 @@ public JEnumerable PropertyValues() /// Gets the with the specified key. /// /// The with the specified key. - public override JToken this[object key] + public override JToken? this[object key] { get { @@ -350,29 +360,29 @@ public override JToken this[object key] /// Gets or sets the with the specified property name. /// /// - public JToken this[string propertyName] + public JToken? this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); - JProperty property = Property(propertyName); + JProperty? property = Property(propertyName, StringComparison.Ordinal); return property?.Value; } set { - JProperty property = Property(propertyName); + JProperty? property = Property(propertyName, StringComparison.Ordinal); if (property != null) { - property.Value = value; + property.Value = value!; } else { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(propertyName); #endif - Add(new JProperty(propertyName, value)); + Add(propertyName, value); OnPropertyChanged(propertyName); } } @@ -401,7 +411,7 @@ public JToken this[string propertyName] /// /// is not valid JSON. /// - public new static JObject Load(JsonReader reader, JsonLoadSettings settings) + public new static JObject Load(JsonReader reader, JsonLoadSettings? settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -457,7 +467,7 @@ public JToken this[string propertyName] /// /// /// - public new static JObject Parse(string json, JsonLoadSettings settings) + public new static JObject Parse(string json, JsonLoadSettings? settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -492,7 +502,7 @@ public JToken this[string propertyName] { JToken token = FromObjectInternal(o, jsonSerializer); - if (token != null && token.Type != JTokenType.Object) + if (token.Type != JTokenType.Object) { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); } @@ -522,7 +532,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter /// /// Name of the property. /// The with the specified property name. - public JToken GetValue(string propertyName) + public JToken? GetValue(string? propertyName) { return GetValue(propertyName, StringComparison.Ordinal); } @@ -535,7 +545,7 @@ public JToken GetValue(string propertyName) /// Name of the property. /// One of the enumeration values that specifies how the strings will be compared. /// The with the specified property name. - public JToken GetValue(string propertyName, StringComparison comparison) + public JToken? GetValue(string? propertyName, StringComparison comparison) { if (propertyName == null) { @@ -557,7 +567,7 @@ public JToken GetValue(string propertyName, StringComparison comparison) /// The value. /// One of the enumeration values that specifies how the strings will be compared. /// true if a value was successfully retrieved; otherwise, false. - public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) + public bool TryGetValue(string propertyName, StringComparison comparison, [NotNullWhen(true)]out JToken? value) { value = GetValue(propertyName, comparison); return (value != null); @@ -569,7 +579,7 @@ public bool TryGetValue(string propertyName, StringComparison comparison, out JT /// /// Name of the property. /// The value. - public void Add(string propertyName, JToken value) + public void Add(string propertyName, JToken? value) { Add(new JProperty(propertyName, value)); } @@ -586,7 +596,7 @@ public bool ContainsKey(string propertyName) return _properties.Contains(propertyName); } - ICollection IDictionary.Keys => _properties.Keys; + ICollection IDictionary.Keys => _properties.Keys; /// /// Removes the property with the specified name. @@ -595,7 +605,7 @@ public bool ContainsKey(string propertyName) /// true if item was successfully removed; otherwise, false. public bool Remove(string propertyName) { - JProperty property = Property(propertyName); + JProperty? property = Property(propertyName, StringComparison.Ordinal); if (property == null) { return false; @@ -611,9 +621,9 @@ public bool Remove(string propertyName) /// Name of the property. /// The value. /// true if a value was successfully retrieved; otherwise, false. - public bool TryGetValue(string propertyName, out JToken value) + public bool TryGetValue(string propertyName, [NotNullWhen(true)]out JToken? value) { - JProperty property = Property(propertyName); + JProperty? property = Property(propertyName, StringComparison.Ordinal); if (property == null) { value = null; @@ -624,24 +634,24 @@ public bool TryGetValue(string propertyName, out JToken value) return true; } - ICollection IDictionary.Values => throw new NotImplementedException(); + ICollection IDictionary.Values => throw new NotImplementedException(); #endregion #region ICollection> Members - void ICollection>.Add(KeyValuePair item) + void ICollection>.Add(KeyValuePair item) { Add(new JProperty(item.Key, item.Value)); } - void ICollection>.Clear() + void ICollection>.Clear() { RemoveAll(); } - bool ICollection>.Contains(KeyValuePair item) + bool ICollection>.Contains(KeyValuePair item) { - JProperty property = Property(item.Key); + JProperty? property = Property(item.Key, StringComparison.Ordinal); if (property == null) { return false; @@ -650,7 +660,7 @@ bool ICollection>.Contains(KeyValuePair>.CopyTo(KeyValuePair[] array, int arrayIndex) + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { if (array == null) { @@ -672,16 +682,16 @@ void ICollection>.CopyTo(KeyValuePair(property.Name, property.Value); + array[arrayIndex + index] = new KeyValuePair(property.Name, property.Value); index++; } } - bool ICollection>.IsReadOnly => false; + bool ICollection>.IsReadOnly => false; - bool ICollection>.Remove(KeyValuePair item) + bool ICollection>.Remove(KeyValuePair item) { - if (!((ICollection>)this).Contains(item)) + if (!((ICollection>)this).Contains(item)) { return false; } @@ -702,11 +712,11 @@ internal override int GetDeepHashCode() /// /// A that can be used to iterate through the collection. /// - public IEnumerator> GetEnumerator() + public IEnumerator> GetEnumerator() { foreach (JProperty property in _properties) { - yield return new KeyValuePair(property.Name, property.Value); + yield return new KeyValuePair(property.Name, property.Value); } } @@ -741,14 +751,15 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { - PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); - - foreach (KeyValuePair propertyValue in this) + PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; + int i = 0; + foreach (KeyValuePair propertyValue in this) { - descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); + propertiesArray[i] = new JPropertyDescriptor(propertyValue.Key); + i++; } - return descriptors; + return new PropertyDescriptorCollection(propertiesArray); } AttributeCollection ICustomTypeDescriptor.GetAttributes() @@ -756,12 +767,12 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() return AttributeCollection.Empty; } - string ICustomTypeDescriptor.GetClassName() + string? ICustomTypeDescriptor.GetClassName() { return null; } - string ICustomTypeDescriptor.GetComponentName() + string? ICustomTypeDescriptor.GetComponentName() { return null; } @@ -771,17 +782,17 @@ TypeConverter ICustomTypeDescriptor.GetConverter() return new TypeConverter(); } - EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() + EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent() { return null; } - PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() + PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty() { return null; } - object ICustomTypeDescriptor.GetEditor(Type editorBaseType) + object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } @@ -796,7 +807,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() return EventDescriptorCollection.Empty; } - object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) + object? ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { if (pd is JPropertyDescriptor) { @@ -824,7 +835,7 @@ protected override DynamicMetaObject GetMetaObject(Expression parameter) private class JObjectDynamicProxy : DynamicProxy { - public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) + public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object? result) { // result can be null result = instance[binder.Name]; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.Async.cs index 35aa44443..63856e967 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -92,7 +95,7 @@ private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationTo /// The token to monitor for cancellation requests. The default value is . /// A representing the asynchronous creation. The /// property returns a that contains the JSON that was read from the specified . - public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public new static async Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { if (reader.TokenType == JsonToken.None) { @@ -109,7 +112,7 @@ private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationTo throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JProperty p = new JProperty((string)reader.Value); + JProperty p = new JProperty((string)reader.Value!); p.SetLineInfo(reader as IJsonLineInfo, settings); await p.ReadTokenFromAsync(reader, settings, cancellationToken).ConfigureAwait(false); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.cs index 9103d0d00..3230b9c6b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JProperty.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal partial class JProperty : JContainer #region JPropertyList private class JPropertyList : IList { - internal JToken _token; + internal JToken? _token; public IEnumerator GetEnumerator() { @@ -119,13 +122,24 @@ public void RemoveAt(int index) public JToken this[int index] { - get => (index == 0) ? _token : null; + get + { + if (index != 0) + { + throw new IndexOutOfRangeException(); + } + + MiscellaneousUtils.Assert(_token != null); + return _token; + } set { - if (index == 0) + if (index != 0) { - _token = value; + throw new IndexOutOfRangeException(); } + + _token = value; } } } @@ -157,7 +171,7 @@ public string Name public JToken Value { [DebuggerStepThrough] - get { return _content._token; } + get { return _content._token!; } set { CheckReentrancy(); @@ -195,7 +209,7 @@ internal override JToken GetItem(int index) return Value; } - internal override void SetItem(int index, JToken item) + internal override void SetItem(int index, JToken? item) { if (index != 0) { @@ -207,14 +221,14 @@ internal override void SetItem(int index, JToken item) return; } - ((JObject)Parent)?.InternalPropertyChanging(this); + ((JObject?)Parent)?.InternalPropertyChanging(this); base.SetItem(0, item); - ((JObject)Parent)?.InternalPropertyChanged(this); + ((JObject?)Parent)?.InternalPropertyChanged(this); } - internal override bool RemoveItem(JToken item) + internal override bool RemoveItem(JToken? item) { throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } @@ -224,17 +238,22 @@ internal override void RemoveItemAt(int index) throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } - internal override int IndexOfItem(JToken item) + internal override int IndexOfItem(JToken? item) { + if (item == null) + { + return -1; + } + return _content.IndexOf(item); } - internal override void InsertItem(int index, JToken item, bool skipParentCheck) + internal override bool InsertItem(int index, JToken? item, bool skipParentCheck) { // don't add comments to JProperty if (item != null && item.Type == JTokenType.Comment) { - return; + return false; } if (Value != null) @@ -242,17 +261,17 @@ internal override void InsertItem(int index, JToken item, bool skipParentCheck) throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } - base.InsertItem(0, item, false); + return base.InsertItem(0, item, false); } - internal override bool ContainsItem(JToken item) + internal override bool ContainsItem(JToken? item) { return (Value == item); } - internal override void MergeItem(object content, JsonMergeSettings settings) + internal override void MergeItem(object content, JsonMergeSettings? settings) { - JToken value = (content as JProperty)?.Value; + JToken? value = (content as JProperty)?.Value; if (value != null && value.Type != JTokenType.Null) { @@ -308,7 +327,7 @@ public JProperty(string name, params object[] content) /// /// The property name. /// The property content. - public JProperty(string name, object content) + public JProperty(string name, object? content) { ValidationUtils.ArgumentNotNull(name, nameof(name)); @@ -361,7 +380,7 @@ internal override int GetDeepHashCode() /// The used to load the JSON. /// If this is null, default load settings will be used. /// A that contains the JSON that was read from the specified . - public new static JProperty Load(JsonReader reader, JsonLoadSettings settings) + public new static JProperty Load(JsonReader reader, JsonLoadSettings? settings) { if (reader.TokenType == JsonToken.None) { @@ -378,7 +397,7 @@ internal override int GetDeepHashCode() throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } - JProperty p = new JProperty((string)reader.Value); + JProperty p = new JProperty((string)reader.Value!); p.SetLineInfo(reader as IJsonLineInfo, settings); p.ReadTokenFrom(reader, settings); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyDescriptor.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyDescriptor.cs index 2f9919a30..fc7828643 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyDescriptor.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyDescriptor.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -71,7 +74,7 @@ public override bool CanResetValue(object component) /// The value of a property for a given component. /// /// The component with the property for which to retrieve the value. - public override object GetValue(object component) + public override object? GetValue(object component) { return (component as JObject)?[Name]; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs index fa89e1403..6a4f626b5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JPropertyKeyedCollection.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +33,8 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq @@ -38,7 +43,7 @@ internal class JPropertyKeyedCollection : Collection { private static readonly IEqualityComparer Comparer = StringComparer.Ordinal; - private Dictionary _dictionary; + private Dictionary? _dictionary; public JPropertyKeyedCollection() : base(new List()) { @@ -47,7 +52,7 @@ public JPropertyKeyedCollection() : base(new List()) private void AddKey(string key, JToken item) { EnsureDictionary(); - _dictionary[key] = item; + _dictionary![key] = item; } protected void ChangeItemKey(JToken item, string newKey) @@ -133,7 +138,7 @@ public bool Remove(string key) if (_dictionary != null) { - return _dictionary.ContainsKey(key) && Remove(_dictionary[key]); + return _dictionary.TryGetValue(key, out JToken value) && Remove(value); } return false; @@ -193,7 +198,7 @@ public JToken this[string key] } } - public bool TryGetValue(string key, out JToken value) + public bool TryGetValue(string key, [NotNullWhen(true)]out JToken? value) { if (_dictionary == null) { @@ -209,7 +214,7 @@ public ICollection Keys get { EnsureDictionary(); - return _dictionary.Keys; + return _dictionary!.Keys; } } @@ -218,7 +223,7 @@ public ICollection Values get { EnsureDictionary(); - return _dictionary.Values; + return _dictionary!.Values; } } @@ -236,8 +241,8 @@ public bool Compare(JPropertyKeyedCollection other) // dictionaries in JavaScript aren't ordered // ignore order when comparing properties - Dictionary d1 = _dictionary; - Dictionary d2 = other._dictionary; + Dictionary? d1 = _dictionary; + Dictionary? d2 = other._dictionary; if (d1 == null && d2 == null) { @@ -246,7 +251,7 @@ public bool Compare(JPropertyKeyedCollection other) if (d1 == null) { - return (d2.Count == 0); + return (d2!.Count == 0); } if (d2 == null) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.Async.cs index cc6eca612..6d557ff2a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.cs index bee40494f..7d16c8156 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JRaw.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -50,7 +53,7 @@ public JRaw(JRaw other) /// Initializes a new instance of the class. /// /// The raw json. - public JRaw(object rawJson) + public JRaw(object? rawJson) : base(rawJson, JTokenType.Raw) { } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.Async.cs index 048ea1579..d6dd1c4c3 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -93,7 +96,7 @@ public static Task ReadFromAsync(JsonReader reader, CancellationToken ca /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -105,7 +108,7 @@ public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettin } } - IJsonLineInfo lineInfo = reader as IJsonLineInfo; + IJsonLineInfo? lineInfo = reader as IJsonLineInfo; switch (reader.TokenType) { @@ -127,7 +130,7 @@ public static async Task ReadFromAsync(JsonReader reader, JsonLoadSettin v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Comment: - v = JValue.CreateComment(reader.Value.ToString()); + v = JValue.CreateComment(reader.Value?.ToString()); v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Null: @@ -172,7 +175,7 @@ public static Task LoadAsync(JsonReader reader, CancellationToken cancel /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static Task LoadAsync(JsonReader reader, JsonLoadSettings settings, CancellationToken cancellationToken = default) + public static Task LoadAsync(JsonReader reader, JsonLoadSettings? settings, CancellationToken cancellationToken = default) { return ReadFromAsync(reader, settings, cancellationToken); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.cs index a2d3c50c5..d5c8c502b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JToken.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -42,11 +45,12 @@ using System.Diagnostics; using System.Globalization; using System.Collections; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq @@ -62,12 +66,12 @@ internal abstract partial class JToken : IJEnumerable, IJsonLineInfo , IDynamicMetaObjectProvider #endif { - private static JTokenEqualityComparer _equalityComparer; + private static JTokenEqualityComparer? _equalityComparer; - private JContainer _parent; - private JToken _previous; - private JToken _next; - private object _annotations; + private JContainer? _parent; + private JToken? _previous; + private JToken? _next; + private object? _annotations; private static readonly JTokenType[] BooleanTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; private static readonly JTokenType[] NumberTypes = new[] { JTokenType.Integer, JTokenType.Float, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Boolean }; @@ -103,7 +107,7 @@ public static JTokenEqualityComparer EqualityComparer /// Gets or sets the parent. /// /// The parent. - public JContainer Parent + public JContainer? Parent { [DebuggerStepThrough] get { return _parent; } @@ -118,7 +122,7 @@ public JToken Root { get { - JContainer parent = Parent; + JContainer? parent = Parent; if (parent == null) { return this; @@ -156,7 +160,7 @@ public JToken Root /// The first to compare. /// The second to compare. /// true if the tokens are equal; otherwise false. - public static bool DeepEquals(JToken t1, JToken t2) + public static bool DeepEquals(JToken? t1, JToken? t2) { return (t1 == t2 || (t1 != null && t2 != null && t1.DeepEquals(t2))); } @@ -165,7 +169,7 @@ public static bool DeepEquals(JToken t1, JToken t2) /// Gets the next sibling token of this node. /// /// The that contains the next sibling token. - public JToken Next + public JToken? Next { get => _next; internal set => _next = value; @@ -175,7 +179,7 @@ public JToken Next /// Gets the previous sibling token of this node. /// /// The that contains the previous sibling token. - public JToken Previous + public JToken? Previous { get => _previous; internal set => _previous = value; @@ -194,8 +198,8 @@ public string Path } List positions = new List(); - JToken previous = null; - for (JToken current = this; current != null; current = current.Parent) + JToken? previous = null; + for (JToken? current = this; current != null; current = current.Parent) { switch (current.Type) { @@ -235,7 +239,7 @@ internal JToken() /// Adds the specified content immediately after this token. /// /// A content object that contains simple content or a collection of content objects to be added after this token. - public void AddAfterSelf(object content) + public void AddAfterSelf(object? content) { if (_parent == null) { @@ -243,14 +247,14 @@ public void AddAfterSelf(object content) } int index = _parent.IndexOfItem(this); - _parent.AddInternal(index + 1, content, false); + _parent.TryAddInternal(index + 1, content, false); } /// /// Adds the specified content immediately before this token. /// /// A content object that contains simple content or a collection of content objects to be added before this token. - public void AddBeforeSelf(object content) + public void AddBeforeSelf(object? content) { if (_parent == null) { @@ -258,7 +262,7 @@ public void AddBeforeSelf(object content) } int index = _parent.IndexOfItem(this); - _parent.AddInternal(index, content, false); + _parent.TryAddInternal(index, content, false); } /// @@ -281,7 +285,7 @@ public IEnumerable AncestorsAndSelf() internal IEnumerable GetAncestors(bool self) { - for (JToken current = self ? this : Parent; current != null; current = current.Parent) + for (JToken? current = self ? this : Parent; current != null; current = current.Parent) { yield return current; } @@ -298,7 +302,7 @@ public IEnumerable AfterSelf() yield break; } - for (JToken o = Next; o != null; o = o.Next) + for (JToken? o = Next; o != null; o = o.Next) { yield return o; } @@ -310,7 +314,12 @@ public IEnumerable AfterSelf() /// A collection of the sibling tokens before this token, in document order. public IEnumerable BeforeSelf() { - for (JToken o = Parent.First; o != this; o = o.Next) + if (Parent == null) + { + yield break; + } + + for (JToken? o = Parent.First; o != this && o != null; o = o.Next) { yield return o; } @@ -320,7 +329,7 @@ public IEnumerable BeforeSelf() /// Gets the with the specified key. /// /// The with the specified key. - public virtual JToken this[object key] + public virtual JToken? this[object key] { get => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); set => throw new InvalidOperationException("Cannot set child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); @@ -332,9 +341,9 @@ public virtual JToken this[object key] /// The type to convert the token to. /// The token key. /// The converted token value. - public virtual T Value(object key) + public virtual T? Value(object key) { - JToken token = this[key]; + JToken? token = this[key]; // null check to fix MonoTouch issue - https://github.com/dolbz/Newtonsoft.Json/commit/a24e3062846b30ee505f3271ac08862bb471b822 return token == null ? default : Extensions.Convert(token); @@ -344,13 +353,13 @@ public virtual T Value(object key) /// Get the first child token of this token. /// /// A containing the first child token of the . - public virtual JToken First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); + public virtual JToken? First => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); /// /// Get the last child token of this token. /// /// A containing the last child token of the . - public virtual JToken Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); + public virtual JToken? Last => throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); /// /// Returns a collection of the child tokens of this token, in document order. @@ -376,7 +385,7 @@ public JEnumerable Children() where T : JToken /// /// The type to convert the values to. /// A containing the child values of this , in document order. - public virtual IEnumerable Values() + public virtual IEnumerable Values() { throw new InvalidOperationException("Cannot access child value on {0}.".FormatWith(CultureInfo.InvariantCulture, GetType())); } @@ -418,6 +427,10 @@ public void Replace(JToken value) /// /// Returns the indented JSON for this token. /// + /// + /// ToString() returns a non-JSON string value for tokens with a type of . + /// If you want the JSON for all token types then you should use . + /// /// /// The indented JSON for this token. /// @@ -445,7 +458,7 @@ public string ToString(Formatting formatting, params JsonConverter[] converters) } } - private static JValue EnsureValue(JToken value) + private static JValue? EnsureValue(JToken value) { if (value == null) { @@ -457,7 +470,7 @@ private static JValue EnsureValue(JToken value) value = property.Value; } - JValue v = value as JValue; + JValue? v = value as JValue; return v; } @@ -479,7 +492,7 @@ private static bool ValidateToken(JToken o, JTokenType[] validTypes, bool nullab return (Array.IndexOf(validTypes, o.Type) != -1) || (nullable && (o.Type == JTokenType.Null || o.Type == JTokenType.Undefined)); } -#region Cast from operators + #region Cast from operators /// /// Performs an explicit conversion from to . /// @@ -487,7 +500,7 @@ private static bool ValidateToken(JToken o, JTokenType[] validTypes, bool nullab /// The result of the conversion. public static explicit operator bool(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, false)) { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -511,7 +524,7 @@ public static explicit operator bool(JToken value) /// The result of the conversion. public static explicit operator DateTimeOffset(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -536,14 +549,14 @@ public static explicit operator DateTimeOffset(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator bool?(JToken value) + public static explicit operator bool?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, BooleanTypes, true)) { throw new ArgumentException("Can not convert {0} to Boolean.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -566,7 +579,7 @@ public static explicit operator DateTimeOffset(JToken value) /// The result of the conversion. public static explicit operator long(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -587,14 +600,14 @@ public static explicit operator long(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator DateTime?(JToken value) + public static explicit operator DateTime?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -616,14 +629,14 @@ public static explicit operator long(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator DateTimeOffset?(JToken value) + public static explicit operator DateTimeOffset?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, true)) { throw new ArgumentException("Can not convert {0} to DateTimeOffset.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -652,14 +665,14 @@ public static explicit operator long(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator decimal?(JToken value) + public static explicit operator decimal?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -680,14 +693,14 @@ public static explicit operator long(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator double?(JToken value) + public static explicit operator double?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -708,14 +721,14 @@ public static explicit operator long(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator char?(JToken value) + public static explicit operator char?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, true)) { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -738,7 +751,7 @@ public static explicit operator long(JToken value) /// The result of the conversion. public static explicit operator int(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -761,7 +774,7 @@ public static explicit operator int(JToken value) /// The result of the conversion. public static explicit operator short(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -785,7 +798,7 @@ public static explicit operator short(JToken value) // [CLSCompliant(false)] public static explicit operator ushort(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -809,7 +822,7 @@ public static explicit operator ushort(JToken value) // [CLSCompliant(false)] public static explicit operator char(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, CharTypes, false)) { throw new ArgumentException("Can not convert {0} to Char.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -832,7 +845,7 @@ public static explicit operator char(JToken value) /// The result of the conversion. public static explicit operator byte(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -856,7 +869,7 @@ public static explicit operator byte(JToken value) // [CLSCompliant(false)] public static explicit operator sbyte(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -877,14 +890,14 @@ public static explicit operator sbyte(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator int?(JToken value) + public static explicit operator int?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -905,14 +918,14 @@ public static explicit operator sbyte(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator short?(JToken value) + public static explicit operator short?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -934,14 +947,14 @@ public static explicit operator sbyte(JToken value) /// The value. /// The result of the conversion. // [CLSCompliant(false)] - public static explicit operator ushort?(JToken value) + public static explicit operator ushort?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt16.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -962,14 +975,14 @@ public static explicit operator sbyte(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator byte?(JToken value) + public static explicit operator byte?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Byte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -991,14 +1004,14 @@ public static explicit operator sbyte(JToken value) /// The value. /// The result of the conversion. // [CLSCompliant(false)] - public static explicit operator sbyte?(JToken value) + public static explicit operator sbyte?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to SByte.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1021,7 +1034,7 @@ public static explicit operator sbyte(JToken value) /// The result of the conversion. public static explicit operator DateTime(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, DateTimeTypes, false)) { throw new ArgumentException("Can not convert {0} to DateTime.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1042,14 +1055,14 @@ public static explicit operator DateTime(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator long?(JToken value) + public static explicit operator long?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Int64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1070,14 +1083,14 @@ public static explicit operator DateTime(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator float?(JToken value) + public static explicit operator float?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1100,7 +1113,7 @@ public static explicit operator DateTime(JToken value) /// The result of the conversion. public static explicit operator decimal(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Decimal.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1122,14 +1135,14 @@ public static explicit operator decimal(JToken value) /// The value. /// The result of the conversion. // [CLSCompliant(false)] - public static explicit operator uint?(JToken value) + public static explicit operator uint?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1151,14 +1164,14 @@ public static explicit operator decimal(JToken value) /// The value. /// The result of the conversion. // [CLSCompliant(false)] - public static explicit operator ulong?(JToken value) + public static explicit operator ulong?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, true)) { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1181,7 +1194,7 @@ public static explicit operator decimal(JToken value) /// The result of the conversion. public static explicit operator double(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Double.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1204,7 +1217,7 @@ public static explicit operator double(JToken value) /// The result of the conversion. public static explicit operator float(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to Single.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1225,14 +1238,14 @@ public static explicit operator float(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator string(JToken value) + public static explicit operator string?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, StringTypes, true)) { throw new ArgumentException("Can not convert {0} to String.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1266,7 +1279,7 @@ public static explicit operator string(JToken value) // [CLSCompliant(false)] public static explicit operator uint(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt32.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1290,7 +1303,7 @@ public static explicit operator uint(JToken value) // [CLSCompliant(false)] public static explicit operator ulong(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, NumberTypes, false)) { throw new ArgumentException("Can not convert {0} to UInt64.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1311,14 +1324,14 @@ public static explicit operator ulong(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator byte[](JToken value) + public static explicit operator byte[]?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, BytesTypes, false)) { throw new ArgumentException("Can not convert {0} to byte array.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1350,7 +1363,7 @@ public static explicit operator byte[](JToken value) /// The result of the conversion. public static explicit operator Guid(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, false)) { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1369,14 +1382,14 @@ public static explicit operator Guid(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator Guid?(JToken value) + public static explicit operator Guid?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, GuidTypes, true)) { throw new ArgumentException("Can not convert {0} to Guid.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1402,7 +1415,7 @@ public static explicit operator Guid(JToken value) /// The result of the conversion. public static explicit operator TimeSpan(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, false)) { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1416,14 +1429,14 @@ public static explicit operator TimeSpan(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator TimeSpan?(JToken value) + public static explicit operator TimeSpan?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, TimeSpanTypes, true)) { throw new ArgumentException("Can not convert {0} to TimeSpan.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1442,14 +1455,14 @@ public static explicit operator TimeSpan(JToken value) /// /// The value. /// The result of the conversion. - public static explicit operator Uri(JToken value) + public static explicit operator Uri?(JToken? value) { if (value == null) { return null; } - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, UriTypes, true)) { throw new ArgumentException("Can not convert {0} to Uri.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1466,18 +1479,18 @@ public static explicit operator Uri(JToken value) #if HAVE_BIG_INTEGER private static BigInteger ToBigInteger(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, false)) { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); } - return ConvertUtils.ToBigInteger(v.Value); + return ConvertUtils.ToBigInteger(v.Value!); } private static BigInteger? ToBigIntegerNullable(JToken value) { - JValue v = EnsureValue(value); + JValue? v = EnsureValue(value); if (v == null || !ValidateToken(v, BigIntegerTypes, true)) { throw new ArgumentException("Can not convert {0} to BigInteger.".FormatWith(CultureInfo.InvariantCulture, GetType(value))); @@ -1491,9 +1504,9 @@ private static BigInteger ToBigInteger(JToken value) return ConvertUtils.ToBigInteger(v.Value); } #endif -#endregion + #endregion -#region Cast to operators + #region Cast to operators /// /// Performs an implicit conversion from to . /// @@ -1771,7 +1784,7 @@ public static implicit operator JToken(float value) /// /// The value to create a from. /// The initialized with the specified value. - public static implicit operator JToken(string value) + public static implicit operator JToken(string? value) { return new JValue(value); } @@ -1813,7 +1826,7 @@ public static implicit operator JToken(byte[] value) /// /// The value to create a from. /// The initialized with the specified value. - public static implicit operator JToken(Uri value) + public static implicit operator JToken(Uri? value) { return new JValue(value); } @@ -1857,7 +1870,7 @@ public static implicit operator JToken(Guid? value) { return new JValue(value); } -#endregion + #endregion IEnumerator IEnumerable.GetEnumerator() { @@ -1871,7 +1884,7 @@ IEnumerator IEnumerable.GetEnumerator() internal abstract int GetDeepHashCode(); - IJEnumerable IJEnumerable.this[object key] => this[key]; + IJEnumerable IJEnumerable.this[object key] => this[key]!; /// /// Creates a for this token. @@ -1891,7 +1904,7 @@ internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerialize using (JTokenWriter jsonWriter = new JTokenWriter()) { jsonSerializer.Serialize(jsonWriter, o); - token = jsonWriter.Token; + token = jsonWriter.Token!; } return token; @@ -1923,9 +1936,9 @@ public static JToken FromObject(object o, JsonSerializer jsonSerializer) /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. - public T ToObject() + public T? ToObject() { - return (T)ToObject(typeof(T)); + return (T?)ToObject(typeof(T)); } /// @@ -1933,7 +1946,7 @@ public T ToObject() /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. - public object ToObject(Type objectType) + public object? ToObject(Type objectType) { if (JsonConvert.DefaultSettings == null) { @@ -1951,7 +1964,7 @@ public object ToObject(Type objectType) catch (Exception ex) { Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); - throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex); + throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string?)this, enumType.Name), ex); } } @@ -2027,13 +2040,13 @@ public object ToObject(Type objectType) return (DateTimeOffset)this; #endif case PrimitiveTypeCode.String: - return (string)this; + return (string?)this; case PrimitiveTypeCode.GuidNullable: return (Guid?)this; case PrimitiveTypeCode.Guid: return (Guid)this; case PrimitiveTypeCode.Uri: - return (Uri)this; + return (Uri?)this; case PrimitiveTypeCode.TimeSpanNullable: return (TimeSpan?)this; case PrimitiveTypeCode.TimeSpan: @@ -2056,9 +2069,9 @@ public object ToObject(Type objectType) /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. - public T ToObject(JsonSerializer jsonSerializer) + public T? ToObject(JsonSerializer jsonSerializer) { - return (T)ToObject(typeof(T), jsonSerializer); + return (T?)ToObject(typeof(T), jsonSerializer); } /// @@ -2067,7 +2080,7 @@ public T ToObject(JsonSerializer jsonSerializer) /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. - public object ToObject(Type objectType, JsonSerializer jsonSerializer) + public object? ToObject(Type objectType, JsonSerializer jsonSerializer) { ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); @@ -2102,7 +2115,7 @@ public static JToken ReadFrom(JsonReader reader) /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings) + public static JToken ReadFrom(JsonReader reader, JsonLoadSettings? settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -2127,7 +2140,7 @@ public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings) throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); } - IJsonLineInfo lineInfo = reader as IJsonLineInfo; + IJsonLineInfo? lineInfo = reader as IJsonLineInfo; switch (reader.TokenType) { @@ -2149,7 +2162,7 @@ public static JToken ReadFrom(JsonReader reader, JsonLoadSettings settings) v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Comment: - v = JValue.CreateComment(reader.Value.ToString()); + v = JValue.CreateComment(reader.Value!.ToString()); v.SetLineInfo(lineInfo, settings); return v; case JsonToken.Null: @@ -2182,7 +2195,7 @@ public static JToken Parse(string json) /// The used to load the JSON. /// If this is null, default load settings will be used. /// A populated from the string that contains JSON. - public static JToken Parse(string json, JsonLoadSettings settings) + public static JToken Parse(string json, JsonLoadSettings? settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { @@ -2193,7 +2206,6 @@ public static JToken Parse(string json, JsonLoadSettings settings) // Any content encountered here other than a comment will throw in the reader. } - return t; } } @@ -2209,7 +2221,7 @@ public static JToken Parse(string json, JsonLoadSettings settings) /// that were read from the reader. The runtime type of the token is determined /// by the token type of the first token encountered in the reader. /// - public static JToken Load(JsonReader reader, JsonLoadSettings settings) + public static JToken Load(JsonReader reader, JsonLoadSettings? settings) { return ReadFrom(reader, settings); } @@ -2228,7 +2240,7 @@ public static JToken Load(JsonReader reader) return Load(reader, null); } - internal void SetLineInfo(IJsonLineInfo lineInfo, JsonLoadSettings settings) + internal void SetLineInfo(IJsonLineInfo? lineInfo, JsonLoadSettings? settings) { if (settings != null && settings.LineInfoHandling != LineInfoHandling.Load) { @@ -2269,7 +2281,7 @@ int IJsonLineInfo.LineNumber { get { - LineInfoAnnotation annotation = Annotation(); + LineInfoAnnotation? annotation = Annotation(); if (annotation != null) { return annotation.LineNumber; @@ -2283,7 +2295,7 @@ int IJsonLineInfo.LinePosition { get { - LineInfoAnnotation annotation = Annotation(); + LineInfoAnnotation? annotation = Annotation(); if (annotation != null) { return annotation.LinePosition; @@ -2294,31 +2306,48 @@ int IJsonLineInfo.LinePosition } /// - /// Selects a using a JPath expression. Selects the token that matches the object path. + /// Selects a using a JSONPath expression. Selects the token that matches the object path. /// /// - /// A that contains a JPath expression. + /// A that contains a JSONPath expression. /// /// A , or null. - public JToken SelectToken(string path) + public JToken? SelectToken(string path) { - return SelectToken(path, false); + return SelectToken(path, settings: null); } /// - /// Selects a using a JPath expression. Selects the token that matches the object path. + /// Selects a using a JSONPath expression. Selects the token that matches the object path. /// /// - /// A that contains a JPath expression. + /// A that contains a JSONPath expression. /// /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. /// A . - public JToken SelectToken(string path, bool errorWhenNoMatch) + public JToken? SelectToken(string path, bool errorWhenNoMatch) + { + JsonSelectSettings? settings = errorWhenNoMatch + ? new JsonSelectSettings { ErrorWhenNoMatch = true } + : null; + + return SelectToken(path, settings); + } + + /// + /// Selects a using a JSONPath expression. Selects the token that matches the object path. + /// + /// + /// A that contains a JSONPath expression. + /// + /// The used to select tokens. + /// A . + public JToken? SelectToken(string path, JsonSelectSettings? settings) { JPath p = new JPath(path); - JToken token = null; - foreach (JToken t in p.Evaluate(this, this, errorWhenNoMatch)) + JToken? token = null; + foreach (JToken t in p.Evaluate(this, this, settings)) { if (token != null) { @@ -2332,29 +2361,46 @@ public JToken SelectToken(string path, bool errorWhenNoMatch) } /// - /// Selects a collection of elements using a JPath expression. + /// Selects a collection of elements using a JSONPath expression. /// /// - /// A that contains a JPath expression. + /// A that contains a JSONPath expression. /// /// An of that contains the selected elements. public IEnumerable SelectTokens(string path) { - return SelectTokens(path, false); + return SelectTokens(path, settings: null); } /// - /// Selects a collection of elements using a JPath expression. + /// Selects a collection of elements using a JSONPath expression. /// /// - /// A that contains a JPath expression. + /// A that contains a JSONPath expression. /// /// A flag to indicate whether an error should be thrown if no tokens are found when evaluating part of the expression. /// An of that contains the selected elements. public IEnumerable SelectTokens(string path, bool errorWhenNoMatch) { - JPath p = new JPath(path); - return p.Evaluate(this, this, errorWhenNoMatch); + JsonSelectSettings? settings = errorWhenNoMatch + ? new JsonSelectSettings { ErrorWhenNoMatch = true } + : null; + + return SelectTokens(path, settings); + } + + /// + /// Selects a collection of elements using a JSONPath expression. + /// + /// + /// A that contains a JSONPath expression. + /// + /// The used to select tokens. + /// An of that contains the selected elements. + public IEnumerable SelectTokens(string path, JsonSelectSettings? settings) + { + var p = new JPath(path); + return p.Evaluate(this, this, settings); } #if HAVE_DYNAMIC @@ -2442,7 +2488,7 @@ public void AddAnnotation(object annotation) /// /// The type of the annotation to retrieve. /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. - public T Annotation() where T : class + public T? Annotation() where T : class { if (_annotations != null) { @@ -2473,7 +2519,7 @@ public T Annotation() where T : class /// /// The of the annotation to retrieve. /// The first annotation object that matches the specified type, or null if no annotation is of the specified type. - public object Annotation(Type type) + public object? Annotation(Type type) { if (type == null) { @@ -2599,7 +2645,7 @@ public void RemoveAnnotations() where T : class { if (_annotations != null) { - if (!(_annotations is object[] annotations)) + if (!(_annotations is object?[] annotations)) { if (_annotations is T) { @@ -2612,7 +2658,7 @@ public void RemoveAnnotations() where T : class int keepCount = 0; while (index < annotations.Length) { - object obj2 = annotations[index]; + object? obj2 = annotations[index]; if (obj2 == null) { break; @@ -2654,7 +2700,7 @@ public void RemoveAnnotations(Type type) if (_annotations != null) { - if (!(_annotations is object[] annotations)) + if (!(_annotations is object?[] annotations)) { if (type.IsInstanceOfType(_annotations)) { @@ -2667,7 +2713,7 @@ public void RemoveAnnotations(Type type) int keepCount = 0; while (index < annotations.Length) { - object o = annotations[index]; + object? o = annotations[index]; if (o == null) { break; @@ -2695,5 +2741,17 @@ public void RemoveAnnotations(Type type) } } } + + internal void CopyAnnotations(JToken target, JToken source) + { + if (source._annotations is object[] annotations) + { + target._annotations = annotations.ToArray(); + } + else + { + target._annotations = source._annotations; + } + } } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs index ae93233de..70d0dc452 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenEqualityComparer.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenReader.cs index 6ec625e00..76c806057 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenReader.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -38,14 +41,14 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq internal class JTokenReader : JsonReader, IJsonLineInfo { private readonly JToken _root; - private string _initialPath; - private JToken _parent; - private JToken _current; + private string? _initialPath; + private JToken? _parent; + private JToken? _current; /// /// Gets the at the reader's current position. /// - public JToken CurrentToken => _current; + public JToken? CurrentToken => _current; /// /// Initializes a new instance of the class. @@ -58,8 +61,12 @@ public JTokenReader(JToken token) _root = token; } - // this is used by json.net schema - internal JTokenReader(JToken token, string initialPath) + /// + /// Initializes a new instance of the class. + /// + /// The token to read from. + /// The initial path of the token. It is prepended to the returned . + public JTokenReader(JToken token, string initialPath) : this(token) { _initialPath = initialPath; @@ -90,6 +97,12 @@ public override bool Read() } } + // The current value could already be the root value if it is a comment + if (_current == _root) + { + return false; + } + _current = _root; SetToken(_current); return true; @@ -102,8 +115,8 @@ private bool ReadOver(JToken t) return ReadToEnd(); } - JToken next = t.Next; - if ((next == null || next == t) || t == t.Parent.Last) + JToken? next = t.Next; + if ((next == null || next == t) || t == t.Parent!.Last) { if (t.Parent == null) { @@ -146,7 +159,7 @@ private bool ReadToEnd() private bool ReadInto(JContainer c) { - JToken firstChild = c.First; + JToken? firstChild = c.First; if (firstChild == null) { return SetEnd(c); @@ -215,7 +228,7 @@ private void SetToken(JToken token) break; case JTokenType.Date: { - object v = ((JValue)token).Value; + object? v = ((JValue)token).Value; if (v is DateTime dt) { v = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); @@ -235,7 +248,7 @@ private void SetToken(JToken token) break; case JTokenType.Uri: { - object v = ((JValue)token).Value; + object? v = ((JValue)token).Value; SetToken(JsonToken.String, v is Uri uri ? uri.OriginalString : SafeToString(v)); break; } @@ -247,7 +260,7 @@ private void SetToken(JToken token) } } - private string SafeToString(object value) + private string? SafeToString(object? value) { return value?.ToString(); } @@ -259,7 +272,7 @@ bool IJsonLineInfo.HasLineInfo() return false; } - IJsonLineInfo info = _current; + IJsonLineInfo? info = _current; return (info != null && info.HasLineInfo()); } @@ -272,7 +285,7 @@ int IJsonLineInfo.LineNumber return 0; } - IJsonLineInfo info = _current; + IJsonLineInfo? info = _current; if (info != null) { return info.LineNumber; @@ -291,7 +304,7 @@ int IJsonLineInfo.LinePosition return 0; } - IJsonLineInfo info = _current; + IJsonLineInfo? info = _current; if (info != null) { return info.LinePosition; @@ -315,9 +328,9 @@ public override string Path _initialPath = _root.Path; } - if (!string.IsNullOrEmpty(_initialPath)) + if (!StringUtils.IsNullOrEmpty(_initialPath)) { - if (string.IsNullOrEmpty(path)) + if (StringUtils.IsNullOrEmpty(path)) { return _initialPath; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenType.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenType.cs index fff9a7e15..c97ec9cf9 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenType.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenType.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.Async.cs index 10a13125c..1dc8847ce 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.cs index 757e6e55e..8c1574397 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -28,6 +31,7 @@ #endregion using System; +using System.Diagnostics; using System.Globalization; #if HAVE_BIG_INTEGER using System.Numerics; @@ -41,22 +45,22 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq /// internal partial class JTokenWriter : JsonWriter { - private JContainer _token; - private JContainer _parent; + private JContainer? _token; + private JContainer? _parent; // used when writer is writing single value and the value has no containing parent - private JValue _value; - private JToken _current; + private JValue? _value; + private JToken? _current; /// /// Gets the at the writer's current position. /// - public JToken CurrentToken => _current; + public JToken? CurrentToken => _current; /// /// Gets the token being written. /// /// The token being written. - public JToken Token + public JToken? Token { get { @@ -135,7 +139,7 @@ private void AddParent(JContainer container) private void RemoveParent() { _current = _parent; - _parent = _parent.Parent; + _parent = _parent!.Parent; if (_parent != null && _parent.Type == JTokenType.Property) { @@ -190,21 +194,26 @@ public override void WritePropertyName(string name) base.WritePropertyName(name); } - private void AddValue(object value, JsonToken token) + private void AddValue(object? value, JsonToken token) { AddValue(new JValue(value), token); } - internal void AddValue(JValue value, JsonToken token) + internal void AddValue(JValue? value, JsonToken token) { if (_parent != null) { - _parent.Add(value); - _current = _parent.Last; - - if (_parent.Type == JTokenType.Property) + // TryAdd will return false if an invalid JToken type is added. + // For example, a JComment can't be added to a JObject. + // If there is an invalid JToken type then skip it. + if (_parent.TryAdd(value)) { - _parent = _parent.Parent; + _current = _parent.Last; + + if (_parent.Type == JTokenType.Property) + { + _parent = _parent.Parent; + } } } else @@ -220,7 +229,7 @@ internal void AddValue(JValue value, JsonToken token) /// An error will be raised if the value cannot be written as a single JSON token. /// /// The value to write. - public override void WriteValue(object value) + public override void WriteValue(object? value) { #if HAVE_BIG_INTEGER if (value is BigInteger) @@ -257,7 +266,7 @@ public override void WriteUndefined() /// Writes raw JSON. /// /// The raw JSON to write. - public override void WriteRaw(string json) + public override void WriteRaw(string? json) { base.WriteRaw(json); AddValue(new JRaw(json), JsonToken.Raw); @@ -267,7 +276,7 @@ public override void WriteRaw(string json) /// Writes a comment /*...*/ containing the specified text. /// /// Text to place inside the comment. - public override void WriteComment(string text) + public override void WriteComment(string? text) { base.WriteComment(text); AddValue(JValue.CreateComment(text), JsonToken.Comment); @@ -277,7 +286,7 @@ public override void WriteComment(string text) /// Writes a value. /// /// The value to write. - public override void WriteValue(string value) + public override void WriteValue(string? value) { base.WriteValue(value); AddValue(value, JsonToken.String); @@ -450,7 +459,7 @@ public override void WriteValue(DateTimeOffset value) /// Writes a [] value. /// /// The [] value to write. - public override void WriteValue(byte[] value) + public override void WriteValue(byte[]? value) { base.WriteValue(value); AddValue(value, JsonToken.Bytes); @@ -480,7 +489,7 @@ public override void WriteValue(Guid value) /// Writes a value. /// /// The value to write. - public override void WriteValue(Uri value) + public override void WriteValue(Uri? value) { base.WriteValue(value); AddValue(value, JsonToken.String); @@ -500,7 +509,7 @@ internal override void WriteToken(JsonReader reader, bool writeChildren, bool wr } } - JToken value = tokenReader.CurrentToken.CloneToken(); + JToken value = tokenReader.CurrentToken!.CloneToken(); if (_parent != null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.Async.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.Async.cs index c9780ac81..9fc3483c2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.Async.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.Async.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -53,7 +56,7 @@ public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellat { if (converters != null && converters.Length > 0 && _value != null) { - JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { // TODO: Call WriteJsonAsync when it exists. @@ -125,13 +128,13 @@ public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellat return writer.WriteValueAsync(Convert.ToDateTime(_value, CultureInfo.InvariantCulture), cancellationToken); case JTokenType.Bytes: - return writer.WriteValueAsync((byte[])_value, cancellationToken); + return writer.WriteValueAsync((byte[]?)_value, cancellationToken); case JTokenType.Guid: return writer.WriteValueAsync(_value != null ? (Guid?)_value : null, cancellationToken); case JTokenType.TimeSpan: return writer.WriteValueAsync(_value != null ? (TimeSpan?)_value : null, cancellationToken); case JTokenType.Uri: - return writer.WriteValueAsync((Uri)_value, cancellationToken); + return writer.WriteValueAsync((Uri?)_value, cancellationToken); } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.cs index ab8fe873d..45322ce8c 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JValue.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +35,8 @@ using System.Diagnostics; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; @@ -51,9 +56,9 @@ internal partial class JValue : JToken, IEquatable, IFormattable, ICompa #endif { private JTokenType _valueType; - private object _value; + private object? _value; - internal JValue(object value, JTokenType type) + internal JValue(object? value, JTokenType type) { _value = value; _valueType = type; @@ -66,6 +71,7 @@ internal JValue(object value, JTokenType type) public JValue(JValue other) : this(other.Value, other.Type) { + CopyAnnotations(this, other); } /// @@ -156,7 +162,7 @@ public JValue(bool value) /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(string value) + public JValue(string? value) : this(value, JTokenType.String) { } @@ -174,7 +180,7 @@ public JValue(Guid value) /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(Uri value) + public JValue(Uri? value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } @@ -192,7 +198,7 @@ public JValue(TimeSpan value) /// Initializes a new instance of the class with the given value. /// /// The value. - public JValue(object value) + public JValue(object? value) : this(value, GetValueType(null, value)) { } @@ -245,7 +251,7 @@ private static int CompareBigInteger(BigInteger i1, object i2) } #endif - internal static int Compare(JTokenType valueType, object objA, object objB) + internal static int Compare(JTokenType valueType, object? objA, object? objB) { if (objA == objB) { @@ -271,8 +277,8 @@ internal static int Compare(JTokenType valueType, object objA, object objB) } if (objB is BigInteger integerB) { - return -CompareBigInteger(integerB, objA); - } + return -CompareBigInteger(integerB, objA); + } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { @@ -304,7 +310,7 @@ internal static int Compare(JTokenType valueType, object objA, object objB) return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } return CompareFloat(objA, objB); - } + } case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: @@ -357,10 +363,10 @@ internal static int Compare(JTokenType valueType, object objA, object objB) throw new ArgumentException("Object must be of type byte[]."); } - byte[] bytesA = objA as byte[]; - Debug.Assert(bytesA != null); + byte[]? bytesA = objA as byte[]; + MiscellaneousUtils.Assert(bytesA != null); - return MiscellaneousUtils.ByteArrayCompare(bytesA, bytesB); + return MiscellaneousUtils.ByteArrayCompare(bytesA!, bytesB); case JTokenType.Guid: if (!(objB is Guid)) { @@ -372,7 +378,7 @@ internal static int Compare(JTokenType valueType, object objA, object objB) return guid1.CompareTo(guid2); case JTokenType.Uri: - Uri uri2 = objB as Uri; + Uri? uri2 = objB as Uri; if (uri2 == null) { throw new ArgumentException("Object must be of type Uri."); @@ -411,7 +417,7 @@ private static int CompareFloat(object objA, object objB) } #if HAVE_EXPRESSIONS - private static bool Operation(ExpressionType operation, object objA, object objB, out object result) + private static bool Operation(ExpressionType operation, object? objA, object? objB, out object? result) { if (objA is string || objB is string) { @@ -568,7 +574,7 @@ internal override JToken CloneToken() /// /// The value. /// A comment with the given value. - public static JValue CreateComment(string value) + public static JValue CreateComment(string? value) { return new JValue(value, JTokenType.Comment); } @@ -578,7 +584,7 @@ public static JValue CreateComment(string value) /// /// The value. /// A string with the given value. - public static JValue CreateString(string value) + public static JValue CreateString(string? value) { return new JValue(value, JTokenType.String); } @@ -601,7 +607,7 @@ public static JValue CreateUndefined() return new JValue(null, JTokenType.Undefined); } - private static JTokenType GetValueType(JTokenType? current, object value) + private static JTokenType GetValueType(JTokenType? current, object? value) { if (value == null) { @@ -698,13 +704,13 @@ private static JTokenType GetStringValueType(JTokenType? current) /// Gets or sets the underlying token value. /// /// The underlying token value. - public object Value + public object? Value { get => _value; set { - Type currentType = _value?.GetType(); - Type newType = value?.GetType(); + Type? currentType = _value?.GetType(); + Type? newType = value?.GetType(); if (currentType != newType) { @@ -724,7 +730,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter { if (converters != null && converters.Length > 0 && _value != null) { - JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); + JsonConverter? matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); @@ -807,7 +813,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter } return; case JTokenType.Bytes: - writer.WriteValue((byte[])_value); + writer.WriteValue((byte[]?)_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); @@ -816,7 +822,7 @@ public override void WriteTo(JsonWriter writer, params JsonConverter[] converter writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: - writer.WriteValue((Uri)_value); + writer.WriteValue((Uri?)_value); return; } @@ -843,7 +849,7 @@ private static bool ValuesEquals(JValue v1, JValue v2) /// true if the current object is equal to the parameter; otherwise, false. /// /// An object to compare with this object. - public bool Equals(JValue other) + public bool Equals(JValue? other) { if (other == null) { @@ -862,7 +868,12 @@ public bool Equals(JValue other) /// public override bool Equals(object obj) { - return Equals(obj as JValue); + if (obj is JValue v) + { + return Equals(v); + } + + return false; } /// @@ -884,6 +895,10 @@ public override int GetHashCode() /// /// Returns a that represents this instance. /// + /// + /// ToString() returns a non-JSON string value for tokens with a type of . + /// If you want the JSON for all token types then you should use . + /// /// /// A that represents this instance. /// @@ -929,7 +944,7 @@ public string ToString(IFormatProvider formatProvider) /// /// A that represents this instance. /// - public string ToString(string format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider formatProvider) { if (_value == null) { @@ -961,7 +976,7 @@ protected override DynamicMetaObject GetMetaObject(Expression parameter) private class JValueDynamicProxy : DynamicProxy { - public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) + public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result) { if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) { @@ -969,7 +984,7 @@ public override bool TryConvert(JValue instance, ConvertBinder binder, out objec return true; } - object value = instance.Value; + object? value = instance.Value; if (value == null) { @@ -981,9 +996,9 @@ public override bool TryConvert(JValue instance, ConvertBinder binder, out objec return true; } - public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) + public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, [NotNullWhen(true)]out object? result) { - object compareValue = arg is JValue value ? value.Value : arg; + object? compareValue = arg is JValue value ? value.Value : arg; switch (binder.Operation) { @@ -1035,7 +1050,7 @@ int IComparable.CompareTo(object obj) } JTokenType comparisonType; - object otherValue; + object? otherValue; if (obj is JValue value) { otherValue = value.Value; @@ -1170,7 +1185,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) return (DateTime)this; } - object IConvertible.ToType(Type conversionType, IFormatProvider provider) + object? IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ToObject(conversionType); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonLoadSettings.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonLoadSettings.cs index 6406f47bb..630614236 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonLoadSettings.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonLoadSettings.cs @@ -2,7 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ -#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011,SYSLIB0032 +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq @@ -74,7 +76,7 @@ public DuplicatePropertyNameHandling DuplicatePropertyNameHandling get => _duplicatePropertyNameHandling; set { - if (value < DuplicatePropertyNameHandling.Ignore || value > DuplicatePropertyNameHandling.Error) + if (value < DuplicatePropertyNameHandling.Replace || value > DuplicatePropertyNameHandling.Error) { throw new ArgumentOutOfRangeException(nameof(value)); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonMergeSettings.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonMergeSettings.cs index 5df477877..a58969aef 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonMergeSettings.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonMergeSettings.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs index 90771f8ac..7ed412fb6 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArrayIndexFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; @@ -12,13 +15,13 @@ internal class ArrayIndexFilter : PathFilter { public int? Index { get; set; } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { if (Index != null) { - JToken v = GetTokenIndex(t, errorWhenNoMatch, Index.GetValueOrDefault()); + JToken? v = GetTokenIndex(t, settings, Index.GetValueOrDefault()); if (v != null) { @@ -36,7 +39,7 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class ArrayMultipleIndexFilter : PathFilter { - public List Indexes { get; set; } + internal List Indexes; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public ArrayMultipleIndexFilter(List indexes) + { + Indexes = indexes; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { foreach (int i in Indexes) { - JToken v = GetTokenIndex(t, errorWhenNoMatch, i); + JToken? v = GetTokenIndex(t, settings, i); if (v != null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs index 9942b6aa7..2615097bb 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ArraySliceFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; using System.Globalization; @@ -15,7 +18,7 @@ internal class ArraySliceFilter : PathFilter public int? End { get; set; } public int? Step { get; set; } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { if (Step == 0) { @@ -60,7 +63,7 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable ExecuteFilter(JToken root, IEnumerable // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; @@ -10,9 +13,14 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class FieldFilter : PathFilter { - public string Name { get; set; } + internal string? Name; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public FieldFilter(string? name) + { + Name = name; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { @@ -20,28 +28,28 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable p in o) + foreach (KeyValuePair p in o) { - yield return p.Value; + yield return p.Value!; } } } else { - if (errorWhenNoMatch) + if (settings?.ErrorWhenNoMatch ?? false) { throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, Name ?? "*", t.GetType().Name)); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs index 657c43e5a..377a1f2d4 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/FieldMultipleFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; using System.Globalization; #if !HAVE_LINQ @@ -15,9 +18,14 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class FieldMultipleFilter : PathFilter { - public List Names { get; set; } + internal List Names; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public FieldMultipleFilter(List names) + { + Names = names; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { @@ -25,14 +33,14 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable ExecuteFilter(JToken root, IEnumerable "'" + n + "'") #if !HAVE_STRING_JOIN_WITH_ENUMERABLE diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/JPath.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/JPath.cs index 038df8bd9..65f29f88a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/JPath.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/JPath.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -111,7 +114,7 @@ private bool ParsePath(List filters, int currentPartStartIndex, bool case '(': if (_currentIndex > currentPartStartIndex) { - string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; @@ -122,6 +125,8 @@ private bool ParsePath(List filters, int currentPartStartIndex, bool } filters.Add(ParseIndexer(currentChar, scan)); + scan = false; + _currentIndex++; currentPartStartIndex = _currentIndex; followingIndexer = true; @@ -140,7 +145,7 @@ private bool ParsePath(List filters, int currentPartStartIndex, bool case '.': if (_currentIndex > currentPartStartIndex) { - string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); + string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex); if (member == "*") { member = null; @@ -181,7 +186,7 @@ private bool ParsePath(List filters, int currentPartStartIndex, bool if (_currentIndex > currentPartStartIndex) { - string member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); + string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex).TrimEnd(); if (member == "*") { member = null; @@ -200,9 +205,9 @@ private bool ParsePath(List filters, int currentPartStartIndex, bool return atPathEnd; } - private static PathFilter CreatePathFilter(string member, bool scan) + private static PathFilter CreatePathFilter(string? member, bool scan) { - PathFilter filter = (scan) ? (PathFilter)new ScanFilter {Name = member} : new FieldFilter {Name = member}; + PathFilter filter = (scan) ? (PathFilter)new ScanFilter(member) : new FieldFilter(member); return filter; } @@ -234,7 +239,7 @@ private PathFilter ParseArrayIndexer(char indexerCloseChar) { int start = _currentIndex; int? end = null; - List indexes = null; + List? indexes = null; int colonCount = 0; int? startIndex = null; int? endIndex = null; @@ -266,7 +271,7 @@ private PathFilter ParseArrayIndexer(char indexerCloseChar) int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture); indexes.Add(index); - return new ArrayMultipleIndexFilter { Indexes = indexes }; + return new ArrayMultipleIndexFilter(indexes); } else if (colonCount > 0) { @@ -425,26 +430,19 @@ private PathFilter ParseQuery(char indexerCloseChar, bool scan) if (!scan) { - return new QueryFilter - { - Expression = expression - }; + return new QueryFilter(expression); } else { - return new QueryScanFilter - { - Expression = expression - }; + return new QueryScanFilter(expression); } } - private bool TryParseExpression(out List expressionPath) + private bool TryParseExpression(out List? expressionPath) { if (_expression[_currentIndex] == '$') { - expressionPath = new List(); - expressionPath.Add(RootFilter.Instance); + expressionPath = new List { RootFilter.Instance }; } else if (_expression[_currentIndex] == '@') { @@ -458,7 +456,7 @@ private bool TryParseExpression(out List expressionPath) _currentIndex++; - if (ParsePath(expressionPath, _currentIndex, true)) + if (ParsePath(expressionPath!, _currentIndex, true)) { throw new JsonException("Path ended with open query."); } @@ -475,12 +473,12 @@ private object ParseSide() { EatWhitespace(); - if (TryParseExpression(out var expressionPath)) + if (TryParseExpression(out List? expressionPath)) { EatWhitespace(); EnsureLength("Path ended with open query."); - return expressionPath; + return expressionPath!; } if (TryParseValue(out var value)) @@ -496,13 +494,13 @@ private object ParseSide() private QueryExpression ParseExpression() { - QueryExpression rootExpression = null; - CompositeExpression parentExpression = null; + QueryExpression? rootExpression = null; + CompositeExpression? parentExpression = null; while (_currentIndex < _expression.Length) { object left = ParseSide(); - object right = null; + object? right = null; QueryOperator op; if (_expression[_currentIndex] == ')' @@ -518,19 +516,14 @@ private QueryExpression ParseExpression() right = ParseSide(); } - BooleanQueryExpression booleanExpression = new BooleanQueryExpression - { - Left = left, - Operator = op, - Right = right - }; + BooleanQueryExpression booleanExpression = new BooleanQueryExpression(op, left, right); if (_expression[_currentIndex] == ')') { if (parentExpression != null) { parentExpression.Expressions.Add(booleanExpression); - return rootExpression; + return rootExpression!; } return booleanExpression; @@ -544,7 +537,7 @@ private QueryExpression ParseExpression() if (parentExpression == null || parentExpression.Operator != QueryOperator.And) { - CompositeExpression andExpression = new CompositeExpression { Operator = QueryOperator.And }; + CompositeExpression andExpression = new CompositeExpression(QueryOperator.And); parentExpression?.Expressions.Add(andExpression); @@ -567,7 +560,7 @@ private QueryExpression ParseExpression() if (parentExpression == null || parentExpression.Operator != QueryOperator.Or) { - CompositeExpression orExpression = new CompositeExpression { Operator = QueryOperator.Or }; + CompositeExpression orExpression = new CompositeExpression(QueryOperator.Or); parentExpression?.Expressions.Add(orExpression); @@ -586,7 +579,7 @@ private QueryExpression ParseExpression() throw new JsonException("Path ended with open query."); } - private bool TryParseValue(out object value) + private bool TryParseValue(out object? value) { char currentChar = _expression[_currentIndex]; if (currentChar == '\'') @@ -767,9 +760,9 @@ private string ReadRegexString() private bool Match(string s) { int currentPosition = _currentIndex; - foreach (char c in s) + for (int i = 0; i < s.Length; i++) { - if (currentPosition < _expression.Length && _expression[currentPosition] == c) + if (currentPosition < _expression.Length && _expression[currentPosition] == s[i]) { currentPosition++; } @@ -836,7 +829,7 @@ private QueryOperator ParseOperator() private PathFilter ParseQuotedField(char indexerCloseChar, bool scan) { - List fields = null; + List? fields = null; while (_currentIndex < _expression.Length) { @@ -851,8 +844,8 @@ private PathFilter ParseQuotedField(char indexerCloseChar, bool scan) { fields.Add(field); return (scan) - ? (PathFilter)new ScanMultipleFilter { Names = fields } - : (PathFilter)new FieldMultipleFilter { Names = fields }; + ? (PathFilter)new ScanMultipleFilter(fields) + : (PathFilter)new FieldMultipleFilter(fields); } else { @@ -888,17 +881,17 @@ private void EnsureLength(string message) } } - internal IEnumerable Evaluate(JToken root, JToken t, bool errorWhenNoMatch) + internal IEnumerable Evaluate(JToken root, JToken t, JsonSelectSettings? settings) { - return Evaluate(Filters, root, t, errorWhenNoMatch); + return Evaluate(Filters, root, t, settings); } - internal static IEnumerable Evaluate(List filters, JToken root, JToken t, bool errorWhenNoMatch) + internal static IEnumerable Evaluate(List filters, JToken root, JToken t, JsonSelectSettings? settings) { IEnumerable current = new[] { t }; foreach (PathFilter filter in filters) { - current = filter.ExecuteFilter(root, current, errorWhenNoMatch); + current = filter.ExecuteFilter(root, current, settings); } return current; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs index c4042f6c7..ece5f2736 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/PathFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; @@ -10,16 +13,15 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal abstract class PathFilter { - public abstract IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch); + public abstract IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings); - protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index) + protected static JToken? GetTokenIndex(JToken t, JsonSelectSettings? settings, int index) { - if (t is JArray a) { if (a.Count <= index) { - if (errorWhenNoMatch) + if (settings?.ErrorWhenNoMatch ?? false) { throw new JsonException("Index {0} outside the bounds of JArray.".FormatWith(CultureInfo.InvariantCulture, index)); } @@ -33,7 +35,7 @@ protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index { if (c.Count <= index) { - if (errorWhenNoMatch) + if (settings?.ErrorWhenNoMatch ?? false) { throw new JsonException("Index {0} outside the bounds of JConstructor.".FormatWith(CultureInfo.InvariantCulture, index)); } @@ -45,7 +47,7 @@ protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index } else { - if (errorWhenNoMatch) + if (settings?.ErrorWhenNoMatch ?? false) { throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, t.GetType().Name)); } @@ -54,7 +56,7 @@ protected static JToken GetTokenIndex(JToken t, bool errorWhenNoMatch, int index } } - protected static JToken GetNextScanValue(JToken originalParent, JToken container, JToken value) + protected static JToken? GetNextScanValue(JToken originalParent, JToken? container, JToken? value) { // step into container's values if (container != null && container.HasValues) @@ -64,7 +66,7 @@ protected static JToken GetNextScanValue(JToken originalParent, JToken container else { // finished container, move to parent - while (value != null && value != originalParent && value == value.Parent.Last) + while (value != null && value != originalParent && value == value.Parent!.Last) { value = value.Parent; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs index ad25debff..a92794c55 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryExpression.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; using System.Globalization; @@ -36,28 +39,39 @@ internal enum QueryOperator internal abstract class QueryExpression { - public QueryOperator Operator { get; set; } + internal QueryOperator Operator; - public abstract bool IsMatch(JToken root, JToken t); + public QueryExpression(QueryOperator @operator) + { + Operator = @operator; + } + + // For unit tests + public bool IsMatch(JToken root, JToken t) + { + return IsMatch(root, t, null); + } + + public abstract bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings); } internal class CompositeExpression : QueryExpression { public List Expressions { get; set; } - public CompositeExpression() + public CompositeExpression(QueryOperator @operator) : base(@operator) { Expressions = new List(); } - public override bool IsMatch(JToken root, JToken t) + public override bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings) { switch (Operator) { case QueryOperator.And: foreach (QueryExpression e in Expressions) { - if (!e.IsMatch(root, t)) + if (!e.IsMatch(root, t, settings)) { return false; } @@ -66,7 +80,7 @@ public override bool IsMatch(JToken root, JToken t) case QueryOperator.Or: foreach (QueryExpression e in Expressions) { - if (e.IsMatch(root, t)) + if (e.IsMatch(root, t, settings)) { return true; } @@ -80,10 +94,16 @@ public override bool IsMatch(JToken root, JToken t) internal class BooleanQueryExpression : QueryExpression { - public object Left { get; set; } - public object Right { get; set; } + public readonly object Left; + public readonly object? Right; - private IEnumerable GetResult(JToken root, JToken t, object o) + public BooleanQueryExpression(QueryOperator @operator, object left, object? right) : base(@operator) + { + Left = left; + Right = right; + } + + private IEnumerable GetResult(JToken root, JToken t, object? o) { if (o is JToken resultToken) { @@ -92,13 +112,13 @@ private IEnumerable GetResult(JToken root, JToken t, object o) if (o is List pathFilters) { - return JPath.Evaluate(pathFilters, root, t, false); + return JPath.Evaluate(pathFilters, root, t, null); } return CollectionUtils.ArrayEmpty(); } - public override bool IsMatch(JToken root, JToken t) + public override bool IsMatch(JToken root, JToken t, JsonSelectSettings? settings) { if (Operator == QueryOperator.Exists) { @@ -117,7 +137,7 @@ public override bool IsMatch(JToken root, JToken t) JToken leftResult = leftResults.Current; foreach (JToken rightResult in rightResults) { - if (MatchTokens(leftResult, rightResult)) + if (MatchTokens(leftResult, rightResult, settings)) { return true; } @@ -129,14 +149,14 @@ public override bool IsMatch(JToken root, JToken t) return false; } - private bool MatchTokens(JToken leftResult, JToken rightResult) + private bool MatchTokens(JToken leftResult, JToken rightResult, JsonSelectSettings? settings) { if (leftResult is JValue leftValue && rightResult is JValue rightValue) { switch (Operator) { case QueryOperator.RegexEquals: - if (RegexEquals(leftValue, rightValue)) + if (RegexEquals(leftValue, rightValue, settings)) { return true; } @@ -208,20 +228,25 @@ private bool MatchTokens(JToken leftResult, JToken rightResult) return false; } - private static bool RegexEquals(JValue input, JValue pattern) + private static bool RegexEquals(JValue input, JValue pattern, JsonSelectSettings? settings) { if (input.Type != JTokenType.String || pattern.Type != JTokenType.String) { return false; } - string regexText = (string)pattern.Value; + string regexText = (string)pattern.Value!; int patternOptionDelimiterIndex = regexText.LastIndexOf('/'); string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1); string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1); - return Regex.IsMatch((string)input.Value, patternText, MiscellaneousUtils.GetRegexOptions(optionsText)); +#if HAVE_REGEX_TIMEOUTS + TimeSpan timeout = settings?.RegexMatchTimeout ?? Regex.InfiniteMatchTimeout; + return Regex.IsMatch((string)input.Value!, patternText, MiscellaneousUtils.GetRegexOptions(optionsText), timeout); +#else + return Regex.IsMatch((string)input.Value!, patternText, MiscellaneousUtils.GetRegexOptions(optionsText)); +#endif } internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) @@ -244,7 +269,7 @@ internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) return false; } - string queryValueString = (string)queryValue.Value; + string queryValueString = (string)queryValue.Value!; string currentValueString; @@ -262,21 +287,21 @@ internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) else #endif { - DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); + DateTimeUtils.WriteDateTimeString(writer, (DateTime)value.Value!, DateFormatHandling.IsoDateFormat, null, CultureInfo.InvariantCulture); } currentValueString = writer.ToString(); } break; case JTokenType.Bytes: - currentValueString = Convert.ToBase64String((byte[])value.Value); + currentValueString = Convert.ToBase64String((byte[])value.Value!); break; case JTokenType.Guid: case JTokenType.TimeSpan: - currentValueString = value.Value.ToString(); + currentValueString = value.Value!.ToString(); break; case JTokenType.Uri: - currentValueString = ((Uri)value.Value).OriginalString; + currentValueString = ((Uri)value.Value!).OriginalString; break; default: return false; @@ -287,8 +312,8 @@ internal static bool EqualsWithStringCoercion(JValue value, JValue queryValue) internal static bool EqualsWithStrictMatch(JValue value, JValue queryValue) { - Debug.Assert(value != null); - Debug.Assert(queryValue != null); + MiscellaneousUtils.Assert(value != null); + MiscellaneousUtils.Assert(queryValue != null); // Handle comparing an integer with a float // e.g. Comparing 1 and 1.0 diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs index d6002152f..06831d9c2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; @@ -9,15 +12,20 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class QueryFilter : PathFilter { - public QueryExpression Expression { get; set; } + internal QueryExpression Expression; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public QueryFilter(QueryExpression expression) + { + Expression = expression; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { foreach (JToken v in t) { - if (Expression.IsMatch(root, v)) + if (Expression.IsMatch(root, v, settings)) { yield return v; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs index cb4cb9232..0fa071d8c 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/QueryScanFilter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; @@ -9,9 +12,14 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class QueryScanFilter : PathFilter { - public QueryExpression Expression { get; set; } + internal QueryExpression Expression; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public QueryScanFilter(QueryExpression expression) + { + Expression = expression; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken t in current) { @@ -19,7 +27,7 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable ExecuteFilter(JToken root, IEnumerable // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath @@ -14,7 +17,7 @@ private RootFilter() { } - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { return new[] { root }; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs index 96c373b67..32ddc0afa 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/JsonPath/ScanFilter.cs @@ -2,15 +2,23 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class ScanFilter : PathFilter { - public string Name { get; set; } + internal string? Name; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public ScanFilter(string? name) + { + Name = name; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken c in current) { @@ -19,11 +27,11 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System.Collections.Generic; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq.JsonPath { internal class ScanMultipleFilter : PathFilter { - public List Names { get; set; } + private List _names; - public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, bool errorWhenNoMatch) + public ScanMultipleFilter(List names) + { + _names = names; + } + + public override IEnumerable ExecuteFilter(JToken root, IEnumerable current, JsonSelectSettings? settings) { foreach (JToken c in current) { - JToken value = c; + JToken? value = c; while (true) { - JContainer container = value as JContainer; + JContainer? container = value as JContainer; value = GetNextScanValue(c, container, value); if (value == null) @@ -28,7 +36,7 @@ public override IEnumerable ExecuteFilter(JToken root, IEnumerable ExecuteFilter(JToken root, IEnumerable +// This file was automatically generated by the UpdateVendors tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable +using System; + +namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq +{ + /// + /// Specifies the settings used when selecting JSON. + /// + internal class JsonSelectSettings + { +#if HAVE_REGEX_TIMEOUTS + /// + /// Gets or sets a timeout that will be used when executing regular expressions. + /// + /// The timeout that will be used when executing regular expressions. + public TimeSpan? RegexMatchTimeout { get; set; } +#endif + + /// + /// Gets or sets a flag that indicates whether an error should be thrown if + /// no tokens are found when evaluating part of the expression. + /// + /// + /// A flag that indicates whether an error should be thrown if + /// no tokens are found when evaluating part of the expression. + /// + public bool ErrorWhenNoMatch { get; set; } + } +} diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/LineInfoHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/LineInfoHandling.cs index 769fc7006..13387be97 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/LineInfoHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/LineInfoHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeArrayHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeArrayHandling.cs index a64c025a5..054029b7a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeArrayHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeArrayHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeNullValueHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeNullValueHandling.cs index 38dc24e5b..5cb78163b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeNullValueHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Linq/MergeNullValueHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Linq diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MemberSerialization.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MemberSerialization.cs index 3f8712584..3323afe5f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MemberSerialization.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MemberSerialization.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MetadataPropertyHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MetadataPropertyHandling.cs index 361e0e35a..115237ede 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MetadataPropertyHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MetadataPropertyHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MissingMemberHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MissingMemberHandling.cs index e1e7e0618..dc0df86e6 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MissingMemberHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/MissingMemberHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.csproj.txt b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.csproj.txt index 2c20b8c44..4dd7b55a0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.csproj.txt +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.csproj.txt @@ -1,8 +1,8 @@  - net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0;portable-net45+win8+wpa81+wp8;portable-net40+win8+wpa81+wp8+sl5 + net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 $(LibraryFrameworks) - latest + 9.0 11.0.0.0 11.0.1 @@ -18,27 +18,33 @@ Json.NET Newtonsoft.Json json - https://www.newtonsoft.com/content/images/nugeticon.png + packageIcon.png + $(MSBuildThisFileDirectory)packageIcon.png https://www.newtonsoft.com/json MIT true Newtonsoft.Json Newtonsoft.Json true + enable 2.12 - - $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb + true + snupkg + Newtonsoft.Json.ruleset + true + + + + + - - - Json.NET - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) + HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) Json.NET .NET 4.0 @@ -53,42 +59,24 @@ NET20;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CAS;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_DB_NULL_TYPE_CODE;HAVE_EMPTY_TYPES;HAVE_FAST_REVERSE;HAVE_FULL_REFLECTION;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_MEMORY_BARRIER;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_REFLECTION_EMIT;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;$(AdditionalConstants) - - - + + + Json.NET .NET Standard 1.0 - NETSTANDARD1_0;PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;$(AdditionalConstants) + NETSTANDARD1_0;PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) - - + + Json.NET .NET Standard 1.3 - NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;$(AdditionalConstants) + NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) Json.NET .NET Standard 2.0 - NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;$(AdditionalConstants) - - - Json.NET Portable .NET 4.0 - PORTABLE40;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;$(AdditionalConstants) - .NETPortable - v4.0 - Profile328 - .NETPortable,Version=v0.0,Profile=Profile328 - $(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets - - - Json.NET Portable - PORTABLE;HAVE_ASYNC;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;$(AdditionalConstants) - .NETPortable - v4.5 - Profile259 - .NETPortable,Version=v0.0,Profile=Profile259 - $(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets + NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.ruleset b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.ruleset index 17596c236..a49f1e22b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.ruleset +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Newtonsoft.Json.ruleset @@ -1,15 +1,199 @@ - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/NullValueHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/NullValueHandling.cs index b18a8d6d2..ceecdd62a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/NullValueHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/NullValueHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ObjectCreationHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ObjectCreationHandling.cs index 076c9c833..fd405ab6f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ObjectCreationHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ObjectCreationHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/PreserveReferencesHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/PreserveReferencesHandling.cs index b9d19865d..40d532293 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/PreserveReferencesHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/PreserveReferencesHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ReferenceLoopHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ReferenceLoopHandling.cs index c512f6713..9fbb2cb1d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ReferenceLoopHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/ReferenceLoopHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Required.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Required.cs index a11589d5d..5aea9c49e 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Required.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Required.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/Extensions.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/Extensions.cs index 9202c3335..61afd8286 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/Extensions.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/Extensions.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +34,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchema.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchema.cs index 7a60a80da..58806d356 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchema.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchema.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -34,6 +36,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// @@ -245,7 +249,9 @@ internal class JsonSchema internal string Location { get; set; } +#pragma warning disable CA1305 // Specify IFormatProvider private readonly string _internalId = Guid.NewGuid().ToString("N"); +#pragma warning restore CA1305 // Specify IFormatProvider internal string InternalId => _internalId; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 1ec413989..c065556aa 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -39,6 +41,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] @@ -223,7 +227,7 @@ private JsonSchema BuildSchema(JToken token) } string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty); - if (!string.IsNullOrEmpty(location)) + if (!StringUtils.IsNullOrEmpty(location)) { location = "/" + location; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaConstants.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaConstants.cs index fee8581bb..62b9045b0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaConstants.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaConstants.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System; using System.Collections.Generic; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaException.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaException.cs index 1100c8c5f..cdfb66802 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaException.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaException.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System; using System.Runtime.Serialization; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index 6a7093a31..20d2a8a2a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -41,6 +43,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// @@ -177,7 +181,7 @@ private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!string.IsNullOrEmpty(containerAttribute?.Title)) + if (!StringUtils.IsNullOrEmpty(containerAttribute?.Title)) { return containerAttribute.Title; } @@ -189,7 +193,7 @@ private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!string.IsNullOrEmpty(containerAttribute?.Description)) + if (!StringUtils.IsNullOrEmpty(containerAttribute?.Description)) { return containerAttribute.Description; } @@ -206,7 +210,7 @@ private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); - if (!string.IsNullOrEmpty(containerAttribute?.Id)) + if (!StringUtils.IsNullOrEmpty(containerAttribute?.Id)) { return containerAttribute.Id; } @@ -234,7 +238,7 @@ private JsonSchema GenerateInternal(Type type, Required valueRequired, bool requ string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); - if (!string.IsNullOrEmpty(resolvedId)) + if (!StringUtils.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModel.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModel.cs index db6437ae1..f45c19064 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModel.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModel.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +34,8 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs index 38e2eb1cb..96ba66059 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaModelBuilder.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -36,6 +38,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNode.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNode.cs index 5baa40685..05e6a6cd5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNode.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNode.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -37,6 +39,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs index ca20696ea..cf43e0b60 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System; using System.Collections.ObjectModel; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaResolver.cs index 351c468cf..f389b8abc 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaResolver.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -36,6 +38,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaType.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaType.cs index 393b39ee3..a4179b2c2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaType.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaType.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -29,6 +31,8 @@ using System; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaWriter.cs index 717950a57..8a796d3c2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/JsonSchemaWriter.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -39,6 +41,8 @@ #endif +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs index 2d81389b9..1a305a459 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/UndefinedSchemaIdHandling.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -29,6 +31,8 @@ using System; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventArgs.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventArgs.cs index ad653309a..481292b50 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventArgs.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventArgs.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +32,8 @@ using System; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventHandler.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventHandler.cs index 7471ab7a5..50cfd2192 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventHandler.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Schema/ValidationEventHandler.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #region License // Copyright (c) 2007 James Newton-King // @@ -29,6 +31,8 @@ using System; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Schema { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs index f501708e5..2cc9c59fe 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -35,9 +38,9 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization { internal static class CachedAttributeGetter where T : Attribute { - private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); + private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); - public static T GetAttribute(object type) + public static T? GetAttribute(object type) { return TypeAttributeCache.Get(type); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs index 2e4b5891f..18293a215 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCaseNamingStrategy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs index ac05ac5e6..f1855c869 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -41,7 +44,7 @@ internal class CamelCasePropertyNamesContractResolver : DefaultContractResolver { private static readonly object TypeContractCacheLock = new object(); private static readonly DefaultJsonNameTable NameTable = new DefaultJsonNameTable(); - private static Dictionary, JsonContract> _contractCache; + private static Dictionary, JsonContract>? _contractCache; /// /// Initializes a new instance of the class. @@ -69,7 +72,7 @@ public override JsonContract ResolveContract(Type type) // for backwards compadibility the CamelCasePropertyNamesContractResolver shares contracts between instances StructMultiKey key = new StructMultiKey(GetType(), type); - Dictionary, JsonContract> cache = _contractCache; + Dictionary, JsonContract>? cache = _contractCache; if (cache == null || !cache.TryGetValue(key, out JsonContract contract)) { contract = CreateContract(type); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 5bcb12586..45b661aa5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -172,7 +175,7 @@ internal class DefaultContractResolver : IContractResolver /// Gets or sets the naming strategy used to resolve how property names and dictionary keys are serialized. /// /// The naming strategy used to resolve how property names and dictionary keys are serialized. - public NamingStrategy NamingStrategy { get; set; } + public NamingStrategy? NamingStrategy { get; set; } /// /// Initializes a new instance of the class. @@ -237,18 +240,21 @@ protected virtual List GetSerializableMembers(Type objectType) MemberSerialization memberSerialization = JsonTypeReflector.GetObjectMemberSerialization(objectType, ignoreSerializableAttribute); + // Exclude index properties + // Do not filter ByRef types here because accessing FieldType/PropertyType can trigger additonal assembly loads IEnumerable allMembers = ReflectionUtils.GetFieldsAndProperties(objectType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) - .Where(FilterMembers); + .Where(m => m is PropertyInfo p ? !ReflectionUtils.IsIndexedProperty(p) : true); List serializableMembers = new List(); if (memberSerialization != MemberSerialization.Fields) { #if HAVE_DATA_CONTRACTS - DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType); + DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(objectType); #endif #pragma warning disable 618 + // Exclude index properties and ByRef types List defaultMembers = ReflectionUtils.GetFieldsAndProperties(objectType, DefaultMembersSearchFlags) .Where(FilterMembers).ToList(); #pragma warning restore 618 @@ -353,17 +359,18 @@ protected virtual JsonObjectContract CreateObjectContract(Type objectType) contract.MemberSerialization = JsonTypeReflector.GetObjectMemberSerialization(contract.NonNullableUnderlyingType, ignoreSerializableAttribute); contract.Properties.AddRange(CreateProperties(contract.NonNullableUnderlyingType, contract.MemberSerialization)); - System.Func extensionDataNameResolver = null; + System.Func? extensionDataNameResolver = null; - JsonObjectAttribute attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + JsonObjectAttribute? attribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); if (attribute != null) { contract.ItemRequired = attribute._itemRequired; contract.ItemNullValueHandling = attribute._itemNullValueHandling; + contract.MissingMemberHandling = attribute._missingMemberHandling; if (attribute.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(attribute); + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(attribute)!; extensionDataNameResolver = s => namingStrategy.GetDictionaryKey(s); } } @@ -377,7 +384,7 @@ protected virtual JsonObjectContract CreateObjectContract(Type objectType) if (contract.IsInstantiable) { - ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); // check if a JsonConstructorAttribute has been defined and use that if (overrideConstructor != null) @@ -398,7 +405,7 @@ protected virtual JsonObjectContract CreateObjectContract(Type objectType) } else if (contract.DefaultCreator == null || contract.DefaultCreatorNonPublic) { - ConstructorInfo constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo? constructor = GetParameterizedConstructor(contract.NonNullableUnderlyingType); if (constructor != null) { contract.ParameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor); @@ -409,7 +416,7 @@ protected virtual JsonObjectContract CreateObjectContract(Type objectType) { // value types always have default constructor // check whether there is a constructor that matches with non-writable properties on value type - ConstructorInfo constructor = GetImmutableConstructor(contract.NonNullableUnderlyingType, contract.Properties); + ConstructorInfo? constructor = GetImmutableConstructor(contract.NonNullableUnderlyingType, contract.Properties); if (constructor != null) { contract.OverrideCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor); @@ -471,7 +478,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) Type t = ReflectionUtils.GetMemberUnderlyingType(m); - if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType)) + if (ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type? dictionaryType)) { Type keyType = dictionaryType.GetGenericArguments()[0]; Type valueType = dictionaryType.GetGenericArguments()[1]; @@ -490,7 +497,7 @@ private MemberInfo GetExtensionDataMemberForType(Type type) private static void SetExtensionDataDelegates(JsonObjectContract contract, MemberInfo member) { - JsonExtensionDataAttribute extensionDataAttribute = ReflectionUtils.GetAttribute(member); + JsonExtensionDataAttribute? extensionDataAttribute = ReflectionUtils.GetAttribute(member); if (extensionDataAttribute == null) { return; @@ -498,10 +505,10 @@ private static void SetExtensionDataDelegates(JsonObjectContract contract, Membe Type t = ReflectionUtils.GetMemberUnderlyingType(member); - ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type dictionaryType); + ReflectionUtils.ImplementsGenericDefinition(t, typeof(IDictionary<,>), out Type? dictionaryType); - Type keyType = dictionaryType.GetGenericArguments()[0]; - Type valueType = dictionaryType.GetGenericArguments()[1]; + Type keyType = dictionaryType!.GetGenericArguments()[0]; + Type valueType = dictionaryType!.GetGenericArguments()[1]; Type createdType; @@ -515,27 +522,27 @@ private static void SetExtensionDataDelegates(JsonObjectContract contract, Membe createdType = t; } - System.Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); + System.Func getExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(member); if (extensionDataAttribute.ReadData) { - System.Action setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) + System.Action? setExtensionDataDictionary = (ReflectionUtils.CanSetMemberValue(member, true, false)) ? JsonTypeReflector.ReflectionDelegateFactory.CreateSet(member) : null; System.Func createExtensionDataDictionary = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor(createdType); - MethodInfo setMethod = t.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); + MethodInfo? setMethod = t.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); if (setMethod == null) { // Item is explicitly implemented and non-public // get from dictionary interface - setMethod = dictionaryType.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); + setMethod = dictionaryType!.GetProperty("Item", BindingFlags.Public | BindingFlags.Instance, null, valueType, new[] { keyType }, null)?.GetSetMethod(); } - MethodCall setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMethod); + MethodCall setExtensionDataDictionaryValue = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMethod!); ExtensionDataSetter extensionDataSetter = (o, key, value) => { - object dictionary = getExtensionDataDictionary(o); + object? dictionary = getExtensionDataDictionary(o); if (dictionary == null) { if (setExtensionDataDictionary == null) @@ -561,7 +568,7 @@ private static void SetExtensionDataDelegates(JsonObjectContract contract, Membe ExtensionDataGetter extensionDataGetter = o => { - object dictionary = getExtensionDataDictionary(o); + object? dictionary = getExtensionDataDictionary(o); if (dictionary == null) { return null; @@ -592,7 +599,7 @@ public IEnumerator> GetEnumerator() { foreach (KeyValuePair item in _e) { - yield return new KeyValuePair(item.Key, item.Value); + yield return new KeyValuePair(item.Key!, item.Value!); } } @@ -602,7 +609,7 @@ IEnumerator IEnumerable.GetEnumerator() } } - private ConstructorInfo GetAttributeConstructor(Type objectType) + private ConstructorInfo? GetAttributeConstructor(Type objectType) { IEnumerator en = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).GetEnumerator(); @@ -626,7 +633,7 @@ private ConstructorInfo GetAttributeConstructor(Type objectType) return null; } - private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCollection memberProperties) + private ConstructorInfo? GetImmutableConstructor(Type objectType, JsonPropertyCollection memberProperties) { IEnumerable constructors = objectType.GetConstructors(); IEnumerator en = constructors.GetEnumerator(); @@ -640,7 +647,7 @@ private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCol { foreach (ParameterInfo parameterInfo in parameters) { - JsonProperty memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + JsonProperty? memberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); if (memberProperty == null || memberProperty.Writable) { return null; @@ -655,7 +662,7 @@ private ConstructorInfo GetImmutableConstructor(Type objectType, JsonPropertyCol return null; } - private ConstructorInfo GetParameterizedConstructor(Type objectType) + private ConstructorInfo? GetParameterizedConstructor(Type objectType) { #if PORTABLE IEnumerable constructors = objectType.GetConstructors(BindingFlags.Public | BindingFlags.Instance); @@ -692,7 +699,12 @@ protected virtual IList CreateConstructorParameters(ConstructorInf foreach (ParameterInfo parameterInfo in constructorParameters) { - JsonProperty matchingMemberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); + if (parameterInfo.Name == null) + { + continue; + } + + JsonProperty? matchingMemberProperty = MatchProperty(memberProperties, parameterInfo.Name, parameterInfo.ParameterType); // ensure that property will have a name from matching property or from parameterinfo // parameterinfo could have no name if generated by a proxy (I'm looking at you Castle) @@ -710,7 +722,7 @@ protected virtual IList CreateConstructorParameters(ConstructorInf return parameterCollection; } - private JsonProperty MatchProperty(JsonPropertyCollection properties, string name, Type type) + private JsonProperty? MatchProperty(JsonPropertyCollection properties, string name, Type type) { // it is possible to generate a member with a null name using Reflection.Emit // protect against an ArgumentNullException from GetClosestMatchProperty by testing for null here @@ -719,7 +731,7 @@ private JsonProperty MatchProperty(JsonPropertyCollection properties, string nam return null; } - JsonProperty property = properties.GetClosestMatchProperty(name); + JsonProperty? property = properties.GetClosestMatchProperty(name); // must match type as well as name if (property == null || property.PropertyType != type) { @@ -735,7 +747,7 @@ private JsonProperty MatchProperty(JsonPropertyCollection properties, string nam /// The matching member property. /// The constructor parameter. /// A created for the given . - protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty matchingMemberProperty, ParameterInfo parameterInfo) + protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProperty? matchingMemberProperty, ParameterInfo parameterInfo) { JsonProperty property = new JsonProperty(); property.PropertyType = parameterInfo.ParameterType; @@ -774,7 +786,7 @@ protected virtual JsonProperty CreatePropertyFromConstructorParameter(JsonProper /// /// Type of the object. /// The contract's default . - protected virtual JsonConverter ResolveContractConverter(Type objectType) + protected virtual JsonConverter? ResolveContractConverter(Type objectType) { return JsonTypeReflector.GetJsonConverter(objectType); } @@ -789,7 +801,7 @@ private System.Func GetDefaultCreator(Type createdType) #endif private void InitializeContract(JsonContract contract) { - JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); + JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetCachedAttribute(contract.NonNullableUnderlyingType); if (containerAttribute != null) { contract.IsReference = containerAttribute._isReference; @@ -797,7 +809,7 @@ private void InitializeContract(JsonContract contract) #if HAVE_DATA_CONTRACTS else { - DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); + DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(contract.NonNullableUnderlyingType); // doesn't have a null value if (dataContractAttribute != null && dataContractAttribute.IsReference) { @@ -827,11 +839,11 @@ private void ResolveCallbackMethods(JsonContract contract, Type t) { GetCallbackMethodsForType( t, - out List onSerializing, - out List onSerialized, - out List onDeserializing, - out List onDeserialized, - out List onError); + out List? onSerializing, + out List? onSerialized, + out List? onDeserializing, + out List? onDeserialized, + out List? onError); if (onSerializing != null) { @@ -859,7 +871,7 @@ private void ResolveCallbackMethods(JsonContract contract, Type t) } } - private void GetCallbackMethodsForType(Type type, out List onSerializing, out List onSerialized, out List onDeserializing, out List onDeserialized, out List onError) + private void GetCallbackMethodsForType(Type type, out List? onSerializing, out List? onSerialized, out List? onDeserializing, out List? onDeserialized, out List? onError) { onSerializing = null; onSerialized = null; @@ -870,11 +882,11 @@ private void GetCallbackMethodsForType(Type type, out List(objectType); + JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(objectType); if (containerAttribute?.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute); + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute)!; contract.DictionaryKeyResolver = s => namingStrategy.GetDictionaryKey(s); } else @@ -1017,7 +1029,7 @@ protected virtual JsonDictionaryContract CreateDictionaryContract(Type objectTyp contract.DictionaryKeyResolver = ResolveDictionaryKey; } - ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); if (overrideConstructor != null) { @@ -1055,7 +1067,7 @@ protected virtual JsonArrayContract CreateArrayContract(Type objectType) JsonArrayContract contract = new JsonArrayContract(objectType); InitializeContract(contract); - ConstructorInfo overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); + ConstructorInfo? overrideConstructor = GetAttributeConstructor(contract.NonNullableUnderlyingType); if (overrideConstructor != null) { @@ -1146,10 +1158,10 @@ protected virtual JsonDynamicContract CreateDynamicContract(Type objectType) JsonDynamicContract contract = new JsonDynamicContract(objectType); InitializeContract(contract); - JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute(objectType); + JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(objectType); if (containerAttribute?.NamingStrategyType != null) { - NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute); + NamingStrategy namingStrategy = JsonTypeReflector.GetContainerNamingStrategy(containerAttribute)!; contract.PropertyNameResolver = s => namingStrategy.GetDictionaryKey(s); } else @@ -1191,7 +1203,7 @@ protected virtual JsonContract CreateContract(Type objectType) } t = ReflectionUtils.EnsureNotNullableType(t); - JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(t); + JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetCachedAttribute(t); if (containerAttribute is JsonObjectAttribute) { @@ -1220,7 +1232,7 @@ protected virtual JsonContract CreateContract(Type objectType) if (typeof(IEnumerable).IsAssignableFrom(t)) { - return CreateArrayContract(t); + return CreateArrayContract(objectType); } if (CanConvertToString(t)) @@ -1290,7 +1302,7 @@ internal static bool CanConvertToString(Type type) return false; } - private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) + private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo? currentCallback, ref Type? prevAttributeType) { if (!method.IsDefined(attributeType, false)) { @@ -1374,7 +1386,7 @@ protected virtual IList CreateProperties(Type type, MemberSerializ // nametable is not thread-safe for multiple writers lock (nameTable) { - property.PropertyName = nameTable.Add(property.PropertyName); + property.PropertyName = nameTable.Add(property.PropertyName!); } properties.AddProperty(property); @@ -1400,7 +1412,7 @@ protected virtual IValueProvider CreateMemberValueProvider(MemberInfo member) // warning - this method use to cause errors with Intellitrace. Retest in VS Ultimate after changes IValueProvider valueProvider; -#if !(PORTABLE40 || PORTABLE || DOTNET || NETSTANDARD2_0 || NETCOREAPP) +#if NETFRAMEWORK if (DynamicCodeGeneration) { valueProvider = new DynamicValueProvider(member); @@ -1462,11 +1474,11 @@ protected virtual JsonProperty CreateProperty(MemberInfo member, MemberSerializa private void SetPropertySettingsFromAttributes(JsonProperty property, object attributeProvider, string name, Type declaringType, MemberSerialization memberSerialization, out bool allowNonPublicAccess) { #if HAVE_DATA_CONTRACTS - DataContractAttribute dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); + DataContractAttribute? dataContractAttribute = JsonTypeReflector.GetDataContractAttribute(declaringType); - MemberInfo memberInfo = attributeProvider as MemberInfo; + MemberInfo? memberInfo = attributeProvider as MemberInfo; - DataMemberAttribute dataMemberAttribute; + DataMemberAttribute? dataMemberAttribute; if (dataContractAttribute != null && memberInfo != null) { dataMemberAttribute = JsonTypeReflector.GetDataMemberAttribute((MemberInfo)memberInfo); @@ -1477,8 +1489,8 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att } #endif - JsonPropertyAttribute propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); - JsonRequiredAttribute requiredAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + JsonPropertyAttribute? propertyAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + JsonRequiredAttribute? requiredAttribute = JsonTypeReflector.GetAttribute(attributeProvider); string mappedName; bool hasSpecifiedName; @@ -1500,9 +1512,9 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att hasSpecifiedName = false; } - JsonContainerAttribute containerAttribute = JsonTypeReflector.GetAttribute(declaringType); + JsonContainerAttribute? containerAttribute = JsonTypeReflector.GetAttribute(declaringType); - NamingStrategy namingStrategy; + NamingStrategy? namingStrategy; if (propertyAttribute?.NamingStrategyType != null) { namingStrategy = JsonTypeReflector.CreateNamingStrategyInstance(propertyAttribute.NamingStrategyType, propertyAttribute.NamingStrategyParameters); @@ -1605,7 +1617,7 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att // the class type might have a converter but the property converter takes precedence property.Converter = JsonTypeReflector.GetJsonConverter(attributeProvider); - DefaultValueAttribute defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); + DefaultValueAttribute? defaultValueAttribute = JsonTypeReflector.GetAttribute(attributeProvider); if (defaultValueAttribute != null) { property.DefaultValue = defaultValueAttribute.Value; @@ -1628,7 +1640,7 @@ private void SetPropertySettingsFromAttributes(JsonProperty property, object att } } - private Predicate CreateShouldSerializeTest(MemberInfo member) + private Predicate? CreateShouldSerializeTest(MemberInfo member) { MethodInfo shouldSerializeMethod = member.DeclaringType.GetMethod(JsonTypeReflector.ShouldSerializePrefix + member.Name, ReflectionUtils.EmptyTypes); @@ -1637,15 +1649,15 @@ private Predicate CreateShouldSerializeTest(MemberInfo member) return null; } - MethodCall shouldSerializeCall = + MethodCall shouldSerializeCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(shouldSerializeMethod); - return o => (bool)shouldSerializeCall(o); + return o => (bool)shouldSerializeCall(o)!; } private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, bool allowNonPublicAccess) { - MemberInfo specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + MemberInfo? specifiedMember = member.DeclaringType.GetProperty(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (specifiedMember == null) { specifiedMember = member.DeclaringType.GetField(member.Name + JsonTypeReflector.SpecifiedPostfix, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); @@ -1656,7 +1668,7 @@ private void SetIsSpecifiedActions(JsonProperty property, MemberInfo member, boo return; } - System.Func specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(specifiedMember); + System.Func specifiedPropertyGet = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(specifiedMember)!; property.GetIsSpecified = o => (bool)specifiedPropertyGet(o); @@ -1723,4 +1735,4 @@ public string GetResolvedPropertyName(string propertyName) return ResolvePropertyName(propertyName); } } -} +} \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultNamingStrategy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultNamingStrategy.cs index b6fc64f31..8992459a3 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultNamingStrategy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultNamingStrategy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization { /// diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 1d542fc06..7a63c4506 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 55ba606ae..584a218c8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -47,19 +50,19 @@ internal class DefaultSerializationBinder : { internal static readonly DefaultSerializationBinder Instance = new DefaultSerializationBinder(); - private readonly ThreadSafeStore, Type> _typeCache; + private readonly ThreadSafeStore, Type> _typeCache; /// /// Initializes a new instance of the class. /// public DefaultSerializationBinder() { - _typeCache = new ThreadSafeStore, Type>(GetTypeFromTypeNameKey); + _typeCache = new ThreadSafeStore, Type>(GetTypeFromTypeNameKey); } - private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) + private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) { - string assemblyName = typeNameKey.Value1; + string? assemblyName = typeNameKey.Value1; string typeName = typeNameKey.Value2; if (assemblyName != null) @@ -100,7 +103,7 @@ private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) throw new JsonSerializationException("Could not load assembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, assemblyName)); } - Type type = assembly.GetType(typeName); + Type? type = assembly.GetType(typeName); if (type == null) { // if generic type, try manually parsing the type arguments for the case of dynamically loaded assemblies @@ -131,9 +134,9 @@ private Type GetTypeFromTypeNameKey(StructMultiKey typeNameKey) } } - private Type GetGenericTypeFromTypeName(string typeName, Assembly assembly) + private Type? GetGenericTypeFromTypeName(string typeName, Assembly assembly) { - Type type = null; + Type? type = null; int openBracketIndex = typeName.IndexOf('['); if (openBracketIndex >= 0) { @@ -163,7 +166,7 @@ private Type GetGenericTypeFromTypeName(string typeName, Assembly assembly) { string typeArgAssemblyQualifiedName = typeName.Substring(typeArgStartIndex, i - typeArgStartIndex); - StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName); + StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(typeArgAssemblyQualifiedName); genericTypeArguments.Add(GetTypeByName(typeNameKey)); } break; @@ -177,7 +180,7 @@ private Type GetGenericTypeFromTypeName(string typeName, Assembly assembly) return type; } - private Type GetTypeByName(StructMultiKey typeNameKey) + private Type GetTypeByName(StructMultiKey typeNameKey) { return _typeCache.Get(typeNameKey); } @@ -190,9 +193,9 @@ private Type GetTypeByName(StructMultiKey typeNameKey) /// /// The type of the object the formatter creates a new instance of. /// - public override Type BindToType(string assemblyName, string typeName) + public override Type BindToType(string? assemblyName, string typeName) { - return GetTypeByName(new StructMultiKey(assemblyName, typeName)); + return GetTypeByName(new StructMultiKey(assemblyName, typeName)); } /// @@ -205,7 +208,7 @@ public override Type BindToType(string assemblyName, string typeName) #if HAVE_SERIALIZATION_BINDER_BIND_TO_NAME override #endif - void BindToName(Type serializedType, out string assemblyName, out string typeName) + void BindToName(Type serializedType, out string? assemblyName, out string? typeName) { #if !HAVE_FULL_REFLECTION assemblyName = serializedType.GetTypeInfo().Assembly.FullName; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs index 866ab3c50..dfaecd0f0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DiagnosticsTraceWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #if HAVE_TRACE_WRITER using System; using System.Diagnostics; @@ -47,7 +50,7 @@ private TraceEventType GetTraceEventType(TraceLevel level) /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - public void Trace(TraceLevel level, string message, Exception ex) + public void Trace(TraceLevel level, string message, Exception? ex) { if (level == TraceLevel.Off) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DynamicValueProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DynamicValueProvider.cs index 780660cf7..9d620f7a0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DynamicValueProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/DynamicValueProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -46,8 +49,8 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization internal class DynamicValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; - private Func _getter; - private Action _setter; + private Func? _getter; + private Action? _setter; /// /// Initializes a new instance of the class. @@ -64,7 +67,7 @@ public DynamicValueProvider(MemberInfo memberInfo) /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object value) + public void SetValue(object target, object? value) { try { @@ -102,7 +105,7 @@ public void SetValue(object target, object value) /// /// The target to get the value from. /// The value. - public object GetValue(object target) + public object? GetValue(object target) { try { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorContext.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorContext.cs index 5d60cfe78..acd46bca1 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorContext.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorContext.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -36,7 +39,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization /// internal class ErrorContext { - internal ErrorContext(object originalObject, object member, string path, Exception error) + internal ErrorContext(object? originalObject, object? member, string path, Exception error) { OriginalObject = originalObject; Member = member; @@ -56,13 +59,13 @@ internal ErrorContext(object originalObject, object member, string path, Excepti /// Gets the original object that caused the error. /// /// The original object that caused the error. - public object OriginalObject { get; } + public object? OriginalObject { get; } /// /// Gets the member that caused the error. /// /// The member that caused the error. - public object Member { get; } + public object? Member { get; } /// /// Gets the path of the JSON location where the error occurred. diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorEventArgs.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorEventArgs.cs index 2980ad078..45137cdaf 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorEventArgs.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ErrorEventArgs.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,7 +43,7 @@ internal class ErrorEventArgs : EventArgs /// Gets the current object the error event is being raised against. /// /// The current object the error event is being raised against. - public object CurrentObject { get; } + public object? CurrentObject { get; } /// /// Gets the error context. @@ -53,7 +56,7 @@ internal class ErrorEventArgs : EventArgs /// /// The current object. /// The error context. - public ErrorEventArgs(object currentObject, ErrorContext errorContext) + public ErrorEventArgs(object? currentObject, ErrorContext errorContext) { CurrentObject = currentObject; ErrorContext = errorContext; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs index 2f652dd67..f7ca95ba1 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -47,8 +50,8 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization internal class ExpressionValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; - private Func _getter; - private Action _setter; + private Func? _getter; + private Action? _setter; /// /// Initializes a new instance of the class. @@ -65,7 +68,7 @@ public ExpressionValueProvider(MemberInfo memberInfo) /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object value) + public void SetValue(object target, object? value) { try { @@ -103,7 +106,7 @@ public void SetValue(object target, object value) /// /// The target to get the value from. /// The value. - public object GetValue(object target) + public object? GetValue(object target) { try { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/FormatterConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/FormatterConverter.cs index f00406d9c..7b348f703 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/FormatterConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/FormatterConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Globalization; using System.Runtime.InteropServices; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IAttributeProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IAttributeProvider.cs index fe2aa51dc..02bcbacc3 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IAttributeProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IAttributeProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IContractResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IContractResolver.cs index b925b6922..cf40b1912 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IContractResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IContractResolver.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IReferenceResolver.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IReferenceResolver.cs index 15ffe5bb3..b2f90e144 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IReferenceResolver.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IReferenceResolver.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ISerializationBinder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ISerializationBinder.cs index 64d7e907d..ed65b0c7d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ISerializationBinder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ISerializationBinder.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal interface ISerializationBinder /// Specifies the name of the serialized object. /// Specifies the name of the serialized object /// The type of the object the formatter creates a new instance of. - Type BindToType(string assemblyName, string typeName); + Type BindToType(string? assemblyName, string typeName); /// /// When implemented, controls the binding of a serialized object to a type. @@ -52,6 +55,6 @@ internal interface ISerializationBinder /// The type of the object the formatter creates a new instance of. /// Specifies the name of the serialized object. /// Specifies the name of the serialized object. - void BindToName(Type serializedType, out string assemblyName, out string typeName); + void BindToName(Type serializedType, out string? assemblyName, out string? typeName); } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ITraceWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ITraceWriter.cs index a4bfcfdbb..972264685 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ITraceWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ITraceWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -27,6 +30,6 @@ internal interface ITraceWriter /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - void Trace(TraceLevel level, string message, Exception ex); + void Trace(TraceLevel level, string message, Exception? ex); } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IValueProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IValueProvider.cs index 7e6e56dc6..24f9ac966 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IValueProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/IValueProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -39,13 +42,13 @@ internal interface IValueProvider /// /// The target to set the value on. /// The value to set on the target. - void SetValue(object target, object value); + void SetValue(object target, object? value); /// /// Gets the value. /// /// The target to get the value from. /// The value. - object GetValue(object target); + object? GetValue(object target); } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonArrayContract.cs index 373cacb54..32cd801ff 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -35,6 +38,7 @@ using System.Reflection; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Collections; +using System.Diagnostics; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -53,7 +57,7 @@ internal class JsonArrayContract : JsonContainerContract /// Gets the of the collection items. /// /// The of the collection items. - public Type CollectionItemType { get; } + public Type? CollectionItemType { get; } /// /// Gets a value indicating whether the collection type is a multidimensional array. @@ -61,26 +65,26 @@ internal class JsonArrayContract : JsonContainerContract /// true if the collection type is a multidimensional array; otherwise, false. public bool IsMultidimensionalArray { get; } - private readonly Type _genericCollectionDefinitionType; + private readonly Type? _genericCollectionDefinitionType; - private Type _genericWrapperType; - private ObjectConstructor _genericWrapperCreator; - private Func _genericTemporaryCollectionCreator; + private Type? _genericWrapperType; + private ObjectConstructor? _genericWrapperCreator; + private Func? _genericTemporaryCollectionCreator; internal bool IsArray { get; } internal bool ShouldCreateWrapper { get; } internal bool CanDeserialize { get; private set; } - private readonly ConstructorInfo _parameterizedConstructor; + private readonly ConstructorInfo? _parameterizedConstructor; - private ObjectConstructor _parameterizedCreator; - private ObjectConstructor _overrideCreator; + private ObjectConstructor? _parameterizedCreator; + private ObjectConstructor? _overrideCreator; - internal ObjectConstructor ParameterizedCreator + internal ObjectConstructor? ParameterizedCreator { get { - if (_parameterizedCreator == null) + if (_parameterizedCreator == null && _parameterizedConstructor != null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } @@ -93,7 +97,7 @@ internal ObjectConstructor ParameterizedCreator /// Gets or sets the function used to create the object. When set this function will override . /// /// The function used to create the object. - public ObjectConstructor OverrideCreator + public ObjectConstructor? OverrideCreator { get => _overrideCreator; set @@ -120,11 +124,14 @@ public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; - IsArray = CreatedType.IsArray; + + // netcoreapp3.0 uses EmptyPartition for empty enumerable. Treat as an empty array. + IsArray = CreatedType.IsArray || + (NonNullableUnderlyingType.IsGenericType() && NonNullableUnderlyingType.GetGenericTypeDefinition().FullName == "System.Linq.EmptyPartition`1"); bool canDeserialize; - Type tempCollectionType; + Type? tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); @@ -132,60 +139,60 @@ public JsonArrayContract(Type underlyingType) _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; - IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); + IsMultidimensionalArray = (CreatedType.IsArray && UnderlyingType.GetArrayRank() > 1); } - else if (typeof(IList).IsAssignableFrom(underlyingType)) + else if (typeof(IList).IsAssignableFrom(NonNullableUnderlyingType)) { - if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) + if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } else { - CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); + CollectionItemType = ReflectionUtils.GetCollectionItemType(NonNullableUnderlyingType); } - if (underlyingType == typeof(IList)) + if (NonNullableUnderlyingType == typeof(IList)) { CreatedType = typeof(List); } if (CollectionItemType != null) { - _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); } - IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); + IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(NonNullableUnderlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } - else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) + else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; - if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) - || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) + if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(ICollection<>)) + || ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IList<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } #if HAVE_ISET - if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) + if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(ISet<>))) { CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); } #endif - _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if HAVE_READ_ONLY_COLLECTIONS - else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) + else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; - if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) - || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) + if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyCollection<>)) + || ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyList<>))) { CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); } @@ -194,14 +201,14 @@ public JsonArrayContract(Type underlyingType) _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); #if HAVE_FSHARP_TYPES - StoreFSharpListCreatorIfNecessary(underlyingType); + StoreFSharpListCreatorIfNecessary(NonNullableUnderlyingType); #endif IsReadOnlyOrFixedSize = true; canDeserialize = HasParameterizedCreatorInternal; } #endif - else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) + else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; @@ -210,13 +217,13 @@ public JsonArrayContract(Type underlyingType) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } - _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); + _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(NonNullableUnderlyingType, CollectionItemType); #if HAVE_FSHARP_TYPES - StoreFSharpListCreatorIfNecessary(underlyingType); + StoreFSharpListCreatorIfNecessary(NonNullableUnderlyingType); #endif - if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + if (NonNullableUnderlyingType.IsGenericType() && NonNullableUnderlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; @@ -255,11 +262,12 @@ public JsonArrayContract(Type underlyingType) } #endif - if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( - underlyingType, + if (CollectionItemType != null && + ImmutableCollectionsUtils.TryBuildImmutableForArrayContract( + NonNullableUnderlyingType, CollectionItemType, - out Type immutableCreatedType, - out ObjectConstructor immutableParameterizedCreator)) + out Type? immutableCreatedType, + out ObjectConstructor? immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; @@ -272,6 +280,8 @@ internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { + MiscellaneousUtils.Assert(_genericCollectionDefinitionType != null); + _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; @@ -315,7 +325,7 @@ private void StoreFSharpListCreatorIfNecessary(Type underlyingType) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); - _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); + _parameterizedCreator = FSharpUtils.Instance.CreateSeq(CollectionItemType!); } } #endif diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContainerContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContainerContract.cs index 437fd4f09..7dedae3d2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContainerContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContainerContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -46,11 +49,11 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization /// internal class JsonContainerContract : JsonContract { - private JsonContract _itemContract; - private JsonContract _finalItemContract; + private JsonContract? _itemContract; + private JsonContract? _finalItemContract; // will be null for containers that don't have an item type (e.g. IList) or for complex objects - internal JsonContract ItemContract + internal JsonContract? ItemContract { get => _itemContract; set @@ -68,13 +71,13 @@ internal JsonContract ItemContract } // the final (i.e. can't be inherited from like a sealed class or valuetype) item contract - internal JsonContract FinalItemContract => _finalItemContract; + internal JsonContract? FinalItemContract => _finalItemContract; /// /// Gets or sets the default collection items . /// /// The converter. - public JsonConverter ItemConverter { get; set; } + public JsonConverter? ItemConverter { get; set; } /// /// Gets or sets a value indicating whether the collection items preserve object references. @@ -101,7 +104,7 @@ internal JsonContract ItemContract internal JsonContainerContract(Type underlyingType) : base(underlyingType) { - JsonContainerAttribute jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute(underlyingType); + JsonContainerAttribute? jsonContainerAttribute = JsonTypeReflector.GetCachedAttribute(underlyingType); if (jsonContainerAttribute != null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContract.cs index 1190a3e1d..c596ca31f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -71,13 +74,13 @@ internal enum JsonContractType /// The object to set extension data on. /// The extension data key. /// The extension data value. - internal delegate void ExtensionDataSetter(object o, string key, object value); + internal delegate void ExtensionDataSetter(object o, string key, object? value); /// /// Gets extension data for an object during serialization. /// /// The object to set extension data on. - internal delegate IEnumerable> ExtensionDataGetter(object o); + internal delegate IEnumerable>? ExtensionDataGetter(object o); /// /// Contract details for a used by the . @@ -94,11 +97,11 @@ internal abstract class JsonContract internal bool IsSealed; internal bool IsInstantiable; - private List _onDeserializedCallbacks; - private IList _onDeserializingCallbacks; - private IList _onSerializedCallbacks; - private IList _onSerializingCallbacks; - private IList _onErrorCallbacks; + private List? _onDeserializedCallbacks; + private List? _onDeserializingCallbacks; + private List? _onSerializedCallbacks; + private List? _onSerializingCallbacks; + private List? _onErrorCallbacks; private Type _createdType; /// @@ -116,6 +119,7 @@ public Type CreatedType get => _createdType; set { + ValidationUtils.ArgumentNotNull(value, nameof(value)); _createdType = value; IsSealed = _createdType.IsSealed(); @@ -133,11 +137,14 @@ public Type CreatedType /// Gets or sets the default for this contract. /// /// The converter. - public JsonConverter Converter { get; set; } + public JsonConverter? Converter { get; set; } - // internally specified JsonConverter's to override default behavour - // checked for after passed in converters and attribute specified converters - internal JsonConverter InternalConverter { get; set; } + /// + /// Gets the internally resolved for the contract's type. + /// This converter is used as a fallback converter when no other converter is resolved. + /// Setting will always override this converter. + /// + public JsonConverter? InternalConverter { get; internal set; } /// /// Gets or sets all methods called immediately after deserialization of the object. @@ -228,7 +235,7 @@ public IList OnErrorCallbacks /// Gets or sets the default creator method used to create the object. /// /// The default creator method used to create the object. - public Func DefaultCreator { get; set; } + public Func? DefaultCreator { get; set; } /// /// Gets or sets a value indicating whether the default creator is non-public. @@ -250,7 +257,7 @@ internal JsonContract(Type underlyingType) NonNullableUnderlyingType = (IsNullable && ReflectionUtils.IsNullableType(underlyingType)) ? Nullable.GetUnderlyingType(underlyingType) : underlyingType; - CreatedType = NonNullableUnderlyingType; + _createdType = CreatedType = NonNullableUnderlyingType; IsConvertable = ConvertUtils.IsConvertible(NonNullableUnderlyingType); IsEnum = NonNullableUnderlyingType.IsEnum(); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 4b4401ab7..0d7d87c4e 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -49,41 +52,41 @@ internal class JsonDictionaryContract : JsonContainerContract /// Gets or sets the dictionary key resolver. /// /// The dictionary key resolver. - public Func DictionaryKeyResolver { get; set; } + public Func? DictionaryKeyResolver { get; set; } /// /// Gets the of the dictionary keys. /// /// The of the dictionary keys. - public Type DictionaryKeyType { get; } + public Type? DictionaryKeyType { get; } /// /// Gets the of the dictionary values. /// /// The of the dictionary values. - public Type DictionaryValueType { get; } + public Type? DictionaryValueType { get; } - internal JsonContract KeyContract { get; set; } + internal JsonContract? KeyContract { get; set; } - private readonly Type _genericCollectionDefinitionType; + private readonly Type? _genericCollectionDefinitionType; - private Type _genericWrapperType; - private ObjectConstructor _genericWrapperCreator; + private Type? _genericWrapperType; + private ObjectConstructor? _genericWrapperCreator; - private Func _genericTemporaryDictionaryCreator; + private Func? _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; } - private readonly ConstructorInfo _parameterizedConstructor; + private readonly ConstructorInfo? _parameterizedConstructor; - private ObjectConstructor _overrideCreator; - private ObjectConstructor _parameterizedCreator; + private ObjectConstructor? _overrideCreator; + private ObjectConstructor? _parameterizedCreator; - internal ObjectConstructor ParameterizedCreator + internal ObjectConstructor? ParameterizedCreator { get { - if (_parameterizedCreator == null) + if (_parameterizedCreator == null && _parameterizedConstructor != null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } @@ -96,7 +99,7 @@ internal ObjectConstructor ParameterizedCreator /// Gets or sets the function used to create the object. When set this function will override . /// /// The function used to create the object. - public ObjectConstructor OverrideCreator + public ObjectConstructor? OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; @@ -119,24 +122,24 @@ public JsonDictionaryContract(Type underlyingType) { ContractType = JsonContractType.Dictionary; - Type keyType; - Type valueType; + Type? keyType; + Type? valueType; - if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) + if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; - if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) + if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IDictionary<,>))) { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } - else if (underlyingType.IsGenericType()) + else if (NonNullableUnderlyingType.IsGenericType()) { // ConcurrentDictionary<,> + IDictionary setter + null value = error // wrap to use generic setter // https://github.com/JamesNK/Newtonsoft.Json/issues/1582 - Type typeDefinition = underlyingType.GetGenericTypeDefinition(); + Type typeDefinition = NonNullableUnderlyingType.GetGenericTypeDefinition(); if (typeDefinition.FullName == JsonTypeReflector.ConcurrentDictionaryTypeName) { ShouldCreateWrapper = true; @@ -144,17 +147,17 @@ public JsonDictionaryContract(Type underlyingType) } #if HAVE_READ_ONLY_COLLECTIONS - IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); + IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(NonNullableUnderlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if HAVE_READ_ONLY_COLLECTIONS - else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) + else if (ReflectionUtils.ImplementsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; - if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) + if (ReflectionUtils.IsGenericDefinition(NonNullableUnderlyingType, typeof(IReadOnlyDictionary<,>))) { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); } @@ -164,9 +167,9 @@ public JsonDictionaryContract(Type underlyingType) #endif else { - ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); + ReflectionUtils.GetDictionaryKeyValueTypes(NonNullableUnderlyingType, out keyType, out valueType); - if (UnderlyingType == typeof(IDictionary)) + if (NonNullableUnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary); } @@ -180,10 +183,10 @@ public JsonDictionaryContract(Type underlyingType) typeof(IDictionary<,>).MakeGenericType(keyType, valueType)); #if HAVE_FSHARP_TYPES - if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) + if (!HasParameterizedCreatorInternal && NonNullableUnderlyingType.Name == FSharpUtils.FSharpMapTypeName) { - FSharpUtils.EnsureInitialized(underlyingType.Assembly()); - _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); + FSharpUtils.EnsureInitialized(NonNullableUnderlyingType.Assembly()); + _parameterizedCreator = FSharpUtils.Instance.CreateMap(keyType, valueType); } #endif } @@ -208,12 +211,14 @@ public JsonDictionaryContract(Type underlyingType) } #endif - if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( - underlyingType, - DictionaryKeyType, - DictionaryValueType, - out Type immutableCreatedType, - out ObjectConstructor immutableParameterizedCreator)) + if (DictionaryKeyType != null && + DictionaryValueType != null && + ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( + NonNullableUnderlyingType, + DictionaryKeyType, + DictionaryValueType, + out Type? immutableCreatedType, + out ObjectConstructor? immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; @@ -227,7 +232,7 @@ internal IWrappedDictionary CreateWrapper(object dictionary) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); - ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); + ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDynamicContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDynamicContract.cs index be5ff6483..c52d1e69a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDynamicContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonDynamicContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -50,13 +53,13 @@ internal class JsonDynamicContract : JsonContainerContract /// Gets or sets the property name resolver. /// /// The property name resolver. - public Func PropertyNameResolver { get; set; } + public Func? PropertyNameResolver { get; set; } private readonly ThreadSafeStore>> _callSiteGetters = new ThreadSafeStore>>(CreateCallSiteGetter); - private readonly ThreadSafeStore>> _callSiteSetters = - new ThreadSafeStore>>(CreateCallSiteSetter); + private readonly ThreadSafeStore>> _callSiteSetters = + new ThreadSafeStore>>(CreateCallSiteSetter); private static CallSite> CreateCallSiteGetter(string name) { @@ -65,11 +68,11 @@ private static CallSite> CreateCallSiteGetter(str return CallSite>.Create(new NoThrowGetBinderMember(getMemberBinder)); } - private static CallSite> CreateCallSiteSetter(string name) + private static CallSite> CreateCallSiteSetter(string name) { SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils)); - return CallSite>.Create(new NoThrowSetBinderMember(binder)); + return CallSite>.Create(new NoThrowSetBinderMember(binder)); } /// @@ -84,7 +87,7 @@ public JsonDynamicContract(Type underlyingType) Properties = new JsonPropertyCollection(UnderlyingType); } - internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object value) + internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string name, out object? value) { ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); @@ -104,11 +107,11 @@ internal bool TryGetMember(IDynamicMetaObjectProvider dynamicProvider, string na } } - internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object value) + internal bool TrySetMember(IDynamicMetaObjectProvider dynamicProvider, string name, object? value) { ValidationUtils.ArgumentNotNull(dynamicProvider, nameof(dynamicProvider)); - CallSite> callSite = _callSiteSetters.Get(name); + CallSite> callSite = _callSiteSetters.Get(name); object result = callSite.Target(callSite, dynamicProvider, value); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 692483560..c38adc113 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,9 +43,9 @@ internal class JsonFormatterConverter : IFormatterConverter { private readonly JsonSerializerInternalReader _reader; private readonly JsonISerializableContract _contract; - private readonly JsonProperty _member; + private readonly JsonProperty? _member; - public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty member) + public JsonFormatterConverter(JsonSerializerInternalReader reader, JsonISerializableContract contract, JsonProperty? member) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); ValidationUtils.ArgumentNotNull(contract, nameof(contract)); @@ -60,7 +63,7 @@ private T GetTokenValue(object value) return (T)System.Convert.ChangeType(v.Value, typeof(T), CultureInfo.InvariantCulture); } - public object Convert(object value, Type type) + public object? Convert(object value, Type type) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -76,12 +79,9 @@ public object Convert(object value, TypeCode typeCode) { ValidationUtils.ArgumentNotNull(value, nameof(value)); - if (value is JValue v) - { - value = v.Value; - } + object? resolvedValue = (value is JValue v) ? v.Value : value; - return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture); + return System.Convert.ChangeType(resolvedValue, typeCode, CultureInfo.InvariantCulture); } public bool ToBoolean(object value) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonISerializableContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonISerializableContract.cs index ef777d16d..3605df384 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonISerializableContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonISerializableContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -42,7 +45,7 @@ internal class JsonISerializableContract : JsonContainerContract /// Gets or sets the object constructor. /// /// The object constructor. - public ObjectConstructor ISerializableCreator { get; set; } + public ObjectConstructor? ISerializableCreator { get; set; } /// /// Initializes a new instance of the class. diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonLinqContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonLinqContract.cs index a3994348b..ef922ff08 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonLinqContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonLinqContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonObjectContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonObjectContract.cs index 16ed9b22e..23fd14881 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonObjectContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonObjectContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -48,6 +51,12 @@ internal class JsonObjectContract : JsonContainerContract /// The member object serialization. public MemberSerialization MemberSerialization { get; set; } + /// + /// Gets or sets the missing member handling used when deserializing this object. + /// + /// The missing member handling. + public MissingMemberHandling? MissingMemberHandling { get; set; } + /// /// Gets or sets a value that indicates whether the object's properties are required. /// @@ -89,13 +98,13 @@ public JsonPropertyCollection CreatorParameters /// This function is called with a collection of arguments which are defined by the collection. /// /// The function used to create the object. - public ObjectConstructor OverrideCreator + public ObjectConstructor? OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; } - internal ObjectConstructor ParameterizedCreator + internal ObjectConstructor? ParameterizedCreator { get => _parameterizedCreator; set => _parameterizedCreator = value; @@ -104,17 +113,17 @@ internal ObjectConstructor ParameterizedCreator /// /// Gets or sets the extension data setter. /// - public ExtensionDataSetter ExtensionDataSetter { get; set; } + public ExtensionDataSetter? ExtensionDataSetter { get; set; } /// /// Gets or sets the extension data getter. /// - public ExtensionDataGetter ExtensionDataGetter { get; set; } + public ExtensionDataGetter? ExtensionDataGetter { get; set; } /// /// Gets or sets the extension data value type. /// - public Type ExtensionDataValueType + public Type? ExtensionDataValueType { get => _extensionDataValueType; set @@ -128,14 +137,14 @@ public Type ExtensionDataValueType /// Gets or sets the extension data name resolver. /// /// The extension data name resolver. - public Func ExtensionDataNameResolver { get; set; } + public Func? ExtensionDataNameResolver { get; set; } internal bool ExtensionDataIsJToken; private bool? _hasRequiredOrDefaultValueProperties; - private ObjectConstructor _overrideCreator; - private ObjectConstructor _parameterizedCreator; - private JsonPropertyCollection _creatorParameters; - private Type _extensionDataValueType; + private ObjectConstructor? _overrideCreator; + private ObjectConstructor? _parameterizedCreator; + private JsonPropertyCollection? _creatorParameters; + private Type? _extensionDataValueType; internal bool HasRequiredOrDefaultValueProperties { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs index b8dc0abe6..21960dd35 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonProperty.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonProperty.cs index f4ffd523f..c99423c2e 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonProperty.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonProperty.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -28,6 +31,7 @@ #endregion using System; +using System.Diagnostics; using System.Reflection; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; @@ -45,20 +49,20 @@ internal class JsonProperty internal Required? _required; internal bool _hasExplicitDefaultValue; - private object _defaultValue; + private object? _defaultValue; private bool _hasGeneratedDefaultValue; - private string _propertyName; + private string? _propertyName; internal bool _skipPropertyNameEscape; - private Type _propertyType; + private Type? _propertyType; // use to cache contract during deserialization - internal JsonContract PropertyContract { get; set; } + internal JsonContract? PropertyContract { get; set; } /// /// Gets or sets the name of the property. /// /// The name of the property. - public string PropertyName + public string? PropertyName { get => _propertyName; set @@ -72,7 +76,7 @@ public string PropertyName /// Gets or sets the type that declared this property. /// /// The type that declared this property. - public Type DeclaringType { get; set; } + public Type? DeclaringType { get; set; } /// /// Gets or sets the order of serialization of a member. @@ -84,25 +88,25 @@ public string PropertyName /// Gets or sets the name of the underlying member or parameter. /// /// The name of the underlying member or parameter. - public string UnderlyingName { get; set; } + public string? UnderlyingName { get; set; } /// /// Gets the that will get and set the during serialization. /// /// The that will get and set the during serialization. - public IValueProvider ValueProvider { get; set; } + public IValueProvider? ValueProvider { get; set; } /// /// Gets or sets the for this property. /// /// The for this property. - public IAttributeProvider AttributeProvider { get; set; } + public IAttributeProvider? AttributeProvider { get; set; } /// /// Gets or sets the type of the property. /// /// The type of the property. - public Type PropertyType + public Type? PropertyType { get => _propertyType; set @@ -120,14 +124,14 @@ public Type PropertyType /// If set this converter takes precedence over the contract converter for the property type. /// /// The converter. - public JsonConverter Converter { get; set; } + public JsonConverter? Converter { get; set; } /// /// Gets or sets the member converter. /// /// The member converter. [Obsolete("MemberConverter is obsolete. Use Converter instead.")] - public JsonConverter MemberConverter + public JsonConverter? MemberConverter { get => Converter; set => Converter = value; @@ -161,7 +165,7 @@ public JsonConverter MemberConverter /// Gets the default value. /// /// The default value. - public object DefaultValue + public object? DefaultValue { get { @@ -179,7 +183,7 @@ public object DefaultValue } } - internal object GetResolvedDefaultValue() + internal object? GetResolvedDefaultValue() { if (_propertyType == null) { @@ -188,7 +192,7 @@ internal object GetResolvedDefaultValue() if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue) { - _defaultValue = ReflectionUtils.GetDefaultValue(PropertyType); + _defaultValue = ReflectionUtils.GetDefaultValue(_propertyType); _hasGeneratedDefaultValue = true; } @@ -205,6 +209,11 @@ public Required Required set => _required = value; } + /// + /// Gets a value indicating whether has a value specified. + /// + public bool IsRequiredSpecified => _required != null; + /// /// Gets or sets a value indicating whether this property preserves object references. /// @@ -247,25 +256,25 @@ public Required Required /// Gets or sets a predicate used to determine whether the property should be serialized. /// /// A predicate used to determine whether the property should be serialized. - public Predicate ShouldSerialize { get; set; } + public Predicate? ShouldSerialize { get; set; } /// /// Gets or sets a predicate used to determine whether the property should be deserialized. /// /// A predicate used to determine whether the property should be deserialized. - public Predicate ShouldDeserialize { get; set; } + public Predicate? ShouldDeserialize { get; set; } /// /// Gets or sets a predicate used to determine whether the property should be serialized. /// /// A predicate used to determine whether the property should be serialized. - public Predicate GetIsSpecified { get; set; } + public Predicate? GetIsSpecified { get; set; } /// /// Gets or sets an action used to set whether the property has been deserialized. /// /// An action used to set whether the property has been deserialized. - public Action SetIsSpecified { get; set; } + public Action? SetIsSpecified { get; set; } /// /// Returns a that represents this instance. @@ -275,14 +284,14 @@ public Required Required /// public override string ToString() { - return PropertyName; + return PropertyName ?? string.Empty; } /// /// Gets or sets the converter used when serializing the property's collection items. /// /// The collection's items converter. - public JsonConverter ItemConverter { get; set; } + public JsonConverter? ItemConverter { get; set; } /// /// Gets or sets whether this property's collection items are serialized as a reference. @@ -304,13 +313,16 @@ public override string ToString() internal void WritePropertyName(JsonWriter writer) { + string? propertyName = PropertyName; + MiscellaneousUtils.Assert(propertyName != null); + if (_skipPropertyNameEscape) { - writer.WritePropertyName(PropertyName, false); + writer.WritePropertyName(propertyName, false); } else { - writer.WritePropertyName(PropertyName); + writer.WritePropertyName(propertyName); } } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index d3822d553..19524955b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -33,6 +36,9 @@ using System.Collections.ObjectModel; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Globalization; +using System.Runtime.CompilerServices; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization { @@ -65,7 +71,7 @@ public JsonPropertyCollection(Type type) /// The key for the specified element. protected override string GetKeyForItem(JsonProperty item) { - return item.PropertyName; + return item.PropertyName!; } /// @@ -74,6 +80,8 @@ protected override string GetKeyForItem(JsonProperty item) /// The property to add to the collection. public void AddProperty(JsonProperty property) { + MiscellaneousUtils.Assert(property.PropertyName != null); + if (Contains(property.PropertyName)) { // don't overwrite existing property with ignored property @@ -133,9 +141,9 @@ public void AddProperty(JsonProperty property) /// /// Name of the property. /// A matching property if found. - public JsonProperty GetClosestMatchProperty(string propertyName) + public JsonProperty? GetClosestMatchProperty(string propertyName) { - JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal); + JsonProperty? property = GetProperty(propertyName, StringComparison.Ordinal); if (property == null) { property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase); @@ -144,8 +152,11 @@ public JsonProperty GetClosestMatchProperty(string propertyName) return property; } -#if !NETCOREAPP - private bool TryGetValue(string key, out JsonProperty item) +#if NETCOREAPP + private new bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) +#else + private bool TryGetValue(string key, [NotNullWhen(true)]out JsonProperty? item) +#endif { if (Dictionary == null) { @@ -155,7 +166,6 @@ private bool TryGetValue(string key, out JsonProperty item) return Dictionary.TryGetValue(key, out item); } -#endif /// /// Gets a property by property name. @@ -163,12 +173,12 @@ private bool TryGetValue(string key, out JsonProperty item) /// The name of the property to get. /// Type property name string comparison. /// A matching property if found. - public JsonProperty GetProperty(string propertyName, StringComparison comparisonType) + public JsonProperty? GetProperty(string propertyName, StringComparison comparisonType) { // KeyedCollection has an ordinal comparer if (comparisonType == StringComparison.Ordinal) { - if (TryGetValue(propertyName, out JsonProperty property)) + if (TryGetValue(propertyName, out JsonProperty? property)) { return property; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs index 08bba0902..4316165fa 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -51,12 +54,12 @@ int IEqualityComparer.GetHashCode(object obj) } } - private ErrorContext _currentErrorContext; - private BidirectionalDictionary _mappings; + private ErrorContext? _currentErrorContext; + private BidirectionalDictionary? _mappings; internal readonly JsonSerializer Serializer; - internal readonly ITraceWriter TraceWriter; - protected JsonSerializerProxy InternalSerializer; + internal readonly ITraceWriter? TraceWriter; + protected JsonSerializerProxy? InternalSerializer; protected JsonSerializerInternalBase(JsonSerializer serializer) { @@ -85,7 +88,7 @@ internal BidirectionalDictionary DefaultReferenceMappings } } - protected NullValueHandling ResolvedNullValueHandling(JsonObjectContract containerContract, JsonProperty property) + protected NullValueHandling ResolvedNullValueHandling(JsonObjectContract? containerContract, JsonProperty property) { NullValueHandling resolvedNullValueHandling = property.NullValueHandling @@ -95,7 +98,7 @@ protected NullValueHandling ResolvedNullValueHandling(JsonObjectContract contain return resolvedNullValueHandling; } - private ErrorContext GetErrorContext(object currentObject, object member, string path, Exception error) + private ErrorContext GetErrorContext(object? currentObject, object? member, string path, Exception error) { if (_currentErrorContext == null) { @@ -120,7 +123,7 @@ protected void ClearErrorContext() _currentErrorContext = null; } - protected bool IsErrorHandled(object currentObject, JsonContract contract, object keyValue, IJsonLineInfo lineInfo, string path, Exception ex) + protected bool IsErrorHandled(object? currentObject, JsonContract? contract, object? keyValue, IJsonLineInfo? lineInfo, string path, Exception ex) { ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 3251a7746..e0f653d68 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,11 +47,12 @@ using System.Runtime.Serialization; using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization @@ -97,10 +101,10 @@ public void Populate(JsonReader reader, object target) { reader.ReadAndAssert(); - string id = null; + string? id = null; if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName - && string.Equals(reader.Value.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) + && string.Equals(reader.Value!.ToString(), JsonTypeReflector.IdPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); id = reader.Value?.ToString(); @@ -127,28 +131,33 @@ public void Populate(JsonReader reader, object target) } } - private JsonContract GetContractSafe(Type type) + private JsonContract? GetContractSafe(Type? type) { if (type == null) { return null; } + return GetContract(type); + } + + private JsonContract GetContract(Type type) + { return Serializer._contractResolver.ResolveContract(type); } - public object Deserialize(JsonReader reader, Type objectType, bool checkAdditionalContent) + public object? Deserialize(JsonReader reader, Type? objectType, bool checkAdditionalContent) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } - JsonContract contract = GetContractSafe(objectType); + JsonContract? contract = GetContractSafe(objectType); try { - JsonConverter converter = GetConverter(contract, null, null, null); + JsonConverter? converter = GetConverter(contract, null, null, null); if (reader.TokenType == JsonToken.None && !reader.ReadForType(contract, converter != null)) { @@ -160,11 +169,11 @@ public object Deserialize(JsonReader reader, Type objectType, bool checkAddition return null; } - object deserializedValue; + object? deserializedValue; if (converter != null && converter.CanRead) { - deserializedValue = DeserializeConvertable(converter, reader, objectType, null); + deserializedValue = DeserializeConvertable(converter, reader, objectType!, null); } else { @@ -212,7 +221,7 @@ private JsonSerializerProxy GetInternalSerializer() return InternalSerializer; } - private JToken CreateJToken(JsonReader reader, JsonContract contract) + private JToken? CreateJToken(JsonReader reader, JsonContract? contract) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); @@ -229,13 +238,22 @@ private JToken CreateJToken(JsonReader reader, JsonContract contract) } } - JToken token; + JToken? token; using (JTokenWriter writer = new JTokenWriter()) { writer.WriteToken(reader); token = writer.Token; } + if (contract != null && token != null) + { + if (!contract.UnderlyingType.IsAssignableFrom(token.GetType())) + { + throw JsonSerializationException.Create(reader, "Deserialized JSON type '{0}' is not compatible with expected type '{1}'." + .FormatWith(CultureInfo.InvariantCulture, token.GetType().FullName, contract.UnderlyingType.FullName)); + } + } + return token; } @@ -252,7 +270,7 @@ private JToken CreateJObject(JsonReader reader) { if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = (string)reader.Value; + string propertyName = (string)reader.Value!; if (!reader.ReadAndMoveToContent()) { break; @@ -273,7 +291,7 @@ private JToken CreateJObject(JsonReader reader) else { writer.WriteEndObject(); - return writer.Token; + return writer.Token!; } } while (reader.Read()); @@ -281,7 +299,7 @@ private JToken CreateJObject(JsonReader reader) } } - private object CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) + private object? CreateValueInternal(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) { if (contract != null && contract.ContractType == JsonContractType.Linq) { @@ -305,7 +323,7 @@ private object CreateValueInternal(JsonReader reader, Type objectType, JsonContr case JsonToken.Bytes: return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.String: - string s = (string)reader.Value; + string s = (string)reader.Value!; // string that needs to be returned as a byte array should be base 64 decoded if (objectType == typeof(byte[])) @@ -321,7 +339,7 @@ private object CreateValueInternal(JsonReader reader, Type objectType, JsonContr return EnsureType(reader, s, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.StartConstructor: - string constructorName = reader.Value.ToString(); + string constructorName = reader.Value!.ToString(); return EnsureType(reader, constructorName, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Null: @@ -335,7 +353,7 @@ private object CreateValueInternal(JsonReader reader, Type objectType, JsonContr return EnsureType(reader, reader.Value, CultureInfo.InvariantCulture, contract, objectType); case JsonToken.Raw: - return new JRaw((string)reader.Value); + return new JRaw((string?)reader.Value); case JsonToken.Comment: // ignore break; @@ -347,9 +365,9 @@ private object CreateValueInternal(JsonReader reader, Type objectType, JsonContr throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } - private static bool CoerceEmptyStringToNull(Type objectType, JsonContract contract, string s) + private static bool CoerceEmptyStringToNull(Type? objectType, JsonContract? contract, string s) { - return string.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; + return StringUtils.IsNullOrEmpty(s) && objectType != null && objectType != typeof(string) && objectType != typeof(object) && contract != null && contract.IsNullable; } internal string GetExpectedDescription(JsonContract contract) @@ -376,9 +394,9 @@ internal string GetExpectedDescription(JsonContract contract) } } - private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter, JsonContainerContract containerContract, JsonProperty containerProperty) + private JsonConverter? GetConverter(JsonContract? contract, JsonConverter? memberConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty) { - JsonConverter converter = null; + JsonConverter? converter = null; if (memberConverter != null) { // member attribute converter @@ -394,13 +412,12 @@ private JsonConverter GetConverter(JsonContract contract, JsonConverter memberCo } else if (contract != null) { - JsonConverter matchingConverter; if (contract.Converter != null) { // class attribute converter converter = contract.Converter; } - else if ((matchingConverter = Serializer.GetMatchingConverter(contract.UnderlyingType)) != null) + else if (Serializer.GetMatchingConverter(contract.UnderlyingType) is JsonConverter matchingConverter) { // passed in converters converter = matchingConverter; @@ -414,10 +431,10 @@ private JsonConverter GetConverter(JsonContract contract, JsonConverter memberCo return converter; } - private object CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) + private object? CreateObject(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) { - string id; - Type resolvedObjectType = objectType; + string? id; + Type? resolvedObjectType = objectType; if (Serializer.MetadataPropertyHandling == MetadataPropertyHandling.Ignore) { @@ -444,7 +461,7 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con reader = tokenReader; } - if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object newValue, out id)) + if (ReadMetadataPropertiesToken(tokenReader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object? newValue, out id)) { return newValue; } @@ -452,7 +469,7 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con else { reader.ReadAndAssert(); - if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object newValue, out id)) + if (ReadMetadataProperties(reader, ref resolvedObjectType, ref contract, member, containerContract, containerMember, existingValue, out object? newValue, out id)) { return newValue; } @@ -463,6 +480,9 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con return CreateJObject(reader); } + MiscellaneousUtils.Assert(resolvedObjectType != null); + MiscellaneousUtils.Assert(contract != null); + switch (contract.ContractType) { case JsonContractType.Object: @@ -494,7 +514,7 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con // if the content is inside $value then read past it if (Serializer.MetadataPropertyHandling != MetadataPropertyHandling.Ignore && reader.TokenType == JsonToken.PropertyName - && string.Equals(reader.Value.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) + && string.Equals(reader.Value!.ToString(), JsonTypeReflector.ValuePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); @@ -505,7 +525,7 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con throw JsonSerializationException.Create(reader, "Unexpected token when deserializing primitive value: " + reader.TokenType); } - object value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); + object? value = CreateValueInternal(reader, resolvedObjectType, primitiveContract, member, null, null, existingValue); reader.ReadAndAssert(); return value; @@ -548,7 +568,7 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con if (createdFromNonDefaultCreator) { - ObjectConstructor creator = dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator; + ObjectConstructor creator = (dictionaryContract.OverrideCreator ?? dictionaryContract.ParameterizedCreator)!; return creator(dictionary); } @@ -557,8 +577,8 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con return wrappedDictionary.UnderlyingDictionary; } - targetDictionary = dictionary; - } + targetDictionary = dictionary; + } else { targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper || !(existingValue is IDictionary) ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); @@ -585,38 +605,29 @@ private object CreateObject(JsonReader reader, Type objectType, JsonContract con throw JsonSerializationException.Create(reader, message); } - private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) + private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) { id = null; newValue = null; if (reader.TokenType == JsonToken.StartObject) { - JObject current = (JObject)reader.CurrentToken; + JObject current = (JObject)reader.CurrentToken!; - JToken refToken = current[JsonTypeReflector.RefPropertyName]; - if (refToken != null) + JProperty? refProperty = current.Property(JsonTypeReflector.RefPropertyName, StringComparison.Ordinal); + if (refProperty != null) { + JToken refToken = refProperty.Value; if (refToken.Type != JTokenType.String && refToken.Type != JTokenType.Null) { throw JsonSerializationException.Create(refToken, refToken.Path, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); } - JToken property = refToken.Parent; - JToken additionalContent = null; - if (property.Next != null) - { - additionalContent = property.Next; - } - else if (property.Previous != null) - { - additionalContent = property.Previous; - } - - string reference = (string)refToken; + string? reference = (string?)refProperty; if (reference != null) { + JToken? additionalContent = refProperty.Next ?? refProperty.Previous; if (additionalContent != null) { throw JsonSerializationException.Create(additionalContent, additionalContent.Path, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName), null); @@ -633,15 +644,15 @@ private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectTyp return true; } } - JToken typeToken = current[JsonTypeReflector.TypePropertyName]; + JToken? typeToken = current[JsonTypeReflector.TypePropertyName]; if (typeToken != null) { - string qualifiedTypeName = (string)typeToken; + string? qualifiedTypeName = (string?)typeToken; JsonReader typeTokenReader = typeToken.CreateReader(); typeTokenReader.ReadAndAssert(); - ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); + ResolveTypeName(typeTokenReader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName!); - JToken valueToken = current[JsonTypeReflector.ValuePropertyName]; + JToken? valueToken = current[JsonTypeReflector.ValuePropertyName]; if (valueToken != null) { while (true) @@ -649,7 +660,7 @@ private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectTyp reader.ReadAndAssert(); if (reader.TokenType == JsonToken.PropertyName) { - if ((string)reader.Value == JsonTypeReflector.ValuePropertyName) + if ((string)reader.Value! == JsonTypeReflector.ValuePropertyName) { return false; } @@ -660,12 +671,12 @@ private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectTyp } } } - JToken idToken = current[JsonTypeReflector.IdPropertyName]; + JToken? idToken = current[JsonTypeReflector.IdPropertyName]; if (idToken != null) { - id = (string)idToken; + id = (string?)idToken; } - JToken valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; + JToken? valuesToken = current[JsonTypeReflector.ArrayValuesPropertyName]; if (valuesToken != null) { JsonReader listReader = valuesToken.CreateReader(); @@ -681,14 +692,14 @@ private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type objectTyp return false; } - private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue, out object newValue, out string id) + private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) { id = null; newValue = null; if (reader.TokenType == JsonToken.PropertyName) { - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (propertyName.Length > 0 && propertyName[0] == '$') { @@ -698,7 +709,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref do { - propertyName = reader.Value.ToString(); + propertyName = reader.Value!.ToString(); if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { @@ -708,7 +719,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); } - string reference = reader.Value?.ToString(); + string? reference = reader.Value?.ToString(); reader.ReadAndAssert(); @@ -723,7 +734,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { - TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue.GetType())), null); + TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Resolved object reference '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, reference, newValue!.GetType())), null); } return true; @@ -736,7 +747,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - string qualifiedTypeName = reader.Value.ToString(); + string qualifiedTypeName = reader.Value!.ToString(); ResolveTypeName(reader, ref objectType, ref contract, member, containerContract, containerMember, qualifiedTypeName); @@ -756,7 +767,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref else if (string.Equals(propertyName, JsonTypeReflector.ArrayValuesPropertyName, StringComparison.Ordinal)) { reader.ReadAndAssert(); - object list = CreateList(reader, objectType, contract, member, existingValue, id); + object? list = CreateList(reader, objectType, contract, member, existingValue, id); reader.ReadAndAssert(); newValue = list; return true; @@ -771,7 +782,7 @@ private bool ReadMetadataProperties(JsonReader reader, ref Type objectType, ref return false; } - private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, string qualifiedTypeName) + private void ResolveTypeName(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, string qualifiedTypeName) { TypeNameHandling resolvedTypeNameHandling = member?.TypeNameHandling @@ -781,7 +792,7 @@ private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonCon if (resolvedTypeNameHandling != TypeNameHandling.None) { - StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName); + StructMultiKey typeNameKey = ReflectionUtils.SplitFullyQualifiedTypeName(qualifiedTypeName); Type specifiedType; try @@ -813,7 +824,7 @@ private void ResolveTypeName(JsonReader reader, ref Type objectType, ref JsonCon } objectType = specifiedType; - contract = GetContractSafe(specifiedType); + contract = GetContract(specifiedType); } } @@ -836,15 +847,18 @@ private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType return arrayContract; } - private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string id) + private object? CreateList(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, object? existingValue, string? id) { - object value; + object? value; if (HasNoDefinedType(contract)) { return CreateJToken(reader, contract); } + MiscellaneousUtils.Assert(objectType != null); + MiscellaneousUtils.Assert(contract != null); + JsonArrayContract arrayContract = EnsureArrayContract(reader, objectType, contract); if (existingValue == null) @@ -887,7 +901,7 @@ private object CreateList(JsonReader reader, Type objectType, JsonContract contr { if (arrayContract.IsMultidimensionalArray) { - list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType, contract.CreatedType.GetArrayRank()); + list = CollectionUtils.ToMultidimensionalArray(list, arrayContract.CollectionItemType!, contract.CreatedType.GetArrayRank()); } else if (arrayContract.IsArray) { @@ -897,7 +911,7 @@ private object CreateList(JsonReader reader, Type objectType, JsonContract contr } else { - ObjectConstructor creator = arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator; + ObjectConstructor creator = (arrayContract.OverrideCreator ?? arrayContract.ParameterizedCreator)!; return creator(list); } @@ -922,7 +936,7 @@ private object CreateList(JsonReader reader, Type objectType, JsonContract contr return value; } - private bool HasNoDefinedType(JsonContract contract) + private bool HasNoDefinedType(JsonContract? contract) { return (contract == null || contract.UnderlyingType == typeof(object) || contract.ContractType == JsonContractType.Linq #if HAVE_DYNAMIC @@ -931,14 +945,15 @@ private bool HasNoDefinedType(JsonContract contract) ); } - private object EnsureType(JsonReader reader, object value, CultureInfo culture, JsonContract contract, Type targetType) + private object? EnsureType(JsonReader reader, object? value, CultureInfo culture, JsonContract? contract, Type? targetType) { if (targetType == null) { return value; } - Type valueType = ReflectionUtils.GetObjectType(value); + MiscellaneousUtils.Assert(contract != null); + Type? valueType = ReflectionUtils.GetObjectType(value); // type of value and type of target don't match // attempt to convert value's type to target's type @@ -959,7 +974,11 @@ private object EnsureType(JsonReader reader, object value, CultureInfo culture, { if (value is string s) { - return EnumUtils.ParseEnum(contract.NonNullableUnderlyingType, null, s, false); + return EnumUtils.ParseEnum( + contract.NonNullableUnderlyingType, + null, + s, + false); } if (ConvertUtils.IsInteger(primitiveContract.TypeCode)) { @@ -997,7 +1016,7 @@ private object EnsureType(JsonReader reader, object value, CultureInfo culture, return value; } - private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, object target) + private bool SetPropertyValue(JsonProperty property, JsonConverter? propertyConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty, JsonReader reader, object target) { bool skipSettingProperty = CalculatePropertyDetails( property, @@ -1007,8 +1026,8 @@ private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConve reader, target, out bool useExistingValue, - out object currentValue, - out JsonContract propertyContract, + out object? currentValue, + out JsonContract? propertyContract, out bool gottenCurrentValue, out bool ignoredValue); @@ -1024,16 +1043,16 @@ private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConve return false; } - object value; + object? value; if (propertyConverter != null && propertyConverter.CanRead) { - if (!gottenCurrentValue && target != null && property.Readable) + if (!gottenCurrentValue && property.Readable) { - currentValue = property.ValueProvider.GetValue(target); + currentValue = property.ValueProvider!.GetValue(target); } - value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, currentValue); + value = DeserializeConvertable(propertyConverter, reader, property.PropertyType!, currentValue); } else { @@ -1046,7 +1065,7 @@ private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConve if ((!useExistingValue || value != currentValue) && ShouldSetPropertyValue(property, containerContract as JsonObjectContract, value)) { - property.ValueProvider.SetValue(target, value); + property.ValueProvider!.SetValue(target, value); if (property.SetIsSpecified != null) { @@ -1067,14 +1086,14 @@ private bool SetPropertyValue(JsonProperty property, JsonConverter propertyConve private bool CalculatePropertyDetails( JsonProperty property, - ref JsonConverter propertyConverter, - JsonContainerContract containerContract, - JsonProperty containerProperty, + ref JsonConverter? propertyConverter, + JsonContainerContract? containerContract, + JsonProperty? containerProperty, JsonReader reader, object target, out bool useExistingValue, - out object currentValue, - out JsonContract propertyContract, + out object? currentValue, + out JsonContract? propertyContract, out bool gottenCurrentValue, out bool ignoredValue) { @@ -1103,12 +1122,12 @@ private bool CalculatePropertyDetails( && (tokenType == JsonToken.StartArray || tokenType == JsonToken.StartObject || propertyConverter != null) && property.Readable) { - currentValue = property.ValueProvider.GetValue(target); + currentValue = property.ValueProvider!.GetValue(target); gottenCurrentValue = true; if (currentValue != null) { - propertyContract = GetContractSafe(currentValue.GetType()); + propertyContract = GetContract(currentValue.GetType()); useExistingValue = (!propertyContract.IsReadOnlyOrFixedSize && !propertyContract.UnderlyingType.IsValueType()); } @@ -1147,7 +1166,7 @@ private bool CalculatePropertyDetails( } else { - propertyContract = GetContractSafe(currentValue.GetType()); + propertyContract = GetContract(currentValue.GetType()); if (propertyContract != property.PropertyContract) { @@ -1180,7 +1199,7 @@ private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) return ((value & flag) == flag); } - private bool ShouldSetPropertyValue(JsonProperty property, JsonObjectContract contract, object value) + private bool ShouldSetPropertyValue(JsonProperty property, JsonObjectContract? contract, object? value) { if (value == null && ResolvedNullValueHandling(contract, property) == NullValueHandling.Ignore) { @@ -1338,7 +1357,7 @@ private void OnDeserialized(JsonReader reader, JsonContract contract, object val contract.InvokeOnDeserialized(value, Serializer._context); } - private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty containerProperty, string id) + private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty? containerProperty, string? id) { object underlyingDictionary = dictionary is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : dictionary; @@ -1361,7 +1380,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso contract.ItemContract = GetContractSafe(contract.DictionaryValueType); } - JsonConverter dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); + JsonConverter? dictionaryValueConverter = contract.ItemConverter ?? GetConverter(contract.ItemContract, null, contract, containerProperty); PrimitiveTypeCode keyTypeCode = (contract.KeyContract is JsonPrimitiveContract keyContract) ? keyContract.TypeCode : PrimitiveTypeCode.Empty; bool finished = false; @@ -1370,7 +1389,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso switch (reader.TokenType) { case JsonToken.PropertyName: - object keyValue = reader.Value; + object keyValue = reader.Value!; if (CheckPropertyName(reader, keyValue.ToString())) { continue; @@ -1388,7 +1407,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso { keyValue = DateTimeUtils.TryParseDateTime(keyValue.ToString(), reader.DateTimeZoneHandling, reader.DateFormatString, reader.Culture, out DateTime dt) ? dt - : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; } #if HAVE_DATE_TIME_OFFSET @@ -1397,12 +1416,14 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso { keyValue = DateTimeUtils.TryParseDateTimeOffset(keyValue.ToString(), reader.DateFormatString, reader.Culture, out DateTimeOffset dt) ? dt - : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; } #endif default: - keyValue = EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType); + keyValue = contract.KeyContract != null && contract.KeyContract.IsEnum + ? EnumUtils.ParseEnum(contract.KeyContract.NonNullableUnderlyingType, (Serializer._contractResolver as DefaultContractResolver)?.NamingStrategy, keyValue.ToString(), false) + : EnsureType(reader, keyValue, CultureInfo.InvariantCulture, contract.KeyContract, contract.DictionaryKeyType)!; break; } } @@ -1416,10 +1437,10 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } - object itemValue; + object? itemValue; if (dictionaryValueConverter != null && dictionaryValueConverter.CanRead) { - itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType, null); + itemValue = DeserializeConvertable(dictionaryValueConverter, reader, contract.DictionaryValueType!, null); } else { @@ -1459,7 +1480,7 @@ private object PopulateDictionary(IDictionary dictionary, JsonReader reader, Jso return underlyingDictionary; } - private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) + private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) { int rank = contract.UnderlyingType.GetArrayRank(); @@ -1470,8 +1491,8 @@ private object PopulateMultidimensionalArray(IList list, JsonReader reader, Json OnDeserializing(reader, contract, list); - JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType); - JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); + JsonContract? collectionItemContract = GetContractSafe(contract.CollectionItemType); + JsonConverter? collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty); int? previousErrorIndex = null; Stack listStack = new Stack(); @@ -1499,11 +1520,11 @@ private object PopulateMultidimensionalArray(IList list, JsonReader reader, Json case JsonToken.Comment: break; default: - object value; + object? value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { - value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null); + value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType!, null); } else { @@ -1590,7 +1611,7 @@ private object PopulateMultidimensionalArray(IList list, JsonReader reader, Json return list; } - private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object currentObject, string message) + private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contract, object? currentObject, string message) { try { @@ -1609,8 +1630,9 @@ private void ThrowUnexpectedEndException(JsonReader reader, JsonContract contrac } } - private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id) + private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) { +#pragma warning disable CS8600, CS8602, CS8603, CS8604 object underlyingList = list is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : list; if (id != null) @@ -1634,7 +1656,7 @@ private object PopulateList(IList list, JsonReader reader, JsonArrayContract con contract.ItemContract = GetContractSafe(contract.CollectionItemType); } - JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); + JsonConverter? collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty); int? previousErrorIndex = null; @@ -1653,7 +1675,7 @@ private object PopulateList(IList list, JsonReader reader, JsonArrayContract con case JsonToken.Comment: break; default: - object value; + object? value; if (collectionItemConverter != null && collectionItemConverter.CanRead) { @@ -1706,10 +1728,11 @@ private object PopulateList(IList list, JsonReader reader, JsonArrayContract con OnDeserialized(reader, contract, underlyingList); return underlyingList; + } #if HAVE_BINARY_SERIALIZATION - private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty member, string id) + private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty? member, string? id) { Type objectType = contract.UnderlyingType; @@ -1735,7 +1758,7 @@ private object CreateISerializable(JsonReader reader, JsonISerializableContract switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value.ToString(); + string memberName = reader.Value!.ToString(); if (!reader.Read()) { throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); @@ -1781,15 +1804,15 @@ private object CreateISerializable(JsonReader reader, JsonISerializableContract return createdObject; } - internal object CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty member) + internal object? CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty? member) { - JsonContract itemContract = GetContractSafe(type); - JsonConverter itemConverter = GetConverter(itemContract, null, contract, member); + JsonContract? itemContract = GetContractSafe(type); + JsonConverter? itemConverter = GetConverter(itemContract, null, contract, member); JsonReader tokenReader = token.CreateReader(); tokenReader.ReadAndAssert(); // Move to first token - object result; + object? result; if (itemConverter != null && itemConverter.CanRead) { result = DeserializeConvertable(itemConverter, tokenReader, type, null); @@ -1804,7 +1827,7 @@ internal object CreateISerializableItem(JToken token, Type type, JsonISerializab #endif #if HAVE_DYNAMIC - private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty member, string id) + private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty? member, string? id) { IDynamicMetaObjectProvider newObject; @@ -1838,7 +1861,7 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value.ToString(); + string memberName = reader.Value!.ToString(); try { @@ -1848,7 +1871,7 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js } // first attempt to find a settable property, otherwise fall back to a dynamic set without type - JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); + JsonProperty? property = contract.Properties.GetClosestMatchProperty(memberName); if (property != null && property.Writable && !property.Ignored) { @@ -1857,7 +1880,7 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js property.PropertyContract = GetContractSafe(property.PropertyType); } - JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, null, null); + JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, null, null); if (!SetPropertyValue(property, propertyConverter, null, member, reader, newObject)) { @@ -1866,15 +1889,15 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js } else { - Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider); + Type t = (JsonTokenUtils.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType! : typeof(IDynamicMetaObjectProvider); - JsonContract dynamicMemberContract = GetContractSafe(t); - JsonConverter dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); + JsonContract? dynamicMemberContract = GetContractSafe(t); + JsonConverter? dynamicMemberConverter = GetConverter(dynamicMemberContract, null, null, member); - object value; + object? value; if (dynamicMemberConverter != null && dynamicMemberConverter.CanRead) { - value = DeserializeConvertable(dynamicMemberConverter, reader, t, null); + value = DeserializeConvertable(dynamicMemberConverter!, reader, t, null); } else { @@ -1917,15 +1940,20 @@ private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, Js internal class CreatorPropertyContext { - public string Name; - public JsonProperty Property; - public JsonProperty ConstructorProperty; + public readonly string Name; + public JsonProperty? Property; + public JsonProperty? ConstructorProperty; public PropertyPresence? Presence; - public object Value; + public object? Value; public bool Used; + + public CreatorPropertyContext(string name) + { + Name = name; + } } - private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor creator, string id) + private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty? containerProperty, ObjectConstructor creator, string? id) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); @@ -1953,10 +1981,9 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj { if (propertyContexts.All(p => p.Property != property)) { - propertyContexts.Add(new CreatorPropertyContext + propertyContexts.Add(new CreatorPropertyContext(property.PropertyName!) { Property = property, - Name = property.PropertyName, Presence = PropertyPresence.None }); } @@ -1964,7 +1991,7 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj } } - object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; + object?[] creatorParameterValues = new object?[contract.CreatorParameters.Count]; foreach (CreatorPropertyContext context in propertyContexts) { @@ -1973,7 +2000,7 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj { if (context.Property != null && context.Presence == null) { - object v = context.Value; + object? v = context.Value; PropertyPresence propertyPresence; if (v == null) { @@ -1994,10 +2021,10 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj } } - JsonProperty constructorProperty = context.ConstructorProperty; + JsonProperty? constructorProperty = context.ConstructorProperty; if (constructorProperty == null && context.Property != null) { - constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName); + constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName!, context.Property.UnderlyingName!); } if (constructorProperty != null && !constructorProperty.Ignored) @@ -2019,7 +2046,7 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj reader, constructorProperty.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, - constructorProperty.PropertyContract, + constructorProperty.PropertyContract!, constructorProperty.PropertyType); } } @@ -2053,17 +2080,17 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj } JsonProperty property = context.Property; - object value = context.Value; + object? value = context.Value; if (ShouldSetPropertyValue(property, contract, value)) { - property.ValueProvider.SetValue(createdObject, value); + property.ValueProvider!.SetValue(createdObject, value); context.Used = true; } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties - JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); + JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType!); if (propertyContract.ContractType == JsonContractType.Array) { @@ -2071,15 +2098,22 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj if (propertyArrayContract.CanDeserialize && !propertyArrayContract.IsReadOnlyOrFixedSize) { - object createdObjectCollection = property.ValueProvider.GetValue(createdObject); + object? createdObjectCollection = property.ValueProvider!.GetValue(createdObject); if (createdObjectCollection != null) { + propertyArrayContract = (JsonArrayContract)GetContract(createdObjectCollection.GetType()); + IList createdObjectCollectionWrapper = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(createdObjectCollection) : (IList)createdObjectCollection; - IList newValues = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(value) : (IList)value; - foreach (object newValue in newValues) + // Don't attempt to populate array/read-only list + if (!createdObjectCollectionWrapper.IsFixedSize) { - createdObjectCollectionWrapper.Add(newValue); + IList newValues = (propertyArrayContract.ShouldCreateWrapper) ? propertyArrayContract.CreateWrapper(value) : (IList)value; + + foreach (object newValue in newValues) + { + createdObjectCollectionWrapper.Add(newValue); + } } } } @@ -2090,7 +2124,7 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj if (!dictionaryContract.IsReadOnlyOrFixedSize) { - object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); + object? createdObjectDictionary = property.ValueProvider!.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; @@ -2153,14 +2187,14 @@ private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObj return createdObject; } - private object DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object existingValue) + private object? DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object? existingValue) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Started deserializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, objectType, converter.GetType())), null); } - object value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); + object? value = converter.ReadJson(reader, objectType, existingValue, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { @@ -2170,7 +2204,7 @@ private object DeserializeConvertable(JsonConverter converter, JsonReader reader return value; } - private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty containerProperty, JsonReader reader, Type objectType) + private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty? containerProperty, JsonReader reader, Type objectType) { List propertyValues = new List(); bool exit = false; @@ -2179,41 +2213,43 @@ private List ResolvePropertyAndCreatorValues(JsonObjectC switch (reader.TokenType) { case JsonToken.PropertyName: - string memberName = reader.Value.ToString(); + string memberName = reader.Value!.ToString(); - CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext + CreatorPropertyContext creatorPropertyContext = new CreatorPropertyContext(memberName) { - Name = reader.Value.ToString(), ConstructorProperty = contract.CreatorParameters.GetClosestMatchProperty(memberName), Property = contract.Properties.GetClosestMatchProperty(memberName) }; propertyValues.Add(creatorPropertyContext); - JsonProperty property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; - if (property != null && !property.Ignored) + JsonProperty? property = creatorPropertyContext.ConstructorProperty ?? creatorPropertyContext.Property; + if (property != null) { - if (property.PropertyContract == null) + if (!property.Ignored) { - property.PropertyContract = GetContractSafe(property.PropertyType); - } + if (property.PropertyContract == null) + { + property.PropertyContract = GetContractSafe(property.PropertyType); + } - JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, containerProperty); + JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, containerProperty); - if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) - { - throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); - } + if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) + { + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + } - if (propertyConverter != null && propertyConverter.CanRead) - { - creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType, null); - } - else - { - creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); + if (propertyConverter != null && propertyConverter.CanRead) + { + creatorPropertyContext.Value = DeserializeConvertable(propertyConverter, reader, property.PropertyType!, null); + } + else + { + creatorPropertyContext.Value = CreateValueInternal(reader, property.PropertyType, property.PropertyContract, property, contract, containerProperty, null); + } + + continue; } - - continue; } else { @@ -2227,7 +2263,7 @@ private List ResolvePropertyAndCreatorValues(JsonObjectC TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}.".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType)), null); } - if (Serializer._missingMemberHandling == MissingMemberHandling.Error) + if ((contract.MissingMemberHandling ?? Serializer._missingMemberHandling) == MissingMemberHandling.Error) { throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); } @@ -2260,9 +2296,9 @@ private List ResolvePropertyAndCreatorValues(JsonObjectC return propertyValues; } - public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty containerMember, JsonProperty containerProperty, string id, out bool createdFromNonDefaultCreator) + public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty? containerMember, JsonProperty? containerProperty, string? id, out bool createdFromNonDefaultCreator) { - object newObject = null; + object? newObject = null; if (objectContract.OverrideCreator != null) { @@ -2303,12 +2339,12 @@ public object CreateNewObject(JsonReader reader, JsonObjectContract objectContra return newObject; } - private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id) + private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty? member, string? id) { OnDeserializing(reader, contract, newObject); // only need to keep a track of properties' presence if they are required or a value should be defaulted if missing - Dictionary propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) + Dictionary? propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) : null; @@ -2326,7 +2362,7 @@ private object PopulateObject(object newObject, JsonReader reader, JsonObjectCon { case JsonToken.PropertyName: { - string propertyName = reader.Value.ToString(); + string propertyName = reader.Value!.ToString(); if (CheckPropertyName(reader, propertyName)) { @@ -2337,7 +2373,7 @@ private object PopulateObject(object newObject, JsonReader reader, JsonObjectCon { // attempt exact case match first // then try match ignoring case - JsonProperty property = contract.Properties.GetClosestMatchProperty(propertyName); + JsonProperty? property = contract.Properties.GetClosestMatchProperty(propertyName); if (property == null) { @@ -2346,7 +2382,7 @@ private object PopulateObject(object newObject, JsonReader reader, JsonObjectCon TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Could not find member '{0}' on {1}".FormatWith(CultureInfo.InvariantCulture, propertyName, contract.UnderlyingType)), null); } - if (Serializer._missingMemberHandling == MissingMemberHandling.Error) + if ((contract.MissingMemberHandling ?? Serializer._missingMemberHandling) == MissingMemberHandling.Error) { throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, propertyName, contract.UnderlyingType.Name)); } @@ -2377,7 +2413,7 @@ private object PopulateObject(object newObject, JsonReader reader, JsonObjectCon property.PropertyContract = GetContractSafe(property.PropertyType); } - JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, member); + JsonConverter? propertyConverter = GetConverter(property.PropertyContract, property.Converter, contract, member); if (!reader.ReadForType(property.PropertyContract, propertyConverter != null)) { @@ -2471,13 +2507,13 @@ private bool CheckPropertyName(JsonReader reader, string memberName) return false; } - private void SetExtensionData(JsonObjectContract contract, JsonProperty member, JsonReader reader, string memberName, object o) + private void SetExtensionData(JsonObjectContract contract, JsonProperty? member, JsonReader reader, string memberName, object o) { if (contract.ExtensionDataSetter != null) { try { - object value = ReadExtensionDataValue(contract, member, reader); + object? value = ReadExtensionDataValue(contract, member, reader); contract.ExtensionDataSetter(o, memberName, value); } @@ -2492,9 +2528,9 @@ private void SetExtensionData(JsonObjectContract contract, JsonProperty member, } } - private object ReadExtensionDataValue(JsonObjectContract contract, JsonProperty member, JsonReader reader) + private object? ReadExtensionDataValue(JsonObjectContract contract, JsonProperty? member, JsonReader reader) { - object value; + object? value; if (contract.ExtensionDataIsJToken) { value = JToken.ReadFrom(reader); @@ -2531,7 +2567,7 @@ private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectC if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate) && property.Writable) { - property.ValueProvider.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract, property.PropertyType)); + property.ValueProvider!.SetValue(newObject, EnsureType(reader, property.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, property.PropertyContract!, property.PropertyType)); } } break; @@ -2561,7 +2597,7 @@ private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectC } } - private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary requiredProperties) + private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary? requiredProperties) { if (property != null && requiredProperties != null) { @@ -2569,7 +2605,7 @@ private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dicti switch (reader.TokenType) { case JsonToken.String: - propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value)) + propertyPresence = (CoerceEmptyStringToNull(property.PropertyType, property.PropertyContract, (string)reader.Value!)) ? PropertyPresence.Null : PropertyPresence.Value; break; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 72f6a95bf..a9490cdc4 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -41,18 +44,19 @@ using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; using System.Runtime.Serialization; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { - private Type _rootType; + private Type? _rootType; private int _rootLevel; private readonly List _serializeStack = new List(); @@ -61,7 +65,7 @@ public JsonSerializerInternalWriter(JsonSerializer serializer) { } - public void Serialize(JsonWriter jsonWriter, object value, Type objectType) + public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { if (jsonWriter == null) { @@ -71,13 +75,13 @@ public void Serialize(JsonWriter jsonWriter, object value, Type objectType) _rootType = objectType; _rootLevel = _serializeStack.Count + 1; - JsonContract contract = GetContractSafe(value); + JsonContract? contract = GetContractSafe(value); try { if (ShouldWriteReference(value, null, contract, null, null)) { - WriteReference(jsonWriter, value); + WriteReference(jsonWriter, value!); } else { @@ -117,17 +121,22 @@ private JsonSerializerProxy GetInternalSerializer() return InternalSerializer; } - private JsonContract GetContractSafe(object value) + private JsonContract? GetContractSafe(object? value) { if (value == null) { return null; } + return GetContract(value); + } + + private JsonContract GetContract(object value) + { return Serializer._contractResolver.ResolveContract(value.GetType()); } - private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { @@ -149,7 +158,7 @@ private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveCo JsonWriter.WriteValue(writer, contract.TypeCode, value); } - private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { if (value == null) { @@ -157,7 +166,9 @@ private void SerializeValue(JsonWriter writer, object value, JsonContract valueC return; } - JsonConverter converter = + MiscellaneousUtils.Assert(valueContract != null); + + JsonConverter? converter = member?.Converter ?? containerProperty?.ItemConverter ?? containerContract?.ItemConverter ?? @@ -213,7 +224,7 @@ private void SerializeValue(JsonWriter writer, object value, JsonContract valueC } } - private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) + private bool? ResolveIsReference(JsonContract contract, JsonProperty? property, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { bool? isReference = null; @@ -241,12 +252,15 @@ private void SerializeValue(JsonWriter writer, object value, JsonContract valueC return isReference; } - private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) + private bool ShouldWriteReference(object? value, JsonProperty? property, JsonContract? valueContract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { if (value == null) { return false; } + + MiscellaneousUtils.Assert(valueContract != null); + if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) { return false; @@ -274,7 +288,7 @@ private bool ShouldWriteReference(object value, JsonProperty property, JsonContr return Serializer.GetReferenceResolver().IsReferenced(this, value); } - private bool ShouldWriteProperty(object memberValue, JsonObjectContract containerContract, JsonProperty property) + private bool ShouldWriteProperty(object? memberValue, JsonObjectContract? containerContract, JsonProperty property) { if (memberValue == null && ResolvedNullValueHandling(containerContract, property) == NullValueHandling.Ignore) { @@ -290,9 +304,16 @@ private bool ShouldWriteProperty(object memberValue, JsonObjectContract containe return true; } - private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) + private bool CheckForCircularReference(JsonWriter writer, object? value, JsonProperty? property, JsonContract? contract, JsonContainerContract? containerContract, JsonProperty? containerProperty) { - if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) + if (value == null) + { + return true; + } + + MiscellaneousUtils.Assert(contract != null); + + if (contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) { return true; } @@ -380,7 +401,7 @@ private string GetReference(JsonWriter writer, object value) } } - internal static bool TryConvertToString(object value, Type type, out string s) + internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s) { #if HAVE_TYPE_DESCRIPTOR if (JsonTypeReflector.CanTypeDescriptorConvertString(type, out TypeConverter converter)) @@ -398,10 +419,9 @@ internal static bool TryConvertToString(object value, Type type, out string s) } #endif - type = value as Type; - if (type != null) + if (value is Type t) { - s = type.AssemblyQualifiedName; + s = t.AssemblyQualifiedName; return true; } @@ -413,7 +433,7 @@ private void SerializeString(JsonWriter writer, object value, JsonStringContract { OnSerializing(writer, contract, value); - TryConvertToString(value, contract.UnderlyingType, out string s); + TryConvertToString(value, contract.UnderlyingType, out string? s); writer.WriteValue(s); OnSerialized(writer, contract, value); @@ -439,7 +459,7 @@ private void OnSerialized(JsonWriter writer, JsonContract contract, object value contract.InvokeOnSerialized(value, Serializer._context); } - private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, value); @@ -454,7 +474,7 @@ private void SerializeObject(JsonWriter writer, object value, JsonObjectContract JsonProperty property = contract.Properties[index]; try { - if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract? memberContract, out object? memberValue)) { continue; } @@ -475,13 +495,13 @@ private void SerializeObject(JsonWriter writer, object value, JsonObjectContract } } - IEnumerable> extensionData = contract.ExtensionDataGetter?.Invoke(value); + IEnumerable>? extensionData = contract.ExtensionDataGetter?.Invoke(value); if (extensionData != null) { foreach (KeyValuePair e in extensionData) { - JsonContract keyContract = GetContractSafe(e.Key); - JsonContract valueContract = GetContractSafe(e.Value); + JsonContract keyContract = GetContract(e.Key); + JsonContract? valueContract = GetContractSafe(e.Value); string propertyName = GetPropertyName(writer, e.Key, keyContract, out _); @@ -492,7 +512,7 @@ private void SerializeObject(JsonWriter writer, object value, JsonObjectContract if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); - WriteReference(writer, e.Value); + WriteReference(writer, e.Value!); } else { @@ -515,16 +535,16 @@ private void SerializeObject(JsonWriter writer, object value, JsonObjectContract OnSerialized(writer, contract, value); } - private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) + private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty? member, JsonProperty property, [NotNullWhen(true)]out JsonContract? memberContract, out object? memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) { - property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); + property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType!); } - memberValue = property.ValueProvider.GetValue(value); + memberValue = property.ValueProvider!.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, contract as JsonObjectContract, property)) @@ -532,7 +552,7 @@ private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContai if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); - WriteReference(writer, memberValue); + WriteReference(writer, memberValue!); return false; } @@ -543,7 +563,7 @@ private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContai if (memberValue == null) { - JsonObjectContract objectContract = contract as JsonObjectContract; + JsonObjectContract? objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? objectContract?.ItemRequired ?? Required.Default; if (resolvedRequired == Required.Always) { @@ -555,7 +575,9 @@ private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContai } } +#pragma warning disable CS8762 // Parameter must have a non-null value when exiting in some condition. return true; +#pragma warning restore CS8762 // Parameter must have a non-null value when exiting in some condition. } } @@ -564,7 +586,7 @@ private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContai return false; } - private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { writer.WriteStartObject(); @@ -580,14 +602,14 @@ private void WriteObjectStart(JsonWriter writer, object value, JsonContract cont } } - private bool HasCreatorParameter(JsonContainerContract contract, JsonProperty property) + private bool HasCreatorParameter(JsonContainerContract? contract, JsonProperty property) { if (!(contract is JsonObjectContract objectContract)) { return false; } - return objectContract.CreatorParameters.Contains(property.PropertyName); + return objectContract.CreatorParameters.Contains(property.PropertyName!); } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) @@ -631,7 +653,7 @@ private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) return ((value & flag) == flag); } - private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { @@ -662,7 +684,7 @@ private void SerializeConvertable(JsonWriter writer, JsonConverter converter, ob } } - private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; @@ -682,7 +704,7 @@ private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContr { try { - JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -725,7 +747,7 @@ private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContr OnSerialized(writer, contract, underlyingList); } - private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, values); @@ -745,7 +767,7 @@ private void SerializeMultidimensionalArray(JsonWriter writer, Array values, Jso OnSerialized(writer, contract, values); } - private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) + private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; @@ -767,7 +789,7 @@ private void SerializeMultidimensionalArray(JsonWriter writer, Array values, Jso try { - JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -802,7 +824,7 @@ private void SerializeMultidimensionalArray(JsonWriter writer, Array values, Jso writer.WriteEndArray(); } - private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); // don't make readonly fields that aren't creator parameters the referenced value because they can't be deserialized to @@ -838,7 +860,7 @@ private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract #if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE [SecuritySafeCritical] #endif - private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { if (!JsonTypeReflector.FullyTrusted) { @@ -859,7 +881,7 @@ private void SerializeISerializable(JsonWriter writer, ISerializable value, Json foreach (SerializationEntry serializationEntry in serializationInfo) { - JsonContract valueContract = GetContractSafe(serializationEntry.Value); + JsonContract? valueContract = GetContractSafe(serializationEntry.Value); if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { @@ -881,7 +903,7 @@ private void SerializeISerializable(JsonWriter writer, ISerializable value, Json #endif #if HAVE_DYNAMIC - private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); @@ -899,7 +921,7 @@ private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider valu { try { - if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract memberContract, out object memberValue)) + if (!CalculatePropertyValues(writer, value, contract, member, property, out JsonContract? memberContract, out object? memberValue)) { continue; } @@ -923,11 +945,11 @@ private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider valu foreach (string memberName in value.GetDynamicMemberNames()) { - if (contract.TryGetMember(value, memberName, out object memberValue)) + if (contract.TryGetMember(value, memberName, out object? memberValue)) { try { - JsonContract valueContract = GetContractSafe(memberValue); + JsonContract? valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) { @@ -965,7 +987,7 @@ private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider valu } #endif - private bool ShouldWriteDynamicProperty(object memberValue) + private bool ShouldWriteDynamicProperty(object? memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) { @@ -981,7 +1003,7 @@ private bool ShouldWriteDynamicProperty(object memberValue) return true; } - private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) + private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { TypeNameHandling resolvedTypeNameHandling = member?.TypeNameHandling @@ -999,7 +1021,7 @@ private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract { if (member != null) { - if (contract.NonNullableUnderlyingType != member.PropertyContract.CreatedType) + if (contract.NonNullableUnderlyingType != member.PropertyContract!.CreatedType) { return true; } @@ -1025,8 +1047,9 @@ private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract return false; } - private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) + private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { +#pragma warning disable CS8600, CS8602, CS8604 object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); @@ -1063,7 +1086,7 @@ private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDict try { object value = entry.Value; - JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); + JsonContract? valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { @@ -1105,6 +1128,7 @@ private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDict _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); +#pragma warning restore CS8600, CS8602, CS8604 } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) @@ -1154,7 +1178,7 @@ private string GetPropertyName(JsonWriter writer, object name, JsonContract cont { escape = true; - if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string enumName)) + if (primitiveContract.IsEnum && EnumUtils.TryToString(primitiveContract.NonNullableUnderlyingType, name, null, out string? enumName)) { return enumName; } @@ -1163,7 +1187,7 @@ private string GetPropertyName(JsonWriter writer, object name, JsonContract cont } } } - else if (TryConvertToString(name, name.GetType(), out string propertyName)) + else if (TryConvertToString(name, name.GetType(), out string? propertyName)) { escape = true; return propertyName; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs index ca41d6a11..33cd1c775 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -38,29 +41,29 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { - private readonly JsonSerializerInternalReader _serializerReader; - private readonly JsonSerializerInternalWriter _serializerWriter; + private readonly JsonSerializerInternalReader? _serializerReader; + private readonly JsonSerializerInternalWriter? _serializerWriter; private readonly JsonSerializer _serializer; - public override event EventHandler Error + public override event EventHandler? Error { add => _serializer.Error += value; remove => _serializer.Error -= value; } - public override IReferenceResolver ReferenceResolver + public override IReferenceResolver? ReferenceResolver { get => _serializer.ReferenceResolver; set => _serializer.ReferenceResolver = value; } - public override ITraceWriter TraceWriter + public override ITraceWriter? TraceWriter { get => _serializer.TraceWriter; set => _serializer.TraceWriter = value; } - public override IEqualityComparer EqualityComparer + public override IEqualityComparer? EqualityComparer { get => _serializer.EqualityComparer; set => _serializer.EqualityComparer = value; @@ -234,7 +237,7 @@ internal JsonSerializerInternalBase GetInternalSerializer() } else { - return _serializerWriter; + return _serializerWriter!; } } @@ -254,7 +257,7 @@ public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) _serializer = serializerWriter.Serializer; } - internal override object DeserializeInternal(JsonReader reader, Type objectType) + internal override object? DeserializeInternal(JsonReader reader, Type? objectType) { if (_serializerReader != null) { @@ -278,7 +281,7 @@ internal override void PopulateInternal(JsonReader reader, object target) } } - internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) + internal override void SerializeInternal(JsonWriter jsonWriter, object? value, Type? rootType) { if (_serializerWriter != null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonStringContract.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonStringContract.cs index 82077bee4..6d4d7c038 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonStringContract.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonStringContract.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index e152f31b2..99f142948 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -62,15 +65,15 @@ internal static class JsonTypeReflector public const string ConcurrentDictionaryTypeName = "System.Collections.Concurrent.ConcurrentDictionary`2"; - private static readonly ThreadSafeStore> CreatorCache = - new ThreadSafeStore>(GetCreator); + private static readonly ThreadSafeStore> CreatorCache = + new ThreadSafeStore>(GetCreator); #if !(NET20 || DOTNET) - private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); - private static ReflectionObject _metadataTypeAttributeReflectionObject; + private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); + private static ReflectionObject? _metadataTypeAttributeReflectionObject; #endif - public static T GetCachedAttribute(object attributeProvider) where T : Attribute + public static T? GetCachedAttribute(object attributeProvider) where T : Attribute { return CachedAttributeGetter.GetAttribute(attributeProvider); } @@ -100,14 +103,14 @@ public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter t #endif #if HAVE_DATA_CONTRACTS - public static DataContractAttribute GetDataContractAttribute(Type type) + public static DataContractAttribute? GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance Type currentType = type; while (currentType != null) { - DataContractAttribute result = CachedAttributeGetter.GetAttribute(currentType); + DataContractAttribute? result = CachedAttributeGetter.GetAttribute(currentType); if (result != null) { return result; @@ -119,7 +122,7 @@ public static DataContractAttribute GetDataContractAttribute(Type type) return null; } - public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) + public static DataMemberAttribute? GetDataMemberAttribute(MemberInfo memberInfo) { // DataMemberAttribute does not have inheritance @@ -131,7 +134,7 @@ public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo)memberInfo; - DataMemberAttribute result = CachedAttributeGetter.GetAttribute(propertyInfo); + DataMemberAttribute? result = CachedAttributeGetter.GetAttribute(propertyInfo); if (result == null) { if (propertyInfo.IsVirtual()) @@ -157,14 +160,14 @@ public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute) { - JsonObjectAttribute objectAttribute = GetCachedAttribute(objectType); + JsonObjectAttribute? objectAttribute = GetCachedAttribute(objectType); if (objectAttribute != null) { return objectAttribute.MemberSerialization; } #if HAVE_DATA_CONTRACTS - DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); + DataContractAttribute? dataContractAttribute = GetDataContractAttribute(objectType); if (dataContractAttribute != null) { return MemberSerialization.OptIn; @@ -182,13 +185,13 @@ public static MemberSerialization GetObjectMemberSerialization(Type objectType, return MemberSerialization.OptOut; } - public static JsonConverter GetJsonConverter(object attributeProvider) + public static JsonConverter? GetJsonConverter(object attributeProvider) { - JsonConverterAttribute converterAttribute = GetCachedAttribute(attributeProvider); + JsonConverterAttribute? converterAttribute = GetCachedAttribute(attributeProvider); if (converterAttribute != null) { - Func creator = CreatorCache.Get(converterAttribute.ConverterType); + Func creator = CreatorCache.Get(converterAttribute.ConverterType); if (creator != null) { return (JsonConverter)creator(converterAttribute.ConverterParameters); @@ -204,19 +207,19 @@ public static JsonConverter GetJsonConverter(object attributeProvider) /// The type to create. /// Optional arguments to pass to an initializing constructor of the JsonConverter. /// If null, the default constructor is used. - public static JsonConverter CreateJsonConverterInstance(Type converterType, object[] args) + public static JsonConverter CreateJsonConverterInstance(Type converterType, object[]? args) { - Func converterCreator = CreatorCache.Get(converterType); + Func converterCreator = CreatorCache.Get(converterType); return (JsonConverter)converterCreator(args); } - public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[] args) + public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[]? args) { - Func converterCreator = CreatorCache.Get(namingStrategyType); + Func converterCreator = CreatorCache.Get(namingStrategyType); return (NamingStrategy)converterCreator(args); } - public static NamingStrategy GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) + public static NamingStrategy? GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) { if (containerAttribute.NamingStrategyInstance == null) { @@ -231,9 +234,9 @@ public static NamingStrategy GetContainerNamingStrategy(JsonContainerAttribute c return containerAttribute.NamingStrategyInstance; } - private static Func GetCreator(Type type) + private static Func GetCreator(Type type) { - Func defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) + Func? defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor(type) : null; @@ -280,12 +283,12 @@ private static Func GetCreator(Type type) } #if !(NET20 || DOTNET) - private static Type GetAssociatedMetadataType(Type type) + private static Type? GetAssociatedMetadataType(Type type) { return AssociatedMetadataTypesCache.Get(type); } - private static Type GetAssociateMetadataTypeFromAttribute(Type type) + private static Type? GetAssociateMetadataTypeFromAttribute(Type type) { Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true); @@ -304,7 +307,7 @@ private static Type GetAssociateMetadataTypeFromAttribute(Type type) _metadataTypeAttributeReflectionObject = ReflectionObject.Create(attributeType, metadataClassTypeName); } - return (Type)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); + return (Type?)_metadataTypeAttributeReflectionObject.GetValue(attribute, metadataClassTypeName); } } @@ -312,12 +315,12 @@ private static Type GetAssociateMetadataTypeFromAttribute(Type type) } #endif - private static T GetAttribute(Type type) where T : Attribute + private static T? GetAttribute(Type type) where T : Attribute { - T attribute; + T? attribute; #if !(NET20 || DOTNET) - Type metadataType = GetAssociatedMetadataType(type); + Type? metadataType = GetAssociatedMetadataType(type); if (metadataType != null) { attribute = ReflectionUtils.GetAttribute(metadataType, true); @@ -346,12 +349,12 @@ private static T GetAttribute(Type type) where T : Attribute return null; } - private static T GetAttribute(MemberInfo memberInfo) where T : Attribute + private static T? GetAttribute(MemberInfo memberInfo) where T : Attribute { - T attribute; + T? attribute; #if !(NET20 || DOTNET) - Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); + Type? metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); if (metadataType != null) { MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); @@ -427,7 +430,7 @@ public static bool IsSerializable(object provider) } #endif - public static T GetAttribute(object provider) where T : Attribute + public static T? GetAttribute(object provider) where T : Attribute { if (provider is Type type) { @@ -519,7 +522,7 @@ public static ReflectionDelegateFactory ReflectionDelegateFactory { get { -#if !(PORTABLE40 || PORTABLE || DOTNET || NETSTANDARD2_0 || NETCOREAPP) +#if NETFRAMEWORK if (DynamicCodeGeneration) { return DynamicReflectionDelegateFactory.Instance; @@ -532,4 +535,4 @@ public static ReflectionDelegateFactory ReflectionDelegateFactory } } } -} +} \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs new file mode 100644 index 000000000..a4f5aa526 --- /dev/null +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/KebabCaseNamingStrategy.cs @@ -0,0 +1,91 @@ +//------------------------------------------------------------------------------ +// +// This file was automatically generated by the UpdateVendors tool. +//------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities; + +namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization +{ + /// + /// A kebab case naming strategy. + /// + internal class KebabCaseNamingStrategy : NamingStrategy + { + /// + /// Initializes a new instance of the class. + /// + /// + /// A flag indicating whether dictionary keys should be processed. + /// + /// + /// A flag indicating whether explicitly specified property names should be processed, + /// e.g. a property name customized with a . + /// + public KebabCaseNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames) + { + ProcessDictionaryKeys = processDictionaryKeys; + OverrideSpecifiedNames = overrideSpecifiedNames; + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// A flag indicating whether dictionary keys should be processed. + /// + /// + /// A flag indicating whether explicitly specified property names should be processed, + /// e.g. a property name customized with a . + /// + /// + /// A flag indicating whether extension data names should be processed. + /// + public KebabCaseNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames, bool processExtensionDataNames) + : this(processDictionaryKeys, overrideSpecifiedNames) + { + ProcessExtensionDataNames = processExtensionDataNames; + } + + /// + /// Initializes a new instance of the class. + /// + public KebabCaseNamingStrategy() + { + } + + /// + /// Resolves the specified property name. + /// + /// The property name to resolve. + /// The resolved property name. + protected override string ResolvePropertyName(string name) => StringUtils.ToKebabCase(name); + } +} \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs index 0e2c729ec..04421ddfd 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -45,7 +48,7 @@ public MemoryTraceWriter() /// The at which to write this trace. /// The trace message. /// The trace exception. This parameter is optional. - public void Trace(TraceLevel level, string message, Exception ex) + public void Trace(TraceLevel level, string message, Exception? ex) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture)); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/NamingStrategy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/NamingStrategy.cs index 4963a9d05..3f36a4322 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/NamingStrategy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/NamingStrategy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -105,5 +108,46 @@ public virtual string GetDictionaryKey(string key) /// The property name to resolve. /// The resolved property name. protected abstract string ResolvePropertyName(string name); + + /// + /// Hash code calculation + /// + /// + public override int GetHashCode() + { + unchecked + { + var hashCode = GetType().GetHashCode(); // make sure different types do not result in equal values + hashCode = (hashCode * 397) ^ ProcessDictionaryKeys.GetHashCode(); + hashCode = (hashCode * 397) ^ ProcessExtensionDataNames.GetHashCode(); + hashCode = (hashCode * 397) ^ OverrideSpecifiedNames.GetHashCode(); + return hashCode; + } + } + + /// + /// Object equality implementation + /// + /// + /// + public override bool Equals(object obj) => Equals(obj as NamingStrategy); + + /// + /// Compare to another NamingStrategy + /// + /// + /// + protected bool Equals(NamingStrategy? other) + { + if (other == null) + { + return false; + } + + return GetType() == other.GetType() && + ProcessDictionaryKeys == other.ProcessDictionaryKeys && + ProcessExtensionDataNames == other.ProcessExtensionDataNames && + OverrideSpecifiedNames == other.OverrideSpecifiedNames; + } } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ObjectConstructor.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ObjectConstructor.cs index 64ef5c378..b14aa2741 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ObjectConstructor.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ObjectConstructor.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -33,5 +36,5 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Serialization /// Represents a method that constructs an object. /// /// The object type to create. - internal delegate object ObjectConstructor(params object[] args); + internal delegate object ObjectConstructor(params object?[] args); } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/OnErrorAttribute.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/OnErrorAttribute.cs index 9f9de5c46..67e54efc6 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/OnErrorAttribute.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/OnErrorAttribute.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionAttributeProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionAttributeProvider.cs index 7f96b6351..c72b35888 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionAttributeProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionAttributeProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs index 06a8c4997..daa4d02bc 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/ReflectionValueProvider.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -56,7 +59,7 @@ public ReflectionValueProvider(MemberInfo memberInfo) /// /// The target to set the value on. /// The value to set on the target. - public void SetValue(object target, object value) + public void SetValue(object target, object? value) { try { @@ -73,7 +76,7 @@ public void SetValue(object target, object value) /// /// The target to get the value from. /// The value. - public object GetValue(object target) + public object? GetValue(object target) { try { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs index 4259a89dc..24407900a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SerializationBinderAdapter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -45,12 +48,12 @@ public SerializationBinderAdapter(SerializationBinder serializationBinder) } #pragma warning restore 618 - public Type BindToType(string assemblyName, string typeName) + public Type BindToType(string? assemblyName, string typeName) { return SerializationBinder.BindToType(assemblyName, typeName); } - public void BindToName(Type serializedType, out string assemblyName, out string typeName) + public void BindToName(Type serializedType, out string? assemblyName, out string? typeName) { #if HAVE_SERIALIZATION_BINDER_BIND_TO_NAME SerializationBinder.BindToName(serializedType, out assemblyName, out typeName); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs index 9d352ed35..d97a8988f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/SnakeCaseNamingStrategy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonReader.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonReader.cs index caf5110b1..edf204b1d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonReader.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -72,16 +75,16 @@ public override bool Read() return value; } - public override string ReadAsString() + public override string? ReadAsString() { - string value = _innerReader.ReadAsString(); + string? value = _innerReader.ReadAsString(); WriteCurrentToken(); return value; } - public override byte[] ReadAsBytes() + public override byte[]? ReadAsBytes() { - byte[] value = _innerReader.ReadAsBytes(); + byte[]? value = _innerReader.ReadAsBytes(); WriteCurrentToken(); return value; } @@ -140,9 +143,9 @@ public override char QuoteChar public override JsonToken TokenType => _innerReader.TokenType; - public override object Value => _innerReader.Value; + public override object? Value => _innerReader.Value; - public override Type ValueType => _innerReader.ValueType; + public override Type ?ValueType => _innerReader.ValueType; public override void Close() { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonWriter.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonWriter.cs index 1b4aea335..dd540d517 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonWriter.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Serialization/TraceJsonWriter.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -148,7 +151,7 @@ public override void WriteValue(char? value) } } - public override void WriteValue(byte[] value) + public override void WriteValue(byte[]? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -325,7 +328,7 @@ public override void WriteValue(long? value) } } - public override void WriteValue(object value) + public override void WriteValue(object? value) { #if HAVE_BIG_INTEGER if (value is BigInteger) @@ -393,7 +396,7 @@ public override void WriteValue(short? value) } } - public override void WriteValue(string value) + public override void WriteValue(string? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -463,7 +466,7 @@ public override void WriteValue(ulong? value) } } - public override void WriteValue(Uri value) + public override void WriteValue(Uri? value) { _textWriter.WriteValue(value); _innerWriter.WriteValue(value); @@ -505,7 +508,7 @@ public override void WriteWhitespace(string ws) base.WriteWhitespace(ws); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { _textWriter.WriteComment(text); _innerWriter.WriteComment(text); @@ -570,7 +573,7 @@ public override void WriteEndObject() base.WriteEndObject(); } - public override void WriteRawValue(string json) + public override void WriteRawValue(string? json) { _textWriter.WriteRawValue(json); _innerWriter.WriteRawValue(json); @@ -579,7 +582,7 @@ public override void WriteRawValue(string json) InternalWriteValue(JsonToken.Undefined); } - public override void WriteRaw(string json) + public override void WriteRaw(string? json) { _textWriter.WriteRaw(json); _innerWriter.WriteRaw(json); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/SerializationBinder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/SerializationBinder.cs index 687b95f26..7d870cc9a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/SerializationBinder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/SerializationBinder.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #if (DOTNET || PORTABLE40 || PORTABLE) using System; @@ -21,7 +24,7 @@ internal abstract class SerializationBinder /// Specifies the name of the serialized object. /// Specifies the name of the serialized object /// The type of the object the formatter creates a new instance of. - public abstract Type BindToType(string assemblyName, string typeName); + public abstract Type BindToType(string? assemblyName, string typeName); /// /// When overridden in a derived class, controls the binding of a serialized object to a type. @@ -29,7 +32,7 @@ internal abstract class SerializationBinder /// The type of the object the formatter creates a new instance of. /// Specifies the name of the serialized object. /// Specifies the name of the serialized object. - public virtual void BindToName(Type serializedType, out string assemblyName, out string typeName) + public virtual void BindToName(Type serializedType, out string? assemblyName, out string? typeName) { assemblyName = null; typeName = null; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/StringEscapeHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/StringEscapeHandling.cs index 48b756c82..0e9d2d130 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/StringEscapeHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/StringEscapeHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TraceLevel.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TraceLevel.cs index e6a2798c0..dbd870e50 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TraceLevel.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TraceLevel.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #if !HAVE_TRACE_WRITER using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameAssemblyFormatHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameAssemblyFormatHandling.cs index 561506710..d1c4c16e8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameAssemblyFormatHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameAssemblyFormatHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameHandling.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameHandling.cs index ef824cd15..d15c69e88 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameHandling.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/TypeNameHandling.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/AsyncUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/AsyncUtils.cs index 44f0b14a3..0578130b1 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/AsyncUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/AsyncUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,12 +47,12 @@ internal static class AsyncUtils internal static Task ToAsync(this bool value) => value ? True : False; - public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken) + public static Task? CancelIfRequestedAsync(this CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : null; } - public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken) + public static Task? CancelIfRequestedAsync(this CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : null; } @@ -58,14 +61,16 @@ public static Task CancelIfRequestedAsync(this CancellationToken cancellat // previous frameworks. public static Task FromCanceled(this CancellationToken cancellationToken) { - Debug.Assert(cancellationToken.IsCancellationRequested); + MiscellaneousUtils.Assert(cancellationToken.IsCancellationRequested); return new Task(() => {}, cancellationToken); } public static Task FromCanceled(this CancellationToken cancellationToken) { - Debug.Assert(cancellationToken.IsCancellationRequested); + MiscellaneousUtils.Assert(cancellationToken.IsCancellationRequested); +#pragma warning disable CS8603 // Possible null reference return. return new Task(() => default, cancellationToken); +#pragma warning restore CS8603 // Possible null reference return. } // Task.Delay(0) is optimised as a cached task within the framework, and indeed @@ -75,25 +80,25 @@ public static Task FromCanceled(this CancellationToken cancellationToken) public static Task WriteAsync(this TextWriter writer, char value, CancellationToken cancellationToken) { - Debug.Assert(writer != null); + MiscellaneousUtils.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value); } - public static Task WriteAsync(this TextWriter writer, string value, CancellationToken cancellationToken) + public static Task WriteAsync(this TextWriter writer, string? value, CancellationToken cancellationToken) { - Debug.Assert(writer != null); + MiscellaneousUtils.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value); } public static Task WriteAsync(this TextWriter writer, char[] value, int start, int count, CancellationToken cancellationToken) { - Debug.Assert(writer != null); + MiscellaneousUtils.Assert(writer != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value, start, count); } public static Task ReadAsync(this TextReader reader, char[] buffer, int index, int count, CancellationToken cancellationToken) { - Debug.Assert(reader != null); + MiscellaneousUtils.Assert(reader != null); return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : reader.ReadAsync(buffer, index, count); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/Base64Encoder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/Base64Encoder.cs index 70739dab6..019e93567 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/Base64Encoder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/Base64Encoder.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal class Base64Encoder private readonly char[] _charsLine = new char[Base64LineSize]; private readonly TextWriter _writer; - private byte[] _leftOverBytes; + private byte[]? _leftOverBytes; private int _leftOverBytesCount; public Base64Encoder(TextWriter writer) @@ -132,7 +135,7 @@ private bool FulfillFromLeftover(byte[] buffer, int index, ref int count) int leftOverBytesCount = _leftOverBytesCount; while (leftOverBytesCount < 3 && count > 0) { - _leftOverBytes[leftOverBytesCount++] = buffer[index++]; + _leftOverBytes![leftOverBytesCount++] = buffer[index++]; count--; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs index 71f66ca04..f9b48b199 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/BidirectionalDictionary.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -67,7 +70,7 @@ public void Set(TFirst first, TSecond second) { if (_firstToSecond.TryGetValue(first, out TSecond existingSecond)) { - if (!existingSecond.Equals(second)) + if (!existingSecond!.Equals(second)) { throw new ArgumentException(_duplicateFirstErrorMessage.FormatWith(CultureInfo.InvariantCulture, first)); } @@ -75,7 +78,7 @@ public void Set(TFirst first, TSecond second) if (_secondToFirst.TryGetValue(second, out TFirst existingFirst)) { - if (!existingFirst.Equals(first)) + if (!existingFirst!.Equals(first)) { throw new ArgumentException(_duplicateSecondErrorMessage.FormatWith(CultureInfo.InvariantCulture, second)); } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionUtils.cs index 4147dbc06..46508fc39 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -120,17 +123,17 @@ public static bool IsDictionaryType(Type type) return false; } - public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) + public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) { Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); } - public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) + public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) { Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); - ConstructorInfo match = null; + ConstructorInfo? match = null; foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { @@ -252,6 +255,7 @@ public static int IndexOfReference(this List list, T item) return i; } } + return -1; } @@ -369,25 +373,17 @@ public static Array ToMultidimensionalArray(IList values, Type type, int rank) return multidimensionalArray; } - // 4.6 has Array.Empty to return a cached empty array. Lacking that in other - // frameworks, Enumerable.Empty happens to be implemented as a cached empty - // array in all versions (in .NET Core the same instance as Array.Empty). - // This includes the internal Linq bridge for 2.0. - // Since this method is simple and only 11 bytes long in a release build it's - // pretty much guaranteed to be inlined, giving us fast access of that cached - // array. With 4.5 and up we use AggressiveInlining just to be sure, so it's - // effectively the same as calling Array.Empty even when not available. -#if HAVE_METHOD_IMPL_ATTRIBUTE - [MethodImpl(MethodImplOptions.AggressiveInlining)] -#endif public static T[] ArrayEmpty() { - T[] array = Enumerable.Empty() as T[]; - Debug.Assert(array != null); - // Defensively guard against a version of Linq where Enumerable.Empty doesn't - // return an array, but throw in debug versions so a better strategy can be - // used if that ever happens. - return array ?? new T[0]; + // Enumerable.Empty no longer returns an empty array in .NET Core 3.0 + return EmptyArrayContainer.Empty; + } + + private static class EmptyArrayContainer + { +#pragma warning disable CA1825 // Avoid zero-length array allocations. + public static readonly T[] Empty = new T[0]; +#pragma warning restore CA1825 // Avoid zero-length array allocations. } } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionWrapper.cs index cadf0a039..93cecbee9 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -48,9 +51,9 @@ internal interface IWrappedCollection : IList internal class CollectionWrapper : ICollection, IWrappedCollection { - private readonly IList _list; - private readonly ICollection _genericCollection; - private object _syncRoot; + private readonly IList? _list; + private readonly ICollection? _genericCollection; + private object? _syncRoot; public CollectionWrapper(IList list) { @@ -81,7 +84,7 @@ public virtual void Add(T item) } else { - _list.Add(item); + _list!.Add(item); } } @@ -93,7 +96,7 @@ public virtual void Clear() } else { - _list.Clear(); + _list!.Clear(); } } @@ -105,7 +108,7 @@ public virtual bool Contains(T item) } else { - return _list.Contains(item); + return _list!.Contains(item); } } @@ -117,7 +120,7 @@ public virtual void CopyTo(T[] array, int arrayIndex) } else { - _list.CopyTo(array, arrayIndex); + _list!.CopyTo(array, arrayIndex); } } @@ -131,7 +134,7 @@ public virtual int Count } else { - return _list.Count; + return _list!.Count; } } } @@ -146,7 +149,7 @@ public virtual bool IsReadOnly } else { - return _list.IsReadOnly; + return _list!.IsReadOnly; } } } @@ -159,11 +162,11 @@ public virtual bool Remove(T item) } else { - bool contains = _list.Contains(item); + bool contains = _list!.Contains(item); if (contains) { - _list.Remove(item); + _list!.Remove(item); } return contains; @@ -177,7 +180,7 @@ public virtual IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return ((IEnumerable)_genericCollection ?? _list).GetEnumerator(); + return ((IEnumerable)_genericCollection! ?? _list!).GetEnumerator(); } int IList.Add(object value) @@ -207,7 +210,7 @@ int IList.IndexOf(object value) if (IsCompatibleObject(value)) { - return _list.IndexOf((T)value); + return _list!.IndexOf((T)value); } return -1; @@ -220,7 +223,7 @@ void IList.RemoveAt(int index) throw new InvalidOperationException("Wrapped ICollection does not support RemoveAt."); } - _list.RemoveAt(index); + _list!.RemoveAt(index); } void IList.Insert(int index, object value) @@ -231,7 +234,7 @@ void IList.Insert(int index, object value) } VerifyValueType(value); - _list.Insert(index, (T)value); + _list!.Insert(index, (T)value); } bool IList.IsFixedSize @@ -245,7 +248,7 @@ bool IList.IsFixedSize } else { - return _list.IsFixedSize; + return _list!.IsFixedSize; } } } @@ -267,7 +270,7 @@ object IList.this[int index] throw new InvalidOperationException("Wrapped ICollection does not support indexer."); } - return _list[index]; + return _list![index]; } set { @@ -277,7 +280,7 @@ object IList.this[int index] } VerifyValueType(value); - _list[index] = (T)value; + _list![index] = (T)value; } } @@ -319,6 +322,6 @@ private static bool IsCompatibleObject(object value) return true; } - public object UnderlyingCollection => (object)_genericCollection ?? _list; + public object UnderlyingCollection => (object)_genericCollection! ?? _list!; } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ConvertUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ConvertUtils.cs index 090f64e26..97cb47e46 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -31,6 +34,7 @@ using System.Collections.Generic; using System.Globalization; using System.ComponentModel; +using System.Runtime.CompilerServices; #if HAVE_BIG_INTEGER using System.Numerics; #endif @@ -40,6 +44,7 @@ #endif using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; using System.Reflection; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #endif @@ -98,8 +103,14 @@ internal enum PrimitiveTypeCode internal class TypeInformation { - public Type Type { get; set; } - public PrimitiveTypeCode TypeCode { get; set; } + public Type Type { get; } + public PrimitiveTypeCode TypeCode { get; } + + public TypeInformation(Type type, PrimitiveTypeCode typeCode) + { + Type = type; + TypeCode = typeCode; + } } internal enum ParseResult @@ -167,25 +178,25 @@ internal static class ConvertUtils private static readonly TypeInformation[] PrimitiveTypeCodes = { // need all of these. lookup against the index with TypeCode value - new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, - new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Object }, - new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.DBNull }, - new TypeInformation { Type = typeof(bool), TypeCode = PrimitiveTypeCode.Boolean }, - new TypeInformation { Type = typeof(char), TypeCode = PrimitiveTypeCode.Char }, - new TypeInformation { Type = typeof(sbyte), TypeCode = PrimitiveTypeCode.SByte }, - new TypeInformation { Type = typeof(byte), TypeCode = PrimitiveTypeCode.Byte }, - new TypeInformation { Type = typeof(short), TypeCode = PrimitiveTypeCode.Int16 }, - new TypeInformation { Type = typeof(ushort), TypeCode = PrimitiveTypeCode.UInt16 }, - new TypeInformation { Type = typeof(int), TypeCode = PrimitiveTypeCode.Int32 }, - new TypeInformation { Type = typeof(uint), TypeCode = PrimitiveTypeCode.UInt32 }, - new TypeInformation { Type = typeof(long), TypeCode = PrimitiveTypeCode.Int64 }, - new TypeInformation { Type = typeof(ulong), TypeCode = PrimitiveTypeCode.UInt64 }, - new TypeInformation { Type = typeof(float), TypeCode = PrimitiveTypeCode.Single }, - new TypeInformation { Type = typeof(double), TypeCode = PrimitiveTypeCode.Double }, - new TypeInformation { Type = typeof(decimal), TypeCode = PrimitiveTypeCode.Decimal }, - new TypeInformation { Type = typeof(DateTime), TypeCode = PrimitiveTypeCode.DateTime }, - new TypeInformation { Type = typeof(object), TypeCode = PrimitiveTypeCode.Empty }, // no 17 in TypeCode for some reason - new TypeInformation { Type = typeof(string), TypeCode = PrimitiveTypeCode.String } + new TypeInformation(typeof(object), PrimitiveTypeCode.Empty), + new TypeInformation(typeof(object), PrimitiveTypeCode.Object), + new TypeInformation(typeof(object), PrimitiveTypeCode.DBNull), + new TypeInformation(typeof(bool), PrimitiveTypeCode.Boolean), + new TypeInformation(typeof(char), PrimitiveTypeCode.Char), + new TypeInformation(typeof(sbyte), PrimitiveTypeCode.SByte), + new TypeInformation(typeof(byte), PrimitiveTypeCode.Byte), + new TypeInformation(typeof(short), PrimitiveTypeCode.Int16), + new TypeInformation(typeof(ushort), PrimitiveTypeCode.UInt16), + new TypeInformation(typeof(int), PrimitiveTypeCode.Int32), + new TypeInformation(typeof(uint), PrimitiveTypeCode.UInt32), + new TypeInformation(typeof(long), PrimitiveTypeCode.Int64), + new TypeInformation(typeof(ulong), PrimitiveTypeCode.UInt64), + new TypeInformation(typeof(float), PrimitiveTypeCode.Single), + new TypeInformation(typeof(double), PrimitiveTypeCode.Double), + new TypeInformation(typeof(decimal), PrimitiveTypeCode.Decimal), + new TypeInformation(typeof(DateTime), PrimitiveTypeCode.DateTime), + new TypeInformation(typeof(object), PrimitiveTypeCode.Empty), // no 17 in TypeCode for some reason + new TypeInformation(typeof(string), PrimitiveTypeCode.String) }; #endif @@ -252,10 +263,10 @@ public static TimeSpan ParseTimeSpan(string input) #endif } - private static readonly ThreadSafeStore, System.Func> CastConverters = - new ThreadSafeStore, System.Func>(CreateCastConverter); + private static readonly ThreadSafeStore, System.Func?> CastConverters = + new ThreadSafeStore, System.Func?>(CreateCastConverter); - private static System.Func CreateCastConverter(StructMultiKey t) + private static System.Func? CreateCastConverter(StructMultiKey t) { Type initialType = t.Value1; Type targetType = t.Value2; @@ -267,7 +278,7 @@ private static System.Func CreateCastConverter(StructMultiKey call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(castMethodInfo); return o => call(null, o); } @@ -367,10 +378,10 @@ internal enum ConvertResult public static object Convert(object initialValue, CultureInfo culture, Type targetType) { - switch (TryConvertInternal(initialValue, culture, targetType, out object value)) + switch (TryConvertInternal(initialValue, culture, targetType, out object? value)) { case ConvertResult.Success: - return value; + return value!; case ConvertResult.CannotConvertNull: throw new Exception("Can not convert null {0} into non-nullable {1}.".FormatWith(CultureInfo.InvariantCulture, initialValue.GetType(), targetType)); case ConvertResult.NotInstantiableType: @@ -382,7 +393,7 @@ public static object Convert(object initialValue, CultureInfo culture, Type targ } } - private static bool TryConvert(object initialValue, CultureInfo culture, Type targetType, out object value) + private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value) { try { @@ -401,7 +412,7 @@ private static bool TryConvert(object initialValue, CultureInfo culture, Type ta } } - private static ConvertResult TryConvertInternal(object initialValue, CultureInfo culture, Type targetType, out object value) + private static ConvertResult TryConvertInternal(object? initialValue, CultureInfo culture, Type targetType, out object? value) { if (initialValue == null) { @@ -486,7 +497,7 @@ private static ConvertResult TryConvertInternal(object initialValue, CultureInfo } if (targetType == typeof(Version)) { - if (VersionTryParse(s, out Version result)) + if (VersionTryParse(s, out Version? result)) { value = result; return ConvertResult.Success; @@ -571,7 +582,7 @@ private static ConvertResult TryConvertInternal(object initialValue, CultureInfo /// The converted type. If conversion was unsuccessful, the initial value /// is returned if assignable to the target type. /// - public static object ConvertOrCast(object initialValue, CultureInfo culture, Type targetType) + public static object? ConvertOrCast(object? initialValue, CultureInfo culture, Type targetType) { if (targetType == typeof(object)) { @@ -583,27 +594,27 @@ public static object ConvertOrCast(object initialValue, CultureInfo culture, Typ return null; } - if (TryConvert(initialValue, culture, targetType, out object convertedValue)) + if (TryConvert(initialValue, culture, targetType, out object? convertedValue)) { return convertedValue; } - return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue), targetType); + return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue)!, targetType); } #endregion - private static object EnsureTypeAssignable(object value, Type initialType, Type targetType) + private static object? EnsureTypeAssignable(object? value, Type initialType, Type targetType) { - Type valueType = value?.GetType(); - if (value != null) { + Type valueType = value.GetType(); + if (targetType.IsAssignableFrom(valueType)) { return value; } - System.Func castConverter = CastConverters.Get(new StructMultiKey(valueType, targetType)); + System.Func? castConverter = CastConverters.Get(new StructMultiKey(valueType, targetType)); if (castConverter != null) { return castConverter(value); @@ -620,7 +631,7 @@ private static object EnsureTypeAssignable(object value, Type initialType, Type throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType?.ToString() ?? "{null}", targetType)); } - public static bool VersionTryParse(string input, out Version result) + public static bool VersionTryParse(string input, [NotNullWhen(true)]out Version? result) { #if HAVE_VERSION_TRY_PARSE return Version.TryParse(input, out result); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeParser.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeParser.cs index 2666ff686..0a16f3d84 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeParser.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeParser.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeUtils.cs index b0f179b37..26f8631d2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DateTimeUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -183,9 +186,9 @@ private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset) internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset) { - long universialTicks = ToUniversalTicks(dateTime, offset); + long universalTicks = ToUniversalTicks(dateTime, offset); - return UniversialTicksToJavaScriptTicks(universialTicks); + return UniversalTicksToJavaScriptTicks(universalTicks); } internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime) @@ -197,12 +200,12 @@ internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool co { long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks; - return UniversialTicksToJavaScriptTicks(ticks); + return UniversalTicksToJavaScriptTicks(ticks); } - private static long UniversialTicksToJavaScriptTicks(long universialTicks) + private static long UniversalTicksToJavaScriptTicks(long universalTicks) { - long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks) / 10000; + long javaScriptTicks = (universalTicks - InitialJavaScriptDateTicks) / 10000; return javaScriptTicks; } @@ -345,7 +348,7 @@ private static DateTime CreateDateTime(DateTimeParser dateTimeParser) return d; } - internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) + internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling dateTimeZoneHandling, string? dateFormatString, CultureInfo culture, out DateTime dt) { if (s.Length > 0) { @@ -368,7 +371,7 @@ internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling da } } - if (!string.IsNullOrEmpty(dateFormatString)) + if (!StringUtils.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeExact(s.ToString(), dateTimeZoneHandling, dateFormatString, culture, out dt)) { @@ -381,7 +384,7 @@ internal static bool TryParseDateTime(StringReference s, DateTimeZoneHandling da return false; } - internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt) + internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string? dateFormatString, CultureInfo culture, out DateTime dt) { if (s.Length > 0) { @@ -404,7 +407,7 @@ internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZon } } - if (!string.IsNullOrEmpty(dateFormatString)) + if (!StringUtils.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeExact(s, dateTimeZoneHandling, dateFormatString, culture, out dt)) { @@ -418,7 +421,7 @@ internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZon } #if HAVE_DATE_TIME_OFFSET - internal static bool TryParseDateTimeOffset(StringReference s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) + internal static bool TryParseDateTimeOffset(StringReference s, string? dateFormatString, CultureInfo culture, out DateTimeOffset dt) { if (s.Length > 0) { @@ -441,7 +444,7 @@ internal static bool TryParseDateTimeOffset(StringReference s, string dateFormat } } - if (!string.IsNullOrEmpty(dateFormatString)) + if (!StringUtils.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeOffsetExact(s.ToString(), dateFormatString, culture, out dt)) { @@ -454,7 +457,7 @@ internal static bool TryParseDateTimeOffset(StringReference s, string dateFormat return false; } - internal static bool TryParseDateTimeOffset(string s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt) + internal static bool TryParseDateTimeOffset(string s, string? dateFormatString, CultureInfo culture, out DateTimeOffset dt) { if (s.Length > 0) { @@ -479,7 +482,7 @@ internal static bool TryParseDateTimeOffset(string s, string dateFormatString, C } } - if (!string.IsNullOrEmpty(dateFormatString)) + if (!StringUtils.IsNullOrEmpty(dateFormatString)) { if (TryParseDateTimeOffsetExact(s, dateFormatString, culture, out dt)) { @@ -622,9 +625,9 @@ private static bool TryReadOffset(StringReference offsetText, int startIndex, ou #endregion #region Write - internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string formatString, CultureInfo culture) + internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string? formatString, CultureInfo culture) { - if (string.IsNullOrEmpty(formatString)) + if (StringUtils.IsNullOrEmpty(formatString)) { char[] chars = new char[64]; int pos = WriteDateTimeString(chars, 0, value, null, value.Kind, format); @@ -755,9 +758,9 @@ internal static int WriteDateTimeOffset(char[] chars, int start, TimeSpan offset } #if HAVE_DATE_TIME_OFFSET - internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string formatString, CultureInfo culture) + internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string? formatString, CultureInfo culture) { - if (string.IsNullOrEmpty(formatString)) + if (StringUtils.IsNullOrEmpty(formatString)) { char[] chars = new char[64]; int pos = WriteDateTimeString(chars, 0, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format); @@ -826,4 +829,4 @@ private static void GetDateValues(DateTime td, out int year, out int month, out day = n - days[m - 1] + 1; } } -} \ No newline at end of file +} diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DictionaryWrapper.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DictionaryWrapper.cs index e005c57c0..027c3a229 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DictionaryWrapper.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DictionaryWrapper.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -31,11 +34,13 @@ using System.Collections.Generic; using System.Collections; using System.Threading; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; - #endif namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities @@ -48,12 +53,12 @@ internal interface IWrappedDictionary internal class DictionaryWrapper : IDictionary, IWrappedDictionary { - private readonly IDictionary _dictionary; - private readonly IDictionary _genericDictionary; + private readonly IDictionary? _dictionary; + private readonly IDictionary? _genericDictionary; #if HAVE_READ_ONLY_COLLECTIONS - private readonly IReadOnlyDictionary _readOnlyDictionary; + private readonly IReadOnlyDictionary? _readOnlyDictionary; #endif - private object _syncRoot; + private object? _syncRoot; public DictionaryWrapper(IDictionary dictionary) { @@ -78,6 +83,15 @@ public DictionaryWrapper(IReadOnlyDictionary dictionary) } #endif + internal IDictionary GenericDictionary + { + get + { + MiscellaneousUtils.Assert(_genericDictionary != null); + return _genericDictionary; + } + } + public void Add(TKey key, TValue value) { if (_dictionary != null) @@ -108,7 +122,7 @@ public bool ContainsKey(TKey key) #endif else { - return _genericDictionary.ContainsKey(key); + return GenericDictionary.ContainsKey(key); } } @@ -128,7 +142,7 @@ public ICollection Keys #endif else { - return _genericDictionary.Keys; + return GenericDictionary.Keys; } } } @@ -155,17 +169,21 @@ public bool Remove(TKey key) #endif else { - return _genericDictionary.Remove(key); + return GenericDictionary.Remove(key); } } - public bool TryGetValue(TKey key, out TValue value) +#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). + public bool TryGetValue(TKey key, out TValue? value) +#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). { if (_dictionary != null) { if (!_dictionary.Contains(key)) { +#pragma warning disable CS8653 // A default expression introduces a null value for a type parameter. value = default; +#pragma warning restore CS8653 // A default expression introduces a null value for a type parameter. return false; } else @@ -182,7 +200,7 @@ public bool TryGetValue(TKey key, out TValue value) #endif else { - return _genericDictionary.TryGetValue(key, out value); + return GenericDictionary.TryGetValue(key, out value); } } @@ -202,7 +220,7 @@ public ICollection Values #endif else { - return _genericDictionary.Values; + return GenericDictionary.Values; } } } @@ -223,7 +241,7 @@ public TValue this[TKey key] #endif else { - return _genericDictionary[key]; + return GenericDictionary[key]; } } set @@ -240,7 +258,7 @@ public TValue this[TKey key] #endif else { - _genericDictionary[key] = value; + GenericDictionary[key] = value; } } } @@ -277,7 +295,7 @@ public void Clear() #endif else { - _genericDictionary.Clear(); + GenericDictionary.Clear(); } } @@ -295,7 +313,7 @@ public bool Contains(KeyValuePair item) #endif else { - return _genericDictionary.Contains(item); + return GenericDictionary.Contains(item); } } @@ -326,7 +344,7 @@ public void CopyTo(KeyValuePair[] array, int arrayIndex) #endif else { - _genericDictionary.CopyTo(array, arrayIndex); + GenericDictionary.CopyTo(array, arrayIndex); } } @@ -346,7 +364,7 @@ public int Count #endif else { - return _genericDictionary.Count; + return GenericDictionary.Count; } } } @@ -367,7 +385,7 @@ public bool IsReadOnly #endif else { - return _genericDictionary.IsReadOnly; + return GenericDictionary.IsReadOnly; } } } @@ -403,7 +421,7 @@ public bool Remove(KeyValuePair item) #endif else { - return _genericDictionary.Remove(item); + return GenericDictionary.Remove(item); } } @@ -421,7 +439,7 @@ public IEnumerator> GetEnumerator() #endif else { - return _genericDictionary.GetEnumerator(); + return GenericDictionary.GetEnumerator(); } } @@ -444,11 +462,11 @@ void IDictionary.Add(object key, object value) #endif else { - _genericDictionary.Add((TKey)key, (TValue)value); + GenericDictionary.Add((TKey)key, (TValue)value); } } - object IDictionary.this[object key] + object? IDictionary.this[object key] { get { @@ -464,7 +482,7 @@ object IDictionary.this[object key] #endif else { - return _genericDictionary[(TKey)key]; + return GenericDictionary[(TKey)key]; } } set @@ -481,7 +499,13 @@ object IDictionary.this[object key] #endif else { - _genericDictionary[(TKey)key] = (TValue)value; + // Consider changing this code to call GenericDictionary.Remove when value is null. + // +#pragma warning disable CS8601 // Possible null reference assignment. +#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. + GenericDictionary[(TKey)key] = (TValue)value; +#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. +#pragma warning restore CS8601 // Possible null reference assignment. } } } @@ -529,7 +553,7 @@ IDictionaryEnumerator IDictionary.GetEnumerator() #endif else { - return new DictionaryEnumerator(_genericDictionary.GetEnumerator()); + return new DictionaryEnumerator(GenericDictionary.GetEnumerator()); } } @@ -547,7 +571,7 @@ bool IDictionary.Contains(object key) #endif else { - return _dictionary.Contains(key); + return _dictionary!.Contains(key); } } @@ -567,7 +591,7 @@ bool IDictionary.IsFixedSize #endif else { - return _dictionary.IsFixedSize; + return _dictionary!.IsFixedSize; } } } @@ -588,7 +612,7 @@ ICollection IDictionary.Keys #endif else { - return _dictionary.Keys; + return _dictionary!.Keys; } } } @@ -607,7 +631,7 @@ public void Remove(object key) #endif else { - _genericDictionary.Remove((TKey)key); + GenericDictionary.Remove((TKey)key); } } @@ -627,7 +651,7 @@ ICollection IDictionary.Values #endif else { - return _dictionary.Values; + return _dictionary!.Values; } } } @@ -646,7 +670,7 @@ void ICollection.CopyTo(Array array, int index) #endif else { - _genericDictionary.CopyTo((KeyValuePair[])array, index); + GenericDictionary.CopyTo((KeyValuePair[])array, index); } } @@ -694,7 +718,7 @@ public object UnderlyingDictionary #endif else { - return _genericDictionary; + return GenericDictionary; } } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxy.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxy.cs index a5ed17178..05a1b1eed 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxy.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxy.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,19 +43,19 @@ public virtual IEnumerable GetDynamicMemberNames(T instance) return CollectionUtils.ArrayEmpty(); } - public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object result) + public virtual bool TryBinaryOperation(T instance, BinaryOperationBinder binder, object arg, out object? result) { result = null; return false; } - public virtual bool TryConvert(T instance, ConvertBinder binder, out object result) + public virtual bool TryConvert(T instance, ConvertBinder binder, out object? result) { result = null; return false; } - public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object result) + public virtual bool TryCreateInstance(T instance, CreateInstanceBinder binder, object[] args, out object? result) { result = null; return false; @@ -68,25 +71,25 @@ public virtual bool TryDeleteMember(T instance, DeleteMemberBinder binder) return false; } - public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object result) + public virtual bool TryGetIndex(T instance, GetIndexBinder binder, object[] indexes, out object? result) { result = null; return false; } - public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object result) + public virtual bool TryGetMember(T instance, GetMemberBinder binder, out object? result) { result = null; return false; } - public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object result) + public virtual bool TryInvoke(T instance, InvokeBinder binder, object[] args, out object? result) { result = null; return false; } - public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object result) + public virtual bool TryInvokeMember(T instance, InvokeMemberBinder binder, object[] args, out object? result) { result = null; return false; @@ -102,7 +105,7 @@ public virtual bool TrySetMember(T instance, SetMemberBinder binder, object valu return false; } - public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object result) + public virtual bool TryUnaryOperation(T instance, UnaryOperationBinder binder, out object? result) { result = null; return false; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index 470b2e4e0..f58b1f7f8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -168,7 +171,7 @@ public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, Dyna : base.BindDeleteIndex(binder, indexes); } - private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); + private delegate DynamicMetaObject Fallback(DynamicMetaObject? errorSuggestion); private static Expression[] NoArgs => CollectionUtils.ArrayEmpty(); @@ -210,7 +213,7 @@ private static ConstantExpression Constant(DynamicMetaObjectBinder binder) /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// - private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, Fallback fallback, Fallback fallbackInvoke = null) + private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, Fallback fallback, Fallback? fallbackInvoke = null) { // // First, call fallback to do default binding @@ -221,7 +224,7 @@ private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObj return BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); } - private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) + private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, IEnumerable args, DynamicMetaObject fallbackResult, Fallback? fallbackInvoke) { // // Build a new expression like: diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index 58212a6ce..976109866 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -44,7 +47,7 @@ internal class DynamicReflectionDelegateFactory : ReflectionDelegateFactory { internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory(); - private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) + private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, Type[] parameterTypes, Type owner) { DynamicMethod dynamicMethod = !owner.IsInterface() ? new DynamicMethod(name, returnType, parameterTypes, owner, true) @@ -63,14 +66,14 @@ public override ObjectConstructor CreateParameterizedConstructor(MethodB return (ObjectConstructor)dynamicMethod.CreateDelegate(typeof(ObjectConstructor)); } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateMethodCallIL(method, generator, 1); - return (MethodCall)dynamicMethod.CreateDelegate(typeof(MethodCall)); + return (MethodCall)dynamicMethod.CreateDelegate(typeof(MethodCall)); } private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator, int argsIndex) @@ -97,6 +100,9 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator LocalBuilder localConvertible = generator.DeclareLocal(typeof(IConvertible)); LocalBuilder localObject = generator.DeclareLocal(typeof(object)); + OpCode variableAddressOpCode = args.Length < 256 ? OpCodes.Ldloca_S : OpCodes.Ldloca; + OpCode variableLoadOpCode = args.Length < 256 ? OpCodes.Ldloc_S : OpCodes.Ldloc; + for (int i = 0; i < args.Length; i++) { ParameterInfo parameter = args[i]; @@ -122,7 +128,7 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator generator.Emit(OpCodes.Brtrue_S, skipSettingDefault); // parameter has no value, initialize to default - generator.Emit(OpCodes.Ldloca_S, localVariable); + generator.Emit(variableAddressOpCode, localVariable); generator.Emit(OpCodes.Initobj, parameterType); generator.Emit(OpCodes.Br_S, finishedProcessingParameter); @@ -142,7 +148,7 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator } } - generator.Emit(OpCodes.Ldloca_S, localVariable); + generator.Emit(variableAddressOpCode, localVariable); } else if (parameterType.IsValueType()) { @@ -160,9 +166,9 @@ private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator // parameter has no value, initialize to default LocalBuilder localVariable = generator.DeclareLocal(parameterType); - generator.Emit(OpCodes.Ldloca_S, localVariable); + generator.Emit(variableAddressOpCode, localVariable); generator.Emit(OpCodes.Initobj, parameterType); - generator.Emit(OpCodes.Ldloc_S, localVariable); + generator.Emit(variableLoadOpCode, localVariable); generator.Emit(OpCodes.Br_S, finishedProcessingParameter); // argument has value, try to convert it to parameter type @@ -283,14 +289,14 @@ private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator generator.Return(); } - public override System.Func CreateGet(PropertyInfo propertyInfo) + public override System.Func CreateGet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateGetPropertyIL(propertyInfo, generator); - return (System.Func)dynamicMethod.CreateDelegate(typeof(System.Func)); + return (System.Func)dynamicMethod.CreateDelegate(typeof(System.Func)); } private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) @@ -311,12 +317,12 @@ private void GenerateCreateGetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator.Return(); } - public override System.Func CreateGet(FieldInfo fieldInfo) + public override System.Func CreateGet(FieldInfo fieldInfo) { if (fieldInfo.IsLiteral) { object constantValue = fieldInfo.GetValue(null); - System.Func getter = o => constantValue; + System.Func getter = o => constantValue; return getter; } @@ -325,7 +331,7 @@ public override System.Func CreateGet(FieldInfo fieldInfo) GenerateCreateGetFieldIL(fieldInfo, generator); - return (System.Func)dynamicMethod.CreateDelegate(typeof(System.Func)); + return (System.Func)dynamicMethod.CreateDelegate(typeof(System.Func)); } private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator) @@ -344,14 +350,14 @@ private void GenerateCreateGetFieldIL(FieldInfo fieldInfo, ILGenerator generator generator.Return(); } - public override System.Action CreateSet(FieldInfo fieldInfo) + public override System.Action CreateSet(FieldInfo fieldInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetFieldIL(fieldInfo, generator); - return (System.Action)dynamicMethod.CreateDelegate(typeof(System.Action)); + return (System.Action)dynamicMethod.CreateDelegate(typeof(System.Action)); } internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator generator) @@ -376,14 +382,14 @@ internal static void GenerateCreateSetFieldIL(FieldInfo fieldInfo, ILGenerator g generator.Return(); } - public override System.Action CreateSet(PropertyInfo propertyInfo) + public override System.Action CreateSet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType); ILGenerator generator = dynamicMethod.GetILGenerator(); GenerateCreateSetPropertyIL(propertyInfo, generator); - return (System.Action)dynamicMethod.CreateDelegate(typeof(System.Action)); + return (System.Action)dynamicMethod.CreateDelegate(typeof(System.Action)); } internal static void GenerateCreateSetPropertyIL(PropertyInfo propertyInfo, ILGenerator generator) diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicUtils.cs index 7c8be7d60..a57b647ad 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -42,6 +45,7 @@ using System.Text; using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { @@ -57,10 +61,10 @@ internal static class BinderWrapper private const string CSharpArgumentInfoFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, " + CSharpAssemblyName; private const string CSharpBinderFlagsTypeName = "Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, " + CSharpAssemblyName; - private static object _getCSharpArgumentInfoArray; - private static object _setCSharpArgumentInfoArray; - private static MethodCall _getMemberCall; - private static MethodCall _setMemberCall; + private static object? _getCSharpArgumentInfoArray; + private static object? _setCSharpArgumentInfoArray; + private static MethodCall? _getMemberCall; + private static MethodCall? _setMemberCall; private static bool _init; private static void Init() @@ -93,7 +97,7 @@ private static object CreateSharpArgumentInfoArray(params int[] values) for (int i = 0; i < values.Length; i++) { MethodInfo createArgumentInfoMethod = csharpArgumentInfoType.GetMethod("Create", new[] { csharpArgumentInfoFlags, typeof(string) }); - object arg = createArgumentInfoMethod.Invoke(null, new object[] { 0, null }); + object arg = createArgumentInfoMethod.Invoke(null, new object?[] { 0, null }); a.SetValue(arg, i); } @@ -109,10 +113,10 @@ private static void CreateMemberCalls() Type csharpArgumentInfoTypeEnumerableType = typeof(IEnumerable<>).MakeGenericType(csharpArgumentInfoType); MethodInfo getMemberMethod = binderType.GetMethod("GetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); - _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); + _getMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getMemberMethod); MethodInfo setMemberMethod = binderType.GetMethod("SetMember", new[] { csharpBinderFlagsType, typeof(string), typeof(Type), csharpArgumentInfoTypeEnumerableType }); - _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); + _setMemberCall = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(setMemberMethod); } #endif @@ -120,7 +124,9 @@ public static CallSiteBinder GetMember(string name, Type context) { #if !HAVE_REFLECTION_BINDER Init(); - return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray); + MiscellaneousUtils.Assert(_getMemberCall != null); + MiscellaneousUtils.Assert(_getCSharpArgumentInfoArray != null); + return (CallSiteBinder)_getMemberCall(null, 0, name, context, _getCSharpArgumentInfoArray)!; #else return Binder.GetMember( CSharpBinderFlags.None, name, context, new[] {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); @@ -131,7 +137,9 @@ public static CallSiteBinder SetMember(string name, Type context) { #if !HAVE_REFLECTION_BINDER Init(); - return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray); + MiscellaneousUtils.Assert(_setMemberCall != null); + MiscellaneousUtils.Assert(_setCSharpArgumentInfoArray != null); + return (CallSiteBinder)_setMemberCall(null, 0, name, context, _setCSharpArgumentInfoArray)!; #else return Binder.SetMember( CSharpBinderFlags.None, name, context, new[] diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumInfo.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumInfo.cs index 7ec13f44c..3706d1b49 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumInfo.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumInfo.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumUtils.cs index 8f55739c8..5ef75bbab 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,6 +43,8 @@ using System.Reflection; using System.Text; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { @@ -48,27 +53,30 @@ internal static class EnumUtils private const char EnumSeparatorChar = ','; private const string EnumSeparatorString = ", "; - private static readonly ThreadSafeStore, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore, EnumInfo>(InitializeValuesAndNames); + private static readonly ThreadSafeStore, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore, EnumInfo>(InitializeValuesAndNames); - private static EnumInfo InitializeValuesAndNames(StructMultiKey key) + private static EnumInfo InitializeValuesAndNames(StructMultiKey key) { Type enumType = key.Value1; string[] names = Enum.GetNames(enumType); string[] resolvedNames = new string[names.Length]; ulong[] values = new ulong[names.Length]; + bool hasSpecifiedName; for (int i = 0; i < names.Length; i++) { string name = names[i]; - FieldInfo f = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + FieldInfo f = enumType.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; values[i] = ToUInt64(f.GetValue(null)); string resolvedName; #if HAVE_DATA_CONTRACTS - resolvedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) + string specifiedName = f.GetCustomAttributes(typeof(EnumMemberAttribute), true) .Cast() .Select(a => a.Value) - .SingleOrDefault() ?? f.Name; + .SingleOrDefault(); + hasSpecifiedName = specifiedName != null; + resolvedName = specifiedName ?? name; if (Array.IndexOf(resolvedNames, resolvedName, 0, i) != -1) { @@ -76,10 +84,11 @@ private static EnumInfo InitializeValuesAndNames(StructMultiKey GetFlagsValues(T value) where T : struct // Used by Newtonsoft.Json.Schema private static CamelCaseNamingStrategy _camelCaseNamingStrategy = new CamelCaseNamingStrategy(); - public static bool TryToString(Type enumType, object value, bool camelCase, out string name) + public static bool TryToString(Type enumType, object value, bool camelCase, [NotNullWhen(true)]out string? name) { return TryToString(enumType, value, camelCase ? _camelCaseNamingStrategy : null, out name); } - public static bool TryToString(Type enumType, object value, NamingStrategy namingStrategy, out string name) + public static bool TryToString(Type enumType, object value, NamingStrategy? namingStrategy, [NotNullWhen(true)]out string? name) { - EnumInfo enumInfo = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); + EnumInfo enumInfo = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); ulong v = ToUInt64(value); if (!enumInfo.IsFlags) @@ -153,7 +162,7 @@ public static bool TryToString(Type enumType, object value, NamingStrategy namin } } - private static string InternalFlagsFormat(EnumInfo entry, ulong result) + private static string? InternalFlagsFormat(EnumInfo entry, ulong result) { string[] resolvedNames = entry.ResolvedNames; ulong[] values = entry.Values; @@ -189,7 +198,7 @@ private static string InternalFlagsFormat(EnumInfo entry, ulong result) index--; } - string returnString; + string? returnString; if (result != 0) { // We were unable to represent this number as a bitwise or of valid flags @@ -217,7 +226,7 @@ private static string InternalFlagsFormat(EnumInfo entry, ulong result) public static EnumInfo GetEnumValuesAndNames(Type enumType) { - return ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, null)); + return ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, null)); } private static ulong ToUInt64(object value) @@ -253,7 +262,7 @@ private static ulong ToUInt64(object value) } } - public static object ParseEnum(Type enumType, NamingStrategy namingStrategy, string value, bool disallowNumber) + public static object ParseEnum(Type enumType, NamingStrategy? namingStrategy, string value, bool disallowNumber) { ValidationUtils.ArgumentNotNull(enumType, nameof(enumType)); ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -263,7 +272,7 @@ public static object ParseEnum(Type enumType, NamingStrategy namingStrategy, str throw new ArgumentException("Type provided must be an Enum.", nameof(enumType)); } - EnumInfo entry = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); + EnumInfo entry = ValuesAndNamesPerEnum.Get(new StructMultiKey(enumType, namingStrategy)); string[] enumNames = entry.Names; string[] resolvedNames = entry.ResolvedNames; ulong[] enumValues = entry.Values; @@ -296,7 +305,7 @@ public static object ParseEnum(Type enumType, NamingStrategy namingStrategy, str Type underlyingType = Enum.GetUnderlyingType(enumType); value = value.Trim(); - object temp = null; + object? temp = null; try { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 355e6f951..283aa7cfd 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -61,7 +64,7 @@ public override ObjectConstructor CreateParameterizedConstructor(MethodB return compiled; } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -74,7 +77,7 @@ public override MethodCall CreateMethodCall(MethodBase method) LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall), callExpression, targetParameterExpression, argsParameterExpression); - MethodCall compiled = (MethodCall)lambdaExpression.Compile(); + MethodCall compiled = (MethodCall)lambdaExpression.Compile(); return compiled; } @@ -83,9 +86,16 @@ private class ByRefParameter public Expression Value; public ParameterExpression Variable; public bool IsOut; + + public ByRefParameter(Expression value, ParameterExpression variable, bool isOut) + { + Value = value; + Variable = variable; + IsOut = isOut; + } } - private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression) + private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression? targetParameterExpression, ParameterExpression argsParameterExpression) { ParameterInfo[] parametersInfo = method.GetParameters(); @@ -121,7 +131,7 @@ private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpres if (isByRef) { ParameterExpression variable = Expression.Variable(parameterType); - refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut}); + refParameterMap.Add(new ByRefParameter(argExpression, variable, parameter.IsOut)); argExpression = variable; } @@ -141,7 +151,7 @@ private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpres } else { - Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType); + Expression readParameter = EnsureCastExpression(targetParameterExpression!, method.DeclaringType); callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression); } @@ -215,7 +225,7 @@ public override System.Func CreateDefaultConstructor(Type type) } } - public override System.Func CreateGet(PropertyInfo propertyInfo) + public override System.Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -225,7 +235,11 @@ public override System.Func CreateGet(PropertyInfo propertyInfo) ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance"); Expression resultExpression; - MethodInfo getMethod = propertyInfo.GetGetMethod(true); + MethodInfo? getMethod = propertyInfo.GetGetMethod(true); + if (getMethod == null) + { + throw new ArgumentException("Property does not have a getter."); + } if (getMethod.IsStatic) { @@ -242,11 +256,11 @@ public override System.Func CreateGet(PropertyInfo propertyInfo) LambdaExpression lambdaExpression = Expression.Lambda(typeof(System.Func), resultExpression, parameterExpression); - System.Func compiled = (System.Func)lambdaExpression.Compile(); + System.Func compiled = (System.Func)lambdaExpression.Compile(); return compiled; } - public override System.Func CreateGet(FieldInfo fieldInfo) + public override System.Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -266,11 +280,11 @@ public override System.Func CreateGet(FieldInfo fieldInfo) fieldExpression = EnsureCastExpression(fieldExpression, typeof(object)); - System.Func compiled = Expression.Lambda>(fieldExpression, sourceParameter).Compile(); + System.Func compiled = Expression.Lambda>(fieldExpression, sourceParameter).Compile(); return compiled; } - public override System.Action CreateSet(FieldInfo fieldInfo) + public override System.Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -302,11 +316,11 @@ public override System.Action CreateSet(FieldInfo fieldInfo) LambdaExpression lambdaExpression = Expression.Lambda(typeof(System.Action), assignExpression, sourceParameterExpression, valueParameterExpression); - System.Action compiled = (System.Action)lambdaExpression.Compile(); + System.Action compiled = (System.Action)lambdaExpression.Compile(); return compiled; } - public override System.Action CreateSet(PropertyInfo propertyInfo) + public override System.Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -325,7 +339,11 @@ public override System.Action CreateSet(PropertyInfo propertyInfo) ParameterExpression valueParameter = Expression.Parameter(valueType, "value"); Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType); - MethodInfo setMethod = propertyInfo.GetSetMethod(true); + MethodInfo? setMethod = propertyInfo.GetSetMethod(true); + if (setMethod == null) + { + throw new ArgumentException("Property does not have a setter."); + } Expression setExpression; if (setMethod.IsStatic) @@ -339,9 +357,9 @@ public override System.Action CreateSet(PropertyInfo propertyInfo) setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter); } - LambdaExpression lambdaExpression = Expression.Lambda(typeof(System.Action), setExpression, instanceParameter, valueParameter); + LambdaExpression lambdaExpression = Expression.Lambda(typeof(System.Action), setExpression, instanceParameter, valueParameter); - System.Action compiled = (System.Action)lambdaExpression.Compile(); + System.Action compiled = (System.Action)lambdaExpression.Compile(); return compiled; } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/FSharpUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/FSharpUtils.cs index 8612e0452..19f66116f 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -35,15 +38,16 @@ using System.Reflection; using System.Text; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; +using System.Diagnostics; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { internal class FSharpFunction { - private readonly object _instance; - private readonly MethodCall _invoker; + private readonly object? _instance; + private readonly MethodCall _invoker; - public FSharpFunction(object instance, MethodCall invoker) + public FSharpFunction(object? instance, MethodCall invoker) { _instance = instance; _invoker = invoker; @@ -57,69 +61,78 @@ public object Invoke(params object[] args) } } - internal static class FSharpUtils + internal class FSharpUtils { - private static readonly object Lock = new object(); + private FSharpUtils(Assembly fsharpCoreAssembly) + { + FSharpCoreAssembly = fsharpCoreAssembly; - private static bool _initialized; - private static MethodInfo _ofSeq; - private static Type _mapType; - - public static Assembly FSharpCoreAssembly { get; private set; } - public static MethodCall IsUnion { get; private set; } - public static MethodCall GetUnionCases { get; private set; } - public static MethodCall PreComputeUnionTagReader { get; private set; } - public static MethodCall PreComputeUnionReader { get; private set; } - public static MethodCall PreComputeUnionConstructor { get; private set; } - public static System.Func GetUnionCaseInfoDeclaringType { get; private set; } - public static System.Func GetUnionCaseInfoName { get; private set; } - public static System.Func GetUnionCaseInfoTag { get; private set; } - public static MethodCall GetUnionCaseInfoFields { get; private set; } + Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); - public const string FSharpSetTypeName = "FSharpSet`1"; - public const string FSharpListTypeName = "FSharpList`1"; - public const string FSharpMapTypeName = "FSharpMap`2"; + MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); + IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo)!; - public static void EnsureInitialized(Assembly fsharpCoreAssembly) - { - if (!_initialized) - { - lock (Lock) - { - if (!_initialized) - { - FSharpCoreAssembly = fsharpCoreAssembly; + MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); + GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo)!; - Type fsharpType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpType"); + Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); - MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static); - IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(isUnionMethodInfo); + PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); + PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); + PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); - MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static); - GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(getUnionCasesMethodInfo); + Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); - Type fsharpValue = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.FSharpValue"); + GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")!)!; + GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")!)!; + GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")!)!; + GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + + Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); + _ofSeq = listModule.GetMethod("OfSeq"); + + _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + } - PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader"); - PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader"); - PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor"); + private static readonly object Lock = new object(); + private static FSharpUtils? _instance; - Type unionCaseInfo = fsharpCoreAssembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo"); + public static FSharpUtils Instance + { + get + { + MiscellaneousUtils.Assert(_instance != null); + return _instance; + } + } - GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Name")); - GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("Tag")); - GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet(unionCaseInfo.GetProperty("DeclaringType")); - GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(unionCaseInfo.GetMethod("GetFields")); + private MethodInfo _ofSeq; + private Type _mapType; - Type listModule = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.ListModule"); - _ofSeq = listModule.GetMethod("OfSeq"); + public Assembly FSharpCoreAssembly { get; private set; } + public MethodCall IsUnion { get; private set; } + public MethodCall GetUnionCases { get; private set; } + public MethodCall PreComputeUnionTagReader { get; private set; } + public MethodCall PreComputeUnionReader { get; private set; } + public MethodCall PreComputeUnionConstructor { get; private set; } + public System.Func GetUnionCaseInfoDeclaringType { get; private set; } + public System.Func GetUnionCaseInfoName { get; private set; } + public System.Func GetUnionCaseInfoTag { get; private set; } + public MethodCall GetUnionCaseInfoFields { get; private set; } - _mapType = fsharpCoreAssembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2"); + public const string FSharpSetTypeName = "FSharpSet`1"; + public const string FSharpListTypeName = "FSharpList`1"; + public const string FSharpMapTypeName = "FSharpMap`2"; -#if HAVE_MEMORY_BARRIER - Thread.MemoryBarrier(); -#endif - _initialized = true; + public static void EnsureInitialized(Assembly fsharpCoreAssembly) + { + if (_instance == null) + { + lock (Lock) + { + if (_instance == null) + { + _instance = new FSharpUtils(fsharpCoreAssembly); } } } @@ -138,20 +151,20 @@ private static MethodInfo GetMethodWithNonPublicFallback(Type type, string metho methodInfo = type.GetMethod(methodName, bindingFlags | BindingFlags.NonPublic); } - return methodInfo; + return methodInfo!; } - private static MethodCall CreateFSharpFuncCall(Type type, string methodName) + private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); MethodInfo invokeFunc = innerMethodInfo.ReturnType.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance); - MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); - MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc); + MethodCall call = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(innerMethodInfo); + MethodCall invoke = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall(invokeFunc)!; - MethodCall createFunction = (target, args) => + MethodCall createFunction = (target, args) => { - object result = call(target, args); + object? result = call(target, args); FSharpFunction f = new FSharpFunction(result, invoke); return f; @@ -160,23 +173,23 @@ private static MethodCall CreateFSharpFuncCall(Type type, string return createFunction; } - public static ObjectConstructor CreateSeq(Type t) + public ObjectConstructor CreateSeq(Type t) { MethodInfo seqType = _ofSeq.MakeGenericMethod(t); return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType); } - public static ObjectConstructor CreateMap(Type keyType, Type valueType) + public ObjectConstructor CreateMap(Type keyType, Type valueType) { MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator"); MethodInfo creatorGeneric = creatorDefinition.MakeGenericMethod(keyType, valueType); - return (ObjectConstructor)creatorGeneric.Invoke(null, null); + return (ObjectConstructor)creatorGeneric.Invoke(this, null); } - public static ObjectConstructor BuildMapCreator() + public ObjectConstructor BuildMapCreator() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); ConstructorInfo ctor = genericMapType.GetConstructor(new[] { typeof(IEnumerable>) }); @@ -185,7 +198,7 @@ public static ObjectConstructor BuildMapCreator() ObjectConstructor creator = args => { // convert dictionary KeyValuePairs to Tuples - IEnumerable> values = (IEnumerable>)args[0]; + IEnumerable> values = (IEnumerable>)args[0]!; IEnumerable> tupleValues = values.Select(kv => new Tuple(kv.Key, kv.Value)); return ctorDelegate(tupleValues); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs index 171e5961d..473d84ef5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ILGeneratorExtensions.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index 73b257b09..05fa16fcd 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -29,12 +32,14 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using System.Reflection; +using System.Runtime.CompilerServices; using System.Text; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; @@ -92,7 +97,7 @@ public ImmutableCollectionTypeInfo(string contractTypeName, string createdTypeNa new ImmutableCollectionTypeInfo(ImmutableQueueGenericTypeName, ImmutableQueueGenericTypeName, ImmutableQueueTypeName), new ImmutableCollectionTypeInfo(ImmutableStackGenericInterfaceTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), new ImmutableCollectionTypeInfo(ImmutableStackGenericTypeName, ImmutableStackGenericTypeName, ImmutableStackTypeName), - new ImmutableCollectionTypeInfo(ImmutableSetGenericInterfaceTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), + new ImmutableCollectionTypeInfo(ImmutableSetGenericInterfaceTypeName, ImmutableHashSetGenericTypeName, ImmutableHashSetTypeName), new ImmutableCollectionTypeInfo(ImmutableSortedSetGenericTypeName, ImmutableSortedSetGenericTypeName, ImmutableSortedSetTypeName), new ImmutableCollectionTypeInfo(ImmutableHashSetGenericTypeName, ImmutableHashSetGenericTypeName, ImmutableHashSetTypeName), new ImmutableCollectionTypeInfo(ImmutableArrayGenericTypeName, ImmutableArrayGenericTypeName, ImmutableArrayTypeName) @@ -108,12 +113,12 @@ public ImmutableCollectionTypeInfo(string contractTypeName, string createdTypeNa private static readonly IList DictionaryContractImmutableCollectionDefinitions = new List { - new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericInterfaceTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), + new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericInterfaceTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName), new ImmutableCollectionTypeInfo(ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryGenericTypeName, ImmutableSortedDictionaryTypeName), new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName) }; - internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor parameterizedCreator) + internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) { if (underlyingType.IsGenericType()) { @@ -145,7 +150,7 @@ internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type return false; } - internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor parameterizedCreator) + internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) { if (underlyingType.IsGenericType()) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JavaScriptUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JavaScriptUtils.cs index 731f280c5..1da91fc67 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JavaScriptUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JavaScriptUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -35,6 +38,8 @@ #endif using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -45,7 +50,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { internal static class BufferUtils { - public static char[] RentBuffer(IArrayPool bufferPool, int minSize) + public static char[] RentBuffer(IArrayPool? bufferPool, int minSize) { if (bufferPool == null) { @@ -56,12 +61,12 @@ public static char[] RentBuffer(IArrayPool bufferPool, int minSize) return buffer; } - public static void ReturnBuffer(IArrayPool bufferPool, char[] buffer) + public static void ReturnBuffer(IArrayPool? bufferPool, char[]? buffer) { bufferPool?.Return(buffer); } - public static char[] EnsureBufferSize(IArrayPool bufferPool, int size, char[] buffer) + public static char[] EnsureBufferSize(IArrayPool? bufferPool, int size, char[]? buffer) { if (bufferPool == null) { @@ -127,15 +132,16 @@ public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandlin return SingleQuoteCharEscapeFlags; } - public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) + public static bool ShouldEscapeJavaScriptString(string? s, bool[] charEscapeFlags) { if (s == null) { return false; } - foreach (char c in s) + for (int i = 0; i < s.Length; i++) { + char c = s[i]; if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; @@ -145,8 +151,8 @@ public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags return false; } - public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, - bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool bufferPool, ref char[] writeBuffer) + public static void WriteEscapedJavaScriptString(TextWriter writer, string? s, char delimiter, bool appendDelimiters, + bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool? bufferPool, ref char[]? writeBuffer) { // leading delimiter if (appendDelimiters) @@ -154,7 +160,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha writer.Write(delimiter); } - if (!string.IsNullOrEmpty(s)) + if (!StringUtils.IsNullOrEmpty(s)) { int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); if (lastWritePosition == -1) @@ -185,7 +191,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha continue; } - string escapedValue; + string? escapedValue; switch (c) { @@ -234,7 +240,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } - StringUtils.ToCharAsUnicode(c, writeBuffer); + StringUtils.ToCharAsUnicode(c, writeBuffer!); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; @@ -252,7 +258,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha continue; } - bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); + bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText, StringComparison.Ordinal); if (i > lastWritePosition) { @@ -267,7 +273,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha // copy it over when creating new buffer if (isEscapedUnicodeText) { - Debug.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); + MiscellaneousUtils.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } @@ -294,7 +300,7 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha } } - Debug.Assert(lastWritePosition != 0); + MiscellaneousUtils.Assert(lastWritePosition != 0); length = s.Length - lastWritePosition; if (length > 0) { @@ -318,13 +324,13 @@ public static void WriteEscapedJavaScriptString(TextWriter writer, string s, cha } } - public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) + public static string ToEscapedJavaScriptString(string? value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { - char[] buffer = null; + char[]? buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } @@ -375,7 +381,7 @@ public static Task WriteEscapedJavaScriptStringAsync(TextWriter writer, string s return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask; } @@ -392,7 +398,7 @@ private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter w return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } - if (!string.IsNullOrEmpty(s)) + if (!StringUtils.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); if (task.IsCompletedSucessfully()) @@ -410,7 +416,7 @@ private static async Task WriteEscapedJavaScriptStringWithDelimitersAsync(Task t { await task.ConfigureAwait(false); - if (!string.IsNullOrEmpty(s)) + if (!StringUtils.IsNullOrEmpty(s)) { await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false); } @@ -454,7 +460,7 @@ private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimiter int length; bool isEscapedUnicodeText = false; - string escapedValue = null; + string? escapedValue = null; for (int i = lastWritePosition; i < s.Length; i++) { @@ -543,7 +549,7 @@ private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimiter lastWritePosition = i + 1; if (!isEscapedUnicodeText) { - await writer.WriteAsync(escapedValue, cancellationToken).ConfigureAwait(false); + await writer.WriteAsync(escapedValue!, cancellationToken).ConfigureAwait(false); } else { @@ -569,7 +575,7 @@ private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimiter } #endif - public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, out string errorMessage) + public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, [NotNullWhen(false)]out string? errorMessage) { dateTime = default; errorMessage = null; @@ -630,7 +636,7 @@ public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime return true; } - private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, out string errorMessage) + private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, [NotNullWhen(false)] out string? errorMessage) { integer = null; errorMessage = null; @@ -650,7 +656,7 @@ private static bool TryGetDateConstructorValue(JsonReader reader, out long? inte return false; } - integer = (long)reader.Value; + integer = (long)reader.Value!; return true; } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JsonTokenUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JsonTokenUtils.cs index e31d78c36..7b27f9479 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JsonTokenUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/JsonTokenUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 6bd356e0b..4a4b40408 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -51,17 +54,13 @@ public override ObjectConstructor CreateParameterizedConstructor(MethodB { // don't convert to method group to avoid medium trust issues // https://github.com/JamesNK/Newtonsoft.Json/issues/476 - return a => - { - object[] args = a; - return c.Invoke(args); - }; + return a => c.Invoke(a); } return a => method.Invoke(null, a); } - public override MethodCall CreateMethodCall(MethodBase method) + public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -87,28 +86,28 @@ public override System.Func CreateDefaultConstructor(Type type) return () => (T)constructorInfo.Invoke(null); } - public override System.Func CreateGet(PropertyInfo propertyInfo) + public override System.Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); return o => propertyInfo.GetValue(o, null); } - public override System.Func CreateGet(FieldInfo fieldInfo) + public override System.Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); return o => fieldInfo.GetValue(o); } - public override System.Action CreateSet(FieldInfo fieldInfo) + public override System.Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); return (o, v) => fieldInfo.SetValue(o, v); } - public override System.Action CreateSet(PropertyInfo propertyInfo) + public override System.Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LinqBridge.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LinqBridge.cs index 0088bb589..fa3e887c5 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LinqBridge.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/LinqBridge.cs @@ -2,6 +2,8 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 #if !HAVE_LINQ @@ -39,6 +41,8 @@ using System.Globalization; using Datadog.Trace.Vendors.Newtonsoft.Json.Serialization; +#nullable disable + namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge { /// @@ -379,7 +383,7 @@ private static TSource FirstImpl( System.Func empty) { CheckNotNull(source, "source"); - Debug.Assert(empty != null); + MiscellaneousUtils.Assert(empty != null); var list = source as IList; // optimized case for lists if (list != null) @@ -1366,7 +1370,7 @@ private static TSource MinMaxImpl( System.Func lesser) { CheckNotNull(source, "source"); - Debug.Assert(lesser != null); + MiscellaneousUtils.Assert(lesser != null); return source.Aggregate((a, item) => lesser(a, item) ? a : item); } @@ -1380,7 +1384,7 @@ private static TSource MinMaxImpl( TSource? seed, System.Func lesser) where TSource : struct { CheckNotNull(source, "source"); - Debug.Assert(lesser != null); + MiscellaneousUtils.Assert(lesser != null); return source.Aggregate(seed, (a, item) => lesser(a, item) ? a : item); // == MinMaxImpl(Repeat(null, 1).Concat(source), lesser); @@ -1444,7 +1448,7 @@ public static TResult Max( private static IEnumerable Renumerable(this IEnumerator e) { - Debug.Assert(e != null); + MiscellaneousUtils.Assert(e != null); do { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MathUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MathUtils.cs index 85fb8b70f..5bc0f32b0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MathUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MathUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodBinder.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodBinder.cs index f82d83d35..d79b2fea2 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodBinder.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodBinder.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -130,7 +133,7 @@ private static bool FilterParameters(ParameterInfo[] parameters, IList typ } // check if the last parameter is ParamArray - Type paramArrayType = null; + Type? paramArrayType = null; if (enableParamArray) { @@ -215,7 +218,7 @@ public int Compare(ParameterInfo[] parameters1, ParameterInfo[] parameters2) return 1; } - Type paramArrayType1 = null, paramArrayType2 = null; + Type? paramArrayType1 = null, paramArrayType2 = null; if (_enableParamArray) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodCall.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodCall.cs index 4a55dbdb7..57812e9b3 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodCall.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MethodCall.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -29,5 +32,5 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { - internal delegate TResult MethodCall(T target, params object[] args); + internal delegate TResult MethodCall(T target, params object?[] args); } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index 6abab3e04..29ce4558d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -35,6 +38,8 @@ using System.Text; using System.Globalization; using System.Text.RegularExpressions; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { @@ -42,7 +47,13 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities internal static class MiscellaneousUtils { - public static bool ValueEquals(object objA, object objB) + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) + { + Debug.Assert(condition, message); + } + + public static bool ValueEquals(object? objA, object? objB) { if (objA == objB) { @@ -81,14 +92,14 @@ public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(stri return new ArgumentOutOfRangeException(paramName, newMessage); } - public static string ToString(object value) + public static string ToString(object? value) { if (value == null) { return "{null}"; } - return (value is string s) ? @"""" + s + @"""" : value.ToString(); + return (value is string s) ? @"""" + s + @"""" : value!.ToString(); } public static int ByteArrayCompare(byte[] a1, byte[] a2) @@ -111,9 +122,9 @@ public static int ByteArrayCompare(byte[] a1, byte[] a2) return 0; } - public static string GetPrefix(string qualifiedName) + public static string? GetPrefix(string qualifiedName) { - GetQualifiedNameParts(qualifiedName, out string prefix, out _); + GetQualifiedNameParts(qualifiedName, out string? prefix, out _); return prefix; } @@ -125,7 +136,7 @@ public static string GetLocalName(string qualifiedName) return localName; } - public static void GetQualifiedNameParts(string qualifiedName, out string prefix, out string localName) + public static void GetQualifiedNameParts(string qualifiedName, out string? prefix, out string localName) { int colonPosition = qualifiedName.IndexOf(':'); @@ -144,9 +155,10 @@ public static void GetQualifiedNameParts(string qualifiedName, out string prefix internal static RegexOptions GetRegexOptions(string optionsText) { RegexOptions options = RegexOptions.None; - foreach (char c in optionsText) + + for (int i = 0; i < optionsText.Length; i++) { - switch (c) + switch (optionsText[i]) { case 'i': options |= RegexOptions.IgnoreCase; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs index 0973600e8..d4d6bc08a 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -40,7 +43,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { internal abstract class ReflectionDelegateFactory { - public System.Func CreateGet(MemberInfo memberInfo) + public System.Func CreateGet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -61,7 +64,7 @@ public System.Func CreateGet(MemberInfo memberInfo) throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } - public System.Action CreateSet(MemberInfo memberInfo) + public System.Action CreateSet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -76,12 +79,12 @@ public System.Action CreateSet(MemberInfo memberInfo) throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } - public abstract MethodCall CreateMethodCall(MethodBase method); + public abstract MethodCall CreateMethodCall(MethodBase method); public abstract ObjectConstructor CreateParameterizedConstructor(MethodBase method); public abstract System.Func CreateDefaultConstructor(Type type); - public abstract System.Func CreateGet(PropertyInfo propertyInfo); - public abstract System.Func CreateGet(FieldInfo fieldInfo); - public abstract System.Action CreateSet(FieldInfo fieldInfo); - public abstract System.Action CreateSet(PropertyInfo propertyInfo); + public abstract System.Func CreateGet(PropertyInfo propertyInfo); + public abstract System.Func CreateGet(FieldInfo fieldInfo); + public abstract System.Action CreateSet(FieldInfo fieldInfo); + public abstract System.Action CreateSet(PropertyInfo propertyInfo); } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionObject.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionObject.cs index 5450759f7..4a18e5ce0 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionObject.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionObject.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -43,37 +46,37 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { internal class ReflectionMember { - public Type MemberType { get; set; } - public System.Func Getter { get; set; } - public System.Action Setter { get; set; } + public Type? MemberType { get; set; } + public System.Func? Getter { get; set; } + public System.Action? Setter { get; set; } } internal class ReflectionObject { - public ObjectConstructor Creator { get; } + public ObjectConstructor? Creator { get; } public IDictionary Members { get; } - private ReflectionObject(ObjectConstructor creator) + private ReflectionObject(ObjectConstructor? creator) { Members = new Dictionary(); Creator = creator; } - public object GetValue(object target, string member) + public object? GetValue(object target, string member) { - System.Func getter = Members[member].Getter; + System.Func getter = Members[member].Getter!; return getter(target); } - public void SetValue(object target, string member, object value) + public void SetValue(object target, string member, object? value) { - System.Action setter = Members[member].Setter; + System.Action setter = Members[member].Setter!; setter(target, value); } public Type GetType(string member) { - return Members[member].MemberType; + return Members[member].MemberType!; } public static ReflectionObject Create(Type t, params string[] memberNames) @@ -81,11 +84,11 @@ public static ReflectionObject Create(Type t, params string[] memberNames) return Create(t, null, memberNames); } - public static ReflectionObject Create(Type t, MethodBase creator, params string[] memberNames) + public static ReflectionObject Create(Type t, MethodBase? creator, params string[] memberNames) { ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; - ObjectConstructor creatorConstructor = null; + ObjectConstructor? creatorConstructor = null; if (creator != null) { creatorConstructor = delegateFactory.CreateParameterizedConstructor(creator); @@ -135,12 +138,12 @@ public static ReflectionObject Create(Type t, MethodBase creator, params string[ ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length == 0 && method.ReturnType != typeof(void)) { - MethodCall call = delegateFactory.CreateMethodCall(method); + MethodCall call = delegateFactory.CreateMethodCall(method); reflectionMember.Getter = target => call(target); } else if (parameters.Length == 1 && method.ReturnType == typeof(void)) { - MethodCall call = delegateFactory.CreateMethodCall(method); + MethodCall call = delegateFactory.CreateMethodCall(method); reflectionMember.Setter = (target, arg) => call(target, arg); } } @@ -149,16 +152,6 @@ public static ReflectionObject Create(Type t, MethodBase creator, params string[ throw new ArgumentException("Unexpected member type '{0}' for member '{1}'.".FormatWith(CultureInfo.InvariantCulture, member.MemberType(), member.Name)); } - if (ReflectionUtils.CanReadMemberValue(member, false)) - { - reflectionMember.Getter = delegateFactory.CreateGet(member); - } - - if (ReflectionUtils.CanSetMemberValue(member, false, false)) - { - reflectionMember.Setter = delegateFactory.CreateSet(member); - } - reflectionMember.MemberType = ReflectionUtils.GetMemberUnderlyingType(member); d.Members[memberName] = reflectionMember; @@ -167,4 +160,4 @@ public static ReflectionObject Create(Type t, MethodBase creator, params string[ return d; } } -} \ No newline at end of file +} diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionUtils.cs index a4a901c80..566d62f12 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -36,6 +39,8 @@ using System.Collections; using System.Globalization; using System.Text; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -45,7 +50,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { -#if (DOTNET || PORTABLE || PORTABLE40) && !NETSTANDARD2_0 && !NETCOREAPP +#if (DOTNET || PORTABLE || PORTABLE40) && !NETSTANDARD2_0 [Flags] internal enum MemberTypes { @@ -56,7 +61,7 @@ internal enum MemberTypes } #endif -#if PORTABLE && !NETSTANDARD2_0 && !NETCOREAPP +#if PORTABLE && !NETSTANDARD2_0 [Flags] internal enum BindingFlags { @@ -100,7 +105,7 @@ public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); - MethodInfo m = propertyInfo.GetGetMethod(true); + MethodInfo? m = propertyInfo.GetGetMethod(true); if (m != null && m.IsVirtual) { return true; @@ -115,11 +120,11 @@ public static bool IsVirtual(this PropertyInfo propertyInfo) return false; } - public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) + public static MethodInfo? GetBaseDefinition(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); - MethodInfo m = propertyInfo.GetGetMethod(true); + MethodInfo? m = propertyInfo.GetGetMethod(true); if (m != null) { return m.GetBaseDefinition(); @@ -130,11 +135,13 @@ public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo) public static bool IsPublic(PropertyInfo property) { - if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic) + var getMethod = property.GetGetMethod(); + if (getMethod != null && getMethod.IsPublic) { return true; } - if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic) + var setMethod = property.GetSetMethod(); + if (setMethod != null && setMethod.IsPublic) { return true; } @@ -142,12 +149,12 @@ public static bool IsPublic(PropertyInfo property) return false; } - public static Type GetObjectType(object v) + public static Type? GetObjectType(object? v) { return v?.GetType(); } - public static string GetTypeName(Type t, TypeNameAssemblyFormatHandling assemblyFormat, ISerializationBinder binder) + public static string GetTypeName(Type t, TypeNameAssemblyFormatHandling assemblyFormat, ISerializationBinder? binder) { string fullyQualifiedTypeName = GetFullyQualifiedTypeName(t, binder); @@ -162,11 +169,11 @@ public static string GetTypeName(Type t, TypeNameAssemblyFormatHandling assembly } } - private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder binder) + private static string GetFullyQualifiedTypeName(Type t, ISerializationBinder? binder) { if (binder != null) { - binder.BindToName(t, out string assemblyName, out string typeName); + binder.BindToName(t, out string? assemblyName, out string? typeName); #if (NET20 || NET35) // for older SerializationBinder implementations that didn't have BindToName if (assemblyName == null & typeName == null) @@ -193,10 +200,6 @@ private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) switch (current) { case '[': - writingAssemblyName = false; - skippingAssemblyDetails = false; - builder.Append(current); - break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; @@ -302,7 +305,7 @@ public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceD return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _); } - public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) + public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, [NotNullWhen(true)]out Type? implementingType) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition)); @@ -349,7 +352,7 @@ public static bool InheritsGenericDefinition(Type type, Type genericClassDefinit return InheritsGenericDefinition(type, genericClassDefinition, out _); } - public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) + public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type? implementingType) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(genericClassDefinition, nameof(genericClassDefinition)); @@ -362,7 +365,7 @@ public static bool InheritsGenericDefinition(Type type, Type genericClassDefinit return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } - private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) + private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type? implementingType) { do { @@ -385,7 +388,7 @@ private static bool InheritsGenericDefinitionInternal(Type currentType, Type gen /// /// The type. /// The type of the typed collection's items. - public static Type GetCollectionItemType(Type type) + public static Type? GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -393,14 +396,14 @@ public static Type GetCollectionItemType(Type type) { return type.GetElementType(); } - if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type genericListType)) + if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out Type? genericListType)) { - if (genericListType.IsGenericTypeDefinition()) + if (genericListType!.IsGenericTypeDefinition()) { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } - return genericListType.GetGenericArguments()[0]; + return genericListType!.GetGenericArguments()[0]; } if (typeof(IEnumerable).IsAssignableFrom(type)) { @@ -410,18 +413,18 @@ public static Type GetCollectionItemType(Type type) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } - public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) + public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type? keyType, out Type? valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); - if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type genericDictionaryType)) + if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out Type? genericDictionaryType)) { - if (genericDictionaryType.IsGenericTypeDefinition()) + if (genericDictionaryType!.IsGenericTypeDefinition()) { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } - Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); + Type[] dictionaryGenericArguments = genericDictionaryType!.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; @@ -530,7 +533,7 @@ public static object GetMemberValue(MemberInfo member, object target) /// The member. /// The target. /// The value. - public static void SetMemberValue(MemberInfo member, object target, object value) + public static void SetMemberValue(MemberInfo member, object target, object? value) { ValidationUtils.ArgumentNotNull(member, nameof(member)); ValidationUtils.ArgumentNotNull(target, nameof(target)); @@ -729,19 +732,19 @@ private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags return true; } - public static T GetAttribute(object attributeProvider) where T : Attribute + public static T? GetAttribute(object attributeProvider) where T : Attribute { return GetAttribute(attributeProvider, true); } - public static T GetAttribute(object attributeProvider, bool inherit) where T : Attribute + public static T? GetAttribute(object attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes(attributeProvider, inherit); return attributes?.FirstOrDefault(); } -#if !(DOTNET || PORTABLE) || NETSTANDARD2_0 || NETCOREAPP +#if !(DOTNET || PORTABLE) || NETSTANDARD2_0 public static T[] GetAttributes(object attributeProvider, bool inherit) where T : Attribute { Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit); @@ -754,7 +757,7 @@ public static T[] GetAttributes(object attributeProvider, bool inherit) where return a.Cast().ToArray(); } - public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit) + public static Attribute[] GetAttributes(object attributeProvider, Type? attributeType, bool inherit) { ValidationUtils.ArgumentNotNull(attributeProvider, nameof(attributeProvider)); @@ -805,7 +808,7 @@ public static T[] GetAttributes(object attributeProvider, bool inherit) where return GetAttributes(attributeProvider, typeof(T), inherit).Cast().ToArray(); } - public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit) + public static Attribute[] GetAttributes(object provider, Type? attributeType, bool inherit) { switch (provider) { @@ -827,12 +830,12 @@ public static Attribute[] GetAttributes(object provider, Type attributeType, boo } #endif - public static StructMultiKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName) + public static StructMultiKey SplitFullyQualifiedTypeName(string fullyQualifiedTypeName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); string typeName; - string assemblyName; + string? assemblyName; if (assemblyDelimiterIndex != null) { @@ -845,7 +848,7 @@ public static StructMultiKey SplitFullyQualifiedTypeName(string assemblyName = null; } - return new StructMultiKey(assemblyName, typeName); + return new StructMultiKey(assemblyName, typeName); } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) @@ -1046,7 +1049,7 @@ public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType return isMethodOverriden; } - public static object GetDefaultValue(Type type) + public static object? GetDefaultValue(Type type) { if (!type.IsValueType()) { @@ -1097,4 +1100,4 @@ public static object GetDefaultValue(Type type) return Activator.CreateInstance(type); } } -} +} \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringBuffer.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringBuffer.cs index 0f62af30f..97f8e8481 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringBuffer.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringBuffer.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -36,7 +39,7 @@ namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities /// internal struct StringBuffer { - private char[] _buffer; + private char[]? _buffer; private int _position; public int Position @@ -47,7 +50,7 @@ public int Position public bool IsEmpty => _buffer == null; - public StringBuffer(IArrayPool bufferPool, int initalSize) : this(BufferUtils.RentBuffer(bufferPool, initalSize)) + public StringBuffer(IArrayPool? bufferPool, int initalSize) : this(BufferUtils.RentBuffer(bufferPool, initalSize)) { } @@ -57,21 +60,21 @@ private StringBuffer(char[] buffer) _position = 0; } - public void Append(IArrayPool bufferPool, char value) + public void Append(IArrayPool? bufferPool, char value) { // test if the buffer array is large enough to take the value - if (_position == _buffer.Length) + if (_position == _buffer!.Length) { EnsureSize(bufferPool, 1); } // set value and increment poisition - _buffer[_position++] = value; + _buffer![_position++] = value; } - public void Append(IArrayPool bufferPool, char[] buffer, int startIndex, int count) + public void Append(IArrayPool? bufferPool, char[] buffer, int startIndex, int count) { - if (_position + count >= _buffer.Length) + if (_position + count >= _buffer!.Length) { EnsureSize(bufferPool, count); } @@ -81,7 +84,7 @@ public void Append(IArrayPool bufferPool, char[] buffer, int startIndex, i _position += count; } - public void Clear(IArrayPool bufferPool) + public void Clear(IArrayPool? bufferPool) { if (_buffer != null) { @@ -91,7 +94,7 @@ public void Clear(IArrayPool bufferPool) _position = 0; } - private void EnsureSize(IArrayPool bufferPool, int appendLength) + private void EnsureSize(IArrayPool? bufferPool, int appendLength) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, (_position + appendLength) * 2); @@ -115,6 +118,6 @@ public string ToString(int start, int length) return new string(_buffer, start, length); } - public char[] InternalBuffer => _buffer; + public char[]? InternalBuffer => _buffer; } } \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringReference.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringReference.cs index eab1d05f7..6a2f549e8 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringReference.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringReference.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringUtils.cs index dce4ca137..2821113da 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StringUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -32,6 +35,7 @@ using System.IO; using System.Text; using System.Globalization; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -49,27 +53,32 @@ internal static class StringUtils public const char LineFeed = '\n'; public const char Tab = '\t'; - public static string FormatWith(this string format, IFormatProvider provider, object arg0) + public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) { - return format.FormatWith(provider, new[] { arg0 }); + return string.IsNullOrEmpty(value); } - public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) + public static string FormatWith(this string format, IFormatProvider provider, object? arg0) { - return format.FormatWith(provider, new[] { arg0, arg1 }); + return format.FormatWith(provider, new object?[] { arg0 }); } - public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) + public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1) { - return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); + return format.FormatWith(provider, new object?[] { arg0, arg1 }); } - public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) + public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2) { - return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); + return format.FormatWith(provider, new object?[] { arg0, arg1, arg2 }); } - private static string FormatWith(this string format, IFormatProvider provider, params object[] args) + public static string FormatWith(this string format, IFormatProvider provider, object? arg0, object? arg1, object? arg2, object? arg3) + { + return format.FormatWith(provider, new object?[] { arg0, arg1, arg2, arg3 }); + } + + private static string FormatWith(this string format, IFormatProvider provider, params object?[] args) { // leave this a private to force code to use an explicit overload // avoids stack memory being reserved for the object array @@ -152,7 +161,7 @@ public static TSource ForgivingCaseSensitiveFind(this IEnumerable ToSeparatedCase(s, '_'); + + public static string ToKebabCase(string s) => ToSeparatedCase(s, '-'); + + private enum SeparatedCaseState { Start, Lower, @@ -209,43 +222,43 @@ internal enum SnakeCaseState NewWord } - public static string ToSnakeCase(string s) + private static string ToSeparatedCase(string s, char separator) { - if (string.IsNullOrEmpty(s)) + if (StringUtils.IsNullOrEmpty(s)) { return s; } StringBuilder sb = new StringBuilder(); - SnakeCaseState state = SnakeCaseState.Start; + SeparatedCaseState state = SeparatedCaseState.Start; for (int i = 0; i < s.Length; i++) { if (s[i] == ' ') { - if (state != SnakeCaseState.Start) + if (state != SeparatedCaseState.Start) { - state = SnakeCaseState.NewWord; + state = SeparatedCaseState.NewWord; } } else if (char.IsUpper(s[i])) { switch (state) { - case SnakeCaseState.Upper: + case SeparatedCaseState.Upper: bool hasNext = (i + 1 < s.Length); if (i > 0 && hasNext) { char nextChar = s[i + 1]; - if (!char.IsUpper(nextChar) && nextChar != '_') + if (!char.IsUpper(nextChar) && nextChar != separator) { - sb.Append('_'); + sb.Append(separator); } } break; - case SnakeCaseState.Lower: - case SnakeCaseState.NewWord: - sb.Append('_'); + case SeparatedCaseState.Lower: + case SeparatedCaseState.NewWord: + sb.Append(separator); break; } @@ -257,22 +270,22 @@ public static string ToSnakeCase(string s) #endif sb.Append(c); - state = SnakeCaseState.Upper; + state = SeparatedCaseState.Upper; } - else if (s[i] == '_') + else if (s[i] == separator) { - sb.Append('_'); - state = SnakeCaseState.Start; + sb.Append(separator); + state = SeparatedCaseState.Start; } else { - if (state == SnakeCaseState.NewWord) + if (state == SeparatedCaseState.NewWord) { - sb.Append('_'); + sb.Append(separator); } sb.Append(s[i]); - state = SnakeCaseState.Lower; + state = SeparatedCaseState.Lower; } } diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StructMultiKey.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StructMultiKey.cs index d054de5ac..f658c234b 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StructMultiKey.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/StructMultiKey.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ThreadSafeStore.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ThreadSafeStore.cs index 9673091f9..85e68fb05 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ThreadSafeStore.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ThreadSafeStore.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/TypeExtensions.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/TypeExtensions.cs index 6a9b313df..b10459886 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -30,6 +33,8 @@ using System; using System.Collections.Generic; using System.Reflection; +using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Datadog.Trace.Vendors.Newtonsoft.Json.Utilities.LinqBridge; #else @@ -44,12 +49,12 @@ internal static class TypeExtensions #if !DOTNET private static readonly BindingFlags DefaultFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; - public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) + public static MethodInfo? GetGetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetGetMethod(false); } - public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) + public static MethodInfo? GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || nonPublic)) @@ -60,12 +65,12 @@ public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPu return null; } - public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) + public static MethodInfo? GetSetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetSetMethod(false); } - public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) + public static MethodInfo? GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || nonPublic)) @@ -89,7 +94,7 @@ public static bool IsAssignableFrom(this Type type, Type c) } #endif - public static bool IsInstanceOfType(this Type type, object o) + public static bool IsInstanceOfType(this Type type, object? o) { if (o == null) { @@ -219,7 +224,7 @@ public static bool IsSealed(this Type type) } #if (PORTABLE40 || DOTNET || PORTABLE) - public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object placeholder1, Type propertyType, IList indexParameters, object placeholder2) + public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags, object? placeholder1, Type propertyType, IList indexParameters, object? placeholder2) { IEnumerable propertyInfos = type.GetProperties(bindingFlags); @@ -293,12 +298,12 @@ public static MethodInfo GetMethod(this Type type, IList parameterTypes) return type.GetMethod(null, parameterTypes); } - public static MethodInfo GetMethod(this Type type, string name, IList parameterTypes) + public static MethodInfo GetMethod(this Type type, string? name, IList parameterTypes) { return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); } - public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingFlags, object placeHolder1, IList parameterTypes, object placeHolder2) + public static MethodInfo GetMethod(this Type type, string? name, BindingFlags bindingFlags, object? placeHolder1, IList parameterTypes, object? placeHolder2) { return MethodBinder.SelectMethod(type.GetTypeInfo().DeclaredMethods.Where(m => (name == null || m.Name == name) && TestAccessibility(m, bindingFlags)), parameterTypes); } @@ -318,7 +323,7 @@ public static ConstructorInfo GetConstructor(this Type type, IList paramet return type.GetConstructor(DefaultFlags, null, parameterTypes, null); } - public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object placeholder1, IList parameterTypes, object placeholder2) + public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, object? placeholder1, IList parameterTypes, object? placeholder2) { return MethodBinder.SelectMethod(type.GetConstructors(bindingFlags), parameterTypes); } @@ -342,12 +347,12 @@ public static MemberInfo[] GetMemberInternal(this Type type, string member, Memb TestAccessibility(m, bindingFlags)).ToArray(); } - public static FieldInfo GetField(this Type type, string member) + public static FieldInfo? GetField(this Type type, string member) { return type.GetField(member, DefaultFlags); } - public static FieldInfo GetField(this Type type, string member, BindingFlags bindingFlags) + public static FieldInfo? GetField(this Type type, string member, BindingFlags bindingFlags) { FieldInfo field = type.GetTypeInfo().GetDeclaredField(member); if (field == null || !TestAccessibility(field, bindingFlags)) @@ -382,7 +387,7 @@ private static bool ContainsMemberName(IEnumerable members, string n private static IList GetMembersRecursive(this TypeInfo type) { - TypeInfo t = type; + TypeInfo? t = type; List members = new List(); while (t != null) { @@ -401,7 +406,7 @@ private static IList GetMembersRecursive(this TypeInfo type) private static IList GetPropertiesRecursive(this TypeInfo type) { - TypeInfo t = type; + TypeInfo? t = type; List properties = new List(); while (t != null) { @@ -420,7 +425,7 @@ private static IList GetPropertiesRecursive(this TypeInfo type) private static IList GetFieldsRecursive(this TypeInfo type) { - TypeInfo t = type; + TypeInfo? t = type; List fields = new List(); while (t != null) { @@ -442,12 +447,12 @@ public static IEnumerable GetMethods(this Type type, BindingFlags bi return type.GetTypeInfo().DeclaredMethods; } - public static PropertyInfo GetProperty(this Type type, string name) + public static PropertyInfo? GetProperty(this Type type, string name) { return type.GetProperty(name, DefaultFlags); } - public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingFlags) + public static PropertyInfo? GetProperty(this Type type, string name, BindingFlags bindingFlags) { PropertyInfo property = type.GetTypeInfo().GetDeclaredProperty(name); if (property == null || !TestAccessibility(property, bindingFlags)) @@ -580,7 +585,7 @@ public static bool IsPrimitive(this Type type) #endif } - public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, out Type match) + public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) { Type current = type; diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ValidationUtils.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ValidationUtils.cs index c99005f59..a0eccb83d 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ValidationUtils.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/Utilities/ValidationUtils.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // @@ -28,12 +31,14 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; namespace Datadog.Trace.Vendors.Newtonsoft.Json.Utilities { internal static class ValidationUtils { - public static void ArgumentNotNull(object value, string parameterName) + public static void ArgumentNotNull([NotNull]object? value, string parameterName) { if (value == null) { diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/WriteState.cs b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/WriteState.cs index 92b93c209..80c781a32 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/WriteState.cs +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/WriteState.cs @@ -2,6 +2,9 @@ // // This file was automatically generated by the UpdateVendors tool. //------------------------------------------------------------------------------ +#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011, SYSLIB0032 +#pragma warning disable CS8600, CS8601, CS8602, CS8603, CS8604, CS8618, CS8620, CS8714, CS8762, CS8765, CS8766, CS8767, CS8768, CS8769, CS8612 +#nullable enable #region License // Copyright (c) 2007 James Newton-King // diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/_last_downloaded_source_url.txt b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/_last_downloaded_source_url.txt index e033bccab..96879b881 100644 --- a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/_last_downloaded_source_url.txt +++ b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/_last_downloaded_source_url.txt @@ -1 +1 @@ -https://github.com/JamesNK/Newtonsoft.Json/archive/12.0.1.zip \ No newline at end of file +https://github.com/JamesNK/Newtonsoft.Json/archive/13.0.1.zip \ No newline at end of file diff --git a/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/packageIcon.png b/tracer/src/Datadog.Trace/Vendors/Newtonsoft.Json/packageIcon.png new file mode 100644 index 0000000000000000000000000000000000000000..10c06a5c4da3336c12fe3b61a37cfef8cd15cceb GIT binary patch literal 8956 zcmbtai$Bxf|9|g-MhHa+(U?nag%G*qHZq!3lAuwQjWsr6mXV+*X4n#irDJ6~sb zr<J{GTMNjvrg2lsG8Hm%>wK5S7+nArS^|4tp?kl1@CLxAkHC zAL%GnJxbL!%11-&U;d=o*f$e~>@Me<$O7 z>yhL5i#OpsMb4u8Ba$QuO+Szef9Sb^mrqvFnf&r_{q*1`!v^3GYxYRA%c)0))nTszlXdsu#y^KQ!RC>b%xql#ravVHvcD9NfN7V{5)k@MH#b{&DSi zqD6cF;A1;ZFmuT^qQ8m~mcN~@E$sA*03LqMficHQOY`sV;7_DwwVHiGCFJKE9|lmvVLJoXyf#~O9}Auh9$ zTfY^A&fge@T=32Hq*mmpbF6nd(x__H%2Q^Dt0H{3$LGE)d0@oRUoie9_Er8f)n7&5 zEr84LRL}g^XW-SRqYSz(0OegnCal9u8|aY8WKpw_leHBN_4frwSsQBT+Frl`oh^Oz znJF7o+(9ryXl@si!021rB^9QWN9p3kteSUeJG@zri>wX|)75?H<<5^*hOkN_EzC*s z^o1Xux0LdsMgf7kw5Y^7#=7jy8_09QKp>|2A4-z9lXJ<4^QZUz_JwEA{Phq-=|p7u z_k9V?C{HR}Wo@2#^EOMF*sDOZc(n+}(O)p-(0_0gEQr33q`63=2&MIy^}A1oXW*N$ zZkxmtQ63yGrKGXdfEZfCJ>b7TMxz(66b=FW{y;BM0C~8YtEVqP#(+Qs3(^#lz_9-F z5IL!y_F0ur{9 zl%cfFzl}q%khXXoGl*{!c1B56$4439 zy;M(5IF5*H)=?OSkBJ^p$xrUDULKB<0scovAqP^D}9Fa?<%mi{n^X! z<793?=#r2CmX-hDlmjgrL{R_1?PNjwcvVD5Alx6ZSx0jVGX><6rpFIl_WIm{;?`x* z2<1|Vl5wHHpF)K)Tw@q-6Eq9U$U1)juQK`29f+$Fg70uIxIxtMN2o?sN-Hwzz#(B4 z(diw-S1eY^t$HSC*R_ojUlF*r}-#E(Z6I6~IEbD&K$-+&L|h0m>|2Mn!lJF-WRrop)fNo<26k zQi@_5atcvB>=5abb{{eb{TSJ0?Q?c*HM;(&Qk3YNTKO~TO^HozFAb{CK#ZyY5+7toDBs*=Ad>9iqhOaaJFsi}*{L%0z zF;S_IW>l}|;Pktt32TTNU#~JCQ<>|GDLQq|%#xgwC!25kBH~KiUXW-W4Ivt-?1QteeZ@?X z9&G<7c~;I8+9xL9Ddj!nlJjy8ON{B$lXB92tkh?xVf%v~RNYkR6cQbL_A>M%*>8)f zR{EokB#GL3^|`^i3h#!}P%UhI+zzALTxsWk`J2x1(#!O=>8F0fr4z5;SMI+J5{XH6 zF}cc1rHAqJu$YxXz5}8u%4(*5uVENsbMV;?L=bCoH!k8Tu28*%f7lHivRVInz;07; z_U9hzS&}bhEuGQVFNZ}nV}kp2n9fC+Z)|5)2Je8nAeMNF7UFgKYvNz#Z%^>{Z9udBZaDNS)SeQa8;n`y%9A(zE z=g1LJ?bsLVxAHZ8Fu;OlZA-G~MYU+KNn<fan5MZC#XT7#8}jP51IDxVj1bn5DP5eI zL8zQ4+jTN^=BXO#x=x4wQ@=i~apJdTmo|__uTMT=(tEIFv7zwUtGFVq1o*H6rY8ga zOhD~AZC*{{Mp`)S8Nn&~eQ)vL)raYh5+-7)Xy^p&M~Z;7{n*5s`TG)cgVppnd2f1) zno2{$Wl$CDt1EUb)D$`xJPHA#?U;edsnb#&iglUH6K7IYr>Py*Jf@ z`J%H;iCLA>dcxgl+pxgt0dn)_uYrW&6tiTUL#K~e|rKYD3#BuU)d>-!Q3D zKs3k*(w;rvQYpHBi@O&oQihoJKAAcjp3#5al=LlGV6=Vy%3W-vY_)8Z>fB&y8du*4 z-yN9Q@2Cf}(crhee7-$mOMU|UZRsI_L3ib629`~uGl?<+yAz*OPLp=Xg$A)A#;Y82 zYdrK1;P99~%5!SRoD^%;aWw{_@wuf40c5qqVaDRw7J_6mdSUwbxXshl`Efhe;ksJo zFs%=dPA$AJ^|isO{InalVW!@j7-S}t3DBK7gzoV!cIksLUoyy^kg`@B}C*WhnmT1S2;Y8M@_EUr7HxX95 zV|{142tg9%lFd{$p=+A-fxPd%$Bu(RaA!x1v8pnpW4#k`0J`gp(FoR#gep^U$E-l~ z`3o7;1pVzrvu{dC(F&_{S+_qjek$mI86T^O${dQd-~XhJ$~gGh2kAVPD0Gu_A? zMRK=NxtE{jG~wDmi77n(%$DQ=G#_*yz;(5d7$=^WN$((+SIcnD+bJ~K^vizM{1kdA5V6_x zTVuOA-S=Aell(U_cbFM z^Pd(1j}|Ntl-B+Y0{3Stb~fcf%{wen*a{0xOY%_=^^&vG%!avE3|+5Me6$ z@w<4U3Yew&j<_slQ%5`6_`!o+;0LQxFYe%9?Ld)CZkm#2kIvm_`m%k!Cl6f6O_J$^ zbiS35r3|*BDW5$oI6vjU26ry@7#*-=u!O$2o(M98oA13dF!QTi5 zyEerqB_yBtsw62wB++=A4)*9StX;cW9#pnhV(5{w9H{sSLthy&~6AG zM8A08hR>3A#=KdtOsaD)(QS$?53TA2$XO35WId2XuDC(Q_eGD0g^88F;yNY_6!OsY zZ}RYAL<4fNXCnrhwnTEZtKFhhskD^*-H(Mj>jF(#TUpg0La>=RVqvfmwS1S%Jjf(c zl3_|yDU!Q}Uif4pZpddL3xmDL6cS=pq|S&GcsOHvP1HpD%Ud6h8)7Xi$WlU<-q0jT zW1b&g8Dd?>Vwp4R^cLP}etjktDH7k=y3lN&yA0Eq4795eyPe#)*t9UkK^2{%y>0vW%JP2IjAw^%hz|c|iEa&o=;M z_FUYszMrQxbgMK~}YLGrnvS}N)(ZN8OtN3@AXNohQljTUAXGdGnpFghM z%C|lZH!>EwWyPbiwJ0>n9Eq!Siu2}_u zvofa8(Vvk1VQOt4Jm?R_xIb8%?tMo3I|`}$noz*b6Wn&jQ1vj7-aPQpb?kCASGpa= zy!T7YAO&YnHMtXsm`%lLoH2vk;($>lvr_&T7JbSgdQz4tD+CG7m1ss#i28XDLFjbv z88jzt3hnw4SvW3q`hH&xcd!dZn*8I2XD7kGOEj;`cfmFt`RPQu%X#jHbsazucKoqc z%6AEFYC*DuQz|D(4M*o99d2Nt6$Q(Bta5-j@Oc%b=|sR>B;mkn=hvn@_VN9ZOQD`X z@E^!0wDlkCVu#Y(TaO;jgEm3Fn}ocG5TSn%5$QOZMAKVn#f@MX=LGBCltWWds2kL= zGVk0P3h{1}35+A;q3;%RZx1%c{f5?x4PPIujU&d$9`3)sYD0Vy?0ZW3qGZp-^X710 z_t+phT1QeEuhP!9jnOzfa8Z-AMHmsT1)@?<#?=@8&S zkSw$?qN$4ka~}4ca*%LU>k@O=lv}c%^GKG7u=7f74Hr|=zpB>K04`PHBRHVp8V0S9 zeQELLT03x3Md6Umd}Ls>Py+F&avTf>#y9fv9^ne!Gsk>e*ZY z{Fg{&I?h2(FA#17Pef5#(T+LJv0VTJQDOoSuLxI;_M15jvYXuANLTK&X3>E(qOuc4 z1FKTME^Y@$ttX}IjOHE)_XNb)wW|O;e*^m4JjM6K;=aK@Z`B8GfVGtlC;qtEjvqrfBJt32Y+_*C8C2lh)qqVqv;M z(6nV*$SZIsF7$12PXGa3|Dq!4;)_7IF!K5fGHbXBhL=~#PS_>I^8y#y(Yh&Q{7Sc! z+V?(ny2lE!ISp&#)Ht6(g`*%#d1d9k=tHB3Jn$lZe|=td#hcm!F)6XvfZJ)e*i{AP z517Lww<5W{sf5+|eRWnGghODA#+A(R6))))r^_O$TXtE>w7Z6{PRbJ_{~-;7NzMIA zE1FJ>pk5+pP_K8VxO~mMFI=DPNp=gb1lOhl&lcwHsuY-K>ACKxkiD*fg;FTnk`eUd95(-3k(| z(%Vet{UY!etFXZ%-EMgBuh0HIZ&aUT{BRzz|##NT5pU&(%W z?1?qVD3?yFM{P9PVJY*uVtQp|dReb&mhT70tM1fWtYVDVz;A;G$>)N;n_kz)0NmsNq;Dvx|?hlRpAWuW`kdvCaK-?O{J37LJ% zfa?c21yH&42-%tMim$3fO2G<}-FKIS#w)W@z#&RMFoyiqHeMxfVgd7(G=UZ_&X zmT-f>sRV9t>`Pj+upw!%mE6CGun^2v5RehU_h3W!ACKu{HRHs&awA{tX!UM1AMV{T<^Nh&E)aj!3FchUO-SAflmn0e1w4=cr?$(tmLY2FY| z1#h3T3l$|kfc8(nfo`HmE{9zq=O%>SevY~BrB_A>o|-}XLk;~O{f zZG>U)$NIYRon#65j(vnN`}jaPaP6~WZDy6StY{nR7R>!A*q!pQLHq`u1YK2o+uE@m z!BIOPv58knu7pF9koTUPZPJZ-j43~)mG6()#dDcUiz=)&T1P@ME!&k}vQx%jej-vO z@n7uw635mSFLF0cCq1Bw%FY?m$F#*xV+Onha8}UIh5|n^fPCx+Ie=7KEO#wlW}w7p zk5$$5!An7qmB;GX>^O$Ee{<7Elftx_$Ky+gmC%Bwhg_P(E% z*V}3FC!Q?QTR!_a)d!i!g5E3lVM&Vl|MuUV5`~%$?wL8(x&M*i&YuOIWz5{UOs)B7 zE55HH_703RPwCWP#b=jK-k8_F^K;Ri-9aH?zzZV&x+?->=kC?%n4vZ_igzP!oeq1#Q6=lNd-7h#FaSvtGw66AAf0;hX zuTMbCJ54%GYM6*mLIRYZ+#s}Rgg#4x>8r(;o{wNG@XnRtrtn)q-zRe!o$d4j#2ZR1 z=@xT_DazDkW)ha?4MieS+}tNPdC+yXIqN5ICh5}%r0rn_)9pzhRe@XnLV#-woSipZ zmK~^?hI3%_c!9hApL;M*pz`{c&M71fJd?DqxRYGRk+$z@V4i3oe}W?23qTZ}1TbVd zD6m7+R;L=}IgW#hk0g)L0N#X&!8@R?>M5c{~c0076)Z%Dg%+0tU#t z8O-%MP}?bLYf*#p1hsu_H#4X!&7FjwK-wMzwqFf{XUSq9A#^l=CJe2PxCKVAWLKa^ z0CdhOh9)o_y*k+Ss9d4;s>16}wQOZpk#zy``!4`lDFtU6^877x19J%+$R{bJVCEB0 z2~M(rdD8QcWs=?ga|cSpAOdi~^wk0}@P(*tNiE7V(^qidei+m*Vg?Jj0(1iLVW0>+ zdOU?VK zFu2JY;7+zAsqSBQ(h_(Gzq<#^$OafmtAlA9-XY5l05|oOq2Mqx82jQXp3-f1k``Fj zurvqE=0N{Ymbm{PaF}H|GW*+YO1^_~zSbn#HsGuhrFGj0#O8%(TDC8Kh}s6e0_C=R zcT)D3rPg~wd54xQc&2NIf|`OL42}efEPx^-GgvgdupGR(FVv!@%z%YCk|dK&xuluD z;x-`GS``!0he@reIQxpfT?_BjEn)TGjw{3;2-+V54-p0cP|WCXV&cG+WgpOD3JQX% zV$PVtw}8U8;JqI|1jVGUj#C;{A`C+V`m4i&1DG8?Sl^JZL+`8*{G|=p~pzy-_3lL2%4;6##D< zr%4AKFn89CLS^5Dj-KX?9R?b$f%{Qr&K#`Frd^)>075=V zL8Z=^JI6t=$pE`ME%<}~>v~#>5Oc!Zq5bVjnNB;@Qdf=vm2x)teB%Cct~L9N7tpL? zwZ!bPx(Q*u_ZQZ5psDkKO>m`AihbA zrwz(4c*_}0elERd53eBP&=>)Y_34s&s-RQMk2-YQL=>pdJmH8beE*=rgK9!oP7&M> z>6crC%{owN*f9IVo^6+;8y2wE(I{I++#-?xT8uAsdt4jKZj(+H{0dns-{5HtX3|>9 zFG>qKjYr;Muu5GYpDJuGUIh3A1o-|m0s;s?P(zGWxQMy2khGMx@N-m}&u`A{I?%%J z_Jw;63f-KrRO7CT@(|Wi;2)fM4ZZ>I00x@Acc-l1_f*Y~_jl194Pa$2fW4a`dAJ`8 zhx~$^)WEVy!0flf3yrcvNz_FwmG+*?xjob@CN{VVeuE30Gb z3$KAy*-nI2O?`ZH4NaE`Mf^xHOg@Yfno8vuj8l#&JQ3PSaQ&=F4-F+zGZHkFtd$)RX&9jpAdG)&tUk&(K;)G(Jg1EiETe5*LZ z$0aXGv<@$!v97)#`wJUgE-LQK-^|i*i~*Kt4JC3zG_iUW(0>_-JMP|NaK#@1KyE+!P>ws6N&k6WO5$ Q{;CDSI^rBE?fuXHA7hI;RR910 literal 0 HcmV?d00001 diff --git a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Dss/SymbolReaderImpl.cs b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Dss/SymbolReaderImpl.cs index 6a6800f77..ac4603649 100644 --- a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Dss/SymbolReaderImpl.cs +++ b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Dss/SymbolReaderImpl.cs @@ -14,7 +14,7 @@ using Datadog.Trace.Vendors.dnlib.DotNet.Pdb.WindowsPdb; namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Dss { - sealed class SymbolReaderImpl : SymbolReader { + sealed partial class SymbolReaderImpl : SymbolReader { ModuleDef module; ISymUnmanagedReader reader; object[] objsToKeepAlive; diff --git a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/DbiScope.cs b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/DbiScope.cs index 1e1933894..964e1bca5 100644 --- a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/DbiScope.cs +++ b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/DbiScope.cs @@ -148,7 +148,7 @@ public void Read(RecursionCounter counter, ref DataReader reader, uint scopeEnd) } counter.Decrement(); if (reader.Position != scopeEnd) - Debugger.Break(); + {} } static string ReadUnicodeString(ref DataReader reader, uint end) { diff --git a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/PdbReader.cs b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/PdbReader.cs index 5d86f991a..0671db07e 100644 --- a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/PdbReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Managed/PdbReader.cs @@ -18,7 +18,7 @@ namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Managed { /// /// A managed PDB reader implementation for .NET modules. /// - sealed class PdbReader : SymbolReader { + sealed partial class PdbReader : SymbolReader { MsfStream[] streams; Dictionary names; Dictionary strings; diff --git a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Portable/PortablePdbReader.cs b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Portable/PortablePdbReader.cs index 517bbe2aa..1e9b69850 100644 --- a/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Portable/PortablePdbReader.cs +++ b/tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Pdb/Portable/PortablePdbReader.cs @@ -16,7 +16,7 @@ using Datadog.Trace.Vendors.dnlib.IO; namespace Datadog.Trace.Vendors.dnlib.DotNet.Pdb.Portable { - sealed class PortablePdbReader : SymbolReader { + sealed partial class PortablePdbReader : SymbolReader { readonly PdbFileKind pdbFileKind; ModuleDef module; readonly Metadata pdbMetadata; diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Datadog.Trace.ClrProfiler.IntegrationTests.csproj b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Datadog.Trace.ClrProfiler.IntegrationTests.csproj index 5e01b1234..95b617c37 100644 --- a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Datadog.Trace.ClrProfiler.IntegrationTests.csproj +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Datadog.Trace.ClrProfiler.IntegrationTests.csproj @@ -21,12 +21,15 @@ + all runtime; build; native; contentfiles; analyzers; buildtransitive + + @@ -39,7 +42,7 @@ - + diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/DumpHeapLive.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/DumpHeapLive.cs new file mode 100644 index 000000000..09872c755 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/DumpHeapLive.cs @@ -0,0 +1,91 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Diagnostics; +using Microsoft.Diagnostics.Runtime; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger.Assertions; + +/// +/// Performs the equivalent of the windbg/sos command "!DumpHeap -stat -live", which provides statistics regarding objects +/// that are still "live" (meaning there is a GC root which directly or indirectly references them). +/// Based on borrowed code from Alois Krause post: https://stackoverflow.com/a/35286955/292555 +/// +internal static class DumpHeapLive +{ + public static Dictionary GetLiveObjectsByTypes(Process process) + { + var objCountByType = new Dictionary(); + if (process.HasExited) + { + throw new MemoryAssertionException("Process has exited", string.Empty); + } + + using var target = DataTarget.CreateSnapshotAndAttach(process.Id); + var heap = target.ClrVersions[0].CreateRuntime().Heap; + var considered = new ObjectSet(heap); + var eval = new Stack(); + + foreach (var root in heap.EnumerateRoots()) + { + eval.Push(root.Object); + } + + while (eval.Count > 0) + { + var obj = eval.Pop(); + if (considered.Contains(obj)) + { + continue; + } + + considered.Add(obj); + + var type = heap.GetObjectType(obj); + + var heapCorrupted = type == null; + if (heapCorrupted) + { + continue; + } + + bool? disposed = null; + var disposedFlagField = type.GetFieldByName("_disposed"); + if (disposedFlagField != null) + { + disposed = disposedFlagField.Read(obj, false); + } + + AddToStats(type.Name, objCountByType, disposed); + + foreach (var child in heap.GetObject(obj) + .EnumerateReferences(carefully: true, considerDependantHandles: true)) + { + if (!considered.Contains(child.Address)) + { + eval.Push(child.Address); + } + } + } + + return objCountByType; + } + + private static void AddToStats(string typeName, Dictionary objCountByType, bool? disposed) + { + if (typeName != null) + { + if (objCountByType.TryGetValue(typeName, out var current)) + { + objCountByType[typeName] = (current.Live + 1, current.Disposed + (disposed == true ? 1 : 0)); + } + else + { + objCountByType[typeName] = (1, disposed == true ? 1 : 0); + } + } + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertionException.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertionException.cs new file mode 100644 index 000000000..ec05abf15 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertionException.cs @@ -0,0 +1,16 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger.Assertions; + +internal class MemoryAssertionException : Exception +{ + public MemoryAssertionException(string message, string dumpDetails) + : base($"{message} {dumpDetails}") + { + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertions.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertions.cs new file mode 100644 index 000000000..67b90700e --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/Assertions/MemoryAssertions.cs @@ -0,0 +1,80 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger.Assertions; + +#if !NETCOREAPP2_1 +/// +/// Perform assertions to validate there are no memory leaks. +/// NOTE: This uses ClrMD instead of the SciTech MemProfiler API or JetBrains dotMemoryUnit because in our case, +/// there is already a profiler attached to the process (and we need it to work in Linux as well). +/// IMPORTANT: Not supported on .net core 2.1 and ARM64 architecture +/// +internal class MemoryAssertions +{ + private readonly Dictionary _liveObjectsByTypes; + + private MemoryAssertions(Dictionary liveObjectsByTypes) + { + _liveObjectsByTypes = liveObjectsByTypes; + } + + /// + /// Capture a snapshot of the current state of a process and returns a MemoryAssertions instance + /// which can perform assertions on said snapshot. + /// + /// Process to capture snapshot of + /// MemoryAssertions + public static MemoryAssertions CaptureSnapshotToAssertOn(Process process) + { + if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64) + { + throw new NotSupportedException("Arm64 is not supported for memory assertions"); + } + + var liveObjectsByTypes = DumpHeapLive.GetLiveObjectsByTypes(process); + return new MemoryAssertions(liveObjectsByTypes); + } + + public void NoUndisposedObjectsExist() + { + if (typeof(T).GetField("_disposed", BindingFlags.NonPublic | BindingFlags.Instance) == null) + { + throw new Exception("Type " + typeof(T).Name + " does not have a private field named '_disposed'. " + + "Therefore, we cannot verify there are no live un-disposed instances." + GetDumpDetails()); + } + + if (_liveObjectsByTypes.TryGetValue(typeof(T).FullName, out var result)) + { + var undisposed = result.Live - result.Disposed; + if (undisposed > 0) + { + throw new MemoryAssertionException($"Expected no {typeof(T).Name} objects in memory with (_disposed = false), but found {undisposed}. ", GetDumpDetails()); + } + } + } + + public void NoObjectsExist() + { + if (_liveObjectsByTypes.TryGetValue(typeof(T).FullName, out var result) && result.Live > 0) + { + throw new MemoryAssertionException($"Expected no {typeof(T).Name} objects in memory, but found {result.Live}.", GetDumpDetails()); + } + } + + private string GetDumpDetails() + { + return string.Empty; + // re-use TaskHelper.TakeMemoryDump after rebasing from datadog upstream + // https://github.com/DataDog/dd-trace-dotnet/pull/2655/files#diff-3eeffff2f0a958d283a96355b666dcfa121a911332c526139121f7f4260af89c + } +} +#endif diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerSampleProcessHelper.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerSampleProcessHelper.cs new file mode 100644 index 000000000..bdd13a011 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerSampleProcessHelper.cs @@ -0,0 +1,44 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Diagnostics; +using System.Net; +using System.Threading.Tasks; +using Datadog.Trace.TestHelpers; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger +{ + internal class DebuggerSampleProcessHelper : ProcessHelper + { + private const string StopSuffix = "stop"; + + private readonly string _stopUrl; + private readonly string _runUrl; + + public DebuggerSampleProcessHelper(string baseUrl, Process process, Action onDataReceived = null) + : base(process, onDataReceived) + { + _stopUrl = $"{baseUrl}{StopSuffix}"; + _runUrl = baseUrl; + } + + internal async Task StopSample() + { + using var httpWebResponse = await WebRequest.CreateHttp(_stopUrl).GetResponseAsync(); + Process.WaitForExit(1000); + + if (Process.ExitCode != 0) + { + throw new InvalidOperationException($"Process exit code is {Process.ExitCode}"); + } + } + + internal async Task RunCodeSample() + { + using var httpWebResponse = await WebRequest.CreateHttp(_runUrl).GetResponseAsync(); + } + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerTestHelper.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerTestHelper.cs new file mode 100644 index 000000000..8abcdbc9b --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DebuggerTestHelper.cs @@ -0,0 +1,111 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Pdb; +using Datadog.Trace.TestHelpers; +using FluentAssertions; +using Samples.Probes; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger; + +internal static class DebuggerTestHelper +{ + internal static DebuggerSampleProcessHelper StartSample(TestHelper helper, MockTracerAgent agent, string testName) + { + var listenPort = TcpPortProvider.GetOpenPort(); + + var localHost = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "http://127.0.0.1" : "http://localhost"; + var listenUrl = $"{localHost}:{listenPort}/"; + + var process = helper.StartSample(agent, $"--test-name {testName} --listen-url {listenUrl}", string.Empty, aspNetCorePort: 5000); + var processHelper = new DebuggerSampleProcessHelper(listenUrl, process); + + return processHelper; + } + + internal static int CalculateExpectedNumberOfSnapshots(ProbeAttributeBase[] probes) + { + return probes.Aggregate(0, (accuNumOfSnapshots, next) => accuNumOfSnapshots + next.ExpectedNumberOfSnapshots); + } + + internal static ProbeConfiguration CreateProbeDefinition(SnapshotProbe[] probes) + { + return new ProbeConfiguration { Id = Guid.Empty.ToString(), SnapshotProbes = probes }; + } + + internal static (ProbeAttributeBase ProbeTestData, SnapshotProbe Probe)[] GetAllProbes(Type type, string targetFramework, bool unlisted, DeterministicGuidGenerator guidGenerator) + { + const BindingFlags allMask = + BindingFlags.Public | + BindingFlags.NonPublic | + BindingFlags.Static | + BindingFlags.Instance; + + var snapshotMethodProbes = type.GetNestedTypes(allMask) + .SelectMany(nestedType => nestedType.GetMethods(allMask | BindingFlags.DeclaredOnly)) + .Concat(type.GetMethods(allMask | BindingFlags.DeclaredOnly)) + .Where( + m => + { + var att = m.GetCustomAttribute(); + return att?.Skip == false && att?.Unlisted == unlisted && att?.SkipOnFrameworks.Contains(targetFramework) == false; + }) + .Select(m => (m.GetCustomAttribute().As(), CreateSnapshotMethodProbe(m, guidGenerator))) + .ToArray(); + + var snapshotLineProbes = type.GetCustomAttributes() + .Where(att => att?.Skip == false && att?.Unlisted == unlisted && att?.SkipOnFrameworks.Contains(targetFramework) == false) + .Select(att => (att.As(), CreateSnapshotLineProbe(type, att, guidGenerator))) + .ToArray(); + + return snapshotLineProbes.Concat(snapshotMethodProbes).ToArray(); + } + + private static SnapshotProbe CreateSnapshotLineProbe(Type type, LineProbeTestDataAttribute line, DeterministicGuidGenerator guidGenerator) + { + var where = CreateLineProbeWhere(type, line); + return CreateSnapshotProbe(where, guidGenerator); + } + + private static Where CreateLineProbeWhere(Type type, LineProbeTestDataAttribute line) + { + using var reader = DatadogPdbReader.CreatePdbReader(type.Assembly); + var symbolMethod = reader.ReadMethodSymbolInfo(type.GetMethods().First().MetadataToken); + var filePath = symbolMethod.SequencePoints.First().Document.URL; + return new Where() { SourceFile = filePath, Lines = new[] { line.LineNumber.ToString() } }; + } + + private static SnapshotProbe CreateSnapshotMethodProbe(MethodInfo method, DeterministicGuidGenerator guidGenerator) + { + var probeTestData = method.GetCustomAttribute(); + var where = CreateMethodProbeWhere(method, probeTestData); + return CreateSnapshotProbe(where, guidGenerator); + } + + private static SnapshotProbe CreateSnapshotProbe(Where where, DeterministicGuidGenerator guidGenerator) + { + return new SnapshotProbe { Id = guidGenerator.New().ToString(), Language = TracerConstants.Language, Active = true, Where = where }; + } + + private static Where CreateMethodProbeWhere(MethodInfo method, MethodProbeTestDataAttribute probeTestData) + { + var @where = new Where(); + @where.TypeName = probeTestData.UseFullTypeName ? method.DeclaringType.FullName : method.DeclaringType.Name; + @where.MethodName = method.Name; + var signature = probeTestData.ReturnTypeName; + if (probeTestData.ParametersTypeName?.Any() == true) + { + signature += "," + string.Join(",", probeTestData.ParametersTypeName); + } + + @where.Signature = signature; + return @where; + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DeterministicGuidGenerator.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DeterministicGuidGenerator.cs new file mode 100644 index 000000000..4613ccc68 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/DeterministicGuidGenerator.cs @@ -0,0 +1,35 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger +{ + /// + /// We want to have deterministic Guid(s) in our testings so we'll be able to assert and approve the same output. + /// This way, we can correlate Snapshots and Probe Statuses to their corresponding Probe request. + /// + internal class DeterministicGuidGenerator + { + private readonly Random _random; + + public DeterministicGuidGenerator(int seed = 1) + { + _random = new Random(seed); + } + + public Guid New() + { + var guid = new byte[16]; + _random.NextBytes(guid); + + return new Guid(guid); + } + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/JsonUtility.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/JsonUtility.cs new file mode 100644 index 000000000..0e16590bd --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/JsonUtility.cs @@ -0,0 +1,68 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Linq; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger; + +public class JsonUtility +{ + /// + /// Alphabetize all the properties in a json document. + /// + /// The string ot normalize + /// Normalized representation of a string. + public static string NormalizeJsonString(string json) + { + // Parse json string into JObject. + var parsedObject = JObject.Parse(json); + + // Sort properties of JObject. + var normalizedObject = SortPropertiesAlphabetically(parsedObject); + + // Serialize JObject . + return JsonConvert.SerializeObject(normalizedObject); + } + + private static JObject SortPropertiesAlphabetically(JObject original) + { + var result = new JObject(); + + foreach (var property in original.Properties().ToList().OrderBy(p => p.Name)) + { + if (property.Value is JObject value) + { + value = SortPropertiesAlphabetically(value); + result.Add(property.Name, value); + } + else if (property.Value is JArray array) + { + var newArray = new JArray(); + foreach (var arrayItem in array) + { + if (arrayItem is JObject obj) + { + newArray.Add(SortPropertiesAlphabetically(obj)); + } + else + { + newArray.Add(arrayItem); + } + } + + result.Add(property.Name, newArray); + } + else + { + result.Add(property.Name, property.Value); + } + } + + return result; + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LiveDebuggerTests.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LiveDebuggerTests.cs new file mode 100644 index 000000000..4a88dec72 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LiveDebuggerTests.cs @@ -0,0 +1,91 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Datadog.Trace.ClrProfiler.IntegrationTests.Debugger.Assertions; +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger; +using Datadog.Trace.Debugger.Configurations; +using Datadog.Trace.Debugger.Sink; +using Datadog.Trace.TestHelpers; +using Samples.Probes; +using VerifyXunit; +using Xunit; +using Xunit.Abstractions; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger; + +#if !NETCOREAPP2_1 +[CollectionDefinition(nameof(LiveDebuggerTests), DisableParallelization = true)] +[Collection(nameof(LiveDebuggerTests))] +[UsesVerify] +public class LiveDebuggerTests : TestHelper +{ + private const string LogFileNamePrefix = "dotnet-tracer-managed-"; + private const string LiveDebuggerDisabledLogEntry = "Live Debugger is disabled. To enable it, please set SIGNALFX_DEBUGGER_ENABLED environment variable to 'true'."; + + public LiveDebuggerTests(ITestOutputHelper output) + : base("Probes", Path.Combine("test", "test-applications", "debugger"), output) + { + SetServiceVersion("1.0.0"); + } + + [Fact] + [Trait("Category", "EndToEnd")] + [Trait("Category", "ArmUnsupported")] + [Trait("RunOnWindows", "True")] + [Trait("Category", "LinuxUnsupported")] + public async Task LiveDebuggerDisabled_DebuggerDisabledByDefault_NoDebuggerTypesCreated() + { + await RunTest(); + } + + [Fact] + [Trait("Category", "EndToEnd")] + [Trait("Category", "ArmUnsupported")] + [Trait("RunOnWindows", "True")] + [Trait("Category", "LinuxUnsupported")] + public async Task LiveDebuggerDisabled_DebuggerExplicitlyDisabled_NoDebuggerTypesCreated() + { + SetEnvironmentVariable(ConfigurationKeys.Debugger.Enabled, "0"); + await RunTest(); + } + + private async Task RunTest() + { + var guidGenerator = new DeterministicGuidGenerator(); + var testType = + typeof(IRun) + .Assembly.GetTypes() + .Where(t => t.GetInterface(nameof(IRun)) != null) + .First(t => DebuggerTestHelper.GetAllProbes(t, EnvironmentHelper.GetTargetFramework(), unlisted: false, guidGenerator).Any()); + + using var agent = EnvironmentHelper.GetMockAgent(); + + using var sample = StartSample(agent, $"--test-name {testType.FullName}", string.Empty, aspNetCorePort: 5000); + using var logEntryWatcher = new LogEntryWatcher($"{LogFileNamePrefix}{sample.ProcessName}*"); + await logEntryWatcher.WaitForLogEntry(LiveDebuggerDisabledLogEntry); + + try + { + var memoryAssertions = MemoryAssertions.CaptureSnapshotToAssertOn(sample); + + memoryAssertions.NoObjectsExist(); + memoryAssertions.NoObjectsExist(); + memoryAssertions.NoObjectsExist(); + } + finally + { + if (!sample.HasExited) + { + sample.Kill(); + } + } + } +} +#endif diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LogEntryWatcher.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LogEntryWatcher.cs new file mode 100644 index 000000000..30bf26ef3 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/LogEntryWatcher.cs @@ -0,0 +1,106 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Datadog.Trace.Logging; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger; + +internal class LogEntryWatcher : IDisposable +{ + private readonly FileSystemWatcher _fileWatcher; + private StreamReader _reader; + + public LogEntryWatcher(string logFilePattern) + { + var logPath = DatadogLogging.GetLogDirectory(); + _fileWatcher = new FileSystemWatcher + { + Path = logPath, + Filter = logFilePattern, + EnableRaisingEvents = true + }; + + var dir = new DirectoryInfo(logPath); + var lastFile = dir + .GetFiles(logFilePattern) + .OrderBy(info => info.LastWriteTime) + .LastOrDefault(); + + if (lastFile != null && lastFile.LastWriteTime.Date == DateTime.Today) + { + SetStream(lastFile.FullName); + _reader.ReadToEnd(); + } + + _fileWatcher.Created += NewLogFileCreated; + } + + public void Dispose() + { + _fileWatcher?.Dispose(); + _reader?.Dispose(); + } + + public async Task WaitForLogEntry(string logEntry, TimeSpan? timeout = null) + { + using var cancellationSource = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + + var isFound = false; + while (!isFound && !cancellationSource.IsCancellationRequested) + { + if (_reader == null) + { + await Task.Delay(100); + continue; + } + + var line = await _reader.ReadLineAsync(); + if (line != null) + { + isFound = line?.Contains(logEntry) == true; + } + else + { + await Task.Delay(100); + } + } + + if (!isFound) + { + throw new InvalidOperationException("Log entry was not found."); + } + } + + private void SetStream(string filePath) + { + var reader = _reader; + + try + { + var fileStream = new FileStream( + filePath, + FileMode.Open, + FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete); + + _reader = new StreamReader(fileStream, Encoding.UTF8); + } + finally + { + reader?.Dispose(); + } + } + + private void NewLogFileCreated(object sender, FileSystemEventArgs e) + { + SetStream(e.FullPath); + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/ProbesTests.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/ProbesTests.cs new file mode 100644 index 000000000..e3edec925 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/ProbesTests.cs @@ -0,0 +1,392 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.TestHelpers; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Samples.Probes; +using Samples.Probes.SmokeTests; +using VerifyTests; +using VerifyXunit; +using Xunit; +using Xunit.Abstractions; + +namespace Datadog.Trace.ClrProfiler.IntegrationTests.Debugger; + +[CollectionDefinition(nameof(ProbesTests), DisableParallelization = true)] +[Collection(nameof(ProbesTests))] +[UsesVerify] +public class ProbesTests : TestHelper +{ + private const string LogFileNamePrefix = "dotnet-tracer-managed-"; + private const string ProbesInstrumentedLogEntry = "Live Debugger.InstrumentProbes: Request to instrument probes definitions completed."; + private const string ProbesDefinitionFileName = "probes_definition.json"; + private readonly string[] _typesToScrub = { nameof(IntPtr), nameof(Guid) }; + private readonly string[] _knownPropertiesToReplace = { "duration", "timestamp", "dd.span_id", "dd.trace_id", "id", "lineNumber", "thread_name", "thread_id" }; + + public ProbesTests(ITestOutputHelper output) + : base("Probes", Path.Combine("test", "test-applications", "debugger"), output) + { + SetServiceVersion("1.0.0"); + } + + public static IEnumerable ProbeTests() + { + return typeof(IRun).Assembly.GetTypes() + .Where(t => t.GetInterface(nameof(IRun)) != null) + .Select(t => new object[] { t }); + } + + [SkippableTheory] + [Trait("Category", "EndToEnd")] + [Trait("RunOnWindows", "True")] + [InlineData(typeof(OverloadAndSimpleNameTest))] + public async Task InstallAndUninstallMethodProbeWithOverloadsTest(Type testType) + { + const int expectedNumberOfSnapshots = 9; + + var probes = GetProbeConfiguration(testType, true, new DeterministicGuidGenerator()); + + if (probes.Length != 1) + { + throw new InvalidOperationException($"{nameof(InstallAndUninstallMethodProbeWithOverloadsTest)} expected one probe request to exist, but found {probes.Length} probes."); + } + + var agent = GetMockAgent(); + + SetDebuggerEnvironment(); + using var sample = DebuggerTestHelper.StartSample(this, agent, testType.FullName); + using var logEntryWatcher = new LogEntryWatcher($"{LogFileNamePrefix}{sample.Process.ProcessName}*"); + + SetProbeConfiguration(DebuggerTestHelper.CreateProbeDefinition(probes.Select(p => p.Probe).ToArray())); + await logEntryWatcher.WaitForLogEntry(ProbesInstrumentedLogEntry); + + await sample.RunCodeSample(); + try + { + var snapshots = await agent.WaitForSnapshots(expectedNumberOfSnapshots); + Assert.Equal(expectedNumberOfSnapshots, snapshots?.Length); + await ApproveSnapshots(snapshots, testType, isMultiPhase: true, phaseNumber: 1); + agent.ClearSnapshots(); + + var statuses = await agent.WaitForProbesStatuses(probes.Length); + Assert.Equal(probes.Length, statuses?.Length); + await ApproveStatuses(statuses, testType, isMultiPhase: true, phaseNumber: 1); + agent.ClearProbeStatuses(); + + var emptyDefinition = DebuggerTestHelper.CreateProbeDefinition(Array.Empty()); + SetProbeConfiguration(emptyDefinition); + await logEntryWatcher.WaitForLogEntry(ProbesInstrumentedLogEntry); + Assert.True(await agent.WaitForNoSnapshots(6000), $"Expected 0 snapshots. Actual: {agent.Snapshots.Count}."); + } + finally + { + await sample.StopSample(); + } + } + + [SkippableFact] + [Trait("Category", "EndToEnd")] + [Trait("RunOnWindows", "True")] + public async Task LineProbeEmit100SnapshotsTest() + { + var testType = typeof(Emit100LineProbeSnapshotsTest); + const int expectedNumberOfSnapshots = 100; + + var probes = GetProbeConfiguration(testType, true, new DeterministicGuidGenerator()); + var agent = GetMockAgent(); + + SetDebuggerEnvironment(); + using var sample = DebuggerTestHelper.StartSample(this, agent, testType.FullName); + using var logEntryWatcher = new LogEntryWatcher($"{LogFileNamePrefix}{sample.Process.ProcessName}*"); + + SetProbeConfiguration(DebuggerTestHelper.CreateProbeDefinition(probes.Select(p => p.Probe).ToArray())); + await logEntryWatcher.WaitForLogEntry(ProbesInstrumentedLogEntry); + + await sample.RunCodeSample(); + try + { + var statuses = await agent.WaitForProbesStatuses(probes.Length); + Assert.Equal(probes.Length, statuses?.Length); + + var snapshots = await agent.WaitForSnapshots(expectedNumberOfSnapshots); + Assert.Equal(expectedNumberOfSnapshots, snapshots?.Length); + Assert.True(snapshots.All(IsSaneSnapshot), "Not all snapshots are sane."); + Assert.True(snapshots.Distinct().Count() == snapshots.Length, "All snapshots should be unique."); + } + finally + { + await sample.StopSample(); + } + + bool IsSaneSnapshot(string snapshot) + { + var shouldBeInSnapshot = new[] { "message", "logger", "stack", "probe", "snapshot", "debugger" }; + + return snapshot.Length > 250 && + shouldBeInSnapshot.All(snapshot.Contains); + } + } + + [SkippableTheory] + [Trait("Category", "EndToEnd")] + [Trait("RunOnWindows", "True")] + [MemberData(nameof(ProbeTests))] + public async Task MethodProbeTest(Type testType) + { + var probes = GetProbeConfiguration(testType, false, new DeterministicGuidGenerator()); + var agent = GetMockAgent(); + + SetDebuggerEnvironment(); + using var sample = DebuggerTestHelper.StartSample(this, agent, testType.FullName); + using var logEntryWatcher = new LogEntryWatcher($"{LogFileNamePrefix}{sample.Process.ProcessName}*"); + + try + { + var isSinglePhase = probes.Select(p => p.ProbeTestData.Phase).Distinct().Count() == 1; + if (isSinglePhase) + { + await PerformSinglePhaseProbeTest(); + } + else + { + await PerformMultiPhasesProbeTest(); + } + } + finally + { + await sample.StopSample(); + } + + async Task PerformSinglePhaseProbeTest() + { + var snapshotProbes = probes.Select(p => p.Probe).ToArray(); + var probeData = probes.Select(p => p.ProbeTestData).ToArray(); + + await RunPhase(snapshotProbes, probeData); + } + + async Task PerformMultiPhasesProbeTest() + { + var phaseNumber = 0; + var groupedPhases = + probes + .GroupBy(p => p.ProbeTestData.Phase) + .OrderBy(group => group.Key); + + foreach (var groupedPhase in groupedPhases) + { + phaseNumber++; + + var snapshotProbes = groupedPhase.Select(p => p.Probe).ToArray(); + var probeData = groupedPhase.Select(p => p.ProbeTestData).ToArray(); + await RunPhase(snapshotProbes, probeData, isMultiPhase: true, phaseNumber); + } + } + + async Task RunPhase(SnapshotProbe[] snapshotProbes, ProbeAttributeBase[] probeData, bool isMultiPhase = false, int phaseNumber = 1) + { + var definition = DebuggerTestHelper.CreateProbeDefinition(snapshotProbes); + SetProbeConfiguration(definition); + await logEntryWatcher.WaitForLogEntry(ProbesInstrumentedLogEntry); + + await sample.RunCodeSample(); + + var expectedNumberOfSnapshots = DebuggerTestHelper.CalculateExpectedNumberOfSnapshots(probeData); + string[] snapshots; + if (expectedNumberOfSnapshots == 0) + { + Assert.True(await agent.WaitForNoSnapshots(), $"Expected 0 snapshots. Actual: {agent.Snapshots.Count}."); + } + else + { + snapshots = await agent.WaitForSnapshots(expectedNumberOfSnapshots); + Assert.Equal(expectedNumberOfSnapshots, snapshots?.Length); + await ApproveSnapshots(snapshots, testType, isMultiPhase, phaseNumber); + agent.ClearSnapshots(); + } + + var statuses = await agent.WaitForProbesStatuses(probeData.Length); + + Assert.Equal(probeData.Length, statuses?.Length); + await ApproveStatuses(statuses, testType, isMultiPhase, phaseNumber); + agent.ClearProbeStatuses(); + } + } + + private async Task ApproveSnapshots(string[] snapshots, Type testType, bool isMultiPhase, int phaseNumber) + { + await ApproveOnDisk(snapshots, testType, isMultiPhase, phaseNumber, "snapshots"); + } + + private async Task ApproveStatuses(string[] statuses, Type testType, bool isMultiPhase, int phaseNumber) + { + await ApproveOnDisk(statuses, testType, isMultiPhase, phaseNumber, "statuses"); + } + + private async Task ApproveOnDisk(string[] dataToApprove, Type testType, bool isMultiPhase, int phaseNumber, string path) + { + if (dataToApprove.Length > 1) + { + // Order the snapshots alphabetically so we'll be able to create deterministic approvals + dataToApprove = dataToApprove.OrderBy(snapshot => snapshot).ToArray(); + } + + var settings = new VerifySettings(); + + var phaseText = isMultiPhase ? $"#{phaseNumber}." : string.Empty; + settings.UseParameters(testType + phaseText); + + settings.ScrubEmptyLines(); + settings.AddScrubber(ScrubSnapshotJson); + + VerifierSettings.DerivePathInfo( + (sourceFile, _, _, _) => new PathInfo(directory: Path.Combine(sourceFile, "..", path))); + + var toVerify = + "[" + + + string.Join( + ",", + dataToApprove.Select(JsonUtility.NormalizeJsonString)) + + + "]"; + + await Verifier.Verify(NormalizeLineEndings(toVerify), settings); + + void ScrubSnapshotJson(StringBuilder input) + { + var json = JArray.Parse(input.ToString()); + + var toRemove = new List(); + foreach (var descendant in json.DescendantsAndSelf().OfType()) + { + foreach (var item in descendant) + { + try + { + if (_knownPropertiesToReplace.Contains(item.Key) && item.Value != null) + { + item.Value.Replace(JToken.FromObject("ScrubbedValue")); + continue; + } + + var value = item.Value.ToString(); + switch (item.Key) + { + case "type": + // Sanitizes types whose values may vary from run to run and consequently produce a different approval file. + if (_typesToScrub.Contains(item.Value.ToString())) + { + item.Value.Parent.Parent["value"].Replace("ScrubbedValue"); + } + + break; + case "function": + + // Remove stackframes from "System" namespace, or where the frame was not resolved to a method + if (value.StartsWith("System") || value == string.Empty) + { + toRemove.Add(item.Value.Parent.Parent); + continue; + } + + // Scrub MoveNext methods from `stack` in the snapshot as it varies between Windows/Linux. + if (item.Key == "function" && value.Contains(".MoveNext")) + { + item.Value.Replace(string.Empty); + } + + break; + case "fileName": + case "file": + // Remove the full path of file names + item.Value.Replace(Path.GetFileName(value)); + + break; + } + } + catch (Exception) + { + Output.WriteLine($"Failed to sanitize snapshot. The part we are trying to sanitize: {item}"); + Output.WriteLine($"Complete snapshot: {json}"); + + throw; + } + } + } + + foreach (var itemToRemove in toRemove) + { + itemToRemove.Remove(); + } + + input.Clear().Append(json); + } + + string NormalizeLineEndings(string text) => + text + .Replace(@"\r\n", @"\n") + .Replace(@"\n\r", @"\n") + .Replace(@"\r", @"\n") + .Replace(@"\n", @"\r\n"); + } + + private (ProbeAttributeBase ProbeTestData, SnapshotProbe Probe)[] GetProbeConfiguration(Type testType, bool unlisted, DeterministicGuidGenerator guidGenerator) + { + var probes = DebuggerTestHelper.GetAllProbes(testType, EnvironmentHelper.GetTargetFramework(), unlisted, guidGenerator); + if (!probes.Any()) + { + throw new SkipException($"No probes for {testType.Name}, skipping."); + } + + return probes; + } + + private void SetDebuggerEnvironment() + { + var probeConfiguration = DebuggerTestHelper.CreateProbeDefinition(Array.Empty()); + var path = SetProbeConfiguration(probeConfiguration); + + SetEnvironmentVariable(ConfigurationKeys.Debugger.ProbeFile, path); + SetEnvironmentVariable(ConfigurationKeys.Debugger.Enabled, "1"); + SetEnvironmentVariable(ConfigurationKeys.Debugger.MaxDepthToSerialize, "3"); + SetEnvironmentVariable(ConfigurationKeys.Debugger.DiagnosticsInterval, "1"); + } + + private string SetProbeConfiguration(ProbeConfiguration probeConfiguration) + { + var json = JsonConvert.SerializeObject(probeConfiguration, Formatting.Indented); + + // We are not using a temp file here, but rather writing it directly to the debugger sample project, + // so that if a test fails, we will be able to simply hit F5 to debug the same probe + // configuration (launchsettings.json references the same file). + var path = Path.Combine(EnvironmentHelper.GetSampleProjectDirectory(), ProbesDefinitionFileName); + File.WriteAllText(path, json); + return path; + } + + private MockTracerAgent GetMockAgent() + { + var mockAgent = EnvironmentHelper.GetMockAgent(); + + if (mockAgent is not MockTracerAgent.TcpUdpAgent agent) + { + throw new NotSupportedException($"Expected the mock agent to be of type {typeof(MockTracerAgent.TcpUdpAgent)} but found {mockAgent.GetType()}."); + } + + SetEnvironmentVariable(ConfigurationKeys.AgentPort, agent.Port.ToString()); + agent.ShouldDeserializeTraces = false; + return agent; + } +} diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt new file mode 100644 index 000000000..3e406a635 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt @@ -0,0 +1,1240 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "a": { + "fields": null, + "type": "Int32", + "value": "-2147483648" + } + }, + "fields": null + }, + "return": { + "arguments": { + "a": { + "fields": null, + "type": "Int32", + "value": "-2147483648" + } + }, + "fields": null, + "throwable": { + "message": "The method or operation is not implemented.", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.ThrowException", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_0", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + } + ], + "type": "System.NotImplementedException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_0", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(a=-2147483648)", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "a": { + "fields": null, + "type": "Int32", + "value": "-2147483648" + }, + "b": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "fields": null + }, + "return": { + "arguments": { + "a": { + "fields": null, + "type": "Int32", + "value": "-2147483648" + }, + "b": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "fields": null, + "throwable": { + "message": "The method or operation is not implemented.", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.ThrowException", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_1", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + } + ], + "type": "System.NotImplementedException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_1", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(a=-2147483648, b=2147483647)", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "a": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "44" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "44" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Theodor Herzl" + } + }, + "type": "Person", + "value": "Person" + }, + "b": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "58" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "58" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "David Wolffsohn" + } + }, + "type": "Person", + "value": "Person" + } + }, + "fields": null + }, + "return": { + "arguments": { + "a": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "44" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "44" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Theodor Herzl" + } + }, + "type": "Person", + "value": "Person" + }, + "b": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "58" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "58" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "David Wolffsohn" + } + }, + "type": "Person", + "value": "Person" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "50" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "50.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Person Name" + } + }, + "type": "Person", + "value": "Person" + }, + "isEqual": { + "fields": null, + "type": "Boolean", + "value": "False" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "OuterType+OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "OuterType+OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "OuterType+OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "Method(a=Person, b=Person): Person\r\n@return=Person, isEqual=False", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "a": { + "fields": null, + "type": "String", + "value": "Marty McFly" + } + }, + "fields": null + }, + "return": { + "arguments": { + "a": { + "fields": null, + "type": "String", + "value": "Marty McFly" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "OuterType+OverloadAndSimpleNameTest.Method[Marty McFly]" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "OuterType+OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "OuterType+OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "OuterType+OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "Method(a=Marty McFly): OuterType+OverloadAndSimpleNameTest.Method[Marty McFly]\r\n@return=OuterType+OverloadAndSimpleNameTest.Method[Marty McFly]", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "adr": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "Some Place" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + } + }, + "fields": null + }, + "return": { + "arguments": { + "adr": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "Some Place" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "Some Place" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "Street": { + "fields": null, + "type": "String", + "value": "null" + } + }, + "type": "Address", + "value": "Address" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Spicing.Things.Up.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Spicing.Things.Up.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Spicing.Things.Up.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(adr=Address): Address\r\n@return=Address", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null + }, + "return": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest.Method.@" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OuterType+OverloadAndSimpleNameTest.Method(c=@): Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest.Method.@\r\n@return=Spicing.Things.Down.OuterType+OverloadAndSimpleNameTest.Method.@", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null + }, + "return": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Spicing.Things.Up.OverloadAndSimpleNameTest.Method.@" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Spicing.Things.Up.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Spicing.Things.Up.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Spicing.Things.Up.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(c=@): Spicing.Things.Up.OverloadAndSimpleNameTest.Method.@\r\n@return=Spicing.Things.Up.OverloadAndSimpleNameTest.Method.@", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null + }, + "return": { + "arguments": { + "c": { + "fields": null, + "type": "Char", + "value": "@" + } + }, + "fields": null, + "locals": { + "local": { + "fields": null, + "type": "String", + "value": "Method@" + } + }, + "throwable": { + "message": "The method or operation is not implemented.", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.ThrowException", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_2", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + } + ], + "type": "System.NotImplementedException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.b__0_2", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.CaptureException", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(c=@)\r\nlocal=Method@", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "First Call" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "First Call" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "13" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest" + } + }, + "stack": [ + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OverloadAndSimpleNameTest.cs", + "function": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.OverloadAndSimpleNameTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OverloadAndSimpleNameTest.Method(callerName=First Call)\r\na=13", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt new file mode 100644 index 000000000..fc64185e1 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt @@ -0,0 +1,356 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "genericParam": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Duplex" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Alfred Hitchcock" + } + }, + "type": "Person", + "value": "Person" + } + }, + "fields": { + "Prop": { + "fields": null, + "type": "String", + "value": "GenericMethodWithArguments" + } + } + }, + "return": { + "arguments": { + "genericParam": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Duplex" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Alfred Hitchcock" + } + }, + "type": "Person", + "value": "Person" + } + }, + "fields": { + "Prop": { + "fields": null, + "type": "String", + "value": "GenericMethodWithArguments" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Alfred Hitchcock (30)" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.GenericMethodWithArguments" + } + }, + "stack": [ + { + "fileName": "GenericMethodWithArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.GenericMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "GenericMethodWithArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.GenericMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.GenericMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "GenericMethodWithArguments.Method(genericParam=Person): Alfred Hitchcock (30)\r\n@return=Alfred Hitchcock (30)", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "22": { + "arguments": { + "genericParam": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Duplex" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Alfred Hitchcock" + } + }, + "type": "Person", + "value": "Person" + } + }, + "fields": { + "Prop": { + "fields": null, + "type": "String", + "value": "GenericMethodWithArguments" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "GenericMethodWithArgumentsAndLocals.cs", + "lines": [ + 22 + ] + } + }, + "stack": [ + { + "fileName": "GenericMethodWithArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.GenericMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "GenericMethodWithArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.GenericMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.GenericMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "GenericMethodWithArguments.Method(genericParam=Person)", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt new file mode 100644 index 000000000..a937b637a --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt @@ -0,0 +1,94 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": { + "FirstName": { + "fields": null, + "type": "String", + "value": "null" + } + } + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": { + "FirstName": { + "fields": null, + "type": "String", + "value": "First" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "First Last" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasArgumentsAndLocals" + } + }, + "stack": [ + { + "fileName": "HasArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.HasArgumentsAndLocals.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasArgumentsAndLocals.cs", + "function": "Samples.Probes.SmokeTests.HasArgumentsAndLocals.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasArgumentsAndLocals", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasArgumentsAndLocals.Method(lastName=Last): First Last\r\n@return=First Last", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt new file mode 100644 index 000000000..6b024baae --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt @@ -0,0 +1,116 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "First" + } + }, + "fields": { + "FirstName": { + "fields": { + "IsValueCreated": { + "fields": null, + "type": "Boolean", + "value": "True" + }, + "Value": { + "fields": null, + "type": "String", + "value": "First" + } + }, + "type": "Lazy`1", + "value": "Lazy`1" + } + } + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "First" + } + }, + "fields": { + "FirstName": { + "fields": { + "IsValueCreated": { + "fields": null, + "type": "Boolean", + "value": "True" + }, + "Value": { + "fields": null, + "type": "String", + "value": "First" + } + }, + "type": "Lazy`1", + "value": "Lazy`1" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "First" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasFieldLazyValueInitialized" + } + }, + "stack": [ + { + "fileName": "HasFieldLazyValueInitialized.cs", + "function": "Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasFieldLazyValueInitialized.cs", + "function": "Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasFieldLazyValueInitialized", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasFieldLazyValueInitialized.Method(lastName=First): First\r\n@return=First", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt new file mode 100644 index 000000000..1d72cc7a1 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt @@ -0,0 +1,106 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": { + "FirstName": { + "fields": { + "IsValueCreated": { + "fields": null, + "type": "Boolean", + "value": "False" + } + }, + "type": "Lazy`1", + "value": "Lazy`1" + } + } + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": { + "FirstName": { + "fields": { + "IsValueCreated": { + "fields": null, + "type": "Boolean", + "value": "False" + } + }, + "type": "Lazy`1", + "value": "Lazy`1" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Last" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized" + } + }, + "stack": [ + { + "fileName": "HasFieldLazyValueNotInitialized.cs", + "function": "Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasFieldLazyValueNotInitialized.cs", + "function": "Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasFieldLazyValueNotInitialized.Method(lastName=Last): Last\r\n@return=Last", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt new file mode 100644 index 000000000..a475d7705 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt @@ -0,0 +1,553 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "age": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "name": { + "fields": null, + "type": "String", + "value": "Greg" + } + }, + "fields": null + }, + "return": { + "arguments": { + "age": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "name": { + "fields": null, + "type": "String", + "value": "Greg" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Hello Greg (36)!" + }, + "children": { + "Collection": [ + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Simon" + } + }, + "type": "Person", + "value": "Person" + }, + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Lucy" + } + }, + "type": "Person", + "value": "Person" + } + ], + "type": "List`1", + "value": "count: 2" + }, + "p": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "17" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Somewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "36" + }, + "Children": { + "Collection": [ + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": null, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Simon" + } + }, + "type": "Person", + "value": "Person" + }, + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": null, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Lucy" + } + }, + "type": "Person", + "value": "Person" + } + ], + "type": "List`1", + "value": "count: 2" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Greg" + } + }, + "type": "Person", + "value": "Person" + }, + "p2": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Simon" + } + }, + "type": "Person", + "value": "Person" + }, + "p3": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "Lucy" + } + }, + "type": "Person", + "value": "Person" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasLocalListOfObjects" + } + }, + "stack": [ + { + "fileName": "HasLocalListOfObjects.cs", + "function": "Samples.Probes.SmokeTests.HasLocalListOfObjects.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasLocalListOfObjects.cs", + "function": "Samples.Probes.SmokeTests.HasLocalListOfObjects.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalListOfObjects", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalListOfObjects.Method(age=36, name=Greg): Hello Greg (36)!\r\n@return=Hello Greg (36)!, children=count: 2, p=Person, p2=Person, p3=Person", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt new file mode 100644 index 000000000..b2ea19b2f --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt @@ -0,0 +1,563 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "age": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "genericVar": { + "fields": null, + "type": "GenericInstantiation", + "value": "GenericInstantiation" + } + }, + "fields": null + }, + "return": { + "arguments": { + "age": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "genericVar": { + "fields": null, + "type": "GenericInstantiation", + "value": "GenericInstantiation" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Hello GenericInstantiation! (36)!" + }, + "children": { + "Collection": [ + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Simon" + } + }, + "type": "Person", + "value": "Person" + }, + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Lucy" + } + }, + "type": "Person", + "value": "Person" + } + ], + "type": "List`1", + "value": "count: 2" + }, + "genericVarToString": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!" + }, + "newT": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!" + }, + "p": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "36" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Cottage" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "17" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Somewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "36" + }, + "Children": { + "Collection": [ + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": null, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Simon" + } + }, + "type": "Person", + "value": "Person" + }, + { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": null, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Lucy" + } + }, + "type": "Person", + "value": "Person" + } + ], + "type": "List`1", + "value": "count: 2" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!" + } + }, + "type": "Person", + "value": "Person" + }, + "p2": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "30" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "Hotel" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Elsewhere" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "30" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Simon" + } + }, + "type": "Person", + "value": "Person" + }, + "p3": { + "fields": { + "_shouldCloned": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "Address": { + "fields": { + "City": { + "fields": { + "Name": { + "fields": null, + "type": "String", + "value": "null" + }, + "Type": { + "fields": null, + "type": "PlaceType", + "value": "City" + } + }, + "type": "Place", + "value": "Place" + }, + "HomeType": { + "fields": null, + "type": "BuildingType", + "value": "House" + }, + "Number": { + "fields": null, + "type": "Int32", + "value": "100" + }, + "Street": { + "fields": null, + "type": "String", + "value": "Here" + } + }, + "type": "Address", + "value": "Address" + }, + "Age": { + "fields": null, + "type": "Double", + "value": "7.5" + }, + "Children": { + "fields": null, + "type": "List`1", + "value": "null" + }, + "Id": { + "fields": null, + "type": "Guid", + "value": "ScrubbedValue" + }, + "Name": { + "fields": null, + "type": "String", + "value": "GenericInstantiation!Lucy" + } + }, + "type": "Person", + "value": "Person" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType+Test`1" + } + }, + "stack": [ + { + "fileName": "HasLocalsAndArgumentsInGenericType.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType+Test`1.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasLocalsAndArgumentsInGenericType.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType+Test`1", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalsAndArgumentsInGenericNestedType+Test`1.Method(age=36, genericVar=GenericInstantiation): Hello GenericInstantiation! (36)!\r\n@return=Hello GenericInstantiation! (36)!, children=count: 2, genericVarToString=GenericInstantiation!, newT=GenericInstantiation!, p=Person, p2=Person, p3=Person", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt new file mode 100644 index 000000000..583d18951 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt @@ -0,0 +1,315 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "num": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + } + }, + "return": { + "arguments": { + "num": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "00:00:07" + }, + "timeSpan": { + "fields": null, + "type": "TimeSpan", + "value": "00:00:07" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue" + } + }, + "stack": [ + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalsAndReturnValue.Method(num=7): 00:00:07\r\n@return=00:00:07, timeSpan=00:00:07", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "16": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "locals": { + "result": { + "fields": null, + "type": "String", + "value": "null" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "HasLocalsAndReturnValue.cs", + "lines": [ + 16 + ] + } + }, + "stack": [ + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalsAndReturnValue.Run()\r\nresult=null", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "17": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "locals": { + "result": { + "fields": null, + "type": "String", + "value": "00:00:07" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "HasLocalsAndReturnValue.cs", + "lines": [ + 17 + ] + } + }, + "stack": [ + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalsAndReturnValue.Run()\r\nresult=00:00:07", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "25": { + "arguments": { + "num": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "locals": { + "timeSpan": { + "fields": null, + "type": "TimeSpan", + "value": "00:00:07" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "HasLocalsAndReturnValue.cs", + "lines": [ + 25 + ] + } + }, + "stack": [ + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasLocalsAndReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasLocalsAndReturnValue", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasLocalsAndReturnValue.Method(num=7)\r\ntimeSpan=00:00:07", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt new file mode 100644 index 000000000..0d7c189f8 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt @@ -0,0 +1,80 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + }, + "return": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "7" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasReturnValue" + } + }, + "stack": [ + { + "fileName": "HasReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasReturnValue.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasReturnValue.cs", + "function": "Samples.Probes.SmokeTests.HasReturnValue.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasReturnValue", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasReturnValue.Method(): 7\r\n@return=7", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt new file mode 100644 index 000000000..eba2244aa --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt @@ -0,0 +1,127 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "k": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + } + }, + "fields": null + }, + "return": { + "arguments": { + "k": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + } + }, + "fields": null, + "locals": { + "@return": { + "Collection": [ + { + "fields": null, + "type": "Test`1", + "value": "Test`1" + } + ], + "type": "List`1", + "value": "count: 1" + }, + "kk": { + "Collection": [ + { + "fields": null, + "type": "Test`1", + "value": "Test`1" + } + ], + "type": "List`1", + "value": "count: 1" + }, + "string": { + "fields": null, + "type": "String", + "value": "Samples.Probes.Shared.Generic" + }, + "tt": { + "Collection": [ + { + "fields": null, + "type": "Test`1", + "value": "Test`1" + } + ], + "type": "List`1", + "value": "count: 1" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.HasVarAndMvar+Test`1" + } + }, + "stack": [ + { + "fileName": "HasVarAndMvar.cs", + "function": "Samples.Probes.SmokeTests.HasVarAndMvar+Test`1.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "HasVarAndMvar.cs", + "function": "Samples.Probes.SmokeTests.HasVarAndMvar.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.HasVarAndMvar+Test`1", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "HasVarAndMvar+Test`1.Method(k=Generic): count: 1\r\n@return=count: 1, kk=count: 1, string=Samples.Probes.Shared.Generic, tt=count: 1", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt new file mode 100644 index 000000000..d5131ad33 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt @@ -0,0 +1,149 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Last" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.InstanceMethodWithArguments" + } + }, + "stack": [ + { + "fileName": "InstanceMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.InstanceMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "InstanceMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.InstanceMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.InstanceMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "InstanceMethodWithArguments.Method(lastName=Last): Last\r\n@return=Last", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "18": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "InstanceMethodWithArguments.cs", + "lines": [ + 18 + ] + } + }, + "stack": [ + { + "fileName": "InstanceMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.InstanceMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "InstanceMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.InstanceMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.InstanceMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "InstanceMethodWithArguments.Method(lastName=Last)", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt new file mode 100644 index 000000000..1a622854c --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt @@ -0,0 +1,73 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + }, + "return": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.InstanceVoidMethod" + } + }, + "stack": [ + { + "fileName": "InstanceVoidMethod.cs", + "function": "Samples.Probes.SmokeTests.InstanceVoidMethod.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "InstanceVoidMethod.cs", + "function": "Samples.Probes.SmokeTests.InstanceVoidMethod.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.InstanceVoidMethod", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "InstanceVoidMethod.Method()", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt new file mode 100644 index 000000000..039c2cb9b --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt @@ -0,0 +1,344 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "8" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "Samples.Probes.SmokeTests.LineProbesWithRevertTest" + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=8, i=5, sum=72", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "41": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 41 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=0, i=0, sum=0", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "55": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 55 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=5, sum=72", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "56": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "4" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 56 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=4, i=5, sum=72", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt new file mode 100644 index 000000000..33b30dcf9 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt @@ -0,0 +1,422 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "41": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 41 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=0, i=0, sum=0", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "55": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 55 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=5, sum=72", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "56": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "4" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 56 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=4, i=5, sum=72", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "57": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 57 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=5, i=5, sum=72", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "58": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "6" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 58 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=6, i=5, sum=72", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt new file mode 100644 index 000000000..e8c29c5b0 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt @@ -0,0 +1,338 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "4" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "18" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=4, sum=18", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "2" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "3" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=2, sum=3", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "6" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=3, sum=6", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "59": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "7" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 59 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=7, i=5, sum=72", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt new file mode 100644 index 000000000..1acc19ad0 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt @@ -0,0 +1,86 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "55": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "5" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "72" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 55 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=5, sum=72", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt new file mode 100644 index 000000000..5eba1272c --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt @@ -0,0 +1,254 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "4" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "18" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=4, sum=18", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "2" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "3" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=2, sum=3", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "46": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "i": { + "fields": null, + "type": "Int32", + "value": "3" + }, + "sum": { + "fields": null, + "type": "Int32", + "value": "6" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "LineProbesWithRevertTest.cs", + "lines": [ + 46 + ] + } + }, + "stack": [ + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "LineProbesWithRevertTest.cs", + "function": "Samples.Probes.SmokeTests.LineProbesWithRevertTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "LineProbesWithRevertTest.MethodToInstrument(callerName=Run)\r\na=3, i=3, sum=6", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt new file mode 100644 index 000000000..0637a088a --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt new file mode 100644 index 000000000..8bb53b53e --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt @@ -0,0 +1,188 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "toSet": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + }, + "return": { + "arguments": { + "toSet": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "locals": { + "numberSnapshot": { + "fields": null, + "type": "Int32", + "value": "7" + } + }, + "throwable": { + "message": "Number 2147483647is above snapshot value 7", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Run", + "lineNumber": "ScrubbedValue" + } + ], + "type": "System.InvalidOperationException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.MethodThrowExceptionTest" + } + }, + "stack": [ + { + "fileName": "MethodThrowExceptionTest.cs", + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MethodThrowExceptionTest.cs", + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MethodThrowExceptionTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MethodThrowExceptionTest.Method(toSet=2147483647)\r\nnumberSnapshot=7", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "26": { + "arguments": { + "toSet": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "2147483647" + } + }, + "locals": { + "numberSnapshot": { + "fields": null, + "type": "Int32", + "value": "7" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MethodThrowExceptionTest.cs", + "lines": [ + 26 + ] + } + }, + "stack": [ + { + "fileName": "MethodThrowExceptionTest.cs", + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MethodThrowExceptionTest.cs", + "function": "Samples.Probes.SmokeTests.MethodThrowExceptionTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MethodThrowExceptionTest", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MethodThrowExceptionTest.Method(toSet=2147483647)\r\nnumberSnapshot=7", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt new file mode 100644 index 000000000..7b0e483bc --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt @@ -0,0 +1,270 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "26": { + "fields": null, + "locals": { + "i": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "localInFor": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultiScopesWithSameLocalNameTest.cs", + "lines": [ + 26 + ] + } + }, + "stack": [ + { + "fileName": "MultiScopesWithSameLocalNameTest.cs", + "function": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultiScopesWithSameLocalNameTest.Run()\r\ni=0, localInFor=0", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "26": { + "fields": null, + "locals": { + "i": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "localInFor": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultiScopesWithSameLocalNameTest.cs", + "lines": [ + 26 + ] + } + }, + "stack": [ + { + "fileName": "MultiScopesWithSameLocalNameTest.cs", + "function": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultiScopesWithSameLocalNameTest.Run()\r\ni=0, localInFor=0", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "33": { + "fields": null, + "locals": { + "i": { + "fields": null, + "type": "Int32", + "value": "0" + }, + "localInFor": { + "fields": null, + "type": "Int32", + "value": "9" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultiScopesWithSameLocalNameTest.cs", + "lines": [ + 33 + ] + } + }, + "stack": [ + { + "fileName": "MultiScopesWithSameLocalNameTest.cs", + "function": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultiScopesWithSameLocalNameTest.Run()\r\ni=0, localInFor=9", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "33": { + "fields": null, + "locals": { + "i": { + "fields": null, + "type": "Int32", + "value": "1" + }, + "localInFor": { + "fields": null, + "type": "Int32", + "value": "10" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultiScopesWithSameLocalNameTest.cs", + "lines": [ + 33 + ] + } + }, + "stack": [ + { + "fileName": "MultiScopesWithSameLocalNameTest.cs", + "function": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest", + "name": "Run", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultiScopesWithSameLocalNameTest.Run()\r\ni=1, localInFor=10", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt new file mode 100644 index 000000000..bb1024c4a --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt @@ -0,0 +1,452 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "6" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "Samples.Probes.SmokeTests.MultipleLineProbes" + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=6", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "21": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultipleLineProbes.cs", + "lines": [ + 21 + ] + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=0", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "22": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "3" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultipleLineProbes.cs", + "lines": [ + 22 + ] + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=3", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "23": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "4" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultipleLineProbes.cs", + "lines": [ + 23 + ] + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=4", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "24": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "5" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultipleLineProbes.cs", + "lines": [ + 24 + ] + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=5", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "25": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "a": { + "fields": null, + "type": "Int32", + "value": "6" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "MultipleLineProbes.cs", + "lines": [ + 25 + ] + } + }, + "stack": [ + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "MultipleLineProbes.cs", + "function": "Samples.Probes.SmokeTests.MultipleLineProbes.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.MultipleLineProbes", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MultipleLineProbes.MethodToInstrument(callerName=Run)\r\na=6", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt new file mode 100644 index 000000000..00643396d --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt @@ -0,0 +1,141 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "gen": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + }, + "gen2": { + "fields": null, + "type": "OpenGenericMethodInDerivedGenericType", + "value": "OpenGenericMethodInDerivedGenericType" + }, + "k": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + } + }, + "fields": null + }, + "return": { + "arguments": { + "gen": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + }, + "gen2": { + "fields": null, + "type": "OpenGenericMethodInDerivedGenericType", + "value": "OpenGenericMethodInDerivedGenericType" + }, + "k": { + "fields": { + "Message": { + "fields": null, + "type": "String", + "value": "Hello" + } + }, + "type": "Generic", + "value": "Generic" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Samples.Probes.Shared.GenericSamples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericTypeSamples.Probes.Shared.Generic" + }, + "gen2ToString": { + "fields": null, + "type": "String", + "value": "Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType" + }, + "genToString": { + "fields": null, + "type": "String", + "value": "Samples.Probes.Shared.Generic" + }, + "kToString": { + "fields": null, + "type": "String", + "value": "Samples.Probes.Shared.Generic" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType+Test2`1" + } + }, + "stack": [ + { + "fileName": "OpenGenericMethodInDerivedGenericType.cs", + "function": "Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType+Test2`1.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "OpenGenericMethodInDerivedGenericType.cs", + "function": "Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType+Test2`1", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "OpenGenericMethodInDerivedGenericType+Test2`1.Method(gen=Generic, gen2=OpenGenericMethodInDerivedGenericType, k=Generic): Samples.Probes.Shared.GenericSamples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericTypeSamples.Probes.Shared.Generic\r\n@return=Samples.Probes.Shared.GenericSamples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericTypeSamples.Probes.Shared.Generic, gen2ToString=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType, genToString=Samples.Probes.Shared.Generic, kToString=Samples.Probes.Shared.Generic", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt new file mode 100644 index 000000000..f4805b194 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt @@ -0,0 +1,112 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "arr": { + "Collection": [ + { + "fields": null, + "type": "String", + "value": "Run" + }, + { + "fields": null, + "type": "String", + "value": "MethodToInstrument" + }, + { + "fields": null, + "type": "String", + "value": "SimpleTypeNameTest" + } + ], + "type": "String[]", + "value": "count: 3" + } + }, + "throwable": { + "message": "Same length.", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest+NestedType.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.Run", + "lineNumber": "ScrubbedValue" + } + ], + "type": "Samples.Probes.Shared.IntentionalDebuggerException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest+NestedType" + } + }, + "stack": [ + { + "fileName": "SimpleNestedTypeNameTest.cs", + "function": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest+NestedType.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "SimpleNestedTypeNameTest.cs", + "function": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.SimpleNestedTypeNameTest+NestedType", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "SimpleNestedTypeNameTest+NestedType.MethodToInstrument(callerName=Run)\r\narr=count: 3", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt new file mode 100644 index 000000000..99cb5ed38 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt @@ -0,0 +1,112 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "arr": { + "Collection": [ + { + "fields": null, + "type": "String", + "value": "Run" + }, + { + "fields": null, + "type": "String", + "value": "MethodToInstrument" + }, + { + "fields": null, + "type": "String", + "value": "SimpleTypeNameTest" + } + ], + "type": "String[]", + "value": "count: 3" + } + }, + "throwable": { + "message": "Same length.", + "stacktrace": [ + { + "function": "Samples.Probes.SmokeTests.SimpleTypeNameTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Samples.Probes.SmokeTests.SimpleTypeNameTest.Run", + "lineNumber": "ScrubbedValue" + } + ], + "type": "Samples.Probes.Shared.IntentionalDebuggerException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "Samples.Probes.SmokeTests.SimpleTypeNameTest" + } + }, + "stack": [ + { + "fileName": "SimpleTypeNameTest.cs", + "function": "Samples.Probes.SmokeTests.SimpleTypeNameTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "SimpleTypeNameTest.cs", + "function": "Samples.Probes.SmokeTests.SimpleTypeNameTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.SimpleTypeNameTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "SimpleTypeNameTest.MethodToInstrument(callerName=Run)\r\narr=count: 3", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt new file mode 100644 index 000000000..0be8600c3 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt @@ -0,0 +1,149 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Last" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.StaticMethodWithArguments" + } + }, + "stack": [ + { + "fileName": "StaticMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.StaticMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "StaticMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.StaticMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.StaticMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "StaticMethodWithArguments.Method(lastName=Last): Last\r\n@return=Last", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "18": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last" + } + }, + "fields": null + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "StaticMethodWithArguments.cs", + "lines": [ + 18 + ] + } + }, + "stack": [ + { + "fileName": "StaticMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.StaticMethodWithArguments.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "StaticMethodWithArguments.cs", + "function": "Samples.Probes.SmokeTests.StaticMethodWithArguments.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.StaticMethodWithArguments", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "StaticMethodWithArguments.Method(lastName=Last)", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt new file mode 100644 index 000000000..5fc65ba39 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt @@ -0,0 +1,182 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last name" + } + }, + "fields": { + "_staticField": { + "fields": null, + "type": "String", + "value": "Static Field" + }, + "StaticProperty": { + "fields": null, + "type": "String", + "value": "Static Property" + } + } + }, + "return": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last name" + } + }, + "fields": { + "_staticField": { + "fields": null, + "type": "String", + "value": "Static Field" + }, + "StaticProperty": { + "fields": null, + "type": "String", + "value": "Static Property" + } + }, + "locals": { + "@return": { + "fields": null, + "type": "String", + "value": "Last name" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.StaticType+StaticTypeInner" + } + }, + "stack": [ + { + "fileName": "StaticType.cs", + "function": "Samples.Probes.SmokeTests.StaticType+StaticTypeInner.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "StaticType.cs", + "function": "Samples.Probes.SmokeTests.StaticType.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.StaticType+StaticTypeInner", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "StaticType+StaticTypeInner.Method(lastName=Last name): Last name\r\n@return=Last name", + "service": "Unknown" + }, + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "lines": { + "22": { + "arguments": { + "lastName": { + "fields": null, + "type": "String", + "value": "Last name" + } + }, + "fields": { + "_staticField": { + "fields": null, + "type": "String", + "value": "Static Field" + }, + "StaticProperty": { + "fields": null, + "type": "String", + "value": "Static Property" + } + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "file": "StaticType.cs", + "lines": [ + 22 + ] + } + }, + "stack": [ + { + "fileName": "StaticType.cs", + "function": "Samples.Probes.SmokeTests.StaticType+StaticTypeInner.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "StaticType.cs", + "function": "Samples.Probes.SmokeTests.StaticType.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.StaticType+StaticTypeInner", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "StaticType+StaticTypeInner.Method(lastName=Last name)", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt new file mode 100644 index 000000000..8f8ca4bd1 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt @@ -0,0 +1,73 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "0" + } + } + }, + "return": { + "fields": { + "Number": { + "fields": null, + "type": "Int32", + "value": "7" + } + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "Method", + "type": "Samples.Probes.SmokeTests.StaticVoidMethod" + } + }, + "stack": [ + { + "fileName": "StaticVoidMethod.cs", + "function": "Samples.Probes.SmokeTests.StaticVoidMethod.Method", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "StaticVoidMethod.cs", + "function": "Samples.Probes.SmokeTests.StaticVoidMethod.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "Samples.Probes.SmokeTests.StaticVoidMethod", + "name": "Method", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "StaticVoidMethod.Method()", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt new file mode 100644 index 000000000..af739088e --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt @@ -0,0 +1,112 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "arr": { + "Collection": [ + { + "fields": null, + "type": "String", + "value": "Run" + }, + { + "fields": null, + "type": "String", + "value": "MethodToInstrument" + }, + { + "fields": null, + "type": "String", + "value": "SimpleTypeNameTest" + } + ], + "type": "String[]", + "value": "count: 3" + } + }, + "throwable": { + "message": "Same length.", + "stacktrace": [ + { + "function": "SimpleNestedTypeNameInGlobalNamespaceTest+NestedType.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "function": "SimpleNestedTypeNameInGlobalNamespaceTest.Run", + "lineNumber": "ScrubbedValue" + } + ], + "type": "Samples.Probes.Shared.IntentionalDebuggerException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "SimpleNestedTypeNameInGlobalNamespaceTest+NestedType" + } + }, + "stack": [ + { + "fileName": "SimpleNestedTypeNameInGlobalNamespaceTest.cs", + "function": "SimpleNestedTypeNameInGlobalNamespaceTest+NestedType.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "SimpleNestedTypeNameInGlobalNamespaceTest.cs", + "function": "SimpleNestedTypeNameInGlobalNamespaceTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "SimpleNestedTypeNameInGlobalNamespaceTest+NestedType", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MethodToInstrument(callerName=Run)\r\narr=count: 3", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt new file mode 100644 index 000000000..e428fb6d1 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/snapshots/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt @@ -0,0 +1,112 @@ +[ + { + "dd.span_id": "ScrubbedValue", + "dd.trace_id": "ScrubbedValue", + "ddsource": "dd_debugger", + "ddtags": "Unknown", + "debugger": { + "snapshot": { + "captures": { + "entry": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null + }, + "return": { + "arguments": { + "callerName": { + "fields": null, + "type": "String", + "value": "Run" + } + }, + "fields": null, + "locals": { + "arr": { + "Collection": [ + { + "fields": null, + "type": "String", + "value": "Run" + }, + { + "fields": null, + "type": "String", + "value": "MethodToInstrument" + }, + { + "fields": null, + "type": "String", + "value": "SimpleTypeNameTest" + } + ], + "type": "String[]", + "value": "count: 3" + } + }, + "throwable": { + "message": "Same length.", + "stacktrace": [ + { + "function": "SimpleTypeNameInGlobalNamespaceTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "function": "SimpleTypeNameInGlobalNamespaceTest.Run", + "lineNumber": "ScrubbedValue" + } + ], + "type": "Samples.Probes.Shared.IntentionalDebuggerException" + } + } + }, + "duration": "ScrubbedValue", + "id": "ScrubbedValue", + "language": "dotnet", + "probe": { + "id": "ScrubbedValue", + "location": { + "method": "MethodToInstrument", + "type": "SimpleTypeNameInGlobalNamespaceTest" + } + }, + "stack": [ + { + "fileName": "SimpleTypeNameInGlobalNamespaceTest.cs", + "function": "SimpleTypeNameInGlobalNamespaceTest.MethodToInstrument", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "SimpleTypeNameInGlobalNamespaceTest.cs", + "function": "SimpleTypeNameInGlobalNamespaceTest.Run", + "lineNumber": "ScrubbedValue" + }, + { + "function": "Program.RunTest", + "lineNumber": "ScrubbedValue" + }, + { + "fileName": "Program.cs", + "function": "Program+<>c__DisplayClass2_0.
b__0", + "lineNumber": "ScrubbedValue" + } + ], + "timestamp": "ScrubbedValue" + } + }, + "logger": { + "method": "SimpleTypeNameInGlobalNamespaceTest", + "name": "MethodToInstrument", + "thread_id": "ScrubbedValue", + "thread_name": "ScrubbedValue", + "version": "2" + }, + "message": "MethodToInstrument(callerName=Run)\r\narr=count: 3", + "service": "Unknown" + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.InstallAndUninstallMethodProbeWithOverloadsTest_testType=Samples.Probes.SmokeTests.OverloadAndSimpleNameTest#1..verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.GenericMethodWithArguments.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasArgumentsAndLocals.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueInitialized.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasFieldLazyValueNotInitialized.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalListOfObjects.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndArgumentsInGenericNestedType.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt new file mode 100644 index 000000000..03237a919 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasLocalsAndReturnValue.verified.txt @@ -0,0 +1,50 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "17c1e39c-e46c-828e-4e02-21be0f3b5358", + "status": "INSTALLED" + } + }, + "message": "Installed probe 17c1e39c-e46c-828e-4e02-21be0f3b5358.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "1828a3f0-e94b-eb91-81e3-12bcf19ac41a", + "status": "INSTALLED" + } + }, + "message": "Installed probe 1828a3f0-e94b-eb91-81e3-12bcf19ac41a.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasReturnValue.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.HasVarAndMvar.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceMethodWithArguments.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.InstanceVoidMethod.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt new file mode 100644 index 000000000..03237a919 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#1..verified.txt @@ -0,0 +1,50 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "17c1e39c-e46c-828e-4e02-21be0f3b5358", + "status": "INSTALLED" + } + }, + "message": "Installed probe 17c1e39c-e46c-828e-4e02-21be0f3b5358.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "1828a3f0-e94b-eb91-81e3-12bcf19ac41a", + "status": "INSTALLED" + } + }, + "message": "Installed probe 1828a3f0-e94b-eb91-81e3-12bcf19ac41a.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt new file mode 100644 index 000000000..a071fb779 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#2..verified.txt @@ -0,0 +1,62 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "31d232fd-e292-63a1-cfc5-f0e71d98afd1", + "status": "INSTALLED" + } + }, + "message": "Installed probe 31d232fd-e292-63a1-cfc5-f0e71d98afd1.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3c5a4d30-f652-b355-51d6-9589d1d290b4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3c5a4d30-f652-b355-51d6-9589d1d290b4.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "86a95ec1-5bda-bd57-3f8e-e610398f9334", + "status": "INSTALLED" + } + }, + "message": "Installed probe 86a95ec1-5bda-bd57-3f8e-e610398f9334.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "a48bde4f-873f-cac7-08f6-3404c6ceec6d", + "status": "INSTALLED" + } + }, + "message": "Installed probe a48bde4f-873f-cac7-08f6-3404c6ceec6d.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "b1fd073e-cd92-947d-4b6b-d9bd0380b1f2", + "status": "INSTALLED" + } + }, + "message": "Installed probe b1fd073e-cd92-947d-4b6b-d9bd0380b1f2.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt new file mode 100644 index 000000000..9f7359554 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#3..verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "d1bf6b7f-7fae-6c5f-3c28-d47a96e0ad70", + "status": "INSTALLED" + } + }, + "message": "Installed probe d1bf6b7f-7fae-6c5f-3c28-d47a96e0ad70.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "f23aa325-ec46-b774-3f32-a89b9879ce7d", + "status": "INSTALLED" + } + }, + "message": "Installed probe f23aa325-ec46-b774-3f32-a89b9879ce7d.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt new file mode 100644 index 000000000..23eed0cbb --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#4..verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "22df6346-f993-1027-bd1a-f25f3a06ca56", + "status": "INSTALLED" + } + }, + "message": "Installed probe 22df6346-f993-1027-bd1a-f25f3a06ca56.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt new file mode 100644 index 000000000..21e8777ed --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#5..verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "b16773f7-ded8-a522-43ce-b51d18f9205e", + "status": "INSTALLED" + } + }, + "message": "Installed probe b16773f7-ded8-a522-43ce-b51d18f9205e.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt new file mode 100644 index 000000000..a6dbfaf18 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.LineProbesWithRevertTest#6..verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "35543785-ac9a-85ea-44af-13938dff3136", + "status": "INSTALLED" + } + }, + "message": "Installed probe 35543785-ac9a-85ea-44af-13938dff3136.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MethodThrowExceptionTest.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultiScopesWithSameLocalNameTest.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt new file mode 100644 index 000000000..c14951866 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.MultipleLineProbes.verified.txt @@ -0,0 +1,74 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "17c1e39c-e46c-828e-4e02-21be0f3b5358", + "status": "INSTALLED" + } + }, + "message": "Installed probe 17c1e39c-e46c-828e-4e02-21be0f3b5358.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "1828a3f0-e94b-eb91-81e3-12bcf19ac41a", + "status": "INSTALLED" + } + }, + "message": "Installed probe 1828a3f0-e94b-eb91-81e3-12bcf19ac41a.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3c5a4d30-f652-b355-51d6-9589d1d290b4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3c5a4d30-f652-b355-51d6-9589d1d290b4.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "86a95ec1-5bda-bd57-3f8e-e610398f9334", + "status": "INSTALLED" + } + }, + "message": "Installed probe 86a95ec1-5bda-bd57-3f8e-e610398f9334.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.NonSupportedInstrumentationTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.NonSupportedInstrumentationTest.verified.txt new file mode 100644 index 000000000..df8d244c5 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.NonSupportedInstrumentationTest.verified.txt @@ -0,0 +1,18 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": { + "Message": null, + "StackTrace": null, + "Type": null + }, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "ERROR" + } + }, + "message": "Error installing probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.OpenGenericMethodInDerivedGenericType.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleNestedTypeNameTest.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.SimpleTypeNameTest.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticMethodWithArguments.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt new file mode 100644 index 000000000..1c8ecbc69 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticType.verified.txt @@ -0,0 +1,26 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "status": "INSTALLED" + } + }, + "message": "Installed probe 3410cda1-5b13-a34e-6f84-a54adf7a0ea0.", + "service": null + }, + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=Samples.Probes.SmokeTests.StaticVoidMethod.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleNestedTypeNameInGlobalNamespaceTest.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt new file mode 100644 index 000000000..fdd81f297 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/Debugger/statuses/ProbesTests.MethodProbeTest_testType=SimpleTypeNameInGlobalNamespaceTest.verified.txt @@ -0,0 +1,14 @@ +[ + { + "ddsource": "dd_debugger", + "debugger": { + "diagnostics": { + "Exception": null, + "probeId": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "status": "INSTALLED" + } + }, + "message": "Installed probe 8286d046-9740-a3e4-95cf-ff46699c73c4.", + "service": null + } +] \ No newline at end of file diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMajors.g.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMajors.g.cs index a12a711c5..25663d0b2 100644 --- a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMajors.g.cs +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMajors.g.cs @@ -27,22 +27,22 @@ public class PackageVersionsLatestMajors new object[] { string.Empty }, #else #if NET461 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP2_1 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_0 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_1 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET5_0 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET6_0 - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #endif }; @@ -55,22 +55,22 @@ public class PackageVersionsLatestMajors new object[] { string.Empty }, #else #if NET461 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP2_1 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_0 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_1 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET5_0 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET6_0 - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #endif }; @@ -168,15 +168,15 @@ public class PackageVersionsLatestMajors #else #if NETCOREAPP3_1 new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET5_0 new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET6_0 new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #endif }; @@ -452,32 +452,32 @@ public class PackageVersionsLatestMajors #if NET461 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP2_1 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_0 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_1 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET5_0 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET6_0 new object[] { "0.69.10" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #endif }; @@ -491,39 +491,39 @@ public class PackageVersionsLatestMajors #else #if NET461 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP2_1 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_1 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET5_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET6_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #endif }; @@ -648,7 +648,7 @@ public class PackageVersionsLatestMajors new object[] { string.Empty }, #else #if NET461 - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NETCOREAPP2_1 new object[] { "3.28.0" }, @@ -657,13 +657,13 @@ public class PackageVersionsLatestMajors new object[] { "3.28.0" }, #endif #if NETCOREAPP3_1 - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET5_0 - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET6_0 - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #endif }; @@ -775,23 +775,23 @@ public class PackageVersionsLatestMajors #endif #if NETCOREAPP2_1 new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_0 new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_1 new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET5_0 new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET6_0 new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #endif }; @@ -832,7 +832,7 @@ public class PackageVersionsLatestMajors new object[] { string.Empty }, #else #if NET461 - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NETCOREAPP2_1 new object[] { "3.2.5" }, @@ -841,13 +841,13 @@ public class PackageVersionsLatestMajors new object[] { "3.2.5" }, #endif #if NETCOREAPP3_1 - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET5_0 - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET6_0 - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #endif }; diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMinors.g.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMinors.g.cs index 28970c58a..f945df1fe 100644 --- a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMinors.g.cs +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestMinors.g.cs @@ -30,32 +30,32 @@ public class PackageVersionsLatestMinors new object[] { "3.1.0.13" }, new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP2_1 new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_0 new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_1 new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET5_0 new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET6_0 new object[] { "3.3.103.26" }, new object[] { "3.5.1.28" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #endif }; @@ -85,6 +85,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP2_1 new object[] { "2.3.0" }, @@ -101,6 +102,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_0 new object[] { "2.3.0" }, @@ -117,6 +119,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_1 new object[] { "2.3.0" }, @@ -133,6 +136,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET5_0 new object[] { "2.3.0" }, @@ -149,6 +153,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET6_0 new object[] { "2.3.0" }, @@ -165,6 +170,7 @@ public class PackageVersionsLatestMinors new object[] { "2.14.1" }, new object[] { "2.15.1" }, new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #endif }; @@ -437,10 +443,9 @@ public class PackageVersionsLatestMinors new object[] { "4.6.1" }, new object[] { "4.7.1" }, new object[] { "4.8.0" }, - new object[] { "5.0.0" }, new object[] { "5.1.1" }, new object[] { "5.2.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET5_0 new object[] { "4.1.0" }, @@ -451,10 +456,9 @@ public class PackageVersionsLatestMinors new object[] { "4.6.1" }, new object[] { "4.7.1" }, new object[] { "4.8.0" }, - new object[] { "5.0.0" }, new object[] { "5.1.1" }, new object[] { "5.2.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET6_0 new object[] { "4.1.0" }, @@ -465,10 +469,9 @@ public class PackageVersionsLatestMinors new object[] { "4.6.1" }, new object[] { "4.7.1" }, new object[] { "4.8.0" }, - new object[] { "5.0.0" }, new object[] { "5.1.1" }, new object[] { "5.2.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #endif }; @@ -990,7 +993,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP2_1 new object[] { "0.61.0" }, @@ -1007,7 +1010,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_0 new object[] { "0.61.0" }, @@ -1024,7 +1027,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_1 new object[] { "0.61.0" }, @@ -1041,7 +1044,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET5_0 new object[] { "0.61.0" }, @@ -1058,7 +1061,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET6_0 new object[] { "0.61.0" }, @@ -1075,7 +1078,7 @@ public class PackageVersionsLatestMinors new object[] { "1.2.1" }, new object[] { "1.3.14" }, new object[] { "2.0.0" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #endif }; @@ -1092,54 +1095,54 @@ public class PackageVersionsLatestMinors new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP2_1 new object[] { "2.0.1" }, new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_0 new object[] { "2.0.1" }, new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_1 new object[] { "2.0.1" }, new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET5_0 new object[] { "2.0.1" }, new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET6_0 new object[] { "2.0.1" }, new object[] { "2.1.14" }, new object[] { "2.2.6" }, new object[] { "3.0.3" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #endif }; @@ -1383,6 +1386,7 @@ public class PackageVersionsLatestMinors new object[] { "3.26.2" }, new object[] { "3.27.2" }, new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NETCOREAPP2_1 new object[] { "3.6.0" }, @@ -1458,6 +1462,7 @@ public class PackageVersionsLatestMinors new object[] { "3.26.2" }, new object[] { "3.27.2" }, new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET5_0 new object[] { "3.6.0" }, @@ -1483,6 +1488,7 @@ public class PackageVersionsLatestMinors new object[] { "3.26.2" }, new object[] { "3.27.2" }, new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET6_0 new object[] { "3.6.0" }, @@ -1508,6 +1514,7 @@ public class PackageVersionsLatestMinors new object[] { "3.26.2" }, new object[] { "3.27.2" }, new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #endif }; @@ -1716,6 +1723,7 @@ public class PackageVersionsLatestMinors new object[] { "4.2.7" }, new object[] { "5.0.0" }, new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_0 new object[] { "4.0.3" }, @@ -1723,6 +1731,7 @@ public class PackageVersionsLatestMinors new object[] { "4.2.7" }, new object[] { "5.0.0" }, new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_1 new object[] { "4.0.3" }, @@ -1730,6 +1739,7 @@ public class PackageVersionsLatestMinors new object[] { "4.2.7" }, new object[] { "5.0.0" }, new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET5_0 new object[] { "4.0.3" }, @@ -1737,6 +1747,7 @@ public class PackageVersionsLatestMinors new object[] { "4.2.7" }, new object[] { "5.0.0" }, new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET6_0 new object[] { "4.0.3" }, @@ -1744,6 +1755,7 @@ public class PackageVersionsLatestMinors new object[] { "4.2.7" }, new object[] { "5.0.0" }, new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #endif }; @@ -1805,7 +1817,7 @@ public class PackageVersionsLatestMinors new object[] { "3.0.7" }, new object[] { "3.1.7" }, new object[] { "3.2.9" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NETCOREAPP2_1 new object[] { "3.0.7" }, @@ -1821,19 +1833,19 @@ public class PackageVersionsLatestMinors new object[] { "3.0.7" }, new object[] { "3.1.7" }, new object[] { "3.2.9" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET5_0 new object[] { "3.0.7" }, new object[] { "3.1.7" }, new object[] { "3.2.9" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET6_0 new object[] { "3.0.7" }, new object[] { "3.1.7" }, new object[] { "3.2.9" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #endif }; diff --git a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestSpecific.g.cs b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestSpecific.g.cs index 48bf29cb1..15bd72005 100644 --- a/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestSpecific.g.cs +++ b/tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/PackageVersionsLatestSpecific.g.cs @@ -29,27 +29,27 @@ public class PackageVersionsLatestSpecific #if NET461 new object[] { "3.1.0.13" }, new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP2_1 new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_0 new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NETCOREAPP3_1 new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET5_0 new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #if NET6_0 new object[] { "3.3.103.26" }, - new object[] { "3.7.2.74" }, + new object[] { "3.7.2.80" }, #endif #endif }; @@ -65,32 +65,32 @@ public class PackageVersionsLatestSpecific new object[] { "2.0.2" }, new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP2_1 new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_0 new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NETCOREAPP3_1 new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET5_0 new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #if NET6_0 new object[] { "2.5.1" }, new object[] { "2.14.1" }, - new object[] { "2.16.1" }, + new object[] { "2.17.0" }, #endif #endif }; @@ -220,19 +220,19 @@ public class PackageVersionsLatestSpecific new object[] { "4.1.0" }, new object[] { "4.3.0" }, new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET5_0 new object[] { "4.1.0" }, new object[] { "4.3.0" }, new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #if NET6_0 new object[] { "4.1.0" }, new object[] { "4.3.0" }, new object[] { "4.8.0" }, - new object[] { "5.3.2" }, + new object[] { "5.3.3" }, #endif #endif }; @@ -528,37 +528,37 @@ public class PackageVersionsLatestSpecific new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP2_1 new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_0 new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NETCOREAPP3_1 new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET5_0 new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #if NET6_0 new object[] { "0.61.0" }, new object[] { "1.0.1" }, new object[] { "1.3.14" }, - new object[] { "2.1.10" }, + new object[] { "2.1.11" }, #endif #endif }; @@ -572,39 +572,39 @@ public class PackageVersionsLatestSpecific #else #if NET461 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP2_1 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NETCOREAPP3_1 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET5_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #if NET6_0 new object[] { "2.2.6" }, - new object[] { "3.1.26" }, + new object[] { "3.1.27" }, new object[] { "5.0.17" }, - new object[] { "6.0.6" }, + new object[] { "6.0.7" }, #endif #endif }; @@ -760,7 +760,7 @@ public class PackageVersionsLatestSpecific #else #if NET461 new object[] { "3.6.0" }, - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NETCOREAPP2_1 new object[] { "3.6.0" }, @@ -772,15 +772,15 @@ public class PackageVersionsLatestSpecific #endif #if NETCOREAPP3_1 new object[] { "3.6.0" }, - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET5_0 new object[] { "3.6.0" }, - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #if NET6_0 new object[] { "3.6.0" }, - new object[] { "3.28.0" }, + new object[] { "3.29.0" }, #endif #endif }; @@ -895,27 +895,27 @@ public class PackageVersionsLatestSpecific #if NETCOREAPP2_1 new object[] { "4.0.3" }, new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_0 new object[] { "4.0.3" }, new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NETCOREAPP3_1 new object[] { "4.0.3" }, new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET5_0 new object[] { "4.0.3" }, new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #if NET6_0 new object[] { "4.0.3" }, new object[] { "4.2.7" }, - new object[] { "5.1.1" }, + new object[] { "5.2.0" }, #endif #endif }; @@ -963,7 +963,7 @@ public class PackageVersionsLatestSpecific #else #if NET461 new object[] { "3.0.7" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NETCOREAPP2_1 new object[] { "3.0.7" }, @@ -975,15 +975,15 @@ public class PackageVersionsLatestSpecific #endif #if NETCOREAPP3_1 new object[] { "3.0.7" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET5_0 new object[] { "3.0.7" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #if NET6_0 new object[] { "3.0.7" }, - new object[] { "3.3.2" }, + new object[] { "3.3.3" }, #endif #endif }; diff --git a/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/PdbReaderTests.cs b/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/PdbReaderTests.cs index 24d7cd5c2..674473041 100644 --- a/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/PdbReaderTests.cs +++ b/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/PdbReaderTests.cs @@ -8,7 +8,7 @@ using System.IO; using System.Linq; using System.Reflection; -using Datadog.Trace.PDBs; +using Datadog.Trace.Pdb; using FluentAssertions; using Xunit; @@ -19,8 +19,7 @@ public class PdbReaderTests [Fact(Skip="Unstable test. Cannot read pdb file in CI. Not used in Splunk distribution")] public void ReadPDBs() { - string assemblyFullPath = Assembly.GetExecutingAssembly().Location; - using var pdbReader = DatadogPdbReader.CreatePdbReader(assemblyFullPath); + using var pdbReader = DatadogPdbReader.CreatePdbReader(Assembly.GetExecutingAssembly()); var symbolMethod = pdbReader.ReadMethodSymbolInfo(MethodBase.GetCurrentMethod().MetadataToken); diff --git a/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/TrieTests.cs b/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/TrieTests.cs new file mode 100644 index 000000000..5c7d7cdb0 --- /dev/null +++ b/tracer/test/Datadog.Trace.ClrProfiler.Managed.Tests/TrieTests.cs @@ -0,0 +1,72 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Debugger.Configurations; +using Xunit; + +namespace Datadog.Trace.ClrProfiler.Managed.Tests; + +public class TrieTests +{ + public class TrieTest + { + [Fact] + public void PrefixMatching() + { + var trie = new Trie(); + trie.Insert("foo"); + trie.Insert("bar"); + Assert.True(trie.HasMatchingPrefix("foobar")); + Assert.True(trie.HasMatchingPrefix("barfoo")); + Assert.False(trie.HasMatchingPrefix("fobar")); + Assert.False(trie.HasMatchingPrefix("bafoo")); + Assert.False(trie.HasMatchingPrefix(string.Empty)); + } + + [Fact] + public void StartsWith() + { + var trie = new Trie(); + trie.Insert("abcde"); + trie.Insert("abcfe"); + Assert.True(trie.ContainsPrefix("a")); + Assert.True(trie.ContainsPrefix("abc")); + Assert.True(trie.ContainsPrefix("abcde")); + Assert.True(trie.ContainsPrefix("abcfe")); + Assert.False(trie.ContainsPrefix("sgsg")); + } + + [Fact] + public void GetStringStartingWith() + { + var trie = new Trie(); + trie.Insert("cs.ArrayExtensions/ExtensionMethods/Datadog.Trace/src/tracer/dd-trace-dotnet"); + trie.Insert("cs.LiveDebugger/Debugger/Datadog.Trace/src/tracer/dd-trace-dotnet/dev"); + Assert.EndsWith( + "cs.ArrayExtensions/ExtensionMethods/Datadog.Trace/src/tracer/dd-trace-dotnet", + trie.GetStringStartingWith("cs.ArrayExtensions/ExtensionMethods/Datadog.Trace/src")); + } + + [Fact] + public void GetStringStartingWithAmbiguous() + { + var trie = new Trie(); + trie.Insert("abcde"); + trie.Insert("abcfe"); + Assert.Null(trie.GetStringStartingWith("abc")); + } + + [Fact] + public void Empty() + { + var trie = new Trie(); + Assert.True(trie.IsEmpty()); + trie.Insert(string.Empty); + Assert.True(trie.IsEmpty()); + trie.Insert("abc"); + Assert.False(trie.IsEmpty()); + } + } +} diff --git a/tracer/test/Datadog.Trace.TestHelpers.SharedSource/VerifyHelper.cs b/tracer/test/Datadog.Trace.TestHelpers.SharedSource/VerifyHelper.cs index 12baf0889..6463d1c6e 100644 --- a/tracer/test/Datadog.Trace.TestHelpers.SharedSource/VerifyHelper.cs +++ b/tracer/test/Datadog.Trace.TestHelpers.SharedSource/VerifyHelper.cs @@ -61,12 +61,11 @@ public static VerifySettings GetSpanVerifierSettings(params object[] parameters) settings.UseParameters(parameters); } - VerifierSettings.MemberConverter>(x => x.Tags, ScrubStackTraceForErrors); - settings.ModifySerialization(_ => { _.IgnoreMember(s => s.Duration); _.IgnoreMember(s => s.Start); + _.MemberConverter>(x => x.Tags, ScrubStackTraceForErrors); }); settings.AddRegexScrubber(LocalhostRegex, "localhost:00000"); @@ -74,7 +73,6 @@ public static VerifySettings GetSpanVerifierSettings(params object[] parameters) settings.AddRegexScrubber(KeepRateRegex, "_dd.tracer_kr: 1.0"); settings.AddRegexScrubber(ProcessIdRegex, "process_id: 0"); settings.ScrubInlineGuids(); - return settings; } diff --git a/tracer/test/Datadog.Trace.TestHelpers/MockProbeSnapshot.cs b/tracer/test/Datadog.Trace.TestHelpers/MockProbeSnapshot.cs new file mode 100644 index 000000000..dd8e61043 --- /dev/null +++ b/tracer/test/Datadog.Trace.TestHelpers/MockProbeSnapshot.cs @@ -0,0 +1,39 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System.Collections.Generic; +using System.Diagnostics; +using MessagePack; // use nuget MessagePack to deserialize + +namespace Datadog.Trace.TestHelpers +{ + [MessagePackObject] + [DebuggerDisplay("{ToString(),nq}")] + public class MockProbeSnapshot + { + [Key("name")] + public string Name { get; set; } + + [Key("service")] + public string Service { get; set; } + + [Key("type")] + public string Type { get; set; } + + [Key("duration")] + public long Duration { get; set; } + + [Key("meta")] + public Dictionary Tags { get; set; } + + [Key("metrics")] + public Dictionary Metrics { get; set; } + + public override string ToString() + { + return $"{nameof(Name)}: {Name}, {nameof(Service)}: {Service}"; + } + } +} diff --git a/tracer/test/Datadog.Trace.TestHelpers/MockTracerAgent.cs b/tracer/test/Datadog.Trace.TestHelpers/MockTracerAgent.cs index 77c72eade..1e333b724 100644 --- a/tracer/test/Datadog.Trace.TestHelpers/MockTracerAgent.cs +++ b/tracer/test/Datadog.Trace.TestHelpers/MockTracerAgent.cs @@ -17,11 +17,14 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Datadog.Trace.Agent.DiscoveryService; using Datadog.Trace.ExtensionMethods; using Datadog.Trace.HttpOverStreams; using Datadog.Trace.Telemetry; using Datadog.Trace.TestHelpers.Stats; using Datadog.Trace.Util; +using Datadog.Trace.Vendors.Newtonsoft.Json; +using Datadog.Trace.Vendors.Newtonsoft.Json.Linq; using Datadog.Tracer.SignalFx.Metrics.Protobuf; using MessagePack; // use nuget MessagePack to deserialize using Xunit.Abstractions; @@ -69,6 +72,10 @@ protected MockTracerAgent(bool telemetryEnabled, TestTransports transport) public IImmutableList RequestHeaders { get; private set; } = ImmutableList.Empty; + public List Snapshots { get; private set; } = new(); + + public List ProbesStatuses { get; private set; } = new(); + public ConcurrentQueue StatsdRequests { get; } = new(); /// @@ -236,6 +243,90 @@ public IImmutableList WaitForStats( return stats; } + /// + /// Wait for the given number of probe snapshots to appear. + /// + /// The expected number of probe snapshots when more than one snapshot is expected (e.g. multiple line probes in method). + /// The timeout + /// The list of probe snapshots. + public async Task WaitForSnapshots(int snapshotCount, TimeSpan? timeout = null) + { + using var cancellationSource = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + + var isFound = false; + while (!isFound && !cancellationSource.IsCancellationRequested) + { + isFound = Snapshots.Count == snapshotCount; + + if (!isFound) + { + await Task.Delay(100); + } + } + + if (!isFound) + { + throw new InvalidOperationException($"Snapshot count not found. Expected {snapshotCount}, actual {Snapshots.Count}"); + } + + return Snapshots.ToArray(); + } + + public async Task WaitForNoSnapshots(int timeoutInMilliseconds = 10000) + { + var deadline = DateTime.Now.AddMilliseconds(timeoutInMilliseconds); + while (DateTime.Now < deadline) + { + if (Snapshots.Any()) + { + return false; + } + + await Task.Delay(100); + } + + return !Snapshots.Any(); + } + + public void ClearSnapshots() + { + Snapshots.Clear(); + } + + /// + /// Wait for the given number of probe statuses to appear. + /// + /// The expected number of probe statuses when more than one status is expected (e.g. multiple line probes in method). + /// The timeout + /// The list of probe statuses. + public async Task WaitForProbesStatuses(int statusCount, TimeSpan? timeout = null) + { + using var cancellationSource = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(5)); + + var isFound = false; + while (!isFound && !cancellationSource.IsCancellationRequested) + { + isFound = ProbesStatuses.Count == statusCount; + + if (!isFound) + { + await Task.Delay(100); + } + } + + if (!isFound) + { + throw new InvalidOperationException($"Snapshot count not found. Expected {statusCount}, actual {Snapshots.Count}"); + } + + return ProbesStatuses.ToArray(); + } + + public void ClearProbeStatuses() + { + ProbesStatuses.Clear(); + } + public virtual void Dispose() { _cancellationTokenSource.Cancel(); @@ -440,6 +531,32 @@ private byte[] ReadStreamBody(MockHttpParser.MockHttpRequest request) return body; } + private void ReceiveDebuggerBatch(string batch) + { + var arr = JArray.Parse(batch); + + var probeStatuses = new List(); + var snapshots = new List(); + + foreach (var token in arr) + { + var stringifiedToken = token.ToString(); + if (token["debugger"]?["diagnostics"]?["status"] != null) + { + probeStatuses.Add(stringifiedToken); + } + else + { + snapshots.Add(stringifiedToken); + } + } + + // We override the previous Probes Statuses as the debugger-agent is always emitting complete set of probes statuses, so we can + // solely rely on that. + ProbesStatuses = probeStatuses; + Snapshots.AddRange(snapshots); + } + public class TcpUdpAgent : MockTracerAgent { private readonly HttpListener _listener; @@ -605,7 +722,21 @@ private void HandleHttpRequests() } else { - if (ShouldDeserializeTraces) + var buffer = Encoding.UTF8.GetBytes("{}"); + + if (ctx.Request.RawUrl.EndsWith("/info")) + { + var endpoints = $"{{\"endpoints\":{JsonConvert.SerializeObject(DiscoveryService.AllSupportedEndpoints)}}}"; + buffer = Encoding.UTF8.GetBytes(endpoints); + } + else if (ctx.Request.RawUrl.Contains("/debugger/v1/input")) + { + using var body = ctx.Request.InputStream; + using var streamReader = new StreamReader(body); + var batch = streamReader.ReadToEnd(); + ReceiveDebuggerBatch(batch); + } + else if (ShouldDeserializeTraces) { if (ctx.Request.Url?.AbsolutePath == "/v0.6/stats") { @@ -634,7 +765,6 @@ private void HandleHttpRequests() } ctx.Response.ContentType = "application/json"; - var buffer = Encoding.UTF8.GetBytes("{}"); ctx.Response.ContentLength64 = buffer.LongLength; ctx.Response.OutputStream.Write(buffer, 0, buffer.Length); } diff --git a/tracer/test/Datadog.Trace.TestHelpers/TestHelper.cs b/tracer/test/Datadog.Trace.TestHelpers/TestHelper.cs index 9818b6d8b..31cdd1e34 100644 --- a/tracer/test/Datadog.Trace.TestHelpers/TestHelper.cs +++ b/tracer/test/Datadog.Trace.TestHelpers/TestHelper.cs @@ -125,7 +125,7 @@ public ProcessResult RunDotnetTestSampleAndWaitForExit(MockTracerAgent agent, in public Process StartSample(MockTracerAgent agent, string arguments, string packageVersion, int aspNetCorePort, int? logCollectorPort = null, string framework = "") { // get path to sample app that the profiler will attach to - string sampleAppPath = EnvironmentHelper.GetSampleApplicationPath(packageVersion, framework); + var sampleAppPath = EnvironmentHelper.GetSampleApplicationPath(packageVersion, framework); if (!File.Exists(sampleAppPath)) { throw new Exception($"application not found: {sampleAppPath}"); diff --git a/tracer/test/Datadog.Trace.Tests/Datadog.Trace.Tests.csproj b/tracer/test/Datadog.Trace.Tests/Datadog.Trace.Tests.csproj index 8784ba020..36d05e881 100644 --- a/tracer/test/Datadog.Trace.Tests/Datadog.Trace.Tests.csproj +++ b/tracer/test/Datadog.Trace.Tests/Datadog.Trace.Tests.csproj @@ -24,10 +24,6 @@ - - - - diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/BatchUploaderTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/BatchUploaderTests.cs new file mode 100644 index 000000000..32f65affd --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/BatchUploaderTests.cs @@ -0,0 +1,169 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using Datadog.Trace.Debugger.Sink; +using FluentAssertions; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger; + +public class BatchUploaderTests +{ + private const int MaxPayloadSize = 5 * 1024 * 1024; + private const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + private const string HebrewChars = "אבגדהוזחטי"; + private static readonly Random Random = new Random(); + + private readonly MockBatchUploadApi _api; + private readonly BatchUploader _upload; + + public BatchUploaderTests() + { + _api = new MockBatchUploadApi(); + _upload = BatchUploader.Create(_api); + } + + [Fact] + public async Task HugePayload_Skipped() + { + await _upload.Upload(new[] { GenerateString(MaxPayloadSize) }); + _api.Segments.Should().BeEmpty(); + } + + [Fact] + public async Task SmallPayloads_BatchInOne() + { + await _upload.Upload(new[] + { + GenerateString(64), + GenerateString(64), + GenerateString(64), + GenerateString(64), + GenerateString(64), + }); + + _api.Segments.Count.Should().Be(1); + } + + [Fact] + public async Task MediumPayloads_Batched() + { + await _upload.Upload(new[] + { + GenerateString(1000 * 1024), + GenerateString(1000 * 1024), + GenerateString(1000 * 1024), + GenerateString(1000 * 1024), + GenerateString(1000 * 1024), + GenerateString(1000 * 1024), + }); + + _api.Segments.Count.Should().Be(2); + } + + [Fact] + public async Task HebrewSerializedHugePayload_Skipped() + { + await _upload.Upload(new[] + { + GenerateString(1024 * 1024 * 3, true) + }); + + _api.Segments.Count.Should().Be(0); + } + + [Fact] + public async Task HebrewSerializedHugePayloadInTheMiddle_MiddleBatchedHugeIgnored() + { + await _upload.Upload(new[] + { + GenerateString(64), + GenerateString(1024 * 1024 * 3, true), + GenerateString(64), + }); + + _api.Segments.Count.Should().Be(1); + } + + [Fact] + public async Task HebrewSerializedMediumPayloadExceed_MiddleBatchedHugeIgnored() + { + await _upload.Upload(new[] + { + GenerateString(512 * 1024, true), + }); + + _api.Segments.Count.Should().Be(0); + } + + [Fact] + public async Task CheckSmallOutput() + { + await _upload.Upload(new[] + { + "Test1", + "Test2", + }); + + _api.Segments.Count.Should().Be(1); + Encoding.UTF8.GetString(_api.Segments[0]).Should().Be("[Test1,Test2]"); + } + + [Fact] + public async Task CheckTwoSmallOutputs() + { + await _upload.Upload(new[] { "Test1", "Test2" }); + await _upload.Upload(new[] { "Test3", }); + + _api.Segments.Count.Should().Be(2); + Encoding.UTF8.GetString(_api.Segments[0]).Should().Be("[Test1,Test2]"); + Encoding.UTF8.GetString(_api.Segments[1]).Should().Be("[Test3]"); + } + + [Fact] + public async Task CheckMediumOutput() + { + var str = GenerateString(1023 * 1024); + await _upload.Upload(new[] + { + str, + str, + str, + str, + str, + str, + }); + + _api.Segments.Count.Should().Be(2); + + (Encoding.UTF8.GetString(_api.Segments[0]) == $"[{str},{str},{str},{str},{str}]").Should().BeTrue(); + (Encoding.UTF8.GetString(_api.Segments[1]) == $"[{str}]").Should().BeTrue(); + } + + private string GenerateString(int length, bool useHebrew = false) + { + return new string( + Enumerable.Repeat(useHebrew ? HebrewChars : Chars, length) + .Select(s => s[Random.Next(s.Length)]) + .ToArray()); + } + + private class MockBatchUploadApi : IBatchUploadApi + { + public List Segments { get; } = new List(); + + public Task SendBatchAsync(ArraySegment snapshots) + { + Segments.Add(snapshots.ToArray()); + return Task.FromResult(true); + } + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/DebuggerSettingsTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/DebuggerSettingsTests.cs new file mode 100644 index 000000000..836c07c2f --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/DebuggerSettingsTests.cs @@ -0,0 +1,172 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger; +using FluentAssertions; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger +{ + public class DebuggerSettingsTests + { + [Fact] + public void WhenFilePathProvided_UseFileMode() + { + var expected = "c:/temp"; + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.ProbeFile, expected }, + })); + + tracerSettings.DebuggerSettings.ProbeMode.Should().Be(ProbeMode.File); + tracerSettings.DebuggerSettings.ProbeConfigurationsPath.Should().Be(expected); + tracerSettings.DebuggerSettings.SnapshotsPath.Should().Be("http://127.0.0.1:9411/api/v2/spans"); + } + + [Fact] + public void DefaultMode_AgentMode() + { + var tracerSettings = new TracerSettings(); + tracerSettings.DebuggerSettings.ProbeMode.Should().Be(ProbeMode.Agent); + } + + [Theory] + [InlineData(null)] + [InlineData("http://127.0.0.1:9411/api/v2/spans")] + public void WhenAgentModeEnabled_UseAgentMode(string agentUri) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.EndpointUrl, agentUri }, + })); + + tracerSettings.DebuggerSettings.ProbeMode.Should().Be(ProbeMode.Agent); + tracerSettings.DebuggerSettings.ProbeConfigurationsPath.Should().Be("http://127.0.0.1:9411/api/v2/spans"); + tracerSettings.DebuggerSettings.SnapshotsPath.Should().Be("http://127.0.0.1:9411/api/v2/spans"); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidPollInterval_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.PollInterval, value }, + })); + + tracerSettings.DebuggerSettings.ProbeConfigurationsPollIntervalSeconds.Should().Be(1); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidMaxDepthToSerialize_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.MaxDepthToSerialize, value }, + })); + + tracerSettings.DebuggerSettings.MaximumDepthOfMembersToCopy.Should().Be(1); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidSerializationTimeThreshold_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.MaxTimeToSerialize, value }, + })); + + tracerSettings.DebuggerSettings.MaxSerializationTimeInMilliseconds.Should().Be(150); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("false")] + public void DebuggerDisabled(string enabled) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.Enabled, enabled }, + })); + + tracerSettings.DebuggerSettings.Enabled.Should().BeFalse(); + } + + [Fact] + public void DebuggerSettings_UseSettings() + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.Enabled, "true" }, + { ConfigurationKeys.Debugger.PollInterval, "10" }, + { ConfigurationKeys.Debugger.MaxDepthToSerialize, "100" }, + { ConfigurationKeys.Debugger.MaxTimeToSerialize, "1000" }, + })); + + tracerSettings.DebuggerSettings.Enabled.Should().BeTrue(); + tracerSettings.DebuggerSettings.ProbeConfigurationsPollIntervalSeconds.Should().Be(10); + tracerSettings.DebuggerSettings.MaximumDepthOfMembersToCopy.Should().Be(100); + tracerSettings.DebuggerSettings.MaxSerializationTimeInMilliseconds.Should().Be(1000); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidUploadBatchSize_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.UploadBatchSize, value }, + })); + + tracerSettings.DebuggerSettings.UploadBatchSize.Should().Be(100); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidDiagnosticsInterval_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.DiagnosticsInterval, value }, + })); + + tracerSettings.DebuggerSettings.DiagnosticsIntervalSeconds.Should().Be(3600); + } + + [Theory] + [InlineData("-1")] + [InlineData("0")] + [InlineData("")] + [InlineData(null)] + public void InvalidUploadFlushInterval_DefaultUsed(string value) + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.UploadFlushInterval, value }, + })); + + tracerSettings.DebuggerSettings.UploadFlushIntervalMilliseconds.Should().Be(0); + } + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/LiveDebuggerTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/LiveDebuggerTests.cs new file mode 100644 index 000000000..46bc3ec89 --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/LiveDebuggerTests.cs @@ -0,0 +1,179 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Datadog.Trace.Agent.DiscoveryService; +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger; +using Datadog.Trace.Debugger.Configurations; +using Datadog.Trace.Debugger.Configurations.Models; +using Datadog.Trace.Debugger.Models; +using Datadog.Trace.Debugger.ProbeStatuses; +using Datadog.Trace.Debugger.Sink; +using Datadog.Trace.Debugger.Sink.Models; +using FluentAssertions; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger; + +public class LiveDebuggerTests +{ + [Fact] + public void DebuggerEnabled_ServicesCalled() + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.Enabled, "1" }, + })); + + var settings = ImmutableDebuggerSettings.Create(tracerSettings); + var discoveryService = new DiscoveryServiceMock(); + var configurationPoller = new ConfigurationPollerMock(); + var lineProbeResolver = new LineProbeResolverMock(); + var debuggerSink = new DebuggerSinkMock(); + var probeStatusPoller = new ProbeStatusPollerMock(); + + LiveDebugger.Create(settings, discoveryService, configurationPoller, lineProbeResolver, debuggerSink, probeStatusPoller); + + var counter = 0; + + var allCalled = discoveryService.Called && configurationPoller.Called && debuggerSink.Called; + while (counter < 10 && !allCalled) + { + Thread.Sleep(100); + + allCalled = discoveryService.Called && configurationPoller.Called && debuggerSink.Called; + counter++; + } + + discoveryService.Called.Should().BeTrue(); + configurationPoller.Called.Should().BeTrue(); + debuggerSink.Called.Should().BeTrue(); + probeStatusPoller.Called.Should().BeTrue(); + } + + [Fact] + public void DebuggerDisabled_ServicesNotCalled() + { + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.Debugger.Enabled, "0" }, + })); + + var settings = ImmutableDebuggerSettings.Create(tracerSettings); + var discoveryService = new DiscoveryServiceMock(); + var configurationPoller = new ConfigurationPollerMock(); + var lineProbeResolver = new LineProbeResolverMock(); + var debuggerSink = new DebuggerSinkMock(); + var probeStatusPoller = new ProbeStatusPollerMock(); + + LiveDebugger.Create(settings, discoveryService, configurationPoller, lineProbeResolver, debuggerSink, probeStatusPoller); + + discoveryService.Called.Should().BeFalse(); + configurationPoller.Called.Should().BeFalse(); + lineProbeResolver.Called.Should().BeFalse(); + debuggerSink.Called.Should().BeFalse(); + probeStatusPoller.Called.Should().BeFalse(); + } + + private class DiscoveryServiceMock : IDiscoveryService + { + public string ProbeConfigurationEndpoint => nameof(ProbeConfigurationEndpoint); + + public string DebuggerEndpoint => nameof(DebuggerEndpoint); + + public string AgentVersion => nameof(AgentVersion); + + internal bool Called { get; private set; } + + public Task DiscoverAsync() + { + Called = true; + return Task.FromResult(true); + } + } + + private class ConfigurationPollerMock : IConfigurationPoller + { + internal bool Called { get; private set; } + + public Task StartPollingAsync() + { + Called = true; + return Task.CompletedTask; + } + + public void Dispose() + { + } + } + + private class LineProbeResolverMock : ILineProbeResolver + { + internal bool Called { get; private set; } + + public void OnDomainUnloaded() + { + Called = true; + } + + public LineProbeResolveResult TryResolveLineProbe(ProbeDefinition probe, out BoundLineProbeLocation location) + { + throw new NotImplementedException(); + } + } + + private class DebuggerSinkMock : IDebuggerSink + { + internal bool Called { get; private set; } + + public Task StartFlushingAsync() + { + Called = true; + return Task.CompletedTask; + } + + public void AddSnapshot(string snapshot) + { + throw new NotImplementedException(); + } + + public void AddProbeStatus(string probeId, Status status, Exception exception = null, string errorMessage = null) + { + throw new NotImplementedException(); + } + + public void Dispose() + { + } + } + + private class ProbeStatusPollerMock : IProbeStatusPoller + { + internal bool Called { get; private set; } + + public void StartPolling() + { + Called = true; + } + + public void AddProbes(string[] newProbes) + { + Called = true; + } + + public void RemoveProbes(string[] newProbes) + { + Called = true; + } + + public void Dispose() + { + } + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/ProbeConfigurationComparerTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/ProbeConfigurationComparerTests.cs new file mode 100644 index 000000000..0554781d2 --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/ProbeConfigurationComparerTests.cs @@ -0,0 +1,279 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using Datadog.Trace.Debugger.Configurations; +using Datadog.Trace.Debugger.Configurations.Models; +using FluentAssertions; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger; + +public class ProbeConfigurationComparerTests +{ + [Fact] + public void WhenDefaultConfiguration_NothingChanged() + { + var current = new ProbeConfiguration(); + var incoming = new ProbeConfiguration(); + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentSamplingNull_IncomingSamplingEmpty_RateLimitChanged() + { + var current = new ProbeConfiguration(); + var incoming = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling() }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSamplingEmpty_IncomingSamplingEmpty_RateLimitNotChanged() + { + var current = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling() }; + var incoming = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling() }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentSamplingHasValue_IncomingSamplingEmpty_RateLimitChanged() + { + var current = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling { SnapshotsPerSecond = 5 } }; + var incoming = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling() }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSamplingHasValue_IncomingSamplingSameValue_RateLimitNotChanged() + { + var current = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling { SnapshotsPerSecond = 5 } }; + var incoming = new ProbeConfiguration { Sampling = new Trace.Debugger.Configurations.Models.Sampling { SnapshotsPerSecond = 5 } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentFilterNull_IncomingFilterEmpty_FilterRelatedChanged() + { + var current = new ProbeConfiguration(); + var incoming = new ProbeConfiguration { AllowList = new FilterList() }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentFilterEmpty_IncomingFilterEmpty_FilterRelatedNotChanged() + { + var current = new ProbeConfiguration { AllowList = new FilterList() }; + var incoming = new ProbeConfiguration { AllowList = new FilterList() }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentFilterNotEmpty_IncomingFilterEmpty_FilterRelatedChanged() + { + var current = new ProbeConfiguration { AllowList = new FilterList() }; + var incoming = new ProbeConfiguration { AllowList = new FilterList { Classes = Array.Empty() } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentFilterValue_IncomingFilterSameValue_FilterRelatedNotChanged() + { + var current = new ProbeConfiguration { AllowList = new FilterList { Classes = new string[] { "1", "2" } } }; + var incoming = new ProbeConfiguration { AllowList = new FilterList { Classes = new string[] { "1", "2" } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentFilterValue_IncomingFilterDifferentValue_FilterRelatedNotChanged() + { + var current = new ProbeConfiguration { AllowList = new FilterList { Classes = new string[] { "1", "2" } } }; + var incoming = new ProbeConfiguration { AllowList = new FilterList { Classes = new string[] { "1", "2", "3" } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSnaphotsEmpty_IncomingSnapshotsWithDefault_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSnaphotsNotEmptyWithDefault_IncomingSnapshotsNotEmptyWithDefault_ProbeRelatedNotChanged() + { + var current = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() } }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentSnaphotsValue_IncomingSnapshotsBaseValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() } }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Version = 5 } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSnaphotsValue_IncomingSnapshotsTypeValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() } }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Capture = new Capture() } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentSnaphotsWhereValue_IncomingSnapshotsWhereSameValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentSnaphotsWhereValue_IncomingSnapshotsWhereAnotherValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "d:/temp/temp.log" } } } }; + var incoming = new ProbeConfiguration { SnapshotProbes = new SnapshotProbe[] { new SnapshotProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsEmpty_IncomingMetricsWithDefault_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsNotEmptyWithDefault_IncomingMetricsNotEmptyWithDefault_ProbeRelatedNotChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentMetricsValue_IncomingMetricsBaseValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Version = 5 } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsValue_IncomingMetricsTypeValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { MetricName = "MetricName" } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsWhereValue_IncomingMetricsWhereSameValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } + + [Fact] + public void CurrentMetricsWhereValue_IncomingMetricsWhereAnotherValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Where = new Where() { Lines = new[] { "56" }, SourceFile = "c:/temp/temp.log" } } } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Where = new Where() { Lines = new[] { "57" }, SourceFile = "c:/temp/temp.log" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsValue_IncomingMetricsAnotherValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Value = new MetricValue() { Expr = "Some" } } } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Value = new MetricValue() { Expr = "AweSome" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeTrue(); + comparer.HasRateLimitChanged.Should().BeTrue(); + } + + [Fact] + public void CurrentMetricsValue_IncomingMetricsSameValue_ProbeRelatedChanged() + { + var current = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Value = new MetricValue() { Expr = "Some" } } } }; + var incoming = new ProbeConfiguration { MetricProbes = new MetricProbe[] { new MetricProbe() { Value = new MetricValue() { Expr = "Some" } } } }; + + var comparer = new ProbeConfigurationComparer(current, incoming); + comparer.HasProbeRelatedChanges.Should().BeFalse(); + comparer.HasRateLimitChanged.Should().BeFalse(); + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/ProbeStatusSinkTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/ProbeStatusSinkTests.cs new file mode 100644 index 000000000..18f989aaa --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/ProbeStatusSinkTests.cs @@ -0,0 +1,255 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Linq; +using Datadog.Trace.Configuration; +using Datadog.Trace.Debugger; +using Datadog.Trace.Debugger.Sink; +using Datadog.Trace.Debugger.Sink.Models; +using Datadog.Trace.Util; +using FluentAssertions; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger +{ + public class ProbeStatusSinkTests + { + private readonly TimeLord _timeLord; + private readonly ProbeStatusSink _sink; + private readonly ImmutableDebuggerSettings _settings; + + public ProbeStatusSinkTests() + { + _timeLord = new TimeLord(); + var tracerSettings = new TracerSettings(new NameValueConfigurationSource(new() + { + { ConfigurationKeys.ServiceName, nameof(ProbeStatusSinkTests) }, + })); + + Clock.SetForCurrentThread(_timeLord); + + _settings = ImmutableDebuggerSettings.Create(tracerSettings); + _sink = ProbeStatusSink.Create(_settings); + } + + [Fact] + public void AddReceived() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Count.Should().Be(1); + + var probe = probes.First(); + probe.DebuggerDiagnostics.Diagnostics.Status.Should().Be(Status.RECEIVED); + probe.DebuggerDiagnostics.Diagnostics.ProbeId.Should().Be(probeId); + probe.Service.Should().Be(nameof(ProbeStatusSinkTests)); + probe.Message.Should().Be($"Received probe {probeId}."); + probe.DebuggerDiagnostics.Diagnostics.Exception.Should().BeNull(); + } + + [Fact] + public void AddInstalled() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddInstalled(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Count.Should().Be(1); + + var probe = probes.First(); + probe.DebuggerDiagnostics.Diagnostics.Status.Should().Be(Status.INSTALLED); + probe.DebuggerDiagnostics.Diagnostics.ProbeId.Should().Be(probeId); + probe.Service.Should().Be(nameof(ProbeStatusSinkTests)); + probe.Message.Should().Be($"Installed probe {probeId}."); + probe.DebuggerDiagnostics.Diagnostics.Exception.Should().BeNull(); + } + + [Fact] + public void AddBlocked() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddBlocked(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Count.Should().Be(1); + + var probe = probes.First(); + probe.DebuggerDiagnostics.Diagnostics.Status.Should().Be(Status.BLOCKED); + probe.DebuggerDiagnostics.Diagnostics.ProbeId.Should().Be(probeId); + probe.Service.Should().Be(nameof(ProbeStatusSinkTests)); + probe.Message.Should().Be($"Blocked probe {probeId}."); + probe.DebuggerDiagnostics.Diagnostics.Exception.Should().BeNull(); + } + + [Fact] + public void AddError() + { + var probeId = Guid.NewGuid().ToString(); + var exception = new InvalidOperationException($"Test exceptions at ${nameof(AddError)}"); + + _sink.AddError(probeId, exception); + + var probes = _sink.GetDiagnostics(); + probes.Count.Should().Be(1); + + var probe = probes.First(); + probe.DebuggerDiagnostics.Diagnostics.Status.Should().Be(Status.ERROR); + probe.DebuggerDiagnostics.Diagnostics.ProbeId.Should().Be(probeId); + probe.Service.Should().Be(nameof(ProbeStatusSinkTests)); + probe.Message.Should().Be($"Error installing probe {probeId}."); + probe.DebuggerDiagnostics.Diagnostics.Exception.Should().NotBeNull(); + probe.DebuggerDiagnostics.Diagnostics.Exception.Type.Should().Be(exception.GetType().Name); + probe.DebuggerDiagnostics.Diagnostics.Exception.Message.Should().Be(exception.Message); + probe.DebuggerDiagnostics.Diagnostics.Exception.StackTrace.Should().Be(exception.StackTrace); + } + + [Fact] + public void AddReceivedThenInstalled() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + _sink.AddInstalled(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.RECEIVED), + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.INSTALLED) + }); + } + + [Fact] + public void AddReceivedThenBlocked() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + _sink.AddBlocked(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.RECEIVED), + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.BLOCKED) + }); + } + + [Fact] + public void AddReceivedThenError() + { + var probeId = Guid.NewGuid().ToString(); + var exception = new InvalidOperationException($"Test exceptions at ${nameof(AddError)}"); + + _sink.AddReceived(probeId); + _sink.AddError(probeId, exception); + + var probes = _sink.GetDiagnostics(); + probes.Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.RECEIVED), + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.ERROR, exception) + }); + } + + [Fact] + public void AddReceivedThenInstalledThenError() + { + var probeId = Guid.NewGuid().ToString(); + var exception = new InvalidOperationException($"Test exceptions at ${nameof(AddError)}"); + + _sink.AddReceived(probeId); + _sink.AddInstalled(probeId); + _sink.AddError(probeId, exception); + + var probes = _sink.GetDiagnostics(); + probes.Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.RECEIVED), + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.INSTALLED), + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.ERROR, exception) + }); + } + + [Fact] + public void Remove() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + _sink.Remove(probeId); + + var probes = _sink.GetDiagnostics(); + probes.Should().BeEmpty(); + } + + [Fact] + public void DoNotDoubleEmitMessageIfIntervalHasntPassed() + { + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + + _sink.GetDiagnostics().Should().NotBeEmpty(); + _sink.GetDiagnostics().Should().BeEmpty(); + } + + [Fact] + public void ReemitOnInterval() + { + _timeLord.StopTime(); + var probeId = Guid.NewGuid().ToString(); + + _sink.AddReceived(probeId); + + _sink.GetDiagnostics().Should().NotBeEmpty(); + _timeLord.TravelTo(_timeLord.UtcNow.AddSeconds(_settings.DiagnosticsIntervalSeconds)); + _sink.GetDiagnostics().Should().NotBeEmpty(); + } + + [Fact] + public void ReemitOnlyLatestMessage() + { + _timeLord.StopTime(); + var probeId = Guid.NewGuid().ToString(); + var exception = new InvalidOperationException($"Custom exception for {nameof(ReemitOnlyLatestMessage)}"); + + _sink.AddReceived(probeId); + _sink.AddError(probeId, exception); + _sink.GetDiagnostics().Should().NotBeEmpty(); + + _timeLord.TravelTo(_timeLord.UtcNow.AddSeconds(_settings.DiagnosticsIntervalSeconds)); + _sink.GetDiagnostics().Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.ERROR, exception) + }); + } + + [Fact] + public void DropDiagnostics() + { + var probeId = Guid.NewGuid().ToString(); + _sink.AddReceived(probeId); + + var exception = new InvalidOperationException($"Custom exception for {nameof(ReemitOnlyLatestMessage)}"); + for (var i = 0; i < 999; i++) + { + _sink.AddError(probeId, exception); + } + + _sink.AddError(probeId, exception); + _sink.GetDiagnostics().Should().Equal(new[] + { + new ProbeStatus(nameof(ProbeStatusSinkTests), probeId, Status.ERROR, exception) + }); + } + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/SupportedTypesServiceTests.cs b/tracer/test/Datadog.Trace.Tests/Debugger/SupportedTypesServiceTests.cs new file mode 100644 index 000000000..8e2dbd76a --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/SupportedTypesServiceTests.cs @@ -0,0 +1,29 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +// ReSharper disable once RedundantUsingDirective +using System.ComponentModel; +using System.Linq; +using Datadog.Trace.Debugger.Snapshots; +using Xunit; + +namespace Datadog.Trace.Tests.Debugger +{ + public class SupportedTypesServiceTests + { + private static readonly object[] Objects = { 3, DateTime.Now, TimeSpan.FromSeconds(3), DateTimeOffset.Now, Guid.NewGuid(), "Hello", new int?(5), new DateTime?(DateTime.Now), ConsoleColor.Blue }; + + public static System.Collections.Generic.IEnumerable ObjectsCanCallToStringOn() => Objects.Select(o => new object[] { o }); + + [Theory] + [MemberData(nameof(ObjectsCanCallToStringOn))] + public void TestCanCallToString(object obj) + { + var type = obj.GetType(); + Assert.True(SupportedTypesService.IsSafeToCallToString(type), $"Type {type} should be safe to call ToString on"); + } + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Debugger/TimeLord.cs b/tracer/test/Datadog.Trace.Tests/Debugger/TimeLord.cs new file mode 100644 index 000000000..9c7c3ebc1 --- /dev/null +++ b/tracer/test/Datadog.Trace.Tests/Debugger/TimeLord.cs @@ -0,0 +1,34 @@ +// +// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. +// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. +// + +using System; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions.Common; +using IClock = Datadog.Trace.Util.IClock; + +namespace Datadog.Trace.Tests.Debugger; + +public class TimeLord : IClock +{ + private static DateTime? _now; + + public DateTime UtcNow => _now ?? DateTime.UtcNow; + + public void TravelTo(DateTime dateTime) + { + _now = dateTime; + } + + public void StopTime() + { + TravelTo(UtcNow); + } + + public void BackToNormal() + { + _now = null; + } +} diff --git a/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/LogsApiTests.cs b/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/LogsApiTests.cs index fa3ffd7c4..b0c9578c7 100644 --- a/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/LogsApiTests.cs +++ b/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/LogsApiTests.cs @@ -175,6 +175,11 @@ public void AddHeader(string name, string value) ExtraHeaders.Add(name, value); } + public Task GetAsync() + { + throw new NotImplementedException(); + } + public Task PostAsync(ArraySegment traces, string contentType) { var response = new TestApiResponse(_statusCode, "The message body", contentType); diff --git a/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueueTests.cs b/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueueTests.cs index b75d0c047..fc07d37fc 100644 --- a/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueueTests.cs +++ b/tracer/test/Datadog.Trace.Tests/Logging/DirectSubmission/Sink/PeriodicBatching/BoundedConcurrentQueueTests.cs @@ -1,11 +1,11 @@ -// +// // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // // Based on https://github.com/serilog/serilog-sinks-periodicbatching/blob/66a74768196758200bff67077167cde3a7e346d5/test/Serilog.Sinks.PeriodicBatching.Tests/BoundedConcurrentQueueTests.cs using System; -using Datadog.Trace.Logging.DirectSubmission.Sink.PeriodicBatching; +using Datadog.Trace.Util; using FluentAssertions; using Xunit; @@ -34,5 +34,27 @@ public void WhenInvalidLimitWillThrow(int limit) { Assert.Throws(() => new BoundedConcurrentQueue(limit)); } + + [Fact] + public void CheckCount() + { + const int limit = 5; + var queue = new BoundedConcurrentQueue(limit); + + for (var i = 0; i < limit; i++) + { + queue.TryEnqueue(i); + queue.Count.Should().Be(i + 1); + } + } + + [Fact] + public void CheckIsEmpty() + { + var queue = new BoundedConcurrentQueue(5); + queue.IsEmpty.Should().BeTrue(); + queue.TryEnqueue(5); + queue.IsEmpty.Should().BeFalse(); + } } } diff --git a/tracer/test/Datadog.Trace.Tests/SpanContextPropagatorTests.cs b/tracer/test/Datadog.Trace.Tests/SpanContextPropagatorTests.cs index 26c408513..b01ec23fb 100644 --- a/tracer/test/Datadog.Trace.Tests/SpanContextPropagatorTests.cs +++ b/tracer/test/Datadog.Trace.Tests/SpanContextPropagatorTests.cs @@ -23,6 +23,7 @@ public class SpanContextPropagatorTests private const ulong StringSpanId = 2000000000000000; private const ulong SpanId = 2305843009213693952; private const int SamplingPriority = 0; + private static readonly TraceId TraceId = TraceId.CreateRandom(); private static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; @@ -265,11 +266,11 @@ private static Mock> SetupMockReadOnlyDictio return headers; } - private static void VerifySetCalls(Mock headers) + private static void VerifySetCalls(Mock headers, KeyValuePair[] headersToCheck = null) { var once = Times.Once(); - foreach (var pair in DefaultHeaderValues) + foreach (var pair in headersToCheck ?? DefaultHeaderValues) { headers.Verify(h => h.Set(pair.Key, pair.Value), once); } diff --git a/tracer/test/benchmarks/Benchmarks.Trace/AgentWriterBenchmark.cs b/tracer/test/benchmarks/Benchmarks.Trace/AgentWriterBenchmark.cs index f94935579..a6ee485f3 100644 --- a/tracer/test/benchmarks/Benchmarks.Trace/AgentWriterBenchmark.cs +++ b/tracer/test/benchmarks/Benchmarks.Trace/AgentWriterBenchmark.cs @@ -107,6 +107,11 @@ public void AddHeader(string name, string value) _realRequest.AddHeader(name, value); } + public Task GetAsync() + { + return Task.FromResult(new FakeApiResponse()); + } + public async Task PostAsync(ArraySegment traces, string contentType) { using (var requestStream = Stream.Null) diff --git a/tracer/test/test-applications/debugger/Samples.Probes/IAsyncRun.cs b/tracer/test/test-applications/debugger/Samples.Probes/IAsyncRun.cs new file mode 100644 index 000000000..4e663f6bd --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/IAsyncRun.cs @@ -0,0 +1,8 @@ +using System.Threading.Tasks; + +namespace Samples.Probes; + +public interface IAsyncRun +{ + Task RunAsync(); +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/IRun.cs b/tracer/test/test-applications/debugger/Samples.Probes/IRun.cs new file mode 100644 index 000000000..841df1035 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/IRun.cs @@ -0,0 +1,6 @@ +namespace Samples.Probes; + +public interface IRun +{ + void Run(); +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/LineProbeTestDataAttribute.cs b/tracer/test/test-applications/debugger/Samples.Probes/LineProbeTestDataAttribute.cs new file mode 100644 index 000000000..519241716 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/LineProbeTestDataAttribute.cs @@ -0,0 +1,17 @@ +using System; + +namespace Samples.Probes; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] +public class LineProbeTestDataAttribute : ProbeAttributeBase +{ + public LineProbeTestDataAttribute(int lineNumber, int columnNumber = 0, bool skip = false, int phase = 1, bool unlisted = false, int expectedNumberOfSnapshots = 1, params string[] skipOnFramework) + : base(skip, phase, unlisted, expectedNumberOfSnapshots, skipOnFramework) + { + LineNumber = lineNumber; + ColumnNumber = columnNumber; + } + + public int LineNumber { get; } + public int ColumnNumber { get; } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/MethodProbeTestDataAttribute.cs b/tracer/test/test-applications/debugger/Samples.Probes/MethodProbeTestDataAttribute.cs new file mode 100644 index 000000000..08ab5e890 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/MethodProbeTestDataAttribute.cs @@ -0,0 +1,21 @@ +using System; + +namespace Samples.Probes +{ + [AttributeUsage(AttributeTargets.Method)] + public class MethodProbeTestDataAttribute : ProbeAttributeBase + { + public MethodProbeTestDataAttribute(string returnTypeName = null, string[] parametersTypeName = null, bool skip = false, int phase = 1, bool unlisted = false, int expectedNumberOfSnapshots = 1, bool useFullTypeName = true, params string[] skipOnFramework) + : base(skip, phase, unlisted, expectedNumberOfSnapshots, skipOnFramework) + { + + ReturnTypeName = returnTypeName; + ParametersTypeName = parametersTypeName; + UseFullTypeName = useFullTypeName; + } + + public string ReturnTypeName { get; } + public string[] ParametersTypeName { get; } + public bool UseFullTypeName { get; } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/ProbeAttributeBase.cs b/tracer/test/test-applications/debugger/Samples.Probes/ProbeAttributeBase.cs new file mode 100644 index 000000000..c94450d0a --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/ProbeAttributeBase.cs @@ -0,0 +1,21 @@ +using System; + +namespace Samples.Probes; + +public class ProbeAttributeBase : Attribute +{ + public ProbeAttributeBase(bool skip, int phase, bool unlisted, int expectedNumberOfSnapshots, string[] skipOnFrameworks) + { + Skip = skip; + Phase = phase; + SkipOnFrameworks = skipOnFrameworks; + Unlisted = unlisted; + ExpectedNumberOfSnapshots = expectedNumberOfSnapshots; + } + + public bool Skip { get; } + public int Phase { get; } + public string[] SkipOnFrameworks { get; } + public bool Unlisted { get; } + public int ExpectedNumberOfSnapshots { get; } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Program.cs b/tracer/test/test-applications/debugger/Samples.Probes/Program.cs new file mode 100644 index 000000000..9b08447bd --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Program.cs @@ -0,0 +1,83 @@ +using System; +using System.Reflection; +using System.Security.Policy; +using System.Threading; +using System.Threading.Tasks; +using Samples.Probes; + +public static class Program +{ + private const int millisecondsToWaitSetProbes = 1000 * 4; + private const int millisecondsToWaitForSendSnapshots = 1000 * 10; + + public static async Task Main(string[] args) + { + var testName = GetArg("--test-name", args); + var instance = GetInstance(testName); + + var listenUrl = GetArg("--listen-url", args); + if (listenUrl == null) + { + Thread.Sleep(millisecondsToWaitSetProbes); + await RunTest(instance, testName); + Thread.Sleep(millisecondsToWaitForSendSnapshots); + } + else + { + var listener = new SimpleHttpListener(listenUrl, () => RunTest(instance, testName)); + await listener.HandleIncomingConnections(); + } + } + + private static object GetInstance(string testName) + { + var type = Assembly.GetExecutingAssembly().GetType(testName); + if (type == null) + { + throw new ArgumentException($"Type {testName} not found in assembly {Assembly.GetExecutingAssembly().GetName().Name}"); + } + + var instance = Activator.CreateInstance(type); + return instance; + } + + private static string GetArg(string key, string[] args) + { + var index = Array.IndexOf(args, key); + if (index == -1) + { + return null; + } + + return args.Length <= index ? null : args[index + 1]; + } + + private static async Task RunTest(object instance, string testClassName) + { + switch (instance) + { + case IRun run: + try + { + run.Run(); + } + catch + { + // Ignored + } + break; + case IAsyncRun asyncRun: + try + { + await asyncRun.RunAsync(); + } + catch + { + // Ignored + } + break; + default: + throw new Exception($"Test class not found: {testClassName}"); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Properties/launchSettings.json b/tracer/test/test-applications/debugger/Samples.Probes/Properties/launchSettings.json new file mode 100644 index 000000000..24ebca786 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Properties/launchSettings.json @@ -0,0 +1,21 @@ +{ + "profiles": { + "Samples.Probes": { + "commandName": "Project", + "commandLineArgs": "--test-name Samples.Probes.SmokeTests.GenericMethodWithArguments", + "environmentVariables": { + "SIGNALFX_LOG_LEVEL": "DEBUG", + "CORECLR_PROFILER_PATH": "$(SolutionDir)shared\\bin\\monitoring-home\\tracer\\win-$(Platform)\\SignalFx.Tracing.ClrProfiler.Native.dll", + "COR_PROFILER_PATH": "$(SolutionDir)shared\\bin\\monitoring-home\\tracer\\win-$(Platform)\\SignalFx.Tracing.ClrProfiler.Native.dll", + "COR_ENABLE_PROFILING": "1", + "COR_PROFILER": "{B4C89B0F-9908-4F73-9F59-0D77C5A06874}", + "SIGNALFX_DEBUGGER_PROBE_FILE": "$(SolutionDir)tracer\\test\\test-applications\\debugger\\Samples.Probes\\probes_definition.json", + "CORECLR_ENABLE_PROFILING": "1", + "SIGNALFX_DEBUGGER_ENABLED": "1", + "SIGNALFX_DOTNET_TRACER_HOME": "$(SolutionDir)shared\\bin\\monitoring-home\\tracer", + "CORECLR_PROFILER": "{B4C89B0F-9908-4F73-9F59-0D77C5A06874}" + }, + "nativeDebugging": true + } + } +} \ No newline at end of file diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Samples.Probes.csproj b/tracer/test/test-applications/debugger/Samples.Probes/Samples.Probes.csproj new file mode 100644 index 000000000..2ff9db13d --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Samples.Probes.csproj @@ -0,0 +1,17 @@ + + + + True + $(MSBuildThisFileDirectory)..\..\..\..\..\SignalFx.Tracing.snk + full + false + x86;x64 + + + + netcoreapp2.1;netcoreapp3.0;netcoreapp3.1;net5.0;net6.0 + net461;$(TargetFrameworks) + win7-x86;win7-x64 + + + diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Shared/Address.cs b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Address.cs new file mode 100644 index 000000000..2b7c53e4e --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Address.cs @@ -0,0 +1,31 @@ +namespace Samples.Probes.Shared; + +internal record struct Address +{ + public string Street { get; set; } + public int Number { get; set; } + public Place City { get; set; } + public BuildingType HomeType { get; set; } +} + +internal struct Place +{ + public PlaceType Type { get; set; } + public string Name { get; set; } +} + +internal enum PlaceType +{ + City, + Country +} + +internal enum BuildingType +{ + Cottage, + Duplex, + House, + Hotel, + Resort +} + diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Shared/Generic.cs b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Generic.cs new file mode 100644 index 000000000..cf1f82a4b --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Generic.cs @@ -0,0 +1,7 @@ +namespace Samples.Probes.Shared +{ + internal class Generic : IGeneric + { + public string Message { get; set; } = "Hello"; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Shared/IGeneric.cs b/tracer/test/test-applications/debugger/Samples.Probes/Shared/IGeneric.cs new file mode 100644 index 000000000..24d5a515e --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Shared/IGeneric.cs @@ -0,0 +1,7 @@ +namespace Samples.Probes.Shared +{ + internal interface IGeneric + { + public string Message { get; } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Shared/IntentionalDebuggerException.cs b/tracer/test/test-applications/debugger/Samples.Probes/Shared/IntentionalDebuggerException.cs new file mode 100644 index 000000000..d1b54635f --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Shared/IntentionalDebuggerException.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Samples.Probes.Shared +{ + internal class IntentionalDebuggerException : Exception + { + public IntentionalDebuggerException(string message) + : base(message) + { + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/Shared/Person.cs b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Person.cs new file mode 100644 index 000000000..5be65ec1f --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/Shared/Person.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; + +namespace Samples.Probes.Shared; + +internal class Person +{ + private int _shouldCloned; + internal Person(string name, double age, Address address, Guid id, List children) + { + _shouldCloned = (int)age; + Name = name; + Age = age; + Address = address; + Id = id; + Children = children; + } + + public string Name { get; } + public double Age { get; } + public Address Address { get; } + public Guid Id { get; } + public List Children { get; } + + public int ShouldNotCloned + { + get + { + var hash = GetHashCode(); + if (hash % 2 == 0) + { + return hash; + } + else + { + return _shouldCloned; + } + } + set + { + _shouldCloned = value; + } + } + + public override string ToString() + { + return $"{Name} ({Age})"; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SimpleHttpListener.cs b/tracer/test/test-applications/debugger/Samples.Probes/SimpleHttpListener.cs new file mode 100644 index 000000000..b6a4786c2 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SimpleHttpListener.cs @@ -0,0 +1,56 @@ +using System; +using System.Net; +using System.Threading.Tasks; + +namespace Samples.Probes; + +public class SimpleHttpListener : IDisposable +{ + private readonly HttpListener _listener; + private readonly Func _task; + + public SimpleHttpListener(string listenUri, Func task) + { + _task = task; + _listener = new HttpListener(); + _listener.Prefixes.Add(listenUri); + } + + public async Task HandleIncomingConnections() + { + _listener.Start(); + + var run = true; + + while (run) + { + var ctx = await _listener.GetContextAsync(); + + + Console.WriteLine($"[{ctx.Request.HttpMethod}] {ctx.Request.Url}"); + var absolutePath = ctx.Request.Url.AbsolutePath; + + switch (absolutePath) + { + case "/stop": + Console.WriteLine("Stop requested"); + run = false; + break; + default: + if (_task != null) + { + await _task.Invoke(); + } + + break; + } + + ctx.Response.Close(); + } + } + + public void Dispose() + { + _listener.Close(); + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/AsyncInstanceMethod.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/AsyncInstanceMethod.cs new file mode 100644 index 000000000..304ae26cb --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/AsyncInstanceMethod.cs @@ -0,0 +1,28 @@ +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Samples.Probes.SmokeTests +{ + internal class AsyncInstanceMethod : IAsyncRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public async Task RunAsync() + { + await Method("Name"); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Threading.Tasks.Task", new[] { "System.String" })] + public async Task Method(string name) + { + char[] array = new char[name.Length]; + for (int i = 0; i < name.Length; i++) + { + array[i] = name[i]; + } + + await Task.Delay(250); + return new string(array); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/Emit100LineProbeSnapshotsTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/Emit100LineProbeSnapshotsTest.cs new file mode 100644 index 000000000..5deff9240 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/Emit100LineProbeSnapshotsTest.cs @@ -0,0 +1,22 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests; + +[LineProbeTestData(lineNumber: 14, unlisted: true, skipOnFramework: new []{ "net6.0" })] +public class Emit100LineProbeSnapshotsTest : IRun +{ + public void Run() + { + var accu = 0; + for (int i = 0; i < 100; i++) + { + accu += i; + } + + if (accu > 0) + { + throw new IntentionalDebuggerException($"accu is {accu}"); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/GenericMethodWithArgumentsAndLocals.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/GenericMethodWithArgumentsAndLocals.cs new file mode 100644 index 000000000..973d6ea02 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/GenericMethodWithArgumentsAndLocals.cs @@ -0,0 +1,25 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(lineNumber: 22)] + internal class GenericMethodWithArguments : IRun + { + public string Prop { get; } = nameof(GenericMethodWithArguments); + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + var p = new Person("Alfred Hitchcock", 30, new Address { HomeType = BuildingType.Duplex, Number = 5, Street = "Elsewhere" }, System.Guid.NewGuid(), null); + Method(p); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "!!0" })] + public string Method(T genericParam) + { + return genericParam.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasArgumentsAndLocals.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasArgumentsAndLocals.cs new file mode 100644 index 000000000..0c5b9c31d --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasArgumentsAndLocals.cs @@ -0,0 +1,23 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class HasArgumentsAndLocals : IRun + { + public string FirstName { get; set; } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method("Last"); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public string Method(string lastName) + { + FirstName = "First"; + return FirstName + " " + lastName; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasException.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasException.cs new file mode 100644 index 000000000..de213344a --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasException.cs @@ -0,0 +1,22 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class HasException : IRun + { + public string Name { get; set; } = "A"; + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(Name); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Int32", new[] { "System.String" }, true)] + public int Method(string name) + { + return int.Parse(name); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueInitialized.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueInitialized.cs new file mode 100644 index 000000000..7dbaf7f42 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueInitialized.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class HasFieldLazyValueInitialized : IRun + { + public Lazy FirstName = new Lazy(new Func(() => "First")); + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(FirstName.Value); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public string Method(string lastName) + { + return lastName; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueNotInitialized.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueNotInitialized.cs new file mode 100644 index 000000000..5ca186331 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasFieldLazyValueNotInitialized.cs @@ -0,0 +1,23 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class HasFieldLazyValueNotInitialized : IRun + { + public Lazy FirstName = new Lazy(new Func(() => "First")); + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method("Last"); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public string Method(string lastName) + { + return lastName; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalListOfObjects.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalListOfObjects.cs new file mode 100644 index 000000000..44c9e9e34 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalListOfObjects.cs @@ -0,0 +1,26 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + // https://datadoghq.atlassian.net/browse/DEBUG-723 + public class HasLocalListOfObjects : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method("Greg", 36); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String", "System.Int32" }, skipOnFramework: "net6.0")] + public string Method(string name, int age) + { + var p2 = new Person("Simon", 30, new Address { HomeType = BuildingType.Hotel, Number = 3, Street = "Elsewhere" }, System.Guid.NewGuid(), null); + var p3 = new Person("Lucy", 7.5, new Address { HomeType = BuildingType.House, Number = 100, Street = "Here" }, System.Guid.NewGuid(), null); + var children = new System.Collections.Generic.List { p2, p3 }; + var p = new Person(name, age, new Address { HomeType = BuildingType.Cottage, Number = 17, Street = "Somewhere" }, System.Guid.NewGuid(), children); + return $"Hello {p}!"; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskCompleted.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskCompleted.cs new file mode 100644 index 000000000..980eabef9 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskCompleted.cs @@ -0,0 +1,27 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Samples.Probes.SmokeTests +{ + internal class HasLocalTaskCompleted : IRun + { + public Task LastNameTask = new Task(new Func(() => "Last")); + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + LastNameTask.Start(); + LastNameTask.Wait(); + Method(LastNameTask); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + // https://datadoghq.atlassian.net/browse/DEBUG-722 + [MethodProbeTestData("System.String", new[] { "System.Threading.Tasks.Task`1" }, true)] + public string Method(Task task) + { + return task.Status.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskNotCompleted.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskNotCompleted.cs new file mode 100644 index 000000000..4afd42cef --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalTaskNotCompleted.cs @@ -0,0 +1,34 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Samples.Probes.SmokeTests +{ + internal class HasLocalTaskNotCompleted : IRun + { + public Task LastNameTask = new Task(new Func(() => throw new Exception())); + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + try + { + LastNameTask.Start(); + LastNameTask.Wait(); + } + catch (Exception) + { + } + + Method(LastNameTask); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + // https://datadoghq.atlassian.net/browse/DEBUG-722 + [MethodProbeTestData("System.String", new[] { "System.Threading.Tasks.Task`1" }, true)] + public string Method(Task task) + { + return task.Status.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndArgumentsInGenericType.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndArgumentsInGenericType.cs new file mode 100644 index 000000000..11660a6f5 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndArgumentsInGenericType.cs @@ -0,0 +1,42 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + internal class HasLocalsAndArgumentsInGenericNestedType : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + new Test().Method(new GenericInstantiation(), 36); + } + + private class GenericInstantiation + { + public GenericInstantiation() + { + } + + public override string ToString() + { + return $"{nameof(GenericInstantiation)}!"; + } + } + + public class Test where T : new() + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "!0", "System.Int32" }, skipOnFramework: new string[]{ "net6.0" })] + public string Method(T genericVar, int age) + { + var genericVarToString = genericVar.ToString(); + var p2 = new Person(genericVarToString + "Simon", 30, new Address { HomeType = BuildingType.Hotel, Number = 3, Street = "Elsewhere" }, System.Guid.NewGuid(), null); + var newT = (new T()).ToString(); + var p3 = new Person(newT + "Lucy", 7.5, new Address { HomeType = BuildingType.House, Number = 100, Street = "Here" }, System.Guid.NewGuid(), null); + var children = new System.Collections.Generic.List { p2, p3 }; + var p = new Person(newT, age, new Address { HomeType = BuildingType.Cottage, Number = 17, Street = "Somewhere" }, System.Guid.NewGuid(), children); + return $"Hello {p}!"; + } + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndReturnValue.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndReturnValue.cs new file mode 100644 index 000000000..8aced8e62 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasLocalsAndReturnValue.cs @@ -0,0 +1,28 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(16)] + [LineProbeTestData(17)] + [LineProbeTestData(25)] + internal class HasLocalsAndReturnValue : IRun + { + public int Number { get; set; } = 7; + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + var result = Method(Number); + Console.WriteLine(result); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.Int32" })] + public string Method(int num) + { + var timeSpan = TimeSpan.FromSeconds(num); + return timeSpan.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasReturnValue.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasReturnValue.cs new file mode 100644 index 000000000..63aebf1c7 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasReturnValue.cs @@ -0,0 +1,23 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class HasReturnValue : IRun + { + public int Number { get; set; } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new string[0])] + public string Method() + { + Number = 7; + return Number.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasVarAndMvar.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasVarAndMvar.cs new file mode 100644 index 000000000..d099742eb --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/HasVarAndMvar.cs @@ -0,0 +1,31 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + internal class HasVarAndMvar : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + new Test().Method(new Generic()); + } + + public class Test where T : IGeneric + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Collections.Generic.List`1>", new[] { "!!0" })] + public List> Method(K k) where K : IGeneric + { + var @string = k.ToString(); + System.Console.WriteLine(@string); + var kk = new List>() { new Test() }; + System.Console.WriteLine(kk); + var tt = new List>() { new Test() }; + return tt; + } + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceMethodWithArguments.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceMethodWithArguments.cs new file mode 100644 index 000000000..c68f32c43 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceMethodWithArguments.cs @@ -0,0 +1,21 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(18)] + internal class InstanceMethodWithArguments : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method("Last"); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public string Method(string lastName) + { + return lastName; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceVoidMethod.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceVoidMethod.cs new file mode 100644 index 000000000..06efb583e --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/InstanceVoidMethod.cs @@ -0,0 +1,22 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class InstanceVoidMethod : IRun + { + public int Number { get; set; } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new string[0])] + public void Method() + { + Number = 7; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/LineProbesWithRevertTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/LineProbesWithRevertTest.cs new file mode 100644 index 000000000..14bb337ec --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/LineProbesWithRevertTest.cs @@ -0,0 +1,61 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests; + +// Phase 1 +[LineProbeTestData(lineNumber: 41, phase: 1)] +[LineProbeTestData(lineNumber: 55, phase: 1)] +[LineProbeTestData(lineNumber: 56, phase: 1)] + +// Phase 2 +[LineProbeTestData(lineNumber: 41, phase: 2)] +[LineProbeTestData(lineNumber: 55, phase: 2)] +[LineProbeTestData(lineNumber: 56, phase: 2)] +[LineProbeTestData(lineNumber: 57, phase: 2)] +[LineProbeTestData(lineNumber: 58, phase: 2)] + +// Phase 3 +[LineProbeTestData(lineNumber: 46, phase: 3, expectedNumberOfSnapshots: 3)] +[LineProbeTestData(lineNumber: 59, phase: 3)] + +// Phase 4 +[LineProbeTestData(lineNumber: 55, phase: 4)] + +// Phase 5 +[LineProbeTestData(lineNumber: 46, phase: 5, expectedNumberOfSnapshots: 3)] + +// Phase 6 +// Probe in unreachable branch should not emit any snapshot +[LineProbeTestData(lineNumber: 52, phase: 6, expectedNumberOfSnapshots: 0)] +public class LineProbesWithRevertTest : IRun +{ + public void Run() + { + MethodToInstrument(nameof(Run)); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" }, phase: 1)] + public void MethodToInstrument(string callerName) + { + int a = callerName.Length; + + int sum = a; + for (int i = 2; i < a + 2; i++) + { + sum *= i; + } + + if (sum < 10) + { + // Unreachable branch + sum = 0; + } + + a++; + a++; + a++; + a++; + a++; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MethodThrowExceptionTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MethodThrowExceptionTest.cs new file mode 100644 index 000000000..f531869b0 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MethodThrowExceptionTest.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(26, skipOnFramework: new[] { "net6.0" })] + internal class MethodThrowExceptionTest : IRun + { + public int Number { get; set; } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(int.MaxValue); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new []{ "System.Int32" }, skipOnFramework: new[] { "net6.0" })] + public string Method(int toSet) + { + Number += 7; + var numberSnapshot = Number; + Number = toSet; + if (Number > numberSnapshot) + { + throw new InvalidOperationException($"Number {Number }is above snapshot value {numberSnapshot}"); + } + + return toSet.ToString(); + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultiScopesWithSameLocalNameTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultiScopesWithSameLocalNameTest.cs new file mode 100644 index 000000000..410771dd5 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultiScopesWithSameLocalNameTest.cs @@ -0,0 +1,40 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests; + +/// +/// This test yields wrongful snapshots. We have two locals, with same names but in different scopes (`i` and `localInFor`). +/// As we currently are not taking into account scoping when we resolve local index -> name, +/// we might capture the wrong local at the wrong location. +/// In this example, we place a line probe on line 25 (first for loop), expected to see the value of the locals +/// at this location but we accidently capture the `i` and `localInFor` that are in the scope of the second for loop (as they override the `i` and `localInFor` of the first loop, because of the same naming) +/// thus they will see the value '0' in the snapshots instead of having their real value. +/// +[LineProbeTestData(lineNumber: 26, expectedNumberOfSnapshots: 2)] +[LineProbeTestData(lineNumber: 33, expectedNumberOfSnapshots: 2)] +public class MultiScopesWithSameLocalNameTest : IRun +{ + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + for (int i = 0; i < 2; i++) + { + int localInFor = i + 2; + Mutate(ref localInFor); + Console.WriteLine(localInFor); + } + + for (int i = 0; i < 2; i++) + { + int localInFor = i + 4; + Mutate(ref localInFor); + Console.WriteLine(localInFor); + } + } + + void Mutate(ref int @out) + { + @out += 5; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultipleLineProbes.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultipleLineProbes.cs new file mode 100644 index 000000000..0281f9e2c --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/MultipleLineProbes.cs @@ -0,0 +1,26 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests; + +[LineProbeTestData(lineNumber: 21)] +[LineProbeTestData(lineNumber: 22)] +[LineProbeTestData(lineNumber: 23)] +[LineProbeTestData(lineNumber: 24)] +[LineProbeTestData(lineNumber: 25)] +public class MultipleLineProbes : IRun +{ + public void Run() + { + MethodToInstrument(nameof(Run)); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" })] + public void MethodToInstrument(string callerName) + { + int a = callerName.Length; + a++; + a++; + a++; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/NonSupportedInstrumentationTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/NonSupportedInstrumentationTest.cs new file mode 100644 index 000000000..903f6c006 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/NonSupportedInstrumentationTest.cs @@ -0,0 +1,29 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests; + +public class NonSupportedInstrumentationTest : IRun +{ + public void Run() + { + new GenericStructIsNotSupported().MethodToInstrument(nameof(Run)); + } + + struct GenericStructIsNotSupported + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData(expectedNumberOfSnapshots: 0)] // Should fail on instrumentation as we don't support the instrumentation of methods that reside inside an inner generic struct. + public void MethodToInstrument(string callerName) + { + var arr = new[] { callerName, nameof(MethodToInstrument), nameof(SimpleTypeNameTest) }; + if (NoOp(arr).Length == arr.Length) + { + throw new IntentionalDebuggerException("Same length."); + } + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + string[] NoOp(string[] arr) => arr; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OpenGenericMethodInDerivedGenericType.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OpenGenericMethodInDerivedGenericType.cs new file mode 100644 index 000000000..6f79ccf45 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OpenGenericMethodInDerivedGenericType.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + internal class OpenGenericMethodInDerivedGenericType : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + new Test2().Method(new Generic(), new OpenGenericMethodInDerivedGenericType(), new Generic()); + } + + public class Test2 : HasVarAndMvar.Test + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "!!0", "!0", "Samples.Probes.Shared.Generic" })] + public string Method(K k, Generic2 gen2, Generic gen) + { + var kToString = k.ToString(); + var gen2ToString = gen2.ToString(); + var genToString = gen.ToString(); + return kToString + gen2ToString + genToString; + } + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OverloadAndSimpleNameTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OverloadAndSimpleNameTest.cs new file mode 100644 index 000000000..81f1ab169 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/OverloadAndSimpleNameTest.cs @@ -0,0 +1,140 @@ +using System; +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests +{ + public class OverloadAndSimpleNameTest : IRun + { + public void Run() + { + // Call every single "Method", while a single Method Probe request is applied. + // Take a note that the signature is not given, thus it shall instrument every single overload. + + Method("First Call"); // Should be instrumented. + CaptureException(() => Method(int.MinValue)); // Should be instrumented. + CaptureException(() => Method(int.MinValue, int.MaxValue)); // Should be instrumented. + CaptureException(() => Method('@')); // Should be instrumented. + + var p1 = new Person("Theodor Herzl", 44, new Address(), new System.Guid(), null); + var p2 = new Person("David Wolffsohn", 58, new Address(), new System.Guid(), null); + new InnerType().Method(p1, p2); // Should not be instrumented. The method name matches, but the class name does not + new InnerType().Method("Marty McFly"); // Should not be instrumented. The method name match. but the class name does not. + + // As inner type (in global namespace): + new OuterType.OverloadAndSimpleNameTest().Method(p1, p2); // Should be instrumented. + new OuterType.OverloadAndSimpleNameTest().Method("Marty McFly"); // Should be instrumented. + + // As inner type in another namespace: + new Spicing.Things.Down.OuterType.OverloadAndSimpleNameTest().Method('@'); // Should be instrumented. + + // As Another namespace: + new Spicing.Things.Up.OverloadAndSimpleNameTest().Method(new Address { City = new Place { Name = "Some Place"} }); // Should be instrumented. + new Spicing.Things.Up.OverloadAndSimpleNameTest().Method('@'); // Should be instrumented. + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData(useFullTypeName: false, unlisted: true)] + public void Method(string callerName) + { + int a = callerName.Length; + a++; + a++; + a++; + } + + public char Method(int a, int b) + { + return ThrowException(null); + } + + public string Method(int a) + { + return ThrowException(null); + } + + public void Method(char c) + { + var local = nameof(Method) + c; + ThrowException(local); + } + + private T ThrowException(string local) + { + throw new System.NotImplementedException(); + } + + public void CaptureException(Action callback) + { + try + { + callback(); + } + catch + { + // Ignored + } + } + + class InnerType + { + public Person Method(Person a, Person b) + { + var isEqual = a.Equals(b); + return new Person("Person Name", isEqual ? 0 : 50.50, new Address(), new System.Guid(), null); + } + + public string Method(string a) + { + return nameof(Method) + a; + } + } + } +} + +class OuterType +{ + public class OverloadAndSimpleNameTest + { + public Person Method(Person a, Person b) + { + var isEqual = a.Equals(b); + return new Person("Person Name", isEqual ? 0 : 50.50, new Address(), new System.Guid(), null); + } + + public string Method(string a) + { + return typeof(OverloadAndSimpleNameTest).FullName + "." + nameof(Method) + "[" + a + "]"; + } + } +} + +namespace Spicing.Things.Up +{ + class OverloadAndSimpleNameTest + { + public Address Method(Address adr) + { + return adr; + } + + public string Method(char c) + { + return typeof(OverloadAndSimpleNameTest).FullName + "." + nameof(Method) + "." + c; + } + } +} + +namespace Spicing.Things.Down +{ + class OuterType + { + public class OverloadAndSimpleNameTest + { + public string Method(char c) + { + return typeof(OverloadAndSimpleNameTest).FullName + "." + nameof(Method) + "." + c; + } + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameInGlobalNamespaceTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameInGlobalNamespaceTest.cs new file mode 100644 index 000000000..8997a0a26 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameInGlobalNamespaceTest.cs @@ -0,0 +1,29 @@ +using System.Runtime.CompilerServices; +using Samples.Probes; +using Samples.Probes.Shared; +using Samples.Probes.SmokeTests; + +public class SimpleNestedTypeNameInGlobalNamespaceTest : IRun +{ + public void Run() + { + new NestedType().MethodToInstrument(nameof(Run)); + } + + class NestedType + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" }, useFullTypeName: false)] + public void MethodToInstrument(string callerName) + { + var arr = new[] { callerName, nameof(MethodToInstrument), nameof(SimpleTypeNameTest) }; + if (NoOp(arr).Length == arr.Length) + { + throw new IntentionalDebuggerException("Same length."); + } + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + string[] NoOp(string[] arr) => arr; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameTest.cs new file mode 100644 index 000000000..c3a71faed --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleNestedTypeNameTest.cs @@ -0,0 +1,29 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests; + +public class SimpleNestedTypeNameTest : IRun +{ + public void Run() + { + new NestedType().MethodToInstrument(nameof(Run)); + } + + class NestedType + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" }, useFullTypeName: false)] + public void MethodToInstrument(string callerName) + { + var arr = new[] { callerName, nameof(MethodToInstrument), nameof(SimpleTypeNameTest) }; + if (NoOp(arr).Length == arr.Length) + { + throw new IntentionalDebuggerException("Same length."); + } + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + string[] NoOp(string[] arr) => arr; + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameInGlobalNamespaceTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameInGlobalNamespaceTest.cs new file mode 100644 index 000000000..39b599e96 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameInGlobalNamespaceTest.cs @@ -0,0 +1,26 @@ +using System.Runtime.CompilerServices; +using Samples.Probes; +using Samples.Probes.Shared; +using Samples.Probes.SmokeTests; + +public class SimpleTypeNameInGlobalNamespaceTest : IRun +{ + public void Run() + { + MethodToInstrument(nameof(Run)); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" }, useFullTypeName: false)] + public void MethodToInstrument(string callerName) + { + var arr = new[] { callerName, nameof(MethodToInstrument), nameof(SimpleTypeNameTest) }; + if (NoOp(arr).Length == arr.Length) + { + throw new IntentionalDebuggerException("Same length."); + } + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + string[] NoOp(string[] arr) => arr; +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameTest.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameTest.cs new file mode 100644 index 000000000..ce7112c2e --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/SimpleTypeNameTest.cs @@ -0,0 +1,26 @@ +using System.Runtime.CompilerServices; +using Samples.Probes.Shared; + +namespace Samples.Probes.SmokeTests; + +public class SimpleTypeNameTest : IRun +{ + public void Run() + { + MethodToInstrument(nameof(Run)); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new[] { "System.String" }, useFullTypeName: false)] + public void MethodToInstrument(string callerName) + { + var arr = new[] { callerName, nameof(MethodToInstrument), nameof(SimpleTypeNameTest) }; + if (NoOp(arr).Length == arr.Length) + { + throw new IntentionalDebuggerException("Same length."); + } + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + string[] NoOp(string[] arr) => arr; +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticMethodWithArguments.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticMethodWithArguments.cs new file mode 100644 index 000000000..d2dca73e5 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticMethodWithArguments.cs @@ -0,0 +1,21 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(18)] + internal class StaticMethodWithArguments : IRun + { + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method("Last"); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public static string Method(string lastName) + { + return lastName; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticType.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticType.cs new file mode 100644 index 000000000..7c00a192a --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticType.cs @@ -0,0 +1,26 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + [LineProbeTestData(lineNumber: 22)] + public class StaticType : IRun + { + public void Run() + { + StaticTypeInner.Method("Last name"); + } + + public static class StaticTypeInner + { + public static string _staticField = "Static Field"; + public static string StaticProperty { get; } = "Static Property"; + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.String", new[] { "System.String" })] + public static string Method(string lastName) + { + return lastName; + } + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticVoidMethod.cs b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticVoidMethod.cs new file mode 100644 index 000000000..fd497dab7 --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/SmokeTests/StaticVoidMethod.cs @@ -0,0 +1,22 @@ +using System.Runtime.CompilerServices; + +namespace Samples.Probes.SmokeTests +{ + internal class StaticVoidMethod : IRun + { + public static int Number { get; set; } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + public void Run() + { + Method(); + } + + [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] + [MethodProbeTestData("System.Void", new string[0])] + public static void Method() + { + Number = 7; + } + } +} diff --git a/tracer/test/test-applications/debugger/Samples.Probes/probes_definition.json b/tracer/test/test-applications/debugger/Samples.Probes/probes_definition.json new file mode 100644 index 000000000..f445b93ef --- /dev/null +++ b/tracer/test/test-applications/debugger/Samples.Probes/probes_definition.json @@ -0,0 +1,92 @@ +{ + "Id": "00000000-0000-0000-0000-000000000000", + "SnapshotProbes": [ + { + "Capture": null, + "Sampling": null, + "Language": "dotnet", + "Id": "3410cda1-5b13-a34e-6f84-a54adf7a0ea0", + "OrgId": null, + "AppId": null, + "Active": true, + "Tags": null, + "Where": { + "TypeName": null, + "MethodName": null, + "SourceFile": "C:\\dev\\slydog-dd-trace-dotnet\\tracer\\test\\test-applications\\debugger\\Samples.Probes\\SmokeTests\\LineProbesWithRevertTest.cs", + "Signature": null, + "Lines": [ + "41" + ] + }, + "AdditionalIds": null, + "Version": null + }, + { + "Capture": null, + "Sampling": null, + "Language": "dotnet", + "Id": "17c1e39c-e46c-828e-4e02-21be0f3b5358", + "OrgId": null, + "AppId": null, + "Active": true, + "Tags": null, + "Where": { + "TypeName": null, + "MethodName": null, + "SourceFile": "C:\\dev\\slydog-dd-trace-dotnet\\tracer\\test\\test-applications\\debugger\\Samples.Probes\\SmokeTests\\LineProbesWithRevertTest.cs", + "Signature": null, + "Lines": [ + "55" + ] + }, + "AdditionalIds": null, + "Version": null + }, + { + "Capture": null, + "Sampling": null, + "Language": "dotnet", + "Id": "1828a3f0-e94b-eb91-81e3-12bcf19ac41a", + "OrgId": null, + "AppId": null, + "Active": true, + "Tags": null, + "Where": { + "TypeName": null, + "MethodName": null, + "SourceFile": "C:\\dev\\slydog-dd-trace-dotnet\\tracer\\test\\test-applications\\debugger\\Samples.Probes\\SmokeTests\\LineProbesWithRevertTest.cs", + "Signature": null, + "Lines": [ + "56" + ] + }, + "AdditionalIds": null, + "Version": null + }, + { + "Capture": null, + "Sampling": null, + "Language": "dotnet", + "Id": "8286d046-9740-a3e4-95cf-ff46699c73c4", + "OrgId": null, + "AppId": null, + "Active": true, + "Tags": null, + "Where": { + "TypeName": "Samples.Probes.SmokeTests.LineProbesWithRevertTest", + "MethodName": "MethodToInstrument", + "SourceFile": null, + "Signature": "System.Void,System.String", + "Lines": null + }, + "AdditionalIds": null, + "Version": null + } + ], + "MetricProbes": [], + "AllowList": null, + "DenyList": null, + "Sampling": null, + "OpsConfiguration": null +} \ No newline at end of file