From d8985ea10c911c994e00dbd6a08dcae907ebc1f7 Mon Sep 17 00:00:00 2001 From: Jakub Jelinek Date: Wed, 22 May 2024 09:12:28 +0200 Subject: [PATCH] ubsan: Use right address space for MEM_REF created for bool/enum sanitization [PR115172] The following testcase is miscompiled, because -fsanitize=bool,enum creates a MEM_REF without propagating there address space qualifiers, so what should be normally loaded using say %gs:/%fs: segment prefix isn't. Together with asan it then causes that load to be sanitized. 2024-05-22 Jakub Jelinek PR sanitizer/115172 * ubsan.c (instrument_bool_enum_load): If rhs is not in generic address space, use qualified version of utype with the right address space. Formatting fix. * gcc.dg/asan/pr115172.c: New test. (cherry picked from commit d3c506eff54fcbac389a529c2e98da108a410b7f) --- gcc/testsuite/gcc.dg/asan/pr115172.c | 20 ++++++++++++++++++++ gcc/ubsan.c | 6 +++++- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 gcc/testsuite/gcc.dg/asan/pr115172.c diff --git a/gcc/testsuite/gcc.dg/asan/pr115172.c b/gcc/testsuite/gcc.dg/asan/pr115172.c new file mode 100644 index 000000000000..8707e6157331 --- /dev/null +++ b/gcc/testsuite/gcc.dg/asan/pr115172.c @@ -0,0 +1,20 @@ +/* PR sanitizer/115172 */ +/* { dg-do compile { target i?86-*-* x86_64-*-* } } */ +/* { dg-options "-O2 -fsanitize=address,bool -ffat-lto-objects -fdump-tree-asan1" } */ +/* { dg-final { scan-tree-dump-not "\.ASAN_CHECK " "asan1" } } */ + +#ifdef __x86_64__ +#define SEG __seg_gs +#else +#define SEG __seg_fs +#endif + +extern struct S { _Bool b; } s; +void bar (void); + +void +foo (void) +{ + if (*(volatile _Bool SEG *) (__UINTPTR_TYPE__) &s.b) + bar (); +} diff --git a/gcc/ubsan.c b/gcc/ubsan.c index 2b12651b4406..f77dee5fddd9 100644 --- a/gcc/ubsan.c +++ b/gcc/ubsan.c @@ -1703,13 +1703,17 @@ instrument_bool_enum_load (gimple_stmt_iterator *gsi) || TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME) return; + addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (rhs)); + if (as != TYPE_ADDR_SPACE (utype)) + utype = build_qualified_type (utype, TYPE_QUALS (utype) + | ENCODE_QUAL_ADDR_SPACE (as)); bool ends_bb = stmt_ends_bb_p (stmt); location_t loc = gimple_location (stmt); tree lhs = gimple_assign_lhs (stmt); tree ptype = build_pointer_type (TREE_TYPE (rhs)); tree atype = reference_alias_ptr_type (rhs); gimple *g = gimple_build_assign (make_ssa_name (ptype), - build_fold_addr_expr (rhs)); + build_fold_addr_expr (rhs)); gimple_set_location (g, loc); gsi_insert_before (gsi, g, GSI_SAME_STMT); tree mem = build2 (MEM_REF, utype, gimple_assign_lhs (g), -- 2.47.2