Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler constant indicating memory alignment requirement

Some CPU architectures (other than x86) dislike reading and writing multibyte numbers at unaligned addresses so much that they raise SIGBUS exception upon detecting this and forcing the programmer to do everything manually on a byte-wise order. While nothing probably can be done with platforms that require this, it would be stupid to check for alignment and perform byte-wise operations on platforms that allow unaligned access (such as x86). The question is: do C/C++ compilers define a constant that indicates alignment requirement?

Currently, I'm using this:

#if defined(_M_IX86) | defined(__i386) | defined(__i386__) | defined(i386) | defined(_X86_)
    // Unaligned access is allowed.
#elif defined(_M_X64) | defined(__x86_64__) | defined(__x86_64) | defined(__amd64) | defined(__amd64__) | defined(_M_AMD64)
    // Unaligned access is allowed.
#else
    #define ALIGNED_ACCESS_ONLY
#endif

But it looks too “home-brew”: rather than indicating the actual properties of current hardware platform, it only depicts my own considerations about x86-32 and x86-64 and the most popular constant names for these platforms.

like image 537
Anton Samsonov Avatar asked Nov 27 '22 06:11

Anton Samsonov


1 Answers

I am not technically answering the question you posed, but I am proposing a workaround in case the answer to your question is no.

If your code is compiled with the help of a configure script, you can test to see if aligned access is required. GNU autoconf has a feature for doing this:

http://www.gnu.org/software/autoconf-archive/ax_check_aligned_access_required.html

Basically it compiles the following small program, runs it, and looks at the result:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char* string = malloc(40);
  int i;
  for (i=0; i < 40; i++)
  {
    string[[i]] = i;
  }

  {
     void* s = string;
     int* p = s+1;
     int* q = s+2;

     if (*p == *q) { return 1; }
  }
  return 0;
}
like image 130
David Grayson Avatar answered Dec 20 '22 14:12

David Grayson