jeudi 23 juin 2016

How can a C++ reference be changed (by any means necessary)

The C++ language doesn't let you change a reference after it is assigned. However, I had a debugging need/desire to change the reference to help debug something. Is there a hacky way to basically overwrite the reference implementation with a new pointer? Once you get an address to the object you want to change, you can cast it to whatever you want and overwrite it. I could not figure out how to get a memory address of the underlying reference instance; using & to dereference the reference doesn't give you the address of the reference, but the address of the object pointed to by the reference. I realize this is obviously going to invoke undefined behavior, and this is just an experiment. A third party library has a bug with global reference that was not getting constructed before the code is exercised, and I want to see if I can fix it by setting the reference myself. At this point, it became a challenge to see if it is even possible. I know you can do this in assembly language, if you can reference the symbol table directly. I imagine something like this. These are globally scoped variables. Apple a; Apple& ref = a; Later I want ref to refer to a new object instance b and leave a alone. Apple b; ref = b; // that doesn't work. that justs sets a=b. &ref = &b; // that doesn't work. the compiler complains. uint64_t addr = find_symbol_by_any_means_necessary(ref); *(Apple**)addr = &b; // this should work if I could get addr Please don't remind me this is a bad idea. I know it is a bad idea. Think of it as a challenge. This is for debug only, to test a hypotheses quickly. I want to learn something about the internals of C++ binary code. (Please tell me if it is impossible because of system page protection... I suppose you could get a seg fault if the references are placed in a holy place).

Aucun commentaire:

Enregistrer un commentaire