OK a few things here - first of all, your definition for READ_REG
is missing a volatile
-- it should be something like
#define READREG(address) (*(uint32_t volatile *)(address))
Secondly - and this is CPU-specific of course - generally speaking, reading a 32-bit value from an odd address (offset 0x123) won't work - at a minimum it will be slow (multiple bus cycles), and on many architectures, you'll hit a processor exception. (BTW, please note that pointer arithmetic doesn't come into play here, since the 2 values are added before being cast to a pointer.)
To answer your original question:
what is the best/appropriate way to access memory and get rid of MISRA
warnings
Well -- you are violating a MISRA rule (you have to in this case, we've all been there...) so you will get a warning.
So what you need to do is suppress the warning(s) in a disciplined, systematic and easily identifiable way. In my opinion, there is no better example and explanation of this than in the Quantum Platform (QP) Event-driven framework's code, which is open source. Specifically:
- Check out the QP's MISRA Compliance matrix for examples of how this is handled -- for example, just search the PDF for the
Q_UINT2PTR_CAST
macro
- Check out the QP's actual source code - for example, the macro that wraps/encapsulates such "int to ptr" casts (this way they are done in a manner that is easy to identify, and easy to change/suppress warnings for in a single place)
- Lastly, check out the PC-Lint config file qpc.lnt, where you can see how/where the warnings are suppressed in a single place. THis is explained in this app note, section 6.3:
6.3 Rule 5-2-8(req)
An object with integer type or pointer to void type shall not be
converted to an object with pointer type.
The QP/C++ applications might deviate from rule 5-2-8 when they need
to access specific hard-coded hardware addresses directly. The QP/C++
framework encapsulates this deviation in the macro Q_UINT2PTR_CAST()
.
The following code snippet provides a use case of this macro:
#define QK_ISR_EXIT() . . . \
*Q_UINT2PTR_CAST(uint32_t, 0xE000ED04U) = \
I don't have time to talk about MISRA warning suppresions, compliance issues, etc. but the above gives you everything you need.
P.S. Not sure which MISRA guidelines you are referring to -- for C, there are the 2004 & 2012 guidelines, and for C++, there are the 2008 guidelines (I know, it's almost 2017!)
reg_base
is actually a pointer, why not type it asuint8_t*
?uint32_t*
, Ifreg_base
really needs to be an integer, why useuint64_t
rather thanuintptr_t
? (MISRA probably wouldn't like that either, butintptr_t
oruintptr_t
is the most logical type to for an integer holding a pointer value.)uint32_t*
multiply FOO_REG_OFFSET by 4 when adding toreg_base
?FOO_REG_OFFSET
. Is it an offset in bytes or in 32-bit words? I might useunsigned char*
rather thanuint8_t*
-- though they're nearly equivalent on any system whereuint8_t
exists.