Re: BUG #16801: Invalid memory access on WITH RECURSIVE with nested WITHs

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: Michael Paquier <michael@paquier.xyz>
Cc: Alexander Lakhin <exclusion@gmail.com>, pgsql-bugs@lists.postgresql.org
Date: 2021-02-24T15:19:23Z
Lists: pgsql-bugs
Michael Paquier <michael@paquier.xyz> writes:
> So attached is a patch to take care of this, with a regression test
> based on what has been sent upthread.  This solves the issue for me.

Surely that breaks things entirely (if it doesn't, then we are badly
under-testing this area).  A nil list is just a null pointer, so
appending to "new_cte_list" later isn't going to affect what was
previously put into the innerwiths list.

I haven't tested, but I think a more correct fix would be

-               ListCell   *cell1;

                cstate->innerwiths = lcons(NIL, cstate->innerwiths);
-               cell1 = list_head(cstate->innerwiths);
                foreach(lc, stmt->withClause->ctes)
                {
                    CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
+                   ListCell   *cell1;

                    (void) makeDependencyGraphWalker(cte->ctequery, cstate);
+                   /* note innerwiths list can change during recursion */
+                   cell1 = list_head(cstate->innerwiths);
                    lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
                }

ie, recompute the "cell1" pointer each time it's needed instead of
assuming that the original value is good throughout the loop.

			regards, tom lane



Commits

  1. Fix list-manipulation bug in WITH RECURSIVE processing.