[PATCH v1 6/8] perf maps: Avoid UB passing NULL to bsearch

Ian Rogers posted 8 patches 1 year ago
There is a newer version of this series
[PATCH v1 6/8] perf maps: Avoid UB passing NULL to bsearch
Posted by Ian Rogers 1 year ago
If maps_by_address is NULL it is UB to pass it to bsearch, and will
trigger ubsan, even if the nr_maps is 0.

Fixes: 659ad3492b91 ("perf maps: Switch from rbtree to lazily sorted array for addresses")
Signed-off-by: Ian Rogers <irogers@google.com>
---
 tools/perf/util/maps.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/tools/perf/util/maps.c b/tools/perf/util/maps.c
index 432399cbe5dd..1830ae776052 100644
--- a/tools/perf/util/maps.c
+++ b/tools/perf/util/maps.c
@@ -1042,10 +1042,13 @@ struct map *maps__find(struct maps *maps, u64 ip)
 	while (!done) {
 		down_read(maps__lock(maps));
 		if (maps__maps_by_address_sorted(maps)) {
-			struct map **mapp =
-				bsearch(&ip, maps__maps_by_address(maps), maps__nr_maps(maps),
-					sizeof(*mapp), map__addr_cmp);
+			struct map **mapp = NULL;
 
+			if (maps__maps_by_address(maps)) {
+				mapp = bsearch(&ip, maps__maps_by_address(maps),
+					       maps__nr_maps(maps), sizeof(*mapp),
+					       map__addr_cmp);
+			}
 			if (mapp)
 				result = map__get(*mapp);
 			done = true;
-- 
2.47.1.613.gc27f4b7a9f-goog
Re: [PATCH v1 6/8] perf maps: Avoid UB passing NULL to bsearch
Posted by Kuan-Wei Chiu 1 year ago
On Fri, Dec 13, 2024 at 01:04:23PM -0800, Ian Rogers wrote:
> If maps_by_address is NULL it is UB to pass it to bsearch, and will
> trigger ubsan, even if the nr_maps is 0.
> 
> Fixes: 659ad3492b91 ("perf maps: Switch from rbtree to lazily sorted array for addresses")
> Signed-off-by: Ian Rogers <irogers@google.com>

Reviewed-by: Kuan-Wei Chiu <visitorckw@gmail.com>

Regards,
Kuan-Wei