Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A typical situation you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to <code>uint32_t</code>s or <code>uint16_t</code>s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.</p> <p>So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:</p> <pre><code>typedef struct Msg { unsigned int a; unsigned int b; } Msg; void SendWord(uint32_t); int main(void) { // Get a 32-bit buffer from the system uint32_t* buff = malloc(sizeof(Msg)); // Alias that buffer through message Msg* msg = (Msg*)(buff); // Send a bunch of messages for (int i =0; i &lt; 10; ++i) { msg-&gt;a = i; msg-&gt;b = i+1; SendWord(buff[0]); SendWord(buff[1]); } } </code></pre> <p>The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a <a href="http://en.cppreference.com/w/c/language/type" rel="noreferrer">compatible type</a> or one of the other types allowed by C 2011 6.5 paragraph 7<sup>1</sup> is undefined behavior. Unfortunately, you can still code this way, <em>maybe</em> get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code. </p> <p>(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)</p> <p>To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of <code>buff</code> every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load <code>buff[0]</code> and <code>buff[1</code>] into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of <code>buff</code> could change at anytime from anywhere by anybody. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.</p> <p>Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.</p> <pre><code>void SendMessage(uint32_t* buff, size_t size32) { for (int i = 0; i &lt; size32; ++i) { SendWord(buff[i]); } } </code></pre> <p>And rewrote our earlier loop to take advantage of this convenient function</p> <pre><code>for (int i = 0; i &lt; 10; ++i) { msg-&gt;a = i; msg-&gt;b = i+1; SendMessage(buff, 2); } </code></pre> <p>The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If <code>SendMessage</code> is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.</p> <p><strong>So how do I get around this?</strong></p> <ul> <li><p>Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.</p> <pre><code>union { Msg msg; unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)]; }; </code></pre></li> <li><p>You can disable strict aliasing in your compiler (<a href="http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825" rel="noreferrer">f[no-]strict-aliasing</a> in gcc)) </p></li> <li><p>You can use <code>char*</code> for aliasing instead of your system's word. The rules allow an exception for <code>char*</code> (including <code>signed char</code> and <code>unsigned char</code>). It's always assumed that <code>char*</code> aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.</p></li> </ul> <p><strong>Beginner beware</strong></p> <p>This is only one potential minefield when overlaying two types onto each other. You should also learn about <a href="http://en.wikipedia.org/wiki/Endianness" rel="noreferrer">endianness</a>, <a href="http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/aligned.html" rel="noreferrer">word alignment</a>, and how to deal with alignment issues through <a href="http://grok2.tripod.com/structure_packing.html" rel="noreferrer">packing structs</a> correctly.</p> <h2>Footnote</h2> <p><sup>1</sup> The types that C 2011 6.5 7 allows an lvalue to access are:</p> <ul> <li>a type compatible with the effective type of the object,</li> <li>a qualified version of a type compatible with the effective type of the object,</li> <li>a type that is the signed or unsigned type corresponding to the effective type of the object,</li> <li>a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,</li> <li>an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or</li> <li>a character type.</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload