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

前端 未结 5 1662
日久生厌
日久生厌 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

    Well, you found a loop hole, the CLR permits it since all overlapped fields are objects. Anything that would allow you to mess with an object reference directly gets rejected with a TypeLoadException:

      [StructLayout(LayoutKind.Explicit)]
      struct Overlaid {
        [FieldOffset(0)]
        public object AsObject;
        [FieldOffset(0)]
        public IntPtr AsPointer;
      }
    

    But you can exploit it by giving the classes fields. Nothing really bad happens as long as you are just reading the field values, you can get the value of the tracking handle that way for example.

    Writing those fields however leads to an ExecutionEngineException. I think however that it is an exploit if you can guess the value of a tracking handle correctly. Practical use is sufficiently close to zero though.

提交回复
热议问题