How to solve access violation reading location in google test? - c++

I am trying to run Google test with the below code. I am reading some memory location for register value with code similar to the examples below.
Header file :
typedef union MYREG
{
uint32_t u32reg;
uint8_t au8byte[4];
} MYREG_t;
#define SET_VALUE (0x00000002)
#define TEST_REGISTER ((volatile MYREG_t*)0x2025111BUL)
In code I am reading and writing values as
void testcode()
{
TEST_REGISTER->u32reg |= SET_VALUE;
call_another_funct();
}
When i try to run google test by writing a test case for this function
TEST_F(sample_test, check)
{
testcode();
}
I am getting below SEH error
First-chance exception at 0x0036B28F in test.exe: 0xC0000005: Access violation reading location 0x2025111B.
Unknown file: error: SEH exception with code 0xC0000005 thrown in the test body.
What is going wrong here ? Any suggestion would helpful for me to understand the error.

Example of dependency injection for unit testability :
#include <memory>
#include <utility>
//-----------------------------------------------------------------------------
// define an interface (abstract base class) to communicate with your register
class register_itf
{
public:
virtual ~register_itf() = default;
virtual void write(const std::uint32_t value) = 0;
virtual std::uint32_t read() const noexcept = 0;
protected:
register_itf() = default;
};
//-----------------------------------------------------------------------------
// toy example of real register
class hardware_register final :
public register_itf
{
public:
explicit hardware_register(std::uint32_t* address) :
m_address(address)
{
}
~hardware_register() override = default;
void write(const std::uint32_t value) override
{
*m_address = value;
}
std::uint32_t read() const noexcept override
{
return *m_address;
}
private:
volatile std::uint32_t* m_address;
};
//-----------------------------------------------------------------------------
// you can also make this a google mock to test if it has been called etc...
class simulated_register final :
public register_itf
{
public:
simulated_register() = default;
~simulated_register() override = default;
void write(const std::uint32_t value) override
{
m_value = value;
}
std::uint32_t read() const noexcept override
{
return m_value;
}
private:
std::uint32_t m_value;
};
//-----------------------------------------------------------------------------
// a device with a register, use dependency injection
// to inject a real or a simulated register
class device_t
{
public:
explicit device_t(std::unique_ptr<register_itf>&& reg) :
m_register(std::move(reg))
{
}
void reset()
{
m_register->write(0x01);
}
private:
std::unique_ptr<register_itf> m_register;
};
int main()
{
// production code on real hardware
//device_t device{ std::make_unique<hardware_register>(0x2025111BUL) };
// unit test code
device_t device{ std::make_unique<simulated_register>() };
// functional code using the register will be the same on production/test
device.reset();
return 1;
}

Related

Implementing template specialized functions

I'm trying to allow a class to implement an interface, where the interface is templated to either allow an update internally or not. The code looks like this and works if the implementation is within the class declaration. If it is moved out (as shown here), I get a compiler error on Visual Studio 2019, and I can't understand why. All help is appreciated!
The following code will not compile. If the out of class implementation and headers are modified to just use the code I commented out, it compiles and works as expected.
#include <atomic>
#include <cstdint>
#include <memory>
#include <iostream>
#include <string>
enum class EntryType { Read, ReadUpdate };
template <EntryType Type>
class IXQ
{
public:
virtual float GetValue() = 0;
};
class X : public IXQ<EntryType::Read>, public IXQ<EntryType::ReadUpdate>
{
public:
float IXQ<EntryType::Read>::GetValue();
/*
float IXQ<EntryType::Read>::GetValue()
{
return _x;
}
*/
float IXQ<EntryType::ReadUpdate>::GetValue();
/*
float IXQ<EntryType::ReadUpdate>::GetValue() {
_counter++;
return _x;
}
*/
float _x = 10.0F;
std::atomic<std::int32_t> _counter = 0;
};
float X::IXQ<EntryType::Read>::GetValue()
{
return _x;
}
float X::IXQ<EntryType::ReadUpdate>::GetValue()
{
_counter++;
return _x;
};
int main(int argc, char* argv[])
{
{
auto k = std::make_unique<X>();
auto ptrQ = static_cast<IXQ<EntryType::Read>*>(k.get());
std::cout << std::to_string(ptrQ->GetValue()) << std::endl;
std::cout << k->_counter.load() << std::endl;
}
{
auto k = std::make_unique<X>();
auto ptrQ = static_cast<IXQ<EntryType::ReadUpdate>*>(k.get());
std::cout << std::to_string(ptrQ->GetValue()) << std::endl;
std::cout << k->_counter.load() << std::endl;
}
return 0;
}
1. Microsoft-specific syntax
The syntax you're using to override GetValue() is not standard c++.
class X : public IXQ<EntryType::Read> {
public:
float IXQ<EntryType::Read>::GetValue() { /* ... */ }
}
This is a Microsoft-Specific Extension for C++ called Explicit Overrides (C++) and is intended to be used with __interfaces (also a microsoft-specific extension to c++).
__interfaces do not officially support c++ templates due to them being intended mostly for COM Interfaces, e.g.:
[ object, uuid("00000000-0000-0000-0000-000000000001"), library_block ]
__interface ISomething {
// properties
[ id(0) ] int iInt;
[ id(5) ] BSTR bStr;
// functions
void DoSomething();
};
It's suprising that float IXQ<EntryType::Read>::GetValue() { /* ... */ } works at all.
2. Standard C++-compliant solutions
In standard C++ the overriden function is determined by the name & arguments alone, so your only option is to override both of them.
e.g.:
class X : public IXQ<EntryType::Read>, public IXQ<EntryType::ReadUpdate>
{
public:
// will be the implementation for both IXQ<EntryType::Read> & IXQ<EntryType::ReadUpdate>
float GetValue() override;
};
float X::GetValue() {
/* ... */
}
Another standard-compliant way would be to create 2 classes that inherit from the given interfaces & then let X inherit from both of them:
class XRead : public IXQ<EntryType::Read> {
public:
float GetValue() override { /* ... */ }
};
class XReadUpdate : public IXQ<EntryType::ReadUpdate> {
public:
float GetValue() override { /* ... */ }
};
class X : public XRead, public XReadUpdate {
/* ... */
};
If you want to share state between XRead & XReadUpdate, you'd have to introduce another level, e.g.:
class XBase {
public:
virtual ~XBase() = default;
protected:
float value;
};
class XRead : public virtual XBase, public IXQ<EntryType::Read> {
float GetValue() override { return value; }
};
class XReadUpdate : public virtual XBase, public IXQ<EntryType::ReadUpdate> {
float GetValue() override { return value; }
};
class X : public XRead, public XReadUpdate {
/* ... */
};
3. Possible recommendations for API Design
Keep in mind though that this type of API design will be rather complicated to use, because you always need to cast to the specific interface first before you can call the function because X{}.GetValue() would be ambigous.
e.g.:
X x;
IXQ<EntryType::Read>& read = x;
std::cout << read.GetValue() << std::endl;
IXQ<EntryType::ReadUpdate>& update = x;
std::cout << update.GetValue() << std::endl;
// this is *not* possible, GetValue() is ambigous
// std::cout << x.GetValue() << std::endl;
I'd recommend separating both interfaces & using different method names, e.g.: godbolt example
struct IXQReadonly {
virtual ~IXQReadonly() = default;
virtual float GetValue() = 0;
};
struct IXQ : IXQReadonly {
virtual float GetValueUpdate() = 0;
};
class X : public IXQ {
public:
X() : value(0.0f), counter(0) { }
float GetValue() override { return value; }
float GetValueUpdate() override {
++counter;
return value;
}
private:
float value;
std::atomic<int> counter;
};
This comes with a whole set of benefits:
You can call GetValue() / GetValueUpdate() directly on X, no need to convert to an interface first
X x;
x.GetValue();
x.GetValueUpdate();
It is immediately clear from the method name if it will update the counter or not
A function that is given an IXQ can call a function that expects IXQReadonly, but not the other way round: (so you can "downgrade" a read-write interface to readonly, but not "upgrade" a readonly interface to read-write)
void bar(IXQReadonly& r) { r.GetValue(); /* we can't do GetValueUpdate() here */ }
void foo(IXQ& x) { bar(x); x.GetValueUpdate(); }
Additionally remember to declare the destructor as virtual (at least in the top-most class / interface), otherwise funny things tend to happen if you try to delete an instance of X through a pointer to one of its bases / interfaces.
I think this can be solved by adding an intermediate layer of classes, let's say X_Read and X_ReadUpdate from which X can inherit.
IXQ
/ \
X_Read X_ReadUpdate
\ /
X
The trick is having those intermediate classes implement GetValue by calling two virtual pure methods, let's say GetValueRead and GetValueReadUpdate respectively. This way, X still inherits from IXQ<EntryType::Read> and IXQ<EntryType::ReadUpdate>, but comes to implement GetValueRead and GetValueReadUpdate, two methods with clear and distinct interfaces.
[Demo]
template <EntryType Type>
class IXQ
{
public:
virtual float GetValue() = 0;
};
class X_Read : public IXQ<EntryType::Read>
{
public:
virtual float GetValue() override { return GetValueRead(); };
virtual float GetValueRead() = 0;
};
class X_ReadUpdate : public IXQ<EntryType::ReadUpdate>
{
public:
virtual float GetValue() override { return GetValueReadUpdate(); };
virtual float GetValueReadUpdate() = 0;
};
class X : public X_Read, public X_ReadUpdate
{
public:
virtual float GetValueRead() override { return _x; }
virtual float GetValueReadUpdate() { _counter++; return _x; };
float _x{10.0f};
std::atomic<std::int32_t> _counter{};
};
// Outputs:
// 10.000000
// 0
// 10.000000
// 1

Quickly determine subclass based on abstract class

I have a C++ base class CAbstrInstruction and a large number of direct subclasses:
class CAbstrInstruction { /* ... */ };
class CSleepInstruction: public CAbstrInstruction { /* ... */ };
class CSetInstruction: public CAbstrInstruction { /* ... */ };
class CIfInstruction: public CAbstrInstruction { /* ... */ };
class CWhileInstruction: public CAbstrInstruction { /* ... */ };
// ...
There is also a CScriptWorker that exposes a public method execute:
class CScriptWorker
{
public:
void execute (const CAbstrInstruction *pI);
private:
void doSleep (const CSleepInstruction *pI);
void doSet (const CSetInstruction *pI);
void doIf (const CIfInstruction *pI);
void doWhile (const CWhileInstruction *pI);
// ...
};
The implementation of the execute method currently looks like this:
void CScriptWorker::execute (const CAbstrInstruction *pI)
{
const CSleepInstruction *pSleep =
dynamic_cast<const CSleepInstruction *>(pI);
if (pSleep != NULL)
{
doSleep (*pSleep);
return;
}
const CSetInstruction *pSet =
dynamic_cast<const CSetInstruction *>(pI);
if (pSet != NULL)
{
doSet (*pSet);
return;
}
const CIfInstruction *pIf =
dynamic_cast<const CIfInstruction *>(pI);
if (pIf != NULL)
{
doIf (*pIf);
return;
}
const CWhileInstruction *pWhile =
dynamic_cast<const CWhileInstruction *>(pI);
if (pWhile != NULL)
{
doWhile (*pWhile);
return;
}
/* ... */
}
This is very clumsy and takes O(log(n)) to invoke the correct private method. Is there
any design pattern or language construct that simplifies this?
Clarification: I could move the private execute methods do... into the instruction
classes. The execute method would simply become:
void execute (const CAbstrInstruction *pI) { pI->execute(); }
However, that's not what I want. Why not? Separation of concerns: The instances of CAbstrInstruction are just the description of what is do be done. They make up the Abstract Syntax Tree of the script. That's enough concern already. The CScriptWorker's concern is to actually do what's described by the instruction. CScriptWorker knows about the context the script is running in. CAbstrInstruction should not know about that.
Moving the implementation of the execute method into the subclasses of CAbstrInstruction could be the answer if things were simple. However, the OP explicitly stated the execute method should be kept separate in a CScriptWorker, to separate the concern of knowing about what is to be done (the instructions' job) from how it is to be done (the CScriptWorker's job). This may be achieved with double dispatch, also sometimes called the visitor pattern:
class IInstructionDispatchTarget
{
public:
virtual void onDispatch (const CSleepInstruction &instr) = 0;
virtual void onDispatch (const CSetInstruction &instr) = 0;
};
class CAbstrInstruction
{
public:
virtual void dispatch (IInstructionDispatchTarget &t) const = 0;
};
class CSleepInstruction: public CAbstrInstruction
{
public:
virtual void dispatch (IInstructionDispatchTarget &t) const override
{ t.onDispatch (*this); }
};
class CSetInstruction: public CAbstrInstruction
{
public:
virtual void dispatch (IInstructionDispatchTarget &t) const override
{ t.onDispatch (*this); }
};
class CScriptWorker: public IInstructionDispatchTarget
{
public:
void execute (const CAbstrInstruction *pI)
{ pI->dispatch (*this); }
virtual void onDispatch (const CSleepInstruction &instr) override
{
// do sleep
}
virtual void onDispatch (const CSetInstruction &instr) override
{
// do set
}
};
When execute gets called on the CScriptWorker, it invokes the dispatch method of the instruction. In return, the instruction invokes the onDispatch method on the dispatch target, using its specific this pointer and thus invoking the correct method.
The interface IInstructionDispatchTarget serves two purposes. On the one hand, it makes sure the instances of CAbstrInstruction do not need to know the CScriptWorker at all; all they need to know is the interface. On the other hand, it allows other dispatch targets to use the same mechanism, e.g. when traversing the instructions to optimize the AST.
If the presence of IInstructionDispatchTarget is considered unnecessary, things can be slightly simplified as shown by the answer by ROX.
CAbstrInstruction should define a pure virtual method (execute() in your example), which your child classes should override and implement.
As an example:
class CAbstrInstruction
{
/* ... */
virtual void execute() const = 0;
}
class CSleepInstruction
{
/* ... */
void execute() override const
{
/* your code here */
}
}
/* ... */
void CScriptWorker::execute (const CAbstrInstruction *pI)
{
pI->execute();
}
Inheritance is best used when the client does not need to know the concrete type of an object. You want to use a variant type, since you have a fixed number of known instructions, and your executor needs to know which kind of instruction it is executing. It's easiest to use std::variant, or boost::variant if you are pre-C++17.
#include <variant>
struct Set {};
struct If {};
struct While {};
using Instruction = std::variant<
Set,
If,
While
>;
#include <iostream>
struct Executor {
void operator()(Set const&) const { std::cout << "Set\n"; }
void operator()(If const&) const { std::cout << "If\n"; }
void operator()(While const&) const { std::cout << "While\n"; }
};
void execute(Instruction const& i) {
std::visit(Executor(), i);
}
Example:
#include <vector>
int main() {
for (auto const& i : std::vector<Instruction>{While(), If(), Set()}) {
execute(i);
}
}
Output:
While
If
Set
The visitor pattern works well if you have other classes that will the implement IInstructionVisitor interface. That ensures all those classes can handle the same set of Instruction classes.
If you don't have additional classes deriving from IInstructorVisitor then you can simplify it slightly:-
class CScriptWorker
{
public:
void execute (const CAbstrInstruction* pI)
{
pI->ResolveInstructionType(*this);
}
// Can be made friends of appropriate instruction classes or left public as you see fit
void doInstruction (const CSleepInstruction* pI);
void doInstruction (const CSetInstruction* pI);
void doInstruction (const CIfInstruction* pI);
void doInstruction (const CWhileInstruction* pI);
// note the name is now the same, name of the parameter should be enough to tell what's being done
// also I'd probably make these references not pointers
};
class CAbstrInstruction
{
public:
virtual void ResolveInstructionType (CScriptWorker& v) = 0;
};
class CSleepInstruction: public CAbstrInstruction
{
public:
void ResolveInstructionType (CScriptWorker& w) override { w.doInstruction (this); }
};
The slight advantages of the simplification are, slightly less code now, slightly less code to modify if a new instruction is added, you can choose names other than visit, visitor etc.

C++ multiple inheritance from base classes with members with same name

Let me tell you the problem I have. I'm designing a set of classes to control a digital device. This device can work in two modes of operation. In the first mode it can perform a specific set of operations, and in the second mode it can perform another set of operations (with possibly some common operations between the two). I can also change the mode of the device on the run, so I can swap between the two modes if necessary. Independently of the mode, the device use the same set of registers.
I was thinking in solve this problem with one base class for each mode, so I can have objects of mode 1 when I need the first set of operations and objects of mode 2 when I need the second set of operations. Then I could derive a class from these two base classes, so I can have objects that perform all the operations.
The problem with my design is that the two base classes have some common functions and references to the same registers. Since I can't prevent inheritance of members I would have duplicates in the derived class. I know I can choose which duplicate to access with the scope operator, but I still think this a bad design.
So my question is: is there an idiomatic way of solve this problem?
If there isn't a right or easy way of solving this, I'm thinking about design 3 hierarchically independently classes. I would have some duplicate code, but that is not a big problem, right?
Code below (simplified) for illustration:
class mode1
{
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation1() final { // do something }
virtual void operation2() final { // do something }
virtual void operation3() final { // do something }
};
class mode2
{
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation4() final { // do something }
virtual void operation2() final { // do something }
virtual void operation5() final { // do something }
};
class mode1and2 : public mode1, public mode2
{
public:
void operation6() { // do something }
void operation7() { // do something }
};
Note modes 1 and 2 have operation2 and all the data members in common.
I'd put the common parts of mode1 and mode2 in a common base class, let's say Common, comprising then your data and member function operation2. Then, together with virtual inheritance, you can have two views on the same data, even at the same time if needed.
class common {
friend class mode1;
friend class mode2;
protected:
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
public:
virtual void operation2() final { // do something
};
};
class mode1 : public virtual common
{
public:
virtual void operation1() final { // do something
};
virtual void operation3() final { // do something }
};
};
class mode2 : public virtual common
{
public:
virtual void operation4() final { // do something
}
virtual void operation5() final { // do something
}
};
class mode1and2 : public mode1, public mode2
{
public:
void operation6() { // do something }
};
void operation7() { // do something }
};
};
The state design pattern looks like a good candidate for your case.
As a minimal, working example:
#include<memory>
#include<iostream>
struct Behavior {
virtual void f() = 0;
virtual void g() = 0;
};
struct NullBehavior: Behavior {
void f() override {}
void g() override {}
};
struct Mode1: Behavior {
void f() override { std::cout << "mode 1 - f" << std::endl; }
void g() override { std::cout << "mode 1 - g" << std::endl; }
};
struct Mode2: Behavior {
void f() override { std::cout << "mode 2 - f" << std::endl; }
void g() override { std::cout << "mode 2 - g" << std::endl; }
};
struct Device {
template<typename B>
void set() { behavior = std::unique_ptr<Behavior>{new B}; }
void f() { behavior->f(); }
void g() { behavior->g(); }
private:
std::unique_ptr<Behavior> behavior{new NullBehavior};
};
int main() {
Device device;
device.f();
device.g();
device.set<Mode1>();
device.f();
device.g();
device.set<Mode2>();
device.f();
device.g();
}
From the point of view of the user of the device, it doesn't matter what's the mode you are using. Anyway, as requested, you can dynamically change it whenever you want and your device will start to work with the new mode from that point on.
Preferring composition over inheritance solves the issue due the conflicting names. Delegating everything from the outer class to the inner state does the rest.
Note that, if you want to share methods between states, nothing prevents you from putting them in the base class.
A slightly different version helps you sharing also data between the twos:
struct Data {
volatile uint8_t& reg1;
volatile uint8_t& reg2;
uint8_t data;
};
struct Behavior {
virtual void f(Data &) = 0;
virtual void g(Data &) = 0;
};
struct NullBehavior: Behavior {
void f(Data &) override {}
void g(Data &) override {}
};
struct Mode1: Behavior {
void f(Data &) override { /* ... */ }
void g(Data &) override { /* ... */ }
};
struct Mode2: Behavior {
void f(Data &) override { /* ... */ }
void g(Data &) override { /* ... */ }
};
struct Device {
template<typename B>
void set() { behavior = std::unique_ptr<Behavior>{new B}; }
void f() { behavior->f(data); }
void g() { behavior->g(data); }
private:
Data data{};
std::unique_ptr<Behavior> behavior{new NullBehavior};
};
All those parameters that are unique for a specific mode can be part of the class definition or put within Data and ignored if you are working in a different mode.

How to make a class property type in C ++ as is how it is done in C#

as the code below made for example purposes in C #, I would have had to do in C ++, if so how do you do?
public class MyClassTest{
public int testint1{get;set;}
public MyClassTest2 classTest2{get;set;}
}
public class MyClassTest2{
public int testint2{get;set;}
public MyClassTest classTest{get;set;}
}
Something like this.
class MyClassTest {
private: // optional: C++ classes are private by default
int testint1;
public:
int getTestInt1() const { return testint1; }
void setTestInt1(int t) { testint1 = t; }
};
Or you could make your member name distinct and skip the get/set keywords:
class MyClassTest {
private:
int testint1_;
public:
int testint1() const { return testint1_; }
void testint1(int t) { testint1_ = t; }
};
There is no equivalent to this in the current C++ standard, you just have to create getter/setter methods for any fields you want:
class MyClass {
public:
MyClass() {}
// note const specifier indicates method guarantees
// no changes to class instance and noexcept specifier
// tells compiler that this method is no-throw guaranteed
int get_x() const noexcept { return x; }
void set_x(int _x) { x = _x; }
private:
int x;
};
In Visual Studio (mine is 2013), it could be done in this way:
__declspec(property(get = Get, put = Set)) bool Switch;
bool Get() { return m_bSwitch; }
void Set(bool val) { m_bSwitch = val; }
bool m_bSwitch;
in a Class.

Odd C++ accessing private member issue

I have this piece of code:
class object
{
public:
virtual ~object(){ }
bool equals(const object& J)const
{
return &J == this;
}
int operator==(const object& J)const
{
return equals(J);
}
virtual int getHash()const;
virtual void getType()const;
void* operator new(size_t size)
{
void*mem = malloc(size);
return mem;
}
};
class notcopyable
{
private:
notcopyable(const notcopyable&){}
notcopyable& operator=(const notcopyable&){}
public:
notcopyable(){}
};
class exception :
public object,public notcopyable
{
private:
public:
virtual ~exception();
virtual const char* info();
};
class exception_not_implemented :
public exception
{
public:
exception_not_implemented()
{
}
virtual const char* info()
{
return "exception_not_implemented: ";
}
};
class exception_oob :public exception
{
public:
exception_oob()
{
}
virtual const char* info()
{
return "Index out of boundary";
}
};
There are two functions throw exception_not_implemented:
void object::getType()const
{
throw exception_not_implemented();
}
int object::getHash()const
{
throw exception_not_implemented();
}
And getting this error:
error C2248: 'js::notcopyable::notcopyable' : cannot access private member declared in class 'js::notcopyable'
The output of the compiler says:
This diagnostic occurred in the compiler generated function 'js::exception::exception(const js::exception &)'
If I delete the two throw shown above, it works well. But the same error doesn't happens to exception_oob. I can't figure out why.
You can temporarily add a private copy constructor declaration, which will generate an error at the point where a copy is being made. Then you can fix that code to not make copies.
The error should happen at other place where you call the (private) copy constructor.
For example:
Exception a;
Exception b = a; // error : cannot access private member ...