[cfe-dev] Diagnostic for under-aligned pointers

Vedant Kumar via cfe-dev cfe-dev at lists.llvm.org
Fri Sep 16 13:09:32 PDT 2016


Hi,

Does it make sense to emit a diagnostic when we implicitly cast a pointer to
another pointer type with a higher required alignment?

Here's an example where this might be useful. The pointer "uiptr" is at least
1-byte aligned, but it's implicitly cast to "int *" (and treated as at least
8-byte aligned):

    extern int printf(const char *S, ...);
    
    int load_aligned(int *ptr) {
      printf("Alignment of ptr: %lu\n", __alignof__(ptr));
      return *ptr;
    }
    
    typedef int unaligned_int __attribute__((aligned(1)));
    
    int main() {
      unaligned_int ui = 0;
      unaligned_int *__attribute__((aligned(1))) uiptr = &ui;
      printf("Alignment of uiptr: %lu\n", __alignof__(uiptr));
      return load_aligned(uiptr);
    }

When compiled with ToT clang, this program prints out:

    Alignment of uiptr: 1
    Alignment of ptr: 8

IIUC, users should only see the warning if they opt into lowering the alignment
of a pointer. I wouldn't expect this to be too noisy, but I don't have any data
on this.

It's true that we can catch this issue with ubsan, but only when the value of
"uiptr" is actually not 8-byte aligned. Besides, it might be helpful to have a
compile-time check for this (e.g in situations where it's tricky to deploy the
sanitizer runtime).

best,
vedant


More information about the cfe-dev mailing list