Bit-domain structure to save some memory space, but improper use will produce race conditions, resulting in program exceptions, the following brief analysis of the cause of the error and solution.
First, define a simple bit field structure.
+structbit_filed {+ Unsigned A:1;+ unsigned B:1;+ unsigned C:1;+ unsigned d:1;+ unsigned e:1;+ unsigned f:1;+ unsigned g:1;+ unsigned h:1;+} val;+++intTest_bitfield1 (void)+{+ VAL.A =1;+return 0;+}++intTest_bitfield2 (void)+{+ val.b =1;+return 0;+}
Then disassembly
Ffffffc0005421e8 <test_bitfield1>: ffffffc0005421e8:f0000fa1 adrp x1, ffffffc000739000<__hyp_idmap_text_end+0x4800>ffffffc0005421ec:f9426821 LDR x1, [x1,#1232]ffffffc0005421f0:52800000mov w0, #0x0 //#0 ffffffc0005421f4: 39400022 LDRB W2, [X1]Ffffffc0005421f8:32000042Orr W2, W2, #0x1FFFFFFC0005421FC:39000022strb W2, [x1]ffffffc000542200:d65f03c0 ret ffffffc000542204<test_bitfield2>: ffffffc000542204:f0000fa1 adrp x1, ffffffc000739000<__hyp_idmap_text_end+0x4800>ffffffc000542208:f9426821 LDR x1, [x1,#1232]ffffffc00054220c:52800000mov w0, #0x0 //#0 ffffffc000542210: 39400022 LDRB W2, [X1]ffffffc000542214:321f0042 Orr W2, W2, #0x2ffffffc000542218:39000022strb W2, [x1]ffffffc00054221c:d65f03c0 ret
As you can see, in this case the minimum memory cell is a byte, and a copy is read from RAM in the yellow instruction, if Test_bitfield1 is test_bitfield2 forcibly inserted after executing the yellow instruction, Test_ Bitfield2 execution is complete, Test_bitfield1 continues to execute,
In this case, the changes made by TEST_BITFIELD2 are discarded.
So if you need to use bit filed struct normally, you need to pay attention to:
1. Different bit domain variables are not in a storage unit (can be viewed through disassembly) inside
2. There is no possibility of concurrent access.
The following article analyzes this problem and gives several solutions:
https://www.securecoding.cert.org/confluence/display/seccode/CON32-C.+Prevent+data+races+when+accessing+ Bit-fields+from+multiple+threads
- One approach for preventing data races in concurrent programming are to use a mutex
- Another approach is to insert a Non-bit-field member between any and bit-fields to ensure that each bit-field are the only One accessed within its storage unit.
- Use distinct Non-bit-field members of a structure
Analysis on the problem of multi-threaded access error in bit-domain structure