-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcor_profiler.cpp
2720 lines (2341 loc) · 111 KB
/
cor_profiler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#include "cor_profiler.h"
#include "corhlpr.h"
#include <corprof.h>
#include <string>
#include <typeinfo>
#ifdef _WIN32
#include <regex>
#else
#include <re2/re2.h>
#endif
#include "clr_helpers.h"
#include "dllmain.h"
#include "environment_variables.h"
#include "environment_variables_util.h"
#include "il_rewriter.h"
#include "il_rewriter_wrapper.h"
#include "logger.h"
#include "metadata_builder.h"
#include "module_metadata.h"
#include "otel_profiler_constants.h"
#include "pal.h"
#include "resource.h"
#include "startup_hook.h"
#include "stats.h"
#include "util.h"
#include "version.h"
#include "continuous_profiler.h"
#ifdef MACOS
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#endif
using namespace std::chrono_literals;
#ifdef _WIN32
#include "netfx_assembly_redirection.h"
#endif
#define FailProfiler(LEVEL, MESSAGE) \
Logger::LEVEL(MESSAGE); \
if (IsFailFastEnabled()) \
{ \
throw std::runtime_error(MESSAGE); \
} \
else \
{ \
return E_FAIL; \
}
namespace trace
{
CorProfiler* profiler = nullptr;
//
// ICorProfilerCallback methods
//
HRESULT STDMETHODCALLTYPE CorProfiler::Initialize(IUnknown* cor_profiler_info_unknown)
{
auto _ = trace::Stats::Instance()->InitializeMeasure();
this->continuousProfiler = nullptr;
CorProfilerBase::Initialize(cor_profiler_info_unknown);
if (Logger::IsDebugEnabled())
{
const auto env_variables = GetEnvironmentVariables(env_vars_prefixes_to_display);
Logger::Debug("Environment variables:");
// Update the list also in SmokeTests.NativeLogsHaveNoSensitiveData
const auto secrets_pattern = "(?:^|_)(API|TOKEN|SECRET|KEY|PASSWORD|PASS|PWD|HEADER|CREDENTIALS)(?:_|$)";
#ifdef _WIN32
const std::regex secrets_regex(secrets_pattern, std::regex_constants::ECMAScript | std::regex_constants::icase);
#else
static re2::RE2 re(secrets_pattern, RE2::Quiet);
#endif
for (const auto& env_variable : env_variables)
{
#ifdef _WIN32
if (!std::regex_search(ToString(env_variable), secrets_regex))
#else
if (!re2::RE2::PartialMatch(ToString(env_variable), re))
#endif
{
Logger::Debug(" ", env_variable);
}
else
{
// Remove secret value and replace with <hidden>
Logger::Debug(" ", env_variable.substr(0, env_variable.find_first_of('=')), "=<hidden>");
}
}
}
// get ICorProfilerInfo12 for >= .NET 5.0
ICorProfilerInfo12* info12 = nullptr;
HRESULT hr = cor_profiler_info_unknown->QueryInterface(__uuidof(ICorProfilerInfo12), (void**)&info12);
if (SUCCEEDED(hr))
{
Logger::Debug("Interface ICorProfilerInfo12 found.");
this->info_ = info12;
this->info12_ = info12;
}
else
{
// get ICorProfilerInfo7 interface for .NET Framework >= 4.6.1 and any .NET (Core)
hr = cor_profiler_info_unknown->QueryInterface(__uuidof(ICorProfilerInfo7), (void**)&this->info_);
if (FAILED(hr))
{
FailProfiler(Warn, "Failed to attach profiler: Not supported .NET Framework version (lower than 4.6.1).")
}
info12 = nullptr;
this->info12_ = nullptr;
}
// code is ready to get runtime information
runtime_information_ = GetRuntimeInformation(this->info_);
if (Logger::IsDebugEnabled())
{
if (runtime_information_.is_desktop())
{
// on .NET Framework it is the CLR version therefore major_version == 4 and minor_version == 0
Logger::Debug(".NET Runtime: .NET Framework");
}
else if (runtime_information_.major_version < 5)
{
// on .NET Core the major_version == 4 and minor_version == 0 (sic!)
Logger::Debug(".NET Runtime: .NET Core");
}
else
{
Logger::Debug(".NET Runtime: .NET ", runtime_information_.major_version, ".",
runtime_information_.minor_version);
}
}
if (runtime_information_.is_core() && runtime_information_.major_version < 6)
{
FailProfiler(Warn, "Failed to attach profiler: Not supported .NET version (lower than 6.0).")
}
#ifdef _WIN32
if (runtime_information_.is_desktop() && IsNetFxAssemblyRedirectionEnabled())
{
InitNetFxAssemblyRedirectsMap();
}
#endif
const auto& process_name = GetCurrentProcessName();
const auto& exclude_process_names = GetEnvironmentValues(environment::exclude_process_names);
// attach profiler only if this process's name is NOT on the list
if (!exclude_process_names.empty() && Contains(exclude_process_names, process_name))
{
Logger::Info("Profiler disabled: ", process_name, " found in ", environment::exclude_process_names, ".");
FailProfiler(Info, "Profiler disabled - excluded process")
}
if (runtime_information_.is_core())
{
// .NET Core applications should use the dotnet StartupHook to bootstrap OpenTelemetry so that the
// necessary dependencies will be available. Bootstrapping with the profiling APIs occurs too early
// and the necessary dependencies are not available yet.
// Ensure that OTel StartupHook is listed.
const auto home_path = GetEnvironmentValue(environment::profiler_home_path);
const auto startup_hooks = GetEnvironmentValues(environment::dotnet_startup_hooks, ENV_VAR_PATH_SEPARATOR);
if (!IsStartupHookValid(startup_hooks, home_path))
{
FailProfiler(Error, "The required StartupHook was not configured correctly. No telemetry will be captured.")
}
}
if (IsAzureAppServices())
{
Logger::Info("Profiler is operating within Azure App Services context.");
in_azure_app_services = true;
const auto& app_pool_id_value = GetEnvironmentValue(environment::azure_app_services_app_pool_id);
if (app_pool_id_value.size() > 1 && app_pool_id_value.at(0) == '~')
{
Logger::Info("Profiler disabled: ", environment::azure_app_services_app_pool_id, " ", app_pool_id_value,
" is recognized as an Azure App Services infrastructure process.");
FailProfiler(Info, "Profiler disabled - Azure App Services infrastructure process.")
}
const auto& cli_telemetry_profile_value =
GetEnvironmentValue(environment::azure_app_services_cli_telemetry_profile_value);
if (cli_telemetry_profile_value == WStr("AzureKudu"))
{
Logger::Info("Profiler disabled: ", app_pool_id_value,
" is recognized as Kudu, an Azure App Services reserved process.");
FailProfiler(Info, "Profiler disabled: - Kudu, an Azure App Services reserved process.")
}
}
auto work_offloader = std::make_shared<RejitWorkOffloader>(this->info_);
rejit_handler = info12 != nullptr ? std::make_shared<RejitHandler>(info12, work_offloader)
: std::make_shared<RejitHandler>(this->info_, work_offloader);
tracer_integration_preprocessor = std::make_unique<TracerRejitPreprocessor>(rejit_handler, work_offloader);
DWORD event_mask = 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;
#ifdef _WIN32
if (runtime_information_.is_desktop())
{
// Only on .NET Framework callbacks for JIT compilation are needed.
event_mask |= COR_PRF_MONITOR_JIT_COMPILATION;
}
#endif
if (!EnableInlining())
{
Logger::Info("JIT Inlining is disabled.");
event_mask |= COR_PRF_DISABLE_INLINING;
}
else
{
Logger::Info("JIT Inlining is enabled.");
}
if (DisableOptimizations())
{
Logger::Info("Disabling all code optimizations.");
event_mask |= COR_PRF_DISABLE_OPTIMIZATIONS;
}
if (IsNGENEnabled())
{
Logger::Info("NGEN is enabled.");
event_mask |= COR_PRF_MONITOR_CACHE_SEARCHES;
}
else
{
Logger::Info("NGEN is disabled.");
event_mask |= COR_PRF_DISABLE_ALL_NGEN_IMAGES;
}
// set event mask to subscribe to events and disable NGEN images
hr = this->info_->SetEventMask2(event_mask, COR_PRF_HIGH_ADD_ASSEMBLY_REFERENCES);
if (FAILED(hr))
{
FailProfiler(Warn, "Failed to attach profiler: unable to set event mask.")
}
runtime_information_ = GetRuntimeInformation(this->info_);
if (process_name == WStr("w3wp.exe") || process_name == WStr("iisexpress.exe"))
{
is_desktop_iis = runtime_information_.is_desktop();
}
// writing opcodes vector for the IL dumper
if (IsDumpILRewriteEnabled())
{
#define OPDEF(c, s, pop, push, args, type, l, s1, s2, flow) opcodes_names.push_back(s);
#include "opcode.def"
#undef OPDEF
opcodes_names.push_back("(count)"); // CEE_COUNT
opcodes_names.push_back("->"); // CEE_SWITCH_ARG
}
managed_profiler_assembly_reference = AssemblyReference::GetFromCache(GetBytecodeInstrumentationAssembly());
const auto currentModuleFileName = GetCurrentModuleFileName();
if (currentModuleFileName == EmptyWStr)
{
FailProfiler(Error, "Profiler filepath: cannot be calculated.")
}
// we're in!
Logger::Info("Profiler filepath: ", currentModuleFileName);
Logger::Info("Profiler attached.");
this->info_->AddRef();
is_attached_.store(true);
profiler = this;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfiler::AssemblyLoadFinished(AssemblyID assembly_id, HRESULT hr_status)
{
auto _ = trace::Stats::Instance()->AssemblyLoadFinishedMeasure();
if (FAILED(hr_status))
{
// if assembly failed to load, skip it entirely,
// otherwise we can crash the process if module is not valid
Logger::Warn("AssemblyLoadFinished: ", assembly_id, " ", hr_status);
CorProfilerBase::AssemblyLoadFinished(assembly_id, hr_status);
return S_OK;
}
if (Logger::IsDebugEnabled())
{
Logger::Debug("AssemblyLoadFinished: ", assembly_id, " ", hr_status);
}
// double check if is_attached_ has changed to avoid possible race condition with shutdown function
if (!is_attached_)
{
return S_OK;
}
const auto& assembly_info = GetAssemblyInfo(this->info_, assembly_id);
if (!assembly_info.IsValid())
{
return S_OK;
}
const auto& is_instrumentation_assembly = assembly_info.name == managed_profiler_name;
if (is_instrumentation_assembly)
{
if (Logger::IsDebugEnabled())
{
Logger::Debug("AssemblyLoadFinished: Bytecode Instrumentation Assembly: ",
GetBytecodeInstrumentationAssembly());
}
ComPtr<IUnknown> metadata_interfaces;
auto hr = this->info_->GetModuleMetaData(assembly_info.manifest_module_id, ofRead | ofWrite,
IID_IMetaDataImport2, metadata_interfaces.GetAddressOf());
if (FAILED(hr))
{
Logger::Warn("AssemblyLoadFinished failed to get metadata interface for module id ",
assembly_info.manifest_module_id, " from assembly ", assembly_info.name);
return S_OK;
}
// Get the IMetaDataAssemblyImport interface to get metadata from the managed assembly
const auto& assembly_import = metadata_interfaces.As<IMetaDataAssemblyImport>(IID_IMetaDataAssemblyImport);
const auto& assembly_metadata = GetAssemblyImportMetadata(assembly_import);
managed_profiler_loaded_app_domains.insert(assembly_info.app_domain_id);
if (runtime_information_.is_desktop() && corlib_module_loaded)
{
// Set the managed_profiler_loaded_domain_neutral flag whenever the
// managed profiler is loaded shared
if (assembly_info.app_domain_id == corlib_app_domain_id)
{
Logger::Info("AssemblyLoadFinished: ", assembly_info.name, " was loaded domain-neutral");
managed_profiler_loaded_domain_neutral = true;
}
else
{
Logger::Info("AssemblyLoadFinished: ", assembly_info.name, " was not loaded domain-neutral");
}
}
}
return S_OK;
}
#ifdef _WIN32
void CorProfiler::RedirectAssemblyReferences(const ComPtr<IMetaDataAssemblyImport>& assembly_import,
const ComPtr<IMetaDataAssemblyEmit>& assembly_emit)
{
HRESULT hr = S_FALSE;
HCORENUM core_enum_handle = NULL;
const ULONG assembly_refs_sz = 16;
mdAssemblyRef assembly_refs[assembly_refs_sz];
ULONG assembly_refs_count;
// Inspect all assembly references and make any necessary redirects.
while (true)
{
hr = assembly_import.Get()->EnumAssemblyRefs(&core_enum_handle, assembly_refs, assembly_refs_sz,
&assembly_refs_count);
if (hr == S_FALSE)
{
// This is expected when the enumeration finished.
Logger::Debug("RedirectAssemblyReferences: EnumAssemblyRefs returned S_FALSE assembly_refs_count=",
assembly_refs_count);
break;
}
// Loop and process each AssemblyRef
for (ULONG i = 0; i < assembly_refs_count; i++)
{
const void* public_key_or_token;
ULONG public_key_or_token_sz;
WCHAR name[kNameMaxSize];
ULONG name_len = 0;
ASSEMBLYMETADATA assembly_metadata{};
const void* hash_value;
ULONG hash_value_sz;
DWORD assembly_flags = 0;
hr = assembly_import->GetAssemblyRefProps(assembly_refs[i], &public_key_or_token, &public_key_or_token_sz,
name, kNameMaxSize, &name_len, &assembly_metadata, &hash_value,
&hash_value_sz, &assembly_flags);
if (FAILED(hr) || name_len == 0)
{
Logger::Warn("RedirectAssemblyReferences: GetAssemblyRefProps failed HRESULT=", HResultStr(hr));
continue;
}
const auto wsz_name = WSTRING(name);
if (Logger::IsDebugEnabled())
{
Logger::Debug("RedirectAssemblyReferences: AssemblyRef for [", wsz_name, "] version=",
AssemblyVersionStr(assembly_metadata));
}
const auto found_redirect = assembly_version_redirect_map_.find(wsz_name);
if (found_redirect == assembly_version_redirect_map_.end())
{
// No redirection to be applied here.
continue;
}
AssemblyVersionRedirection& redirect = found_redirect->second;
auto version_comparison = redirect.CompareToAssemblyVersion(assembly_metadata);
if (version_comparison > 0)
{
// Redirection was a higher version, let's proceed with the redirection
Logger::Info("RedirectAssemblyReferences: redirecting [", wsz_name, "] from_version=",
AssemblyVersionStr(assembly_metadata), " to_version=", redirect.VersionStr(),
" previous_redirects=", redirect.ulRedirectionCount);
assembly_metadata.usMajorVersion = redirect.usMajorVersion;
assembly_metadata.usMinorVersion = redirect.usMinorVersion;
assembly_metadata.usBuildNumber = redirect.usBuildNumber;
assembly_metadata.usRevisionNumber = redirect.usRevisionNumber;
hr = assembly_emit.Get()->SetAssemblyRefProps(assembly_refs[i], public_key_or_token,
public_key_or_token_sz, name, &assembly_metadata,
hash_value, hash_value_sz, assembly_flags);
if (hr != S_OK)
{
Logger::Warn("RedirectAssemblyReferences: redirection error: SetAssemblyRefProps HRESULT=",
HResultStr(hr));
}
else
{
redirect.ulRedirectionCount++;
}
}
else if (version_comparison == 0)
{
// No need to redirect since it is the same assembly version on the ref and on the map
if (Logger::IsDebugEnabled())
{
Logger::Debug("RedirectAssemblyReferences: same version for [", wsz_name, "] version=",
redirect.VersionStr(), " previous_redirects=", redirect.ulRedirectionCount);
}
}
else
{
// Redirection points to a lower version. If no redirection was done yet modify the map to
// point to the higher version. If redirection was already applied do not redirect and let
// the runtime handle it.
if (redirect.ulRedirectionCount == 0)
{
// Redirection was not applied yet use the higher version. Also increment the redirection
// count to indicate that this version was already used.
Logger::Info("RedirectAssemblyReferences: redirection update for [", wsz_name, "] to_version=",
AssemblyVersionStr(assembly_metadata), " previous_version_redirection=",
redirect.VersionStr());
redirect.usMajorVersion = assembly_metadata.usMajorVersion;
redirect.usMinorVersion = assembly_metadata.usMinorVersion;
redirect.usBuildNumber = assembly_metadata.usBuildNumber;
redirect.usRevisionNumber = assembly_metadata.usRevisionNumber;
redirect.ulRedirectionCount++;
}
else
{
// This is risky: we aren't sure if the reference will be actually be used during the runtime.
// So it is possible that nothing will happen but we can't be sure. Using higher versions on
// the OpenTelemetry.AutoInstrumentation dependencies minimizes the chances of hitting this code
// path.
Logger::Error("RedirectAssemblyReferences: AssemblyRef [", wsz_name, "] version=",
AssemblyVersionStr(assembly_metadata),
" has a higher version than an earlier applied redirection to version=",
redirect.VersionStr());
}
}
}
}
}
#endif
void CorProfiler::RewritingPInvokeMaps(const ModuleMetadata& module_metadata, const WSTRING& nativemethods_type_name)
{
HRESULT hr;
const auto& metadata_import = module_metadata.metadata_import;
const auto& metadata_emit = module_metadata.metadata_emit;
// We are in the right module, so we try to load the mdTypeDef from the target type name.
mdTypeDef nativeMethodsTypeDef = mdTypeDefNil;
auto foundType =
FindTypeDefByName(nativemethods_type_name, module_metadata.assemblyName, metadata_import, nativeMethodsTypeDef);
if (foundType)
{
// Define the actual profiler file path as a ModuleRef
WSTRING native_profiler_file = GetCurrentModuleFileName();
Logger::Info("Rewriting PInvokes to native: ", native_profiler_file);
mdModuleRef profiler_ref;
hr = metadata_emit->DefineModuleRef(native_profiler_file.c_str(), &profiler_ref);
if (SUCCEEDED(hr))
{
// Enumerate all methods inside the native methods type with the PInvokes
Enumerator<mdMethodDef> enumMethods = Enumerator<mdMethodDef>(
[metadata_import, nativeMethodsTypeDef](HCORENUM* ptr, mdMethodDef arr[], ULONG max, ULONG* cnt)
-> HRESULT { return metadata_import->EnumMethods(ptr, nativeMethodsTypeDef, arr, max, cnt); },
[metadata_import](HCORENUM ptr) -> void { metadata_import->CloseEnum(ptr); });
EnumeratorIterator<mdMethodDef> enumIterator = enumMethods.begin();
while (enumIterator != enumMethods.end())
{
auto methodDef = *enumIterator;
const auto& caller = GetFunctionInfo(module_metadata.metadata_import, methodDef);
Logger::Info("Rewriting pinvoke for: ", caller.name);
// Get the current PInvoke map to extract the flags and the entrypoint name
DWORD pdwMappingFlags;
WCHAR importName[kNameMaxSize]{};
DWORD importNameLength = 0;
mdModuleRef importModule;
hr = metadata_import->GetPinvokeMap(methodDef, &pdwMappingFlags, importName, kNameMaxSize,
&importNameLength, &importModule);
if (SUCCEEDED(hr))
{
// Delete the current PInvoke map
hr = metadata_emit->DeletePinvokeMap(methodDef);
if (SUCCEEDED(hr))
{
// Define a new PInvoke map with the new ModuleRef of the actual profiler file path
hr = metadata_emit->DefinePinvokeMap(methodDef, pdwMappingFlags, WSTRING(importName).c_str(),
profiler_ref);
if (FAILED(hr))
{
Logger::Warn("RewritingPInvokeMaps: DefinePinvokeMap to the actual profiler file path "
"failed, trying to restore the previous one.");
hr = metadata_emit->DefinePinvokeMap(methodDef, pdwMappingFlags,
WSTRING(importName).c_str(), importModule);
if (FAILED(hr))
{
// We only warn that we cannot rewrite the PInvokeMap but we still continue the module
// load.
// These errors must be handled on the caller with a try/catch.
Logger::Warn("RewritingPInvokeMaps: Error trying to restore the previous PInvokeMap.");
}
}
}
else
{
// We only warn that we cannot rewrite the PInvokeMap but we still continue the module load.
// These errors must be handled on the caller with a try/catch.
Logger::Warn("RewritingPInvokeMaps: DeletePinvokeMap failed");
}
}
enumIterator = ++enumIterator;
}
}
else
{
// We only warn that we cannot rewrite the PInvokeMap but we still continue the module load.
// These errors must be handled on the caller with a try/catch.
Logger::Warn("RewritingPInvokeMaps: Native Profiler DefineModuleRef failed");
}
}
}
HRESULT STDMETHODCALLTYPE CorProfiler::ModuleLoadFinished(ModuleID module_id, HRESULT hr_status)
{
auto _ = trace::Stats::Instance()->ModuleLoadFinishedMeasure();
if (FAILED(hr_status))
{
// if module failed to load, skip it entirely,
// otherwise we can crash the process if module is not valid
CorProfilerBase::ModuleLoadFinished(module_id, hr_status);
return S_OK;
}
if (!is_attached_)
{
return S_OK;
}
// keep this lock until we are done using the module,
// to prevent it from unloading while in use
std::lock_guard<std::mutex> guard(module_ids_lock_);
// double check if is_attached_ has changed to avoid possible race condition with shutdown function
if (!is_attached_ || rejit_handler == nullptr)
{
return S_OK;
}
const auto& module_info = GetModuleInfo(this->info_, module_id);
if (!module_info.IsValid())
{
return S_OK;
}
if (Logger::IsDebugEnabled())
{
Logger::Debug("ModuleLoadFinished: ", module_id, " ", module_info.assembly.name, " AppDomain ",
module_info.assembly.app_domain_id, " [", module_info.assembly.app_domain_name, "] ",
std::boolalpha, " | IsNGEN = ", module_info.IsNGEN(), " | IsDynamic = ", module_info.IsDynamic(),
" | IsResource = ", module_info.IsResource(), std::noboolalpha);
}
if (module_info.IsNGEN())
{
// We check if the Module contains NGEN images and added to the
// rejit handler list to verify the inlines.
rejit_handler->AddNGenInlinerModule(module_id);
}
AppDomainID app_domain_id = module_info.assembly.app_domain_id;
// Identify the AppDomain ID of mscorlib which will be the Shared Domain
// because mscorlib is always a domain-neutral assembly
if (!corlib_module_loaded && (module_info.assembly.name == mscorlib_assemblyName ||
module_info.assembly.name == system_private_corelib_assemblyName))
{
corlib_module_loaded = true;
corlib_app_domain_id = app_domain_id;
ComPtr<IUnknown> metadata_interfaces;
auto hr = this->info_->GetModuleMetaData(module_id, ofRead | ofWrite, IID_IMetaDataImport2,
metadata_interfaces.GetAddressOf());
// Get the IMetaDataAssemblyImport interface to get metadata from the
// managed assembly
const auto& assembly_import = metadata_interfaces.As<IMetaDataAssemblyImport>(IID_IMetaDataAssemblyImport);
const auto& assembly_metadata = GetAssemblyImportMetadata(assembly_import);
hr = assembly_import->GetAssemblyProps(assembly_metadata.assembly_token, &corAssemblyProperty.ppbPublicKey,
&corAssemblyProperty.pcbPublicKey, &corAssemblyProperty.pulHashAlgId,
NULL, 0, NULL, &corAssemblyProperty.pMetaData,
&corAssemblyProperty.assemblyFlags);
if (FAILED(hr))
{
Logger::Warn("AssemblyLoadFinished failed to get properties for COR assembly ");
}
corAssemblyProperty.szName = module_info.assembly.name;
Logger::Info("COR library: ", corAssemblyProperty.szName, " ", corAssemblyProperty.pMetaData.usMajorVersion,
".", corAssemblyProperty.pMetaData.usMinorVersion, ".",
corAssemblyProperty.pMetaData.usRevisionNumber);
if (rejit_handler != nullptr)
{
rejit_handler->SetCorAssemblyProfiler(&corAssemblyProperty);
}
return S_OK;
}
// In IIS, the OpenTelemetry.AutoInstrumentation will be inserted into a method in System.Web (which is
// domain-neutral)
// but the OpenTelemetry.AutoInstrumentation.Loader assembly that the CLR profiler loads from a
// byte array will be loaded into a non-shared AppDomain.
// In this case, do not insert another Loader into that non-shared AppDomain
if (module_info.assembly.name == opentelemetry_autoinstrumentation_loader_assemblyName)
{
Logger::Info("ModuleLoadFinished: OpenTelemetry.AutoInstrumentation.Loader loaded into AppDomain ",
app_domain_id, " [", module_info.assembly.app_domain_name, "]");
first_jit_compilation_app_domains.insert(app_domain_id);
return S_OK;
}
if (module_info.IsWindowsRuntime())
{
// We cannot obtain writable metadata interfaces on Windows Runtime modules
// or instrument their IL.
Logger::Debug("ModuleLoadFinished skipping Windows Metadata module: ", module_id, " ",
module_info.assembly.name);
return S_OK;
}
if (module_info.IsResource())
{
// We don't need to load metadata on resources modules.
Logger::Debug("ModuleLoadFinished skipping Resources module: ", module_id, " ", module_info.assembly.name);
return S_OK;
}
if (module_info.IsDynamic())
{
// For CallTarget we don't need to load metadata on dynamic modules.
Logger::Debug("ModuleLoadFinished skipping Dynamic module: ", module_id, " ", module_info.assembly.name);
return S_OK;
}
// It is not safe to skip assemblies if applying redirection on .NET Framework
if (!runtime_information_.is_desktop() || !IsNetFxAssemblyRedirectionEnabled())
{
// Not .NET Framework or assembly redirection is disabled, check if the
// assembly can be skipped.
for (auto&& skip_assembly : skip_assemblies)
{
if (module_info.assembly.name == skip_assembly)
{
Logger::Debug("ModuleLoadFinished skipping known module: ", module_id, " ", module_info.assembly.name);
return S_OK;
}
}
for (auto&& skip_assembly_pattern : skip_assembly_prefixes)
{
if (module_info.assembly.name.rfind(skip_assembly_pattern, 0) == 0)
{
Logger::Debug("ModuleLoadFinished skipping module by pattern: ", module_id, " ",
module_info.assembly.name);
return S_OK;
}
}
}
#ifdef _WIN32
const bool perform_netfx_redirect = runtime_information_.is_desktop() && IsNetFxAssemblyRedirectionEnabled();
#else
const bool perform_netfx_redirect = false;
#endif // _WIN32
if (perform_netfx_redirect || module_info.assembly.name == managed_profiler_name)
{
ComPtr<IUnknown> metadata_interfaces;
auto hr = this->info_->GetModuleMetaData(module_id, ofRead | ofWrite, IID_IMetaDataImport2,
metadata_interfaces.GetAddressOf());
if (FAILED(hr))
{
Logger::Warn("ModuleLoadFinished failed to get metadata interface for ", module_id, " ",
module_info.assembly.name);
return S_OK;
}
const auto& metadata_import = metadata_interfaces.As<IMetaDataImport2>(IID_IMetaDataImport);
const auto& metadata_emit = metadata_interfaces.As<IMetaDataEmit2>(IID_IMetaDataEmit);
const auto& assembly_import = metadata_interfaces.As<IMetaDataAssemblyImport>(IID_IMetaDataAssemblyImport);
const auto& assembly_emit = metadata_interfaces.As<IMetaDataAssemblyEmit>(IID_IMetaDataAssemblyEmit);
const auto& module_metadata =
ModuleMetadata(metadata_import, metadata_emit, assembly_import, assembly_emit, module_info.assembly.name,
module_info.assembly.app_domain_id, &corAssemblyProperty);
#ifdef _WIN32
if (perform_netfx_redirect)
{
// On the .NET Framework redirect any assembly reference to the versions required by
// OpenTelemetry.AutoInstrumentation assembly, the ones under netfx/ folder.
RedirectAssemblyReferences(assembly_import, assembly_emit);
}
#endif // _WIN32
if (module_info.assembly.name == managed_profiler_name)
{
#ifdef _WIN32
RewritingPInvokeMaps(module_metadata, windows_nativemethods_type);
#else
RewritingPInvokeMaps(module_metadata, nonwindows_nativemethods_type);
#endif // _WIN32
}
if (Logger::IsDebugEnabled())
{
const auto& assemblyImport = GetAssemblyImportMetadata(assembly_import);
const auto& assemblyVersion = assemblyImport.version.str();
Logger::Debug("ModuleLoadFinished: done ", module_info.assembly.name, " v", assemblyVersion);
}
}
if (module_info.assembly.name != managed_profiler_name)
{
module_ids_.push_back(module_id);
// We call the function to analyze the module and request the ReJIT of integrations defined in this module.
if (tracer_integration_preprocessor != nullptr && !integration_definitions_.empty())
{
std::promise<ULONG> promise;
std::future<ULONG> future = promise.get_future();
tracer_integration_preprocessor->EnqueueRequestRejitForLoadedModules(std::vector<ModuleID>{module_id},
integration_definitions_, &promise);
// wait and get the value from the future<ULONG>
const auto status = future.wait_for(100ms);
if (status != std::future_status::timeout)
{
const auto& numReJITs = future.get();
Logger::Debug("Total number of ReJIT Requested: ", numReJITs);
}
else
{
Logger::Warn("Timeout while waiting for the rejit requests to be processed. Rejit will continue "
"asynchronously, but some initial calls may not be instrumented");
}
}
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfiler::ModuleUnloadStarted(ModuleID module_id)
{
auto _ = trace::Stats::Instance()->ModuleUnloadStartedMeasure();
if (!is_attached_)
{
return S_OK;
}
if (Logger::IsDebugEnabled())
{
const auto module_info = GetModuleInfo(this->info_, module_id);
if (module_info.IsValid())
{
Logger::Debug("ModuleUnloadStarted: ", module_id, " ", module_info.assembly.name, " AppDomain ",
module_info.assembly.app_domain_id, " [", module_info.assembly.app_domain_name, "]");
}
else
{
Logger::Debug("ModuleUnloadStarted: ", module_id);
}
}
// take this lock so we block until the
// module metadata is not longer being used
std::lock_guard<std::mutex> guard(module_ids_lock_);
// double check if is_attached_ has changed to avoid possible race condition with shutdown function
if (!is_attached_)
{
return S_OK;
}
const auto& moduleInfo = GetModuleInfo(this->info_, module_id);
if (moduleInfo.IsValid())
{
if (Logger::IsDebugEnabled())
{
Logger::Debug("ModuleUnloadStarted: ", module_id, " ", moduleInfo.assembly.name, " AppDomain ",
moduleInfo.assembly.app_domain_id, " ", moduleInfo.assembly.app_domain_name);
}
}
else
{
Logger::Debug("ModuleUnloadStarted: ", module_id);
return S_OK;
}
const auto is_instrumentation_assembly = moduleInfo.assembly.name == managed_profiler_name;
if (is_instrumentation_assembly)
{
const auto appDomainId = moduleInfo.assembly.app_domain_id;
// remove appdomain id from managed_profiler_loaded_app_domains set
if (managed_profiler_loaded_app_domains.find(appDomainId) != managed_profiler_loaded_app_domains.end())
{
managed_profiler_loaded_app_domains.erase(appDomainId);
}
}
if (rejit_handler != nullptr)
{
rejit_handler->RemoveModule(module_id);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfiler::Shutdown()
{
is_attached_.store(false);
CorProfilerBase::Shutdown();
// keep this lock until we are done using the module,
// to prevent it from unloading while in use
std::lock_guard<std::mutex> guard(module_ids_lock_);
if (rejit_handler != nullptr)
{
rejit_handler->Shutdown();
rejit_handler = nullptr;
}
Logger::Info("Exiting...");
Logger::Debug(" ModuleIds: ", module_ids_.size());
Logger::Debug(" IntegrationDefinitions: ", integration_definitions_.size());
Logger::Debug(" DefinitionsIds: ", definitions_ids_.size());
Logger::Debug(" ManagedProfilerLoadedAppDomains: ", managed_profiler_loaded_app_domains.size());
Logger::Debug(" FirstJitCompilationAppDomains: ", first_jit_compilation_app_domains.size());
Logger::Info("Stats: ", Stats::Instance()->ToString());
Logger::Shutdown();
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfiler::ProfilerDetachSucceeded()
{
if (!is_attached_)
{
return S_OK;
}
CorProfilerBase::ProfilerDetachSucceeded();
// keep this lock until we are done using the module,
// to prevent it from unloading while in use
std::lock_guard<std::mutex> guard(module_ids_lock_);
// double check if is_attached_ has changed to avoid possible race condition with shutdown function
if (!is_attached_)
{
return S_OK;
}
Logger::Info("Detaching profiler.");
Logger::Flush();
is_attached_.store(false);
return S_OK;
}
#ifdef _WIN32
// JITCompilationStarted is only called for .NET Framework. It is used to inject the Loader
// into the application.
HRESULT STDMETHODCALLTYPE CorProfiler::JITCompilationStarted(FunctionID function_id, BOOL is_safe_to_block)
{
auto _ = trace::Stats::Instance()->JITCompilationStartedMeasure();
// The flag for this callback is only set if runtime_information_.is_desktop() is true.
// So there is no need to check it again here.
if (is_attached_ && is_safe_to_block)
{
// The JIT compilation only needs to be tracked on the .NET Framework so the Loader
// can be injected. For .NET the DOTNET_STARTUP_HOOK takes care of injecting the
// instrumentation startup code.
return JITCompilationStartedOnNetFramework(function_id, is_safe_to_block);
}
return S_OK;
}
#endif
HRESULT STDMETHODCALLTYPE CorProfiler::AppDomainShutdownFinished(AppDomainID appDomainId, HRESULT hrStatus)
{
if (!is_attached_)
{
return S_OK;
}
// take this lock so we block until the
// module metadata is not longer being used
std::lock_guard<std::mutex> guard(module_ids_lock_);
// double check if is_attached_ has changed to avoid possible race condition with shutdown function
if (!is_attached_)
{
return S_OK;
}
// remove appdomain metadata from map
const auto& count = first_jit_compilation_app_domains.erase(appDomainId);
Logger::Debug("AppDomainShutdownFinished: AppDomain: ", appDomainId, ", removed ", count, " elements");
return S_OK;
}
HRESULT STDMETHODCALLTYPE CorProfiler::JITInlining(FunctionID callerId, FunctionID calleeId, BOOL* pfShouldInline)
{
auto _ = trace::Stats::Instance()->JITInliningMeasure();
if (!is_attached_ || rejit_handler == nullptr)
{
return S_OK;
}
ModuleID calleeModuleId;
mdToken calleFunctionToken = mdTokenNil;
auto hr = this->info_->GetFunctionInfo(calleeId, nullptr, &calleeModuleId, &calleFunctionToken);
*pfShouldInline = true;
if (FAILED(hr))
{
Logger::Warn("*** JITInlining: Failed to get the function info of the calleId: ", calleeId);