PostgreSQL Source Code  git master
pqexpbuffer.c File Reference
#include "postgres_fe.h"
#include <limits.h>
#include "pqexpbuffer.h"
Include dependency graph for pqexpbuffer.c:

Go to the source code of this file.

Functions

static bool appendPQExpBufferVA (PQExpBuffer str, const char *fmt, va_list args) pg_attribute_printf(2
 
static bool static void markPQExpBufferBroken (PQExpBuffer str)
 
PQExpBuffer createPQExpBuffer (void)
 
void initPQExpBuffer (PQExpBuffer str)
 
void destroyPQExpBuffer (PQExpBuffer str)
 
void termPQExpBuffer (PQExpBuffer str)
 
void resetPQExpBuffer (PQExpBuffer str)
 
int enlargePQExpBuffer (PQExpBuffer str, size_t needed)
 
void printfPQExpBuffer (PQExpBuffer str, const char *fmt,...)
 
void appendPQExpBuffer (PQExpBuffer str, const char *fmt,...)
 
void appendPQExpBufferStr (PQExpBuffer str, const char *data)
 
void appendPQExpBufferChar (PQExpBuffer str, char ch)
 
void appendBinaryPQExpBuffer (PQExpBuffer str, const char *data, size_t datalen)
 

Variables

static const char oom_buffer [1] = ""
 
static const char * oom_buffer_ptr = oom_buffer
 

Function Documentation

◆ appendBinaryPQExpBuffer()

void appendBinaryPQExpBuffer ( PQExpBuffer  str,
const char *  data,
size_t  datalen 
)

Definition at line 399 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), and PQExpBufferData::len.

Referenced by appendPQExpBufferStr(), createViewAsClause(), and pqGets_internal().

400 {
401  /* Make more room if needed */
402  if (!enlargePQExpBuffer(str, datalen))
403  return;
404 
405  /* OK, append the data */
406  memcpy(str->data + str->len, data, datalen);
407  str->len += datalen;
408 
409  /*
410  * Keep a trailing null in place, even though it's probably useless for
411  * binary data...
412  */
413  str->data[str->len] = '\0';
414 }
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:174

◆ appendPQExpBuffer()

void appendPQExpBuffer ( PQExpBuffer  str,
const char *  fmt,
  ... 
)

Definition at line 267 of file pqexpbuffer.c.

References appendPQExpBufferVA(), generate_unaccent_rules::args, and PQExpBufferBroken.

Referenced by _getObjectDescription(), _printTocEntry(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), add_tablespace_footer(), AddAcl(), appendReloptionsArray(), binary_upgrade_extension_member(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), build_client_final_message(), build_client_first_message(), buildACLCommands(), buildDefaultACLCommands(), buildShSecLabelQuery(), check_for_data_type_usage(), cluster_conn_opts(), connectFailureMessage(), connectNoDelay(), constructConnStr(), createDummyViewAsClause(), CreateReplicationSlot(), createViewAsClause(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOperators(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTablespaces(), describeTypes(), do_kill(), DropReplicationSlot(), dumpAccessMethod(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDefaultACL(), dumpDomain(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpIndex(), dumpIndexAttach(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationTable(), dumpRangeType(), dumpRoles(), dumpRule(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStatisticsExt(), dumpStdStrings(), dumpSubscription(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUndefinedType(), dumpUserMappings(), emitShSecLabels(), ExecQueryUsingCursor(), expand_table_name_patterns(), fmtQualifiedId(), format_aggregate_signature(), format_function_arguments(), format_function_arguments_old(), format_function_signature(), GenerateRecoveryConfig(), get_create_object_cmd(), get_db_conn(), get_language_name(), get_parallel_object_list(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTypes(), libpqrcv_get_conninfo(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDomains(), listEventTriggers(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSDictionaries(), listUserMappings(), lockTableForWorker(), lookup_object_oid(), main(), makeAlterConfigCommand(), objectDescription(), parse_int_param(), parseAclItem(), permissionsList(), pg_GSS_error_int(), pgpassfileWarning(), pqBuildErrorMessage3(), PQconnectPoll(), prepare_vacuum_command(), printACLColumn(), processSQLNamePattern(), refreshMatViewData(), report_multiple_error_messages(), reportErrorPosition(), RestoreArchive(), runInitSteps(), runPgDump(), setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), setup_connection(), StreamLogicalLog(), and vacuum_one_database().

268 {
269  int save_errno = errno;
270  va_list args;
271  bool done;
272 
273  if (PQExpBufferBroken(str))
274  return; /* already failed */
275 
276  /* Loop in case we have to retry after enlarging the buffer. */
277  do
278  {
279  errno = save_errno;
280  va_start(args, fmt);
281  done = appendPQExpBufferVA(str, fmt, args);
282  va_end(args);
283  } while (!done);
284 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
static bool appendPQExpBufferVA(PQExpBuffer str, const char *fmt, va_list args) pg_attribute_printf(2
Definition: pqexpbuffer.c:296

◆ appendPQExpBufferChar()

void appendPQExpBufferChar ( PQExpBuffer  str,
char  ch 
)

Definition at line 380 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), and PQExpBufferData::len.

Referenced by _doSetSessionAuth(), AddAcl(), appendConnStrVal(), appendPsqlMetaConnect(), appendShellStringNoError(), appendStringLiteralConn(), appendStringLiteralDQ(), binary_upgrade_set_pg_class_oids(), build_client_first_message(), cluster_conn_opts(), cluster_one_database(), conninfo_uri_parse_options(), constructConnStr(), copyAclUserName(), create_script_for_cluster_analyze(), createDummyViewAsClause(), describeOneTableDetails(), describeRoles(), do_edit(), dumpCompositeType(), dumpConstraint(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpRule(), dumpTableData_insert(), dumpTableSchema(), dumpUserConfig(), ExecuteSimpleCommands(), fmtCopyColumnList(), fmtId(), format_aggregate_signature(), format_function_arguments_old(), format_function_signature(), gather_boolean_expression(), GenerateRecoveryConfig(), get_create_object_cmd(), getAggregates(), getFuncs(), main(), MainLoop(), minimal_error_message(), pg_append_history(), pqBuildErrorMessage3(), PQconnectPoll(), prepare_vacuum_command(), processSQLNamePattern(), reportErrorPosition(), run_reindex_command(), and StreamLogicalLog().

381 {
382  /* Make more room if needed */
383  if (!enlargePQExpBuffer(str, 1))
384  return;
385 
386  /* OK, append the character */
387  str->data[str->len] = ch;
388  str->len++;
389  str->data[str->len] = '\0';
390 }
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:174

◆ appendPQExpBufferStr()

void appendPQExpBufferStr ( PQExpBuffer  str,
const char *  data 
)

Definition at line 369 of file pqexpbuffer.c.

References appendBinaryPQExpBuffer().

Referenced by _connectDB(), _doSetSessionAuth(), _getObjectDescription(), _printTocEntry(), _selectOutputSchema(), _selectTablespace(), add_role_attribute(), AddAcl(), appendConnStrVal(), appendPsqlMetaConnect(), appendQualifiedRelation(), appendReloptionsArray(), appendShellStringNoError(), appendStringLiteralDQ(), binary_upgrade_extension_member(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), build_client_final_message(), build_client_first_message(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), CloneArchive(), cluster_all_databases(), cluster_conn_opts(), cluster_one_database(), collectComments(), collectSecLabels(), conninfo_uri_parse_options(), copy_previous_query(), create_script_for_cluster_analyze(), create_sql_command(), createDummyViewAsClause(), CreateReplicationSlot(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_connect(), do_copy(), do_edit(), do_kill(), dumpAccessMethod(), dumpACL(), dumpAgg(), dumpBaseType(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpRangeType(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpSubscription(), dumpTableComment(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpUserMappings(), emitShSecLabels(), exec_command_ef_ev(), expand_dbname_patterns(), expand_schema_name_patterns(), fmtCopyColumnList(), fmtId(), fmtQualifiedId(), format_aggregate_signature(), format_function_arguments(), format_function_signature(), gather_boolean_expression(), generate_old_dump(), GenerateRecoveryConfig(), get_create_object_cmd(), get_db_conn(), get_parallel_object_list(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getDependencies(), getExtensionMembership(), getExtensions(), getFuncs(), getInherits(), getNamespaces(), getRules(), gets_fromFile(), getTableAttrs(), getTables(), getTransforms(), getTSParsers(), getTSTemplates(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lookup_object_oid(), main(), makeAlterConfigCommand(), minimal_error_message(), objectDescription(), permissionsList(), pg_append_history(), pqBuildErrorMessage3(), pqCatenateResultError(), PQconnectPoll(), PQexecFinish(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqPrepareAsyncResult(), prepare_vacuum_command(), processSQLNamePattern(), reindex_all_databases(), report_multiple_error_messages(), reportErrorPosition(), restore_toc_entry(), RestoreArchive(), restoreErrorMessage(), run_reindex_command(), runInitSteps(), runPgDump(), saveErrorMessage(), setup_connection(), StreamLogicalLog(), vacuum_all_databases(), and vacuum_one_database().

370 {
371  appendBinaryPQExpBuffer(str, data, strlen(data));
372 }
void appendBinaryPQExpBuffer(PQExpBuffer str, const char *data, size_t datalen)
Definition: pqexpbuffer.c:399

◆ appendPQExpBufferVA()

static bool appendPQExpBufferVA ( PQExpBuffer  str,
const char *  fmt,
va_list  args 
)
static

Definition at line 296 of file pqexpbuffer.c.

References PQExpBufferData::data, enlargePQExpBuffer(), PQExpBufferData::len, markPQExpBufferBroken(), PQExpBufferData::maxlen, unlikely, and vsnprintf.

Referenced by appendPQExpBuffer(), and printfPQExpBuffer().

297 {
298  size_t avail;
299  size_t needed;
300  int nprinted;
301 
302  /*
303  * Try to format the given string into the available space; but if there's
304  * hardly any space, don't bother trying, just enlarge the buffer first.
305  */
306  if (str->maxlen > str->len + 16)
307  {
308  avail = str->maxlen - str->len;
309 
310  nprinted = vsnprintf(str->data + str->len, avail, fmt, args);
311 
312  /*
313  * If vsnprintf reports an error, fail (we assume this means there's
314  * something wrong with the format string).
315  */
316  if (unlikely(nprinted < 0))
317  {
319  return true;
320  }
321 
322  if ((size_t) nprinted < avail)
323  {
324  /* Success. Note nprinted does not include trailing null. */
325  str->len += nprinted;
326  return true;
327  }
328 
329  /*
330  * We assume a C99-compliant vsnprintf, so believe its estimate of the
331  * required space, and add one for the trailing null. (If it's wrong,
332  * the logic will still work, but we may loop multiple times.)
333  *
334  * Choke if the required space would exceed INT_MAX, since str->maxlen
335  * can't represent more than that.
336  */
337  if (unlikely(nprinted > INT_MAX - 1))
338  {
340  return true;
341  }
342  needed = nprinted + 1;
343  }
344  else
345  {
346  /*
347  * We have to guess at how much to enlarge, since we're skipping the
348  * formatting work. Fortunately, because of enlargePQExpBuffer's
349  * preference for power-of-2 sizes, this number isn't very sensitive;
350  * the net effect is that we'll double the buffer size before trying
351  * to run vsnprintf, which seems sensible.
352  */
353  needed = 32;
354  }
355 
356  /* Increase the buffer size and try again. */
357  if (!enlargePQExpBuffer(str, needed))
358  return true; /* oops, out of memory */
359 
360  return false;
361 }
static bool static void markPQExpBufferBroken(PQExpBuffer str)
Definition: pqexpbuffer.c:52
#define vsnprintf
Definition: port.h:191
#define unlikely(x)
Definition: c.h:208
int enlargePQExpBuffer(PQExpBuffer str, size_t needed)
Definition: pqexpbuffer.c:174

◆ createPQExpBuffer()

PQExpBuffer createPQExpBuffer ( void  )

Definition at line 74 of file pqexpbuffer.c.

References initPQExpBuffer(), and malloc.

Referenced by _doSetSessionAuth(), _printTocEntry(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), _WriteBlobData(), appendStringLiteralDQ(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), buildShSecLabels(), cluster_conn_opts(), collectComments(), collectSecLabels(), constructConnStr(), createDummyViewAsClause(), CreateReplicationSlot(), createViewAsClause(), do_kill(), DropReplicationSlot(), dropRoles(), dump_lo_buf(), dumpAccessMethod(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDefaultACL(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpIndex(), dumpIndexAttach(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationTable(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStatisticsExt(), dumpStdStrings(), dumpSubscription(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUndefinedType(), dumpUserConfig(), dumpUserMappings(), exec_command_sf_sv(), ExecuteSimpleCommands(), expand_dbname_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fmtQualifiedId(), gather_boolean_expression(), GenerateRecoveryConfig(), get_create_object_cmd(), get_language_name(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), GetMyPSlot(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), gets_fromFile(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), lockTableForWorker(), lookup_object_oid(), main(), MainLoop(), minimal_error_message(), processExtensionTables(), refreshMatViewData(), RestoreArchive(), runPgDump(), setup_connection(), and StreamLogicalLog().

75 {
76  PQExpBuffer res;
77 
78  res = (PQExpBuffer) malloc(sizeof(PQExpBufferData));
79  if (res != NULL)
80  initPQExpBuffer(res);
81 
82  return res;
83 }
PQExpBufferData * PQExpBuffer
Definition: pqexpbuffer.h:51
#define malloc(a)
Definition: header.h:50
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ destroyPQExpBuffer()

void destroyPQExpBuffer ( PQExpBuffer  str)

Definition at line 116 of file pqexpbuffer.c.

References free, and termPQExpBuffer().

Referenced by _doSetSessionAuth(), _printTocEntry(), _selectOutputSchema(), _selectTableAccessMethod(), _selectTablespace(), _WriteBlobData(), appendStringLiteralDQ(), BaseBackup(), binary_upgrade_set_pg_class_oids(), binary_upgrade_set_type_oids_by_rel_oid(), binary_upgrade_set_type_oids_by_type_oid(), buildACLCommands(), buildDefaultACLCommands(), buildMatViewRefreshDependencies(), buildShSecLabels(), collectComments(), collectSecLabels(), constructConnStr(), CreateReplicationSlot(), createViewAsClause(), DeCloneArchive(), DropReplicationSlot(), dropRoles(), dump_lo_buf(), dumpAccessMethod(), dumpACL(), dumpAgg(), dumpAttrDef(), dumpBaseType(), dumpBlob(), dumpCast(), dumpCollation(), dumpComment(), dumpCompositeType(), dumpCompositeTypeColComments(), dumpConstraint(), dumpConversion(), dumpDatabase(), dumpDatabaseConfig(), dumpDefaultACL(), dumpDomain(), dumpEncoding(), dumpEnumType(), dumpEventTrigger(), dumpExtension(), dumpForeignDataWrapper(), dumpForeignServer(), dumpFunc(), dumpGroups(), dumpIndex(), dumpIndexAttach(), dumpNamespace(), dumpOpclass(), dumpOpfamily(), dumpOpr(), dumpPolicy(), dumpProcLang(), dumpPublication(), dumpPublicationTable(), dumpRangeType(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpSearchPath(), dumpSecLabel(), dumpSequence(), dumpSequenceData(), dumpShellType(), dumpStatisticsExt(), dumpStdStrings(), dumpSubscription(), dumpTable(), dumpTableComment(), dumpTableConstraintComment(), dumpTableData(), dumpTableData_copy(), dumpTableData_insert(), dumpTableSchema(), dumpTableSecLabel(), dumpTablespaces(), dumpTransform(), dumpTrigger(), dumpTSConfig(), dumpTSDictionary(), dumpTSParser(), dumpTSTemplate(), dumpUndefinedType(), dumpUserConfig(), dumpUserMappings(), exec_command_sf_sv(), expand_dbname_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), fmtQualifiedId(), get_create_object_cmd(), get_language_name(), getAccessMethods(), getAggregates(), getBlobs(), getCasts(), getCollations(), getConstraints(), getConversions(), getDefaultACLs(), getDependencies(), getDomainConstraints(), getEventTriggers(), getExtendedStatistics(), getExtensionMembership(), getExtensions(), getForeignDataWrappers(), getForeignServers(), getFormattedTypeName(), getFuncs(), getIndexes(), getInherits(), getNamespaces(), getOpclasses(), getOperators(), getOpfamilies(), getPolicies(), getProcLangs(), getPublications(), getPublicationTables(), getRules(), getSubscriptions(), getTableAttrs(), getTables(), getTransforms(), getTriggers(), getTSConfigurations(), getTSDictionaries(), getTSParsers(), getTSTemplates(), getTypes(), ignore_boolean_expression(), is_true_boolean_expression(), lockTableForWorker(), lookup_object_oid(), main(), MainLoop(), minimal_error_message(), processExtensionTables(), refreshMatViewData(), RestoreArchive(), runPgDump(), setup_connection(), and StreamLogicalLog().

117 {
118  if (str)
119  {
120  termPQExpBuffer(str);
121  free(str);
122  }
123 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define free(a)
Definition: header.h:65

◆ enlargePQExpBuffer()

int enlargePQExpBuffer ( PQExpBuffer  str,
size_t  needed 
)

Definition at line 174 of file pqexpbuffer.c.

References PQExpBufferData::data, PQExpBufferData::len, markPQExpBufferBroken(), PQExpBufferData::maxlen, PQExpBufferBroken, and realloc.

Referenced by appendBinaryPQExpBuffer(), appendByteaLiteral(), appendPQExpBufferChar(), appendPQExpBufferVA(), appendStringLiteral(), appendStringLiteralConn(), and build_client_final_message().

175 {
176  size_t newlen;
177  char *newdata;
178 
179  if (PQExpBufferBroken(str))
180  return 0; /* already failed */
181 
182  /*
183  * Guard against ridiculous "needed" values, which can occur if we're fed
184  * bogus data. Without this, we can get an overflow or infinite loop in
185  * the following.
186  */
187  if (needed >= ((size_t) INT_MAX - str->len))
188  {
190  return 0;
191  }
192 
193  needed += str->len + 1; /* total space required now */
194 
195  /* Because of the above test, we now have needed <= INT_MAX */
196 
197  if (needed <= str->maxlen)
198  return 1; /* got enough space already */
199 
200  /*
201  * We don't want to allocate just a little more space with each append;
202  * for efficiency, double the buffer size each time it overflows.
203  * Actually, we might need to more than double it if 'needed' is big...
204  */
205  newlen = (str->maxlen > 0) ? (2 * str->maxlen) : 64;
206  while (needed > newlen)
207  newlen = 2 * newlen;
208 
209  /*
210  * Clamp to INT_MAX in case we went past it. Note we are assuming here
211  * that INT_MAX <= UINT_MAX/2, else the above loop could overflow. We
212  * will still have newlen >= needed.
213  */
214  if (newlen > (size_t) INT_MAX)
215  newlen = (size_t) INT_MAX;
216 
217  newdata = (char *) realloc(str->data, newlen);
218  if (newdata != NULL)
219  {
220  str->data = newdata;
221  str->maxlen = newlen;
222  return 1;
223  }
224 
226  return 0;
227 }
static bool static void markPQExpBufferBroken(PQExpBuffer str)
Definition: pqexpbuffer.c:52
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
#define realloc(a, b)
Definition: header.h:60

◆ initPQExpBuffer()

void initPQExpBuffer ( PQExpBuffer  str)

Definition at line 92 of file pqexpbuffer.c.

References PQExpBufferData::data, INITIAL_EXPBUFFER_SIZE, PQExpBufferData::len, malloc, PQExpBufferData::maxlen, oom_buffer_ptr, and unconstify.

Referenced by _connectDB(), _reconnectToDB(), add_tablespace_footer(), appendPsqlMetaConnect(), appendQualifiedRelation(), build_client_final_message(), build_client_first_message(), check_for_data_type_usage(), CloneArchive(), cluster_all_databases(), cluster_one_database(), conninfo_uri_parse_options(), create_script_for_cluster_analyze(), create_sql_command(), createPQExpBuffer(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_connect(), do_copy(), exec_command_password(), ExecQueryUsingCursor(), format_aggregate_signature(), format_function_arguments(), format_function_arguments_old(), format_function_signature(), generate_old_dump(), GenerateRecoveryConfig(), get_db_conn(), get_parallel_object_list(), getCasts(), getParameterStatus(), getTransforms(), helpSQL(), libpqrcv_get_conninfo(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), main(), makeEmptyPGconn(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_6_invalidate_hash_indexes(), ParseScript(), permissionsList(), pg_SASL_init(), pqCatenateResultError(), PQconndefaults(), PQconninfo(), PQconninfoParse(), pqGetErrorNotice2(), pqGetErrorNotice3(), PQresultVerboseErrorMessage(), process_backslash_command(), processSQLNamePattern(), psql_get_variable(), reindex_all_databases(), report_multiple_error_messages(), resetPQExpBuffer(), restore_toc_entry(), run_reindex_command(), runInitSteps(), saveErrorMessage(), vacuum_all_databases(), and vacuum_one_database().

93 {
94  str->data = (char *) malloc(INITIAL_EXPBUFFER_SIZE);
95  if (str->data == NULL)
96  {
97  str->data = unconstify(char *, oom_buffer_ptr); /* see comment above */
98  str->maxlen = 0;
99  str->len = 0;
100  }
101  else
102  {
104  str->len = 0;
105  str->data[0] = '\0';
106  }
107 }
#define malloc(a)
Definition: header.h:50
#define unconstify(underlying_type, expr)
Definition: c.h:1194
static const char * oom_buffer_ptr
Definition: pqexpbuffer.c:41
#define INITIAL_EXPBUFFER_SIZE
Definition: pqexpbuffer.h:76

◆ markPQExpBufferBroken()

static bool static void markPQExpBufferBroken ( PQExpBuffer  str)
static

Definition at line 52 of file pqexpbuffer.c.

References PQExpBufferData::data, free, PQExpBufferData::len, PQExpBufferData::maxlen, oom_buffer, oom_buffer_ptr, and unconstify.

Referenced by appendPQExpBufferVA(), and enlargePQExpBuffer().

53 {
54  if (str->data != oom_buffer)
55  free(str->data);
56 
57  /*
58  * Casting away const here is a bit ugly, but it seems preferable to not
59  * marking oom_buffer const. We want to do that to encourage the compiler
60  * to put oom_buffer in read-only storage, so that anyone who tries to
61  * scribble on a broken PQExpBuffer will get a failure.
62  */
63  str->data = unconstify(char *, oom_buffer_ptr);
64  str->len = 0;
65  str->maxlen = 0;
66 }
static const char oom_buffer[1]
Definition: pqexpbuffer.c:38
#define unconstify(underlying_type, expr)
Definition: c.h:1194
#define free(a)
Definition: header.h:65
static const char * oom_buffer_ptr
Definition: pqexpbuffer.c:41

◆ printfPQExpBuffer()

void printfPQExpBuffer ( PQExpBuffer  str,
const char *  fmt,
  ... 
)

Definition at line 237 of file pqexpbuffer.c.

References appendPQExpBufferVA(), generate_unaccent_rules::args, PQExpBufferBroken, and resetPQExpBuffer().

Referenced by add_tablespace_footer(), binary_upgrade_set_type_oids_by_type_oid(), build_client_final_message(), build_client_first_message(), buildACLCommands(), buildACLQueries(), check_expected_areq(), connectDBStart(), connectOptions2(), conninfo_add_defaults(), conninfo_array_parse(), conninfo_init(), conninfo_parse(), conninfo_storeval(), conninfo_uri_decode(), conninfo_uri_parse_options(), conninfo_uri_parse_params(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), do_copy(), dropRoles(), dumpDatabaseConfig(), dumpGroups(), dumpRoleMembership(), dumpRoles(), dumpRule(), dumpUserConfig(), exec_command_password(), fillPGconn(), get_create_object_cmd(), getAnotherTuple(), getParamDescriptions(), getRowDescriptions(), getTableAttrs(), handleSyncLoss(), initialize_SSL(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), lo_create(), lo_export(), lo_import_internal(), lo_initialize(), lo_lseek64(), lo_read(), lo_tell64(), lo_truncate(), lo_truncate64(), lo_write(), main(), minimal_error_message(), open_client_SSL(), openssl_verify_peer_name_matches_certificate_name(), parseAclItem(), parseServiceFile(), parseServiceInfo(), permissionsList(), pg_fe_getauthname(), pg_fe_scram_exchange(), pg_fe_sendauth(), pg_GSS_load_servicename(), pg_GSS_read(), pg_GSS_write(), pg_local_sendauth(), pg_password_sendauth(), pg_SASL_continue(), pg_SASL_init(), pgtls_read(), pgtls_write(), pq_verify_peer_name_matches_certificate(), pq_verify_peer_name_matches_certificate_name(), pqCheckInBufferSpace(), pqCheckOutBufferSpace(), PQconnectPoll(), PQencryptPasswordConn(), pqEndcopy2(), pqEndcopy3(), PQescapeByteaInternal(), PQescapeInternal(), PQescapeStringInternal(), PQexecStart(), PQfn(), pqFunctionCall2(), pqFunctionCall3(), PQgetCopyData(), pqGetCopyData2(), pqGetCopyData3(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqGetline3(), PQgetResult(), pqPacketSend(), pqParseInput2(), pqParseInput3(), PQputCopyData(), PQputCopyEnd(), pqReadData(), PQreset(), PQresetPoll(), pqsecure_open_gss(), pqsecure_raw_read(), pqsecure_raw_write(), PQsendDescribe(), PQsendPrepare(), PQsendQuery(), PQsendQueryGuts(), PQsendQueryParams(), PQsendQueryPrepared(), PQsendQueryStart(), pqSendSome(), PQsetdbLogin(), pqSetenvPoll(), pqSocketCheck(), pqWaitTimed(), processExtensionTables(), read_attr_value(), read_server_final_message(), read_server_first_message(), restoreErrorMessage(), and saveErrorMessage().

238 {
239  int save_errno = errno;
240  va_list args;
241  bool done;
242 
243  resetPQExpBuffer(str);
244 
245  if (PQExpBufferBroken(str))
246  return; /* already failed */
247 
248  /* Loop in case we have to retry after enlarging the buffer. */
249  do
250  {
251  errno = save_errno;
252  va_start(args, fmt);
253  done = appendPQExpBufferVA(str, fmt, args);
254  va_end(args);
255  } while (!done);
256 }
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
static bool appendPQExpBufferVA(PQExpBuffer str, const char *fmt, va_list args) pg_attribute_printf(2
Definition: pqexpbuffer.c:296

◆ resetPQExpBuffer()

void resetPQExpBuffer ( PQExpBuffer  str)

Definition at line 148 of file pqexpbuffer.c.

References PQExpBufferData::data, initPQExpBuffer(), PQExpBufferData::len, and oom_buffer.

Referenced by closePGconn(), cluster_all_databases(), cluster_conn_opts(), connectDBComplete(), connectDBStart(), copyAclUserName(), describeOneTableDetails(), describeRoles(), do_edit(), dumpCompositeTypeColComments(), dumpDatabase(), dumpOpclass(), dumpOpfamily(), dumpRoles(), dumpSequence(), dumpSequenceData(), dumpTableComment(), dumpTableData_insert(), dumpTableSecLabel(), dumpTSConfig(), dumpUserConfig(), dumpUserMappings(), exec_command_ef_ev(), exec_command_reset(), exec_command_watch(), ExecuteSimpleCommands(), expand_dbname_patterns(), expand_schema_name_patterns(), expand_table_name_patterns(), get_create_object_cmd(), get_parallel_object_list(), getConstraints(), getIndexes(), GetMyPSlot(), getPolicies(), getPublications(), getPublicationTables(), gets_fromFile(), getSubscriptions(), getTableAttrs(), getTables(), getTriggers(), MainLoop(), parseAclItem(), ParseScript(), pg_GSS_error(), pg_send_history(), pqEndcopy2(), pqEndcopy3(), PQexecFinish(), PQfn(), pqGetErrorNotice2(), pqGetErrorNotice3(), pqGets_internal(), pqPrepareAsyncResult(), PQputCopyEnd(), PQsendQueryStart(), pqSendSome(), prepare_vacuum_command(), printfPQExpBuffer(), processSQLNamePattern(), reindex_all_databases(), restoreErrorMessage(), saveErrorMessage(), StreamLogicalLog(), vacuum_all_databases(), and vacuum_one_database().

149 {
150  if (str)
151  {
152  if (str->data != oom_buffer)
153  {
154  str->len = 0;
155  str->data[0] = '\0';
156  }
157  else
158  {
159  /* try to reinitialize to valid state */
160  initPQExpBuffer(str);
161  }
162  }
163 }
static const char oom_buffer[1]
Definition: pqexpbuffer.c:38
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92

◆ termPQExpBuffer()

void termPQExpBuffer ( PQExpBuffer  str)

Definition at line 131 of file pqexpbuffer.c.

References PQExpBufferData::data, free, PQExpBufferData::len, PQExpBufferData::maxlen, oom_buffer, oom_buffer_ptr, and unconstify.

Referenced by _connectDB(), _reconnectToDB(), add_tablespace_footer(), appendPsqlMetaConnect(), appendQualifiedRelation(), build_client_final_message(), build_client_first_message(), check_for_data_type_usage(), CloneArchive(), cluster_all_databases(), cluster_one_database(), conninfo_uri_parse_options(), create_script_for_cluster_analyze(), describeAccessMethods(), describeAggregates(), describeFunctions(), describeOneTableDetails(), describeOneTSConfig(), describeOneTSParser(), describeOperators(), describePublications(), DescribeQuery(), describeRoles(), describeSubscriptions(), describeTableDetails(), describeTablespaces(), describeTypes(), destroyPQExpBuffer(), do_connect(), do_copy(), exec_command_password(), ExecQueryUsingCursor(), free_command(), freePGconn(), generate_old_dump(), GenerateRecoveryConfig(), get_db_conn(), get_parallel_object_list(), getParameterStatus(), libpqrcv_get_conninfo(), listAllDbs(), listCasts(), listCollations(), listConversions(), listDbRoleSettings(), listDefaultACLs(), listDomains(), listEventTriggers(), listExtensionContents(), listExtensions(), listForeignDataWrappers(), listForeignServers(), listForeignTables(), listLanguages(), listOneExtensionContents(), listPartitionedTables(), listPublications(), listSchemas(), listTables(), listTSConfigs(), listTSConfigsVerbose(), listTSDictionaries(), listTSParsers(), listTSParsersVerbose(), listTSTemplates(), listUserMappings(), main(), new_9_0_populate_pg_largeobject_metadata(), objectDescription(), old_9_6_invalidate_hash_indexes(), ParseScript(), permissionsList(), pg_SASL_init(), pqCatenateResultError(), PQconndefaults(), PQconnectPoll(), PQconninfo(), PQconninfoParse(), pqGetErrorNotice2(), pqGetErrorNotice3(), PQresultVerboseErrorMessage(), process_backslash_command(), processSQLNamePattern(), reindex_all_databases(), report_multiple_error_messages(), restoreErrorMessage(), run_reindex_command(), runInitSteps(), vacuum_all_databases(), and vacuum_one_database().

132 {
133  if (str->data != oom_buffer)
134  free(str->data);
135  /* just for luck, make the buffer validly empty. */
136  str->data = unconstify(char *, oom_buffer_ptr); /* see comment above */
137  str->maxlen = 0;
138  str->len = 0;
139 }
static const char oom_buffer[1]
Definition: pqexpbuffer.c:38
#define unconstify(underlying_type, expr)
Definition: c.h:1194
#define free(a)
Definition: header.h:65
static const char * oom_buffer_ptr
Definition: pqexpbuffer.c:41

Variable Documentation

◆ oom_buffer

const char oom_buffer[1] = ""
static

Definition at line 38 of file pqexpbuffer.c.

Referenced by markPQExpBufferBroken(), resetPQExpBuffer(), and termPQExpBuffer().

◆ oom_buffer_ptr

const char* oom_buffer_ptr = oom_buffer
static

Definition at line 41 of file pqexpbuffer.c.

Referenced by initPQExpBuffer(), markPQExpBufferBroken(), and termPQExpBuffer().