Skip to contentSkip to conversation

UBSAN: run-time undefined behavior sanity checker

PATCH In review Andrey Ryabinin 6 participants 13 messages Dec 3, 2015 – Dec 10, 2015

Subsystems (15)
lore
Share & tools
lore
#0 lore raw

v4 cover UBSAN: run-time undefined behavior sanity checker

UBSAN is run-time undefined behaviour checker. It uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

Changes since v3:
- Fixed build failure/warnings reported by kbuild robot.
- Fixed typo per Sasha.

Changes since V2:
- Dropped -fsanitize=nonnull-attribute. It checks whether null values are not passed to arguments marked as requiring a non-null value by the "nonnull" function attribute.

We don't have much functions with such attribute (early_shadow_write() in arch/blackfin and GCC builtin functions: memcpy, memset, memmove, etc). Some kernel code deliberately passes NULL-ptr with 0-length to mem*(). This should be fine since we compile kernel with -fno-delete-null-pointer-checks. And NULL-ptr with != 0 length will just crash. So this options is useless in kernel since it produces only false positives. See also: http://thread.gmane.org/gmane.linux.kernel/1810656

- Also dropped enabling/disabling various checkers via boot cmdline.
Boot time flag only disable reports, it can't disable compile-time code instrumentation. Thus, if we ever will need to disable some checker it would be better to do it in compile time via Kconfig option.

- Alignment checks produce too much noise if CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS is set. Since there is no boottime option to disable alignment checks, CONFIG_UBSAN_ALIGNMENT was added. It's off by default if CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS is set.

- Couple other small misc changes/fixes.

Changes since v1:
- Refactoring and cleanups in lib/ubsan.c including Sasha's complains.
- Some spelling fixes from Randy
- Fixed possible memory corruption on 64 big endian machines, spotted by Rasmus.
- Links to the relevant GCC documentation added into changelog (Peter).
- Added documentation.
- Fix deadlock caused by kernel/printk/printk.c instrumentation
(patch "kernel: printk: specify alignment for struct printk_log").
- Dropped useless 'Indirect call of a function through a function pointer of the wrong type' checker. GCC doesn't support this, and as clang manual says it's for C++ only.
- Added checker for __builtin_unreachable() calls.
- Removed redundant -fno-sanitize=float-cast-overflow from CFLAGS.
- Added lock to prevent mixing reports.

Andrey Ryabinin (3):
kernel: printk: specify alignment for struct printk_log
mac80211: Prevent build failure with CONFIG_UBSAN=y

  UBSAN: run-time undefined behavior sanity checker
 Documentation/ubsan.txt               |  84 +++++++
 Makefile                              |   3 +-
 arch/x86/Kconfig                      |   1 +
 arch/x86/boot/Makefile                |   1 +
 arch/x86/boot/compressed/Makefile     |   1 +
 arch/x86/entry/vdso/Makefile          |   1 +
 arch/x86/realmode/rm/Makefile         |   1 +
 drivers/firmware/efi/libstub/Makefile |   1 +
 include/linux/sched.h                 |   3 +
 kernel/printk/printk.c                |  10 +-
 lib/Kconfig.debug                     |   1 +
 lib/Kconfig.ubsan                     |  29 +++
 lib/Makefile                          |   3 +
 lib/ubsan.c                           | 456 ++++++++++++++++++++++++++++++++++
 lib/ubsan.h                           |  84 +++++++
 mm/kasan/Makefile                     |   1 +
 net/mac80211/debugfs.c                |   7 +-
 scripts/Makefile.lib                  |   6 +
 scripts/Makefile.ubsan                |  18 ++
 19 files changed, 700 insertions(+), 11 deletions(-)
 create mode 100644 Documentation/ubsan.txt
 create mode 100644 lib/Kconfig.ubsan
 create mode 100644 lib/ubsan.c
 create mode 100644 lib/ubsan.h
 create mode 100644 scripts/Makefile.ubsan
Signature · 1 line
2.4.10
#1 lore raw

PATCH v4 1/3 kernel: printk: specify alignment for struct printk_log

On architectures that have support for efficient unaligned access struct printk_log has 4-byte alignment.
Specify alignment attribute in type declaration.

The whole point of this patch is to fix deadlock which happening when UBSAN detects unaligned access in printk() thus UBSAN recursively calls printk() with logbuf_lock held by top printk() call.

---
 kernel/printk/printk.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
kernel/printk/printk.c +5 -5
index 0c9f0250..8712409 100644
@@ -233,7 +233,11 @@ struct printk_log {
 	u8 facility;		/* syslog facility */
 	u8 flags:5;		/* internal record flags */
 	u8 level:3;		/* syslog level */
-};
+}
+#ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
+__packed __aligned(4)
+#endif
+;
 
 /*
  * The logbuf_lock protects kmsg buffer, indices, counters.  This can be taken
@@ -274,11 +278,7 @@ static u32 clear_idx;
 #define LOG_FACILITY(v)		((v) >> 3 & 0xff)
 
 /* record buffer */
-#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
-#define LOG_ALIGN 4
-#else
 #define LOG_ALIGN __alignof__(struct printk_log)
-#endif
 #define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
 static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);
 static char *log_buf = __log_buf;
Signature · 1 line
2.4.10
#2 lore raw

PATCH v4 2/3 mac80211: Prevent build failure with CONFIG_UBSAN=y

In reply to Andrey Ryabinin

With upcoming CONFIG_UBSAN the following BUILD_BUG_ON in net/mac80211/debugfs.c starts to trigger:

	BUILD_BUG_ON(hw_flag_names[NUM_IEEE80211_HW_FLAGS] != (void *)0x1);

It seems, that compiler instrumentation causes some code deoptimizations. Because of that GCC is not being able to resolve condition in BUILD_BUG_ON() at compile time.

We could make size of hw_flag_names array unspecified and replace the condition in BUILD_BUG_ON() with following:

	ARRAY_SIZE(hw_flag_names) != NUM_IEEE80211_HW_FLAGS

That will have the same effect as before (adding new flag without updating array will trigger build failure) except it doesn't fail with CONFIG_UBSAN. As a bonus this patch slightly decreases size of hw_flag_names array.

Cc Johannes Berg <[email protected]>
Cc "David S. Miller" <[email protected]>
---
 net/mac80211/debugfs.c | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
net/mac80211/debugfs.c +2 -5
index abbdff0..3e24d0d 100644
@@ -91,7 +91,7 @@ static const struct file_operations reset_ops = {
 };
 #endif
 
-static const char *hw_flag_names[NUM_IEEE80211_HW_FLAGS + 1] = {
+static const char *hw_flag_names[] = {
 #define FLAG(F)	[IEEE80211_HW_##F] = #F
 	FLAG(HAS_RATE_CONTROL),
 	FLAG(RX_INCLUDES_FCS),
@@ -126,9 +126,6 @@ static const char *hw_flag_names[NUM_IEEE80211_HW_FLAGS + 1] = {
 	FLAG(SUPPORTS_AMSDU_IN_AMPDU),
 	FLAG(BEACON_TX_STATUS),
 	FLAG(NEEDS_UNIQUE_STA_ADDR),
-
-	/* keep last for the build bug below */
-	(void *)0x1
 #undef FLAG
 };
 
@@ -148,7 +145,7 @@ static ssize_t hwflags_read(struct file *file, char __user *user_buf,
 	/* fail compilation if somebody adds or removes
 	 * a flag without updating the name array above
 	 */
-	BUILD_BUG_ON(hw_flag_names[NUM_IEEE80211_HW_FLAGS] != (void *)0x1);
+	BUILD_BUG_ON(ARRAY_SIZE(hw_flag_names) != NUM_IEEE80211_HW_FLAGS);
 
 	for (i = 0; i < NUM_IEEE80211_HW_FLAGS; i++) {
 		if (test_bit(i, local->hw.flags))
Signature · 1 line
2.4.10
maintainer
#3 lore raw

Re: [PATCH v4 2/3] mac80211: Prevent build failure with CONFIG_UBSAN=y

Quoted 13 lines · Andrey Ryabinin

With upcoming CONFIG_UBSAN the following BUILD_BUG_ON in net/mac80211/debugfs.c starts to trigger:

	BUILD_BUG_ON(hw_flag_names[NUM_IEEE80211_HW_FLAGS] != (void

*)0x1);

It seems, that compiler instrumentation causes some code deoptimizations.
Because of that GCC is not being able to resolve condition in BUILD_BUG_ON()
at compile time.

We could make size of hw_flag_names array unspecified and replace the condition in BUILD_BUG_ON() with following:

Quoted 8 lines
	ARRAY_SIZE(hw_flag_names) != NUM_IEEE80211_HW_FLAGS

That will have the same effect as before (adding new flag without updating
array will trigger build failure) except it doesn't fail with CONFIG_UBSAN.
As a bonus this patch slightly decreases size of hw_flag_names array.

Seems fine, would you want to take it through some other tree together with UBSAN, or do you expect that to still take long enough to allow this to trickle through our trees?

johannes

maintainer
#4 lore raw

Re: [PATCH v4 2/3] mac80211: Prevent build failure with CONFIG_UBSAN=y

2015-12-03 20:05 GMT+03:00 Johannes Berg <[email protected]>:

Quoted 22 lines · Andrey Ryabinin
Quoted 13 lines

With upcoming CONFIG_UBSAN the following BUILD_BUG_ON in net/mac80211/debugfs.c starts to trigger:

      BUILD_BUG_ON(hw_flag_names[NUM_IEEE80211_HW_FLAGS] != (void

*)0x1);

It seems, that compiler instrumentation causes some code deoptimizations.
Because of that GCC is not being able to resolve condition in BUILD_BUG_ON()
at compile time.

We could make size of hw_flag_names array unspecified and replace the condition in BUILD_BUG_ON() with following:

Quoted 8 lines
      ARRAY_SIZE(hw_flag_names) != NUM_IEEE80211_HW_FLAGS

That will have the same effect as before (adding new flag without updating
array will trigger build failure) except it doesn't fail with CONFIG_UBSAN.
As a bonus this patch slightly decreases size of hw_flag_names array.

Quoted 4 lines

Seems fine, would you want to take it through some other tree together with UBSAN, or do you expect that to still take long enough to allow this to trickle through our trees?

I expect that Andrew will take it with UBSAN for 4.5

#5 lore raw

PATCH v4 3/3 UBSAN: run-time undefined behavior sanity checker

In reply to Andrey Ryabinin

UBSAN uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

So the most of the work is done by compiler. This patch just implements ubsan handlers printing errors.

GCC has this capability since 4.9.x [1] (see -fsanitize=undefined option and its suboptions).
However GCC 5.x has more checkers implemented [2]. Article [3] has a bit more details about UBSAN in the GCC.

[1] - https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Debugging-Options.html
[2] - https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
[3] - http://developerblog.redhat.com/2014/10/16/gcc-undefined-behavior-sanitizer-ubsan/

---
 Documentation/ubsan.txt               |  84 +++++++
 Makefile                              |   3 +-
 arch/x86/Kconfig                      |   1 +
 arch/x86/boot/Makefile                |   1 +
 arch/x86/boot/compressed/Makefile     |   1 +
 arch/x86/entry/vdso/Makefile          |   1 +
 arch/x86/realmode/rm/Makefile         |   1 +
 drivers/firmware/efi/libstub/Makefile |   1 +
 include/linux/sched.h                 |   3 +
 lib/Kconfig.debug                     |   1 +
 lib/Kconfig.ubsan                     |  29 +++
 lib/Makefile                          |   3 +
 lib/ubsan.c                           | 456 ++++++++++++++++++++++++++++++++++
 lib/ubsan.h                           |  84 +++++++
 mm/kasan/Makefile                     |   1 +
 scripts/Makefile.lib                  |   6 +
 scripts/Makefile.ubsan                |  18 ++
 17 files changed, 693 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/ubsan.txt
 create mode 100644 lib/Kconfig.ubsan
 create mode 100644 lib/ubsan.c
 create mode 100644 lib/ubsan.h
 create mode 100644 scripts/Makefile.ubsan
Documentation/ubsan.txt new file +84 -0
new file mode 100644
index 0000000..f58215e
@@ -0,0 +1,84 @@
+Undefined Behavior Sanitizer - UBSAN
+
+Overview
+--------
+
+UBSAN is a runtime undefined behaviour checker.
+
+UBSAN uses compile-time instrumentation to catch undefined behavior (UB).
+Compiler inserts code that perform certain kinds of checks before operations
+that may cause UB. If check fails (i.e. UB detected) __ubsan_handle_*
+function called to print error message.
+
+GCC has that feature since 4.9.x [1] (see -fsanitize=undefined option and
+its suboptions). GCC 5.x has more checkers implemented [2].
+
+Report example
+---------------
+
+	 ================================================================================
+	 UBSAN: Undefined behaviour in ../include/linux/bitops.h:110:33
+	 shift exponent 32 is to large for 32-bit type 'unsigned int'
+	 CPU: 0 PID: 0 Comm: swapper Not tainted 4.4.0-rc1+ #26
+	  0000000000000000 ffffffff82403cc8 ffffffff815e6cd6 0000000000000001
+	  ffffffff82403cf8 ffffffff82403ce0 ffffffff8163a5ed 0000000000000020
+	  ffffffff82403d78 ffffffff8163ac2b ffffffff815f0001 0000000000000002
+	 Call Trace:
+	  [<ffffffff815e6cd6>] dump_stack+0x45/0x5f
+	  [<ffffffff8163a5ed>] ubsan_epilogue+0xd/0x40
+	  [<ffffffff8163ac2b>] __ubsan_handle_shift_out_of_bounds+0xeb/0x130
+	  [<ffffffff815f0001>] ? radix_tree_gang_lookup_slot+0x51/0x150
+	  [<ffffffff8173c586>] _mix_pool_bytes+0x1e6/0x480
+	  [<ffffffff83105653>] ? dmi_walk_early+0x48/0x5c
+	  [<ffffffff8173c881>] add_device_randomness+0x61/0x130
+	  [<ffffffff83105b35>] ? dmi_save_one_device+0xaa/0xaa
+	  [<ffffffff83105653>] dmi_walk_early+0x48/0x5c
+	  [<ffffffff831066ae>] dmi_scan_machine+0x278/0x4b4
+	  [<ffffffff8111d58a>] ? vprintk_default+0x1a/0x20
+	  [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
+	  [<ffffffff830b2240>] setup_arch+0x405/0xc2c
+	  [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
+	  [<ffffffff830ae053>] start_kernel+0x83/0x49a
+	  [<ffffffff830ad120>] ? early_idt_handler_array+0x120/0x120
+	  [<ffffffff830ad386>] x86_64_start_reservations+0x2a/0x2c
+	  [<ffffffff830ad4f3>] x86_64_start_kernel+0x16b/0x17a
+	 ================================================================================
+
+Usage
+-----
+
+To enable UBSAN configure kernel with:
+
+	CONFIG_UBSAN=y
+
+and to check the entire kernel:
+
+        CONFIG_UBSAN_SANITIZE_ALL=y
+
+To enable instrumentation for specific files or directories, add a line
+similar to the following to the respective kernel Makefile:
+
+        For a single file (e.g. main.o):
+                UBSAN_SANITIZE_main.o := y
+
+        For all files in one directory:
+                UBSAN_SANITIZE := y
+
+To exclude files from being instrumented even if
+CONFIG_UBSAN_SANITIZE_ALL=y, use:
+
+                UBSAN_SANITIZE_main.o := n
+        and:
+                UBSAN_SANITIZE := n
+
+Detection of unaligned accesses controlled through the separate option -
+CONFIG_UBSAN_ALIGNMENT. It's off by default on architectures that support
+unaligned accesses (CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS=y). One could
+still enable it in config, just note that it will produce a lot of UBSAN
+reports.
+
+References
+----------
+
+[1] - https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Debugging-Options.html
+[2] - https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html
Makefile +2 -1
index b49b551..b8e0923 100644
@@ -416,7 +416,7 @@ export MAKE AWK GENKSYMS INSTALLKERNEL PERL PYTHON UTS_MACHINE
 export HOSTCXX HOSTCXXFLAGS LDFLAGS_MODULE CHECK CHECKFLAGS
 
 export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS LDFLAGS
-export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV CFLAGS_KASAN
+export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV CFLAGS_KASAN CFLAGS_UBSAN
 export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
 export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_LDFLAGS_MODULE
 export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL
@@ -795,6 +795,7 @@ endif
 include scripts/Makefile.kasan
 include scripts/Makefile.extrawarn
 include scripts/Makefile.lto
+include scripts/Makefile.ubsan
 
 # Add any arch overrides and user supplied CPPFLAGS, AFLAGS and CFLAGS as the
 # last assignments
arch/x86/Kconfig +1 -0
index c989d5b..9bcf6b5 100644
@@ -30,6 +30,7 @@ config X86
 	select ARCH_HAS_PMEM_API		if X86_64
 	select ARCH_HAS_MMIO_FLUSH
 	select ARCH_HAS_SG_CHAIN
+	select ARCH_HAS_UBSAN_SANTIZE_ALL
 	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	select ARCH_MIGHT_HAVE_ACPI_PDC		if ACPI
 	select ARCH_MIGHT_HAVE_PC_PARPORT
arch/x86/boot/Makefile +1 -0
index 2ee62db..bbe1a62 100644
@@ -60,6 +60,7 @@ clean-files += cpustr.h
 KBUILD_CFLAGS	:= $(USERINCLUDE) $(REALMODE_CFLAGS) -D_SETUP
 KBUILD_AFLAGS	:= $(KBUILD_CFLAGS) -D__ASSEMBLY__
 GCOV_PROFILE := n
+UBSAN_SANITIZE := n
 
 $(obj)/bzImage: asflags-y  := $(SVGA_MODE)
 
arch/x86/boot/compressed/Makefile +1 -0
index 0a291cd..f9ce75d 100644
@@ -33,6 +33,7 @@ KBUILD_CFLAGS += $(call cc-option,-fno-stack-protector)
 
 KBUILD_AFLAGS  := $(KBUILD_CFLAGS) -D__ASSEMBLY__
 GCOV_PROFILE := n
+UBSAN_SANITIZE :=n
 
 LDFLAGS := -m elf_$(UTS_MACHINE)
 LDFLAGS_vmlinux := -T
arch/x86/entry/vdso/Makefile +1 -0
index 265c0ed..c854541 100644
@@ -4,6 +4,7 @@
 
 KBUILD_CFLAGS += $(DISABLE_LTO)
 KASAN_SANITIZE := n
+UBSAN_SANITIZE := n
 
 VDSO64-$(CONFIG_X86_64)		:= y
 VDSOX32-$(CONFIG_X86_X32_ABI)	:= y
arch/x86/realmode/rm/Makefile +1 -0
index 2730d77..3e75fcf 100644
@@ -70,3 +70,4 @@ KBUILD_CFLAGS	:= $(LINUXINCLUDE) $(REALMODE_CFLAGS) -D_SETUP -D_WAKEUP \
 		   -I$(srctree)/arch/x86/boot
 KBUILD_AFLAGS	:= $(KBUILD_CFLAGS) -D__ASSEMBLY__
 GCOV_PROFILE := n
+UBSAN_SANITIZE := n
drivers/firmware/efi/libstub/Makefile +1 -0
index 3c0467d..b2a172d 100644
@@ -22,6 +22,7 @@ KBUILD_CFLAGS			:= $(cflags-y) \
 
 GCOV_PROFILE			:= n
 KASAN_SANITIZE			:= n
+UBSAN_SANITIZE			:= n
 
 lib-y				:= efi-stub-helper.o
 
include/linux/sched.h +3 -0
index f425aac..418af55 100644
@@ -1629,6 +1629,9 @@ struct task_struct {
 	struct held_lock held_locks[MAX_LOCK_DEPTH];
 	gfp_t lockdep_reclaim_gfp;
 #endif
+#ifdef CONFIG_UBSAN
+	unsigned int in_ubsan;
+#endif
 
 /* journalling filesystem info */
 	void *journal_info;
lib/Kconfig.debug +1 -0
index 334a3c2..b60cf17 100644
@@ -1882,3 +1882,4 @@ source "samples/Kconfig"
 
 source "lib/Kconfig.kgdb"
 
+source "lib/Kconfig.ubsan"
lib/Kconfig.ubsan new file +29 -0
new file mode 100644
index 0000000..3c2868b
@@ -0,0 +1,29 @@
+config ARCH_HAS_UBSAN_SANTIZE_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. Various types of checks may be enabled
+	  via boot parameter ubsan_handle (see: Documentation/ubsan.txt).
+
+config UBSAN_SANITIZE_ALL
+	bool "Enable instrumentation for the entire kernel"
+	depends on UBSAN
+	depends on ARCH_HAS_UBSAN_SANTIZE_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.
+
+config UBSAN_ALIGNMENT
+	bool "Enable checking of pointers alignment"
+	depends on UBSAN
+	default y if !HAVE_EFFICIENT_UNALIGNED_ACCESS
+	help
+	  This option enables detection of unaligned memory accesses.
+	  Enabling this option on architectures that support unalligned
+	  accesses may produce a lot of false positives.
lib/Makefile +3 -0
index 67945a4..736098f 100644
@@ -211,3 +211,6 @@ quiet_cmd_build_OID_registry = GEN     $@
 clean-files	+= oid_registry_data.c
 
 obj-$(CONFIG_UCS2_STRING) += ucs2_string.o
+obj-$(CONFIG_UBSAN) += ubsan.o
+
+UBSAN_SANITIZE_ubsan.o := n
lib/ubsan.c new file +456 -0

456 lines not on this page · raw message

lib/ubsan.h new file +84 -0

84 lines not on this page · raw message

mm/kasan/Makefile +1 -0
index 6471014..a61460d 100644
@@ -1,4 +1,5 @@
 KASAN_SANITIZE := n
+UBSAN_SANITIZE_kasan.o := n
 
 CFLAGS_REMOVE_kasan.o = -pg
 # Function splitter causes unnecessary splits in __asan_load1/__asan_store1
scripts/Makefile.lib +6 -0
index e18957b..78bc5d3 100644
@@ -129,6 +129,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 '/').
 
scripts/Makefile.ubsan new file +18 -0
new file mode 100644
index 0000000..0a0b36d
@@ -0,0 +1,18 @@
+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=null)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=signed-integer-overflow)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=bounds)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=bounds-strict)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=object-size)
+      CFLAGS_UBSAN += $(call cc-option, -fsanitize=returns-nonnull-attribute)
+      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
+endif
Signature · 1 line
2.4.10
#6 lore raw
reproduce:

Hi Andrey,

[auto build test WARNING on next-20151203]
[cannot apply to tip/x86/core kbuild/rc-fixes v4.4-rc3 v4.4-rc2 v4.4-rc1 v4.4-rc3]

url:    https://github.com/0day-ci/linux/commits/Andrey-Ryabinin/UBSAN-run-time-undefined-behavior-sanity-checker/20151204-202547
config: i386-allmodconfig (attached as .config)
reproduce:
        # save the attached .config to linux build tree
        make ARCH=i386 

All warnings (new ones prefixed by >>):

lib/ubsan.c: In function 'val_to_string':

>> lib/ubsan.c:121:8: warning: unused variable 'val' [-Wunused-variable]
     u_max val = get_unsigned_val(type, value);
           ^

vim +/val +121 lib/ubsan.c

105 }
106
107 static u_max get_unsigned_val(struct type_descriptor *type, unsigned long val)
108 {
109 if (is_inline_int(type))
110 return val;
111
112 if (type_bit_width(type) == 64)
113 return *(u64 *)val;
114
115 return *(u_max *)val;
116 }
117
118 static void val_to_string(char *str, size_t size, struct type_descriptor *type,
119 unsigned long value)
120 {

 > 121		u_max val = get_unsigned_val(type, value);

122
123 if (type_is_int(type)) {
124 if (type_bit_width(type) == 128) {
125 #ifdef CONFIG_ARCH_SUPPORTS_INT128
126 scnprintf(str, size, "0x%08x%08x%08x%08x",
127 (u32)(val >> 96),
128 (u32)(val >> 64),
129 (u32)(val >> 32),

---
0-DAY kernel test infrastructure Open Source Technology Center
https://lists.01.org/pipermail/kbuild-all Intel Corporation

maintainer
#7 lore raw
Quoted 9 lines · On Fri, 4 Dec 2015 22:27:36 +0800 kbuild test robot <[email protected]> wrote:

[auto build test WARNING on next-20151203]
[cannot apply to tip/x86/core kbuild/rc-fixes v4.4-rc3 v4.4-rc2 v4.4-rc1 v4.4-rc3]

url:    https://github.com/0day-ci/linux/commits/Andrey-Ryabinin/UBSAN-run-time-undefined-behavior-sanity-checker/20151204-202547
config: i386-allmodconfig (attached as .config)
reproduce:
        # save the attached .config to linux build tree
        make ARCH=i386 
Quoted 5 lines

All warnings (new ones prefixed by >>):

lib/ubsan.c: In function 'val_to_string':

Quoted 1 line
Quoted 1 line

lib/ubsan.c:121:8: warning: unused variable 'val' [-Wunused-variable]

     u_max val = get_unsigned_val(type, value);

I did this.

lib/ubsan.c renamed from lib/ubsan.c~ubsan-run-time-undefined-behavior-sanity-checker-fix +2 -2
@@ -118,11 +118,11 @@ static u_max get_unsigned_val(struct typ
 static void val_to_string(char *str, size_t size, struct type_descriptor *type,
 	unsigned long value)
 {
-	u_max val = get_unsigned_val(type, value);
-
 	if (type_is_int(type)) {
 		if (type_bit_width(type) == 128) {
 #ifdef CONFIG_ARCH_SUPPORTS_INT128
+			u_max val = get_unsigned_val(type, value);
+
 			scnprintf(str, size, "0x%08x%08x%08x%08x",
 				(u32)(val >> 96),
 				(u32)(val >> 64),
maintainer
#8 lore raw
In reply to Andrey Ryabinin
Quoted 15 lines · On Thu, 3 Dec 2015 18:50:07 +0300 Andrey Ryabinin <[email protected]>…

UBSAN uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

So the most of the work is done by compiler. This patch just implements ubsan handlers printing errors.

GCC has this capability since 4.9.x [1] (see -fsanitize=undefined option and its suboptions).
However GCC 5.x has more checkers implemented [2]. Article [3] has a bit more details about UBSAN in the GCC.

...

Review

Quoted 4 lines
(quoted diff) +4 -0
+#ifdef CONFIG_ARCH_SUPPORTS_INT128
+typedef __int128 s_max;
+typedef unsigned __int128 u_max;
+#else

In file included from lib/ubsan.c:21:
lib/ubsan.h:77: error: expected '=', ',', ';', 'asm' or '__attribute__' before 's_max' lib/ubsan.h:78: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'u_max' lib/ubsan.c:89: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'get_signed_val'

gcc-4.4.4 doesn't appear to like __int128. The only other use of __int128 is include/linux/math64.h:mul_u64_u32_shr() and it uses defined(__SIZEOF_INT128__) as well.

Using that gives me

lib/ubsan.c: In function 'val_to_string':
lib/ubsan.c:127: warning: right shift count >= width of type lib/ubsan.c:128: warning: right shift count >= width of type

so I bodged that site too. I need to get an mmotm release out the door.

lib/ubsan.c renamed from lib/ubsan.c~ubsan-run-time-undefined-behavior-sanity-checker-fix-3 +1 -1
@@ -120,7 +120,7 @@ static void val_to_string(char *str, siz
 {
 	if (type_is_int(type)) {
 		if (type_bit_width(type) == 128) {
-#ifdef CONFIG_ARCH_SUPPORTS_INT128
+#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",
lib/ubsan.h renamed from lib/ubsan.h~ubsan-run-time-undefined-behavior-sanity-checker-fix-3 +1 -1
@@ -73,7 +73,7 @@ struct invalid_value_data {
 	struct type_descriptor *type;
 };
 
-#ifdef CONFIG_ARCH_SUPPORTS_INT128
+#if defined(CONFIG_ARCH_SUPPORTS_INT128) && defined(__SIZEOF_INT128__)
 typedef __int128 s_max;
 typedef unsigned __int128 u_max;
 #else

_

maintainer
#10 lore raw
In reply to Andrey Ryabinin
Quoted 4 lines · On Thu, 3 Dec 2015 18:50:04 +0300 Andrey Ryabinin <[email protected]>…

UBSAN is run-time undefined behaviour checker. It uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

What I'd like to see in this changelog is a description of any kernel issues which this checker has already identified: what were they and what was their potential impact at runtime.

This info will help us to understand the value of the proposed feature.

Thanks.

#11 lore raw
Quoted 7 lines · Andrew Morton
Quoted 4 lines · On Thu, 3 Dec 2015 18:50:04 +0300 Andrey Ryabinin <[email protected]>…

UBSAN is run-time undefined behaviour checker. It uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

Quoted 6 lines

What I'd like to see in this changelog is a description of any kernel issues which this checker has already identified: what were they and what was their potential impact at runtime.

This info will help us to understand the value of the proposed feature.

Sure, I'll come back soon with a list of found bugs.

Quoted 2 lines

Thanks.

#12 lore raw
In reply to Andrew Morton
Quoted 7 lines · Andrew Morton
Quoted 4 lines · On Thu, 3 Dec 2015 18:50:04 +0300 Andrey Ryabinin <[email protected]>…

UBSAN is run-time undefined behaviour checker. It uses compile-time instrumentation to catch undefined behavior (UB). Compiler inserts code that perform certain kinds of checks before operations that could cause UB. If check fails (i.e. UB detected) __ubsan_handle_* function called to print error message.

Quoted 6 lines

What I'd like to see in this changelog is a description of any kernel issues which this checker has already identified: what were they and what was their potential impact at runtime.

This info will help us to understand the value of the proposed feature.

It's hard for me to judge about runtime impact of those bugs, as don't know much about what that bugged code is doing. Frankly speaking, nothing looks too scary for me, although some bugs would be hard to find without UBSAN.

Found bugs:

* out-of-bounds access - 97840cb67ff5 ("netfilter: nfnetlink: fix insufficient validation in nfnetlink_bind")

undefined shifts:
* d48458d4a768 ("jbd2: use a better hash function for the revoke table")
* 10632008b9e1 ("clockevents: Prevent shift out of bounds")
* 'x << -1' shift in ext4 - http://lkml.kernel.org/r/<[email protected]>
* undefined rol32(0) - http://lkml.kernel.org/r/<[email protected]>
* undefined dirty_ratelimit calculation - http://lkml.kernel.org/r/<[email protected]>
* undefined roundown_pow_of_two(0) - http://lkml.kernel.org/r/<[email protected]>
* [WONTFIX] undefined shift in __bpf_prog_run - http://lkml.kernel.org/r/<CACT4Y+ZxoR3UjLgcNdUm4fECLMx2VdtfrENMtRRCdgHB2n0bJA@mail.gmail.com>
WONTFIX here because it should be fixed in bpf program, not in kernel.

signed overflows:
* 32a8df4e0b33f ("sched: Fix odd values in effective_load() calculations")
* mul overflow in ntp - http://lkml.kernel.org/r/<[email protected]>
* incorrect conversion into rtc_time in rtc_time64_to_tm() - http://lkml.kernel.org/r/<[email protected]>
* unvalidated timespec in io_getevents() - http://lkml.kernel.org/r/<CACT4Y+bBxVYLQ6LtOKrKtnLthqLHcw-BMp3aqP3mjdAvr9FULQ@mail.gmail.com>
* [NOTABUG] signed overflow in ktime_add_safe() - http://lkml.kernel.org/r/<CACT4Y+aJ4muRnWxsUe1CMnA6P8nooO33kwG-c8YZg=0Xc8rJqw@mail.gmail.com>