Skip to content

Replace sprintf with snprintf #8567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/dbcrypt/CryptApplication.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class App
throw "setDbCryptCallback";

char s[256];
sprintf(s, "localhost:%s", dbName);
snprintf(s, sizeof(s), "localhost:%s", dbName);
att = p->attachDatabase(status, s, 0, NULL);
if (status->getState() & IStatus::STATE_ERRORS)
throw "attachDatabase";
Expand Down
12 changes: 6 additions & 6 deletions examples/empbuild/empbuild.epp
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ else
/* Create the database */

printf ("creating database %s\n", Db_name);
sprintf (cmd, "CREATE DATABASE \"%s\"", Db_name);
snprintf(cmd, sizeof(cmd), "CREATE DATABASE \"%s\"", Db_name);
gds_trans = 0;

EXEC SQL EXECUTE IMMEDIATE :cmd;
Expand All @@ -94,39 +94,39 @@ if (SQLCODE)
}

printf ("Turning forced writes off\n");
sprintf (cmd, "gfix -write async %s", Db_name);
snprintf(cmd, sizeof(cmd), "gfix -write async %s", Db_name);
if (system (cmd))
{
printf ("Couldn't turn forced writes off\n");
exit (FINI_ERROR);
}

printf ("Creating tables\n");
sprintf (cmd, "isql %s -q -i empddl.sql", Db_name);
snprintf(cmd, sizeof(cmd), "isql %s -q -i empddl.sql", Db_name);
if (system (cmd))
{
printf ("Couldn't create tables \n");
exit (FINI_ERROR);
}

printf ("Turning off indices and triggers \n");
sprintf (cmd, "isql %s -i indexoff.sql", Db_name);
snprintf(cmd, sizeof(cmd), "isql %s -i indexoff.sql", Db_name);
if (system (cmd))
{
printf ("Couldn't turn off indices and triggers \n");
exit (FINI_ERROR);
}

printf ("Loading column data\n");
sprintf (cmd, "isql %s -i empdml.sql", Db_name);
snprintf(cmd, sizeof(cmd), "isql %s -i empdml.sql", Db_name);
if (system (cmd))
{
printf ("Couldn't load column data \n");
exit (FINI_ERROR);
}

printf ("Turning on indices and triggers \n");
sprintf (cmd, "isql %s -i indexon.sql", Db_name);
snprintf(cmd, sizeof(cmd), "isql %s -i indexon.sql", Db_name);
if (system (cmd))
{
printf ("Couldn't turn on indices and triggers \n");
Expand Down
2 changes: 1 addition & 1 deletion examples/extauth/TcWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ void check(ThrowStatusWrapper* status, int err, const char* text)
return;

char buf[256];
sprintf(buf, "%s: %s", text, error_to_string(err));
snprintf(buf, sizeof(buf), "%s: %s", text, error_to_string(err));
error(status, buf);
}

Expand Down
2 changes: 1 addition & 1 deletion examples/interfaces/04.print_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ int main()

default:
{
sprintf(s, "Unknown type %d for %s", t, meta->getField(&status, j));
snprintf(s, sizeof(s), "Unknown type %d for %s", t, meta->getField(&status, j));
throw s;
}
continue;
Expand Down
2 changes: 1 addition & 1 deletion examples/replication/fbSampleReplicator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ static const ISC_STATUS wrn[] = { isc_arg_gds, isc_random, isc_arg_string, (ISC_
ReplPlugin::ReplPlugin(IPluginConfig* conf)
{
char fn[100];
sprintf(fn, "session_%08x_%d.log", (unsigned)time(nullptr), logCounter++);
snprintf(fn, sizeof(fn), "session_%08x_%d.log", (unsigned)time(nullptr), logCounter++);
log = fopen(fn, "w");
WriteLog(log, "%p\tReplicatedSession constructed\n", this);
status = master->getStatus();
Expand Down
6 changes: 4 additions & 2 deletions examples/udr/Triggers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ FB_UDR_BEGIN_TRIGGER(replicate)
const char* name = triggerMetadata->getField(status, i);

strcat(buffer, " p");
sprintf(buffer + strlen(buffer), "%d type of column \"%s\".\"%s\" = ?", i, table, name);
const size_t buflen = strlen(buffer);
snprintf(buffer + buflen, sizeof(buffer) - buflen, "%d type of column \"%s\".\"%s\" = ?", i, table, name);
}

strcat(buffer,
Expand Down Expand Up @@ -175,7 +176,8 @@ FB_UDR_BEGIN_TRIGGER(replicate)
if (i > 0)
strcat(buffer, ", ");
strcat(buffer, ":p");
sprintf(buffer + strlen(buffer), "%d", i);
const size_t buflen = strlen(buffer);
snprintf(buffer + buflen, sizeof(buffer) - buflen, "%d", i);
}

strcat(buffer, ")\n on external data source '");
Expand Down
2 changes: 1 addition & 1 deletion src/burp/mvol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2119,7 +2119,7 @@ bool MVOL_split_hdr_write()
time_t seconds = time(NULL);

Firebird::string nm = tdgbl->toSystem(tdgbl->action->act_file->fil_name);
sprintf(buffer, "%s%.24s , file No. %4d of %4d, %-27.27s",
snprintf(buffer, sizeof(buffer), "%s%.24s , file No. %4d of %4d, %-27.27s",
HDR_SPLIT_TAG, ctime(&seconds), tdgbl->action->act_file->fil_seq,
tdgbl->action->act_total, nm.c_str());

Expand Down
8 changes: 4 additions & 4 deletions src/common/DecFloat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,8 @@ Decimal64 Decimal64::set(Int128 value, DecimalStatus decSt, int scale)
Decimal64 Decimal64::set(SINT64 value, DecimalStatus decSt, int scale)
{
{
char s[30]; // for sure enough for int64
sprintf(s, "%" SQUADFORMAT, value);
char s[30];
snprintf(s, sizeof(s), "%" SQUADFORMAT, value);
DecimalContext context(this, decSt);
decDoubleFromString(&dec, s, &context);
}
Expand All @@ -408,7 +408,7 @@ Decimal64 Decimal64::set(const char* value, DecimalStatus decSt)
Decimal64 Decimal64::set(double value, DecimalStatus decSt)
{
char s[50];
sprintf(s, "%.016e", value);
snprintf(s, sizeof(s), "%.016e", value);
DecimalContext context(this, decSt);
decDoubleFromString(&dec, s, &context);

Expand Down Expand Up @@ -685,7 +685,7 @@ Decimal128 Decimal128::set(const char* value, DecimalStatus decSt)
Decimal128 Decimal128::set(double value, DecimalStatus decSt)
{
char s[50];
sprintf(s, "%.016e", value);
snprintf(s, sizeof(s), "%.016e", value);
DecimalContext context(this, decSt);
decQuadFromString(&dec, s, &context);

Expand Down
6 changes: 3 additions & 3 deletions src/common/SimilarToRegex.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ namespace

if (c > 0)
{
sprintf(hex, "\\x00-\\x{%X}", (int) c - 1);
snprintf(hex, sizeof(hex), "\\x00-\\x{%X}", (int) c - 1);
re2PatternStr.append(hex);
}

Expand All @@ -510,7 +510,7 @@ namespace

if (c < maxChar)
{
sprintf(hex, "\\x{%X}-\\x{%X}", (int) c + 1, maxChar);
snprintf(hex, sizeof(hex), "\\x{%X}-\\x{%X}", (int) c + 1, maxChar);
re2PatternStr.append(hex);
}
}
Expand Down Expand Up @@ -572,7 +572,7 @@ namespace
else if (invalidInclude)
{
char str[30];
sprintf(str, "[^\\x{0}-\\x{%X}]", maxChar);
snprintf(str, sizeof(str), "[^\\x{0}-\\x{%X}]", maxChar);
re2PatternStr.append(str);
}
else
Expand Down
6 changes: 3 additions & 3 deletions src/common/StatusArg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -407,19 +407,19 @@ Num::Num(ISC_STATUS s) noexcept :
Int64::Int64(SINT64 val) noexcept :
Str(text)
{
sprintf(text, "%" SQUADFORMAT, val);
snprintf(text, sizeof(text), "%" SQUADFORMAT, val);
}

Int64::Int64(FB_UINT64 val) noexcept :
Str(text)
{
sprintf(text, "%" UQUADFORMAT, val);
snprintf(text, sizeof(text), "%" UQUADFORMAT, val);
}

Quad::Quad(const ISC_QUAD* quad) noexcept :
Str(text)
{
sprintf(text, "%x:%x", quad->gds_quad_high, quad->gds_quad_low);
snprintf(text, sizeof(text), "%x:%x", quad->gds_quad_high, quad->gds_quad_low);
}

Interpreted::Interpreted(const char* text) noexcept :
Expand Down
9 changes: 5 additions & 4 deletions src/common/classes/MsgPrint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const FB_SIZE_T MAX_STRING = 1 << 16;
// Generic functions.
int decode(uint64_t value, char* const rc, int radix = 10);
int decode(int64_t value, char* const rc, int radix = 10);
int decode(double value, char* rc);
int decode(double value, char* const rc, const size_t sz);
int adjust_prefix(int radix, int rev, bool is_neg, char* const rc);
int MsgPrintHelper(BaseStream& out_stream, const safe_cell& item);

Expand Down Expand Up @@ -131,9 +131,10 @@ int decode(int64_t value, char* const rc, int radix)

// Stub that relies on the printf family to write a double using "g"
// for smallest representation in text form.
int decode(double value, char* rc)
int decode(double value, char* const rc, const size_t sz)
{
return sprintf(rc, "%g", value);
int n = snprintf(rc, sz, "%g", value);
return std::min(n, static_cast<int>(sz - 1));
}


Expand Down Expand Up @@ -203,7 +204,7 @@ int MsgPrintHelper(BaseStream& out_stream, const safe_cell& item)
case safe_cell::at_double:
{
char s[DECODE_BUF_SIZE];
int n = decode(item.d_value, s);
int n = decode(item.d_value, s, sizeof(s));
return out_stream.write(s, n);
}
case safe_cell::at_str:
Expand Down
39 changes: 21 additions & 18 deletions src/common/cvt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2361,70 +2361,73 @@ static void datetime_to_text(const dsc* from, dsc* to, Callbacks* cb)

// Decode the timestamp into human readable terms

// yyyy-mm-dd hh:mm:ss.tttt +th:tm OR dd-MMM-yyyy hh:mm:ss.tttt +th:tm
TEXT temp[27 + TimeZoneUtil::MAX_LEN];
TEXT* p = temp;
string temp;
// yyyy-mm-dd hh:mm:ss.tttt [{ +th:tm | zone-name }] OR dd-MMM-yyyy hh:mm:ss.tttt [{ +th:tm | zone-name }]
temp.reserve(26 + TimeZoneUtil::MAX_LEN);

// Make a textual date for data types that include it

if (!from->isTime())
{
// yyyy-mm-dd OR dd-MMM-yyyy + nul-termination
char dateStr[11 + 1];
if (from->dsc_dtype == dtype_sql_date || !version4)
{
sprintf(p, "%4.4d-%2.2d-%2.2d",
snprintf(dateStr, sizeof(dateStr), "%4.4d-%2.2d-%2.2d",
times.tm_year + 1900, times.tm_mon + 1, times.tm_mday);
}
else
{
// Prior to BLR version 5 timestamps were converted to text in the dd-MMM-yyyy format
sprintf(p, "%2.2d-%.3s-%4.4d",
snprintf(dateStr, sizeof(dateStr), "%2.2d-%.3s-%4.4d",
times.tm_mday,
FB_LONG_MONTHS_UPPER[times.tm_mon], times.tm_year + 1900);
}

while (*p)
p++;
temp.append(dateStr);
}

// Put in a space to separate date & time components

if (from->isTimeStamp() && !version4)
*p++ = ' ';
temp.append(" ");

// Add the time part for data types that include it

if (from->dsc_dtype != dtype_sql_date)
{
// hh:mm:ss.tttt + nul-termination
char timeStr[13 + 1];
if (from->isTime() || !version4)
{
sprintf(p, "%2.2d:%2.2d:%2.2d.%4.4d",
snprintf(timeStr, sizeof(timeStr), "%2.2d:%2.2d:%2.2d.%4.4d",
times.tm_hour, times.tm_min, times.tm_sec, fractions);
}
else if (times.tm_hour || times.tm_min || times.tm_sec || fractions)
{
// Timestamp formating prior to BLR Version 5 is slightly different
sprintf(p, " %d:%.2d:%.2d.%.4d",
snprintf(timeStr, sizeof(timeStr), " %d:%.2d:%.2d.%.4d",
times.tm_hour, times.tm_min, times.tm_sec, fractions);
}

while (*p)
p++;
temp.append(timeStr);
}

if (from->isDateTimeTz())
{
*p++ = ' ';
p += TimeZoneUtil::format(p, sizeof(temp) - (p - temp), timezone, !tzLookup);
temp.append(" ");
// [{ +th:tm | zone-name }] + nul-termination
char tzStr[TimeZoneUtil::MAX_LEN + 1];
TimeZoneUtil::format(tzStr, sizeof(tzStr), timezone, !tzLookup);
temp.append(tzStr);
}

// Move the text version of the date/time value into the destination

dsc desc;
MOVE_CLEAR(&desc, sizeof(desc));
desc.dsc_address = (UCHAR*) temp;
desc.dsc_address = (UCHAR*) temp.c_str();
desc.dsc_dtype = dtype_text;
desc.dsc_ttype() = ttype_ascii;
desc.dsc_length = (p - temp);
desc.dsc_length = static_cast<USHORT>(temp.length());

if (from->isTimeStamp() && version4)
{
Expand Down
Loading
Loading