<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="../assets/xml/rss.xsl" media="all"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Diplomats can code too! (Posts about c++)</title><link>https://wintermade.it/blog/</link><description></description><atom:link href="https://wintermade.it/blog/categories/c%2B%2B.xml" rel="self" type="application/rss+xml"></atom:link><language>en</language><lastBuildDate>Fri, 15 Nov 2019 19:31:26 GMT</lastBuildDate><generator>Nikola (getnikola.com)</generator><docs>http://blogs.law.harvard.edu/tech/rss</docs><item><title>Value Struct - wrapping values for strong typing</title><link>https://wintermade.it/blog/posts/value-struct.html</link><dc:creator>Alessandro Balzano</dc:creator><description>&lt;div&gt;&lt;p&gt;One of my favorite tricks of C++ is this one simple compile-time device: &lt;strong&gt;value structs&lt;/strong&gt;.
This trick consists of a struct that wraps its only field, which type is a primitive one (int, float, ...).&lt;/p&gt;
&lt;div class="section" id="everything-seems-the-same"&gt;
&lt;h2&gt;Everything seems the same...&lt;/h2&gt;
&lt;p&gt;Let's start with a very simple example: converting between radians and degrees.&lt;/p&gt;
&lt;pre class="code text"&gt;&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-1"&gt;&lt;/a&gt;#include &amp;lt;iostream&amp;gt;
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-2"&gt;&lt;/a&gt;
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-3"&gt;&lt;/a&gt;float to_rad(float deg) {
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-4"&gt;&lt;/a&gt;    return deg * 3.14 / 180;
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-5"&gt;&lt;/a&gt;}
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-6"&gt;&lt;/a&gt;
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-7"&gt;&lt;/a&gt;float to_deg(float rad) {
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-8"&gt;&lt;/a&gt;    return rad * 180 / 3.14;
&lt;a name="rest_code_c9ff6d30c37a4e958001213f0c59174f-9"&gt;&lt;/a&gt;}
&lt;/pre&gt;&lt;p&gt;You may wonder: what's wrong with this code? Nothing, the code is fine.
The problem is... nothing can stop you from using a value
representing a "degree" to be passed to a function that
takes a "radiant".&lt;/p&gt;
&lt;pre class="code text"&gt;&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-1"&gt;&lt;/a&gt;int main() {
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-2"&gt;&lt;/a&gt;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-3"&gt;&lt;/a&gt;    float half_pi = 1.57;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-4"&gt;&lt;/a&gt;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-5"&gt;&lt;/a&gt;    // `half_pi` is 90 degrees in radians
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-6"&gt;&lt;/a&gt;    float ninety_deg = to_deg(half_pi);
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-7"&gt;&lt;/a&gt;    std::cout &amp;lt;&amp;lt; ninety_deg &amp;lt;&amp;lt; std::endl;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-8"&gt;&lt;/a&gt;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-9"&gt;&lt;/a&gt;    // 90... degrees or radians? the compiler doesn't care!
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-10"&gt;&lt;/a&gt;    float what = to_deg(ninety_deg);
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-11"&gt;&lt;/a&gt;    std::cout &amp;lt;&amp;lt; what &amp;lt;&amp;lt; std::endl;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-12"&gt;&lt;/a&gt;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-13"&gt;&lt;/a&gt;    return 0;
&lt;a name="rest_code_05112a61f7bd44bea5d304961761366e-14"&gt;&lt;/a&gt;}
&lt;/pre&gt;&lt;p&gt;Unfortunately, this issue is &lt;a class="reference external" href="https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure"&gt;more widespread than you think&lt;/a&gt;, and I've seen it happen several times.&lt;/p&gt;
&lt;p&gt;A variant of this problem shows up when a function &lt;code&gt;fun(int caller_id, int message_id)&lt;/code&gt; has two parameters with the same type, and someone swaps them (&lt;code&gt;fun(int message_id, int caller_id)&lt;/code&gt;).
If the client code is not updated to reflect this change, the program may not work correctly anymore. The compiler, however, will &lt;em&gt;not&lt;/em&gt; warn about this change!&lt;/p&gt;
&lt;p&gt;Let's go back to the original problem: what if &lt;cite&gt;to_deg&lt;/cite&gt; and &lt;cite&gt;to_rad&lt;/cite&gt; accept and return a special type, instead of a raw float?&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="wrapping-values"&gt;
&lt;h2&gt;Wrapping values&lt;/h2&gt;
&lt;p&gt;Let's create two ad-hoc structures for our Degrees and Radians. Both structures
will wrap a single float, that can be accessed directly.&lt;/p&gt;
&lt;pre class="code text"&gt;&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-1"&gt;&lt;/a&gt;struct Degrees {
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-2"&gt;&lt;/a&gt;    float value;
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-3"&gt;&lt;/a&gt;    Degrees(float v): value(v){}
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-4"&gt;&lt;/a&gt;};
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-5"&gt;&lt;/a&gt;
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-6"&gt;&lt;/a&gt;struct Radians {
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-7"&gt;&lt;/a&gt;    float value;
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-8"&gt;&lt;/a&gt;    Radians(float v): value(v){}
&lt;a name="rest_code_a7d12585de5f49109ef28f1ef5c43f2c-9"&gt;&lt;/a&gt;};
&lt;/pre&gt;&lt;p&gt;These two structs look exactly the same, but they are different types,
and the compiler will treat them as such. No mixing allowed, this time!&lt;/p&gt;
&lt;pre class="code text"&gt;&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-1"&gt;&lt;/a&gt;Radians to_rad(Degrees d){
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-2"&gt;&lt;/a&gt;    return d.value * 180 / 3.14;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-3"&gt;&lt;/a&gt;}
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-4"&gt;&lt;/a&gt;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-5"&gt;&lt;/a&gt;Degrees to_deg(Radians r) {
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-6"&gt;&lt;/a&gt;    return r.value * 3.14 / 180;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-7"&gt;&lt;/a&gt;}
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-8"&gt;&lt;/a&gt;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-9"&gt;&lt;/a&gt;int main() {
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-10"&gt;&lt;/a&gt;    Radians half_pi = Radians(1.57);
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-11"&gt;&lt;/a&gt;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-12"&gt;&lt;/a&gt;    Degrees ninety_degrees = to_deg(half_pi);
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-13"&gt;&lt;/a&gt;    std::cout &amp;lt;&amp;lt; ninety_degrees.value &amp;lt;&amp;lt; std::endl;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-14"&gt;&lt;/a&gt;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-15"&gt;&lt;/a&gt;    // Degrees what = to_deg(ninety_degrees);       // COMPILE ERROR!
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-16"&gt;&lt;/a&gt;    // std::cout &amp;lt;&amp;lt; what.value &amp;lt;&amp;lt; std::endl;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-17"&gt;&lt;/a&gt;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-18"&gt;&lt;/a&gt;    return 0;
&lt;a name="rest_code_0b199b505a5640e99826e5e34f60ed26-19"&gt;&lt;/a&gt;}
&lt;/pre&gt;&lt;/div&gt;
&lt;div class="section" id="under-the-hood-nothing-has-changed"&gt;
&lt;h2&gt;Under the hood, nothing has changed&lt;/h2&gt;
&lt;p&gt;You may now think: "wait, are we going to create a lot of temporary objects? It's going to be slow!". Well, gcc and clang recognize
this pattern, and will replace &lt;cite&gt;Degrees&lt;/cite&gt; and &lt;cite&gt;Radians&lt;/cite&gt; with the &lt;cite&gt;float&lt;/cite&gt; value - as if those structures were never defined.&lt;/p&gt;
&lt;p&gt;Let's compare the generated assembly code, generated by gcc 9.1.0 (compile flags: &lt;cite&gt;-O2&lt;/cite&gt;).
In this listing, we are going to examine the difference between the first, float-based version (left side)
and the struct-based version (right side).&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: section .LFE1544 and section .LFE1551 define to_deg(float) and to_deg(Radians).&lt;/em&gt;
&lt;em&gt;section .LFB1545 and section .LF1552 contain the code that is executed - the "real code"&lt;/em&gt;&lt;/p&gt;
&lt;pre class="code text"&gt;&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-1"&gt;&lt;/a&gt;.LFE1544:                                       |       .LFE1551:
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-2"&gt;&lt;/a&gt;        .size   _Z6to_radf, .-_Z6to_radf        |               .size   _Z6to_rad7Degrees, .-_Z6to_rad7Degrees
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-3"&gt;&lt;/a&gt;        .p2align 4                                              .p2align 4
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-4"&gt;&lt;/a&gt;        .globl  _Z6to_degf                      |               .globl  _Z6to_deg7Radians
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-5"&gt;&lt;/a&gt;        .type   _Z6to_degf, @function           |               .type   _Z6to_deg7Radians, @function
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-6"&gt;&lt;/a&gt;_Z6to_degf:                                     |       _Z6to_deg7Radians:
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-7"&gt;&lt;/a&gt;.LFB1545:                                       |       .LFB1552:
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-8"&gt;&lt;/a&gt;        .cfi_startproc                                          .cfi_startproc
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-9"&gt;&lt;/a&gt;        mulss   .LC2(%rip), %xmm0                               mulss   .LC2(%rip), %xmm0
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-10"&gt;&lt;/a&gt;        cvtss2sd        %xmm0, %xmm0                            cvtss2sd        %xmm0, %xmm0
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-11"&gt;&lt;/a&gt;        divsd   .LC0(%rip), %xmm0                               divsd   .LC0(%rip), %xmm0
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-12"&gt;&lt;/a&gt;        cvtsd2ss        %xmm0, %xmm0                            cvtsd2ss        %xmm0, %xmm0
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-13"&gt;&lt;/a&gt;        ret                                                     ret
&lt;a name="rest_code_1d0915448ddd4e21841856e37ce0bbd7-14"&gt;&lt;/a&gt;        .cfi_endproc                                            .cfi_endproc
&lt;/pre&gt;&lt;p&gt;As we can see, the difference is just in the description of the
function: the real code is the same.
Both versions perform the same multiplications and divisions, and read the same registers.&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="conclusion"&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;In this blog post, we looked at value structs, that are structures that wrap
a single field, and how we can use them to type-check our code and avoid mixing
raw values. We also looked the assembly code, and noticed that
the wrappers we introduced do not affect the performance of our code: they are compiled
as if we just used the raw values.&lt;/p&gt;
&lt;p&gt;If you feel that this article helped you, feel free to share it! If you have questions, ask on &lt;a class="reference external" href="https://twitter.com/alfateam123"&gt;Twitter&lt;/a&gt;,
or offer me a &lt;a class="reference external" href="https://ko-fi.com/alessandrobalzano"&gt;coffee&lt;/a&gt; to let me keep writing these notes!&lt;/p&gt;
&lt;/div&gt;
&lt;div class="section" id="references"&gt;
&lt;h2&gt;References:&lt;/h2&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;&lt;a class="reference external" href="https://gist.github.com/alfateam123/042d37c2f944089e424bc01c7c569b1b"&gt;https://gist.github.com/alfateam123/042d37c2f944089e424bc01c7c569b1b&lt;/a&gt; - the source code used in this article.&lt;/li&gt;
&lt;li&gt;&lt;a class="reference external" href="https://www.youtube.com/watch?v=1fwbG5TyI18"&gt;https://www.youtube.com/watch?v=1fwbG5TyI18&lt;/a&gt; - CppCon 2018: Arno Lepisk "Avoiding Disasters with Strongly Typed C++"&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;&lt;/div&gt;</description><category>c++</category><guid>https://wintermade.it/blog/posts/value-struct.html</guid><pubDate>Fri, 15 Nov 2019 18:31:00 GMT</pubDate></item><item><title>__attribute__((packed)) on Windows is ignored (with MinGW)!</title><link>https://wintermade.it/blog/posts/__attribute__packed-on-windows-is-ignored-with-mingw.html</link><dc:creator>Alessandro Balzano</dc:creator><description>&lt;div&gt;&lt;p&gt;&lt;strong&gt;tl;dr&lt;/strong&gt; by default, MinGW on win32 behaves as if it ignores
&lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;__attribute__((packed))&lt;/span&gt;&lt;/tt&gt;, you need to add &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-mno-ms-bitfields&lt;/span&gt;&lt;/tt&gt; to
make it work as expected.&lt;/p&gt;
&lt;p&gt;Some days ago, I was tasked with a port of a simple networked
application to Windows 7. There is a small issue, though: to serialize
the messages, the code filled a packed structure, that is then memcpy-ed
into a buffer and then thrown into the TCP stack. &lt;em&gt;Don't blame me, I
trusted a bad advice, I was young and stupid!&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We may get away with it (it works, somehow!). The big problem here
is that everything falls apart if the structure layout
is not like we expect it to be! In the best case, the application
segfaults because it tried to access some memory we should &lt;em&gt;not&lt;/em&gt; access,
or some internal checks fire because the values are so wrong they simply
are out of range.&lt;/p&gt;
&lt;p&gt;Let's say I'm passing this packed structure around...&lt;/p&gt;
&lt;pre class="code cpp"&gt;&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-1"&gt;&lt;/a&gt;&lt;span class="k"&gt;typedef&lt;/span&gt; &lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="n"&gt;_mypackedstruct&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-2"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint32_t&lt;/span&gt; &lt;span class="n"&gt;magic_number&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-3"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint8_t&lt;/span&gt;  &lt;span class="n"&gt;version&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-4"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint32_t&lt;/span&gt; &lt;span class="n"&gt;interesting_property&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-5"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;creation_time_sec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-6"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;creation_time_usec&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-7"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint32_t&lt;/span&gt; &lt;span class="n"&gt;first_info_no&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-8"&gt;&lt;/a&gt;  &lt;span class="kt"&gt;uint32_t&lt;/span&gt; &lt;span class="n"&gt;second_info_no&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_a239aec82db54c81bbf6a7127c5403f7-9"&gt;&lt;/a&gt;&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="n"&gt;__attribute__&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="n"&gt;packed&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="n"&gt;MyPackedStructure&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/pre&gt;&lt;p&gt;... and the code receives and parses the serialized structure, as in the following pseudo-C++ example&lt;/p&gt;
&lt;pre class="code cpp"&gt;&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-1"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// a very simplified sample of the code that highlighted the problem&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-2"&gt;&lt;/a&gt;&lt;span class="n"&gt;MyPackedStructure&lt;/span&gt; &lt;span class="n"&gt;destination&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-3"&gt;&lt;/a&gt;&lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;buffer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="kt"&gt;char&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="k"&gt;sizeof&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;destination&lt;/span&gt;&lt;span class="p"&gt;)];&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-4"&gt;&lt;/a&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-5"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// read some data from a previously created socket&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-6"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// and push them into a buffer&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-7"&gt;&lt;/a&gt;&lt;span class="n"&gt;socket&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;recv_message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;buffer&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-8"&gt;&lt;/a&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-9"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// push the unparsed data into destination&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-10"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// to perform an automatic "deserialization".&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-11"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// Don't try this at home. Please, use serialization libraries.&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-12"&gt;&lt;/a&gt;&lt;span class="n"&gt;memcpy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;&amp;amp;&lt;/span&gt;&lt;span class="n"&gt;destination&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;buffer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;sizeof&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;destination&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-13"&gt;&lt;/a&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-14"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// perform validity check on the structure's content.&lt;/span&gt;
&lt;a name="rest_code_1cedcc26ca6747b1a0f516f38a1ccf91-15"&gt;&lt;/a&gt;&lt;span class="n"&gt;assert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;is_packet_ok&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;destination&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
&lt;/pre&gt;&lt;p&gt;On various Linux distros, everything works fine. Once I built the project
on Windows, the &lt;tt class="docutils literal"&gt;is_packet_ok&lt;/tt&gt; assert fired. Why?&lt;/p&gt;
&lt;p&gt;After looking at the code, trying to understand the problem, I had
the idea of checking the size of the structure. On Windows
(using MinGW), &lt;tt class="docutils literal"&gt;sizeof(MyPackedStructure)&lt;/tt&gt; returns 40, while on Linux
(using three different compilers: gcc 4.6.3, gcc 4.9.2, clang/llvm 3.8) the same expression returns 33.
Seven bits sure do a big difference! I want you to focus your attention
on that 40. It's easy to recognize that &lt;tt class="docutils literal"&gt;40 mod 8 = 0&lt;/tt&gt;: the structure
was aligned to 8 bytes. Why was the packing attribute &lt;strong&gt;ignored&lt;/strong&gt;?&lt;/p&gt;
&lt;p&gt;A simple search on the Wired showed me that &lt;a class="reference external" href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52991"&gt;this strange
behavior&lt;/a&gt; is
known since April 2012, but the ticket is still marked as &lt;strong&gt;new&lt;/strong&gt;. In
the comments, you'll find a workaround: set &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-mno-ms-bitfields&lt;/span&gt;&lt;/tt&gt;.&lt;/p&gt;
&lt;p&gt;What is this &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-mno-ms-bitfiels&lt;/span&gt;&lt;/tt&gt; option? The &lt;a class="reference external" href="http://gcc.gnu.org/onlinedocs/gcc-4.9.3/gcc/Variable-Attributes.html"&gt;6.36.5 i386
Variable
Attributes&lt;/a&gt;
section of the manual says&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;"If packed is used on a structure, or if bit-fields are used, it may be
that the Microsoft ABI lays out the structure differently than the way
GCC normally does. Particularly when moving packed data between
functions compiled with GCC and the native Microsoft compiler (either
via function call or as data in a file), it may be necessary to access
either format."&lt;/p&gt;
&lt;p&gt;[snip]&lt;/p&gt;
&lt;p&gt;"2. Every data object has an alignment requirement.
The alignment requirement for all data except structures, unions, and
arrays is either the size of the object or the current packing size
(specified with either the aligned attribute or the pack pragma),
whichever is less. For structures, unions, and arrays, the alignment
requirement is the largest alignment requirement of its members. Every
object is allocated an offset so that: &lt;tt class="docutils literal"&gt;offset % alignment_requirement == 0&lt;/tt&gt;"&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;What does it mean? It means that, by default, MinGW uses the Microsoft algorithm
to calculate packed structures requirements, and it doesn't work as we'd like.&lt;/p&gt;
&lt;p&gt;The expected behavior (as described in the same link!) is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;dl class="docutils"&gt;
&lt;dt&gt;packed&lt;/dt&gt;
&lt;dd&gt;The packed attribute specifies that a variable or structure field should
have the smallest possible alignment—one byte for a variable, and one bit
for a field, unless you specify a larger value with the aligned attribute.&lt;/dd&gt;
&lt;/dl&gt;
&lt;/blockquote&gt;
&lt;p&gt;To explain it, I will write a simple program that creates a packed structure
and initializes it with known values. The program will be later inspected
with GDB in order to check the actual memory layout of the structure.&lt;/p&gt;
&lt;pre class="code cpp"&gt;&lt;a name="rest_code_d69244af253045de8b969e99908270a0-1"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// file: main.cpp&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-2"&gt;&lt;/a&gt;&lt;span class="c1"&gt;// MyPackedStructure is the same structure we defined at the start of the blog post&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-3"&gt;&lt;/a&gt;&lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(){&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-4"&gt;&lt;/a&gt;  &lt;span class="c1"&gt;// print the size of the structure&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-5"&gt;&lt;/a&gt;  &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;cout&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="s"&gt;"sizeof(MyPackedStructure) = "&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="k"&gt;sizeof&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;MyPackedStructure&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class="n"&gt;std&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;endl&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-6"&gt;&lt;/a&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-7"&gt;&lt;/a&gt;  &lt;span class="c1"&gt;// prepare a structure variable...&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-8"&gt;&lt;/a&gt;  &lt;span class="n"&gt;MyPackedStructure&lt;/span&gt; &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-9"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;magic_number&lt;/span&gt;         &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mh"&gt;0xa5a61ff5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-10"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;version&lt;/span&gt;              &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-11"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;interesting_property&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mh"&gt;0x33&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-12"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;creation_time_sec&lt;/span&gt;    &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1462224873&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-13"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;creation_time_usec&lt;/span&gt;   &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;4141457&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-14"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;first_info_no&lt;/span&gt;        &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-15"&gt;&lt;/a&gt;  &lt;span class="n"&gt;obj&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;second_info_no&lt;/span&gt;       &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-16"&gt;&lt;/a&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-17"&gt;&lt;/a&gt;  &lt;span class="c1"&gt;// ... and put a breakpoint here to inspect its memory!&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-18"&gt;&lt;/a&gt;  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;a name="rest_code_d69244af253045de8b969e99908270a0-19"&gt;&lt;/a&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/pre&gt;&lt;p&gt;I built and ran the code on ArchLinux (x86, GCC 5.3.0, GDB 7.11) and...&lt;/p&gt;
&lt;pre class="literal-block"&gt;
[~/projects/experimental/sizeof_packed_struct]&amp;gt; g++ -o test main.cpp -g # let's build it with the latest GCC on ArchLinux, x86
[winter@timeofeve] [/dev/pts/3] [master]
[~/projects/experimental/sizeof_packed_struct]&amp;gt; gdb ./test
Reading symbols from ./test...done.
(gdb) break main.cpp:29
Breakpoint 1 at 0x804875c: file main.cpp, line 29.
(gdb) r
Starting program: /home/winter/projects/experimental/sizeof_packed_struct/test
sizeof(MyPackedStructure) = 33

Breakpoint 1, main () at main.cpp:29
29        return 0;
(gdb) x /33x &amp;amp;obj  # let's dump 33 bytes of memory from the address of `obj`
0xbffff5af:     0xf5     0x1f    0xa6    0xa5    0x02   0x33    0x00    0x00
0xbffff5b7:     0x00     0xe9    0xc7    0x27    0x57   0x00    0x00    0x00
0xbffff5bf:     0x00     0x91    0x31    0x3f    0x00   0x00    0x00    0x00
0xbffff5c7:     0x00     0x05    0x00    0x00    0x00   0x02    0x00    0x00
0xbffff5cf:     0x00
&lt;/pre&gt;
&lt;p&gt;... the memory is laid out as we'd expect it: we can see the magic number in the first 4 bytes,
&lt;cite&gt;version&lt;/cite&gt; occupies only the fifth byte. &lt;cite&gt;interesting_property&lt;/cite&gt; is unaligned: the field
is 4 bytes long, but the first 3 bytes are in the first row (&lt;cite&gt;0xbffff5af&lt;/cite&gt;), and the last one
lies in the second row (&lt;cite&gt;0xbffff5b7&lt;/cite&gt;). Please note that &lt;tt class="docutils literal"&gt;MyPackedStructure&lt;/tt&gt;, on ArchLinux is 33 bytes long.&lt;/p&gt;
&lt;p&gt;If we run it on Windows 7 (x86_64, mingw 4.9.3, gdb 7.6.1, PowerShell x86), we get...&lt;/p&gt;
&lt;pre class="literal-block"&gt;
PS C:\Users\WinterHarrison\Desktop&amp;gt; g++ main.cpp -o test -g
PS C:\Users\WinterHarrison\Desktop&amp;gt; gdb .\test
Reading symbols from C:\Users\WinterHarrison\Desktop\test.exe...done.
(gdb) break main.cpp:29
Breakpoint 1 at 0x401498: file main.cpp, line 29.
(gdb) r
Starting program: C:\Users\WinterHarrison\Desktop/.\test.exe
[New Thread 164.0x5c8]
sizeof(MyPackedStructure) = 40

Breakpoint 1, _fu0___ZSt4cout () at main.cpp:29
29        return 0;
(gdb) x /40x &amp;amp;obj
0x28ff08:        0xf5    0x1f    0xa6    0xa5    0x02   (0xff    0x28    0x00)
0x28ff10:        0x33    0x00    0x00    0x00   (0x53    0x40    0x0e    0x64)
0x28ff18:        0xe9    0xc7    0x27    0x57    0x00    0x00    0x00    0x00
0x28ff20:        0x91    0x31    0x3f    0x00    0x00    0x00    0x00    0x00
0x28ff28:        0x05    0x00    0x00    0x00    0x02    0x00    0x00    0x00
&lt;/pre&gt;
&lt;p&gt;... that &lt;tt class="docutils literal"&gt;MyPackedStructure&lt;/tt&gt; is now 40 bytes long.
The fact that my Arch is 32bit doesn't mean anything, as I'm using &lt;a class="reference external" href="http://en.cppreference.com/w/c/types/integer"&gt;fixed-size integers&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Please also note that there are &lt;strong&gt;no&lt;/strong&gt; unaligned fields: &lt;cite&gt;interesting_property&lt;/cite&gt; now starts
at the first byte of the second row (&lt;cite&gt;0x28ff10&lt;/cite&gt;).&lt;/p&gt;
&lt;p&gt;This fact &lt;strong&gt;is&lt;/strong&gt; the real cause of the problem I described
at the start of this post: &lt;tt class="docutils literal"&gt;memcpy&lt;/tt&gt; writes important (and correctly packed!) data inside the &lt;cite&gt;padding bytes&lt;/cite&gt;,
that are then not considered nor accessible. When you try to read from the structure, you will
get some junk with no meaning at all. Just a simple example: after the &lt;tt class="docutils literal"&gt;memcpy&lt;/tt&gt; in the
pseudocode at the top of the article, we'd expect
&lt;tt class="docutils literal"&gt;obj.interesting_property&lt;/tt&gt; to be &lt;cite&gt;0x33&lt;/cite&gt;, but it's &lt;cite&gt;0&lt;/cite&gt; on Windows. &lt;cite&gt;0x33&lt;/cite&gt; would be where
we now can see &lt;cite&gt;0xff&lt;/cite&gt; (first row, sixth byte), but that particular address is not accessible
by the client code. Well, I may access it doing some pointer arithmetics, but isn't the point
of using a packed structure to &lt;cite&gt;avoid pointer arithmetics&lt;/cite&gt; at all?&lt;/p&gt;
&lt;p&gt;Let's now apply the suggested workaround: tell GCC "whatever, I don't care
about this MS bitfields algorithm, please do as you do on Linux" using the &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-mno-ms-bitfields&lt;/span&gt;&lt;/tt&gt;
compiler flag.&lt;/p&gt;
&lt;pre class="literal-block"&gt;
PS C:\Users\WinterHarrison\Desktop&amp;gt; g++ main.cpp -o test -g -mno-ms-bitfields
PS C:\Users\WinterHarrison\Desktop&amp;gt; gdb .\test
Reading symbols from C:\Users\WinterHarrison\Desktop\test.exe...done.
(gdb) break main.cpp:29
Breakpoint 1 at 0x401498: file main.cpp, line 29.
(gdb) r
Starting program: C:\Users\WinterHarrison\Desktop/.\test.exe
[New Thread 832.0xaf8]
sizeof(MyPackedStructure) = 33

Breakpoint 1, _fu0___ZSt4cout () at main.cpp:29
29        return 0;
(gdb) x /33x &amp;amp;obj
0x28ff0f:       0xf5    0x1f    0xa6    0xa5    0x02    0x33    0x00    0x00
0x28ff17:       0x00    0xe9    0xc7    0x27    0x57    0x00    0x00    0x00
0x28ff1f:       0x00    0x91    0x31    0x3f    0x00    0x00    0x00    0x00
0x28ff27:       0x00    0x05    0x00    0x00    0x00    0x02    0x00    0x00
0x28ff2f:       0x00
&lt;/pre&gt;
&lt;p&gt;Both the size and the memory dump look like the Linux size and dump. This is exactly
what we wanted! Everything works now! Mission accomplished, let's call it a day!&lt;/p&gt;
&lt;hr class="docutils"&gt;
&lt;p&gt;So, what did I learn from this experience?&lt;/p&gt;
&lt;ul class="simple"&gt;
&lt;li&gt;Use &lt;tt class="docutils literal"&gt;&lt;span class="pre"&gt;-mno-ms-bitfields&lt;/span&gt;&lt;/tt&gt; if you want to use packed structures on
Windows (using MinGW)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Serialization libraries&lt;/strong&gt; (cereal, messagepack, protocolbuffers, ...)
exist for a reason: to avoid writing similar blog posts and
to ensure that messages are serialized and deserialized in the same way on every platform&lt;/li&gt;
&lt;li&gt;Don't think that your code will run the same everywhere: &lt;strong&gt;always have
a test suite&lt;/strong&gt; (and don't make it a pain to build and run on a new target platform!)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Read your compiler's documentation&lt;/strong&gt;, especially if you're using
language extensions&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;That's all for today. &lt;a class="reference external" href="https://twitter.com/alfateam123"&gt;Let me know&lt;/a&gt; if you found those notes useful - if you like them,
please consider offering me a &lt;a class="reference external" href="https://www.ko-fi.com/alessandrobalzano"&gt;Ko-fi&lt;/a&gt; to let me keep writing!&lt;/p&gt;&lt;/div&gt;</description><category>c++</category><category>packed structures</category><guid>https://wintermade.it/blog/posts/__attribute__packed-on-windows-is-ignored-with-mingw.html</guid><pubDate>Fri, 06 May 2016 20:22:26 GMT</pubDate></item><item><title>Suzuha: a shim for gettimeofday</title><link>https://wintermade.it/blog/posts/suzuha-a-shim-for-gettimeofday.html</link><dc:creator>Alessandro Balzano</dc:creator><description>&lt;div&gt;&lt;p&gt;In my daily work, I have to develop a logging system for realtime applications.
Nothing too complex though, but it's &lt;em&gt;nice to have&lt;/em&gt; when your system crashes and you don't know why.&lt;/p&gt;
&lt;p&gt;I need to do a bit of integration testing, and I want to &lt;a class="reference external" href="https://wintermade.it/blog/posts/embeddable-scripting-languages-are-for-integration-testing-too.html"&gt;automatize&lt;/a&gt; it.
Obviously, requirements talk about possible timing issues and some time-based business logic,
so I have to test it, and using &lt;tt class="docutils literal"&gt;sleep&lt;/tt&gt; is not an option.&lt;/p&gt;
&lt;p&gt;How hard can it be to mock &lt;tt class="docutils literal"&gt;gettimeofday&lt;/tt&gt; ?
In C++, it requires a bit of work, but it's not impossible.
At least, a bit more work than installing &lt;a class="reference external" href="https://github.com/spulec/freezegun"&gt;freezegun&lt;/a&gt; or &lt;a class="reference external" href="https://github.com/harvesthq/time-warp"&gt;time warp&lt;/a&gt; for projects in
scripting languages such as Python or Ruby :D&lt;/p&gt;
&lt;p&gt;After a fast search on github, I found two interesting projects: &lt;a class="reference external" href="https://github.com/brettdh/mocktime"&gt;mocktime&lt;/a&gt;
and &lt;a class="reference external" href="https://github.com/dtzWill/gtod-shim"&gt;gtod-shim&lt;/a&gt;. The main problem of the former is I don't want to change my actual code to
call something different than &lt;tt class="docutils literal"&gt;gettimeofday&lt;/tt&gt;.
The latter was promising: a dynamic library you have to load at startup
that changes the runtime behaviour of time functions, making it suitable to test
time-related bugs in various applications.&lt;/p&gt;
&lt;p&gt;After some modifications (mainly make users able to change the time shift using
&lt;tt class="docutils literal"&gt;settimeofday&lt;/tt&gt; and automated testing), &lt;a class="reference external" href="https://github.com/alfateam123/suzuha"&gt;suzuha&lt;/a&gt; is now released in beta.
You can read more in the README, and check the unit tests.&lt;/p&gt;&lt;/div&gt;</description><category>c++</category><category>gettimeofday</category><guid>https://wintermade.it/blog/posts/suzuha-a-shim-for-gettimeofday.html</guid><pubDate>Sat, 26 Sep 2015 21:44:05 GMT</pubDate></item></channel></rss>