Skip to contentSkip to conversation

mm/folio-compat.c: folio should not be NULL when it is referenced

PATCH In review Yi Wang 2 participants 2 messages Aug 23, 2021

Subsystems (2)
lore
Share & tools
lore

Yi Wang

author
#0 lore raw

PATCH 1/1 mm/folio-compat.c: folio should not be NULL when it is referenced

From: Changcheng Deng <[email protected]>

A bug was found by coccinelle:
folio is NULL but dereferenced
Therefore,added a check to make sure 'folio' is not NULL.

---
 mm/folio-compat.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/folio-compat.c +3 -2
index 5b6ae1d..bee45e7 100644
@@ -123,8 +123,9 @@ struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
 	struct folio *folio;
 
 	folio = __filemap_get_folio(mapping, index, fgp_flags, gfp);
-	if ((fgp_flags & FGP_HEAD) || !folio || xa_is_value(folio))
-		return &folio->page;
+	if ((fgp_flags & FGP_HEAD) || xa_is_value(folio))
+		if (folio != NULL)
+			return &folio->page;
 	return folio_file_page(folio, index);
 }
 EXPORT_SYMBOL(pagecache_get_page);
Signature · 1 line
1.8.3.1
#1 lore raw
Quoted 7 lines · Yi Wang

From: Changcheng Deng <[email protected]>

A bug was found by coccinelle:
folio is NULL but dereferenced
Therefore,added a check to make sure 'folio' is not NULL.

Your robot is overzealous. This does not dereference folio; rather it takes the address of the page element of the folio structure.

By a strict reading of the C spec, it is not allowed. However, GCC (and I assume Clang) does the right thing.

mm/folio-compat.c struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index, · line 129

Quoted 7 lines
mm/folio-compat.c +3 -2
 	folio = __filemap_get_folio(mapping, index, fgp_flags, gfp);
-	if ((fgp_flags & FGP_HEAD) || !folio || xa_is_value(folio))
-		return &folio->page;
+	if ((fgp_flags & FGP_HEAD) || xa_is_value(folio))
+		if (folio != NULL)
+			return &folio->page;
 	return folio_file_page(folio, index);

This is definitely wrong. Did you test it? I bet you get a NULL pointer dereference if you try it.

You could potentially make the case for:

	if (!folio)
		return NULL;
	if ((fgp_flags & FGP_HEAD) || xa_is_value(folio))
		return &folio->page;

but you actually have the same problem with the C spec, that unless folio is actually a pointer to a folio, then &folio->page is _technically_ undefined. So it would have to be something even more complex to be pedantically correct.

It's just not worth it. Fix your tool.