【问题标题】:CLR4 Hosting Interface is causing Heap Corruption?CLR4 托管接口导致堆损坏?
【发布时间】:2011-08-16 08:31:23
【问题描述】:

我正在使用本地 CLR 托管服务已有数周时间。一开始它工作得很好。但后来我注意到我的应用程序中的某些东西会导致堆损坏。我发现这是由 CLR 启动引起的。 (请参阅以下代码的简短版本。)

#pragma comment(lib, "mscoree.lib")
#include <mscoree.h>
#include <metahost.h>
#include <comdef.h>
#import "mscorlib.tlb" raw_interfaces_only          \
    high_property_prefixes("_get","_put","_putref")     \
    rename("ReportEvent", "InteropServices_ReportEvent")

using namespace mscorlib;

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr; // In fullversion used for error detection - but here unused.
    PCWSTR pszVersion = L"v4.0.30319";
    ICLRMetaHost* lpMetaHost = NULL;
    ICLRRuntimeInfo* lpRuntimeInfo = NULL;
    ICorRuntimeHost* lpRuntimeHost = NULL;
    _AppDomainPtr spAppDomain = NULL;
    BOOL bLoadable = false;
    IUnknownPtr spAppDomainThunk = NULL;

    CLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (LPVOID *)&lpMetaHost);
    // After this line i can "late detect" 6 array bound heap corruptions in process memory.

    lpMetaHost->GetRuntime(pszVersion, IID_ICLRRuntimeInfo, (LPVOID *)&lpRuntimeInfo);    
    lpRuntimeInfo->IsLoadable(&bLoadable);
    lpRuntimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&lpRuntimeHost));
    lpRuntimeHost->Start();
    lpRuntimeHost->GetDefaultDomain(&spAppDomainThunk);
    spAppDomainThunk->QueryInterface(IID_PPV_ARGS(&spAppDomain));
    spAppDomainThunk->Release();
    // Now I can "late detect" up to 9 array bound heap corruptions in process memory.

    return 0;
}

关于如何避免这种情况的任何想法?目前在某些情况下它仍然有效,但随着我的应用程序变得越来越大,出错的机会成倍增加。

【问题讨论】:

  • 您没有检查失败,也没有将指针初始化为 NULL - 我认为完整版本的代码确实会检查错误?
  • 是的,因此我使用 HRESULT,它在我的摘录中已定义但未使用。没有错误我只想让我的问题尽可能简短。我会在我的问题中注意到这一点。
  • 这里的代码似乎没有错。如果您在 spAppDomainThunk->Release() 之后立即返回,是否会收到 purify 错误?
  • 如代码中所述,我已经得到!6!在以下行之后净化错误:CLRCreateInstance ...。稍后通过运行应用程序,我注意到由于堆损坏异常。
  • 您还没有回答问题。 ABWL 是“延迟数组边界写入”。这意味着 Purify 稍后会在对象被释放或启动泄漏扫描时检测到错误。因此,如果您在随后的代码中遇到问题,尤其是在托管部分 - 您很有可能在不相关的地方获得 ABWL。创建一个只创建托管堆并退出的项目,看看你是否看到谁的错误。

标签: c++ native clr-hosting heap-corruption


【解决方案1】:

虽然目视检查上面的代码并没有发现可能导致堆损坏的原因,但请尝试AppVerifier + Windbg 来检测它。这是有关如何执行此操作的一些信息 http://blogs.msdn.com/b/lagdas/archive/2008/06/24/debugging-heap-corruption-with-application-verifier-and-debugdiag.aspx。 AppVerifier 实际上查明了堆栈(帧、调用)上破坏堆的位置。

【讨论】:

  • AppVerifier 和 windbg 所做的与理性 puritfy 所做的完全一样,这向我显示了上面的错误。我对此的研究结论是,这些错误似乎是在 CLR 中硬编码的,并且可能用于检测系统特定变量或类似的东西。换句话说,微软似乎做了一些小技巧来解决一个问题,这显示在这 9 个错误中。顺便提一句。无论这些错误,CLR 主机都能正常工作。
猜你喜欢
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
相关资源
最近更新 更多