Hacker News new | ask | show | jobs
by dotancohen 10 days ago
Go on.
2 comments

  int *x = malloc(4);
  *x = 42;
  int *y = realloc(x, 4);
  *y = 43;
  printf(“%p %d %p %d\n”, x, *x, y, *y);
This may well print the same address for x and y while printing different values for x and y. Despite having the same bitwise value, x was invalidated by the call to realloc and it became illegal to access x. Thus the compiler is free to assume that x still holds the value previously assigned to it (or make demons fly out of your nose when you try to read from it), because a pointer isn’t just a memory address, it has meaning tied to where you got it and what you did with it.
Isn't the proper sane default behavior to fault if x is accessed after realloc?
That certainly would be very nice. It’s also extremely difficult to do reliably. One certainly could make the argument that it should be done in easy cases like this example. But I suspect that the cases where it’s easy to consistently fault and the cases where it’s a useful diagnostic in real programs don’t have much overlap.
To do that you need to track more information than the integer-like value of pointer x.

In this case there’s a good chance that x and y have the same value, for example.

So that is more costly in storage and speed.

I think that depends on compiler flags, at least with gcc.
I tried, but frankly, typing "pointer provenance" into Google gets you a much better explanation than my attempt. Google's AI analysis might be questionable, but it's less questionable than my first attempt.

To oversimplify, provenance is the metadata a compiler keeps about a pointer during the compilation process.

For example, Arm Memory Tagging Extension uses the top byte of a 64-bit address to store a tag that the CPU verifies against the allocation tag on pointer dereference. If the tags don't match, an exception occurs. MTE makes exploiting memory vulnerabilities more difficult by preventing the attacker from generating valid pointers to hijack program control flow with. To bypass MTE, the attack would need to combine the exploit with an info leak or arbitrary memory read to set the correct tag for a new pointer.

On a MTE enabled system, adding an offset to a pointer cast to integer will result in an exception with high probability since the new pointer will be using the tag for the old address.

https://docs.kernel.org/arch/arm64/memory-tagging-extension....