2

I'm trying to build a struct that holds various fields, of varying size. Since I'd like to also compute an HMAC over the concatenated fields I thought it might be nice to just be able to pass a pointer to the struct instance to the HMAC function. However, I'm fearing that some compilers may add padding to between the struct fields, which would lead to inconsistent HMAC results.

Is there a portable way to ensure that the compiler does not add padding between the fields?

cdecker
  • 4,515
  • 8
  • 46
  • 75
  • 4
    There is no truly portable way to do this, and in some cases, no way to do it *at all*. OS/400, for example, *requires* pointer variables, including structure members, reside on a 16-byte paragraph boundary, and will enforce this with extreme prejudice regardless of how much, or what form, of packing you request for a struct type containing members of that ilk. – WhozCraig Jul 06 '16 at 19:10
  • Why not just calculate HMAC on the `sizeof(instance_of_structure)`. If you'd prefer to use a pointer, then `sizeof(*ptr_to_struct)`. – user590028 Jul 06 '16 at 19:10
  • 1
    @WhozCraig and it is really frustrating as it is a *very* common problem.. – Eugene Sh. Jul 06 '16 at 19:10
  • @user590028 OP is trying to avoid possibly indeterminate content of padding bits. – WhozCraig Jul 06 '16 at 19:11
  • @user590028 Because this size will be different on different compilers, which the OP sees as a problem – Eugene Sh. Jul 06 '16 at 19:11
  • 3
    The only portable way would be to manually copy the fields into a memory buffer one by one. – Eugene Sh. Jul 06 '16 at 19:14
  • Ahh -- you mean you OP want's to calculate platform independent HMAC that disregards structure packing? – user590028 Jul 06 '16 at 19:14
  • 1
    The best solution I came up with so far is to have a buffer field with all the data and then also have pointers in the struct that point into that buffer at the appropriate places, but it's a bit tricky to ensure these pointers always point to the correct location. – cdecker Jul 06 '16 at 19:16
  • 1
    The best approach is Eugene Sh's suggestion. – user590028 Jul 06 '16 at 19:18
  • But even given the theory above, the most common (and very deprecated, but mostly working) approach is still to rely on the `packed` attribute :D (Disclaimer - I am not advocating it by any means) – Eugene Sh. Jul 06 '16 at 19:24
  • @cdecker *The best solution I came up with so far is to have a buffer field with all the data and then also have pointers in the struct that point into that buffer at the appropriate places* That won't work in general. The object you're pointing to might not be properly aligned for the architecture you're running on. For example, [simple `long` values on SPARC hardware](https://docs.oracle.com/cd/E19205-01/819-5265/bjbbi/index.html). See http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule – Andrew Henle Jul 06 '16 at 21:18

0 Answers0