Re: Detecting pointer misalignment (was Re: pgsql: Implementation of subscripting for jsonb) - Mailing list pgsql-hackers

From Tom Lane
Subject Re: Detecting pointer misalignment (was Re: pgsql: Implementation of subscripting for jsonb)
Date
Msg-id 628089.1612802981@sss.pgh.pa.us
Whole thread Raw
In response to Re: Detecting pointer misalignment (was Re: pgsql: Implementation of subscripting for jsonb)  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: Detecting pointer misalignment (was Re: pgsql: Implementation of subscripting for jsonb)
List pgsql-hackers
I wrote:
> After digging in gcc's release history, it seems they invented
> "-fsanitize=alignment" in GCC 5, so we can make this work for gcc
> by writing
> #if __GNUC__ >= 5
> (the likely() macro already uses a similar approach).  Can't say
> if that's close enough for clang too.

Ugh, no it isn't: even pretty recent clang releases only define
__GNUC__ as 4.  It looks like we need a separate test on clang's
version.  I looked at their version history and sanitizers seem
to have come in around clang 7, so I propose the attached (where
I worked a bit harder on the comment, too).

            regards, tom lane

diff --git a/src/include/c.h b/src/include/c.h
index ae978830da..a86342093e 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -132,6 +132,18 @@
 #define pg_nodiscard
 #endif

+/*
+ * Place this macro before functions that should be allowed to make misaligned
+ * accesses.  Think twice before using it on non-x86-specific code!
+ * Testing can be done with "-fsanitize=alignment -fsanitize-trap=alignment"
+ * on clang, or "-fsanitize=alignment -fno-sanitize-recover=alignment" on gcc.
+ */
+#if __clang_major__ >= 7 || __GNUC__ >= 5
+#define pg_attribute_no_sanitize_alignment() __attribute__((no_sanitize("alignment")))
+#else
+#define pg_attribute_no_sanitize_alignment()
+#endif
+
 /*
  * Append PG_USED_FOR_ASSERTS_ONLY to definitions of variables that are only
  * used in assert-enabled builds, to avoid compiler warnings about unused
diff --git a/src/port/pg_crc32c_sse42.c b/src/port/pg_crc32c_sse42.c
index 3b94a7388a..10fc01e1f0 100644
--- a/src/port/pg_crc32c_sse42.c
+++ b/src/port/pg_crc32c_sse42.c
@@ -18,6 +18,7 @@

 #include "port/pg_crc32c.h"

+pg_attribute_no_sanitize_alignment()
 pg_crc32c
 pg_comp_crc32c_sse42(pg_crc32c crc, const void *data, size_t len)
 {

pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Re: Made ecpg compatibility mode and run-time behaviour options case insensitive
Next
From: "Euler Taveira"
Date:
Subject: Re: pg_replication_origin_drop API potential race condition