PostgreSQL Source Code  git master
psprintf.c File Reference
#include "postgres.h"
#include "utils/memutils.h"
Include dependency graph for psprintf.c:

Go to the source code of this file.

Functions

char * psprintf (const char *fmt,...)
 
size_t pvsnprintf (char *buf, size_t len, const char *fmt, va_list args)
 

Function Documentation

◆ psprintf()

char* psprintf ( const char *  fmt,
  ... 
)

Definition at line 46 of file psprintf.c.

47 {
48  int save_errno = errno;
49  size_t len = 128; /* initial assumption about buffer size */
50 
51  for (;;)
52  {
53  char *result;
54  va_list args;
55  size_t newlen;
56 
57  /*
58  * Allocate result buffer. Note that in frontend this maps to malloc
59  * with exit-on-error.
60  */
61  result = (char *) palloc(len);
62 
63  /* Try to format the data. */
64  errno = save_errno;
65  va_start(args, fmt);
66  newlen = pvsnprintf(result, len, fmt, args);
67  va_end(args);
68 
69  if (newlen < len)
70  return result; /* success */
71 
72  /* Release buffer and loop around to try again with larger len. */
73  pfree(result);
74  len = newlen;
75  }
76 }
static void const char * fmt
va_end(args)
va_start(args, fmt)
void pfree(void *pointer)
Definition: mcxt.c:1508
void * palloc(Size size)
Definition: mcxt.c:1304
const void size_t len
size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
Definition: psprintf.c:106

References generate_unaccent_rules::args, fmt, len, palloc(), pfree(), pvsnprintf(), va_end(), and va_start().

Referenced by _mdfd_segpath(), accesstype_arg_to_string(), accesstype_to_string(), adjust_data_dir(), anytime_typmodout(), anytimestamp_typmodout(), auth_failed(), BaseBackup(), bbsink_server_begin_archive(), bbsink_server_begin_manifest(), bbsink_server_end_manifest(), BootstrapModeMain(), brin_metapage_info(), brin_page_type(), bt_entry_unique_check(), bt_metap(), bt_multi_page_stats(), bt_page_stats_internal(), bt_report_duplicate(), bt_target_page_check(), build_function_result_tupdesc_d(), build_server_final_message(), build_server_first_message(), cash_out(), check_compressed_file(), check_control_files(), check_for_composite_data_type_usage(), check_for_data_type_usage(), check_toast_tuple(), check_toasted_attribute(), check_tuple(), check_tuple_attribute(), check_tuple_header(), check_tuple_visibility(), check_valid_polymorphic_signature(), complex_out(), create_script_for_old_cluster_deletion(), create_tablespace_directories(), create_xlog_or_symlink(), CreateBackupStreamer(), datasegpath(), dblink_get_pkey(), DebugPrintBufferRefcount(), defGetString(), describeOneTableDetails(), destroy_tablespace_directories(), do_init(), do_shell(), dumpAttrDef(), dumpConstraint(), dumpFunc(), dumpPolicy(), dumpPublicationNamespace(), dumpPublicationTable(), dumpRule(), dumpSubscriptionTable(), dumpTrigger(), ecpg_postprocess_result(), ecpg_start_test(), editFile(), execute_extension_script(), expand_dynamic_library_name(), expand_tilde(), expect_boolean_value(), expect_integer_value(), ExplainNode(), ExplainPropertyFloat(), fetch_finfo_record(), filtered_base_yylex(), float4_to_char(), float8_to_char(), foreign_grouping_ok(), foreign_join_ok(), format_type_extended(), get_altertable_subcmdinfo(), get_collation_actual_version(), get_hba_options(), get_role_password(), get_user_name(), GetConfFilesInDir(), GetDatabasePath(), getFormattedOperatorName(), GetIncrementalFilePath(), getObjectIdentityParts(), GetRelationPath(), getTableAttrs(), GetWALBlockInfo(), GetWALRecordInfo(), GetXLogSummaryStats(), GUCArrayAdd(), HandleParallelApplyMessage(), HandleParallelMessage(), initialize_data_directory(), initialize_environment(), initializeInput(), InitializeSystemUser(), InitWalRecovery(), int4_to_char(), isolation_start_test(), json_errdetail(), libpqrcv_connect(), line_out(), llvm_compile_module(), llvm_expand_funcname(), llvm_function_reference(), load_libraries(), log_status_format(), main(), make_temp_sockdir(), makeMultirangeTypeName(), md5_crypt_verify(), open_auth_file(), parse_compress_specification(), parse_hba_auth_opt(), parse_hba_line(), parse_required_wal(), parseCommandLine(), perform_base_backup(), pg_control_checkpoint(), pg_get_multixact_members(), pg_import_system_collations(), pg_size_pretty_numeric(), pg_tablespace_databases(), pgstatindex_impl(), plain_crypt_verify(), postgresGetForeignRelSize(), postprocess_sql_command(), PrintManyTest(), PrintString(), printTypmod(), process_directory_recursively(), process_psqlrc_file(), ProcessConfigFileInternal(), prompt_for_password(), pset_value_string(), psql_start_test(), readCommandResponse(), reconstruct_from_incremental_file(), regcomp_auth_token(), ResourceOwnerReleaseAll(), ResOwnerPrintBufferIO(), ResOwnerPrintCatCache(), ResOwnerPrintCatCacheList(), ResOwnerPrintDSM(), ResOwnerPrintFile(), ResOwnerPrintRelCache(), ResOwnerPrintTupleDesc(), scram_init(), sendDir(), SendXlogRecPtrResult(), sequence_options(), set_input(), set_null_conf(), set_tablespace_directory_suffix(), spawn_process(), sql_exec_searchtables(), SS_make_initplan_from_plan(), SS_process_ctes(), start_postmaster(), StartLogStreamer(), StoreQueryTuple(), substitute_libpath_macro(), supports_compression(), test_resowner_many(), test_resowner_priorities(), test_singlerowmode(), tokenize_auth_file(), typenameTypeMod(), validate_compress_specification(), verify_backup_checksums(), verify_backup_directory(), verify_heapam(), wait_for_connection_state(), widget_out(), write_version_file(), XLogDumpDisplayStats(), and xstrcat().

◆ pvsnprintf()

size_t pvsnprintf ( char *  buf,
size_t  len,
const char *  fmt,
va_list  args 
)

Definition at line 106 of file psprintf.c.

107 {
108  int nprinted;
109 
110  nprinted = vsnprintf(buf, len, fmt, args);
111 
112  /* We assume failure means the fmt is bogus, hence hard failure is OK */
113  if (unlikely(nprinted < 0))
114  {
115 #ifndef FRONTEND
116  elog(ERROR, "vsnprintf failed: %m with format string \"%s\"", fmt);
117 #else
118  fprintf(stderr, "vsnprintf failed: %m with format string \"%s\"\n",
119  fmt);
121 #endif
122  }
123 
124  if ((size_t) nprinted < len)
125  {
126  /* Success. Note nprinted does not include trailing null. */
127  return (size_t) nprinted;
128  }
129 
130  /*
131  * We assume a C99-compliant vsnprintf, so believe its estimate of the
132  * required space, and add one for the trailing null. (If it's wrong, the
133  * logic will still work, but we may loop multiple times.)
134  *
135  * Choke if the required space would exceed MaxAllocSize. Note we use
136  * this palloc-oriented overflow limit even when in frontend.
137  */
138  if (unlikely((size_t) nprinted > MaxAllocSize - 1))
139  {
140 #ifndef FRONTEND
141  ereport(ERROR,
142  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
143  errmsg("out of memory")));
144 #else
145  fprintf(stderr, _("out of memory\n"));
147 #endif
148  }
149 
150  return nprinted + 1;
151 }
#define unlikely(x)
Definition: c.h:298
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define _(x)
Definition: elog.c:90
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
exit(1)
#define MaxAllocSize
Definition: memutils.h:40
static char * buf
Definition: pg_test_fsync.c:73
#define vsnprintf
Definition: port.h:237
#define fprintf
Definition: port.h:242
#define EXIT_FAILURE
Definition: settings.h:167

References _, generate_unaccent_rules::args, buf, elog, ereport, errcode(), errmsg(), ERROR, exit(), EXIT_FAILURE, fmt, fprintf, len, MaxAllocSize, unlikely, and vsnprintf.

Referenced by ahprintf(), appendJSONKeyValueFmt(), appendStringInfoVA(), archprintf(), psprintf(), and tarPrintf().