Skip to content

Commit 4232cff

Browse files
committed
Initialize random() in bootstrap/stand-alone postgres and in initdb.
This removes a difference between the standard IsUnderPostmaster execution environment and that of --boot and --single. In a stand-alone backend, "SELECT random()" always started at the same seed. On a system capable of using posix shared memory, initdb could still conclude "selecting dynamic shared memory implementation ... sysv". Crashed --boot or --single postgres processes orphaned shared memory objects having names that collided with the not-actually-random names that initdb probed. The sysv fallback appeared after ten crashes of --boot or --single postgres. Since --boot and --single are rare in production use, systems used for PostgreSQL development are the principal candidate to notice this symptom. Back-patch to 9.3 (all supported versions). PostgreSQL 9.4 introduced dynamic shared memory, but 9.3 does share the "SELECT random()" problem. Reviewed by Tom Lane and Kyotaro HORIGUCHI. Discussion: https://postgr.es/m/20180915221546.GA3159382@rfd.leadboat.com
1 parent 5ed281e commit 4232cff

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

src/backend/utils/init/miscinit.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,14 @@ InitStandaloneProcess(const char *argv0)
225225

226226
MyStartTime = time(NULL); /* set our start time in case we call elog */
227227

228+
/*
229+
* Initialize random() for the first time, like PostmasterMain() would.
230+
* In a regular IsUnderPostmaster backend, BackendRun() computes a
231+
* high-entropy seed before any user query. Fewer distinct initial seeds
232+
* can occur here.
233+
*/
234+
srandom((unsigned int) (MyProcPid ^ MyStartTime));
235+
228236
/* Initialize process-local latch support */
229237
InitializeLatchSupport();
230238
MyLatch = &LocalLatchData;

src/bin/initdb/initdb.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,9 @@ choose_dsm_implementation(void)
868868
#ifdef HAVE_SHM_OPEN
869869
int ntries = 10;
870870

871+
/* Initialize random(); this function is its only user in this program. */
872+
srandom((unsigned int) (getpid() ^ time(NULL)));
873+
871874
while (ntries > 0)
872875
{
873876
uint32 handle;

0 commit comments

Comments
 (0)