Inquiry MISRA C 2012 6.1

26 views (last 30 days)
Seungyeop
Seungyeop on 20 Jun 2019
Edited: Walter Roberson on 20 Jun 2019
Polyspace 2018a detected a warning, 6.1 Bit-fileds shall only be declared with an appropriate type.
According to the polyspace docomments, the use of enum, short char, or any other type of bit-field is not permitted in C90 because the behavior is undefined.
  1. Should the below unsigned short be modified to unsigned int? In our system, int size is not 2byte but 4byte. "Control Register 3 size is 2byte. So, we don't know exactly how to solve this 6.1 warning.
  2. Would you mind explaining us which side effect might be occur if we don't modify the type of Bit-Field?
================================
typedef volatile unsigned short vuint16_t;
typedef union eSCI_CR3_union_tag { /* Control Register 3 */
vuint16_t R;
struct {
vuint16_t :4; //
vuint16_t EROE:1;
vuint16_t ERFE:1;
vuint16_t ERPE:1;
vuint16_t M2:1;
vuint16_t :8;
} B;
} eSCI_CR3_tag;
===============================
Thank you.
Sincerely yours.
SY Seo

Answers (1)

Walter Roberson
Walter Roberson on 20 Jun 2019
Edited: Walter Roberson on 20 Jun 2019
You have a problem.
A bit-field may have type int , unsigned int , or signed int .
So unsigned int is not permitted.
An implementation may allocate any addressable storage unit large enough to hold a bit-field.
So you have no control over the number of bytes allocated.
The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined.
So if you were to try to just let it allocate (probably) 4 bytes intending to ignore the extra, then you cannot be sure whether the bits are allocated at the beginning or end of the space.
A work around for these problems requires multiple strategies:
  1. Define a union of unsigned short [2] and struct with bitfields, not of volatile unsigned short and something that is 16+ bits.
  2. Define all of the bitfields as unsigned int
  3. During regular execution, copy your vuint16_t into one of the unsigned short entries and access through the bitfields
  4. You might need to define a struct with the bitfields in exactly the other order as well
  5. At initialization time, test to find out how the bitfields get laid out. Take a test variable and zero the two unsigned short, and then write a 1 to EROE. Now test which of the two shorts is non-zero in order to find out which of two shorts to copy into in step 3. Now test whether the short is 0x0800 (EROE is 5th most significant bit) or is 0x0010 (EROE is 5th least significant bit) in order to determine which of the two bitfield orders you need to use.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!