On Fri Nov 13, 2026 at 11:51 AM UTC, Peter Eisentraut wrote:
> In my ventures to apply more compiler attributes, I came to alloc_size. 
> This is to annotate memory allocation functions so that the compiler can 
> know the size of the allocated memory and so some cross-checking based 
> on that.  This is all pretty straightforward and I think we should do it.
>
> Andres had previously reported some issues he encountered in [0].  (That 
> message didn't go into details on what attributes or compiler options 
> were used, but it certainly looked very closely related.)
>
> The issue is that under-allocating a struct is bad.  With this 
> attribute, the compiler flags this, because it looks like a mistake. 
> For uses where this is legitimate, you'd normally use a struct with a 
> trailing flexible-array member, and we mostly make use of that.  But 
> there are a couple of cases where we assign to a struct pointer less 
> memory than what the struct expects.  In some cases, this is done with a 
> union where we only allocate enough memory for one branch of the union, 
> which seems like an intuitive thing to do but is actually also bad.
>
> In the attached patches I have some fixes and/or workarounds for the 
> issues that I found.
>
> Note that as documented this attribute and the associated warning 
> options are for diagnostics only, they don't change compilation.  So in 
> that sense, once all warnings are fixed, this shouldn't create any more 
> hidden issues.
>
> - varattrib_4b is a union of a normal varlena with a 4-byte header and 0 
> or more payload bytes, and a compressed format with a 4-byte header, a 
> 4-byte "tcinfo", followed by payload data.  The typical coding pattern
>
>      val = palloc(VARHDRSZ + len);
>      SET_VARSIZE(val, VARHDRSZ + len);
>
> could get flagged by -Warray-bounds because the allocation could be too 
> short to cover both branches of the union.  In this case, I think we 
> don't actually need the union, so I'm replacing this with two separate 
> structs.
>
> - TRGM in contrib/pg_trgm/ is an instance of what [0] talks about: It 
> has a trailing flexible array member, but it also has trailing padding, 
> so allocating palloc(TRGMHDRSIZE) causes a warning, because it's less 
> than sizeof(TRGM).  In my patch I work around this by allocating like 
> palloc(Max(TRGMHDRSIZE, sizeof(TRGM))).

Maybe we should add an allocator function or macro for this? In the 
counted_by discussion, I talked a bit about how core does a pretty good 
job of providing allocator helpers for structs with flexible array 
members. I realize this is contrib/, but it might still be valuable.

> - There is a bit of a maze of different structs and unions that underlie 
> the numeric type.  The allocation (Numeric) palloc(NUMERIC_HDRSZ_SHORT) 
> gets flagged by the compiler.  In my patch I change this to (Numeric) 
> palloc(sizeof(struct NumericData)), which allocates a bit more but makes 
> the sizes and types match.  Maybe some more judicious reshuffling of the 
> underlying data structures could avoid this, or maybe it's okay like this.

Like the previous comment, I wonder if some helper allocator 
functions/macros could be useful. But as you said, maybe some 
reshuffling could avoid that all together, not sure.

> - As of commit 6a3da13d376 from this week, FormData_pg_attribute has 4 
> bytes of trailing padding, and so sizeof(FormData_pg_attribute) is now 
> different from ATTRIBUTE_FIXED_PART_SIZE.  This causes a warning in one 
> place.  We had a discussion about this some time ago [1], where the 
> opinions diverged between like, it's important to keep this distinction 
> in case we ever have padding bytes, and, it's already incorrect and 
> would be even more incorrect if we had padding bytes. ;-)  Well, we're 
> here now, so perhaps this should be revisited.

In [1], Tom said:

> What I'm trying to figure out is if we need to put in place some
> provisions to prevent there from being pad bytes at the end of any
> catalog struct.

I figured I could propose at least one way to flag padding bytes in the 
attached patch. I am currently not proposing a solution.

Two options proposed in the thread[1]:

- Placeholder fields exactly matching the size of the padding bytes.

        #ifdef CATALOG_VARLEN                   /* variable-length fields start 
here */
                pg_node_tree ev_qual;
                pg_node_tree ev_action;
        #else
                uint8       dummy;
        #endif

- Use different structs for on-media and in-memory representations.

To not rock the boat too much, maybe I would throw my hat in the ring 
for option 1? It seems like the simplest and most immediate solution.

> This is all that I found.  [0] lists a lot more sources of potential 
> problems, but apparently they are not flagged as they are currently used.
>
>
> [0]: 
> https://www.postgresql.org/message-id/flat/axxbw7ku4w24hwe6uvkm4vdufo4zr4k5344m6naahkpsoafag5%40llovwgptzbgq
>
> [1]: 
> https://www.postgresql.org/message-id/flat/7c7d41c1-fd5d-f9a5-afd5-f00168d91fe2%402ndquadrant.com

Anyway, thanks for the patch. I think the attribute is valuable, and 
it's good that we are having this discussion.

-- 
Tristan Partin
PostgreSQL Contributors Team
AWS (https://aws.amazon.com)
From 904ea4c6bf87895dda5be200a61f85c96004876f Mon Sep 17 00:00:00 2001
From: Tristan Partin <[email protected]>
Date: Fri, 13 Nov 2026 23:08:49 +0000
Subject: [PATCH v1] Add TAP test to check for trailing padding in catalog
 structs

The test uses pahole(1) to inspect debug information to get the struct
metadata and reports and error if any catalog structs have trailing
padding.

In Postgres, we sometimes allocate memory for catalog tuples that does
not necessarily match the size reported by sizeof(FormData_pg_foo). For
instance, AllocateAttribute() allocates only ATTRIBUTE_FIXED_PART_SIZE
bytes for an instance of FormData_pg_attribute. That is fine if
ATTRIBUTE_FIXED_PART_SIZE == sizeof(FormData_pg_attribute), but that
isn't necessarily guaranteed and in fact, is not the case in current
master.

That matters because, per C11 6.2.6.1p6:

    When a value is stored in an object of structure or union type,
    including in a member object, the bytes of the object
    representation that correspond to any padding bytes take
    unspecified values.

This could become a problem if someone were to write code like the
following:

	FormData_pg_attribute *attr = AllocateAttribute();

	attr->attcollation = ...;

The compiler could generate that code into a store wider than the
sizeof(attr->attcollation) due to the padding bytes at the end of the
struct. That could overwrite subsequent memory and create a corruption.

Signed-off-by: Tristan Partin <[email protected]>
---
 GNUmakefile.in                               |   2 +-
 configure                                    |  55 +++++++
 configure.ac                                 |   1 +
 meson.build                                  |   1 +
 meson_options.txt                            |   3 +
 src/Makefile.global.in                       |   1 +
 src/backend/catalog/.gitignore               |   3 +
 src/backend/catalog/Makefile                 |  17 +++
 src/backend/catalog/meson.build              |  15 ++
 src/backend/catalog/t/001_catalog_padding.pl | 143 +++++++++++++++++++
 src/makefiles/meson.build                    |   1 +
 11 files changed, 241 insertions(+), 1 deletion(-)
 create mode 100644 src/backend/catalog/.gitignore
 create mode 100644 src/backend/catalog/t/001_catalog_padding.pl

diff --git a/GNUmakefile.in b/GNUmakefile.in
index cf6e759486e..b8344053058 100644
--- a/GNUmakefile.in
+++ b/GNUmakefile.in
@@ -68,7 +68,7 @@ check check-tests installcheck installcheck-parallel installcheck-tests: CHECKPR
 check check-tests installcheck installcheck-parallel installcheck-tests: submake-generated-headers
 	$(MAKE) -C src/test/regress $@
 
-$(call recurse,check-world,src/test src/pl src/interfaces contrib src/bin src/tools/pg_bsd_indent,check)
+$(call recurse,check-world,src/test src/pl src/interfaces contrib src/bin src/tools/pg_bsd_indent src/backend/catalog,check)
 $(call recurse,checkprep,  src/test src/pl src/interfaces contrib src/bin)
 
 $(call recurse,installcheck-world,src/test src/pl src/interfaces contrib src/bin,installcheck)
diff --git a/configure b/configure
index 8d29a0bf6a0..2b22afc128d 100755
--- a/configure
+++ b/configure
@@ -685,6 +685,7 @@ BISON
 NM
 MKDIR_P
 LN_S
+PAHOLE
 TAR
 install_bin
 INSTALL_DATA
@@ -10381,6 +10382,60 @@ $as_echo_n "checking for TAR... " >&6; }
 $as_echo "$TAR" >&6; }
 fi
 
+if test -z "$PAHOLE"; then
+  for ac_prog in pahole
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_PAHOLE+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $PAHOLE in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_PAHOLE="$PAHOLE" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_PAHOLE="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  ;;
+esac
+fi
+PAHOLE=$ac_cv_path_PAHOLE
+if test -n "$PAHOLE"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PAHOLE" >&5
+$as_echo "$PAHOLE" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$PAHOLE" && break
+done
+
+else
+  # Report the value of PAHOLE in configure's output in all cases.
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for PAHOLE" >&5
+$as_echo_n "checking for PAHOLE... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PAHOLE" >&5
+$as_echo "$PAHOLE" >&6; }
+fi
+
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5
 $as_echo_n "checking whether ln -s works... " >&6; }
 LN_S=$as_ln_s
diff --git a/configure.ac b/configure.ac
index 36e4f9ca0cf..4fa9384f633 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1268,6 +1268,7 @@ esac
 AC_SUBST(install_bin)
 
 PGAC_PATH_PROGS(TAR, tar)
+PGAC_PATH_PROGS(PAHOLE, pahole)
 AC_PROG_LN_S
 AC_PROG_MKDIR_P
 # When Autoconf chooses install-sh as mkdir -p program it tries to generate
diff --git a/meson.build b/meson.build
index 3238c849e1b..863350b86b4 100644
--- a/meson.build
+++ b/meson.build
@@ -414,6 +414,7 @@ cp = find_program('cp', required: false, native: true)
 xmllint_bin = find_program(get_option('XMLLINT'), native: true, required: false)
 xsltproc_bin = find_program(get_option('XSLTPROC'), native: true, required: false)
 nm = find_program('nm', required: false, native: true)
+pahole = find_program(get_option('PAHOLE'), native: true, required: false)
 ditaa = find_program('ditaa', native: true, required: false)
 dot = find_program('dot', native: true, required: false)
 
diff --git a/meson_options.txt b/meson_options.txt
index 6a793f3e479..006d9a5cc13 100644
--- a/meson_options.txt
+++ b/meson_options.txt
@@ -189,6 +189,9 @@ option('LZ4', type: 'string', value: 'lz4',
 option('OPENSSL', type: 'string', value: 'openssl',
   description: 'Path to openssl binary')
 
+option('PAHOLE', type: 'string', value: 'pahole',
+  description: 'Path to pahole binary')
+
 option('PERL', type: 'string', value: 'perl',
   description: 'Path to perl binary')
 
diff --git a/src/Makefile.global.in b/src/Makefile.global.in
index 38914773b83..91ff5066cb6 100644
--- a/src/Makefile.global.in
+++ b/src/Makefile.global.in
@@ -357,6 +357,7 @@ MSGFMT  = @MSGFMT@
 MSGFMT_FLAGS = @MSGFMT_FLAGS@
 MSGMERGE = @MSGMERGE@
 OPENSSL	= @OPENSSL@
+PAHOLE	= @PAHOLE@
 PYTHON	= @PYTHON@
 TAR	= @TAR@
 XGETTEXT = @XGETTEXT@
diff --git a/src/backend/catalog/.gitignore b/src/backend/catalog/.gitignore
new file mode 100644
index 00000000000..eb31e701acd
--- /dev/null
+++ b/src/backend/catalog/.gitignore
@@ -0,0 +1,3 @@
+# Generated by test suite
+/log/
+/tmp_check/
diff --git a/src/backend/catalog/Makefile b/src/backend/catalog/Makefile
index 26fa0c9b18c..d81685b6cc6 100644
--- a/src/backend/catalog/Makefile
+++ b/src/backend/catalog/Makefile
@@ -64,3 +64,20 @@ installdirs:
 .PHONY: uninstall-data
 uninstall-data:
 	rm -f $(addprefix '$(DESTDIR)$(datadir)'/, system_functions.sql system_views.sql information_schema.sql sql_features.txt)
+
+# pahole needs debug information to inspect struct layouts
+ifeq ($(enable_debug),yes)
+export PAHOLE
+else
+export PAHOLE =
+endif
+
+check:
+	$(prove_check)
+
+installcheck:
+	$(prove_installcheck)
+
+clean: clean-check
+clean-check:
+	rm -rf log/ tmp_check/
diff --git a/src/backend/catalog/meson.build b/src/backend/catalog/meson.build
index 11d21c5ad6b..917da33c725 100644
--- a/src/backend/catalog/meson.build
+++ b/src/backend/catalog/meson.build
@@ -45,3 +45,18 @@ install_data(
   'system_views.sql',
   install_dir: dir_data,
 )
+
+tests += {
+  'name': 'catalog_padding',
+  'sd': meson.current_source_dir(),
+  'bd': meson.current_build_dir(),
+  'tap': {
+    'env': {
+      # pahole needs debug information to inspect struct layouts
+      'PAHOLE': pahole.found() and get_option('debug') ? pahole.full_path() : '',
+    },
+    'tests': [
+      't/001_catalog_padding.pl',
+    ],
+  },
+}
diff --git a/src/backend/catalog/t/001_catalog_padding.pl b/src/backend/catalog/t/001_catalog_padding.pl
new file mode 100644
index 00000000000..58393c6ecec
--- /dev/null
+++ b/src/backend/catalog/t/001_catalog_padding.pl
@@ -0,0 +1,143 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that system catalog structs (FormData_pg_*) have no trailing
+# padding.
+#
+# Trailing padding means sizeof(FormData_pg_foo) is larger than the end
+# of the struct's last fixed-width column.  Code that allocates only the
+# fixed part of a catalog row (e.g. ATTRIBUTE_FIXED_PART_SIZE) and then
+# accesses it through a struct pointer can then trigger -Warray-bounds
+# warnings when allocation functions are marked with alloc_size.
+#
+# This uses pahole to inspect the debug information of the installed
+# postgres binary.  A catalog struct that is missing from the debug
+# information also counts as a failure.  The results are only valid for
+# the architecture the binary was built for.
+
+use strict;
+use warnings FATAL => 'all';
+
+use Config;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my @catalog_structs = qw(
+  FormData_pg_aggregate
+  FormData_pg_am
+  FormData_pg_amop
+  FormData_pg_amproc
+  FormData_pg_attrdef
+  FormData_pg_attribute
+  FormData_pg_auth_members
+  FormData_pg_authid
+  FormData_pg_cast
+  FormData_pg_class
+  FormData_pg_collation
+  FormData_pg_constraint
+  FormData_pg_conversion
+  FormData_pg_database
+  FormData_pg_db_role_setting
+  FormData_pg_default_acl
+  FormData_pg_depend
+  FormData_pg_description
+  FormData_pg_enum
+  FormData_pg_event_trigger
+  FormData_pg_extension
+  FormData_pg_foreign_data_wrapper
+  FormData_pg_foreign_server
+  FormData_pg_foreign_table
+  FormData_pg_index
+  FormData_pg_inherits
+  FormData_pg_init_privs
+  FormData_pg_language
+  FormData_pg_largeobject
+  FormData_pg_largeobject_metadata
+  FormData_pg_namespace
+  FormData_pg_opclass
+  FormData_pg_operator
+  FormData_pg_opfamily
+  FormData_pg_parameter_acl
+  FormData_pg_partitioned_table
+  FormData_pg_policy
+  FormData_pg_proc
+  FormData_pg_publication
+  FormData_pg_publication_namespace
+  FormData_pg_publication_rel
+  FormData_pg_range
+  FormData_pg_replication_origin
+  FormData_pg_rewrite
+  FormData_pg_seclabel
+  FormData_pg_sequence
+  FormData_pg_shdepend
+  FormData_pg_shdescription
+  FormData_pg_shseclabel
+  FormData_pg_statistic
+  FormData_pg_statistic_ext
+  FormData_pg_statistic_ext_data
+  FormData_pg_subscription
+  FormData_pg_subscription_rel
+  FormData_pg_tablespace
+  FormData_pg_transform
+  FormData_pg_trigger
+  FormData_pg_ts_config
+  FormData_pg_ts_config_map
+  FormData_pg_ts_dict
+  FormData_pg_ts_parser
+  FormData_pg_ts_template
+  FormData_pg_type
+  FormData_pg_user_mapping
+);
+
+my $pahole = $ENV{PAHOLE};
+plan skip_all => 'pahole not available'
+  unless defined $pahole && $pahole ne '';
+
+my ($bindir) = run_command([ 'pg_config', '--bindir' ]);
+my $binary = "$bindir/postgres$Config{_exe}";
+BAIL_OUT("postgres binary not found: $binary") unless -f $binary;
+
+my ($stdout, $stderr) =
+  run_command([ $pahole, '--prefix_filter=FormData_pg_', $binary ]);
+diag("pahole stderr: $stderr") if $stderr ne '';
+
+my %wanted = map { $_ => 1 } @catalog_structs;
+my %found;
+my %padding;
+my $current;
+foreach my $line (split /\n/, $stdout)
+{
+	if ($line =~ /^struct (\w+) \{/)
+	{
+		if ($wanted{$1})
+		{
+			$current = $1;
+			$found{$current} = 1;
+			$padding{$current} = 0;
+		}
+		else
+		{
+			undef $current;
+		}
+	}
+	elsif (defined $current && $line =~ m{/\* padding: (\d+) \*/})
+	{
+		$padding{$current} = $1;
+	}
+	elsif ($line =~ /^\};/)
+	{
+		undef $current;
+	}
+}
+
+foreach my $struct (@catalog_structs)
+{
+	if (!$found{$struct})
+	{
+		fail("$struct found in debug information");
+		next;
+	}
+
+	is($padding{$struct}, 0, "$struct has no trailing padding");
+}
+
+done_testing();
diff --git a/src/makefiles/meson.build b/src/makefiles/meson.build
index d0430b3519e..d1711c746f6 100644
--- a/src/makefiles/meson.build
+++ b/src/makefiles/meson.build
@@ -164,6 +164,7 @@ pgxs_empty = [
   'ZIC',
   'TCLSH',
   'NM',
+  'PAHOLE',
 
   # docs don't seem to be supported by pgxs
   'XMLLINT',
-- 
Tristan Partin
https://tristan.partin.io

Reply via email to