0

How can I reliably test (in IL or with some methods provided by the .NET) whether a given native int is a valid object reference (O)? The pointer may have been retrieved from some debugger, and it might not be valid (or collected after it was returned). Simply returning it as an object throws uncatchable ExecutionEngineException on invalid addresses. I tried castclass to object, which throws NullPointerException in case of some invalid references, but it also throws bad AccessViolationException with some addresses. Is there a better way to do it, without throwing any uncatchable exceptions or corrupting memory?

IS4
  • 11,945
  • 2
  • 47
  • 86
  • You could enumerate all heap objects using the profiler API and see whether this pointer is in the set of all objects. You also would have to freeze all thread while doing that so that there can't be a GC moving objects. You really need to traverse the heap to check the pointer because the data being pointed to could be the middle of a byte[] that just happens to look like an object. – usr Jun 14 '15 at 21:55
  • @usr Ironically, the pointer actually comes from the profiler API (or similar one). Most objects returned by it work, but some of them throw EEE. – IS4 Jun 14 '15 at 22:02
  • I see garbage collection issues ahead when objects move around but your poor integer is left behind. – sisve Jun 16 '15 at 05:23
  • @SimonSvensson Yes, that's why I want to check its validity. – IS4 Jun 16 '15 at 11:25

1 Answers1

0

In a comment on the question, you said the pointer comes from the profiler API, so I'm going to assume that your debugger is implemented using the profiler API.

There is no reliable way to check if a pointer to an object (ObjectID) is valid. Even if it is pointing to what appears to be a valid object, it might not be the same object. Instead, the normal approach is to track the object through the GC callbacks and update/discard your references as appropriate.

If you store the pointer somewhere that isn't updated and the GC is allowed to run, then you should automatically assume the pointer is invalid.

Brian Reichle
  • 2,798
  • 2
  • 30
  • 34