Cast structs with certain common members - c++

Lets say I have 2 structs:
typedef struct
{
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
} tstr1
and
typedef struct
{
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
} tstr2
I will only need the useThis member inside a function, but in some cases I will need to cast one struct or the other:
void someFunction()
{
someStuff();
SOMETHING MyInstance;
if(someVariable)
{
MyInstance = reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE); //This line of course doesn't work
}
else
{
MyInstance = reinterpret_cast<tstr2*>(INFO_FROM_HARDWARE); //This line of course doesn't work
}
MyInstance->useThis; //Calling this memeber with no problem
moreStuff();
}
So I want to use useThis no matter what cast was done. How can this be done?
I want to avoid someFunction() to be template (just to avoid this kind of things)
Note tha questions like this have a kind of similar problem but the struct members have the same order
EDIT:
In RealLife these structs are way larger and have several "same named" members. Directly casting a uint8_t as reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis would be tedious and require several reinterpret_casts (althought it's a working solution for my question before this EDIT). This is why I insist on MyInstance being "complete".

This is what templates are for:
template<class tstr>
std::uint8_t
do_something(std::uint8_t* INFO_FROM_HARDWARE)
{
tstr MyInstance;
std::memcpy(&MyInstance, INFO_FROM_HARDWARE, sizeof MyInstance);
MyInstance.useThis; //Calling this memeber with no problem
// access MyInstance within the template
}
// usage
if(someVariable)
{
do_something<tstr1>(INFO_FROM_HARDWARE);
}
else
{
do_something<tstr2>(INFO_FROM_HARDWARE);
}
I want to avoid someFunction() to be template (just to avoid this kind of things)
Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
The linked problem isn't an issue for your use case because the potential set of template arguments is a finite set. The very next FAQ entry explains how: Use explicit instantiations of the template.

as suggested by AndyG, how about std::variant (there's no mention of the c++ standard you are using so maybe a c++17 solution is ok - also worth using <insert other variant implementation> if no c++17 available).
here's an example
std::variant knows what type is stored in it and you can use visit anytime you wish to use any of the members in there (snippet here for clarity):
// stolen from #eerrorika (sorry for that :( )
struct hardware {
uint8_t a = 'A';
uint8_t b = 'B';
uint8_t c = 'C';
uint8_t d = 'D';
};
struct tstr1 {
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
};
struct tstr2 {
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
};
// stuff
if(true)
{
msg = *reinterpret_cast<tstr1*>(&hw);
}
else
{
msg = *reinterpret_cast<tstr2*>(&hw);
}
std::visit(overloaded {
[](tstr1 const& arg) { std::cout << arg.useThis << ' '; },
[](tstr2 const& arg) { std::cout << arg.useThis << ' '; }
}, msg);
EDIT: you can also do a variant of pointers
EDIT2: forgot to escape some stuff...

Using virtual dispatch is usually not what you want when mapping to hardware but it is an alternative.
Example:
// define a common interface
struct overlay_base {
virtual ~overlay_base() = default;
virtual uint8_t& useThis() = 0;
virtual uint8_t& useThat() = 0;
};
template<class T>
class wrapper : public overlay_base {
public:
template<class HW>
wrapper(HW* hw) : instance_ptr(reinterpret_cast<T*>(hw)) {}
uint8_t& useThis() { return instance_ptr->useThis; }
uint8_t& useThat() { return instance_ptr->useThat; }
private:
T* instance_ptr;
};
With that, you can declare a base class pointer, assign it, and use after the if statement:
int main(int argc, char**) {
std::unique_ptr<overlay_base> MyInstance;
if(argc % 2) {
MyInstance.reset( new wrapper<tstr1>(INFO_FROM_HARDWARE) );
} else {
MyInstance.reset( new wrapper<tstr2>(INFO_FROM_HARDWARE) );
}
std::cout << MyInstance->useThis() << '\n';
std::cout << MyInstance->useThat() << '\n';
}
Demo
Explanation regarding my comment: "It works, but unless the compiler is really clever and can optimize away the virtual dispatch in your inner loops, it's going to be slower than if you actually take the time to type cast":
Think of virtual dispatch as having a lookup table (vtable) used at runtime (which is often what actually happens). When calling a virtual function, the program has to use that lookup table to find the address of the actual member function to call. When it's impossible to optimize away the lookup (as I made sure in my example above by using a value only available at runtime) it does take a few CPU cycles extra compared to what you'd get by doing a static cast.

A simple reference to the struct member might be what you need:
uint8_t &useThis=SomeVariable
?reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis
:reinterpret_cast<tstr2*>(INFO_FROM_HARDWARE)->useThis;

Related

Optimize destructors size away

I'm building a code for an embedded system and I'm trying to save as much binary space as necessary.
The code is for parsing a protocol (MQTT for what it's worth), where there are numerous packets type and they are all different, but share some common parts.
Currently, to simplify writing the code, I'm using this pattern :
template <PacketType type>
struct ControlPacket
{
FixedHeader<type> type;
VariableHeader<type> header;
Properties<type> props;
... and so on...
};
// Specialize for each type
template <>
struct FixedHeader<CONNECT>
{
uint8_t typeAndFlags;
PacketType getType() const { return static_cast<PacketType>(typeAndFlags >> 4); }
uint8 getFlags() const { return 0; }
bool parseType(const uint8_t * buffer, int len)
{
if (len < 1) return false;
typeAndFlags = buffer[0];
return true;
}
...
};
template <>
struct FixedHeader<PUBLISH>
{
uint8_t typeAndFlags;
PacketType getType() const { return static_cast<PacketType>(typeAndFlags >> 4); }
uint8 getFlags() const { return typeAndFlags & 0xF; }
bool parseType(const uint8_t * buffer, int len)
{
if (len < 1) return false;
typeAndFlags = buffer[0];
if (typeAndFlags & 0x1) return false; // Example of per packet specific check to perform
return true;
}
...
};
... For all packet types ...
This is working, and I'm now trying to reduce the binary impact of all those template specializations (else the code is almost duplicated 16 times)
So, I've came up to this paradigm:
// Store the most common implementation in a base class
struct FixedHeaderBase
{
uint8_t typeAndFlags;
virtual PacketType getType() { return static_cast<PacketType(typeAndFlags >> 4); }
virtual uint8 getFlags() { return 0; } // Most common code here
virtual bool parseType(const uint8_t * buffer, int len)
{
if (len < 1) return false;
typeAndFlags = buffer[0];
return true;
}
virtual ~FixedHeaderBase() {}
};
// So that most class ends up empty
template <>
struct FixedHeader<CONNECT> final : public FixedHeaderBase
{
};
// And specialize only the specific classes
template <>
struct FixedHeader<PUBLISH> final : public FixedHeaderBase
{
uint8 getFlags() const { return typeAndFlags & 0xF; }
bool parseType(const uint8_t * buffer, int len)
{
if (!FixedHeaderBase::parseType(buffer, len)) return false;
if (typeAndFlags & 0x1) return false; // Example of per packet specific check to perform
return true;
}
};
// Most of the code is shared here
struct ControlPacketBase
{
FixedHeaderBase & type;
...etc ...
virtual bool parsePacket(const uint8_t * packet, int packetLen)
{
if (!type.parseType(packet, packetLen)) return false;
...etc ...
}
ControlPacketBase(FixedHeaderBase & type, etc...) : type(type) {}
virtual ~ControlPacketBase() {}
};
// This is only there to tell which specific version to use for the generic code
template <PacketType type>
struct ControlPacket final : public ControlPacketBase
{
FixedHeader<type> type;
VariableHeader<type> header;
Properties<type> props;
... and so on...
ControlPacket() : ControlPacketBase(type, header, props, etc...) {}
};
This is working quite well and allows to shave a lot of the used binary code space. By the way, I'm using final here so the compiler could devirtualize, and I'm compiling without RTTI (obviously also with -Os and each function in its own section that are garbage collected).
However, when I inspect the symbol table size, I'm finding a lot of duplication on the destructors (all template instances are implementing a destructor which is clearly the same (same binary size) or empty).
Typically, I understand that ControlPacket<CONNECT> needs to call ~FixedHeader<CONNECT>() and that ControlPacket<PUBLISH> needs to call ~FixedHeader<PUBLISH>() upon destruction.
Yet, since all the destructor are virtual, is there a way that the specialization of ControlPacket avoid their destructors and instead have ControlPacketBase to destruct them virtually so that I don't ends up with 16 useless destructors but only one ?
It's worth pointing out that this is related to an optimization called "identical COMDAT folding", or ICF. This is a linker feature where identical functions (i.e., empty functions) are all merged into one.
Not every linker supports this, and not every linker is willing to do this (because the language says that different functions require different address), but your toolchain could have this. It would be fast and easy.
I'm going to assume your problem is reproduced with this toy example:
#include <iostream>
#include <memory>
#include <variant>
extern unsigned nondet();
struct Base {
virtual const char* what() const = 0;
virtual ~Base() = default;
};
struct A final : Base {
const char* what() const override {
return "a";
}
};
struct B final : Base {
const char* what() const override {
return "b";
}
};
std::unique_ptr<Base> parse(unsigned v) {
if (v == 0) {
return std::make_unique<A>();
} else if (v == 1) {
return std::make_unique<B>();
} else {
__builtin_unreachable();
}
}
const char* what(const Base& b) {
return b.what(); // virtual dispatch
}
const char* what(const std::unique_ptr<Base>& b) {
return what(*b);
}
int main() {
unsigned v = nondet();
auto packet = parse(v);
std::cout << what(packet) << std::endl;
}
The disassembly shows that both A::~A and B::~B have (multiple) listings, even though they are empty and identical. This is with = default and final.
If one removes virtual, then these vacuous definitions go away and we achieve the goal - but now when the unique_ptr deletes the object, we invoke undefined behavior.
We have three choices for leaving the destructor non-virtual while maintaining well-defined behavior, two of which are useful and one is not.
Non-useful: the first option is to use shared_ptr. This works because shared_ptr actually type-erases its deleter function (see this question), so at no point does it delete via the base. In other words, when you make a shared_ptr<T>(u) for some u deriving from T, the shared_ptr stores a function pointer to U::~U directly.
However, this type erasure simply reintroduces the problem and generates even more empty virtual destructors. See the modified toy example to compare. I'm mentioning this for completeness, in case you happen to already be putting these into shared_ptr's on the side.
Useful: the alternative is to avoid virtual dispatch for lifetime management, and use a variant. It's not really proper to make such a blanket statement, but generally you can achieve smaller code and even some speedup with tag dispatch, as you avoid specifying vtables and dynamic allocation.
This requires the largest change in your code, because the object representing your packet must be interacted with in a different way (it is no longer an is-a relationship):
#include <iostream>
#include <boost/variant.hpp>
extern unsigned nondet();
struct Base {
~Base() = default;
};
struct A final : Base {
const char* what() const {
return "a";
}
};
struct B final : Base {
const char* what() const {
return "b";
}
};
typedef boost::variant<A, B> packet_t;
packet_t parse(unsigned v) {
if (v == 0) {
return A();
} else if (v == 1) {
return B();
} else {
__builtin_unreachable();
}
}
const char* what(const packet_t& p) {
return boost::apply_visitor([](const auto& v){
return v.what();
}, p);
}
int main() {
unsigned v = nondet();
auto packet = parse(v);
std::cout << what(packet) << std::endl;
}
I used Boost.Variant because it produces the smallest code. Annoyingly, std::variant insists on producing some minor but present vtables for implementing itself - I feel like this defeats the purpose a bit, though even with the variant vtables the code remains much smaller overall.
I want to point out a nice result of modern optimizing compilers. Note the resulting implementation of what:
what(boost::variant<A, B> const&):
mov eax, DWORD PTR [rdi]
cdq
cmp eax, edx
mov edx, OFFSET FLAT:.LC1
mov eax, OFFSET FLAT:.LC0
cmove rax, rdx
ret
The compiler understands the closed set of options in the variant, the lambda duck-typing proved that each option really has a ...::what member function, and so it's really just picking out the string literal to return based on the variant value.
The trade-off with a variant is that you must have a closed set of options, and you no longer have a virtual interface enforcing certain functions exist. In return you get smaller code and the compiler can often see through the dispatch "wall".
However, if we define these simple visitor helper functions per "expected" member function, it acts as an interface checker - plus you've already got your helper class templates to keep things in line.
Finally, as an extension of the above: you are always free to maintain some virtual functions within the base class. This can offer the best of both worlds, if the cost of vtables is acceptable to you:
#include <iostream>
#include <boost/variant.hpp>
extern unsigned nondet();
struct Base {
virtual const char* what() const = 0;
~Base() = default;
};
struct A final : Base {
const char* what() const override {
return "a";
}
};
struct B final : Base {
const char* what() const override {
return "b";
}
};
typedef boost::variant<A, B> packet_t;
packet_t parse(unsigned v) {
if (v == 0) {
return A();
} else if (v == 1) {
return B();
} else {
__builtin_unreachable();
}
}
const Base& to_base(const packet_t& p) {
return *boost::apply_visitor([](const auto& v){
return static_cast<const Base*>(&v);
}, p);
}
const char* what(const Base& b) {
return b.what(); // virtual dispatch
}
const char* what(const packet_t& p) {
return what(to_base(p));
}
int main() {
unsigned v = nondet();
auto packet = parse(v);
std::cout << what(packet) << std::endl;
}
This produces fairly compact code.
What we have here is a virtual base class (but, no virtual destructor as it is not needed), and a to_base function that can take a variant and return for you the common base interface. (And in a hierarchy such as yours, you could have several of these per kind of base.)
From the common base you are free to perform virtual dispatch. This is sometimes easier to manage and faster depending on workload, and the additional freedom only costs some vtables. In this example, I've implemented what as first converting to the base class, and then perform virtual dispatch to the what member function.
Again, I want to point out the the definition of a visit, this time in to_base:
to_base(boost::variant<A, B> const&):
lea rax, [rdi+8]
ret
The compiler understands the closed set of classes all inherit from Base, and so doesn't have to actually examine any variant type tag at all.
In the above I used Boost.Variant. Not everyone can or wants to use Boost, but the principles of the answer still apply: store an object and track what type of object is stored in an integer. When it's time to do something, peek at the integer and jump to the right place in code.
Implementing a variant is a whole different question. :)

C++: can you force the access to a private member of a class? [duplicate]

Disclaimer
Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot. I'm mainly looking to see if can be done.
Now that that's out of the way, is there any way to access private class members in C++ from outside the class? For example, is there any way to do this with pointer offsets?
(Naive and otherwise non-production-ready techniques welcome)
Update
As noted in the comments, I asked this question because I wanted to write a blog post on over-encapsulation (and how it affects TDD). I wanted to see if there was a way to say "using private variables isn't a 100% reliable way to enforce encapsulation, even in C++." At the end, I decided to focus more on how to solve the problem rather than why it's a problem, so I didn't feature some of the stuff brought up here as prominently as I had planned, but I still left a link.
At any rate, if anyone's interested in how it came out, here it is: Enemies of Test Driven Development part I: encapsulation (I suggest reading it before you decide that I'm crazy).
If the class contains any template member functions you can specialize that member function to suit your needs. Even if the original developer didn't think of it.
safe.h
class safe
{
int money;
public:
safe()
: money(1000000)
{
}
template <typename T>
void backdoor()
{
// Do some stuff.
}
};
main.cpp:
#include <safe.h>
#include <iostream>
class key;
template <>
void safe::backdoor<key>()
{
// My specialization.
money -= 100000;
std::cout << money << "\n";
}
int main()
{
safe s;
s.backdoor<key>();
s.backdoor<key>();
}
Output:
900000
800000
I've added an entry to my blog (see below) that shows how it can be done. Here is an example on how you use it for the following class
struct A {
private:
int member;
};
Just declare a struct for it where you describe it and instantiate the implementation class used for robbery
// tag used to access A::member
struct A_member {
typedef int A::*type;
friend type get(A_member);
};
template struct Rob<A_member, &A::member>;
int main() {
A a;
a.*get(A_member()) = 42; // write 42 to it
std::cout << "proof: " << a.*get(A_member()) << std::endl;
}
The Rob class template is defined like this, and needs only be defined once, regardless how many private members you plan to access
template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};
However, this doesn't show that c++'s access rules aren't reliable. The language rules are designed to protect against accidental mistakes - if you try to rob data of an object, the language by-design does not take long ways to prevent you.
The following is sneaky, illegal, compiler-dependent, and may not work depending on various implementation details.
#define private public
#define class struct
But it is an answer to your OP, in which you explicitly invite a technique which, and I quote, is "totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot".
Another technique is to access private member data, by contructing pointers using hard-coded/hand-coded offsets from the beginning of the object.
Hmmm, don't know if this would work, but might be worth a try. Create another class with the same layout as the object with private members but with private changed to public. Create a variable of pointer to this class. Use a simple cast to point this to your object with private members and try calling a private function.
Expect sparks and maybe a crash ;)
class A
{
int a;
}
class B
{
public:
int b;
}
union
{
A a;
B b;
};
That should do it.
ETA: It will work for this sort of trivial class, but as a general thing it won't.
TC++PL Section C.8.3: "A class with a constructor, destructor, or copy operation cannot be the type of a union member ... because the compiler would not know which member to destroy."
So we're left with the best bet being to declare class B to match A's layout and hack to look at a class's privates.
If you can get a pointer to a member of a class you can use the pointer no matter what the access specifiers are (even methods).
class X;
typedef void (X::*METHOD)(int);
class X
{
private:
void test(int) {}
public:
METHOD getMethod() { return &X::test;}
};
int main()
{
X x;
METHOD m = x.getMethod();
X y;
(y.*m)(5);
}
Of course my favorite little hack is the friend template back door.
class Z
{
public:
template<typename X>
void backDoor(X const& p);
private:
int x;
int y;
};
Assuming the creator of the above has defined backDoor for his normal uses. But you want to access the object and look at the private member variables. Even if the above class has been compiled into a static library you can add your own template specialization for backDoor and thus access the members.
namespace
{
// Make this inside an anonymous namespace so
// that it does not clash with any real types.
class Y{};
}
// Now do a template specialization for the method.
template<>
void Z::backDoor<Y>(Y const& p)
{
// I now have access to the private members of Z
}
int main()
{
Z z; // Your object Z
// Use the Y object to carry the payload into the method.
z.backDoor(Y());
}
It's definately possible to access private members with a pointer offset in C++. Lets assume i had the following type definition that I wanted access to.
class Bar {
SomeOtherType _m1;
int _m2;
};
Assuming there are no virtual methods in Bar, The easy case is _m1. Members in C++ are stored as offsets of the memory location of the object. The first object is at offset 0, the second object at offset of sizeof(first member), etc ...
So here is a way to access _m1.
SomeOtherType& GetM1(Bar* pBar) {
return*(reinterpret_cast<SomeOtherType*>(pBar));
}
Now _m2 is a bit more difficult. We need to move the original pointer sizeof(SomeOtherType) bytes from the original. The cast to char is to ensure that I am incrementing in a byte offset
int& GetM2(Bar* pBar) {
char* p = reinterpret_cast<char*>(pBar);
p += sizeof(SomeOtherType);
return *(reinterpret_cast<int*>(p));
}
This answer is based on the exact concept demonstrated by #Johannes's answer/blog, as that seems to be the only "legitimate" way. I have converted that example code into a handy utility. It's easily compatible with C++03 (by implementing std::remove_reference & replacing nullptr).
Library
#define CONCATE_(X, Y) X##Y
#define CONCATE(X, Y) CONCATE_(X, Y)
#define ALLOW_ACCESS(CLASS, MEMBER, ...) \
template<typename Only, __VA_ARGS__ CLASS::*Member> \
struct CONCATE(MEMBER, __LINE__) { friend __VA_ARGS__ CLASS::*Access(Only*) { return Member; } }; \
template<typename> struct Only_##MEMBER; \
template<> struct Only_##MEMBER<CLASS> { friend __VA_ARGS__ CLASS::*Access(Only_##MEMBER<CLASS>*); }; \
template struct CONCATE(MEMBER, __LINE__)<Only_##MEMBER<CLASS>, &CLASS::MEMBER>
#define ACCESS(OBJECT, MEMBER) \
(OBJECT).*Access((Only_##MEMBER<std::remove_reference<decltype(OBJECT)>::type>*)nullptr)
API
ALLOW_ACCESS(<class>, <member>, <type>);
Usage
ACCESS(<object>, <member>) = <value>; // 1
auto& ref = ACCESS(<object>, <member>); // 2
Demo
struct X {
int get_member () const { return member; };
private:
int member = 0;
};
ALLOW_ACCESS(X, member, int);
int main() {
X x;
ACCESS(x, member) = 42;
std::cout << "proof: " << x.get_member() << std::endl;
}
If you know how your C++ compiler mangles names, yes.
Unless, I suppose, it's a virtual function. But then, if you know how your C++ compiler builds the VTABLE ...
Edit: looking at the other responses, I realize that I misread the question and thought it was about member functions, not member data. However, the point still stands: if you know how your compiler lays out data, then you can access that data.
cool question btw... here's my piece:
using namespace std;
class Test
{
private:
int accessInt;
string accessString;
public:
Test(int accessInt,string accessString)
{
Test::accessInt=accessInt;
Test::accessString=accessString;
}
};
int main(int argnum,char **args)
{
int x;
string xyz;
Test obj(1,"Shit... This works!");
x=((int *)(&obj))[0];
xyz=((string *)(&obj))[1];
cout<<x<<endl<<xyz<<endl;
return 0;
}
Hope this helps.
As an alternative to template backdoor method you can use template backdoor class. The difference is that you don't need to put this backdoor class into public area of the class your are going to test. I use the fact that many compilers allow nested classes to access private area of enclosing class (which is not exactly 1998 standard but considered to be "right" behaviour). And of course in C++11 this became legal behaviour.
See this example:
#include <vector>
#include <cassert>
#include <iostream>
using std::cout;
using std::endl;
///////// SystemUnderTest.hpp
class SystemUnderTest
{
//...put this 'Tested' declaration into private area of a class that you are going to test
template<typename T> class Tested;
public:
SystemUnderTest(int a): a_(a) {}
private:
friend std::ostream& operator<<(std::ostream& os, const SystemUnderTest& sut)
{
return os << sut.a_;
}
int a_;
};
/////////TestFramework.hpp
class BaseTest
{
public:
virtual void run() = 0;
const char* name() const { return name_; }
protected:
BaseTest(const char* name): name_(name) {}
virtual ~BaseTest() {}
private:
BaseTest(const BaseTest&);
BaseTest& operator=(const BaseTest&);
const char* name_;
};
class TestSuite
{
typedef std::vector<BaseTest*> Tests;
typedef Tests::iterator TIter;
public:
static TestSuite& instance()
{
static TestSuite TestSuite;
return TestSuite;
}
void run()
{
for(TIter iter = tests_.begin(); tests_.end() != iter; ++iter)
{
BaseTest* test = *iter;
cout << "Run test: " << test->name() << endl;
test->run();
}
}
void addTest(BaseTest* test)
{
assert(test);
cout << "Add test: " << test->name() << endl;
tests_.push_back(test);
}
private:
std::vector<BaseTest*> tests_;
};
#define TEST_CASE(SYSTEM_UNDER_TEST, TEST_NAME) \
class TEST_NAME {}; \
template<> \
class SYSTEM_UNDER_TEST::Tested<TEST_NAME>: public BaseTest \
{ \
Tested(): BaseTest(#SYSTEM_UNDER_TEST "::" #TEST_NAME) \
{ \
TestSuite::instance().addTest(this); \
} \
void run(); \
static Tested instance_; \
}; \
SYSTEM_UNDER_TEST::Tested<TEST_NAME> SYSTEM_UNDER_TEST::Tested<TEST_NAME>::instance_; \
void SYSTEM_UNDER_TEST::Tested<TEST_NAME>::run()
//...TestSuiteForSystemUnderTest.hpp
TEST_CASE(SystemUnderTest, AccessPrivateValueTest)
{
SystemUnderTest sut(23);
cout << "Changed private data member from " << sut << " to ";
sut.a_ = 12;
cout << sut << endl;
}
//...TestRunner.cpp
int main()
{
TestSuite::instance().run();
}
Beside #define private public you can also #define private protected and then define some foo class as descendant of wanted class to have access to it's (now protected) methods via type casting.
just create your own access member function to extend the class.
To all the people suggesting "#define private public":
This kind of thing is illegal. The standard forbids defining/undef-ing macros that are lexically equivalent to reserved language keywords. While your compiler probably won't complain (I've yet to see a compiler that does), it isn't something that's a "Good Thing" to do.
It's actually quite easy:
class jail {
int inmate;
public:
int& escape() { return inmate; }
};
"using private variables isn't a 100% reliable way to enforce encapsulation, even in C++."
Really? You can disassemble the library you need, find all the offsets needed and use them.
That will give you an ability to change any private member you like... BUT!
You can't access private members without some dirty hacking.
Let us say that writing const won't make your constant be really constant, 'cause you can
cast const away or just use it's address to invalidate it. If you're using MSVC++ and you specified "-merge:.rdata=.data" to a linker, the trick will work without any memory access faults.
We can even say that writing apps in C++ is not reliable way to write programs, 'cause resulting low level code may be patched from somewhere outside when your app is running.
Then what is reliable documented way to enforce encapsulation? Can we hide the data somewhere in RAM and prevent anything from accessing them except our code? The only idea I have is to encrypt private members and backup them, 'cause something may corrupt those members.
Sorry if my answer is too rude, I didn't mean to offend anybody, but I really don't think that statement is wise.
since you have an object of required class I am guessing that you have declaration of class.
Now what you can do is declare another class with same members but keep all of there access specifiers as public.
For example previous class is:
class Iamcompprivate
{
private:
Type1 privateelement1;
Typ2 privateelement2;
...
public:
somefunctions
}
you can declare a class as
class NowIampublic
{
**public:**
Type1 privateelement1;
Type2 privateelement2;
...
somefunctions
};
Now all you need to do is cast pointer of class Iamcompprivate into an pointer of class NowIampublic and use them as U wish.
Example:
NowIampublic * changetopublic(Iamcompprivate *A)
{
NowIampublic * B = (NowIampublic *)A;
return B;
}
By referencing to *this you enable a backdoor to all private data within an object.
class DumbClass
{
private:
int my_private_int;
public:
DumbClass& backdoor()
{
return *this;
}
}
Quite often a class provides mutator methods to private data (getters and setters).
If a class does provide a getter that returns a const reference (but no setter), then you can just const_cast the return value of the getter, and use that as an l-value:
class A {
private:
double _money;
public:
A(money) :
_money(money)
{}
const double &getMoney() const
{
return _money;
}
};
A a(1000.0);
const_cast<double &>(a.getMoney()) = 2000.0;
I've used another useful approach (and solution) to access a c++ private/protected member.
The only condition is that you are able to inherit from the class you want to access.
Then all credit goes to reinterpret_cast<>().
A possible problem is that it won't work if you insert a virtual function, which will modify virtual table, and so, object size/alignment.
class QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE(QObject)
void dumpObjectInfo();
void dumpObjectTree();
...
protected:
QScopedPointer<QObjectData> d_ptr;
...
}
class QObjectWrapper : public QObject
{
public:
void dumpObjectInfo2();
void dumpObjectTree2();
};
Then you just need to use the class as follows:
QObject* origin;
QObjectWrapper * testAccesor = reinterpret_cast<QObjectWrapper *>(origin);
testAccesor->dumpObjectInfo2();
testAccesor->dumpObjectTree2();
My original problem was as follows: I needed a solution that won't imply recompiling QT libraries.
There are 2 methods in QObject, dumpObjectInfo() and dumpObjectTree(), that
just work if QT libs are compiled in debug mode, and they of course need access to d_ptr proteted member (among other internal structures).
What I did was to use the proposed solution to reimplement (with copy and paste) those methods in dumpObjectInfo2() and dumpObjectTree2() in my own class (QObjectWrapper) removing those debug preprocesor guards.
The following code accesses and modifies a private member of the class using a pointer to that class.
#include <iostream>
using namespace std;
class A
{
int private_var;
public:
A(){private_var = 0;}//initialized to zero.
void print(){cout<<private_var<<endl;}
};
int main()
{
A ob;
int *ptr = (int*)&ob; // the pointer to the class is typecast to a integer pointer.
(*ptr)++; //private variable now changed to 1.
ob.print();
return 0;
}
/*prints 1. subsequent members can also be accessed by incrementing the pointer (and
type casting if necessary).*/
study purpose only....
try this ....may be helpfull i guess.....
this program can access the private data just by knowing the values...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
Inspired by #Johannes Schaub - litb, the following code may be a bit easier to digest.
struct A {
A(): member(10){}
private:
int get_member() { return member;}
int member;
};
typedef int (A::*A_fm_ptr)();
A_fm_ptr get_fm();
template< A_fm_ptr p>
struct Rob{
friend A_fm_ptr get_fm() {
return p;
}
};
template struct Rob< &A::get_member>;
int main() {
A a;
A_fm_ptr p = get_fm();
std::cout << (a.*p)() << std::endl;
}
Well, with pointer offsets, it's quite easy. The difficult part is finding the offset:
other.hpp
class Foo
{
public:
int pub = 35;
private:
int foo = 5;
const char * secret = "private :)";
};
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include "other.hpp"
unsigned long long getPrivOffset(
const char * klass,
const char * priv,
const char * srcfile
){
std::ifstream read(srcfile);
std::ofstream write("fork.hpp");
std::regex r ("private:");
std::string line;
while(getline(read, line))
// make all of the members public
write << std::regex_replace(line, r, "public:") << '\n';
write.close();
read.close();
// find the offset, using the clone object
std::ofstream phony("phony.cpp");
phony <<
"#include <iostream>\n"
"#include <fstream>\n"
"#include \"fork.hpp\"\n"
"int main() {\n";
phony << klass << " obj;\n";
// subtract to find the offset, the write it to a file
phony <<
"std::ofstream out(\"out.txt\");\n out << (((unsigned char *) &(obj."
<< priv << ")) -((unsigned char *) &obj)) << '\\n';\nout.close();";
phony << "return 0;\n}";
phony.close();
system(
"clang++-7 -o phony phony.cpp\n"
"./phony\n"
"rm phony phony.cpp fork.hpp");
std::ifstream out("out.txt");
// read the file containing the offset
getline(out, line);
out.close();
system("rm out.txt");
unsigned long long offset = strtoull(line.c_str(), NULL, 10);
return offset;
}
template <typename OutputType, typename Object>
OutputType hack(
Object obj,
const char * objectname,
const char * priv_method_name,
const char * srcfile
) {
unsigned long long o = getPrivOffset(
objectname,
priv_method_name,
srcfile
);
return *(OutputType *)(((unsigned char *) (&obj)+o));
}
#define HACK($output, $object, $inst, $priv, $src)\
hack <$output, $object> (\
$inst,\
#$object,\
$priv,\
$src)
int main() {
Foo bar;
std::cout << HACK(
// output type
const char *,
// type of the object to be "hacked"
Foo,
// the object being hacked
bar,
// the desired private member name
"secret",
// the source file of the object's type's definition
"other.hpp"
) << '\n';
return 0;
}
clang++ -o main main.cpp
./main
output:
private :)
You could also use reinterpret_cast.
Maybe some pointer arithmetics can do it
#pragma pack(1)
class A
{
int x{0};
char c{0};
char s[8]{0};
public:
void display()
{
print(x);
print(c);
print(s);
};
};
int main(void)
{
A a;
int *ptr2x = (int *)&a;
*ptr2x = 10;
char *ptr2c = (char *)ptr2x+4;
*ptr2c = 'A';
char *ptr2s = (char *)ptr2c+1;
strcpy(ptr2s ,"Foo");
a.display();
}
class Test{
int a;
alignas(16) int b;
int c;
};
Test t;
method A : intrusive mood.
since we can access source code and recomplie it, we can use
many other way like friend class to access private member, they are all legal backdoor.
method B : brute mood.
int* ptr_of_member_c = reinterpret_cast<int*>(reinterpret_cast<char*>(&t) + 20);
we use a magic number (20) , and It's not always right. When the layout of class Test changed, the magic number is a big bug source.
method C : super hacker mood.
is there any non-intrusive and non-brute mood ?
since the class Test's layout infomation is hide by the complier,
we can not get offset information from the complie's mouth.
ex.
offsetof(Test,c); //complie error. they said can not access private member.
we also can not get member pointer from class Test.
ex.
&Test::c ; //complie error. they said can not access private member.
#Johannes Schaub - litb has a blog, he found a way to rob private member pointer.
but i thought this should be complier's bug or language pitfall.
i can complie it on gcc4.8, but not on vc8 complier.
so the conclusion may be :
the landlord build all backdoor.
the thief always has brute and bad way to break into.
the hacker accidental has elegant and automated way to break into.
I made Johannes answer more generic. You can get the source here: https://github.com/lackhole/Lupin
All you have to know is just the name of the class and the member.
You can use like,
#include <iostream>
#include "access/access.hpp"
struct foo {
private:
std::string name = "hello";
int age = 27;
void print() {}
};
using tag_foo_name = access::Tag<class foo_name>;
template struct access::Accessor<tag_foo_name, foo, decltype(&foo::name), &foo::name>;
int main() {
foo f;
// peek hidden data
std::cout << access::get<tag_foo_name>(f) << '\n'; // "hello"
// steal hidden data
access::get<tag_foo_name>(f) = "lupin";
std::cout << access::get<tag_foo_name>(f) << '\n'; // "lupin"
}
Call private functions, get the type of private members is also possible with only using the tag.

How to do the equivalent of memset(this, ...) without clobbering the vtbl?

I know that memset is frowned upon for class initialization. For example, something like the following:
class X { public:
X() { memset( this, 0, sizeof(*this) ) ; }
...
} ;
will clobber the vtbl if there's a virtual function in the mix.
I'm working on a (humongous) legacy codebase that is C-ish but compiled in C++, so all the members in question are typically POD and require no traditional C++ constructors. C++ usage gradually creeps in (like virtual functions), and this bites the developers that don't realize that memset has these additional C++ teeth.
I'm wondering if there is a C++ safe way to do an initial catch-all zero initialization, that could be followed by specific by-member initialization where zero initialization isn't appropriate?
I find the similar questions memset for initialization in C++, and zeroing derived struct using memset. Both of these have "don't use memset()" answers, but no good alternatives (esp. for large structures potentially containing many many members).
For each class where you find a memset call, add a memset member function which ignores the pointer and size arguments and does assignments to all the data members.
edit:
Actually, it shouldn't ignore the pointer, it should compare it to this. On a match, do the right thing for the object, on a mismatch, reroute to the global function.
You could always add constructors to these embedded structures, so they clear themselves so to speak.
Try this:
template <class T>
void reset(T& t)
{
t = T();
}
This will zeroed your object - no matter it is POD or not.
But do not do this:
A::A() { reset(*this); }
This will invoke A::A in infinite recursion!!!
Try this:
struct AData { ... all A members };
class A {
public:
A() { reset(data); }
private:
AData data;
};
This is hideous, but you could overload operator new/delete for these objects (or in a common base class), and have the implementation provide zero'd out buffers. Something like this :
class HideousBaseClass
{
public:
void* operator new( size_t nSize )
{
void* p = malloc( nSize );
memset( p, 0, nSize );
return p;
}
void operator delete( void* p )
{
if( p )
free( p );
}
};
One could also override the global new/delete operators, but this could have negative perf implications.
Edit: I just realized that this approach won't work for stack allocated objects.
Leverage the fact that a static instance is initialised to zero:
https://ideone.com/GEFKG0
template <class T>
struct clearable
{
void clear()
{
static T _clear;
*((T*)this) = _clear;
};
};
class test : public clearable<test>
{
public:
int a;
};
int main()
{
test _test;
_test.a=3;
_test.clear();
printf("%d", _test.a);
return 0;
}
However the above will cause the constructor (of the templatised class) to be called a second time.
For a solution that causes no ctor call this can be used instead: https://ideone.com/qTO6ka
template <class T>
struct clearable
{
void *cleared;
clearable():cleared(calloc(sizeof(T), 1)) {}
void clear()
{
*((T*)this) = *((T*)cleared);
};
};
...and if you're using C++11 onwards the following can be used: https://ideone.com/S1ae8G
template <class T>
struct clearable
{
void clear()
{
*((T*)this) = {};
};
};
The better solution I could find is to create a separated struct where you will put the members that must be memsetted to zero. Not sure if this design is suitable for you.
This struct got no vtable and extends nothings. It will be just a chunk of data. This way memsetting the struct is safe.
I have made an example:
#include <iostream>
#include <cstring>
struct X_c_stuff {
X_c_stuff() {
memset(this,0,sizeof(this));
}
int cMember;
};
class X : private X_c_stuff{
public:
X()
: normalMember(3)
{
std::cout << cMember << normalMember << std::endl;
}
private:
int normalMember;
};
int main() {
X a;
return 0;
}
You can use pointer arithmetic to find the range of bytes you want to zero out:
class Thing {
public:
Thing() {
memset(&data1, 0, (char*)&lastdata - (char*)&data1 + sizeof(lastdata));
}
private:
int data1;
int data2;
int data3;
// ...
int lastdata;
};
(Edit: I originally used offsetof() for this, but a comment pointed out that this is only supposed to work on PODs, and then I realised that you can just use the member addresses directly.)

Is it possible to generate constant value during compilation?

I would like my classes to be identified each type by an unique hash code. But I don't want these hashed to be generated every time a method, eg. int GetHashCode(), is invoked during runtime. I'd like to use already generated constants and I was hoping there is a way to make the compiler do some come computing and set these constants. Can it be done using templates? Could you give me some example, if it is possible.
UPDATE:
Thanks to kriss' comment I realized my question should go like this:
How to do the type checking with the lowest runtime cost possible?
I'd like to check a pointer to an object against a class type. Just the classes I implement in my libs, so I was thinking of some custom hashing, thus the original question. I did consider using typeid but I am unaware of the runtime cost of using it. I made an assumption that since typeid produces a type_info class that would be more consuming than simple comparision of unique int values.
You can do it with boost.MPL.
I would go simple route:
For classes that would be static property - so just pick a number for each class.
For instances - just use the address.
Static const's are evaluated at compile time - which is pretty much the basis for metaprogramming at large. Moreover, type_info::hash_code is particularly adapted for your needs, so try -
class MyClass
{
static const size_t TypeHashCode = typeid(MyClass).hash_code();
...
}
(I'm not around a compiler right now, so this may take some refining. Will try and recheck tomorrow)
EDIT: indeed, it is not only MS specific but also added only in VS2010 - but hey, at least MS agrees this is a valid need. If you don't allow both VS2010 and boost in your code - you're pretty much left with the standard compliant facilities: typeid or dynamic_cast. They do incur some overhead, but I'd take extra care to verify this overhead is indeed a worthy battle. (my money goes to - not.)
All such classes share something common. Then why not add a symbolic constant in a common enum for each one, you'll leave the enum give values for you, it's easier than giving explicit constants (you still have to declare each class in the enum).
template<class T>
struct provide_hash_code_for_class
{
public:
static uintptr_t GetHashCode()
{
return(reinterpret_cast<uintptr_t>(&unused));
}
private:
static void *unused;
};
template<class T>
void *provide_hash_code_for_class<T>::unused;
class MyClass : public provide_hash_code_for_class<MyClass>
{
};
int main()
{
std::cout << std::hex << MyClass::GetHashCode() << std::endl;
std::cout << std::hex << MyClass().GetHashCode() << std::endl;
return(0);
}
Please be aware that hash codes will change between runs so you can't rely on them for example for interprocess communication.
building on the simple route route by Nikolai N Fetissov:
For classes that would be static property - use the address of a function cast to an intptr_t to give a unique yet compiled-in value.
For instances - just use the address.
It is a pitty that there is no compile-time type hash_code supported by the standard. As a workaround, one can generate a compile time hash from the class name. An example below.
#include <stdint.h>
#include <string>
#include <vector>
#include <iostream>
#include <memory>
#include <cassert>
//Compile-time string hashing.
class HashedString
{
public:
typedef int64_t HashType;
explicit constexpr HashedString(const char* str): m_hash(hashString(str)) {}
static inline constexpr HashType hashString(const char* str)
{
return ( !str ? 0 : hashStringRecursive(5381, str));
}
static inline constexpr HashType hashStringRecursive(HashType hash, const char* str)
{
return ( !*str ? hash : hashStringRecursive(((hash << 5) + hash) + *str, str + 1));
}
const HashType m_hash;
};
struct EventBase
{
using IdType = HashedString::HashType;
virtual ~EventBase() {}
IdType getId() const { return m_eventId; } //present the runtime event id
EventBase(IdType myId) : m_eventId { myId } { }
template<class DerivedEvent>
const DerivedEvent* getAs() const
{
return dynamic_cast<const DerivedEvent*>(this);
}
protected:
const IdType m_eventId;
};
#define DEFINE_EVENT_ID(className) \
static constexpr IdType id = HashedString(#className).m_hash; \
struct SomeEvent1 : public EventBase
{
DEFINE_EVENT_ID(SomeEvent1);
SomeEvent1(int status) : EventBase(id), m_status { status } { assert(id == m_eventId); }
int m_status;
};
struct SomeEvent2 : public EventBase
{
DEFINE_EVENT_ID(SomeEvent2);
SomeEvent2() : EventBase(id) { assert(id == m_eventId); }
std::string m_s = "test event 2";
};
void testEvents()
{
std::vector<std::shared_ptr<EventBase>> events;
events.push_back(std::make_shared<SomeEvent1>(123));
events.push_back(std::make_shared<SomeEvent2>());
for (auto event : events) {
switch(event->getId()) {
case SomeEvent1::id:
std::cout << "SomeEvent1 " << event->getAs<SomeEvent1>()->m_status << std::endl;
break;
case SomeEvent2::id:
std::cout << "SomeEvent2 " << event->getAs<SomeEvent2>()->m_s << std::endl;
break;
}
}
}

Can I access private members from outside the class without using friends?

Disclaimer
Yes, I am fully aware that what I am asking about is totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot. I'm mainly looking to see if can be done.
Now that that's out of the way, is there any way to access private class members in C++ from outside the class? For example, is there any way to do this with pointer offsets?
(Naive and otherwise non-production-ready techniques welcome)
Update
As noted in the comments, I asked this question because I wanted to write a blog post on over-encapsulation (and how it affects TDD). I wanted to see if there was a way to say "using private variables isn't a 100% reliable way to enforce encapsulation, even in C++." At the end, I decided to focus more on how to solve the problem rather than why it's a problem, so I didn't feature some of the stuff brought up here as prominently as I had planned, but I still left a link.
At any rate, if anyone's interested in how it came out, here it is: Enemies of Test Driven Development part I: encapsulation (I suggest reading it before you decide that I'm crazy).
If the class contains any template member functions you can specialize that member function to suit your needs. Even if the original developer didn't think of it.
safe.h
class safe
{
int money;
public:
safe()
: money(1000000)
{
}
template <typename T>
void backdoor()
{
// Do some stuff.
}
};
main.cpp:
#include <safe.h>
#include <iostream>
class key;
template <>
void safe::backdoor<key>()
{
// My specialization.
money -= 100000;
std::cout << money << "\n";
}
int main()
{
safe s;
s.backdoor<key>();
s.backdoor<key>();
}
Output:
900000
800000
I've added an entry to my blog (see below) that shows how it can be done. Here is an example on how you use it for the following class
struct A {
private:
int member;
};
Just declare a struct for it where you describe it and instantiate the implementation class used for robbery
// tag used to access A::member
struct A_member {
typedef int A::*type;
friend type get(A_member);
};
template struct Rob<A_member, &A::member>;
int main() {
A a;
a.*get(A_member()) = 42; // write 42 to it
std::cout << "proof: " << a.*get(A_member()) << std::endl;
}
The Rob class template is defined like this, and needs only be defined once, regardless how many private members you plan to access
template<typename Tag, typename Tag::type M>
struct Rob {
friend typename Tag::type get(Tag) {
return M;
}
};
However, this doesn't show that c++'s access rules aren't reliable. The language rules are designed to protect against accidental mistakes - if you try to rob data of an object, the language by-design does not take long ways to prevent you.
The following is sneaky, illegal, compiler-dependent, and may not work depending on various implementation details.
#define private public
#define class struct
But it is an answer to your OP, in which you explicitly invite a technique which, and I quote, is "totally stupid and that anyone who would wish to try such a thing in production code should be fired and/or shot".
Another technique is to access private member data, by contructing pointers using hard-coded/hand-coded offsets from the beginning of the object.
Hmmm, don't know if this would work, but might be worth a try. Create another class with the same layout as the object with private members but with private changed to public. Create a variable of pointer to this class. Use a simple cast to point this to your object with private members and try calling a private function.
Expect sparks and maybe a crash ;)
class A
{
int a;
}
class B
{
public:
int b;
}
union
{
A a;
B b;
};
That should do it.
ETA: It will work for this sort of trivial class, but as a general thing it won't.
TC++PL Section C.8.3: "A class with a constructor, destructor, or copy operation cannot be the type of a union member ... because the compiler would not know which member to destroy."
So we're left with the best bet being to declare class B to match A's layout and hack to look at a class's privates.
If you can get a pointer to a member of a class you can use the pointer no matter what the access specifiers are (even methods).
class X;
typedef void (X::*METHOD)(int);
class X
{
private:
void test(int) {}
public:
METHOD getMethod() { return &X::test;}
};
int main()
{
X x;
METHOD m = x.getMethod();
X y;
(y.*m)(5);
}
Of course my favorite little hack is the friend template back door.
class Z
{
public:
template<typename X>
void backDoor(X const& p);
private:
int x;
int y;
};
Assuming the creator of the above has defined backDoor for his normal uses. But you want to access the object and look at the private member variables. Even if the above class has been compiled into a static library you can add your own template specialization for backDoor and thus access the members.
namespace
{
// Make this inside an anonymous namespace so
// that it does not clash with any real types.
class Y{};
}
// Now do a template specialization for the method.
template<>
void Z::backDoor<Y>(Y const& p)
{
// I now have access to the private members of Z
}
int main()
{
Z z; // Your object Z
// Use the Y object to carry the payload into the method.
z.backDoor(Y());
}
It's definately possible to access private members with a pointer offset in C++. Lets assume i had the following type definition that I wanted access to.
class Bar {
SomeOtherType _m1;
int _m2;
};
Assuming there are no virtual methods in Bar, The easy case is _m1. Members in C++ are stored as offsets of the memory location of the object. The first object is at offset 0, the second object at offset of sizeof(first member), etc ...
So here is a way to access _m1.
SomeOtherType& GetM1(Bar* pBar) {
return*(reinterpret_cast<SomeOtherType*>(pBar));
}
Now _m2 is a bit more difficult. We need to move the original pointer sizeof(SomeOtherType) bytes from the original. The cast to char is to ensure that I am incrementing in a byte offset
int& GetM2(Bar* pBar) {
char* p = reinterpret_cast<char*>(pBar);
p += sizeof(SomeOtherType);
return *(reinterpret_cast<int*>(p));
}
This answer is based on the exact concept demonstrated by #Johannes's answer/blog, as that seems to be the only "legitimate" way. I have converted that example code into a handy utility. It's easily compatible with C++03 (by implementing std::remove_reference & replacing nullptr).
Library
#define CONCATE_(X, Y) X##Y
#define CONCATE(X, Y) CONCATE_(X, Y)
#define ALLOW_ACCESS(CLASS, MEMBER, ...) \
template<typename Only, __VA_ARGS__ CLASS::*Member> \
struct CONCATE(MEMBER, __LINE__) { friend __VA_ARGS__ CLASS::*Access(Only*) { return Member; } }; \
template<typename> struct Only_##MEMBER; \
template<> struct Only_##MEMBER<CLASS> { friend __VA_ARGS__ CLASS::*Access(Only_##MEMBER<CLASS>*); }; \
template struct CONCATE(MEMBER, __LINE__)<Only_##MEMBER<CLASS>, &CLASS::MEMBER>
#define ACCESS(OBJECT, MEMBER) \
(OBJECT).*Access((Only_##MEMBER<std::remove_reference<decltype(OBJECT)>::type>*)nullptr)
API
ALLOW_ACCESS(<class>, <member>, <type>);
Usage
ACCESS(<object>, <member>) = <value>; // 1
auto& ref = ACCESS(<object>, <member>); // 2
Demo
struct X {
int get_member () const { return member; };
private:
int member = 0;
};
ALLOW_ACCESS(X, member, int);
int main() {
X x;
ACCESS(x, member) = 42;
std::cout << "proof: " << x.get_member() << std::endl;
}
If you know how your C++ compiler mangles names, yes.
Unless, I suppose, it's a virtual function. But then, if you know how your C++ compiler builds the VTABLE ...
Edit: looking at the other responses, I realize that I misread the question and thought it was about member functions, not member data. However, the point still stands: if you know how your compiler lays out data, then you can access that data.
cool question btw... here's my piece:
using namespace std;
class Test
{
private:
int accessInt;
string accessString;
public:
Test(int accessInt,string accessString)
{
Test::accessInt=accessInt;
Test::accessString=accessString;
}
};
int main(int argnum,char **args)
{
int x;
string xyz;
Test obj(1,"Shit... This works!");
x=((int *)(&obj))[0];
xyz=((string *)(&obj))[1];
cout<<x<<endl<<xyz<<endl;
return 0;
}
Hope this helps.
As an alternative to template backdoor method you can use template backdoor class. The difference is that you don't need to put this backdoor class into public area of the class your are going to test. I use the fact that many compilers allow nested classes to access private area of enclosing class (which is not exactly 1998 standard but considered to be "right" behaviour). And of course in C++11 this became legal behaviour.
See this example:
#include <vector>
#include <cassert>
#include <iostream>
using std::cout;
using std::endl;
///////// SystemUnderTest.hpp
class SystemUnderTest
{
//...put this 'Tested' declaration into private area of a class that you are going to test
template<typename T> class Tested;
public:
SystemUnderTest(int a): a_(a) {}
private:
friend std::ostream& operator<<(std::ostream& os, const SystemUnderTest& sut)
{
return os << sut.a_;
}
int a_;
};
/////////TestFramework.hpp
class BaseTest
{
public:
virtual void run() = 0;
const char* name() const { return name_; }
protected:
BaseTest(const char* name): name_(name) {}
virtual ~BaseTest() {}
private:
BaseTest(const BaseTest&);
BaseTest& operator=(const BaseTest&);
const char* name_;
};
class TestSuite
{
typedef std::vector<BaseTest*> Tests;
typedef Tests::iterator TIter;
public:
static TestSuite& instance()
{
static TestSuite TestSuite;
return TestSuite;
}
void run()
{
for(TIter iter = tests_.begin(); tests_.end() != iter; ++iter)
{
BaseTest* test = *iter;
cout << "Run test: " << test->name() << endl;
test->run();
}
}
void addTest(BaseTest* test)
{
assert(test);
cout << "Add test: " << test->name() << endl;
tests_.push_back(test);
}
private:
std::vector<BaseTest*> tests_;
};
#define TEST_CASE(SYSTEM_UNDER_TEST, TEST_NAME) \
class TEST_NAME {}; \
template<> \
class SYSTEM_UNDER_TEST::Tested<TEST_NAME>: public BaseTest \
{ \
Tested(): BaseTest(#SYSTEM_UNDER_TEST "::" #TEST_NAME) \
{ \
TestSuite::instance().addTest(this); \
} \
void run(); \
static Tested instance_; \
}; \
SYSTEM_UNDER_TEST::Tested<TEST_NAME> SYSTEM_UNDER_TEST::Tested<TEST_NAME>::instance_; \
void SYSTEM_UNDER_TEST::Tested<TEST_NAME>::run()
//...TestSuiteForSystemUnderTest.hpp
TEST_CASE(SystemUnderTest, AccessPrivateValueTest)
{
SystemUnderTest sut(23);
cout << "Changed private data member from " << sut << " to ";
sut.a_ = 12;
cout << sut << endl;
}
//...TestRunner.cpp
int main()
{
TestSuite::instance().run();
}
Beside #define private public you can also #define private protected and then define some foo class as descendant of wanted class to have access to it's (now protected) methods via type casting.
just create your own access member function to extend the class.
To all the people suggesting "#define private public":
This kind of thing is illegal. The standard forbids defining/undef-ing macros that are lexically equivalent to reserved language keywords. While your compiler probably won't complain (I've yet to see a compiler that does), it isn't something that's a "Good Thing" to do.
It's actually quite easy:
class jail {
int inmate;
public:
int& escape() { return inmate; }
};
"using private variables isn't a 100% reliable way to enforce encapsulation, even in C++."
Really? You can disassemble the library you need, find all the offsets needed and use them.
That will give you an ability to change any private member you like... BUT!
You can't access private members without some dirty hacking.
Let us say that writing const won't make your constant be really constant, 'cause you can
cast const away or just use it's address to invalidate it. If you're using MSVC++ and you specified "-merge:.rdata=.data" to a linker, the trick will work without any memory access faults.
We can even say that writing apps in C++ is not reliable way to write programs, 'cause resulting low level code may be patched from somewhere outside when your app is running.
Then what is reliable documented way to enforce encapsulation? Can we hide the data somewhere in RAM and prevent anything from accessing them except our code? The only idea I have is to encrypt private members and backup them, 'cause something may corrupt those members.
Sorry if my answer is too rude, I didn't mean to offend anybody, but I really don't think that statement is wise.
since you have an object of required class I am guessing that you have declaration of class.
Now what you can do is declare another class with same members but keep all of there access specifiers as public.
For example previous class is:
class Iamcompprivate
{
private:
Type1 privateelement1;
Typ2 privateelement2;
...
public:
somefunctions
}
you can declare a class as
class NowIampublic
{
**public:**
Type1 privateelement1;
Type2 privateelement2;
...
somefunctions
};
Now all you need to do is cast pointer of class Iamcompprivate into an pointer of class NowIampublic and use them as U wish.
Example:
NowIampublic * changetopublic(Iamcompprivate *A)
{
NowIampublic * B = (NowIampublic *)A;
return B;
}
By referencing to *this you enable a backdoor to all private data within an object.
class DumbClass
{
private:
int my_private_int;
public:
DumbClass& backdoor()
{
return *this;
}
}
Quite often a class provides mutator methods to private data (getters and setters).
If a class does provide a getter that returns a const reference (but no setter), then you can just const_cast the return value of the getter, and use that as an l-value:
class A {
private:
double _money;
public:
A(money) :
_money(money)
{}
const double &getMoney() const
{
return _money;
}
};
A a(1000.0);
const_cast<double &>(a.getMoney()) = 2000.0;
I've used another useful approach (and solution) to access a c++ private/protected member.
The only condition is that you are able to inherit from the class you want to access.
Then all credit goes to reinterpret_cast<>().
A possible problem is that it won't work if you insert a virtual function, which will modify virtual table, and so, object size/alignment.
class QObject
{
Q_OBJECT
Q_DECLARE_PRIVATE(QObject)
void dumpObjectInfo();
void dumpObjectTree();
...
protected:
QScopedPointer<QObjectData> d_ptr;
...
}
class QObjectWrapper : public QObject
{
public:
void dumpObjectInfo2();
void dumpObjectTree2();
};
Then you just need to use the class as follows:
QObject* origin;
QObjectWrapper * testAccesor = reinterpret_cast<QObjectWrapper *>(origin);
testAccesor->dumpObjectInfo2();
testAccesor->dumpObjectTree2();
My original problem was as follows: I needed a solution that won't imply recompiling QT libraries.
There are 2 methods in QObject, dumpObjectInfo() and dumpObjectTree(), that
just work if QT libs are compiled in debug mode, and they of course need access to d_ptr proteted member (among other internal structures).
What I did was to use the proposed solution to reimplement (with copy and paste) those methods in dumpObjectInfo2() and dumpObjectTree2() in my own class (QObjectWrapper) removing those debug preprocesor guards.
The following code accesses and modifies a private member of the class using a pointer to that class.
#include <iostream>
using namespace std;
class A
{
int private_var;
public:
A(){private_var = 0;}//initialized to zero.
void print(){cout<<private_var<<endl;}
};
int main()
{
A ob;
int *ptr = (int*)&ob; // the pointer to the class is typecast to a integer pointer.
(*ptr)++; //private variable now changed to 1.
ob.print();
return 0;
}
/*prints 1. subsequent members can also be accessed by incrementing the pointer (and
type casting if necessary).*/
study purpose only....
try this ....may be helpfull i guess.....
this program can access the private data just by knowing the values...
//GEEK MODE....;)
#include<iostream.h>
#include<conio.h>
class A
{
private :int iData,x;
public: void get() //enter the values
{cout<<"Enter iData : ";
cin>>iData;cout<<"Enter x : ";cin>>x;}
void put() //displaying values
{cout<<endl<<"sum = "<<iData+x;}
};
void hack(); //hacking function
void main()
{A obj;clrscr();
obj.get();obj.put();hack();obj.put();getch();
}
void hack() //hack begins
{int hck,*ptr=&hck;
cout<<endl<<"Enter value of private data (iData or x) : ";
cin>>hck; //enter the value assigned for iData or x
for(int i=0;i<5;i++)
{ptr++;
if(*ptr==hck)
{cout<<"Private data hacked...!!!\nChange the value : ";
cin>>*ptr;cout<<hck<<" Is chaged to : "<<*ptr;
return;}
}cout<<"Sorry value not found.....";
}
Inspired by #Johannes Schaub - litb, the following code may be a bit easier to digest.
struct A {
A(): member(10){}
private:
int get_member() { return member;}
int member;
};
typedef int (A::*A_fm_ptr)();
A_fm_ptr get_fm();
template< A_fm_ptr p>
struct Rob{
friend A_fm_ptr get_fm() {
return p;
}
};
template struct Rob< &A::get_member>;
int main() {
A a;
A_fm_ptr p = get_fm();
std::cout << (a.*p)() << std::endl;
}
Well, with pointer offsets, it's quite easy. The difficult part is finding the offset:
other.hpp
class Foo
{
public:
int pub = 35;
private:
int foo = 5;
const char * secret = "private :)";
};
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include "other.hpp"
unsigned long long getPrivOffset(
const char * klass,
const char * priv,
const char * srcfile
){
std::ifstream read(srcfile);
std::ofstream write("fork.hpp");
std::regex r ("private:");
std::string line;
while(getline(read, line))
// make all of the members public
write << std::regex_replace(line, r, "public:") << '\n';
write.close();
read.close();
// find the offset, using the clone object
std::ofstream phony("phony.cpp");
phony <<
"#include <iostream>\n"
"#include <fstream>\n"
"#include \"fork.hpp\"\n"
"int main() {\n";
phony << klass << " obj;\n";
// subtract to find the offset, the write it to a file
phony <<
"std::ofstream out(\"out.txt\");\n out << (((unsigned char *) &(obj."
<< priv << ")) -((unsigned char *) &obj)) << '\\n';\nout.close();";
phony << "return 0;\n}";
phony.close();
system(
"clang++-7 -o phony phony.cpp\n"
"./phony\n"
"rm phony phony.cpp fork.hpp");
std::ifstream out("out.txt");
// read the file containing the offset
getline(out, line);
out.close();
system("rm out.txt");
unsigned long long offset = strtoull(line.c_str(), NULL, 10);
return offset;
}
template <typename OutputType, typename Object>
OutputType hack(
Object obj,
const char * objectname,
const char * priv_method_name,
const char * srcfile
) {
unsigned long long o = getPrivOffset(
objectname,
priv_method_name,
srcfile
);
return *(OutputType *)(((unsigned char *) (&obj)+o));
}
#define HACK($output, $object, $inst, $priv, $src)\
hack <$output, $object> (\
$inst,\
#$object,\
$priv,\
$src)
int main() {
Foo bar;
std::cout << HACK(
// output type
const char *,
// type of the object to be "hacked"
Foo,
// the object being hacked
bar,
// the desired private member name
"secret",
// the source file of the object's type's definition
"other.hpp"
) << '\n';
return 0;
}
clang++ -o main main.cpp
./main
output:
private :)
You could also use reinterpret_cast.
Maybe some pointer arithmetics can do it
#pragma pack(1)
class A
{
int x{0};
char c{0};
char s[8]{0};
public:
void display()
{
print(x);
print(c);
print(s);
};
};
int main(void)
{
A a;
int *ptr2x = (int *)&a;
*ptr2x = 10;
char *ptr2c = (char *)ptr2x+4;
*ptr2c = 'A';
char *ptr2s = (char *)ptr2c+1;
strcpy(ptr2s ,"Foo");
a.display();
}
class Test{
int a;
alignas(16) int b;
int c;
};
Test t;
method A : intrusive mood.
since we can access source code and recomplie it, we can use
many other way like friend class to access private member, they are all legal backdoor.
method B : brute mood.
int* ptr_of_member_c = reinterpret_cast<int*>(reinterpret_cast<char*>(&t) + 20);
we use a magic number (20) , and It's not always right. When the layout of class Test changed, the magic number is a big bug source.
method C : super hacker mood.
is there any non-intrusive and non-brute mood ?
since the class Test's layout infomation is hide by the complier,
we can not get offset information from the complie's mouth.
ex.
offsetof(Test,c); //complie error. they said can not access private member.
we also can not get member pointer from class Test.
ex.
&Test::c ; //complie error. they said can not access private member.
#Johannes Schaub - litb has a blog, he found a way to rob private member pointer.
but i thought this should be complier's bug or language pitfall.
i can complie it on gcc4.8, but not on vc8 complier.
so the conclusion may be :
the landlord build all backdoor.
the thief always has brute and bad way to break into.
the hacker accidental has elegant and automated way to break into.
I made Johannes answer more generic. You can get the source here: https://github.com/lackhole/Lupin
All you have to know is just the name of the class and the member.
You can use like,
#include <iostream>
#include "access/access.hpp"
struct foo {
private:
std::string name = "hello";
int age = 27;
void print() {}
};
using tag_foo_name = access::Tag<class foo_name>;
template struct access::Accessor<tag_foo_name, foo, decltype(&foo::name), &foo::name>;
int main() {
foo f;
// peek hidden data
std::cout << access::get<tag_foo_name>(f) << '\n'; // "hello"
// steal hidden data
access::get<tag_foo_name>(f) = "lupin";
std::cout << access::get<tag_foo_name>(f) << '\n'; // "lupin"
}
Call private functions, get the type of private members is also possible with only using the tag.