temp_deriv3.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Compile with /home/llozano/local2/proj/vtable/gcc-root/usr/local/bin/g++ -m32 -fvtable-verify=std -fpic -rdynamic -Wl,-R,/home/llozano/local2/proj/vtable/gcc-root/usr/local/lib32:./lib32 -I/home/llozano/local2/proj/vtable/vt2/gcc-4_6-mobile-vtable-security//libstdc++-v3/libsupc++ temp_deriv.cc -O0 -ldl -lpthread -Wl,--whole-archive,-lvtv_init,--no-whole-archive,-z,relro -DTPID=0 -g
  2. // Look at assembly with: objdump -drl a.out
  3. #include <dlfcn.h>
  4. #include <assert.h>
  5. #include <stdlib.h>
  6. extern "C" int printf(const char *, ...);
  7. static int counter = 0;
  8. int i = TPID;
  9. struct base
  10. {
  11. virtual void inc() { counter += i; }
  12. };
  13. struct derived: public base
  14. {
  15. virtual void inc() { counter += (10*i); }
  16. };
  17. // We don't use this class. It is just here so that the
  18. // compiler does not devirtualize calls to derived::inc()
  19. struct derived2: public derived
  20. {
  21. virtual void inc() { counter += (20*i); }
  22. };
  23. static base * bp = new base();
  24. static derived * dp = new derived();
  25. static base * dbp = new derived();
  26. typedef void * vtptr;
  27. vtptr get_vtptr(void * object_ptr)
  28. {
  29. vtptr * object_vtptr_ptr = (vtptr *)object_ptr;
  30. return *object_vtptr_ptr;
  31. }
  32. void set_vptr(void * object_ptr, vtptr vtp)
  33. {
  34. vtptr * object_vtptr_ptr = (vtptr *)object_ptr;
  35. *object_vtptr_ptr = vtp;
  36. }
  37. // Given 2 pointers to C++ objects (non PODs), exchange the pointers to vtable
  38. void exchange_vtptr(void * object1_ptr, void * object2_ptr)
  39. {
  40. vtptr object1_vtptr = get_vtptr(object1_ptr);
  41. vtptr object2_vtptr = get_vtptr(object2_ptr);
  42. set_vptr(object1_ptr, object2_vtptr);
  43. set_vptr(object2_ptr, object1_vtptr);
  44. }
  45. main()
  46. {
  47. int prev_counter;
  48. counter = 0;
  49. bp->inc();
  50. dp->inc();
  51. dbp->inc();
  52. assert(counter == (TPID + 10*TPID + 10*TPID));
  53. prev_counter = counter;
  54. printf("before ex bp vptr=%x dp vptr=%x\n", get_vtptr(bp), get_vtptr(dp));
  55. exchange_vtptr(bp, dp);
  56. printf("after ex bp vptr=%x dp vptr=%x\n", get_vtptr(bp), get_vtptr(dp));
  57. bp->inc(); // This one should not abort but it is calling the wrong member
  58. assert(counter == (prev_counter + 10*TPID));
  59. printf("Pass first attack! Expected!\n");
  60. printf("TPDI=%d counter %d\n", TPID, counter);
  61. dp->inc();
  62. printf("Pass second attack! SHOULD NOT BE HERE!\n");
  63. printf("TPDI=%d counter %d\n", TPID, counter);
  64. exit(1);
  65. }