hiding a pointer

Thomas Kuehne thomas-dloop at kuehne.cn
Mon Oct 23 23:38:41 PDT 2006


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Sometimes you might have to hide a pointer, so that the GC doesn't
"see" it and might reclaim the pointer's destination if there are
no other pointers into this area.

XORing and other mathematical transformations aren't save(the result
might look like a pointer into some other GC-controlled area).

Using memory allocated by std.c.stdlib.malloc to store the pointer
works, but will require you to call std.c.stdlib.free at some later
point.

As far as I am aware Linux and Windows never allocate user memory
at 0x0000_00XX(32bit) or 0x0000_0000_0000_00XX(64bit):

# struct HiddenPointer(T : T*){
#     size_t[size_t.sizeof] data;
# 
#     void set(T* ptr){
#         ubyte[] raw = (cast(ubyte*)&ptr)[0 .. size_t.sizeof];
#         foreach(size_t i, ubyte element; raw){
#             data[i] = element;
#         }
#     }
# 
#     T* get(){
#         T* result;
#         ubyte[] raw = (cast(ubyte*)&result)[0 .. size_t.sizeof];
#         foreach(size_t i, size_t element; data){
#             raw[i] = cast(ubyte)element;
#         }
#         return result;
#     }
# }

The above code should work regardless of endianess or pointer size.

trivial usage sample:

# int main(){
#     HiddenPointer!(int*) hidden_pointer;
# 
#     int x;
#     hidden_pointer.set(&x);
#     int* y = hidden_pointer.get();
# 
#     return 0;
# }

Thomas


-----BEGIN PGP SIGNATURE-----

iD8DBQFFPcHMLK5blCcjpWoRAtk9AJ9obolpi2cPg0C55yjnHdAousvVaACfaZhf
LTOod2fWIxnfSsT5AnOaLcQ=
=b8dw
-----END PGP SIGNATURE-----



More information about the Digitalmars-d-learn mailing list