CLR探索系列:Windbg+SOS动态调试分析托管代码

Windbg调试SOS.DLL和CLR 不匹配问题 我们在用windbg调试客户发来的dump文件的时候,如果不是相同的环境的话,很容易出现这个现象,简单的说就是程序运行机器上的CLR与当前开发调试人员机器上的CLR是不同的版本,从而导致开发人员机器上的SOS.dll与dump file中要求的SOS.dll不一样(比如应用程序要求是.net framework 4.6,所以客户机安装的就是.net 4.6,但是开发人员机器上安装的是.net 4.... 阅读详情

在使用VS进行托管应用程序的调试的时候,有的时候总感觉有些力不从心。譬如查看一个托管堆或者计算堆栈的时候,VS就不能胜任了。这个时候,Windbg+SOS扩展调试模块就为我们提供了一个很好的解决方案。
我们看一段代码:
class Program
    {
        static void Main(string[] args)
        {
            Program b = new Program();
            b.test();
            System.Console.ReadLine();
        }

        public void test()
        {
            int i = 67;
            System.Console.WriteLine((char)i);
            System.Console.WriteLine((char)67);
            i = 1;
        }
    }

这是C#里面的一个强制类型转换,我们现在用windbg+SOS来分析下计算堆栈,以及强制类型转换之后的JIT代码。
在windbg里面加载这个正在运行的程序,attach to this process,然后加载SOS扩展调试模块:
0:003> .load C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/SOS.dll
然后显示当前的线程:
0:003> ~
   0  Id: cf0.450 Suspend: 1 Teb: 7ffdf000 Unfrozen
   1  Id: cf0.be8 Suspend: 1 Teb: 7ffdd000 Unfrozen
   2  Id: cf0.168 Suspend: 1 Teb: 7ffdc000 Unfrozen
.  3  Id: cf0.7d0 Suspend: 1 Teb: 7ffde000 Unfrozen
切换到第0个线程:
0:003> ~0s
eax=0012f2e4 ebx=00000000 ecx=0012f400 edx=00000008 esi=0012f1f4 edi=00250688
eip=7c92eb94 esp=0012f194 ebp=0012f1b4 iopl=0         nv up ei pl zr na pe nc
cs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246
ntdll!KiFastSystemCallRet:
7c92eb94 c3              ret
显示test方法相关的地址:
0:000> !name2ee TestConcoleApp.exe TestConcoleApp.Program.test
Module: 00ab2c24 (TestConcoleApp.exe)
Token: 0x06000002
MethodDesc: 00ab2ff0
Name: TestConcoleApp.Program.test()
JITTED Code Address: 00d000f8
显示这个方法被C#编译器编译之后的IL代码:
0:000> !dumpil 00ab2ff0
ilAddr = 00402074
IL_0000: nop
IL_0001: ldc.i4.s 67
IL_0003: stloc.0
IL_0004: ldloc.0
IL_0005: conv.u2
IL_0006: call System.Console::WriteLine
IL_000b: nop
IL_000c: ldc.i4.s 67
IL_000e: call System.Console::WriteLine
IL_0013: nop
IL_0014: ldc.i4.1
IL_0015: stloc.0
IL_0016: ret

这里,sandwi对conv.u2这条指令一直困惑良多。我也对这个问题困惑了好久,翻阅了很多资料也没找到,后来准备在sscli的C#编译器里面找到答案,不过没找到地方......
后来被证实,这条指令是C#编译器为了类型安全,而生成的一条指令。作用在于把一个integer转换称为一个unsigned int16,然后前面补0成为int32压入堆栈里面去。
这是一个语言编译器行为,为了证实这个想法,同时写了一段同样的VB代码来证实我们的想法:
Module Module1

    Sub Main()
        Dim i As Integer

        i = 67
        System.Console.WriteLine(Chr(i))
        System.Console.WriteLine(Chr(67))
        System.Console.ReadLine()

    End Sub
  
End Module

编译之后的IL代码也同样支持上面的想法。
这里,感谢微软的张翼证实了我关于conv.u2的存在原因的猜想。但是,zhangyi说在test方法中的conv.u2指令在JIT生成的本地代码中被优化掉了,我却不同意这种看法:
0:000> !u 00d000f8
这条指令,是显示JIT编译了的test方法的本地代码,根据
JITTED Code Address: 00d000f8
这一行得来的。显示结果如下:
Normal JIT generated code
TestConcoleApp.Program.test()

push          esi
push          eax
mov          dword ptr [esp],ecx
cmp          dword ptr ds:[0AB2DD8h],0
je              00d0010b  (跳到xor  esi,esi这里)
call            mscorwks!CorLaunchApplication+0x108b4 (7a08e179)
xor            esi,esi
nop
mov           esi,43h
movzx       ecx,si
call            mscorlib_ni+0x2f8b9c (793b8b9c) (System.Console.WriteLine(Char), mdToken: 06000759)
nop
mov           ecx,43h
call            mscorlib_ni+0x2f8b9c (793b8b9c) (System.Console.WriteLine(Char), mdToken: 06000759)
nop
mov           esi,1
pop            ecx
pop            esi
ret
这里,movzx   ecx,si这条指令就对应了IL代码里面的Conv.u2,把对应的int前面补0放入到
ecx寄存器里面去。

后记:关于动态调试托管代码,我也是刚接触不久,上面有不准确的地方,欢迎大家多多指正。

 
告别单一查询!MultiQueryRetriever在LangChain中的高级用法解析 本文深入解析了LangChain中的MultiQueryRetriever高级用法,该工具通过大语言模型自动生成多样化查询,显著提升文档检索的召回率和准确性。文章详细介绍了其核心机制、高级配置调优策略以及在多语言和专业领域中的实际应用,为开发者提供了优化知识库问答系统的实用方案。 阅读详情

相关推荐

Intouch实时报警

Intouch实时报警功能的相关设置

weixin_41571357的博客 4232

Windows调试学习笔记:(一)WinDBG中加载SOS和CLR

  最近产品环境出现了部分服务器当机情况,虽然重启之后问题就不出现了。但本着彻底解决问题的态度,想要找到root cause。多次尝试Visual Studio失败(可能是代码惊醒了优化和签名)之后,决定使用WinDBG来调试。于是。。。灾难发生了。   想要一次性成功搭建测试环境,那得靠人品。看来我近来人品积累的不够,不断的有小问题出现。比如加载SOS和CLR,就让我不胜其烦。必须得记下来,分...

weixin_34198762的博客 629

二次开发vba_CATIA VBA(VBS)二次开发:使用Search批量选择元素

在CATIA二次开发中很多在程序中进行自动交互的方法或函数都需要使用选择集作为参数,将几何元素按照要求批量添加到选择集中也是实现程序自动运行的有效方法。在前面的文章《CATIA使用VBA(VBS)二次开发时用户的交互选择》和《CATIA使用VBA(VBS)二次开发时工程图和草图位置的交互选择函数Indicate2D》中介绍了在CATIA VBA(VBS)二次开发中用户和选择集之间的交互操...

weixin_32497403的博客 1330

windbg调试.net程序知识快速参考

最近因团队下一个开发工程师的WPF应用存在偶尔卡顿的现象,重新温习了下windbg的知识,此次记录备忘下,以下是整理的思维导图,有点乱,哈哈。

omage的专栏 1209

MCGS 和 200SMART 时间同步

在实际应用中,PLC经常会因为断电原因,导致时间不准确。假设我们设置了一个投加泵,每天8-18点投加。屏幕上显示的时间和PLC内部的时间,很可能不一样。所以需要在触摸屏上读取PLC的时间,并且提供设置功能。

mmxxoo_xxmmp的博客 1528

如何通过CAD图中的坐标来确定是哪个坐标系

地理坐标系:为球面坐标。参考平面地是椭球面,坐标单位:经纬度。以地球参考为例,坐标系就相当于整个地球,而地理坐标系就是椭球状的完整的立体地球。所以我们可以看到生活中的数据与地图是一定含有地理坐标系的,因为他是客观上来说确确实实存在的。投影坐标系:为平面坐标。参考平面地是水平面,坐标单位:米、千米等。这就相当于把地球当成一个橘子,然后一刀切开,把橘子皮平面铺开,这个过程就是地理投影的过程。严谨一点来说就是建立一个参考系统,按照对应位置把椭球体投射到平面。那坐标系统主要有那些呢?北京54。

vjmap的博客 2万+

windbg 调试提示sos与clr不匹配问题

解决方法: 运行命令: .cordll -ve -u -l查看依赖的mscordacwks.dll和对应的sos.dll的版本,去故障机拷贝对应版本 按提示修改文件名放在对应目录, 使用.load命令分别加载对应的mscordacwks和sos的dll 转载于:https://www.cnblogs.com/karl-F/p/9870846.html...

weixin_34034261的博客 350

ESP32水墨屏日历实战:低功耗自动更新与HTTPS数据解析

本文详细介绍了ESP32水墨屏日历项目的开发实践,重点讲解了低功耗自动更新与HTTPS数据解析的实现方法。通过ESP32的自动休眠功能和水墨屏的零功耗特性,结合HTTPS请求安全获取网络数据,实现了高效节能的桌面日历应用。项目代码开源,适合物联网开发者参考。

xx56789的博客 780

CLR探索系列:Windbg+SOS动态调试分析托管代码 -- cnblog

在使用VS进行托管应用程序的调试的时候,有的时候总感觉有些力不从心。譬如查看一个托管堆或者计算堆栈的时候,VS就不能胜任了。这个时候,Windbg+SOS扩展调试模块就为我们提供了一个很好的解决方案。我们看一段代码:class Program    {        static void Main(string[] args)        {            Program b =

agan4014的专栏 882

GNSS-RTK/INS紧组合里,那个‘杆臂改正’到底怎么算?一个公式讲清INS与天线位置的关系

本文深入解析GNSS-RTK/INS紧组合导航系统中的杆臂改正(Lever Arm Correction)原理与实现方法。详细介绍了杆臂效应的物理本质、数学建模及误差扰动分析,揭示了IMU与GNSS天线位置关系的核心公式,并提供了工程实现中的常见误区与验证方法。通过Python代码示例和紧组合量测模型处理流程,帮助开发者准确理解并应用这一关键技术。

weixin_33137081的博客 363

Android 12,通过JNI写framebuff实现白板书写加速

Android 书写加速

448313096@qq.com 1208

.NET / Rotor源码研究3 – 调试Rotor托管代码的利器:WinDbg和SOS

WinDbg+SOS简介在动手进一步研究Rotor之前,我们需要首先解决一个问题:用什么调试工具最好? 很有可能你会说,这还不简单,直接用Visual Studio不就好了?一般情况下是的,只不过,在这个情况下,Visual Studio并非是最好的选择:1.     CLR对代码的编译是动态进行的(其实还有可能是静态的,称之为Prejit或者NGEN,不过可惜Rotor对此不支持),也就

张羿的CSDN专栏 4937

vue接入海康4G版摄像头通过萤石云平台推送视频流教程

vue-video-player接入海康视频,videojs-contrib-hls,vue播放视频

renkai721的专栏 7291

Windbg 及sos.dll、mex.dll扩展插件

mscordacwks.dll 就是这样一个抽象层 ( Data-Access-Component (DAC) ),它实现了让调试器SOS.dll 以比较稳定的接口来访问CLR内部不断的数据结构的目的。.cordll –ve –u –l (小写的L ) 这个命令是控制调试和控制CLR的命令,-ve是显示详细信息,-u 卸载模块,-l (小写的L) 是加载模块,上面这个命令就是卸载CLR 调试模块,然后再加载CLR调试模块,并显示详细信息。自己去获取匹配版本的关键dll。当这种方式不行时尝试如下操作。

u011234288的博客 1356

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

使用Windbg和SoS扩展调试分析.NET程序

使用Windbg和SoS扩展调试分析.NET程序 在博客堂的不是我舍不得 - High CPU in GC(都是+=惹的祸,为啥不用StringBuilder呢?)、 不是我舍不得 - .NET里面的Out Of Memory 看到很多人在问如何分析dump,所以就写下了这篇短文,抛砖引玉。一、安装 DebuggingToolsforWindows: 从以下 Microsoft 网站下载

tanliyoung的专栏 1753

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

CLR探索系列:Windbg+SOS剖析揭示域世界

在CLR的世界中,有一系列的令人Amazing的技术和架构。其中,CLR对应用程序在内存中内存分配,执行模型,程序之间的交互等一系列的技术,值得每一个致力于DotNet平台的技术人员深究。编程人员在开发的过程中,如果把程序集的加载(Assemblies Load),反射(Reflection),寄宿(Hosting),应用程序域(AppDomain),这四种技术结合起来使用的话

lbq1221119 630

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

用WinDbg探索CLR世界 [3] 跟踪方法的 JIT 过程

用WinDbg探索CLR世界 [3] 跟踪方法的 JIT 过程    本来想按照 sos 的帮助文件上命令的分类逐步介绍 WinDbg 下使用 sos 调试 CLR 程序,但发现这样实在不够直观。索性改成根据我分析 CLR 的实际案例,step by step 介绍功能,这样结构上虽然混乱一点,但更加直观,也易于上手 :P      前面两篇文章里面分别介绍了 WinDbg 的调试配置和线

tanliyoung的专栏 1191
上一篇: C#实现常用的数据结构(一):链表
下一篇: CLR探索应用程序域世界(上):Windbg SOS剖析揭示域世界
cslie
博客等级 码龄19年 40粉丝 76原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值