PostgreSQL Source Code git master
injection_points.c
Go to the documentation of this file.
1/*--------------------------------------------------------------------------
2 *
3 * injection_points.c
4 * Code for testing injection points.
5 *
6 * Injection points are able to trigger user-defined callbacks in pre-defined
7 * code paths.
8 *
9 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
11 *
12 * IDENTIFICATION
13 * src/test/modules/injection_points/injection_points.c
14 *
15 * -------------------------------------------------------------------------
16 */
17
18#include "postgres.h"
19
20#include "fmgr.h"
21#include "funcapi.h"
22#include "injection_stats.h"
23#include "miscadmin.h"
24#include "nodes/pg_list.h"
25#include "nodes/value.h"
28#include "storage/ipc.h"
29#include "storage/lwlock.h"
30#include "storage/shmem.h"
31#include "utils/builtins.h"
32#include "utils/guc.h"
34#include "utils/memutils.h"
35#include "utils/wait_event.h"
36
38
39/* Maximum number of waits usable in injection points at once */
40#define INJ_MAX_WAIT 8
41#define INJ_NAME_MAXLEN 64
42
43/*
44 * Conditions related to injection points. This tracks in shared memory the
45 * runtime conditions under which an injection point is allowed to run,
46 * stored as private_data when an injection point is attached, and passed as
47 * argument to the callback.
48 *
49 * If more types of runtime conditions need to be tracked, this structure
50 * should be expanded.
51 */
53{
54 INJ_CONDITION_ALWAYS = 0, /* always run */
55 INJ_CONDITION_PID, /* PID restriction */
57
59{
60 /* Type of the condition */
62
63 /* ID of the process where the injection point is allowed to run */
64 int pid;
66
67/*
68 * List of injection points stored in TopMemoryContext attached
69 * locally to this process.
70 */
72
73/*
74 * Shared state information for injection points.
75 *
76 * This state data can be initialized in two ways: dynamically with a DSM
77 * or when loading the module.
78 */
80{
81 /* Protects access to other fields */
82 slock_t lock;
83
84 /* Counters advancing when injection_points_wakeup() is called */
86
87 /* Names of injection points attached to wait counters */
89
90 /* Condition variable used for waits and wakeups */
93
94/* Pointer to shared-memory state. */
96
97extern PGDLLEXPORT void injection_error(const char *name,
98 const void *private_data,
99 void *arg);
100extern PGDLLEXPORT void injection_notice(const char *name,
101 const void *private_data,
102 void *arg);
103extern PGDLLEXPORT void injection_wait(const char *name,
104 const void *private_data,
105 void *arg);
106
107/* track if injection points attached in this process are linked to it */
108static bool injection_point_local = false;
109
110/*
111 * GUC variable
112 *
113 * This GUC is useful to control if statistics should be enabled or not
114 * during a test with injection points, like for example if a test relies
115 * on a callback run in a critical section where no allocation should happen.
116 */
117bool inj_stats_enabled = false;
118
119/* Shared memory init callbacks */
122
123/*
124 * Routine for shared memory area initialization, used as a callback
125 * when initializing dynamically with a DSM or when loading the module.
126 */
127static void
129{
131
132 SpinLockInit(&state->lock);
133 memset(state->wait_counts, 0, sizeof(state->wait_counts));
134 memset(state->name, 0, sizeof(state->name));
135 ConditionVariableInit(&state->wait_point);
136}
137
138/* Shared memory initialization when loading module */
139static void
141{
142 Size size;
143
146
147 size = MAXALIGN(sizeof(InjectionPointSharedState));
149}
150
151static void
153{
154 bool found;
155
158
159 /* Create or attach to the shared memory state */
160 LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
161
162 inj_state = ShmemInitStruct("injection_points",
164 &found);
165
166 if (!found)
167 {
168 /*
169 * First time through, so initialize. This is shared with the dynamic
170 * initialization using a DSM.
171 */
173 }
174
175 LWLockRelease(AddinShmemInitLock);
176}
177
178/*
179 * Initialize shared memory area for this module through DSM.
180 */
181static void
183{
184 bool found;
185
186 if (inj_state != NULL)
187 return;
188
189 inj_state = GetNamedDSMSegment("injection_points",
192 &found);
193}
194
195/*
196 * Check runtime conditions associated to an injection point.
197 *
198 * Returns true if the named injection point is allowed to run, and false
199 * otherwise.
200 */
201static bool
203{
204 bool result = true;
205
206 switch (condition->type)
207 {
209 if (MyProcPid != condition->pid)
210 result = false;
211 break;
213 break;
214 }
215
216 return result;
217}
218
219/*
220 * before_shmem_exit callback to remove injection points linked to a
221 * specific process.
222 */
223static void
225{
226 ListCell *lc;
227
228 /* Leave if nothing is tracked locally */
230 return;
231
232 /* Detach all the local points */
233 foreach(lc, inj_list_local)
234 {
235 char *name = strVal(lfirst(lc));
236
238
239 /* Remove stats entry */
241 }
242}
243
244/* Set of callbacks available to be attached to an injection point. */
245void
246injection_error(const char *name, const void *private_data, void *arg)
247{
248 InjectionPointCondition *condition = (InjectionPointCondition *) private_data;
249 char *argstr = (char *) arg;
250
251 if (!injection_point_allowed(condition))
252 return;
253
255
256 if (argstr)
257 elog(ERROR, "error triggered for injection point %s (%s)",
258 name, argstr);
259 else
260 elog(ERROR, "error triggered for injection point %s", name);
261}
262
263void
264injection_notice(const char *name, const void *private_data, void *arg)
265{
266 InjectionPointCondition *condition = (InjectionPointCondition *) private_data;
267 char *argstr = (char *) arg;
268
269 if (!injection_point_allowed(condition))
270 return;
271
273
274 if (argstr)
275 elog(NOTICE, "notice triggered for injection point %s (%s)",
276 name, argstr);
277 else
278 elog(NOTICE, "notice triggered for injection point %s", name);
279}
280
281/* Wait on a condition variable, awaken by injection_points_wakeup() */
282void
283injection_wait(const char *name, const void *private_data, void *arg)
284{
285 uint32 old_wait_counts = 0;
286 int index = -1;
287 uint32 injection_wait_event = 0;
288 InjectionPointCondition *condition = (InjectionPointCondition *) private_data;
289
290 if (inj_state == NULL)
292
293 if (!injection_point_allowed(condition))
294 return;
295
297
298 /*
299 * Use the injection point name for this custom wait event. Note that
300 * this custom wait event name is not released, but we don't care much for
301 * testing as this should be short-lived.
302 */
303 injection_wait_event = WaitEventInjectionPointNew(name);
304
305 /*
306 * Find a free slot to wait for, and register this injection point's name.
307 */
309 for (int i = 0; i < INJ_MAX_WAIT; i++)
310 {
311 if (inj_state->name[i][0] == '\0')
312 {
313 index = i;
315 old_wait_counts = inj_state->wait_counts[i];
316 break;
317 }
318 }
320
321 if (index < 0)
322 elog(ERROR, "could not find free slot for wait of injection point %s ",
323 name);
324
325 /* And sleep.. */
327 for (;;)
328 {
329 uint32 new_wait_counts;
330
332 new_wait_counts = inj_state->wait_counts[index];
334
335 if (old_wait_counts != new_wait_counts)
336 break;
337 ConditionVariableSleep(&inj_state->wait_point, injection_wait_event);
338 }
340
341 /* Remove this injection point from the waiters. */
343 inj_state->name[index][0] = '\0';
345}
346
347/*
348 * SQL function for creating an injection point.
349 */
351Datum
353{
356 char *function;
357 InjectionPointCondition condition = {0};
358
359 if (strcmp(action, "error") == 0)
360 function = "injection_error";
361 else if (strcmp(action, "notice") == 0)
362 function = "injection_notice";
363 else if (strcmp(action, "wait") == 0)
364 function = "injection_wait";
365 else
366 elog(ERROR, "incorrect action \"%s\" for injection point creation", action);
367
369 {
370 condition.type = INJ_CONDITION_PID;
371 condition.pid = MyProcPid;
372 }
373
374 pgstat_report_inj_fixed(1, 0, 0, 0, 0);
375 InjectionPointAttach(name, "injection_points", function, &condition,
377
379 {
380 MemoryContext oldctx;
381
382 /* Local injection point, so track it for automated cleanup */
385 MemoryContextSwitchTo(oldctx);
386 }
387
388 /* Add entry for stats */
390
392}
393
394/*
395 * SQL function for creating an injection point with library name, function
396 * name and private data.
397 */
399Datum
401{
402 char *name;
403 char *lib_name;
404 char *function;
405 bytea *private_data = NULL;
406 int private_data_size = 0;
407
408 if (PG_ARGISNULL(0))
409 elog(ERROR, "injection point name cannot be NULL");
410 if (PG_ARGISNULL(1))
411 elog(ERROR, "injection point library cannot be NULL");
412 if (PG_ARGISNULL(2))
413 elog(ERROR, "injection point function cannot be NULL");
414
416 lib_name = text_to_cstring(PG_GETARG_TEXT_PP(1));
418
419 if (!PG_ARGISNULL(3))
420 {
421 private_data = PG_GETARG_BYTEA_PP(3);
422 private_data_size = VARSIZE_ANY_EXHDR(private_data);
423 }
424
425 pgstat_report_inj_fixed(1, 0, 0, 0, 0);
426 if (private_data != NULL)
427 InjectionPointAttach(name, lib_name, function, VARDATA_ANY(private_data),
428 private_data_size);
429 else
430 InjectionPointAttach(name, lib_name, function, NULL,
431 0);
433}
434
435/*
436 * SQL function for loading an injection point.
437 */
439Datum
441{
443
444 if (inj_state == NULL)
446
447 pgstat_report_inj_fixed(0, 0, 0, 0, 1);
449
451}
452
453/*
454 * SQL function for triggering an injection point.
455 */
457Datum
459{
460 char *name;
461 char *arg = NULL;
462
463 if (PG_ARGISNULL(0))
466
467 if (!PG_ARGISNULL(1))
469
470 pgstat_report_inj_fixed(0, 0, 1, 0, 0);
472
474}
475
476/*
477 * SQL function for triggering an injection point from cache.
478 */
480Datum
482{
483 char *name;
484 char *arg = NULL;
485
486 if (PG_ARGISNULL(0))
489
490 if (!PG_ARGISNULL(1))
492
493 pgstat_report_inj_fixed(0, 0, 0, 1, 0);
495
497}
498
499/*
500 * SQL function for waking up an injection point waiting in injection_wait().
501 */
503Datum
505{
507 int index = -1;
508
509 if (inj_state == NULL)
511
512 /* First bump the wait counter for the injection point to wake up */
514 for (int i = 0; i < INJ_MAX_WAIT; i++)
515 {
516 if (strcmp(name, inj_state->name[i]) == 0)
517 {
518 index = i;
519 break;
520 }
521 }
522 if (index < 0)
523 {
525 elog(ERROR, "could not find injection point %s to wake up", name);
526 }
529
530 /* And broadcast the change to the waiters */
533}
534
535/*
536 * injection_points_set_local
537 *
538 * Track if any injection point created in this process ought to run only
539 * in this process. Such injection points are detached automatically when
540 * this process exits. This is useful to make test suites concurrent-safe.
541 */
543Datum
545{
546 /* Enable flag to add a runtime condition based on this process ID */
548
549 if (inj_state == NULL)
551
552 /*
553 * Register a before_shmem_exit callback to remove any injection points
554 * linked to this process.
555 */
557
559}
560
561/*
562 * SQL function for dropping an injection point.
563 */
565Datum
567{
569
570 pgstat_report_inj_fixed(0, 1, 0, 0, 0);
572 elog(ERROR, "could not detach injection point \"%s\"", name);
573
574 /* Remove point from local list, if required */
575 if (inj_list_local != NIL)
576 {
577 MemoryContext oldctx;
578
581 MemoryContextSwitchTo(oldctx);
582 }
583
584 /* Remove stats entry */
586
588}
589
590/*
591 * SQL function for listing all the injection points attached.
592 */
594Datum
596{
597#define NUM_INJECTION_POINTS_LIST 3
598 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
599 List *inj_points;
600 ListCell *lc;
601
602 /* Build a tuplestore to return our results in */
603 InitMaterializedSRF(fcinfo, 0);
604
605 inj_points = InjectionPointList();
606
607 foreach(lc, inj_points)
608 {
610 bool nulls[NUM_INJECTION_POINTS_LIST];
611 InjectionPointData *inj_point = lfirst(lc);
612
613 memset(values, 0, sizeof(values));
614 memset(nulls, 0, sizeof(nulls));
615
616 values[0] = PointerGetDatum(cstring_to_text(inj_point->name));
619
620 /* shove row into tuplestore */
621 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
622 }
623
624 return (Datum) 0;
625#undef NUM_INJECTION_POINTS_LIST
626}
627
628
629void
631{
633 return;
634
635 DefineCustomBoolVariable("injection_points.stats",
636 "Enables statistics for injection points.",
637 NULL,
639 false,
641 0,
642 NULL,
643 NULL,
644 NULL);
645
646 MarkGUCPrefixReserved("injection_points");
647
648 /* Shared memory initialization */
653
656}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define MAXALIGN(LEN)
Definition: c.h:815
#define PGDLLEXPORT
Definition: c.h:1339
uint32_t uint32
Definition: c.h:543
size_t Size
Definition: c.h:615
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableInit(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
void * GetNamedDSMSegment(const char *name, size_t size, void(*init_callback)(void *ptr), bool *found)
Definition: dsm_registry.c:186
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define NOTICE
Definition: elog.h:35
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
int MyProcPid
Definition: globals.c:47
void DefineCustomBoolVariable(const char *name, const char *short_desc, const char *long_desc, bool *valueAddr, bool bootValue, GucContext context, int flags, GucBoolCheckHook check_hook, GucBoolAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5011
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5148
@ PGC_POSTMASTER
Definition: guc.h:74
bool InjectionPointDetach(const char *name)
List * InjectionPointList(void)
void InjectionPointAttach(const char *name, const char *library, const char *function, const void *private_data, int private_data_size)
#define INJECTION_POINT(name, arg)
#define INJECTION_POINT_CACHED(name, arg)
#define INJECTION_POINT_LOAD(name)
Datum injection_points_detach(PG_FUNCTION_ARGS)
static bool injection_point_local
static void injection_shmem_request(void)
#define INJ_MAX_WAIT
PG_FUNCTION_INFO_V1(injection_points_attach)
void _PG_init(void)
PGDLLEXPORT void injection_wait(const char *name, const void *private_data, void *arg)
InjectionPointConditionType
@ INJ_CONDITION_PID
@ INJ_CONDITION_ALWAYS
static void injection_init_shmem(void)
Datum injection_points_cached(PG_FUNCTION_ARGS)
PG_MODULE_MAGIC
Datum injection_points_attach(PG_FUNCTION_ARGS)
struct InjectionPointCondition InjectionPointCondition
Datum injection_points_run(PG_FUNCTION_ARGS)
static List * inj_list_local
Datum injection_points_set_local(PG_FUNCTION_ARGS)
bool inj_stats_enabled
static shmem_startup_hook_type prev_shmem_startup_hook
static bool injection_point_allowed(InjectionPointCondition *condition)
static shmem_request_hook_type prev_shmem_request_hook
#define INJ_NAME_MAXLEN
static void injection_points_cleanup(int code, Datum arg)
static void injection_shmem_startup(void)
PGDLLEXPORT void injection_error(const char *name, const void *private_data, void *arg)
struct InjectionPointSharedState InjectionPointSharedState
Datum injection_points_attach_func(PG_FUNCTION_ARGS)
#define NUM_INJECTION_POINTS_LIST
Datum injection_points_wakeup(PG_FUNCTION_ARGS)
PGDLLEXPORT void injection_notice(const char *name, const void *private_data, void *arg)
Datum injection_points_list(PG_FUNCTION_ARGS)
static void injection_point_init_state(void *ptr)
static InjectionPointSharedState * inj_state
Datum injection_points_load(PG_FUNCTION_ARGS)
void pgstat_report_inj(const char *name)
void pgstat_register_inj(void)
void pgstat_create_inj(const char *name)
void pgstat_drop_inj(const char *name)
void pgstat_register_inj_fixed(void)
void pgstat_report_inj_fixed(uint32 numattach, uint32 numdetach, uint32 numrun, uint32 numcached, uint32 numloaded)
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void(* shmem_startup_hook_type)(void)
Definition: ipc.h:22
shmem_startup_hook_type shmem_startup_hook
Definition: ipci.c:59
void RequestAddinShmemSpace(Size size)
Definition: ipci.c:75
int i
Definition: isn.c:77
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_delete(List *list, void *datum)
Definition: list.c:853
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1174
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1894
@ LW_EXCLUSIVE
Definition: lwlock.h:112
char * pstrdup(const char *in)
Definition: mcxt.c:1759
MemoryContext TopMemoryContext
Definition: mcxt.c:166
void(* shmem_request_hook_type)(void)
Definition: miscadmin.h:533
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1789
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1786
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
on_exit_nicely_callback function
void * arg
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
uint64_t Datum
Definition: postgres.h:70
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:388
#define SpinLockInit(lock)
Definition: spin.h:57
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
InjectionPointConditionType type
const char * library
const char * function
uint32 wait_counts[INJ_MAX_WAIT]
char name[INJ_MAX_WAIT][INJ_NAME_MAXLEN]
ConditionVariable wait_point
Definition: pg_list.h:54
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363
Definition: type.h:96
Definition: regguts.h:323
Definition: c.h:697
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:82
static Size VARSIZE_ANY_EXHDR(const void *PTR)
Definition: varatt.h:472
static char * VARDATA_ANY(const void *PTR)
Definition: varatt.h:486
text * cstring_to_text(const char *s)
Definition: varlena.c:181
char * text_to_cstring(const text *t)
Definition: varlena.c:214
uint32 WaitEventInjectionPointNew(const char *wait_event_name)
Definition: wait_event.c:169
const char * name