On 24 July 2013 09:20, Nevin Liber <span dir="ltr"><<a href="mailto:nevin@eviloverlord.com" target="_blank">nevin@eviloverlord.com</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">On 24 July 2013 06:58, Gabriel Dos Reis <span dir="ltr"><<a href="mailto:gdr@cs.tamu.edu" target="_blank">gdr@cs.tamu.edu</a>></span> wrote:<br></div><div class="gmail_quote"><div class="im"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div>The "union hack" is treacherous and needs far more investigation</div>
than it appears.</blockquote><div><br></div></div><div>So treacherous that people have been managing to use it for the last 30 years or so?</div><div class="im"><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
Are we going to mandate that the reintepretation of<br>
the bits cannot possibly yield trap representation? </blockquote><div><br></div></div><div>I wouldn't. This is for non-portable machine-specific code. If you blow a trap representation or an alignment access, you are on your own.</div>
<div><br></div><div>If I wanted to do this via copying, I'd just use Java.<br></div></div></blockquote><div><br>Assuming no alignment, packing, endian or malformed packet issues, here is an example of what people want to do:<br>
<br><font size="1"><span style="font-family:courier new,monospace">enum class Protocol : char<br>{<br> UDP = 17, <br> // ...<br>};<br><br>struct IPHeader<br>{<br> //...<br> Protocol protocol;<br> // ...<br>
};<br><br>struct UDPHeader : IPHeader<br>{<br> //...<br> uint16_t length;<br> //...<br> char data[1];<br>};<br><br>union Header<br>{<br> IPHeader ip; <br> UDPHeader udp;<br> //...<br>};<br><br>// Deliver payload to f without copying<br>
Payload(dynarray<char> const& packet, std::function<void(char const*, char const*)> const& f)<br>{<br> // Want to overlay Header on packet.data()<br> auto& header = *static_cast<Header const*>(static_cast<void const*>(packet.data()));<br>
<br> switch (header.ip.protocol)<br> { <br> case Protocol::UDP:<br> f(&header.udp.data[0], &header.udp.data[header.udp.length - 8]);<br> break;<br> //...<br> } <br>
<br>}</span><br></font><br>Q1: How many places has undefined behavior been invoked in the above?<br>Q2: What is the correct way to write this code?<br></div></div>-- <br> Nevin ":-)" Liber <mailto:<a href="mailto:nevin@eviloverlord.com" target="_blank">nevin@eviloverlord.com</a>> (847) 691-1404