Re: C to Java Byte Code

From: Flash Gordon (spam_at_flash-gordon.me.uk)
Date: 10/27/04


Date: Wed, 27 Oct 2004 13:45:59 +0100

On Wed, 27 Oct 2004 13:06:51 +0200
"dandelion" <dandelion@meadow.net> wrote:

<snip unions>

> So if I read from a stream of data, I can overlay a set of nested
> structs/unions in order to decypher the byte-array into a structured
> message? As in the following?
>
> typedef struct
> {
> uint8 inputs;

The compiler might insert padding here...

> uint8 outputs;

or here...

> uint8 timers;

or here.

> } lc_statr_t;

Well, in C you might not have an 8 bit data type, which is presumably
what uint8 is...

> typedef struct
> {
> uint8 errno;

The compiler might insert different padding here to that which it might
(or might not) have inserted in lc_statr_t

> char message[1];
> } lc_error_t;
>
> typedef struct
> {
> uint8 opcode;
> uint8 sequence;
> } lc_msg_header_t;

I believe that lc_msgs_header_t is required to map correctly on to the
first 2 elements of lc_statr_t when they are combined in a union since
the first two elements are the same type.

> typedef struct
> {
> lc_msg_header_t hdr;
>
> union
> {
> lc_statr_t statr;
> lc_error_t error;
>
> uint8 cmd[LC_CMD_LEN]; /* placeholder */
> char name[LC_NAME_LEN];
> } data;
> } lc_msg_t;
>
> typedef struct
> {
> uint32 addr; /* originating ip_address */
> uint16 port; /* originating port */
> uint16 len; /* length of the packet */
> } lc_packet_header_t;
>
> typedef struct
> {
> lc_packet_header_t hdr;
>
> union
> {
> lc_msg_t msg;
> lc_tftp tftp;
> char buffer[LC_BUFFERSIZE];
> } u;
> } lc_packet_t;
>
> lc_packet_t.buffer is read (recv) and I can use
> lc_packet_t.msg.hdr.opcode to get at the opcode? Without actually
> moving *anything* in memory, of course, since I don't have enough RAM
> available.

*If* your compiler pads structs in the way your incoming data is padded
then I believe that you will get what you expect. However, version x.1
of your compiler might use different padding, and changing compiler
options might change the padding. So it is not a portable solution.
Also, if you had a double in there you would have a real danger of
reading a trap representation.

So if you want portable code you have to strip your message apart by
hand.

-- 
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.


Relevant Pages