ICorProfilerInfo7::ApplyMetaData on a ReadyToRun module makes later ReadyToRun fixups decode the wrong module (stack overflow at startup on .NET 11 when applied to System.Private.CoreLib)
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức phù hợp với người mới
- 42/100
Hướng nghiên cứu
Start by reading src/coreclr/vm/ceeload.cpp, src/coreclr/vm/ceeload.h, and the module-index decoding in src/coreclr/vm/zapsig.cpp, then trace the startup path in src/coreclr/vm/jitinterface.cpp. Reproduce with the provided profiler and System.Console.dll on .NET 11, confirming that ApplyMetaData causes the ReadyToRun startup failure. Done means the module boundary no longer changes after metadata application and a regression test proves ReadyToRun fixups still decode the correct module.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
AI disclosure. I used AI tools to read the runtime source, to write the repro profiler and the image scan, to run the experiments and to draft this report.
Description
We maintain a CLR profiler. It adds types and members to modules with IMetaDataEmit::Define* and then calls ICorProfilerInfo7::ApplyMetaData.
On .NET 11.0.0 the process crashes at startup when the profiler calls ApplyMetaData on System.Private.CoreLib while CoreLib's ReadyToRun code is in use. The crash is a stack overflow. The stack shows BadImageFormatException..ctor again and again. The metadata content does not matter. One ApplyMetaData call after one empty DefineTypeDef is enough. One ApplyMetaData call with no edit at all is also enough.
The same profiler works on .NET 9 and .NET 10. The runtime code at fault is the same in 9, 10 and 11. The difference is in the ReadyToRun images that ship with 11.0.0 (details below).
Runtime: 11.0.0 (tag v11.0.0), osx-arm64. The code paths below are not platform-specific.
Root cause
-
Module::ApplyMetaDataalways makes sure that the AssemblyRef-to-Module map can store the row after the last AssemblyRef row:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/ceeload.cpp#L661-L663ulCount = GetMDImport()->GetCountWithTokenKind(mdtAssemblyRef) + 1; EnsureAssemblyRefCanBeStored(TokenFromRid(ulCount, mdtAssemblyRef)); -
At load, the map has exactly
AssemblyRefCount + 1slots:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/ceeload.cpp#L1393-L1394So the first
ApplyMetaDatacall on any module always grows the map.LookupMapBase::GrowMapadds a block of at least 32 slots:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/ceeload.cpp#L2659-L2686 -
Module::GetAssemblyRefMax()returns the map size minus one:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/ceeload.h#L1367 -
ZapSig::DecodeModuleFromIndexandZapSig::DecodeModuleFromIndexIfLoadeduseGetAssemblyRefMax()as the end of the module's own AssemblyRef rows. An index above that value selects the native manifest module (R2R 6.3 and later) or an AssemblyRef row of the manifest metadata:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/zapsig.cpp#L574-L621
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/zapsig.cpp#L640-L665The ReadyToRun compiler encodes these indices relative to the AssemblyRef count of the original IL image. After step 2 the runtime uses a different, larger boundary. Every module index in the range (N, N+32] is then read as an IL AssemblyRef row that does not exist, where N is the original AssemblyRef count. An index above N+32 selects the wrong manifest AssemblyRef.
-
CoreLib has 0 AssemblyRefs. Index 1 means the native manifest module. After
ApplyMetaData, index 1 is decoded as AssemblyRef row 1 of CoreLib.PEAssembly::LoadAssemblythrowsCOR_E_BADIMAGEFORMAT. -
The 11.0.0 CoreLib image has an import cell with this form: a
READYTORUN_FIXUP_StringHandle(0x1b) withREADYTORUN_FIXUP_ModuleOverrideand module index 1. The string comes from the user-string heap of the manifest metadata. In our trace, the first decode of that cell is underReadyToRunInfo::GetEntryPoint->FixupDelayList->LoadDynamicInfoEntry(duringAppContext.Setup):
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/jitinterface.cpp#L14365-L14369The constructor of
BadImageFormatExceptionloads a resource string. That path needs a CoreLib method that has the same kind of fixup, so the throw repeats until the stack overflows.
All other callers of Module::GetModuleFromIndex / GetModuleFromIndexIfLoaded get the same wrong result after ApplyMetaData. These callers include method signatures with ENCODE_METHOD_SIG_UpdateContext, type signatures with ELEMENT_TYPE_MODULE_ZAPSIG, generic dictionary lookups, cross-module inlining info, and the #:<index> module references of the manifest metadata.
Why 11.0.0 and not 9 or 10
We parsed every import cell signature of the shared framework images, including nested signatures. We counted module indices above the image's own AssemblyRef count:
| Framework | ReadyToRun images | Images with such indices | CoreLib |
|---|---|---|---|
| 9.0.2 | 89 | 0 | 0 cells |
| 10.0.11 | 92 | 0 | 0 cells |
| 11.0.0 | 101 | 58 | 1 cell (StringHandle, module index 1) |
On 9 and 10 the bug is latent. It also affects 9 and 10 when an image has such indices, for example an application compiled with a larger version bubble or cross-module inlining.
In 11.0.0, the manifest metadata of CoreLib has TypeRefs to System.Runtime.CompilerServices.AsyncHelpers, RuntimeAsyncAwaitState and ResumeInfo. So we think that the new indices come from code that the compiler generates for runtime async. We did not confirm this.
Minimal repro
- Write a CLR profiler that does only this:
- In
Initialize: queryICorProfilerInfo7and callSetEventMask(COR_PRF_MONITOR_MODULE_LOADS). - In
ModuleLoadFinishedforSystem.Private.CoreLib: callGetModuleMetaData(ofWrite, IID_IMetaDataEmit). CallDefineTypeDef("Repro.Empty", tdPublic | tdInterface | tdAbstract, mdTokenNil, NULL, &td). Then callApplyMetaData(moduleId).
- In
- Keep ReadyToRun on (the default). Run any application on the 11.0.0 shared framework with
CORECLR_ENABLE_PROFILING=1. - Controls:
- Remove only the
ApplyMetaDatacall. The application starts. - Run the same profiler on 10.0.11. The application starts.
- In our tests with a larger profiler,
DOTNET_ReadyToRun=0andDOTNET_ReadyToRunExcludeList=System.Private.CoreLibalso remove the crash.
- Remove only the
We ran this profiler (about 80 lines of C, in the section below) with System.Console.dll of the framework as the application. That file has no entry point, so a normal start ends with "Entry point not found":
| Runtime | Profiler action | Result |
|---|---|---|
| 11.0.0 | DefineTypeDef + ApplyMetaData | ApplyMetaData = S_OK, then "Stack overflow." |
| 11.0.0 | DefineTypeDef only | normal start |
| 10.0.11 | DefineTypeDef + ApplyMetaData | normal start |
Repro profiler
minprof.c (macOS build line in the header; the same code builds as a .so on Linux)
/* Minimal CLR profiler for an upstream bug report.
* In ModuleLoadFinished of System.Private.CoreLib: DefineTypeDef of an empty interface, then
* (REPRO_MODE=define-apply) ApplyMetaData. Build: clang -shared -o libminprof.dylib minprof.c */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int32_t HRESULT;
typedef struct { uint32_t a; uint16_t b, c; uint8_t d[8]; } GUID;
typedef void *(*fn)(void);
static const GUID IID_IUnknown = {0, 0, 0, {0xC0, 0, 0, 0, 0, 0, 0, 0x46}};
static const GUID IID_IClassFactory = {1, 0, 0, {0xC0, 0, 0, 0, 0, 0, 0, 0x46}};
static const GUID IID_Info7 = {0x9AEECC0D, 0x63E0, 0x4187, {0x8C, 0x00, 0xE3, 0x12, 0xF5, 0x03, 0xF6, 0x63}};
static const GUID IID_Emit = {0xba3fee4c, 0xecb9, 0x4e41, {0x83, 0xb7, 0x18, 0x3f, 0xa4, 0x1c, 0xd8, 0x59}};
static void **info; /* ICorProfilerInfo7* */
static int done;
static HRESULT ok(void) { return 0; }
static HRESULT qi(void *self, const GUID *iid, void **out) { *out = self; return 0; }
static uint32_t addref(void *self) { return 1; }
static HRESULT cb_initialize(void *self, void **unk) {
HRESULT (*q)(void *, const GUID *, void **) = (void *)((void **)*unk)[0];
HRESULT hr = q(unk, &IID_Info7, (void **)&info);
fprintf(stderr, "minprof: QI(ICorProfilerInfo7)=0x%08x\n", hr);
if (hr < 0) return hr;
HRESULT (*set_mask)(void *, uint32_t) = (void *)((void **)*info)[16];
hr = set_mask(info, 0x4 /* COR_PRF_MONITOR_MODULE_LOADS */);
fprintf(stderr, "minprof: SetEventMask=0x%08x\n", hr);
return 0;
}
static HRESULT cb_module_load_finished(void *self, uintptr_t module, HRESULT status) {
if (done) return 0;
uint16_t name[512]; uint32_t len = 0; const void *base; uintptr_t asm_id;
HRESULT (*get_info)(void *, uintptr_t, const void **, uint32_t, uint32_t *, uint16_t *, uintptr_t *) =
(void *)((void **)*info)[20];
if (get_info(info, module, &base, 512, &len, name, &asm_id) < 0) return 0;
char ascii[512]; uint32_t i;
for (i = 0; i < len && i < 511 && name[i]; i++) ascii[i] = (char)name[i];
ascii[i] = 0;
if (!strstr(ascii, "System.Private.CoreLib.dll")) return 0;
done = 1;
const char *mode = getenv("REPRO_MODE");
if (!mode) mode = "define-apply";
void **emit = NULL;
HRESULT (*get_md)(void *, uintptr_t, uint32_t, const GUID *, void ***) = (void *)((void **)*info)[21];
HRESULT hr = get_md(info, module, 0x1 /* ofWrite */, &IID_Emit, &emit);
fprintf(stderr, "minprof: CoreLib GetModuleMetaData(ofWrite, IMetaDataEmit)=0x%08x mode=%s\n", hr, mode);
if (hr < 0) return 0;
static const uint16_t tname[] = {'R','e','p','r','o','.','E','m','p','t','y',0};
uint32_t td = 0;
HRESULT (*define_type)(void *, const uint16_t *, uint32_t, uint32_t, const uint32_t *, uint32_t *) =
(void *)((void **)*emit)[7];
hr = define_type(emit, tname, 0x1 | 0x20 | 0x80 /* public interface abstract */, 0, NULL, &td);
fprintf(stderr, "minprof: DefineTypeDef=0x%08x token=0x%08x\n", hr, td);
if (strcmp(mode, "define-apply") == 0) {
HRESULT (*apply)(void *, uintptr_t) = (void *)((void **)*info)[84];
hr = apply(info, module);
fprintf(stderr, "minprof: ApplyMetaData=0x%08x\n", hr);
}
return 0;
}
static fn callback_vtbl[128];
static void *callback_obj = callback_vtbl;
static HRESULT cf_create(void *self, void *outer, const GUID *iid, void **out) { *out = &callback_obj; return 0; }
static fn factory_vtbl[5] = {(fn)qi, (fn)addref, (fn)addref, (fn)cf_create, (fn)ok};
static void *factory_obj = factory_vtbl;
__attribute__((visibility("default"))) HRESULT DllGetClassObject(const GUID *clsid, const GUID *iid, void **out) {
for (int i = 0; i < 128; i++) callback_vtbl[i] = (fn)ok;
callback_vtbl[0] = (fn)qi;
callback_vtbl[1] = (fn)addref;
callback_vtbl[2] = (fn)addref;
callback_vtbl[3] = (fn)cb_initialize;
callback_vtbl[14] = (fn)cb_module_load_finished;
*out = &factory_obj;
return 0;
}
Expected behaviour
ApplyMetaData makes the new metadata usable. The documentation lists TypeDef records as supported since .NET Core 3.0. ReadyToRun code of the module continues to work.
Actual behaviour
ApplyMetaData returns S_OK. The next ReadyToRun fixup with a module index above the original AssemblyRef count throws BadImageFormatException. On CoreLib in 11.0.0 this happens at startup and ends in a stack overflow:
Stack overflow.
at System.Runtime.EH.DispatchEx(...)
at System.Runtime.EH.RhThrowEx(...)
at System.String.CreateStringFromEncoding(Byte*, Int32, System.Text.Encoding)
at System.RuntimeType+RuntimeTypeCache.GetNamespace()
...
at System.SR.GetResourceString(System.String)
at System.BadImageFormatException..ctor()
...
If the profiler also adds AssemblyRef rows to the module, an index in (N, N+32] can resolve to one of the new rows. Then the runtime uses the wrong module and no error is reported.
Suggested fix
Make the boundary in DecodeModuleFromIndex / DecodeModuleFromIndexIfLoaded independent of the map size. Examples:
- Store the AssemblyRef count of the image at module load. You can store it in
Moduleor inReadyToRunInfo. Use that count in both functions instead ofGetAssemblyRefMax(). The count must be the original count.GetCountWithTokenKind(mdtAssemblyRef)on the current metadata is also wrong after a profiler adds AssemblyRef rows. - Separately,
ApplyMetaDataasks for one slot more than it needs (count + 1where the largest RID iscount). If you remove the+ 1, the growth stops for a profiler that adds no AssemblyRef. This alone does not fix the case where the profiler adds AssemblyRef rows.
A test for the fix: a profiler test that calls ApplyMetaData on CoreLib in ModuleLoadFinished with ReadyToRun on. We did not find a test in src/tests/profiler that calls ApplyMetaData on a ReadyToRun module.
Related observation (possibly a separate issue)
Module::UpdateNewlyAddedTypes disables the ReadyToRun custom-attribute filter only when the available-class hash already exists:
https://github.com/dotnet/runtime/blob/v11.0.0/src/coreclr/vm/ceeload.cpp#L239-L265
On a fresh ReadyToRun module the hash does not exist. So the first call (from ApplyMetaData, or the one after ModuleLoadFinished) builds the hash and returns. It does not disable the filter. A well-known attribute that a profiler adds, for example SuppressGCTransitionAttribute, is then not seen by Module::GetCustomAttribute. "ReJIT on Attach.md" lists DefineCustomAttribute as legal with ApplyMetadata. A profiler can work around this only with a second ApplyMetaData call, and that call is where it hits the bug above.
- Ngôn ngữ chính
- C#
- Star
- 18.5k
- Fork
- 5.8k
- Merge trung bình
- 2 ngày 8 giờ
- Pull request đã merge (30 ngày)
- 597
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của dotnet/runtime
-
area-VM-meta-mono untriaged
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 75/100
Maintainer thường phản hồi trong vòng 1 ngày
-
area-Debugger-mono untriaged
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 75/100
dotnet/runtime#138494 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
area-AssemblyLoader-mono untriaged
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
dotnet/runtime#138493 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
JsonConsoleFormatter throws on NaN and infinite double and float values, failing the log callCó thể đã có người làm @Mohamedadel-prog đã nhận 1 ngày trước. Đang mởarea-Extensions-Logging untriaged
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 82/100
dotnet/runtime#138418 · 2 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
area-System.IO untriaged
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
dotnet/runtime#138417 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của dotnet/runtime
Issue tương tự
-
bug
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 76/100
juandresrodca/AdminForge#69 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Keep PublicAPI.Unshipped.txt sorted, with a guard, so concurrent API PRs stop conflicting on itĐang mởchore small tooling
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 79/100
BattletechModders/ModTek#256 · 1 bình luận ·
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 65/100
Facepunch/sbox-public#12484 ·
Maintainer thường phản hồi trong vòng 2 ngày
-
good first issue
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 62/100
Maintainer thường phản hồi trong vòng 1 ngày