thermal: core: Move initial num_trips assignment before memcpy()
authorNathan Chancellor <nathan@kernel.org>
Tue, 27 Feb 2024 00:54:58 +0000 (17:54 -0700)
committerRafael J. Wysocki <rafael.j.wysocki@intel.com>
Tue, 27 Feb 2024 10:58:47 +0000 (11:58 +0100)
commitda1983355ccefcfb3f8eb410fff82e250fa87e39
tree05ed4e07bc36b2cd7744dbeb4f3e7228d693b3ab
parenta85739c8c6894c3b9ff860e79e91db44cb59bd63
thermal: core: Move initial num_trips assignment before memcpy()

When booting a CONFIG_FORTIFY_SOURCE=y kernel compiled with a toolchain
that supports __counted_by() (such as clang-18 and newer), there is a
panic on boot:

  [    2.913770] memcpy: detected buffer overflow: 72 byte write of buffer size 0
  [    2.920834] WARNING: CPU: 2 PID: 1 at lib/string_helpers.c:1027 __fortify_report+0x5c/0x74
  ...
  [    3.039208] Call trace:
  [    3.041643]  __fortify_report+0x5c/0x74
  [    3.045469]  __fortify_panic+0x18/0x20
  [    3.049209]  thermal_zone_device_register_with_trips+0x4c8/0x4f8

This panic occurs because trips is counted by num_trips but num_trips is
assigned after the call to memcpy(), so the fortify checks think the
buffer size is zero because tz was allocated with kzalloc().

Move the num_trips assignment before the memcpy() to resolve the panic
and ensure that the fortify checks work properly.

Fixes: 9b0a62758665 ("thermal: core: Store zone trips table in struct thermal_zone_device")
Signed-off-by: Nathan Chancellor <nathan@kernel.org>
Reviewed-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Rafael J. Wysocki <rafael.j.wysocki@intel.com>
drivers/thermal/thermal_core.c