Saturday, July 3, 2010

Access to private members. That's easy!

So, always thought that it's impossible without undefined behavior to access private members of arbitrary classes without being friend.

Today I noticed I've been horribly wrong, after reading some insightful commit to the clang compiler, that enabled it to allow explicit instantiation to disregard accessibilities, as per the Standard. This enables us to access private members of others. As an experiment, I created some class templates

template<typename Tag>
struct result {
  /* export it ... */
  typedef typename Tag::type type;
  static type ptr;
};

template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;

template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
  /* fill it ... */
  struct filler {
    filler() { result<Tag>::ptr = p; }
  };
  static filler filler_obj;
};

template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;

So, how is it used? Let's have an example

struct A {
private:
  void f() {
    std::cout << "proof!" << std::endl;
  }
};

struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;

Ah, that's all to expose poor A's "f" member. Now anyone can use them using the member pointer snytax, as does the main function below

int main() {
  A a;
  (a.*result<Af>::ptr)();
}

Of course, as Herb Sutter told us, don't do these things in real code.

81 comments:

  1. I recently started to think whether enforcing privateness is really a good thing. It can be useful to have access to private variables if you are debugging with printf statements. Or when you are dealing with badly designed legacy code. If we can have a const_cast, then why not a "private_cast"?

    ReplyDelete
  2. Can you give the corresponding revision number of clang ?

    ReplyDelete
  3. I think you're forgetting that C++ is not an object-oriented language. It is a language that supports many object-oriented idioms.

    I can think of several ways of accessing a private method in C++. Off the top of my head:

    - Function Pointers
    - Friend classes / functions.
    - static member functions.
    - copy constructors / assignment operators (allow access to private members of rhs if it's the same type).
    - Just make it public(!)

    I always view privacy as something to help other programmers. If something is private, I'm saying to any other programmer 'please don't interfere with this stuff when using this class'.

    Of course they can still change it if they want to, but they have to consciously make that decision which means they will more likely be aware of the consequences of doing so.

    ReplyDelete
  4. i like to use #define private public and #define protected public

    ReplyDelete
  5. Guys, Herb Sutter says "This isn't actually a problem. The issue here is of protecting against Murphy vs. protecting against Machiavelli... that is, protecting against accidental misuse (which the language does very well) vs. protecting against deliberate abuse (which is effectively impossible). In the end, if a programmer wants badly enough to subvert the system, he'll find a way, as demonstrated above in Examples 1 to 3.". You do *not* want to do this at home. You also do want to notice: This blog demonstrates a way that your compiler will have to support in order to be a C++ compiler. Any #define hacks and the-like are not guaranteed to work.

    ReplyDelete
  6. Wow. Any chance of posting a follow-up to explain a little more what is going on? Does the function pointer declaration typedef void(A::*type)() need to match the private method you are trying to access?

    ReplyDelete
  7. Applying this method to virtual functions one may only call final overriding method of the object's type, ancestor methods are not accessible.

    E.g.:

    struct A {
    private:
    virtual void f() {
    std::cout << "proof!" << std::endl;
    }
    };

    struct B: public A {
    private:
    virtual void f() {
    std::cout << "not proof!" << std::endl;
    }
    };

    struct Af { typedef void(A::*type)(); };
    template class rob;

    int main() {
    B a;
    (a.*result::ptr)();
    }

    would print "not proof!" (B::f), although we'd like to see "proof!" (A::f).

    ReplyDelete
  8. sorry, but I got a compile error
    VS 2008
    : error C2248: 'A::f' : cannot access private member declared in class 'A'

    ReplyDelete
  9. Spending some time cleaning this up and simplifying it... it looks like derivation of rob from result is superfluous.

    ReplyDelete
  10. Having analyzed and rewritten the code it turns out I ended up very close to where you started! Here's my version including explanatory comments: https://gist.github.com/1528856

    ReplyDelete
  11. very nice. but it won't work if A::f() is overloaded.

    ReplyDelete
  12. well, I have to swallow my own words -- it actually works even with overloaded functions, if you use the RIGHT compiler :) GCC handles it well, whereas MSVC complains about not being able to access private member...

    ReplyDelete
  13. Thank you for the solution! private QCheckListItem::setState(int,bool,bool) in Qt3 has the complexity > O^2 when the checkbox parent is the checkbox controller when legally called

    ReplyDelete
  14. Nice ...

    And ideas how this could be extended to also access private _static_ members?

    ReplyDelete
  15. Found out how to do it with static members myself:

    struct A {
    private:
    static void f() {
    std::cout << "proof!" << std::endl;
    }
    };

    struct Af { typedef void(*type)(); };
    template class rob;

    int main() {
    A a;
    (*result::ptr)();
    }

    ReplyDelete
  16. I get segfaults with gcc and clang (https://wandbox.org/permlink/CWeIkBwi95eSpLPK). Clang spits out a couple of warnings in addition.
    Am I missing something how to get this working?

    ReplyDelete
  17. Yes, in real code we just cast to void* and access the VTable index manually. It's also easier to understand what's happening.

    ReplyDelete
  18. This is what I get on that page, Nice Post and Appreciated your support. Thank you so much for sharing such a detailed information. We are proud that clients hold against using our moving company.
    movers and packers
    movers

    ReplyDelete
  19. Thanks you
    100% Guaranteed Services
    We can provide the Fast and reliable 100% Guaranteed Services within the agreement. Our work will be satisfied to you.Movers and Packers in Dubai Movers and Packers in DubaiMovers and Packers in Dubai

    ReplyDelete
  20. Great...!I Really Really Thanks to you Experts blog writer I like it and same as one of our blog like
    Movers and Packers in Dubai

    ReplyDelete
  21. Movers and packers in Dubai our expert movers and packers in Dubai are in a function to p. C. Pass any form of gadgets from any type of services within the metropolis with modern-day generation. Ali movers with its greatly accelerated community of relocation cars, storehouses hard work workplace now offers the subsequent offerings in dubai. Movers and packers in dubai are you looking for a expert shifting shifting agency. A transferring business enterprise that may offer low priced, reliable and moreover nicely timed packing and moving offerings inside the uae.Thanks to you Experts blog writer I like it and same as one of our blog like Movers and Packers in Dubai

    Movers and Packers in Dubai

    House Moving Companies in Dubai
    http://moverspackers-dubai.com/2019/01/26/movers-and-packers-in-dubai

    ReplyDelete
  22. as a Head office with branches network in Dubai Sharjah Abu dhabi Ajman Al ain. We have skilled team /staff of Packers /Managers to assist for all your packing and moving needs, Customs clearing agent, Freight Forwarding Service, Goods transportation, House shifting and relocation, Cargo services Movers and Packers in Dubai

    Movers and Packers in Dubaihttps://moversandpackersdubai.com/category/movers-and-packers-in-dubai/

    House Moving Company in Dubai
    https://moversandpackersdubai.com/category/house-movers-and-packers-in-dubai/

    ReplyDelete
  23. Dear Vistors Actully This Is the Link About House Office And Villa, Apartment Studio household Stuff Moving Shifting One Place To Other So Totaly You Understod If You Are Intrested Than Click On The Link And Go On Our Wbe Site Professional Sh Movers Than Read More About Us This Link About Movers And packers In Dubai ServicesProfessional Movers And Packers In Dubai

    ReplyDelete
  24. Beautiful blog post. Please follow our site links
    https://Dubaimoverscompany.com/
    Https://trendmoversdubai.com/
    WWW.TRENDMOVERSDUBAI.COM

    ReplyDelete
  25. Saba movers are the leading cargo movers in Dubai that provide a wide range of cargo moving services to its clients at competitive prices

    ReplyDelete
  26. "I wish I had the words to describe how amazing this photo is. Simply stunning

    ReplyDelete
  27. This view is giving me major wanderlust. I need to plan a trip ASAP!"

    ReplyDelete
  28. "Digital marketing allows for personalized and tailored communication with customers."

    ReplyDelete
  29. Digital marketing is an ongoing process that requires constant monitoring and optimization."

    ReplyDelete
  30. This photo brings back memories of my own travels. It's incredible how images can evoke such emotions."

    ReplyDelete
  31. "Nature never ceases to amaze me. This photo captures its beauty perfectly."

    ReplyDelete
  32. "I am to describe how amazing this photo is. Simply stunning!"

    ReplyDelete
  33. This bedroom furniture set exudes elegance and sophistication. Its clean lines and luxurious materials create a serene and inviting atmosphere."

    ReplyDelete
  34. wish I could be there right now. This place looks like a dream!

    ReplyDelete
  35. "I love how the colors in this picture blend so beautifully. Mother Nature is an artist

    ReplyDelete
  36. Hats off to the team behind this outstanding website!"

    ReplyDelete
  37. Appreciating the user-centric approach and responsiveness."

    ReplyDelete
  38. 20. "A big thank you to the creators for sharing their expertise with us!"

    ReplyDelete
  39. The Earth's well-being is intricately connected to our own well-being."

    ReplyDelete
  40. "Mother Nature deserves our utmost respect and protection."

    ReplyDelete
  41. Conservation efforts today will shape a greener world for generations to come."

    ReplyDelete
  42. "I'm in awe of the natural wonders our world has to offer. This photo is a true testament to that."

    ReplyDelete
  43. You have an eye for capturing beauty. Keep sharing these amazing photos with us!"

    ReplyDelete
  44. "You have an eye for capturing beauty. Keep sharing these amazing photos with us

    ReplyDelete


  45. "I've never seen anything like this before. Thanks for sharing this unique perspective!"

    ReplyDelete
  46. Wow, this picture is absolutely stunning

    ReplyDelete
  47. The world is full of hidden gems, and this photo just uncovered one. Absolutely mesmerizing!"

    ReplyDelete
  48. This photo reminds me why I love exploring and discovering new places. Thanks for the inspiration!"

    ReplyDelete
  49. Wow, this picture is absolutely stunning!

    ReplyDelete
  50. Nature never ceases to amaze me. This photo captures its beauty perfectly."

    ReplyDelete
  51. "I love how the colors in this picture blend so beautifully. Mother Nature is an artist!"

    ReplyDelete
  52. "I can almost hear the sound of waves crashing just by looking at this picture.

    ReplyDelete
  53. Bruhhhhhh you're excellent content writer"This place looks so peaceful and serene. I could spend hours just soaking in the beauty."

    ReplyDelete
  54. Bruhhhhhh you're excellent content writer

    ReplyDelete
  55. The world is full of incredible places, and this is definitely one of them. Thanks for sharing!"

    ReplyDelete
  56. "I can't get over how clear the water is in this picture. It's like paradise

    ReplyDelete
  57. Navigating the World of Decentralized Finance Safely and Seamlessly**

    ReplyDelete
  58. In the rapidly expanding landscape of blockchain and cryptocurrency

    ReplyDelete
  59. and a web3 interface that allows users to interact with blockchain-based.

    ReplyDelete
  60. providing a user-friendly interface for both beginners and .

    ReplyDelete
  61. What sets Metamask apart is its focus on .

    ReplyDelete
  62. At its core, Metamask is a cryptocurrency wallet.

    ReplyDelete
  63. **Unveiling the New Twitter Logo X: A Bold Step into the Future**

    ReplyDelete
  64. applications using a browser extension or mobile app.

    ReplyDelete
  65. Whoa, talk about #travelgoals! Adding this to my bucket list for sure."

    ReplyDelete
  66. This place looks so peaceful and serene. I could spend hours just soaking in the beauty."

    ReplyDelete
  67. "I can't get over how clear the water is in this picture. It's like paradise!"

    ReplyDelete
  68. I can't get over how clear the water is in this picture. It's like paradise!"

    ReplyDelete
  69. I was facing the same problem with my company website Mili Movers but now going well after some changes

    ReplyDelete
  70. Here's a even more straightforward implementation, with better encapsulations & use cases:
    https://github.com/YunHsiao/UnrealSourceInjector/blob/main/SourcePatch/Runtime/Core/Public/Misc/PrivateAccessor.h

    ReplyDelete
  71. This comment has been removed by the author.

    ReplyDelete