Explain frag alignment hacks

Alan Modra amodra@gmail.com
Wed Sep 3 05:34:20 GMT 2025


"the weird alignment hackery" comment doesn't help anyone understand
the code.  Explain what is going on.  Replace the zero length
obstack_alloc with obstack_finish, which by inspection of obstack.h is
all the zero length alloc does.

	* frags.c (frag_alloc): Comment.  Replace zero length
	obstack_alloc with obstack_finish.
	(frag_new): Remove unnecessary obstack_finish.
	* write.c (compress_frag, compress_debug): Likewise.

diff --git a/gas/frags.c b/gas/frags.c
index 0ad1240a7bd..54b98d1d735 100644
--- a/gas/frags.c
+++ b/gas/frags.c
@@ -69,8 +69,8 @@ frag_alloc_check (const struct obstack *ob)
 }
 
 /* Allocate a frag on the specified obstack.
-   Call this routine from everywhere else, so that all the weird alignment
-   hackery can be done in just one place.  */
+   Call this routine every time a new frag is made, so that the
+   alignment hackery can be done in just one place.  */
 
 fragS *
 frag_alloc (struct obstack *ob, size_t extra)
@@ -78,7 +78,12 @@ frag_alloc (struct obstack *ob, size_t extra)
   fragS *ptr;
   int oalign;
 
-  (void) obstack_alloc (ob, 0);
+  /* This will align the obstack so the next struct we allocate on it
+     will begin at a correct boundary.  */
+  (void) obstack_finish (ob);
+  /* Turn off alignment as otherwise obstack_alloc will align the end
+     of the frag (obstack next_free pointer), making it seem like the
+     frag already has contents in fr_literal.  */
   oalign = obstack_alignment_mask (ob);
   obstack_alignment_mask (ob) = 0;
   ptr = obstack_alloc (ob, extra + SIZEOF_STRUCT_FRAG);
@@ -172,9 +177,6 @@ frag_new (size_t old_frags_var_max_size
   /* Make sure its type is valid.  */
   gas_assert (frag_now->fr_type != 0);
 
-  /* This will align the obstack so the next struct we allocate on it
-     will begin at a correct boundary.  */
-  obstack_finish (&frchain_now->frch_obstack);
   frchP = frchain_now;
   know (frchP);
   former_last_fragP = frchP->frch_last;
diff --git a/gas/write.c b/gas/write.c
index 9d304455338..33d821b144e 100644
--- a/gas/write.c
+++ b/gas/write.c
@@ -1456,7 +1456,6 @@ compress_frag (bool use_zstd, void *ctx, const char *contents, int in_size,
       avail_out = obstack_room (ob);
       if (avail_out <= 0)
 	{
-	  obstack_finish (ob);
 	  f = frag_alloc (ob, 0);
 	  f->fr_type = rs_fill;
 	  (*last_newf)->fr_next = f;
@@ -1570,10 +1569,7 @@ compress_debug (bfd *abfd, asection *sec, void *xxx ATTRIBUTE_UNUSED)
       avail_out = obstack_room (ob);
       if (avail_out <= 0)
 	{
-	  fragS *newf;
-
-	  obstack_finish (ob);
-	  newf = frag_alloc (ob, 0);
+	  fragS *newf = frag_alloc (ob, 0);
 	  newf->fr_type = rs_fill;
 	  last_newf->fr_next = newf;
 	  last_newf = newf;

-- 
Alan Modra


More information about the Binutils mailing list