Add use of asprintf()

Add asprintf(), pg_asprintf(), and psprintf() to simplify string
allocation and composition.  Replacement implementations taken from
NetBSD.

Reviewed-by: Álvaro Herrera <alvherre@2ndquadrant.com>
Reviewed-by: Asif Naeem <anaeem.it@gmail.com>
pull/6/head
Peter Eisentraut 12 years ago
parent a53dee43fe
commit 5b6d08cd29
  1. 3
      configure
  2. 2
      configure.in
  3. 3
      contrib/adminpack/adminpack.c
  4. 3
      contrib/oid2name/oid2name.c
  5. 21
      contrib/pg_upgrade/check.c
  6. 7
      contrib/pg_upgrade/tablespace.c
  7. 5
      contrib/pg_upgrade/util.c
  8. 4
      contrib/pg_upgrade/version_old_8_3.c
  9. 3
      contrib/spi/refint.c
  10. 3
      contrib/spi/timetravel.c
  11. 4
      src/backend/bootstrap/bootstrap.c
  12. 20
      src/backend/catalog/catalog.c
  13. 16
      src/backend/commands/tablespace.c
  14. 21
      src/backend/libpq/auth.c
  15. 3
      src/backend/optimizer/plan/subselect.c
  16. 33
      src/backend/parser/gram.y
  17. 7
      src/backend/postmaster/postmaster.c
  18. 22
      src/backend/utils/adt/cash.c
  19. 28
      src/backend/utils/adt/dbsize.c
  20. 13
      src/backend/utils/adt/misc.c
  21. 12
      src/backend/utils/fmgr/dfmgr.c
  22. 5
      src/backend/utils/fmgr/fmgr.c
  23. 8
      src/backend/utils/init/miscinit.c
  24. 3
      src/backend/utils/misc/guc.c
  25. 49
      src/backend/utils/mmgr/mcxt.c
  26. 31
      src/bin/initdb/initdb.c
  27. 16
      src/bin/pg_ctl/pg_ctl.c
  28. 10
      src/bin/pg_dump/compress_io.c
  29. 6
      src/bin/pg_dump/pg_dump.c
  30. 40
      src/bin/psql/command.c
  31. 9
      src/bin/psql/common.c
  32. 4
      src/bin/psql/copy.c
  33. 6
      src/bin/psql/input.c
  34. 8
      src/bin/psql/large_obj.c
  35. 14
      src/bin/psql/startup.c
  36. 4
      src/bin/psql/tab-complete.c
  37. 39
      src/common/fe_memutils.c
  38. 38
      src/common/relpath.c
  39. 1
      src/include/common/fe_memutils.h
  40. 3
      src/include/pg_config.h.in
  41. 5
      src/include/port.h
  42. 2
      src/include/utils/palloc.h
  43. 9
      src/interfaces/ecpg/test/expected/pgtypeslib-dt_test2.c
  44. 9
      src/interfaces/ecpg/test/pgtypeslib/dt_test2.pgc
  45. 17
      src/interfaces/libpq/fe-auth.c
  46. 10
      src/test/isolation/isolationtester.c
  47. 37
      src/test/regress/pg_regress.c

3
configure vendored

@ -21502,7 +21502,8 @@ fi
for ac_func in crypt fls getopt getrusage inet_aton random rint srandom strerror strlcat strlcpy
for ac_func in asprintf crypt fls getopt getrusage inet_aton random rint srandom strerror strlcat strlcpy
do do
as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
{ $as_echo "$as_me:$LINENO: checking for $ac_func" >&5 { $as_echo "$as_me:$LINENO: checking for $ac_func" >&5

@ -1346,7 +1346,7 @@ else
AC_CHECK_FUNCS([fpclass fp_class fp_class_d class], [break]) AC_CHECK_FUNCS([fpclass fp_class fp_class_d class], [break])
fi fi
AC_REPLACE_FUNCS([crypt fls getopt getrusage inet_aton random rint srandom strerror strlcat strlcpy]) AC_REPLACE_FUNCS([asprintf crypt fls getopt getrusage inet_aton random rint srandom strerror strlcat strlcpy])
case $host_os in case $host_os in

@ -376,8 +376,7 @@ pg_logdir_ls(PG_FUNCTION_ARGS)
/* Seems the timestamp is OK; prepare and return tuple */ /* Seems the timestamp is OK; prepare and return tuple */
values[0] = timestampbuf; values[0] = timestampbuf;
values[1] = palloc(strlen(fctx->location) + strlen(de->d_name) + 2); values[1] = psprintf("%s/%s", fctx->location, de->d_name);
sprintf(values[1], "%s/%s", fctx->location, de->d_name);
tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); tuple = BuildTupleFromCStrings(funcctx->attinmeta, values);

@ -508,8 +508,7 @@ sql_exec_searchtables(PGconn *conn, struct options * opts)
free(comma_filenodes); free(comma_filenodes);
/* now build the query */ /* now build the query */
todo = (char *) pg_malloc(650 + strlen(qualifiers)); pg_asprintf(&todo,
snprintf(todo, 650 + strlen(qualifiers),
"SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s\n" "SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s\n"
"FROM pg_catalog.pg_class c \n" "FROM pg_catalog.pg_class c \n"
" LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \n" " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \n"

@ -455,18 +455,13 @@ create_script_for_cluster_analyze(char **analyze_script_file_name)
FILE *script = NULL; FILE *script = NULL;
char *user_specification = ""; char *user_specification = "";
if (os_info.user_specified)
{
user_specification = pg_malloc(strlen(os_info.user) + 7);
sprintf(user_specification, "-U \"%s\" ", os_info.user);
}
*analyze_script_file_name = pg_malloc(MAXPGPATH);
prep_status("Creating script to analyze new cluster"); prep_status("Creating script to analyze new cluster");
snprintf(*analyze_script_file_name, MAXPGPATH, "analyze_new_cluster.%s", if (os_info.user_specified)
SCRIPT_EXT); pg_asprintf(&user_specification, "-U \"%s\" ", os_info.user);
pg_asprintf(analyze_script_file_name, "analyze_new_cluster.%s",
SCRIPT_EXT);
if ((script = fopen_priv(*analyze_script_file_name, "w")) == NULL) if ((script = fopen_priv(*analyze_script_file_name, "w")) == NULL)
pg_fatal("Could not open file \"%s\": %s\n", pg_fatal("Could not open file \"%s\": %s\n",
@ -597,10 +592,8 @@ create_script_for_old_cluster_deletion(char **deletion_script_file_name)
int tblnum; int tblnum;
char old_cluster_pgdata[MAXPGPATH]; char old_cluster_pgdata[MAXPGPATH];
*deletion_script_file_name = pg_malloc(MAXPGPATH); pg_asprintf(deletion_script_file_name, "delete_old_cluster.%s",
SCRIPT_EXT);
snprintf(*deletion_script_file_name, MAXPGPATH, "delete_old_cluster.%s",
SCRIPT_EXT);
/* /*
* Some users (oddly) create tablespaces inside the cluster data * Some users (oddly) create tablespaces inside the cluster data

@ -84,12 +84,9 @@ set_tablespace_directory_suffix(ClusterInfo *cluster)
else else
{ {
/* This cluster has a version-specific subdirectory */ /* This cluster has a version-specific subdirectory */
cluster->tablespace_suffix = pg_malloc(4 +
strlen(cluster->major_version_str) +
10 /* OIDCHARS */ + 1);
/* The leading slash is needed to start a new directory. */ /* The leading slash is needed to start a new directory. */
sprintf(cluster->tablespace_suffix, "/PG_%s_%d", cluster->major_version_str, pg_asprintf(&cluster->tablespace_suffix, "/PG_%s_%d",
cluster->controldata.cat_ver); cluster->major_version_str, cluster->controldata.cat_ver);
} }
} }

@ -276,10 +276,9 @@ pg_putenv(const char *var, const char *val)
if (val) if (val)
{ {
#ifndef WIN32 #ifndef WIN32
char *envstr = (char *) pg_malloc(strlen(var) + char *envstr;
strlen(val) + 2);
sprintf(envstr, "%s=%s", var, val); pg_asprintf(&envstr, "%s=%s", var, val);
putenv(envstr); putenv(envstr);
/* /*

@ -675,9 +675,9 @@ old_8_3_create_sequence_script(ClusterInfo *cluster)
int dbnum; int dbnum;
FILE *script = NULL; FILE *script = NULL;
bool found = false; bool found = false;
char *output_path = pg_malloc(MAXPGPATH); char *output_path;
snprintf(output_path, MAXPGPATH, "adjust_sequences.sql"); output_path = pg_strdup("adjust_sequences.sql");
prep_status("Creating script to adjust sequences"); prep_status("Creating script to adjust sequences");

@ -634,8 +634,7 @@ find_plan(char *ident, EPlan **eplan, int *nplans)
(*nplans) = i = 0; (*nplans) = i = 0;
} }
newp->ident = (char *) malloc(strlen(ident) + 1); newp->ident = strdup(ident);
strcpy(newp->ident, ident);
newp->nplans = 0; newp->nplans = 0;
newp->splan = NULL; newp->splan = NULL;
(*nplans)++; (*nplans)++;

@ -540,8 +540,7 @@ find_plan(char *ident, EPlan **eplan, int *nplans)
(*nplans) = i = 0; (*nplans) = i = 0;
} }
newp->ident = (char *) malloc(strlen(ident) + 1); newp->ident = strdup(ident);
strcpy(newp->ident, ident);
newp->splan = NULL; newp->splan = NULL;
(*nplans)++; (*nplans)++;

@ -249,9 +249,9 @@ AuxiliaryProcessMain(int argc, char *argv[])
case 'd': case 'd':
{ {
/* Turn on debugging for the bootstrap process. */ /* Turn on debugging for the bootstrap process. */
char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1); char *debugstr;
sprintf(debugstr, "debug%s", optarg); debugstr = psprintf("debug%s", optarg);
SetConfigOption("log_min_messages", debugstr, SetConfigOption("log_min_messages", debugstr,
PGC_POSTMASTER, PGC_S_ARGV); PGC_POSTMASTER, PGC_S_ARGV);
SetConfigOption("client_min_messages", debugstr, SetConfigOption("client_min_messages", debugstr,

@ -75,35 +75,23 @@ forkname_to_number(char *forkName)
char * char *
GetDatabasePath(Oid dbNode, Oid spcNode) GetDatabasePath(Oid dbNode, Oid spcNode)
{ {
int pathlen;
char *path;
if (spcNode == GLOBALTABLESPACE_OID) if (spcNode == GLOBALTABLESPACE_OID)
{ {
/* Shared system relations live in {datadir}/global */ /* Shared system relations live in {datadir}/global */
Assert(dbNode == 0); Assert(dbNode == 0);
pathlen = 6 + 1; return pstrdup("global");
path = (char *) palloc(pathlen);
snprintf(path, pathlen, "global");
} }
else if (spcNode == DEFAULTTABLESPACE_OID) else if (spcNode == DEFAULTTABLESPACE_OID)
{ {
/* The default tablespace is {datadir}/base */ /* The default tablespace is {datadir}/base */
pathlen = 5 + OIDCHARS + 1; return psprintf("base/%u", dbNode);
path = (char *) palloc(pathlen);
snprintf(path, pathlen, "base/%u",
dbNode);
} }
else else
{ {
/* All other tablespaces are accessed via symlinks */ /* All other tablespaces are accessed via symlinks */
pathlen = 9 + 1 + OIDCHARS + 1 + strlen(TABLESPACE_VERSION_DIRECTORY) + return psprintf("pg_tblspc/%u/%s/%u",
1 + OIDCHARS + 1; spcNode, TABLESPACE_VERSION_DIRECTORY, dbNode);
path = (char *) palloc(pathlen);
snprintf(path, pathlen, "pg_tblspc/%u/%s/%u",
spcNode, TABLESPACE_VERSION_DIRECTORY, dbNode);
} }
return path;
} }

@ -541,12 +541,11 @@ DropTableSpace(DropTableSpaceStmt *stmt)
static void static void
create_tablespace_directories(const char *location, const Oid tablespaceoid) create_tablespace_directories(const char *location, const Oid tablespaceoid)
{ {
char *linkloc = palloc(OIDCHARS + OIDCHARS + 1); char *linkloc;
char *location_with_version_dir = palloc(strlen(location) + 1 + char *location_with_version_dir;
strlen(TABLESPACE_VERSION_DIRECTORY) + 1);
sprintf(linkloc, "pg_tblspc/%u", tablespaceoid); linkloc = psprintf("pg_tblspc/%u", tablespaceoid);
sprintf(location_with_version_dir, "%s/%s", location, location_with_version_dir = psprintf("%s/%s", location,
TABLESPACE_VERSION_DIRECTORY); TABLESPACE_VERSION_DIRECTORY);
/* /*
@ -652,9 +651,7 @@ destroy_tablespace_directories(Oid tablespaceoid, bool redo)
char *subfile; char *subfile;
struct stat st; struct stat st;
linkloc_with_version_dir = palloc(9 + 1 + OIDCHARS + 1 + linkloc_with_version_dir = psprintf("pg_tblspc/%u/%s", tablespaceoid,
strlen(TABLESPACE_VERSION_DIRECTORY));
sprintf(linkloc_with_version_dir, "pg_tblspc/%u/%s", tablespaceoid,
TABLESPACE_VERSION_DIRECTORY); TABLESPACE_VERSION_DIRECTORY);
/* /*
@ -711,8 +708,7 @@ destroy_tablespace_directories(Oid tablespaceoid, bool redo)
strcmp(de->d_name, "..") == 0) strcmp(de->d_name, "..") == 0)
continue; continue;
subfile = palloc(strlen(linkloc_with_version_dir) + 1 + strlen(de->d_name) + 1); subfile = psprintf("%s/%s", linkloc_with_version_dir, de->d_name);
sprintf(subfile, "%s/%s", linkloc_with_version_dir, de->d_name);
/* This check is just to deliver a friendlier error message */ /* This check is just to deliver a friendlier error message */
if (!redo && !directory_is_empty(subfile)) if (!redo && !directory_is_empty(subfile))

@ -1015,17 +1015,15 @@ pg_GSS_recvauth(Port *port)
*/ */
if (getenv("KRB5_KTNAME") == NULL) if (getenv("KRB5_KTNAME") == NULL)
{ {
size_t kt_len = strlen(pg_krb_server_keyfile) + 14; char *kt_path;
char *kt_path = malloc(kt_len);
if (!kt_path) if (asprintf(&kt_path, "KRB5_KTNAME=%s", pg_krb_server_keyfile) < 0)
{ {
ereport(LOG, ereport(LOG,
(errcode(ERRCODE_OUT_OF_MEMORY), (errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"))); errmsg("out of memory")));
return STATUS_ERROR; return STATUS_ERROR;
} }
snprintf(kt_path, kt_len, "KRB5_KTNAME=%s", pg_krb_server_keyfile);
putenv(kt_path); putenv(kt_path);
} }
} }
@ -1488,8 +1486,7 @@ pg_SSPI_recvauth(Port *port)
char *namebuf; char *namebuf;
int retval; int retval;
namebuf = palloc(strlen(accountname) + strlen(domainname) + 2); namebuf = psprintf("%s@%s", accountname, domainname);
sprintf(namebuf, "%s@%s", accountname, domainname);
retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true); retval = check_usermap(port->hba->usermap, port->user_name, namebuf, true);
pfree(namebuf); pfree(namebuf);
return retval; return retval;
@ -2209,8 +2206,7 @@ CheckLDAPAuth(Port *port)
attributes[0] = port->hba->ldapsearchattribute ? port->hba->ldapsearchattribute : "uid"; attributes[0] = port->hba->ldapsearchattribute ? port->hba->ldapsearchattribute : "uid";
attributes[1] = NULL; attributes[1] = NULL;
filter = palloc(strlen(attributes[0]) + strlen(port->user_name) + 4); filter = psprintf("(%s=%s)",
sprintf(filter, "(%s=%s)",
attributes[0], attributes[0],
port->user_name); port->user_name);
@ -2299,17 +2295,10 @@ CheckLDAPAuth(Port *port)
} }
} }
else else
{ fulluser = psprintf("%s%s%s",
fulluser = palloc((port->hba->ldapprefix ? strlen(port->hba->ldapprefix) : 0) +
strlen(port->user_name) +
(port->hba->ldapsuffix ? strlen(port->hba->ldapsuffix) : 0) +
1);
sprintf(fulluser, "%s%s%s",
port->hba->ldapprefix ? port->hba->ldapprefix : "", port->hba->ldapprefix ? port->hba->ldapprefix : "",
port->user_name, port->user_name,
port->hba->ldapsuffix ? port->hba->ldapsuffix : ""); port->hba->ldapsuffix ? port->hba->ldapsuffix : "");
}
r = ldap_simple_bind_s(ldap, fulluser, passwd); r = ldap_simple_bind_s(ldap, fulluser, passwd);
ldap_unbind(ldap); ldap_unbind(ldap);

@ -1119,8 +1119,7 @@ SS_process_ctes(PlannerInfo *root)
root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id); root->cte_plan_ids = lappend_int(root->cte_plan_ids, splan->plan_id);
/* Label the subplan for EXPLAIN purposes */ /* Label the subplan for EXPLAIN purposes */
splan->plan_name = palloc(4 + strlen(cte->ctename) + 1); splan->plan_name = psprintf("CTE %s", cte->ctename);
sprintf(splan->plan_name, "CTE %s", cte->ctename);
/* Lastly, fill in the cost estimates for use later */ /* Lastly, fill in the cost estimates for use later */
cost_subplan(root, splan, plan); cost_subplan(root, splan, plan);

@ -1450,10 +1450,7 @@ set_rest_more: /* Generic SET syntaxes: */
var_name: ColId { $$ = $1; } var_name: ColId { $$ = $1; }
| var_name '.' ColId | var_name '.' ColId
{ { $$ = psprintf("%s.%s", $1, $3); }
$$ = palloc(strlen($1) + strlen($3) + 2);
sprintf($$, "%s.%s", $1, $3);
}
; ;
var_list: var_value { $$ = list_make1($1); } var_list: var_value { $$ = list_make1($1); }
@ -10327,15 +10324,7 @@ ConstCharacter: CharacterWithLength
CharacterWithLength: character '(' Iconst ')' opt_charset CharacterWithLength: character '(' Iconst ')' opt_charset
{ {
if (($5 != NULL) && (strcmp($5, "sql_text") != 0)) if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
{ $1 = psprintf("%s_%s", $1, $5);
char *type;
type = palloc(strlen($1) + 1 + strlen($5) + 1);
strcpy(type, $1);
strcat(type, "_");
strcat(type, $5);
$1 = type;
}
$$ = SystemTypeName($1); $$ = SystemTypeName($1);
$$->typmods = list_make1(makeIntConst($3, @3)); $$->typmods = list_make1(makeIntConst($3, @3));
@ -10346,15 +10335,7 @@ CharacterWithLength: character '(' Iconst ')' opt_charset
CharacterWithoutLength: character opt_charset CharacterWithoutLength: character opt_charset
{ {
if (($2 != NULL) && (strcmp($2, "sql_text") != 0)) if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
{ $1 = psprintf("%s_%s", $1, $2);
char *type;
type = palloc(strlen($1) + 1 + strlen($2) + 1);
strcpy(type, $1);
strcat(type, "_");
strcat(type, $2);
$1 = type;
}
$$ = SystemTypeName($1); $$ = SystemTypeName($1);
@ -13339,13 +13320,7 @@ doNegateFloat(Value *v)
if (*oldval == '-') if (*oldval == '-')
v->val.str = oldval+1; /* just strip the '-' */ v->val.str = oldval+1; /* just strip the '-' */
else else
{ v->val.str = psprintf("-%s", oldval);
char *newval = (char *) palloc(strlen(oldval) + 2);
*newval = '-';
strcpy(newval+1, oldval);
v->val.str = newval;
}
} }
static Node * static Node *

@ -1969,12 +1969,7 @@ retry1:
else else
{ {
/* Append '@' and dbname */ /* Append '@' and dbname */
char *db_user; port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
db_user = palloc(strlen(port->user_name) +
strlen(port->database_name) + 2);
sprintf(db_user, "%s@%s", port->user_name, port->database_name);
port->user_name = db_user;
} }
} }

@ -377,18 +377,16 @@ cash_out(PG_FUNCTION_ARGS)
* from the value. * from the value.
*---------- *----------
*/ */
result = palloc(strlen(bufptr) + strlen(csymbol) + strlen(signsymbol) + 4);
switch (sign_posn) switch (sign_posn)
{ {
case 0: case 0:
if (cs_precedes) if (cs_precedes)
sprintf(result, "(%s%s%s)", result = psprintf("(%s%s%s)",
csymbol, csymbol,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
bufptr); bufptr);
else else
sprintf(result, "(%s%s%s)", result = psprintf("(%s%s%s)",
bufptr, bufptr,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
csymbol); csymbol);
@ -396,14 +394,14 @@ cash_out(PG_FUNCTION_ARGS)
case 1: case 1:
default: default:
if (cs_precedes) if (cs_precedes)
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
signsymbol, signsymbol,
(sep_by_space == 2) ? " " : "", (sep_by_space == 2) ? " " : "",
csymbol, csymbol,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
bufptr); bufptr);
else else
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
signsymbol, signsymbol,
(sep_by_space == 2) ? " " : "", (sep_by_space == 2) ? " " : "",
bufptr, bufptr,
@ -412,14 +410,14 @@ cash_out(PG_FUNCTION_ARGS)
break; break;
case 2: case 2:
if (cs_precedes) if (cs_precedes)
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
csymbol, csymbol,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
bufptr, bufptr,
(sep_by_space == 2) ? " " : "", (sep_by_space == 2) ? " " : "",
signsymbol); signsymbol);
else else
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
bufptr, bufptr,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
csymbol, csymbol,
@ -428,14 +426,14 @@ cash_out(PG_FUNCTION_ARGS)
break; break;
case 3: case 3:
if (cs_precedes) if (cs_precedes)
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
signsymbol, signsymbol,
(sep_by_space == 2) ? " " : "", (sep_by_space == 2) ? " " : "",
csymbol, csymbol,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
bufptr); bufptr);
else else
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
bufptr, bufptr,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
signsymbol, signsymbol,
@ -444,14 +442,14 @@ cash_out(PG_FUNCTION_ARGS)
break; break;
case 4: case 4:
if (cs_precedes) if (cs_precedes)
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
csymbol, csymbol,
(sep_by_space == 2) ? " " : "", (sep_by_space == 2) ? " " : "",
signsymbol, signsymbol,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
bufptr); bufptr);
else else
sprintf(result, "%s%s%s%s%s", result = psprintf("%s%s%s%s%s",
bufptr, bufptr,
(sep_by_space == 1) ? " " : "", (sep_by_space == 1) ? " " : "",
csymbol, csymbol,

@ -627,18 +627,14 @@ pg_size_pretty_numeric(PG_FUNCTION_ARGS)
Numeric size = PG_GETARG_NUMERIC(0); Numeric size = PG_GETARG_NUMERIC(0);
Numeric limit, Numeric limit,
limit2; limit2;
char *buf, char *result;
*result;
limit = int64_to_numeric(10 * 1024); limit = int64_to_numeric(10 * 1024);
limit2 = int64_to_numeric(10 * 1024 * 2 - 1); limit2 = int64_to_numeric(10 * 1024 * 2 - 1);
if (numeric_is_less(size, limit)) if (numeric_is_less(size, limit))
{ {
buf = numeric_to_cstring(size); result = psprintf("%s bytes", numeric_to_cstring(size));
result = palloc(strlen(buf) + 7);
strcpy(result, buf);
strcat(result, " bytes");
} }
else else
{ {
@ -650,10 +646,7 @@ pg_size_pretty_numeric(PG_FUNCTION_ARGS)
{ {
/* size = (size + 1) / 2 */ /* size = (size + 1) / 2 */
size = numeric_plus_one_over_two(size); size = numeric_plus_one_over_two(size);
buf = numeric_to_cstring(size); result = psprintf("%s kB", numeric_to_cstring(size));
result = palloc(strlen(buf) + 4);
strcpy(result, buf);
strcat(result, " kB");
} }
else else
{ {
@ -663,10 +656,7 @@ pg_size_pretty_numeric(PG_FUNCTION_ARGS)
{ {
/* size = (size + 1) / 2 */ /* size = (size + 1) / 2 */
size = numeric_plus_one_over_two(size); size = numeric_plus_one_over_two(size);
buf = numeric_to_cstring(size); result = psprintf("%s MB", numeric_to_cstring(size));
result = palloc(strlen(buf) + 4);
strcpy(result, buf);
strcat(result, " MB");
} }
else else
{ {
@ -677,10 +667,7 @@ pg_size_pretty_numeric(PG_FUNCTION_ARGS)
{ {
/* size = (size + 1) / 2 */ /* size = (size + 1) / 2 */
size = numeric_plus_one_over_two(size); size = numeric_plus_one_over_two(size);
buf = numeric_to_cstring(size); result = psprintf("%s GB", numeric_to_cstring(size));
result = palloc(strlen(buf) + 4);
strcpy(result, buf);
strcat(result, " GB");
} }
else else
{ {
@ -688,10 +675,7 @@ pg_size_pretty_numeric(PG_FUNCTION_ARGS)
size = numeric_shift_right(size, 10); size = numeric_shift_right(size, 10);
/* size = (size + 1) / 2 */ /* size = (size + 1) / 2 */
size = numeric_plus_one_over_two(size); size = numeric_plus_one_over_two(size);
buf = numeric_to_cstring(size); result = psprintf("%s TB", numeric_to_cstring(size));
result = palloc(strlen(buf) + 4);
strcpy(result, buf);
strcat(result, " TB");
} }
} }
} }

@ -242,11 +242,6 @@ pg_tablespace_databases(PG_FUNCTION_ARGS)
fctx = palloc(sizeof(ts_db_fctx)); fctx = palloc(sizeof(ts_db_fctx));
/*
* size = tablespace dirname length + dir sep char + oid + terminator
*/
fctx->location = (char *) palloc(9 + 1 + OIDCHARS + 1 +
strlen(TABLESPACE_VERSION_DIRECTORY) + 1);
if (tablespaceOid == GLOBALTABLESPACE_OID) if (tablespaceOid == GLOBALTABLESPACE_OID)
{ {
fctx->dirdesc = NULL; fctx->dirdesc = NULL;
@ -256,9 +251,9 @@ pg_tablespace_databases(PG_FUNCTION_ARGS)
else else
{ {
if (tablespaceOid == DEFAULTTABLESPACE_OID) if (tablespaceOid == DEFAULTTABLESPACE_OID)
sprintf(fctx->location, "base"); fctx->location = psprintf("base");
else else
sprintf(fctx->location, "pg_tblspc/%u/%s", tablespaceOid, fctx->location = psprintf("pg_tblspc/%u/%s", tablespaceOid,
TABLESPACE_VERSION_DIRECTORY); TABLESPACE_VERSION_DIRECTORY);
fctx->dirdesc = AllocateDir(fctx->location); fctx->dirdesc = AllocateDir(fctx->location);
@ -297,9 +292,7 @@ pg_tablespace_databases(PG_FUNCTION_ARGS)
/* if database subdir is empty, don't report tablespace as used */ /* if database subdir is empty, don't report tablespace as used */
/* size = path length + dir sep char + file name + terminator */ subdir = psprintf("%s/%s", fctx->location, de->d_name);
subdir = palloc(strlen(fctx->location) + 1 + strlen(de->d_name) + 1);
sprintf(subdir, "%s/%s", fctx->location, de->d_name);
dirdesc = AllocateDir(subdir); dirdesc = AllocateDir(subdir);
while ((de = ReadDir(dirdesc, subdir)) != NULL) while ((de = ReadDir(dirdesc, subdir)) != NULL)
{ {

@ -503,9 +503,7 @@ expand_dynamic_library_name(const char *name)
pfree(full); pfree(full);
} }
new = palloc(strlen(name) + strlen(DLSUFFIX) + 1); new = psprintf("%s%s", name, DLSUFFIX);
strcpy(new, name);
strcat(new, DLSUFFIX);
if (!have_slash) if (!have_slash)
{ {
@ -554,7 +552,6 @@ static char *
substitute_libpath_macro(const char *name) substitute_libpath_macro(const char *name)
{ {
const char *sep_ptr; const char *sep_ptr;
char *ret;
AssertArg(name != NULL); AssertArg(name != NULL);
@ -572,12 +569,7 @@ substitute_libpath_macro(const char *name)
errmsg("invalid macro name in dynamic library path: %s", errmsg("invalid macro name in dynamic library path: %s",
name))); name)));
ret = palloc(strlen(pkglib_path) + strlen(sep_ptr) + 1); return psprintf("%s%s", pkglib_path, sep_ptr);
strcpy(ret, pkglib_path);
strcat(ret, sep_ptr);
return ret;
} }

@ -448,10 +448,7 @@ fetch_finfo_record(void *filehandle, char *funcname)
const Pg_finfo_record *inforec; const Pg_finfo_record *inforec;
static Pg_finfo_record default_inforec = {0}; static Pg_finfo_record default_inforec = {0};
/* Compute name of info func */ infofuncname = psprintf("pg_finfo_%s", funcname);
infofuncname = (char *) palloc(strlen(funcname) + 10);
strcpy(infofuncname, "pg_finfo_");
strcat(infofuncname, funcname);
/* Try to look up the info function */ /* Try to look up the info function */
infofunc = (PGFInfoFunction) lookup_external_function(filehandle, infofunc = (PGFInfoFunction) lookup_external_function(filehandle,

@ -165,12 +165,10 @@ make_absolute_path(const char *path)
} }
} }
new = malloc(strlen(buf) + strlen(path) + 2); if (asprintf(&new, "%s/%s", buf, path) < 0)
if (!new)
ereport(FATAL, ereport(FATAL,
(errcode(ERRCODE_OUT_OF_MEMORY), (errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory"))); errmsg("out of memory")));
sprintf(new, "%s/%s", buf, path);
free(buf); free(buf);
} }
else else
@ -1286,9 +1284,7 @@ load_libraries(const char *libraries, const char *gucname, bool restricted)
{ {
char *expanded; char *expanded;
expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1); expanded = psprintf("$libdir/plugins/%s", filename);
strcpy(expanded, "$libdir/plugins/");
strcat(expanded, filename);
pfree(filename); pfree(filename);
filename = expanded; filename = expanded;
} }

@ -7938,8 +7938,7 @@ GUCArrayAdd(ArrayType *array, const char *name, const char *value)
name = record->name; name = record->name;
/* build new item for array */ /* build new item for array */
newval = palloc(strlen(name) + 1 + strlen(value) + 1); newval = psprintf("%s=%s", name, value);
sprintf(newval, "%s=%s", name, value);
datum = CStringGetTextDatum(newval); datum = CStringGetTextDatum(newval);
if (array) if (array)

@ -852,3 +852,52 @@ pnstrdup(const char *in, Size len)
out[len] = '\0'; out[len] = '\0';
return out; return out;
} }
/*
* asprintf()-like functions around palloc, adapted from
* http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/pkgtools/libnbcompat/files/asprintf.c
*/
char *
psprintf(const char *format, ...)
{
va_list ap;
char *retval;
va_start(ap, format);
retval = pvsprintf(format, ap);
va_end(ap);
return retval;
}
char *
pvsprintf(const char *format, va_list ap)
{
char *buf, *new_buf;
size_t len;
int retval;
va_list ap2;
len = 128;
buf = palloc(len);
va_copy(ap2, ap);
retval = vsnprintf(buf, len, format, ap);
Assert(retval >= 0);
if (retval < len)
{
new_buf = repalloc(buf, retval + 1);
va_end(ap2);
return new_buf;
}
len = (size_t)retval + 1;
pfree(buf);
buf = palloc(len);
retval = vsnprintf(buf, len, format, ap2);
va_end(ap2);
Assert(retval == len - 1);
return buf;
}

@ -948,13 +948,10 @@ mkdatadir(const char *subdir)
{ {
char *path; char *path;
path = pg_malloc(strlen(pg_data) + 2 + if (subdir)
(subdir == NULL ? 0 : strlen(subdir))); pg_asprintf(&path, "%s/%s", pg_data, subdir);
if (subdir != NULL)
sprintf(path, "%s/%s", pg_data, subdir);
else else
strcpy(path, pg_data); path = pg_strdup(pg_data);
if (pg_mkdir_p(path, S_IRWXU) == 0) if (pg_mkdir_p(path, S_IRWXU) == 0)
return true; return true;
@ -972,8 +969,7 @@ mkdatadir(const char *subdir)
static void static void
set_input(char **dest, char *filename) set_input(char **dest, char *filename)
{ {
*dest = pg_malloc(strlen(share_path) + strlen(filename) + 2); pg_asprintf(dest, "%s/%s", share_path, filename);
sprintf(*dest, "%s/%s", share_path, filename);
} }
/* /*
@ -1027,15 +1023,9 @@ write_version_file(char *extrapath)
char *path; char *path;
if (extrapath == NULL) if (extrapath == NULL)
{ pg_asprintf(&path, "%s/PG_VERSION", pg_data);
path = pg_malloc(strlen(pg_data) + 12);
sprintf(path, "%s/PG_VERSION", pg_data);
}
else else
{ pg_asprintf(&path, "%s/%s/PG_VERSION", pg_data, extrapath);
path = pg_malloc(strlen(pg_data) + strlen(extrapath) + 13);
sprintf(path, "%s/%s/PG_VERSION", pg_data, extrapath);
}
if ((version_file = fopen(path, PG_BINARY_W)) == NULL) if ((version_file = fopen(path, PG_BINARY_W)) == NULL)
{ {
@ -1063,8 +1053,7 @@ set_null_conf(void)
FILE *conf_file; FILE *conf_file;
char *path; char *path;
path = pg_malloc(strlen(pg_data) + 17); pg_asprintf(&path, "%s/postgresql.conf", pg_data);
sprintf(path, "%s/postgresql.conf", pg_data);
conf_file = fopen(path, PG_BINARY_W); conf_file = fopen(path, PG_BINARY_W);
if (conf_file == NULL) if (conf_file == NULL)
{ {
@ -2961,8 +2950,7 @@ setup_pgdata(void)
* need quotes otherwise on Windows because paths there are most likely to * need quotes otherwise on Windows because paths there are most likely to
* have embedded spaces. * have embedded spaces.
*/ */
pgdata_set_env = pg_malloc(8 + strlen(pg_data)); pg_asprintf(&pgdata_set_env, "PGDATA=%s", pg_data);
sprintf(pgdata_set_env, "PGDATA=%s", pg_data);
putenv(pgdata_set_env); putenv(pgdata_set_env);
} }
@ -3356,8 +3344,7 @@ create_xlog_symlink(void)
} }
/* form name of the place where the symlink must go */ /* form name of the place where the symlink must go */
linkloc = (char *) pg_malloc(strlen(pg_data) + 8 + 1); pg_asprintf(&linkloc, "%s/pg_xlog", pg_data);
sprintf(linkloc, "%s/pg_xlog", pg_data);
#ifdef HAVE_SYMLINK #ifdef HAVE_SYMLINK
if (symlink(xlog_dir, linkloc) != 0) if (symlink(xlog_dir, linkloc) != 0)

@ -2045,12 +2045,11 @@ main(int argc, char **argv)
case 'D': case 'D':
{ {
char *pgdata_D; char *pgdata_D;
char *env_var = pg_malloc(strlen(optarg) + 8); char *env_var;
pgdata_D = pg_strdup(optarg); pgdata_D = pg_strdup(optarg);
canonicalize_path(pgdata_D); canonicalize_path(pgdata_D);
snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s", pg_asprintf(&env_var, "PGDATA=%s", pgdata_D);
pgdata_D);
putenv(env_var); putenv(env_var);
/* /*
@ -2058,10 +2057,7 @@ main(int argc, char **argv)
* variable but we do -D too for clearer postmaster * variable but we do -D too for clearer postmaster
* 'ps' display * 'ps' display
*/ */
pgdata_opt = pg_malloc(strlen(pgdata_D) + 7); pg_asprintf(&pgdata_opt, "-D \"%s\" ", pgdata_D);
snprintf(pgdata_opt, strlen(pgdata_D) + 7,
"-D \"%s\" ",
pgdata_D);
break; break;
} }
case 'l': case 'l':
@ -2102,11 +2098,7 @@ main(int argc, char **argv)
register_username = pg_strdup(optarg); register_username = pg_strdup(optarg);
else else
/* Prepend .\ for local accounts */ /* Prepend .\ for local accounts */
{ pg_asprintf(&register_username, ".\\%s", optarg);
register_username = pg_malloc(strlen(optarg) + 3);
strcpy(register_username, ".\\");
strcat(register_username, optarg);
}
break; break;
case 'w': case 'w':
do_wait = true; do_wait = true;

@ -487,10 +487,9 @@ cfopen_read(const char *path, const char *mode)
#ifdef HAVE_LIBZ #ifdef HAVE_LIBZ
if (fp == NULL) if (fp == NULL)
{ {
int fnamelen = strlen(path) + 4; char *fname;
char *fname = pg_malloc(fnamelen);
snprintf(fname, fnamelen, "%s%s", path, ".gz"); pg_asprintf(&fname, "%s.gz", path);
fp = cfopen(fname, mode, 1); fp = cfopen(fname, mode, 1);
free(fname); free(fname);
} }
@ -518,10 +517,9 @@ cfopen_write(const char *path, const char *mode, int compression)
else else
{ {
#ifdef HAVE_LIBZ #ifdef HAVE_LIBZ
int fnamelen = strlen(path) + 4; char *fname;
char *fname = pg_malloc(fnamelen);
snprintf(fname, fnamelen, "%s%s", path, ".gz"); pg_asprintf(&fname, "%s.gz", path);
fp = cfopen(fname, mode, 1); fp = cfopen(fname, mode, 1);
free(fname); free(fname);
#else #else

@ -10439,8 +10439,7 @@ convertOperatorReference(Archive *fout, const char *opr)
/* If not schema-qualified, don't need to add OPERATOR() */ /* If not schema-qualified, don't need to add OPERATOR() */
if (!sawdot) if (!sawdot)
return name; return name;
oname = pg_malloc(strlen(name) + 11); pg_asprintf(&oname, "OPERATOR(%s)", name);
sprintf(oname, "OPERATOR(%s)", name);
free(name); free(name);
return oname; return oname;
} }
@ -12754,8 +12753,7 @@ dumpTable(Archive *fout, TableInfo *tbinfo)
char *acltag; char *acltag;
attnamecopy = pg_strdup(fmtId(attname)); attnamecopy = pg_strdup(fmtId(attname));
acltag = pg_malloc(strlen(tbinfo->dobj.name) + strlen(attname) + 2); pg_asprintf(&acltag, "%s.%s", tbinfo->dobj.name, attname);
sprintf(acltag, "%s.%s", tbinfo->dobj.name, attname);
/* Column's GRANT type is always TABLE */ /* Column's GRANT type is always TABLE */
dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE", dumpACL(fout, tbinfo->dobj.catId, tbinfo->dobj.dumpId, "TABLE",
namecopy, attnamecopy, acltag, namecopy, attnamecopy, acltag,

@ -1186,10 +1186,9 @@ exec_command(const char *cmd,
else else
{ {
/* Set variable to the value of the next argument */ /* Set variable to the value of the next argument */
int len = strlen(envvar) + strlen(envval) + 1; char *newval;
char *newval = pg_malloc(len + 1);
snprintf(newval, len + 1, "%s=%s", envvar, envval); pg_asprintf(&newval, "%s=%s", envvar, envval);
putenv(newval); putenv(newval);
success = true; success = true;
@ -1550,9 +1549,7 @@ prompt_for_password(const char *username)
{ {
char *prompt_text; char *prompt_text;
prompt_text = pg_malloc(strlen(username) + 100); pg_asprintf(&prompt_text, _("Password for user %s: "), username);
snprintf(prompt_text, strlen(username) + 100,
_("Password for user %s: "), username);
result = simple_prompt(prompt_text, 100, false); result = simple_prompt(prompt_text, 100, false);
free(prompt_text); free(prompt_text);
} }
@ -1923,14 +1920,6 @@ editFile(const char *fname, int lineno)
} }
} }
/* Allocate sufficient memory for command line. */
if (lineno > 0)
sys = pg_malloc(strlen(editorName)
+ strlen(editor_lineno_arg) + 10 /* for integer */
+ 1 + strlen(fname) + 10 + 1);
else
sys = pg_malloc(strlen(editorName) + strlen(fname) + 10 + 1);
/* /*
* On Unix the EDITOR value should *not* be quoted, since it might include * On Unix the EDITOR value should *not* be quoted, since it might include
* switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it * switches, eg, EDITOR="pico -t"; it's up to the user to put quotes in it
@ -1940,18 +1929,18 @@ editFile(const char *fname, int lineno)
*/ */
#ifndef WIN32 #ifndef WIN32
if (lineno > 0) if (lineno > 0)
sprintf(sys, "exec %s %s%d '%s'", pg_asprintf(&sys, "exec %s %s%d '%s'",
editorName, editor_lineno_arg, lineno, fname); editorName, editor_lineno_arg, lineno, fname);
else else
sprintf(sys, "exec %s '%s'", pg_asprintf(&sys, "exec %s '%s'",
editorName, fname); editorName, fname);
#else #else
if (lineno > 0) if (lineno > 0)
sprintf(sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE, pg_asprintf(&sys, SYSTEMQUOTE "\"%s\" %s%d \"%s\"" SYSTEMQUOTE,
editorName, editor_lineno_arg, lineno, fname); editorName, editor_lineno_arg, lineno, fname);
else else
sprintf(sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE, pg_asprintf(&sys, SYSTEMQUOTE "\"%s\" \"%s\"" SYSTEMQUOTE,
editorName, fname); editorName, fname);
#endif #endif
result = system(sys); result = system(sys);
if (result == -1) if (result == -1)
@ -2644,14 +2633,11 @@ do_shell(const char *command)
if (shellName == NULL) if (shellName == NULL)
shellName = DEFAULT_SHELL; shellName = DEFAULT_SHELL;
sys = pg_malloc(strlen(shellName) + 16);
#ifndef WIN32
sprintf(sys,
/* See EDITOR handling comment for an explanation */ /* See EDITOR handling comment for an explanation */
"exec %s", shellName); #ifndef WIN32
pg_asprintf(&sys, "exec %s", shellName);
#else #else
/* See EDITOR handling comment for an explanation */ pg_asprintf(&sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
sprintf(sys, SYSTEMQUOTE "\"%s\"" SYSTEMQUOTE, shellName);
#endif #endif
result = system(sys); result = system(sys);
free(sys); free(sys);

@ -594,9 +594,7 @@ StoreQueryTuple(const PGresult *result)
char *value; char *value;
/* concate prefix and column name */ /* concate prefix and column name */
varname = pg_malloc(strlen(pset.gset_prefix) + strlen(colname) + 1); pg_asprintf(&varname, "%s%s", pset.gset_prefix, colname);
strcpy(varname, pset.gset_prefix);
strcat(varname, colname);
if (!PQgetisnull(result, 0, i)) if (!PQgetisnull(result, 0, i))
value = PQgetvalue(result, 0, i); value = PQgetvalue(result, 0, i);
@ -1687,10 +1685,7 @@ expand_tilde(char **filename)
{ {
char *newfn; char *newfn;
newfn = pg_malloc(strlen(home) + strlen(p) + 1); pg_asprintf(&newfn, "%s%s", home, p);
strcpy(newfn, home);
strcat(newfn, p);
free(fn); free(fn);
*filename = newfn; *filename = newfn;
} }

@ -79,9 +79,7 @@ xstrcat(char **var, const char *more)
{ {
char *newvar; char *newvar;
newvar = pg_malloc(strlen(*var) + strlen(more) + 1); pg_asprintf(&newvar, "%s%s", *var, more);
strcpy(newvar, *var);
strcat(newvar, more);
free(*var); free(*var);
*var = newvar; *var = newvar;
} }

@ -298,11 +298,7 @@ initializeInput(int flags)
if (histfile == NULL) if (histfile == NULL)
{ {
if (get_home_path(home)) if (get_home_path(home))
{ pg_asprintf(&psql_history, "%s/%s", home, PSQLHISTORY);
psql_history = pg_malloc(strlen(home) + 1 +
strlen(PSQLHISTORY) + 1);
snprintf(psql_history, MAXPGPATH, "%s/%s", home, PSQLHISTORY);
}
} }
else else
{ {

@ -200,12 +200,12 @@ do_lo_import(const char *filename_arg, const char *comment_arg)
char *cmdbuf; char *cmdbuf;
char *bufptr; char *bufptr;
size_t slen = strlen(comment_arg); size_t slen = strlen(comment_arg);
int rv;
cmdbuf = malloc(slen * 2 + 256); rv = asprintf(&cmdbuf, "COMMENT ON LARGE OBJECT %u IS '", loid);
if (!cmdbuf) if (rv < 0)
return fail_lo_xact("\\lo_import", own_transaction); return fail_lo_xact("\\lo_import", own_transaction);
sprintf(cmdbuf, "COMMENT ON LARGE OBJECT %u IS '", loid); bufptr = cmdbuf + rv;
bufptr = cmdbuf + strlen(cmdbuf);
bufptr += PQescapeStringConn(pset.db, bufptr, comment_arg, slen, NULL); bufptr += PQescapeStringConn(pset.db, bufptr, comment_arg, slen, NULL);
strcpy(bufptr, "'"); strcpy(bufptr, "'");

@ -182,12 +182,8 @@ main(int argc, char *argv[])
if (options.username == NULL) if (options.username == NULL)
password_prompt = pg_strdup(_("Password: ")); password_prompt = pg_strdup(_("Password: "));
else else
{ pg_asprintf(&password_prompt, _("Password for user %s: "),
password_prompt = pg_malloc(strlen(_("Password for user %s: ")) - 2 + options.username);
strlen(options.username) + 1);
sprintf(password_prompt, _("Password for user %s: "),
options.username);
}
if (pset.getPassword == TRI_YES) if (pset.getPassword == TRI_YES)
password = simple_prompt(password_prompt, 100, false); password = simple_prompt(password_prompt, 100, false);
@ -642,10 +638,8 @@ process_psqlrc_file(char *filename)
#define R_OK 4 #define R_OK 4
#endif #endif
psqlrc_minor = pg_malloc(strlen(filename) + 1 + strlen(PG_VERSION) + 1); pg_asprintf(&psqlrc_minor, "%s-%s", filename, PG_VERSION);
sprintf(psqlrc_minor, "%s-%s", filename, PG_VERSION); pg_asprintf(&psqlrc_major, "%s-%s", filename, PG_MAJORVERSION);
psqlrc_major = pg_malloc(strlen(filename) + 1 + strlen(PG_MAJORVERSION) + 1);
sprintf(psqlrc_major, "%s-%s", filename, PG_MAJORVERSION);
/* check for minor version first, then major, then no version */ /* check for minor version first, then major, then no version */
if (access(psqlrc_minor, R_OK) == 0) if (access(psqlrc_minor, R_OK) == 0)

@ -3822,7 +3822,6 @@ static char **
complete_from_variables(char *text, const char *prefix, const char *suffix) complete_from_variables(char *text, const char *prefix, const char *suffix)
{ {
char **matches; char **matches;
int overhead = strlen(prefix) + strlen(suffix) + 1;
char **varnames; char **varnames;
int nvars = 0; int nvars = 0;
int maxvars = 100; int maxvars = 100;
@ -3847,8 +3846,7 @@ complete_from_variables(char *text, const char *prefix, const char *suffix)
} }
} }
buffer = (char *) pg_malloc(strlen(ptr->name) + overhead); pg_asprintf(&buffer, "%s%s%s", prefix, ptr->name, suffix);
sprintf(buffer, "%s%s%s", prefix, ptr->name, suffix);
varnames[nvars++] = buffer; varnames[nvars++] = buffer;
} }

@ -93,6 +93,25 @@ pg_free(void *ptr)
free(ptr); free(ptr);
} }
int
pg_asprintf(char **ret, const char *format, ...)
{
va_list ap;
int rc;
va_start(ap, format);
rc = vasprintf(ret, format, ap);
va_end(ap);
if (rc < 0)
{
fprintf(stderr, _("out of memory\n"));
exit(EXIT_FAILURE);
}
return rc;
}
/* /*
* Frontend emulation of backend memory management functions. Useful for * Frontend emulation of backend memory management functions. Useful for
* programs that compile backend files. * programs that compile backend files.
@ -126,3 +145,23 @@ repalloc(void *pointer, Size size)
{ {
return pg_realloc(pointer, size); return pg_realloc(pointer, size);
} }
char *
psprintf(const char *format, ...)
{
va_list ap;
int rc;
char *ret;
va_start(ap, format);
rc = vasprintf(&ret, format, ap);
va_end(ap);
if (rc < 0)
{
fprintf(stderr, _("out of memory\n"));
exit(EXIT_FAILURE);
}
return ret;
}

@ -74,7 +74,6 @@ forkname_chars(const char *str, ForkNumber *fork)
char * char *
relpathbackend(RelFileNode rnode, BackendId backend, ForkNumber forknum) relpathbackend(RelFileNode rnode, BackendId backend, ForkNumber forknum)
{ {
int pathlen;
char *path; char *path;
if (rnode.spcNode == GLOBALTABLESPACE_OID) if (rnode.spcNode == GLOBALTABLESPACE_OID)
@ -82,41 +81,33 @@ relpathbackend(RelFileNode rnode, BackendId backend, ForkNumber forknum)
/* Shared system relations live in {datadir}/global */ /* Shared system relations live in {datadir}/global */
Assert(rnode.dbNode == 0); Assert(rnode.dbNode == 0);
Assert(backend == InvalidBackendId); Assert(backend == InvalidBackendId);
pathlen = 7 + OIDCHARS + 1 + FORKNAMECHARS + 1;
path = (char *) palloc(pathlen);
if (forknum != MAIN_FORKNUM) if (forknum != MAIN_FORKNUM)
snprintf(path, pathlen, "global/%u_%s", path = psprintf("global/%u_%s",
rnode.relNode, forkNames[forknum]); rnode.relNode, forkNames[forknum]);
else else
snprintf(path, pathlen, "global/%u", rnode.relNode); path = psprintf("global/%u", rnode.relNode);
} }
else if (rnode.spcNode == DEFAULTTABLESPACE_OID) else if (rnode.spcNode == DEFAULTTABLESPACE_OID)
{ {
/* The default tablespace is {datadir}/base */ /* The default tablespace is {datadir}/base */
if (backend == InvalidBackendId) if (backend == InvalidBackendId)
{ {
pathlen = 5 + OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1;
path = (char *) palloc(pathlen);
if (forknum != MAIN_FORKNUM) if (forknum != MAIN_FORKNUM)
snprintf(path, pathlen, "base/%u/%u_%s", path = psprintf("base/%u/%u_%s",
rnode.dbNode, rnode.relNode, rnode.dbNode, rnode.relNode,
forkNames[forknum]); forkNames[forknum]);
else else
snprintf(path, pathlen, "base/%u/%u", path = psprintf("base/%u/%u",
rnode.dbNode, rnode.relNode); rnode.dbNode, rnode.relNode);
} }
else else
{ {
/* OIDCHARS will suffice for an integer, too */
pathlen = 5 + OIDCHARS + 2 + OIDCHARS + 1 + OIDCHARS + 1
+ FORKNAMECHARS + 1;
path = (char *) palloc(pathlen);
if (forknum != MAIN_FORKNUM) if (forknum != MAIN_FORKNUM)
snprintf(path, pathlen, "base/%u/t%d_%u_%s", path = psprintf("base/%u/t%d_%u_%s",
rnode.dbNode, backend, rnode.relNode, rnode.dbNode, backend, rnode.relNode,
forkNames[forknum]); forkNames[forknum]);
else else
snprintf(path, pathlen, "base/%u/t%d_%u", path = psprintf("base/%u/t%d_%u",
rnode.dbNode, backend, rnode.relNode); rnode.dbNode, backend, rnode.relNode);
} }
} }
@ -125,34 +116,25 @@ relpathbackend(RelFileNode rnode, BackendId backend, ForkNumber forknum)
/* All other tablespaces are accessed via symlinks */ /* All other tablespaces are accessed via symlinks */
if (backend == InvalidBackendId) if (backend == InvalidBackendId)
{ {
pathlen = 9 + 1 + OIDCHARS + 1
+ strlen(TABLESPACE_VERSION_DIRECTORY) + 1 + OIDCHARS + 1
+ OIDCHARS + 1 + FORKNAMECHARS + 1;
path = (char *) palloc(pathlen);
if (forknum != MAIN_FORKNUM) if (forknum != MAIN_FORKNUM)
snprintf(path, pathlen, "pg_tblspc/%u/%s/%u/%u_%s", path = psprintf("pg_tblspc/%u/%s/%u/%u_%s",
rnode.spcNode, TABLESPACE_VERSION_DIRECTORY, rnode.spcNode, TABLESPACE_VERSION_DIRECTORY,
rnode.dbNode, rnode.relNode, rnode.dbNode, rnode.relNode,
forkNames[forknum]); forkNames[forknum]);
else else
snprintf(path, pathlen, "pg_tblspc/%u/%s/%u/%u", path = psprintf("pg_tblspc/%u/%s/%u/%u",
rnode.spcNode, TABLESPACE_VERSION_DIRECTORY, rnode.spcNode, TABLESPACE_VERSION_DIRECTORY,
rnode.dbNode, rnode.relNode); rnode.dbNode, rnode.relNode);
} }
else else
{ {
/* OIDCHARS will suffice for an integer, too */
pathlen = 9 + 1 + OIDCHARS + 1
+ strlen(TABLESPACE_VERSION_DIRECTORY) + 1 + OIDCHARS + 2
+ OIDCHARS + 1 + OIDCHARS + 1 + FORKNAMECHARS + 1;
path = (char *) palloc(pathlen);
if (forknum != MAIN_FORKNUM) if (forknum != MAIN_FORKNUM)
snprintf(path, pathlen, "pg_tblspc/%u/%s/%u/t%d_%u_%s", path = psprintf("pg_tblspc/%u/%s/%u/t%d_%u_%s",
rnode.spcNode, TABLESPACE_VERSION_DIRECTORY, rnode.spcNode, TABLESPACE_VERSION_DIRECTORY,
rnode.dbNode, backend, rnode.relNode, rnode.dbNode, backend, rnode.relNode,
forkNames[forknum]); forkNames[forknum]);
else else
snprintf(path, pathlen, "pg_tblspc/%u/%s/%u/t%d_%u", path = psprintf("pg_tblspc/%u/%s/%u/t%d_%u",
rnode.spcNode, TABLESPACE_VERSION_DIRECTORY, rnode.spcNode, TABLESPACE_VERSION_DIRECTORY,
rnode.dbNode, backend, rnode.relNode); rnode.dbNode, backend, rnode.relNode);
} }

@ -14,6 +14,7 @@ extern void *pg_malloc(size_t size);
extern void *pg_malloc0(size_t size); extern void *pg_malloc0(size_t size);
extern void *pg_realloc(void *pointer, size_t size); extern void *pg_realloc(void *pointer, size_t size);
extern void pg_free(void *pointer); extern void pg_free(void *pointer);
extern int pg_asprintf(char **ret, const char *format, ...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
#include "utils/palloc.h" #include "utils/palloc.h"

@ -87,6 +87,9 @@
/* Define to 1 if you have the `append_history' function. */ /* Define to 1 if you have the `append_history' function. */
#undef HAVE_APPEND_HISTORY #undef HAVE_APPEND_HISTORY
/* Define to 1 if you have the `asprintf' function. */
#undef HAVE_ASPRINTF
/* Define to 1 if you have the `cbrt' function. */ /* Define to 1 if you have the `cbrt' function. */
#undef HAVE_CBRT #undef HAVE_CBRT

@ -404,6 +404,11 @@ extern double rint(double x);
extern int inet_aton(const char *cp, struct in_addr * addr); extern int inet_aton(const char *cp, struct in_addr * addr);
#endif #endif
#ifndef HAVE_ASPRINTF
extern int asprintf(char **ret, const char *fmt, ...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
extern int vasprintf(char **ret, const char *fmt, va_list ap) __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 0)));
#endif
#if !HAVE_DECL_STRLCAT #if !HAVE_DECL_STRLCAT
extern size_t strlcat(char *dst, const char *src, size_t siz); extern size_t strlcat(char *dst, const char *src, size_t siz);
#endif #endif

@ -101,5 +101,7 @@ extern void *palloc(Size size);
extern void *palloc0(Size size); extern void *palloc0(Size size);
extern void pfree(void *pointer); extern void pfree(void *pointer);
extern void *repalloc(void *pointer, Size size); extern void *repalloc(void *pointer, Size size);
extern char *psprintf(const char *format, ...) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
extern char *pvsprintf(const char *format, va_list ap) __attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 0)));
#endif /* PALLOC_H */ #endif /* PALLOC_H */

@ -127,12 +127,9 @@ main(void)
{ {
for (j = 0; times[j]; j++) for (j = 0; times[j]; j++)
{ {
int length = strlen(dates[i]) char* t;
+ 1 if (asprintf(&t, "%s %s", dates[i], times[j]) < 0)
+ strlen(times[j]) abort();
+ 1;
char* t = malloc(length);
sprintf(t, "%s %s", dates[i], times[j]);
ts1 = PGTYPEStimestamp_from_asc(t, NULL); ts1 = PGTYPEStimestamp_from_asc(t, NULL);
text = PGTYPEStimestamp_to_asc(ts1); text = PGTYPEStimestamp_to_asc(ts1);
if (i != 19 || j != 3) /* timestamp as integer or double differ for this case */ if (i != 19 || j != 3) /* timestamp as integer or double differ for this case */

@ -92,12 +92,9 @@ main(void)
{ {
for (j = 0; times[j]; j++) for (j = 0; times[j]; j++)
{ {
int length = strlen(dates[i]) char* t;
+ 1 if (asprintf(&t, "%s %s", dates[i], times[j]) < 0)
+ strlen(times[j]) abort();
+ 1;
char* t = malloc(length);
sprintf(t, "%s %s", dates[i], times[j]);
ts1 = PGTYPEStimestamp_from_asc(t, NULL); ts1 = PGTYPEStimestamp_from_asc(t, NULL);
text = PGTYPEStimestamp_to_asc(ts1); text = PGTYPEStimestamp_to_asc(ts1);
if (i != 19 || j != 3) /* timestamp as integer or double differ for this case */ if (i != 19 || j != 3) /* timestamp as integer or double differ for this case */

@ -420,7 +420,6 @@ pg_GSS_startup(PGconn *conn)
{ {
OM_uint32 maj_stat, OM_uint32 maj_stat,
min_stat; min_stat;
int maxlen;
gss_buffer_desc temp_gbuf; gss_buffer_desc temp_gbuf;
if (!(conn->pghost && conn->pghost[0] != '\0')) if (!(conn->pghost && conn->pghost[0] != '\0'))
@ -441,10 +440,14 @@ pg_GSS_startup(PGconn *conn)
* Import service principal name so the proper ticket can be acquired by * Import service principal name so the proper ticket can be acquired by
* the GSSAPI system. * the GSSAPI system.
*/ */
maxlen = NI_MAXHOST + strlen(conn->krbsrvname) + 2; if (asprintf((char **)&temp_gbuf.value, "%s@%s",
temp_gbuf.value = (char *) malloc(maxlen); conn->krbsrvname, conn->pghost) < 0)
snprintf(temp_gbuf.value, maxlen, "%s@%s", {
conn->krbsrvname, conn->pghost); printfPQExpBuffer(&conn->errorMessage,
libpq_gettext("out of memory"));
return STATUS_ERROR;
}
temp_gbuf.length = strlen(temp_gbuf.value); temp_gbuf.length = strlen(temp_gbuf.value);
maj_stat = gss_import_name(&min_stat, &temp_gbuf, maj_stat = gss_import_name(&min_stat, &temp_gbuf,
@ -656,13 +659,11 @@ pg_SSPI_startup(PGconn *conn, int use_negotiate)
libpq_gettext("host name must be specified\n")); libpq_gettext("host name must be specified\n"));
return STATUS_ERROR; return STATUS_ERROR;
} }
conn->sspitarget = malloc(strlen(conn->krbsrvname) + strlen(conn->pghost) + 2); if (asprintf(&conn->sspitarget, "%s/%s", conn->krbsrvname, conn->pghost) < 0)
if (!conn->sspitarget)
{ {
printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n")); printfPQExpBuffer(&conn->errorMessage, libpq_gettext("out of memory\n"));
return STATUS_ERROR; return STATUS_ERROR;
} }
sprintf(conn->sspitarget, "%s/%s", conn->krbsrvname, conn->pghost);
/* /*
* Indicate that we're in SSPI authentication mode to make sure that * Indicate that we're in SSPI authentication mode to make sure that

@ -466,8 +466,7 @@ report_two_error_messages(Step * step1, Step * step2)
{ {
char *prefix; char *prefix;
prefix = malloc(strlen(step1->name) + strlen(step2->name) + 2); pg_asprintf(&prefix, "%s %s", step1->name, step2->name);
sprintf(prefix, "%s %s", step1->name, step2->name);
if (step1->errormsg) if (step1->errormsg)
{ {
@ -795,12 +794,9 @@ try_complete_step(Step * step, int flags)
PG_DIAG_MESSAGE_PRIMARY); PG_DIAG_MESSAGE_PRIMARY);
if (sev && msg) if (sev && msg)
{ pg_asprintf(&step->errormsg, "%s: %s", sev, msg);
step->errormsg = malloc(5 + strlen(sev) + strlen(msg));
sprintf(step->errormsg, "%s: %s", sev, msg);
}
else else
step->errormsg = strdup(PQresultErrorMessage(res)); step->errormsg = pg_strdup(PQresultErrorMessage(res));
} }
break; break;
default: default:

@ -654,9 +654,9 @@ get_expectfile(const char *testname, const char *file)
static void static void
doputenv(const char *var, const char *val) doputenv(const char *var, const char *val)
{ {
char *s = malloc(strlen(var) + strlen(val) + 2); char *s;
sprintf(s, "%s=%s", var, val); pg_asprintf(&s, "%s=%s", var, val);
putenv(s); putenv(s);
} }
@ -671,16 +671,11 @@ add_to_path(const char *pathname, char separator, const char *addval)
char *newval; char *newval;
if (!oldval || !oldval[0]) if (!oldval || !oldval[0])
{
/* no previous value */ /* no previous value */
newval = malloc(strlen(pathname) + strlen(addval) + 2); pg_asprintf(&newval, "%s=%s", pathname, addval);
sprintf(newval, "%s=%s", pathname, addval);
}
else else
{ pg_asprintf(&newval, "%s=%s%c%s", pathname, addval, separator, oldval);
newval = malloc(strlen(pathname) + strlen(addval) + strlen(oldval) + 3);
sprintf(newval, "%s=%s%c%s", pathname, addval, separator, oldval);
}
putenv(newval); putenv(newval);
} }
@ -747,8 +742,7 @@ initialize_environment(void)
if (!old_pgoptions) if (!old_pgoptions)
old_pgoptions = ""; old_pgoptions = "";
new_pgoptions = malloc(strlen(old_pgoptions) + strlen(my_pgoptions) + 12); pg_asprintf(&new_pgoptions, "PGOPTIONS=%s %s", old_pgoptions, my_pgoptions);
sprintf(new_pgoptions, "PGOPTIONS=%s %s", old_pgoptions, my_pgoptions);
putenv(new_pgoptions); putenv(new_pgoptions);
} }
@ -798,16 +792,13 @@ initialize_environment(void)
/* /*
* Adjust path variables to point into the temp-install tree * Adjust path variables to point into the temp-install tree
*/ */
tmp = malloc(strlen(temp_install) + 32 + strlen(bindir)); pg_asprintf(&tmp, "%s/install/%s", temp_install, bindir);
sprintf(tmp, "%s/install/%s", temp_install, bindir);
bindir = tmp; bindir = tmp;
tmp = malloc(strlen(temp_install) + 32 + strlen(libdir)); pg_asprintf(&tmp, "%s/install/%s", temp_install, libdir);
sprintf(tmp, "%s/install/%s", temp_install, libdir);
libdir = tmp; libdir = tmp;
tmp = malloc(strlen(temp_install) + 32 + strlen(datadir)); pg_asprintf(&tmp, "%s/install/%s", temp_install, datadir);
sprintf(tmp, "%s/install/%s", temp_install, datadir);
datadir = tmp; datadir = tmp;
/* psql will be installed into temp-install bindir */ /* psql will be installed into temp-install bindir */
@ -961,9 +952,9 @@ spawn_process(const char *cmdline)
* "exec" the command too. This saves two useless processes per * "exec" the command too. This saves two useless processes per
* parallel test case. * parallel test case.
*/ */
char *cmdline2 = malloc(strlen(cmdline) + 6); char *cmdline2;
sprintf(cmdline2, "exec %s", cmdline); pg_asprintf(&cmdline2, "exec %s", cmdline);
execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL); execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
fprintf(stderr, _("%s: could not exec \"%s\": %s\n"), fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
progname, shellprog, strerror(errno)); progname, shellprog, strerror(errno));
@ -1040,8 +1031,7 @@ spawn_process(const char *cmdline)
exit(2); exit(2);
} }
cmdline2 = malloc(strlen(cmdline) + 8); pg_asprintf(&cmdline2, "cmd /c %s", cmdline);
sprintf(cmdline2, "cmd /c %s", cmdline);
#ifndef __CYGWIN__ #ifndef __CYGWIN__
AddUserToTokenDacl(restrictedToken); AddUserToTokenDacl(restrictedToken);
@ -1862,8 +1852,7 @@ make_absolute_path(const char *in)
} }
} }
result = malloc(strlen(cwdbuf) + strlen(in) + 2); pg_asprintf(&result, "%s/%s", cwdbuf, in);
sprintf(result, "%s/%s", cwdbuf, in);
} }
canonicalize_path(result); canonicalize_path(result);

Loading…
Cancel
Save