Overlaying several CLR reference fields with each other in explicit struct?

前端 未结 5 1721
日久生厌
日久生厌 2021-02-07 20:59

Edit: I\'m well aware of that this works very well with value types, my specific question is about using this for reference types.

Edit2:

5条回答
  •  野的像风
    2021-02-07 21:22

    Since the garbage collector is untyped and only distinguishes between object references and plain bits, overlapping references won't confuse it. However, while one object reference can completely overlap another, this is unverifiable, aka unsafe (ECMA-335 standard, page 180, II.10.7 Controlling instance layout). It's easy to construct a program that exploits this unverifiability to crash horrendously:

    using System.Runtime.InteropServices;
    
    class Bar
    {
        public virtual void func() { }
    }
    
    [StructLayout(LayoutKind.Explicit)]
    struct Overlaid
    {
        [FieldOffset(0)]
        public object foo;
    
        [FieldOffset(0)]
        public Bar bar;
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var overlaid = new Overlaid();
            overlaid.foo = new object();
            overlaid.bar.func();
        }
    }
    

    Here the func call loads a function pointer from one past the last element of object class's virtual table. According to this article following the vtbl there's a handle table. Treating it as a function pointer leads to a System.AccessViolationException.

提交回复
热议问题