All of lore.kernel.org
 help / color / mirror / Atom feed
From: Eugeniu Rosca <roscaeugeniu@gmail.com>
To: u-boot@lists.denx.de
Subject: [U-Boot] [PATCH v2 01/13] UBSAN: run-time undefined behavior sanity checker
Date: Mon, 27 Aug 2018 01:13:19 +0200	[thread overview]
Message-ID: <20180826231332.2491-2-erosca@de.adit-jv.com> (raw)
In-Reply-To: <20180826231332.2491-1-erosca@de.adit-jv.com>

Import Undefined Behavior SANitizer from Linux Kernel v4.18, as
implemented by Andrey Ryabinin <aryabinin@virtuozzo.com>.

Roughly, the UBSAN development history in Linux kernel looks like:

v4.18     3ca17b1f3628 ("lib/ubsan: remove null-pointer checks")
v4.17-rc1 317506009216 ("lib/test_ubsan.c: make test_ubsan_misaligned_access() static")
v4.17-rc1 854686f4edf4 ("lib: add testing module for UBSAN")
v4.16-rc1 bac7a1fff792 ("lib/ubsan: remove returns-nonnull-attribute checks")
v4.16-rc1 42440c1f9911 ("lib/ubsan: add type mismatch handler for new GCC/Clang")
v4.16-rc1 b8fe1120b4ba ("lib/ubsan.c: s/missaligned/misaligned/")
v4.10-rc1 0462554707d6 ("Kconfig: lib/Kconfig.ubsan fix reference to ubsan documentation")
 v4.9-rc5 a76bcf557ef4 ("Kbuild: enable -Wmaybe-uninitialized warning for "make W=1"")
 v4.9-rc1 725c4d22bbc4 ("ubsan: allow to disable the null sanitizer")
 v4.9-rc1 1ead009cd622 ("docs: sphinxify ubsan.txt and move it to dev-tools")
 v4.8-rc1 901d805c33fc ("UBSAN: fix typo in format string")
 v4.8-rc1 6e8d666e9253 ("Disable "maybe-uninitialized" warning globally")
 v4.6-rc1 dde5cf39d4d2 ("ubsan: fix tree-wide -Wmaybe-uninitialized false positives")
 v4.5-rc4 7707535ab95e ("ubsan: cosmetic fix to Kconfig text")
 v4.5-rc1 bf76f73c5f65 ("powerpc: enable UBSAN support")
 v4.5-rc1 c6d308534aef ("UBSAN: run-time undefined behavior sanity checker")

What's not interesting for U-Boot is:
 - 317506009216 ("lib/test_ubsan.c: make test_ubsan_misaligned_access() static")
 - 854686f4edf4 ("lib: add testing module for UBSAN")
   since they add a module-only test functionality.
 - any Documentation commits.

Since dump_stack() evaluates to NOOP in U-Boot, the UBSAN report
retains only the header from the original kernel report.

As example, below is a UB found in U-Boot thanks to UBSAN:

 ====================================================================
 UBSAN: Undefined behaviour in drivers/net/phy/phy.c:728:19
 left shift of 1 by 31 places cannot be represented in type 'int'
 ====================================================================

For comparison, below is a full-fledged kernel UBSAN report, based on
v4.17-rc4 Linux commit 0dfc0c792d69 ("iommu/vt-d: fix shift-out-of-
bounds in bug checking"):

 ================================================================================
UBSAN: Undefined behaviour in drivers/iommu/dmar.c:1348:3
shift exponent 64 is too large for 32-bit type 'int'
CPU: 2 PID: 0 Comm: swapper/2 Tainted: G     U            4.17.0-rc1+ #89
Hardware name: Dell Inc. OptiPlex 7040/0Y7WYT, BIOS 1.2.8 01/26/2016
Call Trace:
 <IRQ>
 dump_stack+0x90/0xfb
 ubsan_epilogue+0x9/0x40
 __ubsan_handle_shift_out_of_bounds+0x10e/0x170
 ? qi_flush_dev_iotlb+0x124/0x180
-----[snip]-----
 apic_timer_interrupt+0xf/0x20
 </IRQ>
RIP: 0010:poll_idle+0x60/0xe7
RSP: 0018:ffffb1b201943e30 EFLAGS: 00000246 ORIG_RAX: ffffffffffffff13
RAX: 0000000080200000 RBX: 000000000000008e RCX: 000000000000001f
RDX: 0000000000000000 RSI: 000000002819aa06 RDI: 0000000000000000
RBP: ffff9e93c6b33280 R08: 00000010f717d567 R09: 000000000010d205
R10: ffffb1b201943df8 R11: 0000000000000001 R12: 00000000e01b169d
R13: 0000000000000000 R14: ffffffffb12aa400 R15: 0000000000000000
 cpuidle_enter_state+0xb4/0x470
 do_idle+0x222/0x310
 cpu_startup_entry+0x78/0x90
 start_secondary+0x205/0x2e0
 secondary_startup_64+0xa5/0xb0
 ================================================================================

To enable UBSAN, two prerequisites must be met from Kconfig perspective:
* ARCH has to select CONFIG_ARCH_HAS_UBSAN_SANITIZE_ALL
* defconfig has to enable CONFIG_UBSAN

Enable CONFIG_ARCH_HAS_UBSAN_SANITIZE_ALL on below architectures
(specify compiler, defconfig and phys/virt target used for testing):
* SANDBOX:
  * gcc (Ubuntu 8.1.0-5ubuntu1~16.04)
  * sandbox*_defconfig
  * x86_64 Ubuntu machine
* x86:
  * gcc (Ubuntu 8.1.0-5ubuntu1~16.04)
  * qemu-x86_defconfig
  * qemu-system-i386
* ARM:
  * arm-linux-gnueabihf-gcc (Linaro GCC 7.2-2017.11)
  * vexpress_ca9x4_defconfig
  * qemu-system-arm
* ARM64:
  * aarch64-linux-gnu-gcc (Linaro GCC 7.2-2017.11)
  * r8a7795_salvator-x_defconfig
  * R-Car H3 ES2.0 Salvator-X board
* PPC:
  * powerpc-linux-gnu-gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9)
  * qemu-ppce500_defconfig
  * qemu-system-ppc

Any defconfig update (UBSAN=y) is expected to come separately.
No functional change is intended, assuming CONFIG_UBSAN=n.

Signed-off-by: Eugeniu Rosca <erosca@de.adit-jv.com>
---

Changes in v2:
 - [Tom Rini] Relocate the ELF/BIN size measurements to the commit
   updating the sandbox defconfig, to avoid confusion.
 - [York Sun] Fix SPL build with UBSAN=y.
 - Enable CONFIG_ARCH_HAS_UBSAN_SANITIZE_ALL on x86, ARM and PPC, in
   addition to SANDBOX and ARM64 (all build and runtime tested with
   at least one defconfig as described in the commit description).
---
 Makefile                     |   3 +-
 arch/Kconfig                 |   4 ++
 arch/arm/Kconfig             |   1 +
 examples/standalone/Makefile |   2 +
 include/linux/compat.h       |   3 +
 lib/Kconfig                  |   1 +
 lib/Kconfig.ubsan            |  29 +++++++++
 lib/Makefile                 |   2 +
 lib/linux_compat.c           |   3 +
 lib/ubsan.c                  | 461 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 lib/ubsan.h                  |  94 +++++++++++++++++++++++++++++
 scripts/Makefile.lib         |   6 ++
 scripts/Makefile.ubsan       |  20 +++++++
 13 files changed, 628 insertions(+), 1 deletion(-)

diff --git a/Makefile b/Makefile
index b5bf8abc1f88..d1eeaa9dbcd2 100644
--- a/Makefile
+++ b/Makefile
@@ -391,7 +391,7 @@ export MAKE LEX YACC AWK PERL PYTHON PYTHON2 PYTHON3
 export HOSTCXX HOSTCXXFLAGS CHECK CHECKFLAGS DTC DTC_FLAGS
 
 export KBUILD_CPPFLAGS NOSTDINC_FLAGS UBOOTINCLUDE OBJCOPYFLAGS LDFLAGS
-export KBUILD_CFLAGS KBUILD_AFLAGS
+export KBUILD_CFLAGS KBUILD_AFLAGS CFLAGS_UBSAN
 
 # When compiling out-of-tree modules, put MODVERDIR in the module
 # tree rather than in the kernel tree. The kernel tree might
@@ -648,6 +648,7 @@ endif
 KBUILD_CFLAGS   += $(call cc-option,-Werror=date-time)
 
 include scripts/Makefile.extrawarn
+include scripts/Makefile.ubsan
 
 # Add user supplied CPPFLAGS, AFLAGS and CFLAGS as the last assignments
 KBUILD_CPPFLAGS += $(KCPPFLAGS)
diff --git a/arch/Kconfig b/arch/Kconfig
index bf1b4a9afac6..ebb8ee5979e0 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -19,6 +19,7 @@ config ARC
 
 config ARM
 	bool "ARM architecture"
+	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select CREATE_ARCH_SYMLINK
 	select HAVE_PRIVATE_LIBGCC if !ARM64
 	select SUPPORT_OF_CONTROL
@@ -54,6 +55,7 @@ config NIOS2
 
 config PPC
 	bool "PowerPC architecture"
+	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select HAVE_PRIVATE_LIBGCC
 	select SUPPORT_OF_CONTROL
 	select SYS_BOOT_GET_CMDLINE
@@ -65,6 +67,7 @@ config RISCV
 
 config SANDBOX
 	bool "Sandbox"
+	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select BOARD_LATE_INIT
 	select DM
 	select DM_GPIO
@@ -98,6 +101,7 @@ config SH
 
 config X86
 	bool "x86 architecture"
+	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select CREATE_ARCH_SYMLINK
 	select DM
 	select DM_PCI
diff --git a/arch/arm/Kconfig b/arch/arm/Kconfig
index 9f5eaf8591b6..0905ebce7004 100644
--- a/arch/arm/Kconfig
+++ b/arch/arm/Kconfig
@@ -6,6 +6,7 @@ config SYS_ARCH
 
 config ARM64
 	bool
+	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select PHYS_64BIT
 	select SYS_CACHE_SHIFT_6
 
diff --git a/examples/standalone/Makefile b/examples/standalone/Makefile
index 09364d84a0ad..66716d37465a 100644
--- a/examples/standalone/Makefile
+++ b/examples/standalone/Makefile
@@ -3,6 +3,8 @@
 # (C) Copyright 2000-2006
 # Wolfgang Denk, DENX Software Engineering, wd at denx.de.
 
+UBSAN_SANITIZE := n
+
 extra-y        := hello_world
 extra-$(CONFIG_SMC91111)           += smc91111_eeprom
 extra-$(CONFIG_SMC911X)            += smc911x_eeprom
diff --git a/include/linux/compat.h b/include/linux/compat.h
index 6e3feb64d2d5..e851b2982d76 100644
--- a/include/linux/compat.h
+++ b/include/linux/compat.h
@@ -11,6 +11,9 @@ typedef struct unused unused_t;
 
 struct p_current{
        int pid;
+#ifdef CONFIG_UBSAN
+	unsigned int in_ubsan;
+#endif
 };
 
 extern struct p_current *current;
diff --git a/lib/Kconfig b/lib/Kconfig
index 622f3c26c331..251903af9e6b 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -375,6 +375,7 @@ endmenu
 
 source lib/efi/Kconfig
 source lib/efi_loader/Kconfig
+source lib/Kconfig.ubsan
 source lib/optee/Kconfig
 
 endmenu
diff --git a/lib/Kconfig.ubsan b/lib/Kconfig.ubsan
new file mode 100644
index 000000000000..dbbfe974221d
--- /dev/null
+++ b/lib/Kconfig.ubsan
@@ -0,0 +1,29 @@
+config ARCH_HAS_UBSAN_SANITIZE_ALL
+	bool
+
+config UBSAN
+	bool "Undefined behaviour sanity checker"
+	help
+	  This option enables undefined behaviour sanity checker
+	  Compile-time instrumentation is used to detect various undefined
+	  behaviours in runtime.
+
+config UBSAN_SANITIZE_ALL
+	bool "Enable instrumentation for the entire kernel"
+	depends on UBSAN
+	depends on ARCH_HAS_UBSAN_SANITIZE_ALL
+	default y
+	help
+	  This option activates instrumentation for the entire kernel.
+	  If you don't enable this option, you have to explicitly specify
+	  UBSAN_SANITIZE := y for the files/directories you want to check for UB.
+	  Enabling this option will get kernel image size increased
+	  significantly.
+
+config UBSAN_ALIGNMENT
+	bool "Enable checking of pointers alignment"
+	depends on UBSAN
+	help
+	  This option enables detection of unaligned memory accesses.
+	  Enabling this option on architectures that support unaligned
+	  accesses may produce a lot of false positives.
diff --git a/lib/Makefile b/lib/Makefile
index 5f583aed37d9..0ae2c121cacf 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -51,6 +51,8 @@ endif
 obj-$(CONFIG_RSA) += rsa/
 obj-$(CONFIG_SHA1) += sha1.o
 obj-$(CONFIG_SHA256) += sha256.o
+obj-$(CONFIG_UBSAN) += ubsan.o
+UBSAN_SANITIZE_ubsan.o := n
 
 obj-$(CONFIG_$(SPL_)ZLIB) += zlib/
 obj-$(CONFIG_$(SPL_)GZIP) += gunzip.o
diff --git a/lib/linux_compat.c b/lib/linux_compat.c
index a936a7eac214..4dd89b50e924 100644
--- a/lib/linux_compat.c
+++ b/lib/linux_compat.c
@@ -4,6 +4,9 @@
 
 struct p_current cur = {
 	.pid = 1,
+#ifdef CONFIG_UBSAN
+	.in_ubsan = 0,
+#endif
 };
 __maybe_unused struct p_current *current = &cur;
 
diff --git a/lib/ubsan.c b/lib/ubsan.c
new file mode 100644
index 000000000000..642ef9f02c00
--- /dev/null
+++ b/lib/ubsan.c
@@ -0,0 +1,461 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * UBSAN error reporting functions
+ *
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ * Author: Andrey Ryabinin <ryabinin.a.a@gmail.com>
+ */
+
+#include <linux/bitops.h>
+#include <linux/bug.h>
+#include <linux/ctype.h>
+#include <linux/kernel.h>
+#include <linux/types.h>
+
+#ifdef __UBOOT__
+#include <linux/compat.h>
+#include <common.h>
+#endif
+
+#include "ubsan.h"
+
+const char *type_check_kinds[] = {
+	"load of",
+	"store to",
+	"reference binding to",
+	"member access within",
+	"member call on",
+	"constructor call on",
+	"downcast of",
+	"downcast of"
+};
+
+#define REPORTED_BIT 31
+
+#if (BITS_PER_LONG == 64) && defined(__BIG_ENDIAN)
+#define COLUMN_MASK (~(1U << REPORTED_BIT))
+#define LINE_MASK   (~0U)
+#else
+#define COLUMN_MASK   (~0U)
+#define LINE_MASK (~(1U << REPORTED_BIT))
+#endif
+
+#define VALUE_LENGTH 40
+
+static bool was_reported(struct source_location *location)
+{
+	return test_and_set_bit(REPORTED_BIT, &location->reported);
+}
+
+static void print_source_location(const char *prefix,
+				struct source_location *loc)
+{
+	pr_err("%s %s:%d:%d\n", prefix, loc->file_name,
+		loc->line & LINE_MASK, loc->column & COLUMN_MASK);
+}
+
+static bool suppress_report(struct source_location *loc)
+{
+	return current->in_ubsan || was_reported(loc);
+}
+
+static bool type_is_int(struct type_descriptor *type)
+{
+	return type->type_kind == type_kind_int;
+}
+
+static bool type_is_signed(struct type_descriptor *type)
+{
+	WARN_ON(!type_is_int(type));
+	return  type->type_info & 1;
+}
+
+static unsigned type_bit_width(struct type_descriptor *type)
+{
+	return 1 << (type->type_info >> 1);
+}
+
+static bool is_inline_int(struct type_descriptor *type)
+{
+	unsigned inline_bits = sizeof(unsigned long)*8;
+	unsigned bits = type_bit_width(type);
+
+	WARN_ON(!type_is_int(type));
+
+	return bits <= inline_bits;
+}
+
+static s_max get_signed_val(struct type_descriptor *type, unsigned long val)
+{
+	if (is_inline_int(type)) {
+		unsigned extra_bits = sizeof(s_max)*8 - type_bit_width(type);
+		return ((s_max)val) << extra_bits >> extra_bits;
+	}
+
+	if (type_bit_width(type) == 64)
+		return *(s64 *)val;
+
+	return *(s_max *)val;
+}
+
+static bool val_is_negative(struct type_descriptor *type, unsigned long val)
+{
+	return type_is_signed(type) && get_signed_val(type, val) < 0;
+}
+
+static u_max get_unsigned_val(struct type_descriptor *type, unsigned long val)
+{
+	if (is_inline_int(type))
+		return val;
+
+	if (type_bit_width(type) == 64)
+		return *(u64 *)val;
+
+	return *(u_max *)val;
+}
+
+static void val_to_string(char *str, size_t size, struct type_descriptor *type,
+	unsigned long value)
+{
+	if (type_is_int(type)) {
+		if (type_bit_width(type) == 128) {
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) && defined(__SIZEOF_INT128__)
+			u_max val = get_unsigned_val(type, value);
+
+			scnprintf(str, size, "0x%08x%08x%08x%08x",
+				(u32)(val >> 96),
+				(u32)(val >> 64),
+				(u32)(val >> 32),
+				(u32)(val));
+#else
+			WARN_ON(1);
+#endif
+		} else if (type_is_signed(type)) {
+			scnprintf(str, size, "%lld",
+				(s64)get_signed_val(type, value));
+		} else {
+			scnprintf(str, size, "%llu",
+				(u64)get_unsigned_val(type, value));
+		}
+	}
+}
+
+#ifndef __UBOOT__
+static DEFINE_SPINLOCK(report_lock);
+#endif
+
+static void ubsan_prologue(struct source_location *location,
+			unsigned long *flags)
+{
+	current->in_ubsan++;
+	spin_lock_irqsave(&report_lock, *flags);
+
+	pr_err("========================================"
+		"========================================\n");
+	print_source_location("UBSAN: Undefined behaviour in", location);
+}
+
+static void ubsan_epilogue(unsigned long *flags)
+{
+	dump_stack();
+	pr_err("========================================"
+		"========================================\n");
+	spin_unlock_irqrestore(&report_lock, *flags);
+	current->in_ubsan--;
+}
+
+static void handle_overflow(struct overflow_data *data, unsigned long lhs,
+			unsigned long rhs, char op)
+{
+
+	struct type_descriptor *type = data->type;
+	unsigned long flags;
+	char lhs_val_str[VALUE_LENGTH];
+	char rhs_val_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(lhs_val_str, sizeof(lhs_val_str), type, lhs);
+	val_to_string(rhs_val_str, sizeof(rhs_val_str), type, rhs);
+	pr_err("%s integer overflow:\n",
+		type_is_signed(type) ? "signed" : "unsigned");
+	pr_err("%s %c %s cannot be represented in type %s\n",
+		lhs_val_str,
+		op,
+		rhs_val_str,
+		type->type_name);
+
+	ubsan_epilogue(&flags);
+}
+
+void __ubsan_handle_add_overflow(struct overflow_data *data,
+				unsigned long lhs,
+				unsigned long rhs)
+{
+
+	handle_overflow(data, lhs, rhs, '+');
+}
+EXPORT_SYMBOL(__ubsan_handle_add_overflow);
+
+void __ubsan_handle_sub_overflow(struct overflow_data *data,
+				unsigned long lhs,
+				unsigned long rhs)
+{
+	handle_overflow(data, lhs, rhs, '-');
+}
+EXPORT_SYMBOL(__ubsan_handle_sub_overflow);
+
+void __ubsan_handle_mul_overflow(struct overflow_data *data,
+				unsigned long lhs,
+				unsigned long rhs)
+{
+	handle_overflow(data, lhs, rhs, '*');
+}
+EXPORT_SYMBOL(__ubsan_handle_mul_overflow);
+
+void __ubsan_handle_negate_overflow(struct overflow_data *data,
+				unsigned long old_val)
+{
+	unsigned long flags;
+	char old_val_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(old_val_str, sizeof(old_val_str), data->type, old_val);
+
+	pr_err("negation of %s cannot be represented in type %s:\n",
+		old_val_str, data->type->type_name);
+
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_negate_overflow);
+
+
+void __ubsan_handle_divrem_overflow(struct overflow_data *data,
+				unsigned long lhs,
+				unsigned long rhs)
+{
+	unsigned long flags;
+	char rhs_val_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(rhs_val_str, sizeof(rhs_val_str), data->type, rhs);
+
+	if (type_is_signed(data->type) && get_signed_val(data->type, rhs) == -1)
+		pr_err("division of %s by -1 cannot be represented in type %s\n",
+			rhs_val_str, data->type->type_name);
+	else
+		pr_err("division by zero\n");
+
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_divrem_overflow);
+
+static void handle_null_ptr_deref(struct type_mismatch_data_common *data)
+{
+	unsigned long flags;
+
+	if (suppress_report(data->location))
+		return;
+
+	ubsan_prologue(data->location, &flags);
+
+	pr_err("%s null pointer of type %s\n",
+		type_check_kinds[data->type_check_kind],
+		data->type->type_name);
+
+	ubsan_epilogue(&flags);
+}
+
+static void handle_misaligned_access(struct type_mismatch_data_common *data,
+				unsigned long ptr)
+{
+	unsigned long flags;
+
+	if (suppress_report(data->location))
+		return;
+
+	ubsan_prologue(data->location, &flags);
+
+	pr_err("%s misaligned address %p for type %s\n",
+		type_check_kinds[data->type_check_kind],
+		(void *)ptr, data->type->type_name);
+	pr_err("which requires %ld byte alignment\n", data->alignment);
+
+	ubsan_epilogue(&flags);
+}
+
+static void handle_object_size_mismatch(struct type_mismatch_data_common *data,
+					unsigned long ptr)
+{
+	unsigned long flags;
+
+	if (suppress_report(data->location))
+		return;
+
+	ubsan_prologue(data->location, &flags);
+	pr_err("%s address %p with insufficient space\n",
+		type_check_kinds[data->type_check_kind],
+		(void *) ptr);
+	pr_err("for an object of type %s\n", data->type->type_name);
+	ubsan_epilogue(&flags);
+}
+
+static void ubsan_type_mismatch_common(struct type_mismatch_data_common *data,
+				unsigned long ptr)
+{
+
+	if (!ptr)
+		handle_null_ptr_deref(data);
+	else if (data->alignment && !IS_ALIGNED(ptr, data->alignment))
+		handle_misaligned_access(data, ptr);
+	else
+		handle_object_size_mismatch(data, ptr);
+}
+
+void __ubsan_handle_type_mismatch(struct type_mismatch_data *data,
+				unsigned long ptr)
+{
+	struct type_mismatch_data_common common_data = {
+		.location = &data->location,
+		.type = data->type,
+		.alignment = data->alignment,
+		.type_check_kind = data->type_check_kind
+	};
+
+	ubsan_type_mismatch_common(&common_data, ptr);
+}
+EXPORT_SYMBOL(__ubsan_handle_type_mismatch);
+
+void __ubsan_handle_type_mismatch_v1(struct type_mismatch_data_v1 *data,
+				unsigned long ptr)
+{
+
+	struct type_mismatch_data_common common_data = {
+		.location = &data->location,
+		.type = data->type,
+		.alignment = 1UL << data->log_alignment,
+		.type_check_kind = data->type_check_kind
+	};
+
+	ubsan_type_mismatch_common(&common_data, ptr);
+}
+EXPORT_SYMBOL(__ubsan_handle_type_mismatch_v1);
+
+void __ubsan_handle_vla_bound_not_positive(struct vla_bound_data *data,
+					unsigned long bound)
+{
+	unsigned long flags;
+	char bound_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(bound_str, sizeof(bound_str), data->type, bound);
+	pr_err("variable length array bound value %s <= 0\n", bound_str);
+
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_vla_bound_not_positive);
+
+void __ubsan_handle_out_of_bounds(struct out_of_bounds_data *data,
+				unsigned long index)
+{
+	unsigned long flags;
+	char index_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(index_str, sizeof(index_str), data->index_type, index);
+	pr_err("index %s is out of range for type %s\n", index_str,
+		data->array_type->type_name);
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_out_of_bounds);
+
+void __ubsan_handle_shift_out_of_bounds(struct shift_out_of_bounds_data *data,
+					unsigned long lhs, unsigned long rhs)
+{
+	unsigned long flags;
+	struct type_descriptor *rhs_type = data->rhs_type;
+	struct type_descriptor *lhs_type = data->lhs_type;
+	char rhs_str[VALUE_LENGTH];
+	char lhs_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(rhs_str, sizeof(rhs_str), rhs_type, rhs);
+	val_to_string(lhs_str, sizeof(lhs_str), lhs_type, lhs);
+
+	if (val_is_negative(rhs_type, rhs))
+		pr_err("shift exponent %s is negative\n", rhs_str);
+
+	else if (get_unsigned_val(rhs_type, rhs) >=
+		type_bit_width(lhs_type))
+		pr_err("shift exponent %s is too large for %u-bit type %s\n",
+			rhs_str,
+			type_bit_width(lhs_type),
+			lhs_type->type_name);
+	else if (val_is_negative(lhs_type, lhs))
+		pr_err("left shift of negative value %s\n",
+			lhs_str);
+	else
+		pr_err("left shift of %s by %s places cannot be"
+			" represented in type %s\n",
+			lhs_str, rhs_str,
+			lhs_type->type_name);
+
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_shift_out_of_bounds);
+
+
+void __noreturn
+__ubsan_handle_builtin_unreachable(struct unreachable_data *data)
+{
+	unsigned long flags;
+
+	ubsan_prologue(&data->location, &flags);
+	pr_err("calling __builtin_unreachable()\n");
+	ubsan_epilogue(&flags);
+	panic("can't return from __builtin_unreachable()");
+}
+EXPORT_SYMBOL(__ubsan_handle_builtin_unreachable);
+
+void __ubsan_handle_load_invalid_value(struct invalid_value_data *data,
+				unsigned long val)
+{
+	unsigned long flags;
+	char val_str[VALUE_LENGTH];
+
+	if (suppress_report(&data->location))
+		return;
+
+	ubsan_prologue(&data->location, &flags);
+
+	val_to_string(val_str, sizeof(val_str), data->type, val);
+
+	pr_err("load of value %s is not a valid value for type %s\n",
+		val_str, data->type->type_name);
+
+	ubsan_epilogue(&flags);
+}
+EXPORT_SYMBOL(__ubsan_handle_load_invalid_value);
diff --git a/lib/ubsan.h b/lib/ubsan.h
new file mode 100644
index 000000000000..01efea6bae11
--- /dev/null
+++ b/lib/ubsan.h
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0
+#ifndef _LIB_UBSAN_H
+#define _LIB_UBSAN_H
+
+enum {
+	type_kind_int = 0,
+	type_kind_float = 1,
+	type_unknown = 0xffff
+};
+
+struct type_descriptor {
+	u16 type_kind;
+	u16 type_info;
+	char type_name[1];
+};
+
+struct source_location {
+	const char *file_name;
+	union {
+		unsigned long reported;
+		struct {
+			u32 line;
+			u32 column;
+		};
+	};
+};
+
+struct overflow_data {
+	struct source_location location;
+	struct type_descriptor *type;
+};
+
+struct type_mismatch_data {
+	struct source_location location;
+	struct type_descriptor *type;
+	unsigned long alignment;
+	unsigned char type_check_kind;
+};
+
+struct type_mismatch_data_v1 {
+	struct source_location location;
+	struct type_descriptor *type;
+	unsigned char log_alignment;
+	unsigned char type_check_kind;
+};
+
+struct type_mismatch_data_common {
+	struct source_location *location;
+	struct type_descriptor *type;
+	unsigned long alignment;
+	unsigned char type_check_kind;
+};
+
+struct nonnull_arg_data {
+	struct source_location location;
+	struct source_location attr_location;
+	int arg_index;
+};
+
+struct vla_bound_data {
+	struct source_location location;
+	struct type_descriptor *type;
+};
+
+struct out_of_bounds_data {
+	struct source_location location;
+	struct type_descriptor *array_type;
+	struct type_descriptor *index_type;
+};
+
+struct shift_out_of_bounds_data {
+	struct source_location location;
+	struct type_descriptor *lhs_type;
+	struct type_descriptor *rhs_type;
+};
+
+struct unreachable_data {
+	struct source_location location;
+};
+
+struct invalid_value_data {
+	struct source_location location;
+	struct type_descriptor *type;
+};
+
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) && defined(__SIZEOF_INT128__)
+typedef __int128 s_max;
+typedef unsigned __int128 u_max;
+#else
+typedef s64 s_max;
+typedef u64 u_max;
+#endif
+
+#endif
diff --git a/scripts/Makefile.lib b/scripts/Makefile.lib
index f8c3fff1d151..ccf683265fcb 100644
--- a/scripts/Makefile.lib
+++ b/scripts/Makefile.lib
@@ -131,6 +131,12 @@ _c_flags += $(if $(patsubst n%,, \
 		$(CFLAGS_KASAN))
 endif
 
+ifeq ($(CONFIG_UBSAN),y)
+_c_flags += $(if $(patsubst n%,, \
+		$(UBSAN_SANITIZE_$(basetarget).o)$(UBSAN_SANITIZE)$(CONFIG_UBSAN_SANITIZE_ALL)), \
+		$(CFLAGS_UBSAN))
+endif
+
 # If building the kernel in a separate objtree expand all occurrences
 # of -Idir to -I$(srctree)/dir except for absolute paths (starting with '/').
 
diff --git a/scripts/Makefile.ubsan b/scripts/Makefile.ubsan
new file mode 100644
index 000000000000..38b2b4818e8e
--- /dev/null
+++ b/scripts/Makefile.ubsan
@@ -0,0 +1,20 @@
+# SPDX-License-Identifier: GPL-2.0
+ifdef CONFIG_UBSAN
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=shift)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=integer-divide-by-zero)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=unreachable)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=vla-bound)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=signed-integer-overflow)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=bounds)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=object-size)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=bool)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=enum)
+
+ifdef CONFIG_UBSAN_ALIGNMENT
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=alignment)
+endif
+
+      # -fsanitize=* options makes GCC less smart than usual and
+      # increase number of 'maybe-uninitialized false-positives
+      CFLAGS_UBSAN += $(call cc-option, -Wno-maybe-uninitialized)
+endif
-- 
2.18.0

  reply	other threads:[~2018-08-26 23:13 UTC|newest]

Thread overview: 32+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2018-08-26 23:13 [U-Boot] [PATCH v2 00/13] Import Undefined Behavior Sanitizer Eugeniu Rosca
2018-08-26 23:13 ` Eugeniu Rosca [this message]
2018-08-27 14:13   ` [U-Boot] [PATCH v2 01/13] UBSAN: run-time undefined behavior sanity checker Tom Rini
2018-08-26 23:13 ` [U-Boot] [PATCH v2 02/13] mmc: Fix signed shift overflow Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 03/13] armv8: mmu: " Eugeniu Rosca
2018-08-27 14:13   ` Tom Rini
2018-08-26 23:13 ` [U-Boot] [PATCH v2 04/13] pinctrl: renesas: " Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 05/13] net: phy: " Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 06/13] net: ravb: " Eugeniu Rosca
2018-08-26 23:22   ` Marek Vasut
2018-08-27 20:24     ` Eugeniu Rosca
2018-08-27 23:55       ` Marek Vasut
2018-08-26 23:13 ` [U-Boot] [PATCH v2 07/13] x86: Fix signed shift overflow in MSR_IA32_APICBASE_BASE Eugeniu Rosca
2018-08-28  2:05   ` Bin Meng
2018-08-28  6:42     ` Eugeniu Rosca
2018-09-01 10:59       ` Eugeniu Rosca
2018-09-04  4:00         ` Bin Meng
2018-09-16 18:46           ` Eugeniu Rosca
2018-09-22 23:10             ` Eugeniu Rosca
2018-09-25  2:06               ` Bin Meng
2018-10-09  0:22                 ` Eugeniu Rosca
2018-08-28  8:14     ` Andy Shevchenko
2018-08-26 23:13 ` [U-Boot] [PATCH v2 08/13] disk: part_dos: Fix signed shift overflow Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 09/13] common.h: Fix signed shift overflow in cpumask_next() Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 10/13] mmc: Fix read-past-end-of-array Eugeniu Rosca
2018-08-26 23:13 ` [U-Boot] [PATCH v2 11/13] hashtable: Fix zero-sized array Eugeniu Rosca
2018-08-27 14:13   ` Tom Rini
2018-08-26 23:13 ` [U-Boot] [PATCH v2 12/13] input: " Eugeniu Rosca
2018-08-27 14:13   ` Tom Rini
2018-08-26 23:13 ` [U-Boot] [PATCH v2 13/13] configs: sandbox*: Enable UBSAN Eugeniu Rosca
2018-08-30  2:51   ` Simon Glass
2018-09-17 21:10     ` Eugeniu Rosca

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20180826231332.2491-2-erosca@de.adit-jv.com \
    --to=roscaeugeniu@gmail.com \
    --cc=u-boot@lists.denx.de \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.