public inbox for [email protected]  
help / color / mirror / Atom feed
From: Tristan Partin <[email protected]>
To: pgsql-hackers <[email protected]>
Subject: Add support for __attribute__((returns_nonnull))
Date: Tue, 19 Dec 2023 14:43:49 -0600
Message-ID: <[email protected]> (raw)

Here is a patch which adds support for the returns_nonnull attribute 
alongside all the other attributes we optionally support.

I recently wound up in a situation where I was checking for NULL return 
values of a function that couldn't ever return NULL because the 
inability to allocate memory was always elog(ERROR)ed (aborted).

I didn't go through and mark anything, but I feel like it could be 
useful for people going forward, including myself.

-- 
Tristan Partin
Neon (https://neon.tech)


Attachments:

  [text/x-patch] v1-0001-Add-support-for-__attribute__-returns_nonnull.patch (1.2K, ../[email protected]/2-v1-0001-Add-support-for-__attribute__-returns_nonnull.patch)
  download | inline diff:
From 15a36d68519b332e7ae970708399744cbc69c6c3 Mon Sep 17 00:00:00 2001
From: Tristan Partin <[email protected]>
Date: Tue, 19 Dec 2023 14:39:03 -0600
Subject: [PATCH v1] Add support for __attribute__((returns_nonnull))

Allows for marking functions that can't possibly return NULL, like those
that always elog(ERROR) for instance in the case of failures.
---
 src/include/c.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/include/c.h b/src/include/c.h
index 26bf7ec16e..e3a127f954 100644
--- a/src/include/c.h
+++ b/src/include/c.h
@@ -285,6 +285,18 @@
 #define pg_unreachable() abort()
 #endif
 
+/*
+ * Place on functions which return a pointer but can't return NULL. When used,
+ * it can allow the compiler to warn if a NULL check occurs in the parent
+ * function because that NULL check would always fail. It is also an opportunity
+ * to help the compiler with optimizations.
+ */
+#if __has_attribute (returns_nonnull)
+#define pg_returns_nonnull __attribute__((returns_nonnull))
+#else
+#define pg_returns_nonnull
+#endif
+
 /*
  * Hints to the compiler about the likelihood of a branch. Both likely() and
  * unlikely() return the boolean value of the contained expression.
-- 
Tristan Partin
Neon (https://neon.tech)



view thread (2+ messages)

reply

Reply instructions:

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

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected]
  Subject: Re: Add support for __attribute__((returns_nonnull))
  In-Reply-To: <[email protected]>

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

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox