Should GCC prevent unaligned memory access on Cortex-M0?

Comments

4 comments

  • Avatar
    Michael Johnson

    Not that I know of, a cortex-m3 is a better bet if you have a lot of code doing unaligned access.

    0
    Comment actions Permalink
  • Avatar
    Dr Danish Ali

    Gcc should not (on its own) make a long * point to an unaligned address, or where it does it should generate appropriate code for the access.

    What might you be doing to get into that situation?

    One thing that springs to mind is if you have a pointer-to-char (which is allowed to point to any address) and then pass that to a pointer-to-long. This is a dodgy action and should generate an error or warning in the compiler - unless you do an explicit cast which is telling the compiler that you know the address you're pointing to won't end up as unaligned.

    I haven't tested this, but you might be able to trick the compiler into producing code that allows for unaligned accesses by marking the item as packed:

    struct unalignedlong {

        long l;

    } __attribute__ ((packed));

    char *t = "testing";

    unalignedlong *ul = (unalignedlong *)t;

    long l = ul->l;

    ul = (unalignedlong *)&t[1];     // if the first assignment happened to be aligned, this one won't be

    l += ul->l;

    Hope this helps,

    Danish

    0
    Comment actions Permalink
  • Avatar
    Jay K

    Of course there's a cast involved here.

    I tried adding -Wcast-align to the compiler options, but no warning was generated.

    I'm also going to try -mno-unaligned-access and see if the code generated is any different.

    This isn't a big deal... I can work around it with a little extra code.  I'm just trying to understand if the compiler should be able to detect and correct this.  I understand the memory address isn't know until link-time, but is alignment known at compile-time?  If not, what's the point of the two above options?

     

     

    0
    Comment actions Permalink
  • Avatar
    Dr Danish Ali

    Interesting. I hadn't heard of -Wcast-align; I'll include it in my future builds (on top of -Wall -Wextra)

    I have just tried the following code and I do get cast-align warnings so I'm not sure why you don't get them. The processor selected was stm32f030C6

    struct unalignedlong {
    long l;
    } __attribute__ ((packed)) ;

    struct alignedlong {
    long l;
    };

    char *t = "testing";

    int main(void)
    {
    struct unalignedlong *ul = (struct unalignedlong *)&t[2];
    struct alignedlong *al = (struct alignedlong *)&t[2]; // gives warning: cast increases required alignment of target type [-Wcast-align]
    long *pl = (long *)&t[2]; // gives warning: cast increases required alignment of target type [-Wcast-align]
    long l = ul->l;
    ul = &t[1]; // gives warning: assignment from incompatible pointer type
    l += ul->l + *pl + al->l;
    return 0;
    }

    0
    Comment actions Permalink

Please sign in to leave a comment.