c# - 如何在托管代码中获取 EIP 的当前值?

标签 c# .net clr

这个问题看起来像是一个肮脏的 hack,你不应该这样做,但让我先解释一下。最终目标是像 C++ 中那样拥有方法局部静态。

void Func()
{
   static methodLocalObject = new ExpensiveThing();
   // use methodlocal Object
}

这和指令指针有什么关系?我想根据调用者缓存数据。为了加快速度,我返回堆栈以获取调用者的地址,并将其用作字典的唯一键来存储数据。 这将允许创建一个基于反射的跟踪器,它不会每次都使用反射来获取当前方法和类型的名称,而是只使用一次并将反射信息存储在哈希表中。

到目前为止的答案都是基于单声道的。我想尝试一个适用于 .NET 3.5/4.0 32/64 位的通用解决方案。我知道 calling convention对于 64 位来说是完全不同的,所以要获得可靠的东西可能会很有挑战性。但另一方面,我在我的方法中完全控制了堆栈的外观。堆栈在 .NET 3.5 和 4.0 之间确实看起来非常不同,当然在发布版本之间也不同。我仍然需要检查 NGen 是否也创建了具有不同堆栈布局的代码。一种可能性是使用 C++ 辅助方法,该方法采用 5 个魔术整数参数(在 x64 上只有第 5 个在堆栈中)并检查我可以在堆栈中找到它们的位置。 另一种可能性是简单地使用整个堆栈,直到我在堆栈上找到我的魔法标记作为键并将堆栈的这一部分用作足够唯一的键。但我不确定这种方法是否可行,或者是否有更好的选择。我知道我可以通过分析或调试 api 以安全的方式遍历堆栈,但它们都不快。

对于跟踪库,通常的方法是使用反射遍历堆栈以获取当前方法名称和类型。

class Tracer
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    public Tracer()
    {
        StackFrame frame = new StackTrace().GetFrame(1); // get caller
        Console.WriteLine("Entered method {0}.{1}", frame.GetMethod().DeclaringType.FullName, frame.GetMethod().Name);
    }

}

但这很慢。另一种解决方案是直接通过字符串传递数据,这要快得多,但需要更多的输入。替代解决方案是使用调用函数的指令指针(如果可以以非常快的方式确定)来绕过昂贵的反射调用。 那么这将是可能的:

class Tracer
{
    static Dictionary<Int64, string> _CachedMethods = new Dictionary<Int64, string>();

    [MethodImpl(MethodImplOptions.NoInlining)]
    public Tracer()
    {
        Int64 eip = GetEIpOfParentFrame();
        string name;
        lock (_CachedMethods)
        {
            if (!_CachedMethods.TryGetValue(eip, out name))
            {
                var callingMethod = new StackTrace().GetFrame(1).GetMethod();
                name =  callingMethod.DeclaringType + "." + callingMethod.Name;
                _CachedMethods[eip] = name;
            }
        }
        Console.WriteLine("Entered method {0}", name);

    }

    Int64 GetEIpOfParentFrame()
    {
        return 0; // todo this is the question how to get it
    }

}

我知道解决方案需要不受管理。在 C++ 中,有一个名为 _ReturnAddress 的编译器内部函数。但根据文档,它不适用于托管代码。提出相同问题的另一种方式:有人知道 .NET 3.5/4 x32/x64 托管方法的调用约定和堆栈布局吗?

您的, 阿洛伊斯·克劳斯

最佳答案

Update This answer is now obsolete for recent version of .NET: see here How to get current value of EIP in managed code?

真正简短的回答是:CLR VM 是堆栈机器,因此那里没有 EIP。 稍微长一点的答案是:如果您依赖未记录的特定于实现的详细信息,您可以从非托管代码中的 CPU EIP 推断出可用的 ID。

概念验证

我刚刚在 Linux 32 位上使用 mono 2.11 完成了以下概念验证。我希望这些信息可能有所帮助。这实现了非托管功能:

extern static string CurrentMethodDisplay();
extern static uint CurrentMethodAddress();

原生来源:tracehelper.c [1]:

#include <string.h>

void* CurrentMethodAddress()
{
    void* ip;
    asm ("movl 4(%%ebp),%0" : "=r"(ip) );
    return ip;
}

const char* const MethodDisplayFromAddress(void* ip);
const char* const CurrentMethodDisplay()
{
    return MethodDisplayFromAddress(CurrentMethodAddress());
}

#ifndef USE_UNDOCUMENTED_APIS
extern char * mono_pmip (void *ip);

const char* const MethodDisplayFromAddress(void* ip)
{
    const char* text = mono_pmip(ip);
    return strdup(text? text:"(unknown)");
}
#else

/* 
 * undocumented structures, not part of public API
 *
 * mono_pmip only returns a rather ugly string representation of the stack frame
 * this version of the code tries establish only the actual name of the method
 *
 * mono_pmip understands call trampolines as well, this function skips those
 */
struct _MonoDomain; // forward
struct _MonoMethod; // forward
typedef struct _MonoDomain  MonoDomain;
typedef struct _MonoMethod  MonoMethod;
struct _MonoJitInfo { MonoMethod* method; /* rest ommitted */ };

typedef struct _MonoJitInfo MonoJitInfo;

MonoDomain *mono_domain_get(void);
char* mono_method_full_name(MonoMethod *method, int signature);
MonoJitInfo *mono_jit_info_table_find(MonoDomain *domain, char *addr);

const char* const MethodDisplayFromAddress(void* ip)
{
    MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get(), ip);
    const char* text = ji? mono_method_full_name (ji->method, 1) : 0;
    return text? text:strdup("(unknown, trampoline?)");
}

#endif

C# 源代码 (client.cs) 调用 native 库函数:

using System;
using System.Runtime.InteropServices;

namespace PoC
{
    class MainClass
    {
        [DllImportAttribute("libtracehelper.so")] extern static string CurrentMethodDisplay();
        [DllImportAttribute("libtracehelper.so")] extern static uint CurrentMethodAddress();

        static MainClass()
        {
            Console.WriteLine ("TRACE 0 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
        }

        public static void Main (string[] args)
        {
            Console.WriteLine ("TRACE 1 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
            {
                var instance = new MainClass();
                instance.OtherMethod();
            }
            Console.WriteLine ("TRACE 2 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
            {
                var instance = new MainClass();
                instance.OtherMethod();
            }
            Console.WriteLine ("TRACE 3 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
            Console.Read();
        }

        private void OtherMethod()
        {
            ThirdMethod();
            Console.WriteLine ("TRACE 4 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
        }

        private void ThirdMethod()
        {
            Console.WriteLine ("TRACE 5 {0:X8} {1}", CurrentMethodAddress(), CurrentMethodDisplay());
        }
    }
}

使用 Makefile 编译和链接:

CFLAGS+=-DUSE_UNDOCUMENTED_APIS
CFLAGS+=-fomit-frame-pointer
CFLAGS+=-save-temps
CFLAGS+=-g -O3

all: client.exe libtracehelper.so

client.exe: client.cs | libtracehelper.so
    gmcs -debug+ -optimize- client.cs 

tracehelper.s libtracehelper.so: tracehelper.c
    gcc -shared $(CFLAGS) -lmono -o $@ tracehelper.c 
#   gcc -g -O0 -shared -fomit-frame-pointer -save-temps -lmono -o $@ tracehelper.c 

test: client.exe
    LD_LIBRARY_PATH=".:..:/opt/mono/lib/" valgrind --tool=memcheck --leak-check=full --smc-check=all --suppressions=mono.supp mono --gc=sgen --debug ./client.exe

clean:
    rm -fv *.so *.exe a.out *.[iso] *.mdb

使用 LD_LIBRARY_PATH= 运行它。 ./client.exe 结果:

TRACE 0 B57EF34B PoC.MainClass:.cctor ()
TRACE 1 B57EF1B3 PoC.MainClass:Main (string[])
TRACE 5 B57F973B PoC.MainClass:ThirdMethod ()
TRACE 4 B57F96E9 PoC.MainClass:OtherMethod ()
TRACE 2 B57EF225 PoC.MainClass:Main (string[])
TRACE 5 B57F973B PoC.MainClass:ThirdMethod ()
TRACE 4 B57F96E9 PoC.MainClass:OtherMethod ()
TRACE 3 B57EF292 PoC.MainClass:Main (string[])

请注意,这是在 Mono 2.11 上。它也适用于 2.6.7,有和没有优化。

[1] 我学会了GNU extended asm以此目的;谢谢!

结论 ?

提供了概念证明;此实现特定于 Mono。可以在 MS .Net 上提供类似的“技巧”(也许使用 ::LoadLibrary of SOS.dll ?)但留给读者作为练习:)

我个人还是会 go with my other answer ,但我想我屈服于挑战,就像我之前说过的:YMMV、这里有龙、TIMTOWTDI、KISS 等。

晚安

关于c# - 如何在托管代码中获取 EIP 的当前值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695827/

相关文章:

c# 像 facebook 和 linkedin 一样从 url 获取内容

c# - windows窗体如何在文本框的右侧或左侧添加图标

c# - C#中uint转int的编译时间转换

.NET CLR - 将 CIL 编译为特定于平台的指令时,新的 CPU 体系结构等呢?

c# - Asp.Net Core OData 4.0 中 BaseUrl 中的动态路由

c# - 使用 GenericTypeArgument 在运行时更改类型

c# - 如何将时间插入MySQL数据库?

c# - 使用 .NET 2.0 驱动程序获取 MongoDB Collection 统计信息

c# - 如何将 Image 类型转换为 Image<Bgr, Byte>?

c# - 是否可以克隆 ValueType?