Preface
Lying flat for a long time , I'm too lazy to move . This article is all about personal understanding , If there are any omissions , Please correct me. .
Wedge
Jin Yong's Wuxia Tianlong eight books , The supreme treasure of Shaolin Temple , The muscle changing Sutra, the internal skill secret collection that Wulin people dream of, was stolen by ah Zhu , But Shaolin Temple didn't send experts to look for , Why? ?
This is the supreme internal skill secret collection of Shaolin Temple , Ordinary Jianghu people simply can't understand . Unless a master with deep internal skills .
Let's see .Net It's an internal skill secret that you can't understand R2R principle .
Concept :
R2R In essence, compilation is to store the results of method operation in the binary dynamic link library , When calling this method , Get the result of the method directly from the dynamic link library . Without going through RyuJit Tedious compilation , Improve the performance of the program . It's a kind of AOT Pre compiled form of .
compile dotnet publish -c Release -r win-x64 -p:PublishReadyToRun=true
The whole process :
When CLI The command is marked PublishReadyToRun,Rosyln Recompiled dynamic links will generate Native Header, It saves the running results of the methods of the current module . Thereafter CLR When loading it ,CLR Will find in the dynamic link library Native Header Whether there is , If there is , When the caller , Get the result of this method directly .
Because the process is too complex, here is only an outline :
CLI(PublishReadyToRun:true)->Rosyln(Native Header) -> CLR (Get NH)
Precompiled storage structure
typedef struct _IMAGE_RUNTIME_FUNCTION_ENTRY {
DWORD BeginAddress;
DWORD EndAddress;
union {
DWORD UnwindInfoAddress;
DWORD UnwindData;
} DUMMYUNIONNAME;
} _IMAGE_RUNTIME_FUNCTION_ENTRY, *_PIMAGE_RUNTIME_FUNCTION_ENTRY;
The way it's made up :
A memory space will be allocated in the dynamic link library , be called Nativie Header. It stores the following contents :
1. Compiler identifier (CompilerIdentifier)
2. Import method segment (ImportSections)
3. Run time method (RuntimeFunctions)
4. Method entry point (MethodDefEntryPoints)
5. Abnormal information (ExceptionInfo)
6. Debugging information (DebugInfo)
7. Delaying method load calls is fast (DelayLoadMethodCallThunks)
Wait, a total of 18 Item information , Because these things are too complex, only the first few of them are listed here . Constitute the Native Header.
load R2R
CLR When loading a module , It initializes R2R, If it is judged that this module has Native Header, Then put the inside 18 Item information is added to memory . The code is as follows ( Too complicated , Omit most )
PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker *pamTracker)
{
// A million lines of code are omitted here
return new (pMemory) ReadyToRunInfo(pModule, pModule->GetLoaderAllocator(), pLayout, pHeader, nativeImage, pamTracker);
}
ReadyToRunInfo::ReadyToRunInfo(Module * pModule, LoaderAllocator* pLoaderAllocator, PEImageLayout * pLayout, READYTORUN_HEADER * pHeader, NativeImage *pNativeImage, AllocMemTracker *pamTracker)
: m_pModule(pModule),
m_pHeader(pHeader),
m_pNativeImage(pNativeImage),
m_readyToRunCodeDisabled(FALSE),
m_Crst(CrstReadyToRunEntryPointToMethodDescMap),
m_pPersistentInlineTrackingMap(NULL)
{
// pHeader It's in the dynamic link library native header, It contains Signature,MajorVersion,CoreHeader etc. .
STANDARD_VM_CONTRACT;
if (pNativeImage != NULL)
{
// Omit here
}
else
{
m_pCompositeInfo = this;
m_component = ReadyToRunCoreInfo(pLayout, &pHeader->CoreHeader);
m_pComposite = &m_component;
m_isComponentAssembly = false;
}
// Get runtime R2R Method's memory virtual address and length , Use the obtained index to get R2R Method entry address
IMAGE_DATA_DIRECTORY * pRuntimeFunctionsDir = m_pComposite->FindSection(ReadyToRunSectionType::RuntimeFunctions);
if (pRuntimeFunctionsDir != NULL)
{
m_pRuntimeFunctions = (T_RUNTIME_FUNCTION *)m_pComposite->GetLayout()->GetDirectoryData(pRuntimeFunctionsDir);
m_nRuntimeFunctions = pRuntimeFunctionsDir->Size / sizeof(T_RUNTIME_FUNCTION);
}
else
{
m_nRuntimeFunctions = 0;
}
Call the process :
When you are in C# When calling methods in the code ,CLR Check whether the module of the current method contains R2R Information , If it is included, get R2R Information , adopt R2R Information , Get Native Header Inside RuntimeFunctions and MethodDefEntryPoints. Then through these two items, it is calculated that this method is in RuntimeFunctions Index in memory block , Through this index, calculate the method in RuntimeFunctions Offset value of memory block , Get the attribute by the offset value BeginAddress, That is, the result of the method stored in the binary dynamic link library . The process is complicated , Here's some of the code .
PCODE MethodDesc::GetPrecompiledR2RCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
#ifdef FEATURE_READYTORUN
Module * pModule = GetModule(); // Get the module of the called method
if (pModule->IsReadyToRun()) // Check whether this module contains R2R Information
{
// If you include , Then we get R2R Information , Then get the entry point of the called method
pCode = pModule->GetReadyToRunInfo()->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
}
// Get the called method entry point
PCODE ReadyToRunInfo::GetEntryPoint(MethodDesc * pMD, PrepareCodeConfig* pConfig, BOOL fFixups)
{
mdToken token = pMD->GetMemberDef();
int rid = RidFromToken(token);// Get the of the called method MethodDef Indexes
if (rid == 0)
goto done;
uint offset;
if (pMD->HasClassOrMethodInstantiation())
{
// Ten thousand words are omitted here
}
else
{
// This m_methodDefEntryPoints Namely Native Header The method entry point item inside . Get the runtime method of the called method through the function entry point item (RuntimeFunctions) The index of
if (!m_methodDefEntryPoints.TryGetAt(rid - 1, &offset))
goto done;
}
uint id;
offset = m_nativeReader.DecodeUnsigned(offset, &id);
if (id & 1)
{
if (id & 2)
{
uint val;
m_nativeReader.DecodeUnsigned(offset, &val);
offset -= val;
}
if (fFixups)
{
BOOL mayUsePrecompiledNDirectMethods = TRUE;
mayUsePrecompiledNDirectMethods = !pConfig->IsForMulticoreJit();
if (!m_pModule->FixupDelayList(dac_cast<TADDR>(GetImage()->GetBase()) + offset, mayUsePrecompiledNDirectMethods))
{
pConfig->SetReadyToRunRejectedPrecompiledCode();
goto done;
}
}
id >>= 2;
}
else
{
id >>= 1;
}
_ASSERTE(id < m_nRuntimeFunctions);
// After a series of calculations , Put this real index id As m_pRuntimeFunctions That is to say native header term RuntimeFunctions Index of memory block , Then get the attribute BeginAddress, That is, the entry point of the called method .
pEntryPoint = dac_cast<TADDR>(GetImage()->GetBase()) + m_pRuntimeFunctions[id].BeginAddress;
This is the updated entry point of the called method
m_pCompositeInfo->SetMethodDescForEntryPointInNativeImage(pEntryPoint, pMD);
return pEntryPoint;
}
The above references are as follows :
1.https://github.com/dotnet/runtime/blob/main/src/coreclr/gc/gchandletable.cpp
2.https://github.com/dotnet/runtime/blob/main/src/coreclr/gc/gc.cpp
3.https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/readytoruninfo.cpp
4.https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/prestub.cpp
5.https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/nativeformatreader.h
ending :
It has always been believed that technology can be freely shared and freely grabbed , If you like, you can reprint and modify at will . WeChat official account :jianghupt QQ Group :676817308. Welcome to the discussion .
.Net CLR R2R More related articles on the principle of compilation
- PHP A brief analysis of the principle of setting the error reporting level of
A brief analysis of the principle excerpts php.ini The default configuration of the file (php5.4): ; Common Values: ; E_ALL (Show all errors, warnings and notices inclu ...
- Java Annotation And several common open source project annotation principle analysis
PDF edition : Java Annotation.pdf, PPT edition :Java Annotation.pptx, Keynote edition :Java Annotation.key One .Annotation in ...
- Java Android annotation (Annotation) And several common open source project annotation principle analysis
Many open source libraries (ButterKnife.Retrofit.ActiveAndroid wait ) Annotation is used to simplify code and improve development efficiency . This article briefly introduces Annotation Example . Concept and function . classification . Customize . ...
- [ Reprint ] Thrift A brief analysis of the principle (JAVA)
Reprinted from http://shift-alt-ctrl.iteye.com/blog/1987416 Apache Thrift It's a cross language service framework , In essence RPC, It also has serialization . Send serialization mechanism : When we drive ...
- Spring series [email protected] A brief analysis of the principle
In a clustered system , It is often necessary to Session Share . Otherwise, there will be such a problem : The user is in the system A After landing , If some subsequent operations are load balanced to the system B above , System B It is found that there is no such user on this machine Session, Will force users to re ...
- SIFT A brief analysis of the characteristic principle (HELU edition )
SIFT(Scale-Invariant Feature Transform) It is a feature descriptor with scale invariance and illumination invariance , It is also a theory of feature extraction , For the first time by D. G. Lowe On 2004 In the past years < ...
- be based on IdentityServer4 Of OIDC Single sign on (SSO) A brief analysis of the principle
It says the front IdentityServer4 My study is off and on , To work around , A lot of detours , It took a lot of time . Maybe it's because I didn't read the source code , There is no special systematic learning material , A lot of related articles are related to the big guys in the garden , There are a series of articles , such as : ...
- A dynamic proxy A brief analysis of the principle (java. Dynamic compilation , A dynamic proxy )
A dynamic proxy : 1. Dynamic compilation JavaCompiler.CompilationTask Dynamic compiler want to understand their own look up API file 2. Reflection is represented by class The main use of Method.invoke(Object o,Object ...
- 【 Ultra Compact JS Template library / Front end template library 】 A brief analysis of the principle and XSS To guard against
Use jsp.php.asp Or later struts Wait a minute, my friend , You don't necessarily know what a template is , But it must be clear that this kind of development : <div class="m-carousel"> < ...
- ARP Analysis of attack principle and defense measures
0x1 brief introduction Network spoofing attack as a very professional means of attack , To network security managers , Bring a severe test . The battlefield of network security has spread from the Internet to the internal network of users , Especially the local area network . At present, we use ARP Cheating trojan virus is widely spread in LAN ...
Random recommendation
- Kotlin:Android World Swift
from :http://www.infoq.com/cn/news/2015/06/Android-JVM-JetBrains-Kotlin Kotlin It's a school with Swift Similar static types JVM Language , from Je ...
- About JavaScript The shallow copy and the deep copy of
stay JS There are some basic types in this book, like Number.String.Boolean, And objects are things like this { name: 'Larry', skill: 'Node.js' }, The biggest difference between objects and basic types is that they ...
- 【NOI2016】 Section Answer key
The main idea of the topic : Yes n Intervals , When there is m When an interval has a common part , seek m The minimum of the difference between the maximum and the minimum of the length of an interval . Ideas : Sort by the length of the interval from small to large , We know that several continuous intervals are optimal , Then use two pointers to point to the head and tail , Linear scanning , And then use the line segment tree interval ...
- eclipse install Veloeclipse(Velocity Edit plugins )
eclipse install Veloeclipse(Velocity Edit plugins ) Help-->install new software-->Add increase Name:Veloeclipse Value ...
- SEO- External link types and standards
External links The role of the outer chain : Promote your website I believe everyone has heard of " Inner chain is king , The outer chain is the emperor " this sentence , Whether it's true or not , From this sentence , We can all realize the importance of the outer chain . Outside the chain type : 1. Blog 2. Forum 3. branch ...
- 【Spring Source code depth analysis series 】Spring The overall architecture
One .Spring The overall architecture and modules Two . Module classification : 1.Core Container Core Container contains Core .Beans.Context. and Expression Language ...
- Use CocoaPods establish Pod
I wanted to give it to App score , Good open source components do not Swift edition , If I wrote a simple . Thinking that since I wrote , Just write it better , Provide it to those who need it . such SwiftyiRate The birth of . The following is about creating pod Steps for : One . establish git ...
- STM32L476RG_ Interrupt development and implementation
The main function of this program is to realize the key control light on and off . When the light is off, press the key to turn on the light , When the light is on, press the key to turn off the light , That is to realize the level reversal operation of the lamp . Key scanning uses GPIO Descent interrupt , To monitor the key press action . And eliminate the chattering operation ...
- sqlserver Database status of —— Offline and online
1. Database state : online: You can access the database offline: The database cannot be accessed 2. How to view the status of the database : (1) Using query statements : SELECT state_desc FROM SYS.datab ...
- NOI.AC NOIP Simulation game Third field Supplement notes
NOI.AC NOIP Simulation game Third field Supplement notes Line up The main idea of the topic : Given a \(n\times m(n,m\le1000)\) Matrix , There is a number on each grid \(w_{i,j}\). Guarantee \(w_{i,j}\) Not each other ...





![[shutter -- layout] linear layout (row and column)](/img/0e/df0f4bce73dd9785cc843adaf371d0.png)


