From 904ea4c6bf87895dda5be200a61f85c96004876f Mon Sep 17 00:00:00 2001
From: Tristan Partin <tristan@partin.io>
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 <tristan@partin.io>
---
 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

