Replace sprintf with snprintf in all of Trick source. #1384 (#1392)

* Replace sprintf with snprintf in all of Trick source. #1384

* Don't add -Werror for MacOS because of deprecated sprintf warnings which we cant get rid of because SWIG. #1384

* Fixed an unbalanced parenthesis in S_overrides.mk. #1384
This commit is contained in:
jmpenn 2022-11-15 15:00:05 -06:00 committed by GitHub
parent 265513684a
commit 2a03ff5cf4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
72 changed files with 303 additions and 277 deletions

View File

@ -148,7 +148,7 @@ void TimeSession::sendMessage() {
int month = theTime->tm_mon + 1; int month = theTime->tm_mon + 1;
int year = theTime->tm_year + 1900; int year = theTime->tm_year + 1900;
sprintf(message, "Time: %02d:%02d:%02d Date: %02d/%02d/%d\n", hours, minutes, seconds, month, day, year); snprintf(message, sizeof(message), "Time: %02d:%02d:%02d Date: %02d/%02d/%d\n", hours, minutes, seconds, month, day, year);
mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, message, strlen(message)); mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, message, strlen(message));
} }

View File

@ -127,6 +127,9 @@ namespace Trick {
/** Buffer to hold formatted data ready for disk or other destination.\n */ /** Buffer to hold formatted data ready for disk or other destination.\n */
char * writer_buff ; /**< trick_io(**) trick_units(--) */ char * writer_buff ; /**< trick_io(**) trick_units(--) */
/** Size of the writer_buff. */
size_t writer_buff_size;
/** Little_endian or big_endian indicator.\n */ /** Little_endian or big_endian indicator.\n */
std::string byte_order; /**< trick_io(*io) trick_units(--) */ std::string byte_order; /**< trick_io(*io) trick_units(--) */

View File

@ -44,7 +44,7 @@ namespace Trick {
/** Data recording group for logging frame/overrun time.\n trick_units(--) */ /** Data recording group for logging frame/overrun time.\n trick_units(--) */
Trick::FrameDataRecordGroup * drg_frame; /**< trick_io(*io) trick_units(--) */ Trick::FrameDataRecordGroup * drg_frame; /**< trick_io(*io) trick_units(--) */
int plots_per_page; /**< trick_io(*io) trick_units(--) number of plots per page */ unsigned int plots_per_page; /**< trick_io(*io) trick_units(--) number of plots per page */
/** Cyclic jobs timeline to log, dimensioned as [num_threads][tl_max_samples].\n */ /** Cyclic jobs timeline to log, dimensioned as [num_threads][tl_max_samples].\n */
Trick::timeline_t **timeline; /**< trick_io(**) */ Trick::timeline_t **timeline; /**< trick_io(**) */
/** Non-Cyclic jobs timeline to log, dimensioned as [num_threads][tl_max_samples].\n */ /** Non-Cyclic jobs timeline to log, dimensioned as [num_threads][tl_max_samples].\n */

View File

@ -295,7 +295,7 @@ namespace Trick {
} }
int vs_format_ascii(Trick::VariableReference * var, char *value); int vs_format_ascii(Trick::VariableReference * var, char *value, size_t value_size);
Trick::VariableServer * var_server_get_var_server() ; Trick::VariableServer * var_server_get_var_server() ;

View File

@ -456,7 +456,7 @@ namespace Trick {
/** /**
@brief Called by write_data to write given variables to socket in var_ascii format. @brief Called by write_data to write given variables to socket in var_ascii format.
*/ */
int write_ascii_data(char * dest_buf, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type ); int write_ascii_data(char * dest_buf, size_t dest_buf_size, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type );
/** /**
@brief Construct a variable reference from the string in_name and handle error checking @brief Construct a variable reference from the string in_name and handle error checking

View File

@ -154,7 +154,7 @@ int Trick::SegmentedExecutive::write_s_job_execution(FILE *fp) {
/* Get full path to S_job_execution */ /* Get full path to S_job_execution */
output_dir = command_line_args_get_output_dir() ; output_dir = command_line_args_get_output_dir() ;
sprintf(buf, "%s/S_job_execution", output_dir.c_str()); snprintf(buf, sizeof(buf), "%s/S_job_execution", output_dir.c_str());
/* Reopen the S_job_execution file. If it fails, it's not a fatal error, return 0. */ /* Reopen the S_job_execution file. If it fails, it's not a fatal error, return 0. */
if ((fp = fopen(buf, "a")) == NULL) { if ((fp = fopen(buf, "a")) == NULL) {

View File

@ -2,7 +2,14 @@ MODELS :=$(CURDIR)/models
# Warn about comment markers /* within comments and make them errors, causing # Warn about comment markers /* within comments and make them errors, causing
# the build to fail. # the build to fail.
TRICK_CXXFLAGS += -I$(MODELS) -Wcomment -Werror TRICK_CXXFLAGS += -I$(MODELS) -Wcomment
# We can't yet make warnings to be errors on MacOS, because
# MACOS deprecates and warns about sprintf. But SWIG
# still generates code containing sprintf..
ifneq ($(TRICK_HOST_TYPE), Darwin)
TRICK_CXXFLAGS += -Werror
endif
PATHS := $(MODELS)/many $(MODELS)/nested PATHS := $(MODELS)/many $(MODELS)/nested

View File

@ -21,13 +21,13 @@ int sched_amf(
if ( S->amf == 2 ) { if ( S->amf == 2 ) {
/* Things are in order */ /* Things are in order */
sprintf(test, "Test %d", i); snprintf(test, sizeof(test), "Test %d", i);
add_test_result("sched_amf: Things are in order", test, ""); add_test_result("sched_amf: Things are in order", test, "");
i++; i++;
S->amf = 1 ; S->amf = 1 ;
} else { } else {
/* Things are out of order */ /* Things are out of order */
sprintf(test, "Test %d", i); snprintf(test, sizeof(test), "Test %d", i);
add_test_result("sched_amf: Things are NOT in order", test, ". "); add_test_result("sched_amf: Things are NOT in order", test, ". ");
i++; i++;
S->amf = 3 ; S->amf = 3 ;

View File

@ -37,7 +37,7 @@ int VSTest::init() {
// default cycle rate // default cycle rate
cycle_rate = 0.01; cycle_rate = 0.01;
sprintf(msg,"trick.var_cycle(%.2f)\n", cycle_rate); snprintf(msg, sizeof(msg), "trick.var_cycle(%.2f)\n", cycle_rate);
vs_write(msg); vs_write(msg);
return (0); return (0);

View File

@ -39,7 +39,7 @@ int VSTest::testUnits() {
int result; int result;
// INVALID UNIT CHANGE // INVALID UNIT CHANGE
sprintf(msg,"trick.var_add(\"vsx.vst.c\")\ntrick.var_units(\"vsx.vst.c\",\"g\")\n"); snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.c\")\ntrick.var_units(\"vsx.vst.c\",\"g\")\n");
vs_write(msg); vs_write(msg);
std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl; std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl;
vs_read(); vs_read();
@ -47,21 +47,21 @@ int VSTest::testUnits() {
TRICK_EXPECT_EQ(result, 0, suite, "VariableInvalidUnits") TRICK_EXPECT_EQ(result, 0, suite, "VariableInvalidUnits")
// ADD UNITS // ADD UNITS
sprintf(msg,"trick.var_add(\"vsx.vst.e\",\"m\")\n"); snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.e\",\"m\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("0 -1234 -123456 {m}", got_read); result = strcmp_IgnoringWhiteSpace("0 -1234 -123456 {m}", got_read);
TRICK_EXPECT_EQ(result, 0, suite, "VariableAddUnits") TRICK_EXPECT_EQ(result, 0, suite, "VariableAddUnits")
// CHANGE UNITS // CHANGE UNITS
sprintf(msg,"trick.var_units(\"vsx.vst.e\",\"ft\")\n"); snprintf(msg, sizeof(msg), "trick.var_units(\"vsx.vst.e\",\"ft\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("0 -1234 -405039 {ft}", got_read); result = strcmp_IgnoringWhiteSpace("0 -1234 -405039 {ft}", got_read);
TRICK_EXPECT_EQ(result, 0, suite, "VariableChangeUnits") TRICK_EXPECT_EQ(result, 0, suite, "VariableChangeUnits")
// CLEAR VARIABLE SERVER // CLEAR VARIABLE SERVER
sprintf(msg,"trick.var_clear()\n"); snprintf(msg, sizeof(msg), "trick.var_clear()\n");
vs_write(msg); vs_write(msg);
} }
@ -71,7 +71,7 @@ int VSTest::testAddRemove() {
int result; int result;
// NO UNITS // NO UNITS
sprintf(msg,"trick.var_add(\"vsx.vst.c\")\n"); snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.c\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
std::cout << got_read << std::endl; std::cout << got_read << std::endl;
@ -83,14 +83,14 @@ int VSTest::testAddRemove() {
TRICK_EXPECT_EQ(result, 0, suite, "VariableAddCyclic") TRICK_EXPECT_EQ(result, 0, suite, "VariableAddCyclic")
// REMOVE SINGLE VARIABLE // REMOVE SINGLE VARIABLE
sprintf(msg,"trick.var_remove(\"vsx.vst.e\")\n"); snprintf(msg, sizeof(msg), "trick.var_remove(\"vsx.vst.e\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("0 -1234", got_read); result = strcmp_IgnoringWhiteSpace("0 -1234", got_read);
TRICK_EXPECT_EQ(result, 0, suite, "VariableRemove") TRICK_EXPECT_EQ(result, 0, suite, "VariableRemove")
// CLEAR VARIABLE SERVER // CLEAR VARIABLE SERVER
sprintf(msg,"trick.var_clear()\n"); snprintf(msg, sizeof(msg), "trick.var_clear()\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
TRICK_EXPECT_EQ(strcmp(got_read, ""), 0, suite, "VariableClear") TRICK_EXPECT_EQ(strcmp(got_read, ""), 0, suite, "VariableClear")
@ -104,7 +104,7 @@ int VSTest::testSendOnce() {
int result; int result;
// SEND ONCE // SEND ONCE
sprintf(msg,"trick.var_send_once(\"vsx.vst.e\")\n"); snprintf(msg, sizeof(msg), "trick.var_send_once(\"vsx.vst.e\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("5 -123456", got_read); result = strcmp_IgnoringWhiteSpace("5 -123456", got_read);
@ -112,14 +112,14 @@ int VSTest::testSendOnce() {
trick_test_add_parent( suite , "VariableSendOnce" , ""); trick_test_add_parent( suite , "VariableSendOnce" , "");
// SEND ONCE LIST // SEND ONCE LIST
sprintf(msg,"trick.var_send_once(\"vsx.vst.n[0], vsx.vst.n[1], vsx.vst.n[2],\", 3)\n"); snprintf(msg, sizeof(msg), "trick.var_send_once(\"vsx.vst.n[0], vsx.vst.n[1], vsx.vst.n[2],\", 3)\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("5 0 1 2", got_read); result = strcmp_IgnoringWhiteSpace("5 0 1 2", got_read);
TRICK_EXPECT_EQ(result, 0, suite, "VariableSendOnceList") TRICK_EXPECT_EQ(result, 0, suite, "VariableSendOnceList")
// SEND ONCE LIST - WRONG INDICES // SEND ONCE LIST - WRONG INDICES
sprintf(msg,"trick.var_send_once(\"vsx.vst.n[0], vsx.vst.n[1], vsx.vst.n[2],\", 4)\n"); snprintf(msg, sizeof(msg), "trick.var_send_once(\"vsx.vst.n[0], vsx.vst.n[1], vsx.vst.n[2],\", 4)\n");
vs_write(msg); vs_write(msg);
std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl; std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl;
vs_read(); vs_read();
@ -133,7 +133,7 @@ int VSTest::testExists() {
int result; int result;
// VARIABLE EXISTS // VARIABLE EXISTS
sprintf(msg,"trick.var_exists(\"vsx.vst.e\")\n"); snprintf(msg, sizeof(msg), "trick.var_exists(\"vsx.vst.e\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("1 1",got_read); result = strcmp_IgnoringWhiteSpace("1 1",got_read);
@ -141,14 +141,14 @@ int VSTest::testExists() {
trick_test_add_parent( suite , "VariableExists" , "3587464751"); trick_test_add_parent( suite , "VariableExists" , "3587464751");
// VARIABLE DOES NOT EXIST // VARIABLE DOES NOT EXIST
sprintf(msg,"trick.var_exists(\"vsx.vst.z\")\n"); snprintf(msg, sizeof(msg), "trick.var_exists(\"vsx.vst.z\")\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
std::cout << "Check variable doesn't exist: " << got_read << std::endl; std::cout << "Check variable doesn't exist: " << got_read << std::endl;
result = strcmp_IgnoringWhiteSpace("1 0",got_read); result = strcmp_IgnoringWhiteSpace("1 0",got_read);
TRICK_EXPECT_EQ(result, 0, suite, "VariableNotExists") TRICK_EXPECT_EQ(result, 0, suite, "VariableNotExists")
sprintf(msg,"trick.var_clear()\n"); snprintf(msg, sizeof(msg), "trick.var_clear()\n");
vs_write(msg); vs_write(msg);
return(0); return(0);
@ -159,13 +159,13 @@ int VSTest::testPause() {
char suite[] = "VariableServerTest"; char suite[] = "VariableServerTest";
int result; int result;
sprintf(msg,"trick.var_add(\"vsx.vst.f\")\n"); snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.f\")\n");
vs_write(msg); vs_write(msg);
sprintf(msg,"trick.var_add(\"vsx.vst.i\")\n"); snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.i\")\n");
vs_write(msg); vs_write(msg);
// PAUSE // PAUSE
sprintf(msg,"trick.var_pause()\n"); snprintf(msg, sizeof(msg), "trick.var_pause()\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
vs_read(); vs_read();
@ -173,7 +173,7 @@ int VSTest::testPause() {
trick_test_add_parent( suite , "VariablePause" , "964174074"); trick_test_add_parent( suite , "VariablePause" , "964174074");
// SEND // SEND
sprintf(msg,"trick.var_send()\n"); snprintf(msg, sizeof(msg), "trick.var_send()\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("0 123456 1234.5677", got_read); result = strcmp_IgnoringWhiteSpace("0 123456 1234.5677", got_read);
@ -185,7 +185,7 @@ int VSTest::testPause() {
trick_test_add_parent( suite , "VariableSendNoCyclic" , "67211805"); trick_test_add_parent( suite , "VariableSendNoCyclic" , "67211805");
// UNPAUSE // UNPAUSE
sprintf(msg,"trick.var_unpause()\n"); snprintf(msg, sizeof(msg), "trick.var_unpause()\n");
vs_write(msg); vs_write(msg);
vs_read(); vs_read();
result = strcmp_IgnoringWhiteSpace("0 123456 1234.5677", got_read); result = strcmp_IgnoringWhiteSpace("0 123456 1234.5677", got_read);
@ -197,7 +197,7 @@ int VSTest::testPause() {
TRICK_EXPECT_EQ(result, 0, suite, "VariableUnpauseCyclic") TRICK_EXPECT_EQ(result, 0, suite, "VariableUnpauseCyclic")
trick_test_add_parent( suite , "VariableUnpauseCyclic" , "964174074"); trick_test_add_parent( suite , "VariableUnpauseCyclic" , "964174074");
sprintf(msg,"trick.var_clear()\n"); snprintf(msg, sizeof(msg), "trick.var_clear()\n");
vs_write(msg); vs_write(msg);
return(0); return(0);

View File

@ -32,7 +32,7 @@ void TimeSession::sendMessage() {
int month = theTime->tm_mon + 1; int month = theTime->tm_mon + 1;
int year = theTime->tm_year + 1900; int year = theTime->tm_year + 1900;
sprintf(message, "Time: %02d:%02d:%02d Date: %02d/%02d/%d\n", hours, minutes, seconds, month, day, year); snprintf(message, sizeof(message), "Time: %02d:%02d:%02d Date: %02d/%02d/%d\n", hours, minutes, seconds, month, day, year);
mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, message, strlen(message)); mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, message, strlen(message));
} }
@ -53,3 +53,4 @@ WebSocketSession* makeTimeSession( struct mg_connection *nc ) {
std::cerr << "DEBUG: Creating new TimeSession." << std::endl; std::cerr << "DEBUG: Creating new TimeSession." << std::endl;
return new TimeSession(nc); return new TimeSession(nc);
} }

View File

@ -535,8 +535,9 @@ T getVar(Socket& socket, std::string varName) {
// Wrapper for sprintf use case bc im tired of dealing with std::string vs char* stuff // Wrapper for sprintf use case bc im tired of dealing with std::string vs char* stuff
std::string format(const std::string& formatString, int num) { std::string format(const std::string& formatString, int num) {
char *buf = (char *)malloc(formatString.size() + 10); size_t buf_len = formatString.size() + 10;
sprintf(buf, formatString.c_str(), num); char *buf = (char *)malloc(buf_len);
snprintf(buf, buf_len, formatString.c_str(), num);
return std::string(buf); return std::string(buf);
} }
@ -697,7 +698,7 @@ int main(int argc, char *argv[])
std::string templateString = "dyn.table.applyCueForce(%.3f, %.3f) \n"; std::string templateString = "dyn.table.applyCueForce(%.3f, %.3f) \n";
char buf[128]; char buf[128];
sprintf(buf, templateString.c_str(), mouseX, mouseY); snprintf(buf, sizeof(buf), templateString.c_str(), mouseX, mouseY);
cueRequest += std::string(buf); cueRequest += std::string(buf);
socket << cueRequest; socket << cueRequest;
return false; return false;
@ -804,7 +805,7 @@ int main(int argc, char *argv[])
char * templateString = "trick.var_add(\"dyn.table.balls[%d][0].pos._x\")\ntrick.var_add(\"dyn.table.balls[%d][0].pos._y\")\ntrick.var_add(\"dyn.table.balls[%d][0].inPlay\")\n"; char * templateString = "trick.var_add(\"dyn.table.balls[%d][0].pos._x\")\ntrick.var_add(\"dyn.table.balls[%d][0].pos._y\")\ntrick.var_add(\"dyn.table.balls[%d][0].inPlay\")\n";
for (int i = 0; i < numBalls; i++) { for (int i = 0; i < numBalls; i++) {
char buf[128]; char buf[128];
sprintf(buf, templateString, i, i, i); snprintf(buf, sizeof(buf), templateString, i, i, i);
positionRequest += std::string(buf); positionRequest += std::string(buf);
} }
socket << positionRequest; socket << positionRequest;

View File

@ -55,17 +55,15 @@ int sun_pred_fast_display(
char message[500]; char message[500];
message[0] = '\0'; message[0] = '\0';
sprintf(tmp_s,"%ls %0d:%0d:%02.f",S->label_UTC, S->utc.hour , S->utc.min , S->utc.sec ); snprintf(tmp_s, sizeof(tmp_s), "%ls %0d:%0d:%02.f",S->label_UTC, S->utc.hour , S->utc.min , S->utc.sec );
strcat(message,tmp_s); strcat(message,tmp_s);
// sprintf(tmp_s," %ls %.6f",S->label_JD, S->JD);
// strcat(message,tmp_s);
if ( S->label_Azimuth != NULL ) { if ( S->label_Azimuth != NULL ) {
sprintf(tmp_s," %ls %.3f%d",S->label_Azimuth, S->solar_azimuth, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " %ls %.3f%d",S->label_Azimuth, S->solar_azimuth, DEGREE_SIGN);
} else { } else {
sprintf(tmp_s," AZIMUTH %.3f%d", S->solar_azimuth, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " AZIMUTH %.3f%d", S->solar_azimuth, DEGREE_SIGN);
} }
strcat(message,tmp_s); strcat(message,tmp_s);
sprintf(tmp_s," %ls %.3f%d",S->label_Elevation, S->solar_elevation, DEGREE_SIGN); snprintf(tmp_s," sizeof(tmp_s), %ls %.3f%d",S->label_Elevation, S->solar_elevation, DEGREE_SIGN);
strcat(message,tmp_s); strcat(message,tmp_s);
send_hs(stdout,"%s\n",message); send_hs(stdout,"%s\n",message);

View File

@ -55,15 +55,15 @@ int sun_pred_slow_display(
char message[500]; char message[500];
message[0] = '\0'; message[0] = '\0';
sprintf(tmp_s,"%lc",POSITION_INDICATOR); snprintf(tmp_s, sizeof(tmp_s), "%lc",POSITION_INDICATOR);
strcat(message,tmp_s); strcat(message,tmp_s);
sprintf(tmp_s," %lc %5.2f%lc",GREEK_SMALL_LETTER_PHI, S->observer_latitude, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " %lc %5.2f%lc",GREEK_SMALL_LETTER_PHI, S->observer_latitude, DEGREE_SIGN);
strcat(message,tmp_s); strcat(message,tmp_s);
sprintf(tmp_s," L %5.2f%lc", S->observer_longitude, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " L %5.2f%lc", S->observer_longitude, DEGREE_SIGN);
strcat(message,tmp_s); strcat(message,tmp_s);
sprintf(tmp_s," %lc %5.2f%lc",GREEK_SMALL_LETTER_ALPHA, S->right_ascension, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " %lc %5.2f%lc",GREEK_SMALL_LETTER_ALPHA, S->right_ascension, DEGREE_SIGN);
strcat(message,tmp_s); strcat(message,tmp_s);
sprintf(tmp_s," %lc %5.2f%lc",GREEK_SMALL_LETTER_DELTA, S->declination, DEGREE_SIGN); snprintf(tmp_s, sizeof(tmp_s), " %lc %5.2f%lc",GREEK_SMALL_LETTER_DELTA, S->declination, DEGREE_SIGN);
strcat(message,tmp_s); strcat(message,tmp_s);
send_hs(stdout,"%s\n",message); send_hs(stdout,"%s\n",message);

View File

@ -150,8 +150,9 @@ char * almostRealPath( const char * in_path ) {
char * final_path = NULL ; char * final_path = NULL ;
resolved_path = realpath( dir , resolved_path) ; resolved_path = realpath( dir , resolved_path) ;
if ( resolved_path != NULL ) { if ( resolved_path != NULL ) {
final_path = (char *)malloc(strlen(resolved_path) + strlen(file) + 2) ; size_t final_path_len = strlen(resolved_path) + strlen(file) + 2;
sprintf(final_path,"%s/%s", resolved_path , file ) ; final_path = (char *)malloc(final_path_len) ;
snprintf(final_path, final_path_len, "%s/%s", resolved_path , file ) ;
free(resolved_path) ; free(resolved_path) ;
} }
free(file_copy_path) ; free(file_copy_path) ;

View File

@ -179,14 +179,14 @@ int main(int argc, char* argv[])
done = 0; done = 0;
while ( !done ) { while ( !done ) {
current_line.clear(); current_line.clear();
sprintf(buf, "%8s<Row>", ""); snprintf(buf, sizeof(buf), "%8s<Row>", "");
current_line.append(buf); current_line.append(buf);
for ( idx = 0; idx < ds_list.size(); idx++ ) { for ( idx = 0; idx < ds_list.size(); idx++ ) {
if ( ds_list[idx]->get( &t, &y) == 0 ) { if ( ds_list[idx]->get( &t, &y) == 0 ) {
done = 1; done = 1;
break; break;
} }
sprintf(buf, "<Col>%.15G</Col>", y); snprintf(buf, sizeof(buf), "<Col>%.15G</Col>", y);
current_line.append(buf); current_line.append(buf);
} }
current_line.append("</Row>"); current_line.append("</Row>");
@ -228,14 +228,14 @@ int main(int argc, char* argv[])
break; break;
} }
if ( idx != 0) { if ( idx != 0) {
sprintf(buf, "%s", delimiter.c_str()); snprintf(buf, sizeof(buf), "%s", delimiter.c_str());
current_line.append(buf); current_line.append(buf);
} }
if ( Format == FIX ) { if ( Format == FIX ) {
sprintf(buf, "%20.16g", y); snprintf(buf, sizeof(buf), "%20.16g", y);
current_line.append(buf); current_line.append(buf);
} else { } else {
sprintf(buf, "%.15G", y); snprintf(buf, sizeof(buf), "%.15G", y);
current_line.append(buf); current_line.append(buf);
} }
} }

View File

@ -32,7 +32,7 @@ fermi_view::fermi_view(Widget TopLevel) {
trick_home = getenv("TRICK_HOME"); trick_home = getenv("TRICK_HOME");
if (trick_home != NULL) { if (trick_home != NULL) {
sprintf( applresdir,"%s/trick_source/data_products/DPX/APPS/FXPLOT",trick_home); snprintf( applresdir,sizeof(applresdir), "%s/trick_source/data_products/DPX/APPS/FXPLOT",trick_home);
setenv("XAPPLRESDIR", applresdir, 0); setenv("XAPPLRESDIR", applresdir, 0);
} else { } else {
std::cerr << "ERROR: $TRICK_HOME is not set." << std::endl; std::cerr << "ERROR: $TRICK_HOME is not set." << std::endl;

View File

@ -204,7 +204,7 @@ void PageViewNode::pdf_file_cb(Widget w, XtPointer client_data, XtPointer call_d
page_view_node->generate_PS(tmp_file); page_view_node->generate_PS(tmp_file);
// Convert PS tmp file to PDF // Convert PS tmp file to PDF
sprintf(cmd, "ps2pdf %s %s", tmp_file, file_name); snprintf(cmd, sizeof(cmd), "ps2pdf %s %s", tmp_file, file_name);
system(cmd); system(cmd);
XtFree(file_name); XtFree(file_name);
@ -234,8 +234,9 @@ int PageViewNode::exists_program(const char *programName)
strptr = path; strptr = path;
while ((tokptr = strtok(strptr, ":")) != NULL) { while ((tokptr = strtok(strptr, ":")) != NULL) {
program = (char *) malloc(strlen(tokptr) + strlen(programName) + 2); size_t program_len = strlen(tokptr) + strlen(programName) + 2;
sprintf(program, "%s/%s", tokptr, programName); program = (char *) malloc( program_len);
snprintf(program, program_len, "%s/%s", tokptr, programName);
if (access(program, F_OK | X_OK) == 0) { if (access(program, F_OK | X_OK) == 0) {
free(program); free(program);
return (1); return (1);
@ -492,12 +493,12 @@ void PageViewNode::print() {
if (!strcmp(trick_print_cmd, "lpr")) { if (!strcmp(trick_print_cmd, "lpr")) {
if ((trick_printer_name == NULL) || (strlen(trick_printer_name) == 0)) { if ((trick_printer_name == NULL) || (strlen(trick_printer_name) == 0)) {
sprintf(system_cmd, "%s %s", trick_print_cmd, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s %s", trick_print_cmd, ps_file_name);
} else { } else {
sprintf(system_cmd, "%s -P %s %s", trick_print_cmd, trick_printer_name, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s -P %s %s", trick_print_cmd, trick_printer_name, ps_file_name);
} }
} else { } else {
sprintf(system_cmd, "%s %s", trick_print_cmd, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s %s", trick_print_cmd, ps_file_name);
} }
std::cout << "Printing with command: " << system_cmd << std::endl; std::cout << "Printing with command: " << system_cmd << std::endl;

View File

@ -129,18 +129,18 @@ static void print_plot_cb(Widget w, XtPointer client_data, XtPointer call_data)
if (!strcmp(trick_print_cmd, "lpr")) { if (!strcmp(trick_print_cmd, "lpr")) {
if ((trick_printer_name == NULL) || (strlen(trick_printer_name) == 0)) { if ((trick_printer_name == NULL) || (strlen(trick_printer_name) == 0)) {
sprintf(system_cmd, "%s %s", trick_print_cmd, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s %s", trick_print_cmd, ps_file_name);
} else { } else {
sprintf(system_cmd, "%s -P %s %s", trick_print_cmd, trick_printer_name, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s -P %s %s", trick_print_cmd, trick_printer_name, ps_file_name);
} }
} else { } else {
sprintf(system_cmd, "%s %s", trick_print_cmd, ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "%s %s", trick_print_cmd, ps_file_name);
} }
std::cout << "Printing with command: " << system_cmd << std::endl; std::cout << "Printing with command: " << system_cmd << std::endl;
sys_ret = system( system_cmd); sys_ret = system( system_cmd);
std::cout << " System call returned: " << sys_ret << std::endl; std::cout << " System call returned: " << sys_ret << std::endl;
sprintf(system_cmd, "rm %s", ps_file_name); snprintf(system_cmd, sizeof(system_cmd), "rm %s", ps_file_name);
system( system_cmd); system( system_cmd);
} }

View File

@ -61,9 +61,9 @@ void ProductViewNode::generate_PS(const char* file_name) {
for (ii=0 ; ii<n; ii++ ) { for (ii=0 ; ii<n; ii++ ) {
if (n > 1) { if (n > 1) {
sprintf(indexedFileName, "%s.%d.%d.ps", file_name_str.c_str(), dpIndex, ii+1); snprintf(indexedFileName, sizeof(indexedFileName), "%s.%d.%d.ps", file_name_str.c_str(), dpIndex, ii+1);
} else { } else {
sprintf(indexedFileName, "%s.%d.ps", file_name_str.c_str(), dpIndex); snprintf(indexedFileName, sizeof(indexedFileName), "%s.%d.ps", file_name_str.c_str(), dpIndex);
} }
page_node_list[ii]->generate_PS(indexedFileName); page_node_list[ii]->generate_PS(indexedFileName);
std::cout << "Generating " << indexedFileName << " ..." << std::endl; std::cout << "Generating " << indexedFileName << " ..." << std::endl;

View File

@ -301,7 +301,7 @@ TableViewNode::TableViewNode( Widget Toplevel, DPC_table* Table, int Xpos, int Y
} else { } else {
// Parse succeeded. // Parse succeeded.
char temp_s[32]; char temp_s[32];
sprintf(temp_s,"%%+%ds",width); snprintf(temp_s, sizeof(temp_s), "%%+%ds",width);
column_heading_format[colix] = strdup(temp_s); column_heading_format[colix] = strdup(temp_s);
column_data_format[colix] = strdup(user_format); column_data_format[colix] = strdup(user_format);
column_width[colix] = width; column_width[colix] = width;

View File

@ -307,27 +307,27 @@ static void layout_page (GPViewPageNode* gp_view_page_node ) {
// CALCULATE PLOT WIDTH // CALCULATE PLOT WIDTH
cell_width = 1.0 / n_horizontal_cells; cell_width = 1.0 / n_horizontal_cells;
sprintf(value_text, "%5.3f", cell_width); snprintf(value_text, sizeof(value_text), "%5.3f", cell_width);
gp_view_page_node->textbuf.subst("<PLOT_WIDTH>", value_text); gp_view_page_node->textbuf.subst("<PLOT_WIDTH>", value_text);
// CALCULATE PLOT HEIGHT // CALCULATE PLOT HEIGHT
cell_height = 1.0 / n_vertical_cells; cell_height = 1.0 / n_vertical_cells;
sprintf(value_text, "%5.3f", cell_height); snprintf(value_text, sizeof(value_text), "%5.3f", cell_height);
gp_view_page_node->textbuf.subst("<PLOT_HEIGHT>", value_text); gp_view_page_node->textbuf.subst("<PLOT_HEIGHT>", value_text);
for (plot_ix=0; plot_ix< number_of_plots; plot_ix++) { for (plot_ix=0; plot_ix< number_of_plots; plot_ix++) {
float x,y; float x,y;
char key_text[20]; char key_text[20];
sprintf(key_text, "<PLOT_ORIGIN_X_%d>", plot_ix); snprintf(key_text, sizeof(key_text), "<PLOT_ORIGIN_X_%d>", plot_ix);
x = (float)((plot_ix % n_horizontal_cells) * cell_width); x = (float)((plot_ix % n_horizontal_cells) * cell_width);
sprintf(value_text, "%5.3f", x); snprintf(value_text, sizeof(value_text), "%5.3f", x);
gp_view_page_node->textbuf.subst(key_text, value_text); gp_view_page_node->textbuf.subst(key_text, value_text);
sprintf(key_text, "<PLOT_ORIGIN_Y_%d>", plot_ix); snprintf(key_text, sizeof(key_text), "<PLOT_ORIGIN_Y_%d>", plot_ix);
y = (float)(1.0 - ((plot_ix / n_horizontal_cells) * cell_height + cell_height)); y = (float)(1.0 - ((plot_ix / n_horizontal_cells) * cell_height + cell_height));
sprintf(value_text, "%5.3f", y); snprintf(value_text, sizeof(value_text), "%5.3f", y);
gp_view_page_node->textbuf.subst(key_text, value_text); gp_view_page_node->textbuf.subst(key_text, value_text);
} }
} }

View File

@ -109,7 +109,7 @@ std::string DPCTest::parseDPCData(const char* name) {
for ( product_ix = 0; product_ix < n_product_files; product_ix++ ) { for ( product_ix = 0; product_ix < n_product_files; product_ix++ ) {
DPC_product *product; DPC_product *product;
char tmp [50]; char tmp [50];
sprintf(tmp, "../TEST_DATA/%s", session->product_file_list[product_ix]); snprintf(tmp, sizeof(tmp), "../TEST_DATA/%s", session->product_file_list[product_ix]);
const char *product_file_name = tmp; const char *product_file_name = tmp;
try { try {

View File

@ -345,7 +345,7 @@ TEST_F(DSTest, DataStream_Delta) {
const char* a = "sun_predictor.sun.solar_azimuth:../TEST_DATA/BUNCHORUNS/RUN1"; const char* a = "sun_predictor.sun.solar_azimuth:../TEST_DATA/BUNCHORUNS/RUN1";
const char* b = "sun_predictor.sun.solar_azimuth:../TEST_DATA/BUNCHORUNS/RUN2"; const char* b = "sun_predictor.sun.solar_azimuth:../TEST_DATA/BUNCHORUNS/RUN2";
sprintf(DeltaName, "delta(%s, %s)", a, b); snprintf(DeltaName, sizeof(DeltaName), "delta(%s, %s)", a, b);
data_stream_factory = new DataStreamFactory(); data_stream_factory = new DataStreamFactory();
testds = data_stream_factory->create(RUN_dir, DeltaName, "s_simtime"); testds = data_stream_factory->create(RUN_dir, DeltaName, "s_simtime");

View File

@ -19,7 +19,7 @@ char *eqperror(int code)
errorprintout = ( char* ) malloc ( 128 ) ; errorprintout = ( char* ) malloc ( 128 ) ;
sprintf(errorprintout,"\nError %d in eqparse.c:",code) ; snprintf(errorprintout, 128, "\nError %d in eqparse.c:",code) ;
switch (code){ switch (code){
case 1: case 1:
strcat(errorprintout,"\nSyntax Error: ) Expected") ; strcat(errorprintout,"\nSyntax Error: ) Expected") ;

View File

@ -57,7 +57,7 @@ stack fillno(stack1 * no, stack stk, double value)
tmp_no = revers_stk(tmp_no); tmp_no = revers_stk(tmp_no);
for (j = 0; j < i; j++) { for (j = 0; j < i; j++) {
tmp_no = pop(tmp_no, &ch); tmp_no = pop(tmp_no, &ch);
sprintf(num, "%s%c", num, ch); snprintf(num, sizeof(numstr), "%s%c", num, ch);
} }
x = atof(num); x = atof(num);
#ifdef DEBUG #ifdef DEBUG

View File

@ -61,8 +61,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir,
while ((dp = readdir(dirp)) != NULL) { while ((dp = readdir(dirp)) != NULL) {
len = strlen(dp->d_name); len = strlen(dp->d_name);
if ( !strcmp( &(dp->d_name[len - 3]) , ".h5")) { if ( !strcmp( &(dp->d_name[len - 3]) , ".h5")) {
full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2;
sprintf(full_path, "%s/%s" , runDir.c_str() , dp->d_name); full_path = (char*) malloc (full_path_len) ;
snprintf(full_path, full_path_len, "%s/%s" , runDir.c_str() , dp->d_name);
if ( HDF5LocateParam((const char*)full_path , paramName.c_str()) ) { if ( HDF5LocateParam((const char*)full_path , paramName.c_str()) ) {
closedir(dirp) ; closedir(dirp) ;
stream = new TrickHDF5(full_path , (char *)paramName.c_str() , (char *)timeName ) ; stream = new TrickHDF5(full_path , (char *)paramName.c_str() , (char *)timeName ) ;
@ -79,8 +80,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir,
while ((dp = readdir(dirp)) != NULL) { while ((dp = readdir(dirp)) != NULL) {
len = strlen(dp->d_name); len = strlen(dp->d_name);
if ( !strcmp( &(dp->d_name[len - 4]) , ".trk")) { if ( !strcmp( &(dp->d_name[len - 4]) , ".trk")) {
full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2;
sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); full_path = (char*) malloc( full_path_len) ;
snprintf(full_path, full_path_len, "%s/%s", runDir.c_str(), dp->d_name);
if ( TrickBinaryLocateParam((const char*)full_path , paramName.c_str()) ) { if ( TrickBinaryLocateParam((const char*)full_path , paramName.c_str()) ) {
closedir(dirp) ; closedir(dirp) ;
stream = new TrickBinary(full_path , (char *)paramName.c_str()) ; stream = new TrickBinary(full_path , (char *)paramName.c_str()) ;
@ -96,8 +98,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir,
while ((dp = readdir(dirp)) != NULL) { while ((dp = readdir(dirp)) != NULL) {
len = strlen(dp->d_name); len = strlen(dp->d_name);
if ( !strcmp( &(dp->d_name[len - 4]) , ".csv")) { if ( !strcmp( &(dp->d_name[len - 4]) , ".csv")) {
full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2;
sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); full_path = (char*) malloc( full_path_len) ;
snprintf(full_path, full_path_len, "%s/%s", runDir.c_str(), dp->d_name);
if ( CsvLocateParam(full_path , (char *)paramName.c_str()) ) { if ( CsvLocateParam(full_path , (char *)paramName.c_str()) ) {
closedir(dirp) ; closedir(dirp) ;
stream = new Csv(full_path , (char *)paramName.c_str()) ; stream = new Csv(full_path , (char *)paramName.c_str()) ;
@ -113,8 +116,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir,
while ((dp = readdir(dirp)) != NULL) { while ((dp = readdir(dirp)) != NULL) {
len = strlen(dp->d_name); len = strlen(dp->d_name);
if ( !strcmp( &(dp->d_name[len - 4]) , ".mat")) { if ( !strcmp( &(dp->d_name[len - 4]) , ".mat")) {
full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2;
sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); full_path = (char*) malloc ( full_path_len) ;
snprintf(full_path, full_path_len, "%s/%s", runDir.c_str(), dp->d_name);
if ( MatLabLocateParam(full_path , if ( MatLabLocateParam(full_path ,
(char *)paramName.c_str(), (char *)paramName.c_str(),
(char *)timeName ) ) { (char *)timeName ) ) {

View File

@ -18,7 +18,7 @@ ExternalProgram::ExternalProgram( const char* sharedLibName,
// Open up external plugin program // Open up external plugin program
progHandle_ = dlopen(sharedLibName, RTLD_LAZY); progHandle_ = dlopen(sharedLibName, RTLD_LAZY);
if (!progHandle_) { if (!progHandle_) {
sprintf(msg, "ERROR: Couldn't load shared program \"%s\" \n", snprintf(msg, sizeof(msg), "ERROR: Couldn't load shared program \"%s\" \n",
sharedLibName); sharedLibName);
fputs(msg, stderr); fputs(msg, stderr);
exit(1); exit(1);

View File

@ -39,7 +39,7 @@ void *dlsym(void *handle, char *funcname)
NSSymbol symbol; NSSymbol symbol;
int cb = strlen(funcname) + 2; int cb = strlen(funcname) + 2;
char *symname = (char *) alloca(cb); char *symname = (char *) alloca(cb);
sprintf(symname, "_%s", funcname); snprintf(symname, cb, "_%s", funcname);
dyn_error = NULL; dyn_error = NULL;
@ -47,7 +47,7 @@ void *dlsym(void *handle, char *funcname)
if (symbol) { if (symbol) {
return (void *) NSAddressOfSymbol(symbol); return (void *) NSAddressOfSymbol(symbol);
} else { } else {
sprintf(dyn_buf, "Symbol [%s] not found", symname); snprintf(dyn_buf, sizeof(dyn_buf), "Symbol [%s] not found", symname);
dyn_error = dyn_buf; dyn_error = dyn_buf;
return (void *) NULL; return (void *) NULL;
} }

View File

@ -375,18 +375,18 @@ int LogData::openCurrBinaryFile()
// Construct extension // Construct extension
if (currBinExtension_ < 10) { if (currBinExtension_ < 10) {
sprintf(extension, "00%d", currBinExtension_); snprintf(extension, sizeof(extension), "00%d", currBinExtension_);
} else if (currBinExtension_ < 100) { } else if (currBinExtension_ < 100) {
sprintf(extension, "0%d", currBinExtension_); snprintf(extension, sizeof(extension), "0%d", currBinExtension_);
} else { } else {
sprintf(extension, "%d", currBinExtension_); snprintf(extension, sizeof(extension), "%d", currBinExtension_);
} }
// Construct binary filename // Construct binary filename
len = strlen(binFilePath_) + strlen(binFileName_) + len = strlen(binFilePath_) + strlen(binFileName_) +
strlen(extension) + 3; strlen(extension) + 3;
file = new char[len]; file = new char[len];
sprintf(file, "%s/%s.%s", binFilePath_, binFileName_, extension); snprintf(file, len, "%s/%s.%s", binFilePath_, binFileName_, extension);
// Do sanity check on file // Do sanity check on file
if (access(file, F_OK | R_OK) == -1) { if (access(file, F_OK | R_OK) == -1) {
@ -454,11 +454,11 @@ int LogData::getNumRecords()
// Construct extension // Construct extension
if (ii < 10) { if (ii < 10) {
sprintf(extension, "00%d", ii); snprintf(extension, sizeof(extension), "00%d", ii);
} else if (ii < 100) { } else if (ii < 100) {
sprintf(extension, "0%d", ii); snprintf(extension, sizeof(extension), "0%d", ii);
} else { } else {
sprintf(extension, "%d", ii); snprintf(extension, sizeof(extension), "%d", ii);
} }
// Allocate & construct file name // Allocate & construct file name
@ -466,7 +466,7 @@ int LogData::getNumRecords()
len = strlen(binFilePath_) + strlen(binFileName_) + len = strlen(binFilePath_) + strlen(binFileName_) +
strlen(extension) + 3; strlen(extension) + 3;
file = new char[len]; file = new char[len];
sprintf(file, "%s/%s.%s", binFilePath_, snprintf(file, len, "%s/%s.%s", binFilePath_,
binFileName_, extension); binFileName_, extension);
fpTmp = fopen(file, "r"); fpTmp = fopen(file, "r");
@ -1487,7 +1487,7 @@ int LogGroup::getHeaders()
len = strlen(dp->d_name) + len = strlen(dp->d_name) +
strlen(pathToBinaryData_) + 2 ; strlen(pathToBinaryData_) + 2 ;
full_header_name = (char*) malloc ( len ) ; full_header_name = (char*) malloc ( len ) ;
sprintf(full_header_name, "%s/%s", snprintf(full_header_name, len, "%s/%s",
pathToBinaryData_, dp->d_name); pathToBinaryData_, dp->d_name);
if (!strncmp(dp->d_name, "log_", 4) && if (!strncmp(dp->d_name, "log_", 4) &&
is04BinaryHeader_(full_header_name)) { is04BinaryHeader_(full_header_name)) {

View File

@ -56,7 +56,7 @@ int LogGroup::parseLogHeaders()
headerName = new char[len]; headerName = new char[len];
// Full path of log header // Full path of log header
sprintf(headerName, "%s/%s", pathToBinaryData_, headers_[i]); snprintf(headerName, len, "%s/%s", pathToBinaryData_, headers_[i]);
// Open log header // Open log header
if ((fp_ = fopen(headerName, "r")) == NULL) { if ((fp_ = fopen(headerName, "r")) == NULL) {

View File

@ -228,12 +228,11 @@ static int getCompositeSubReference(
char* reference_name /* destination buffer of composite subreference */ char* reference_name /* destination buffer of composite subreference */
) { ) {
int j, k, m; int j, m;
long offset; long offset;
int my_index[9]; int my_index[9];
int ret; int ret;
int size, last_size; int size, last_size;
int temp_size;
char* rAddr = (char*)reference_address; char* rAddr = (char*)reference_address;
char* sAddr = (char*)structure_address; char* sAddr = (char*)structure_address;
@ -263,7 +262,7 @@ static int getCompositeSubReference(
if (referenceOffset == 0) { if (referenceOffset == 0) {
reference_name[0] = '\0' ; reference_name[0] = '\0' ;
} else if (referenceOffset > 0) { } else if (referenceOffset > 0) {
sprintf(reference_name, " + %ld" , referenceOffset); snprintf(reference_name, (size_t)256, " + %ld" , referenceOffset);
} else { } else {
return 1; // ERROR return 1; // ERROR
} }
@ -273,7 +272,7 @@ static int getCompositeSubReference(
/******************************************************************************/ /******************************************************************************/
/* We found a member corresponding to the reference address, so print it's name. */ /* We found a member corresponding to the reference address, so print it's name. */
sprintf(reference_name, ".%s", Ai->name); snprintf(reference_name, (size_t)256, ".%s", Ai->name);
/* If the referenced member variable is an intrinsic type */ /* If the referenced member variable is an intrinsic type */
if (Ai->type != TRICK_STRUCTURED) { if (Ai->type != TRICK_STRUCTURED) {
@ -310,7 +309,9 @@ static int getCompositeSubReference(
} }
for (j = 0; j < num_fixed_dims; j++) { for (j = 0; j < num_fixed_dims; j++) {
sprintf(&reference_name[strlen(reference_name)], "[%d]", my_index[j]); size_t len = strlen(reference_name);
size_t rem = (size_t)256 - len;
snprintf(&reference_name[len], rem, "[%d]", my_index[j]);
} }
return 0; return 0;
} }
@ -325,7 +326,9 @@ static int getCompositeSubReference(
ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset, (ATTRIBUTES *) Ai->attr, buf); ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset, (ATTRIBUTES *) Ai->attr, buf);
if (ret == 0) { if (ret == 0) {
sprintf(&reference_name[strlen(reference_name)],"%s", buf); size_t len = strlen(reference_name);
size_t rem = (size_t)256 - len;
snprintf(&reference_name[len], rem, "%s", buf);
} else { } else {
return 1; // ERROR. return 1; // ERROR.
} }
@ -354,7 +357,9 @@ static int getCompositeSubReference(
for (j = 0; j < Ai->num_index; j++) { for (j = 0; j < Ai->num_index; j++) {
sprintf(&reference_name[strlen(reference_name)], "[%d]", my_index[j]); size_t len = strlen(reference_name);
size_t rem = (size_t)256 - len;
snprintf(&reference_name[len], rem, "[%d]", my_index[j]);
} }
/* if left_type specifies the current member, stop here */ /* if left_type specifies the current member, stop here */
@ -379,7 +384,9 @@ static int getCompositeSubReference(
ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset + offset, (ATTRIBUTES *) Ai->attr, buf); ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset + offset, (ATTRIBUTES *) Ai->attr, buf);
if (ret == 0) { if (ret == 0) {
sprintf(&reference_name[strlen(reference_name)], "%s", buf); size_t len = strlen(reference_name);
size_t rem = (size_t)256 - len;
snprintf(&reference_name[len], rem, "%s", buf);
} else { } else {
return 1; // ERROR return 1; // ERROR
} }

View File

@ -348,8 +348,9 @@ units_string: NAME {
$$ = $1; $$ = $1;
} }
| NAME '.' NAME '.' { | NAME '.' NAME '.' {
$$ = (char*)malloc( strlen($1) + strlen($3) + 3 ); size_t m_size = strlen($1) + strlen($3) + 3;
sprintf($$, "%s.%s.", $1,$3); $$ = (char*)malloc(m_size);
snprintf($$, m_size, "%s.%s.", $1,$3);
free($1); free($1);
free($3); free($3);
} }
@ -358,23 +359,24 @@ units_string: NAME {
} }
| I_CON { | I_CON {
if ($1 == 1) { if ($1 == 1) {
$$ = (char*)malloc(2); size_t m_size = 2;
sprintf($$, "1"); $$ = (char*)malloc(m_size);
snprintf($$, m_size, "1");
} else { } else {
return (MM_INVALID_UNITS); return (MM_INVALID_UNITS);
} }
} }
| units_string '*' NAME { | units_string '*' NAME {
int len = strlen($1) + strlen($3); size_t m_size = strlen($1) + strlen($3) + 2;
$$ = (char*)malloc((size_t)len+2) ; $$ = (char*)malloc(m_size) ;
sprintf($$, "%s*%s",$1,$3); snprintf($$, m_size, "%s*%s",$1,$3);
free($1); free($1);
free($3); free($3);
} }
| units_string '/' NAME { | units_string '/' NAME {
int len = strlen($1) + strlen($3); size_t m_size = strlen($1) + strlen($3) + 2;
$$ = (char*)malloc((size_t)len+2) ; $$ = (char*)malloc(m_size) ;
sprintf($$, "%s/%s",$1,$3); snprintf($$, m_size, "%s/%s",$1,$3);
free($1); free($1);
free($3); free($3);
} }
@ -432,7 +434,7 @@ param: NAME {
$$.ref_type = REF_INVALID; $$.ref_type = REF_INVALID;
} }
} }
sprintf(temp , "%s[%d]" , $$.reference, vval_int(&$3)) ; snprintf(temp , sizeof(temp), "%s[%d]" , $$.reference, vval_int(&$3)) ;
$$.reference = (char*)realloc( $$.reference , strlen(temp) + 1); $$.reference = (char*)realloc( $$.reference , strlen(temp) + 1);
strcpy($$.reference , temp) ; strcpy($$.reference , temp) ;
@ -469,9 +471,9 @@ param: NAME {
$$.num_index_left = $$.attr->num_index; $$.num_index_left = $$.attr->num_index;
if ($2 == 1) { if ($2 == 1) {
sprintf(temp , "%s->%s" , $$.reference, $3) ; snprintf(temp ,sizeof(temp), "%s->%s" , $$.reference, $3) ;
} else { } else {
sprintf(temp , "%s.%s" , $$.reference, $3) ; snprintf(temp ,sizeof(temp), "%s.%s" , $$.reference, $3) ;
} }
} else { } else {

View File

@ -119,11 +119,10 @@ int Trick::CommandLineArguments::process_sim_args(int nargs , char **args) {
char *buf, *buf2; char *buf, *buf2;
size_t found ; size_t found ;
int ii ;
argc = nargs ; argc = nargs ;
argv = (char **)TMM_declare_var_1d("char *", argc) ; argv = (char **)TMM_declare_var_1d("char *", argc) ;
for ( ii = 0 ; ii < argc ; ii++ ) { for (int ii = 0 ; ii < argc ; ii++ ) {
argv[ii] = TMM_strdup(args[ii]) ; argv[ii] = TMM_strdup(args[ii]) ;
} }
@ -195,7 +194,7 @@ int Trick::CommandLineArguments::process_sim_args(int nargs , char **args) {
output_dir = run_dir ; output_dir = run_dir ;
for (ii = 1; ii < argc; ii++) { for (int ii = 1; ii < argc; ii++) {
if (!strncmp("-OO", argv[ii], (size_t) 3) || !strncmp("-O", argv[ii], (size_t) 2)) { if (!strncmp("-OO", argv[ii], (size_t) 3) || !strncmp("-O", argv[ii], (size_t) 2)) {
if (ii == ( argc - 1 )) { if (ii == ( argc - 1 )) {
std::cerr << "\nERROR: No directory specified after -O or -OO argument" << std::endl ; std::cerr << "\nERROR: No directory specified after -O or -OO argument" << std::endl ;
@ -245,7 +244,7 @@ int Trick::CommandLineArguments::output_dir_timestamped_on() {
date = time(NULL) ; date = time(NULL) ;
curr_time = localtime(&date) ; curr_time = localtime(&date) ;
sprintf(temp_str, "DATA_%4d_%02d_%02d_%02d_%02d_%02d", snprintf(temp_str, sizeof(temp_str), "DATA_%4d_%02d_%02d_%02d_%02d_%02d",
curr_time->tm_year + 1900 , curr_time->tm_mon + 1 , curr_time->tm_mday, curr_time->tm_year + 1900 , curr_time->tm_mon + 1 , curr_time->tm_mday,
curr_time->tm_hour , curr_time->tm_min , curr_time->tm_sec ); curr_time->tm_hour , curr_time->tm_min , curr_time->tm_sec );

View File

@ -56,7 +56,8 @@ int Trick::DRAscii::format_specific_init() {
} }
/* Calculate a "worst case" for space used for 1 record. */ /* Calculate a "worst case" for space used for 1 record. */
writer_buff = (char *)calloc(1 , record_size * rec_buffer.size()) ; writer_buff_size = record_size * rec_buffer.size();
writer_buff = (char *)calloc(1 , writer_buff_size) ;
/* This loop touches all of the memory locations in the allocation forcing the /* This loop touches all of the memory locations in the allocation forcing the
system to actually do the allocation */ system to actually do the allocation */
@ -182,28 +183,30 @@ int Trick::DRAscii::copy_data_ascii_item( Trick::DataRecordBuffer * DI, int item
address = DI->buffer + (item_num * DI->ref->attr->size) ; address = DI->buffer + (item_num * DI->ref->attr->size) ;
size_t writer_buf_spare = writer_buff + writer_buff_size - buf;
switch (DI->ref->attr->type) { switch (DI->ref->attr->type) {
case TRICK_CHARACTER: case TRICK_CHARACTER:
sprintf(buf, "%c", *((char *) address)); snprintf(buf, writer_buf_spare, "%c", *((char *) address));
break; break;
case TRICK_UNSIGNED_CHARACTER: case TRICK_UNSIGNED_CHARACTER:
#if ( __linux | __sgi ) #if ( __linux | __sgi )
case TRICK_BOOLEAN: case TRICK_BOOLEAN:
#endif #endif
sprintf(buf, "%u", *((unsigned char *) address)); snprintf(buf, writer_buf_spare, "%u", *((unsigned char *) address));
break; break;
case TRICK_STRING: case TRICK_STRING:
sprintf(buf, "%s", *((char **) address)); snprintf(buf, writer_buf_spare, "%s", *((char **) address));
break; break;
case TRICK_SHORT: case TRICK_SHORT:
sprintf(buf, "%d", *((short *) address)); snprintf(buf, writer_buf_spare, "%d", *((short *) address));
break; break;
case TRICK_UNSIGNED_SHORT: case TRICK_UNSIGNED_SHORT:
sprintf(buf, "%u", *((unsigned short *) address)); snprintf(buf, writer_buf_spare, "%u", *((unsigned short *) address));
break; break;
case TRICK_ENUMERATED: case TRICK_ENUMERATED:
@ -211,45 +214,45 @@ int Trick::DRAscii::copy_data_ascii_item( Trick::DataRecordBuffer * DI, int item
#if ( __sun | __APPLE__ ) #if ( __sun | __APPLE__ )
case TRICK_BOOLEAN: case TRICK_BOOLEAN:
#endif #endif
sprintf(buf, "%d", *((int *) address)); snprintf(buf, writer_buf_spare, "%d", *((int *) address));
break; break;
case TRICK_UNSIGNED_INTEGER: case TRICK_UNSIGNED_INTEGER:
sprintf(buf, "%u", *((unsigned int *) address)); snprintf(buf, writer_buf_spare, "%u", *((unsigned int *) address));
break; break;
case TRICK_LONG: case TRICK_LONG:
sprintf(buf, "%ld", *((long *) address)); snprintf(buf, writer_buf_spare, "%ld", *((long *) address));
break; break;
case TRICK_UNSIGNED_LONG: case TRICK_UNSIGNED_LONG:
sprintf(buf, "%lu", *((unsigned long *) address)); snprintf(buf, writer_buf_spare, "%lu", *((unsigned long *) address));
break; break;
case TRICK_FLOAT: case TRICK_FLOAT:
sprintf(buf, ascii_float_format.c_str() , *((float *) address)); snprintf(buf, writer_buf_spare, ascii_float_format.c_str() , *((float *) address));
break; break;
case TRICK_DOUBLE: case TRICK_DOUBLE:
sprintf(buf, ascii_double_format.c_str() , *((double *) address)); snprintf(buf, writer_buf_spare, ascii_double_format.c_str() , *((double *) address));
break; break;
case TRICK_BITFIELD: case TRICK_BITFIELD:
sbf = GET_BITFIELD(address, DI->ref->attr->size, DI->ref->attr->index[0].start, DI->ref->attr->index[0].size); sbf = GET_BITFIELD(address, DI->ref->attr->size, DI->ref->attr->index[0].start, DI->ref->attr->index[0].size);
sprintf(buf, "%d", sbf); snprintf(buf, writer_buf_spare, "%d", sbf);
break; break;
case TRICK_UNSIGNED_BITFIELD: case TRICK_UNSIGNED_BITFIELD:
bf = GET_UNSIGNED_BITFIELD(address, DI->ref->attr->size, DI->ref->attr->index[0].start, DI->ref->attr->index[0].size); bf = GET_UNSIGNED_BITFIELD(address, DI->ref->attr->size, DI->ref->attr->index[0].start, DI->ref->attr->index[0].size);
sprintf(buf, "%lu", bf); snprintf(buf, writer_buf_spare, "%lu", bf);
break; break;
case TRICK_LONG_LONG: case TRICK_LONG_LONG:
sprintf(buf, "%lld", *((long long *) address)); snprintf(buf, writer_buf_spare, "%lld", *((long long *) address));
break; break;
case TRICK_UNSIGNED_LONG_LONG: case TRICK_UNSIGNED_LONG_LONG:
sprintf(buf, "%llu", *((unsigned long long *) address)); snprintf(buf, writer_buf_spare, "%llu", *((unsigned long long *) address));
break; break;
default: default:
break; break;

View File

@ -449,28 +449,28 @@ int Trick::DataRecordGroup::checkpoint() {
void Trick::DataRecordGroup::clear_checkpoint_vars() { void Trick::DataRecordGroup::clear_checkpoint_vars() {
if ( variable_names ) { if ( variable_names ) {
for(int jj = 0; jj < num_variable_names; jj++) { for(unsigned int jj = 0; jj < num_variable_names; jj++) {
TMM_delete_var_a(variable_names[jj]); TMM_delete_var_a(variable_names[jj]);
} }
TMM_delete_var_a(variable_names) ; TMM_delete_var_a(variable_names) ;
} }
if ( variable_alias ) { if ( variable_alias ) {
for(int jj = 0; jj < num_variable_names; jj++) { for(unsigned int jj = 0; jj < num_variable_names; jj++) {
TMM_delete_var_a(variable_alias[jj]); TMM_delete_var_a(variable_alias[jj]);
} }
TMM_delete_var_a(variable_alias) ; TMM_delete_var_a(variable_alias) ;
} }
if ( change_variable_names ) { if ( change_variable_names ) {
for(int jj = 0; jj < num_change_variable_names; jj++) { for(unsigned int jj = 0; jj < num_change_variable_names; jj++) {
TMM_delete_var_a(change_variable_names[jj]); TMM_delete_var_a(change_variable_names[jj]);
} }
TMM_delete_var_a(change_variable_names) ; TMM_delete_var_a(change_variable_names) ;
} }
if ( change_variable_alias ) { if ( change_variable_alias ) {
for(int jj = 0; jj < num_change_variable_names; jj++) { for(unsigned int jj = 0; jj < num_change_variable_names; jj++) {
TMM_delete_var_a(change_variable_alias[jj]); TMM_delete_var_a(change_variable_alias[jj]);
} }
TMM_delete_var_a(change_variable_alias) ; TMM_delete_var_a(change_variable_alias) ;

View File

@ -71,15 +71,15 @@ void Trick::Executive::fpe_handler(siginfo_t * sip __attribute__((unused)) ) {
/* /*
Attempt to attach with debugger or print stack trace. Not a requirement. Attempt to attach with debugger or print stack trace. Not a requirement.
sprintf and system are not async signal safe, but we don't have anything to lose. snprintf and system are not async signal safe, but we don't have anything to lose.
*/ */
#if __linux #if __linux
char command[1024]; char command[1024];
if (attach_debugger == true) { if (attach_debugger == true) {
sprintf(command, "%s -silent /proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid()); snprintf(command, sizeof(command), "%s -silent /proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid());
system(command); system(command);
} else if (stack_trace == true ) { } else if (stack_trace == true ) {
sprintf(command, "%s -silent -batch -x ${TRICK_HOME}/bin/gdb_commands " snprintf(command, sizeof(command), "%s -silent -batch -x ${TRICK_HOME}/bin/gdb_commands "
"/proc/%d/exe %d | grep -A 20 \"signal handler\"", debugger_command.c_str(), getpid(), getpid()); "/proc/%d/exe %d | grep -A 20 \"signal handler\"", debugger_command.c_str(), getpid(), getpid());
system(command); system(command);
} }
@ -90,11 +90,11 @@ void Trick::Executive::fpe_handler(siginfo_t * sip __attribute__((unused)) ) {
if (_NSGetExecutablePath(path, &size) == 0 ) { if (_NSGetExecutablePath(path, &size) == 0 ) {
if (attach_debugger == true) { if (attach_debugger == true) {
write( 2 , "Attempting to attach debugger... standby.\n" , 41 ) ; write( 2 , "Attempting to attach debugger... standby.\n" , 41 ) ;
sprintf(command, "%s -silent %s %d", debugger_command.c_str(), path, getpid()); snprintf(command, sizeof(command), "%s -silent %s %d", debugger_command.c_str(), path, getpid());
system(command); system(command);
} else if (stack_trace == true ) { } else if (stack_trace == true ) {
write( 2 , "Attempting to generate stack trace... standby.\n" , 47 ) ; write( 2 , "Attempting to generate stack trace... standby.\n" , 47 ) ;
sprintf(command, "%s -batch -x ${TRICK_HOME}/bin/gdb_commands " snprintf(command, sizeof(command), "%s -batch -x ${TRICK_HOME}/bin/gdb_commands "
"%s %d", debugger_command.c_str(), path, getpid()); "%s %d", debugger_command.c_str(), path, getpid());
system(command); system(command);
} }

View File

@ -37,7 +37,7 @@ int Trick::Executive::process_sim_args() {
argv = command_line_args_get_argv() ; argv = command_line_args_get_argv() ;
/* Save off a usage statement for messages */ /* Save off a usage statement for messages */
sprintf(buf, "%s", "\n\n" snprintf(buf, sizeof(buf), "%s", "\n\n"
"USAGE: S_main_<host_cpu>.exe [option...]\n\n" "USAGE: S_main_<host_cpu>.exe [option...]\n\n"
" RUN_<name>/<input_file>\n" " RUN_<name>/<input_file>\n"
" Every Trick simulation needs an input file.\n" " Every Trick simulation needs an input file.\n"

View File

@ -62,10 +62,10 @@ void Trick::Executive::signal_handler(int sig) {
#if __linux #if __linux
char command[1024]; char command[1024];
if (attach_debugger == true) { if (attach_debugger == true) {
sprintf(command, "%s -silent /proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid()); snprintf(command, sizeof(command), "%s -silent /proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid());
system(command); system(command);
} else if (stack_trace == true ) { } else if (stack_trace == true ) {
sprintf(command, "%s -silent -batch -x ${TRICK_HOME}/share/trick/gdb_commands " snprintf(command, sizeof(command), "%s -silent -batch -x ${TRICK_HOME}/share/trick/gdb_commands "
"/proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid()); "/proc/%d/exe %d", debugger_command.c_str(), getpid(), getpid());
system(command); system(command);
} }

View File

@ -37,7 +37,7 @@ int Trick::Executive::write_s_job_execution(FILE *fp) {
/* Get full path to S_job_execution */ /* Get full path to S_job_execution */
output_dir = command_line_args_get_output_dir() ; output_dir = command_line_args_get_output_dir() ;
sprintf(buf, "%s/S_job_execution", output_dir.c_str()); snprintf(buf, sizeof(buf), "%s/S_job_execution", output_dir.c_str());
/* Create the output directory if it does not exist */ /* Create the output directory if it does not exist */
if (access(output_dir.c_str(), F_OK) != 0) { if (access(output_dir.c_str(), F_OK) != 0) {

View File

@ -31,7 +31,7 @@ int Trick::Executive::write_s_run_summary(FILE *fp) {
/* Get full path to S_run_summary */ /* Get full path to S_run_summary */
output_dir = command_line_args_get_output_dir() ; output_dir = command_line_args_get_output_dir() ;
sprintf(buf, "%s/S_run_summary", output_dir.c_str()); snprintf(buf, sizeof(buf), "%s/S_run_summary", output_dir.c_str());
/* Open the S_run_summary file. If it fails, it's not a fatal error, return 0. */ /* Open the S_run_summary file. If it fails, it's not a fatal error, return 0. */
if ((fp = fopen(buf, "w")) == NULL) { if ((fp = fopen(buf, "w")) == NULL) {

View File

@ -578,7 +578,7 @@ int Trick::FrameLog::shutdown() {
/** @li Manually create the log_timeline and log_timeline_init files from saved timeline data. */ /** @li Manually create the log_timeline and log_timeline_init files from saved timeline data. */
if (fp_time_main == NULL) { if (fp_time_main == NULL) {
sprintf(log_buff, "%s/log_timeline.csv", command_line_args_get_output_dir()); snprintf(log_buff, sizeof(log_buff), "%s/log_timeline.csv", command_line_args_get_output_dir());
if ((fp_time_main = fopen(log_buff, "w")) == NULL) { if ((fp_time_main = fopen(log_buff, "w")) == NULL) {
message_publish(MSG_ERROR, "Could not open log_timeline.csv file for Job Timeline Logging\n") ; message_publish(MSG_ERROR, "Could not open log_timeline.csv file for Job Timeline Logging\n") ;
exit(0); exit(0);
@ -590,7 +590,7 @@ int Trick::FrameLog::shutdown() {
} }
fprintf(fp_time_main, "\n"); fprintf(fp_time_main, "\n");
sprintf(log_buff, "%s/log_timeline_init.csv", command_line_args_get_output_dir()); snprintf(log_buff, sizeof(log_buff), "%s/log_timeline_init.csv", command_line_args_get_output_dir());
if ((fp_time_other = fopen(log_buff, "w")) == NULL) { if ((fp_time_other = fopen(log_buff, "w")) == NULL) {
message_publish(MSG_ERROR, "Could not open log_timeline_init.csv file for Job Timeline Logging\n") ; message_publish(MSG_ERROR, "Could not open log_timeline_init.csv file for Job Timeline Logging\n") ;
exit(0); exit(0);
@ -737,7 +737,7 @@ int Trick::FrameLog::create_DP_job_files() {
std::vector<std::string>::iterator job_iterator; std::vector<std::string>::iterator job_iterator;
FILE *fpx; FILE *fpx;
int pages, plots, total_plots, vcells, dot; unsigned int pages, plots, total_plots, vcells, dot;
char *bg_color; char *bg_color;
double time_scale; double time_scale;
std::string DP_buff; std::string DP_buff;
@ -830,7 +830,7 @@ int Trick::FrameLog::create_DP_job_files() {
if ( ii == 0 ) { if ( ii == 0 ) {
DP_buff = DP_dir + "/DP_rt_userjobs.xml"; DP_buff = DP_dir + "/DP_rt_userjobs.xml";
} else { } else {
sprintf(numstr, "%d", ii); snprintf(numstr, sizeof(numstr), "%d", ii);
DP_buff = DP_dir + "/DP_rt_userjobs_C" + numstr + ".xml"; DP_buff = DP_dir + "/DP_rt_userjobs_C" + numstr + ".xml";
} }

View File

@ -100,28 +100,28 @@ int Trick::MTV::send_event_data() {
int jj; int jj;
for (ii=0; ii < mtv_count; ii++) { for (ii=0; ii < mtv_count; ii++) {
sprintf(varname, "%s[%u][0].name", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].name", mtv_name,ii);
var_add(varname); var_add(varname);
sprintf(varname, "%s[%u][0].active", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].active", mtv_name,ii);
var_add(varname); var_add(varname);
sprintf(varname, "%s[%u][0].added", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].added", mtv_name,ii);
var_add(varname); var_add(varname);
sprintf(varname, "%s[%u][0].condition_count", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].condition_count", mtv_name,ii);
var_add(varname); var_add(varname);
sprintf(varname, "%s[%u][0].action_count", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].action_count", mtv_name,ii);
var_add(varname); var_add(varname);
sprintf(varname, "%s[%u][0].before_after", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].before_after", mtv_name,ii);
var_add(varname); var_add(varname);
for (jj=0; jj< mtv_list[ii]->condition_count; jj++) { for (jj=0; jj< mtv_list[ii]->condition_count; jj++) {
sprintf(varname, "%s[%u][0].cond[%d].comment", mtv_name,ii,jj); snprintf(varname, sizeof(varname), "%s[%u][0].cond[%d].comment", mtv_name,ii,jj);
var_add(varname); var_add(varname);
} }
for (jj=0; jj< mtv_list[ii]->action_count; jj++) { for (jj=0; jj< mtv_list[ii]->action_count; jj++) {
sprintf(varname, "%s[%u][0].act[%d].comment", mtv_name,ii,jj); snprintf(varname, sizeof(varname), "%s[%u][0].act[%d].comment", mtv_name,ii,jj);
var_add(varname); var_add(varname);
} }
if (mtv_list[ii]->get_before_after() > 0) { if (mtv_list[ii]->get_before_after() > 0) {
sprintf(varname, "%s[%u][0].target_name", mtv_name,ii); snprintf(varname, sizeof(varname), "%s[%u][0].target_name", mtv_name,ii);
var_add(varname); var_add(varname);
} }
} }

View File

@ -130,7 +130,7 @@ void Trick::MemoryManager::get_stl_dependencies_in_arrayed_class(
curr_dim_size = attr->index[curr_dim].size; curr_dim_size = attr->index[curr_dim].size;
for (ii = 0; ii < curr_dim_size; ii++) { for (ii = 0; ii < curr_dim_size; ii++) {
char index[16] ; char index[16] ;
sprintf(index, "[%d]", ii) ; snprintf(index, sizeof(index), "[%d]", ii) ;
if (curr_dim < attr->num_index - 1) { if (curr_dim < attr->num_index - 1) {
get_stl_dependencies_in_arrayed_class( name + index, address, attr, curr_dim + 1, offset * curr_dim_size + ii); get_stl_dependencies_in_arrayed_class( name + index, address, attr, curr_dim + 1, offset * curr_dim_size + ii);
} else { } else {
@ -183,7 +183,7 @@ void Trick::MemoryManager::get_stl_dependencies_in_intrinsic( std::string name ,
int ii; int ii;
for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) { for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) {
char index[16] ; char index[16] ;
sprintf(index, "[%d]", ii) ; snprintf(index, sizeof(index), "[%d]", ii) ;
//get_stl_dependencies_in_intrinsic( name + index , address, attr, curr_dim + 1, offset * attr->index[curr_dim].size + ii); //get_stl_dependencies_in_intrinsic( name + index , address, attr, curr_dim + 1, offset * attr->index[curr_dim].size + ii);
} }
} }

View File

@ -135,7 +135,7 @@ void Trick::MemoryManager::restore_stls_in_arrayed_class(
curr_dim_size = attr->index[curr_dim].size; curr_dim_size = attr->index[curr_dim].size;
for (ii = 0; ii < curr_dim_size; ii++) { for (ii = 0; ii < curr_dim_size; ii++) {
char index[16] ; char index[16] ;
sprintf(index, "[%d]", ii) ; snprintf(index, sizeof(index), "[%d]", ii) ;
if (curr_dim < attr->num_index - 1) { if (curr_dim < attr->num_index - 1) {
restore_stls_in_arrayed_class( name + index, address, attr, curr_dim + 1, offset * curr_dim_size + ii); restore_stls_in_arrayed_class( name + index, address, attr, curr_dim + 1, offset * curr_dim_size + ii);
} else { } else {
@ -188,7 +188,7 @@ void Trick::MemoryManager::restore_stls_in_intrinsic( std::string name , void* a
int ii; int ii;
for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) { for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) {
char index[16] ; char index[16] ;
sprintf(index, "[%d]", ii) ; snprintf(index, sizeof(index), "[%d]", ii) ;
//restore_stls_in_intrinsic( name + index , address, attr, curr_dim + 1, offset * attr->index[curr_dim].size + ii); //restore_stls_in_intrinsic( name + index , address, attr, curr_dim + 1, offset * attr->index[curr_dim].size + ii);
} }
} }

View File

@ -35,10 +35,10 @@ void Trick::MemoryManager::execute_checkpoint( std::ostream& out_s ) {
/** Generate temporary names for anonymous variables. */ /** Generate temporary names for anonymous variables. */
if (alloc_info->name == NULL) { if (alloc_info->name == NULL) {
if ( alloc_info->stcl == TRICK_LOCAL) { if ( alloc_info->stcl == TRICK_LOCAL) {
sprintf( name, "%s%d", local_anon_var_prefix, local_anon_var_number++); snprintf( name, sizeof(name), "%s%d", local_anon_var_prefix, local_anon_var_number++);
alloc_info->name = strdup( name); alloc_info->name = strdup( name);
} else if (alloc_info->stcl == TRICK_EXTERN) { } else if (alloc_info->stcl == TRICK_EXTERN) {
sprintf( name, "%s%d", extern_anon_var_prefix, extern_anon_var_number++); snprintf( name, sizeof(name), "%s%d", extern_anon_var_prefix, extern_anon_var_number++);
alloc_info->name = strdup( name); alloc_info->name = strdup( name);
/** @b NOTE: We should not write declarations for external /** @b NOTE: We should not write declarations for external
anonymous variables, because we should not reload them.*/ anonymous variables, because we should not reload them.*/

View File

@ -170,7 +170,7 @@ param: NAME {
/* create a new reference string because previous nodes may refer to old strings */ /* create a new reference string because previous nodes may refer to old strings */
$$.num_index_left = $$.attr->num_index; $$.num_index_left = $$.attr->num_index;
sprintf(temp , "%s.%s" , $$.reference, $3) ; snprintf(temp, sizeof(temp), "%s.%s" , $$.reference, $3) ;
$$.reference = (char*)realloc($$.reference, strlen(temp) + 1) ; $$.reference = (char*)realloc($$.reference, strlen(temp) + 1) ;
strcpy($$.reference , temp) ; strcpy($$.reference , temp) ;

View File

@ -49,13 +49,13 @@ size_t wcs_to_ncs(const wchar_t * wcs, char *ncs, size_t ncs_max_len)
it. Note that the external representation will also be printable in the current locale. */ it. Note that the external representation will also be printable in the current locale. */
if (wcint == '\'') { if (wcint == '\'') {
sprintf(work_s, "\\\'"); snprintf(work_s, sizeof(work_s), "\\\'");
} else if (wcint == '\"') { } else if (wcint == '\"') {
sprintf(work_s, "\\\""); snprintf(work_s, sizeof(work_s), "\\\"");
} else if (wcint == '\?') { } else if (wcint == '\?') {
sprintf(work_s, "\\\?"); snprintf(work_s, sizeof(work_s), "\\\?");
} else if (wcint == '\\') { } else if (wcint == '\\') {
sprintf(work_s, "\\\\"); snprintf(work_s, sizeof(work_s), "\\\\");
} else { } else {
len = wcrtomb(work_s, (wchar_t) wcint, NULL); len = wcrtomb(work_s, (wchar_t) wcint, NULL);
work_s[len] = '\0'; work_s[len] = '\0';
@ -66,26 +66,26 @@ size_t wcs_to_ncs(const wchar_t * wcs, char *ncs, size_t ncs_max_len)
representation of this non-printable character. */ representation of this non-printable character. */
if (wcint <= 0xFF) { if (wcint <= 0xFF) {
if (wcint == '\a') { if (wcint == '\a') {
sprintf(work_s, "\\a"); snprintf(work_s, sizeof(work_s), "\\a");
} else if (wcint == '\b') { } else if (wcint == '\b') {
sprintf(work_s, "\\b"); snprintf(work_s, sizeof(work_s), "\\b");
} else if (wcint == '\f') { } else if (wcint == '\f') {
sprintf(work_s, "\\f"); snprintf(work_s, sizeof(work_s), "\\f");
} else if (wcint == '\n') { } else if (wcint == '\n') {
sprintf(work_s, "\\n"); snprintf(work_s, sizeof(work_s), "\\n");
} else if (wcint == '\r') { } else if (wcint == '\r') {
sprintf(work_s, "\\n"); snprintf(work_s, sizeof(work_s), "\\n");
} else if (wcint == '\t') { } else if (wcint == '\t') {
sprintf(work_s, "\\t"); snprintf(work_s, sizeof(work_s), "\\t");
} else if (wcint == '\v') { } else if (wcint == '\v') {
sprintf(work_s, "\\v"); snprintf(work_s, sizeof(work_s), "\\v");
} else { } else {
sprintf(work_s, "\\x%02x", wcint); snprintf(work_s, sizeof(work_s), "\\x%02x", wcint);
} }
} else if (wcint <= 0xFFFF) { } else if (wcint <= 0xFFFF) {
sprintf(work_s, "\\u%04X", wcint); snprintf(work_s, sizeof(work_s), "\\u%04X", wcint);
} else { } else {
sprintf(work_s, "\\U%08X", wcint); snprintf(work_s, sizeof(work_s), "\\U%08X", wcint);
} }
} }

View File

@ -27,7 +27,7 @@ Trick::MessagePublisher::MessagePublisher() {
void Trick::MessagePublisher::set_print_format() { void Trick::MessagePublisher::set_print_format() {
num_digits = (int)round(log10((double)tics_per_sec)) ; num_digits = (int)round(log10((double)tics_per_sec)) ;
sprintf(print_format, "|L %%3d|%%s|%%s|%%s|T %%d|%%lld.%%0%dlld| ", num_digits) ; snprintf(print_format, sizeof(print_format), "|L %%3d|%%s|%%s|%%s|T %%d|%%lld.%%0%dlld| ", num_digits) ;
} }
int Trick::MessagePublisher::init() { int Trick::MessagePublisher::init() {
@ -52,7 +52,7 @@ int Trick::MessagePublisher::publish(int level , std::string message) {
date = time(NULL) ; date = time(NULL) ;
strftime(date_buf, (size_t) 20, "%Y/%m/%d,%H:%M:%S", localtime(&date)); strftime(date_buf, (size_t) 20, "%Y/%m/%d,%H:%M:%S", localtime(&date));
(void) gethostname(hostname, (size_t) 48); (void) gethostname(hostname, (size_t) 48);
sprintf(header_buf , print_format , level, date_buf, hostname, snprintf(header_buf, sizeof(header_buf), print_format , level, date_buf, hostname,
sim_name.c_str(), exec_get_process_id(), tics/tics_per_sec , sim_name.c_str(), exec_get_process_id(), tics/tics_per_sec ,
(long long)((double)(tics % tics_per_sec) * (double)(pow(10 , num_digits)/tics_per_sec)) ) ; (long long)((double)(tics % tics_per_sec) * (double)(pow(10 , num_digits)/tics_per_sec)) ) ;
header = header_buf ; header = header_buf ;

View File

@ -34,36 +34,36 @@ std::string Trick::MonteVarCalculated::get_next_value() {
switch (ref2->attr->type) { switch (ref2->attr->type) {
case TRICK_CHARACTER: case TRICK_CHARACTER:
case TRICK_UNSIGNED_CHARACTER: case TRICK_UNSIGNED_CHARACTER:
sprintf(buffer, "%d", *(char *)ref2->address); snprintf(buffer, sizeof(buffer), "%d", *(char *)ref2->address);
value = buffer; value = buffer;
break; break;
case TRICK_SHORT: case TRICK_SHORT:
case TRICK_UNSIGNED_SHORT: case TRICK_UNSIGNED_SHORT:
sprintf(buffer, "%d", *(short *)ref2->address); snprintf(buffer, sizeof(buffer), "%d", *(short *)ref2->address);
value = buffer; value = buffer;
break; break;
case TRICK_INTEGER: case TRICK_INTEGER:
case TRICK_UNSIGNED_INTEGER: case TRICK_UNSIGNED_INTEGER:
case TRICK_LONG: case TRICK_LONG:
case TRICK_UNSIGNED_LONG: case TRICK_UNSIGNED_LONG:
sprintf(buffer, "%ld", *(long *)ref2->address); snprintf(buffer, sizeof(buffer), "%ld", *(long *)ref2->address);
value = buffer; value = buffer;
break; break;
case TRICK_LONG_LONG: case TRICK_LONG_LONG:
case TRICK_UNSIGNED_LONG_LONG: case TRICK_UNSIGNED_LONG_LONG:
sprintf(buffer, "%lld", *(long long *)ref2->address); snprintf(buffer, sizeof(buffer), "%lld", *(long long *)ref2->address);
value = buffer; value = buffer;
break; break;
case TRICK_FLOAT: case TRICK_FLOAT:
sprintf(buffer, "%.15g", *(float *)ref2->address); snprintf(buffer, sizeof(buffer), "%.15g", *(float *)ref2->address);
value = buffer; value = buffer;
break; break;
case TRICK_DOUBLE: case TRICK_DOUBLE:
sprintf(buffer, "%.15g", *(double *)ref2->address); snprintf(buffer, sizeof(buffer), "%.15g", *(double *)ref2->address);
value = buffer; value = buffer;
break; break;
default: default:
sprintf(buffer, "#Unsupported value type %d", ref2->attr->type) ; snprintf(buffer, sizeof(buffer), "#Unsupported value type %d", ref2->attr->type) ;
break ; break ;
} }

View File

@ -72,7 +72,7 @@ std::string Trick::MonteVarFile::get_next_value() {
// Verify the input column number is valid. // Verify the input column number is valid.
if ((column == 0) || (column > ntokens)) { if ((column == 0) || (column > ntokens)) {
char string[100]; char string[100];
sprintf(string, "Trick:MonteVarFile An invalid column number %u, valid column numbers are 1 - %u", column, ntokens); snprintf(string, sizeof(string), "Trick:MonteVarFile An invalid column number %u, valid column numbers are 1 - %u", column, ntokens);
exec_terminate_with_return(-1, __FILE__, __LINE__, string); exec_terminate_with_return(-1, __FILE__, __LINE__, string);
} }
@ -105,7 +105,7 @@ std::string Trick::MonteVarFile::get_next_value() {
} }
char string[100]; char string[100];
sprintf(string, "Trick:MonteVarFile the input file \"%s\" is not open for reading", file_name.c_str()); snprintf(string, sizeof(string), "Trick:MonteVarFile the input file \"%s\" is not open for reading", file_name.c_str());
exec_terminate_with_return(-1, __FILE__, __LINE__, string); exec_terminate_with_return(-1, __FILE__, __LINE__, string);
return NULL; return NULL;

View File

@ -178,14 +178,14 @@ std::string Trick::MonteVarRandom::get_next_value() {
} }
if (count >= 100) { if (count >= 100) {
char string[100]; char string[100];
sprintf(string, "Trick:MonteVarRandom failed to generate a random value for variable \"%s\"\n", name.c_str()); snprintf(string, sizeof(string), "Trick:MonteVarRandom failed to generate a random value for variable \"%s\"\n", name.c_str());
exec_terminate_with_return(-1, __FILE__, __LINE__, string); exec_terminate_with_return(-1, __FILE__, __LINE__, string);
} }
} else { } else {
if (trick_gsl_rand(&randist, &return_value) != 0) { if (trick_gsl_rand(&randist, &return_value) != 0) {
char string[100]; char string[100];
sprintf(string, "Trick:MonteVarRandom failed to generate a random value for variable \"%s\"\n", name.c_str()); snprintf(string, sizeof(string), "Trick:MonteVarRandom failed to generate a random value for variable \"%s\"\n", name.c_str());
exec_terminate_with_return(-1, __FILE__, __LINE__, string); exec_terminate_with_return(-1, __FILE__, __LINE__, string);
} }
} }
@ -194,16 +194,16 @@ std::string Trick::MonteVarRandom::get_next_value() {
case TRICK_GSL_POISSON: case TRICK_GSL_POISSON:
// STL returns int, GSL returns unsigned int // STL returns int, GSL returns unsigned int
if (stlGenPtr) { if (stlGenPtr) {
sprintf(buffer, " %d", return_value.ii); snprintf(buffer, sizeof(buffer), " %d", return_value.ii);
} else { } else {
sprintf(buffer, " %u", return_value.ui); snprintf(buffer, sizeof(buffer), " %u", return_value.ui);
} }
value = buffer; value = buffer;
break; break;
case TRICK_GSL_GAUSS: case TRICK_GSL_GAUSS:
case TRICK_GSL_FLAT: case TRICK_GSL_FLAT:
default: default:
sprintf(buffer, "%.15g", return_value.d); snprintf(buffer, sizeof(buffer), "%.15g", return_value.d);
value = buffer; value = buffer;
break; break;
} }

View File

@ -332,7 +332,7 @@ int Trick::RealtimeSync::rt_monitor(long long sim_time_tics) {
(double)(frame_overrun_time/tics_per_sec), rt_max_overrun_time); (double)(frame_overrun_time/tics_per_sec), rt_max_overrun_time);
exec_freeze() ; exec_freeze() ;
} else { } else {
sprintf(buf, "\nMaximum overrun condition exceeded:\n" snprintf(buf, sizeof(buf), "\nMaximum overrun condition exceeded:\n"
"consecutive overruns/allowed overruns: %d/%d\n" "consecutive overruns/allowed overruns: %d/%d\n"
"total overrun time/allowed time: %f/%g\n", "total overrun time/allowed time: %f/%g\n",
frame_overrun_cnt, rt_max_overrun_cnt, frame_overrun_cnt, rt_max_overrun_cnt,

View File

@ -119,7 +119,7 @@ int Trick::ITimer::start(double in_frame_time) {
active = true ; active = true ;
} else { } else {
char error_message[256]; char error_message[256];
sprintf(error_message, "itimer frame_time is not set\n" ) ; snprintf(error_message, sizeof(error_message), "itimer frame_time is not set\n" ) ;
exec_terminate_with_return(-1, __FILE__, __LINE__ , error_message); exec_terminate_with_return(-1, __FILE__, __LINE__ , error_message);
} }
} }

View File

@ -182,7 +182,7 @@ void * Trick::VariableServerListenThread::thread_body() {
vst->wait_for_accept() ; vst->wait_for_accept() ;
pthread_mutex_unlock(&restart_pause) ; pthread_mutex_unlock(&restart_pause) ;
} else if ( broadcast ) { } else if ( broadcast ) {
sprintf(buf1 , "%s\t%hu\t%s\t%d\t%s\t%s\t%s\t%s\t%s\t%hu\n" , listen_dev.hostname , (unsigned short)listen_dev.port , snprintf(buf1 , sizeof(buf1), "%s\t%hu\t%s\t%d\t%s\t%s\t%s\t%s\t%s\t%hu\n" , listen_dev.hostname , (unsigned short)listen_dev.port ,
user_name , (int)getpid() , command_line_args_get_default_dir() , command_line_args_get_cmdline_name() , user_name , (int)getpid() , command_line_args_get_default_dir() , command_line_args_get_cmdline_name() ,
command_line_args_get_input_file() , version.c_str() , user_tag.c_str(), (unsigned short)listen_dev.port ) ; command_line_args_get_input_file() , version.c_str() , user_tag.c_str(), (unsigned short)listen_dev.port ) ;

View File

@ -236,7 +236,7 @@ int Trick::VariableServerThread::var_exists(std::string in_name) {
tc_write(&connection, (char *) buf1, 5); tc_write(&connection, (char *) buf1, 5);
} else { } else {
/* send ascii "1" or "0" */ /* send ascii "1" or "0" */
sprintf(buf1, "%d\t%d\n", VS_VAR_EXISTS, (error==false)); snprintf(buf1, sizeof(buf1), "%d\t%d\n", VS_VAR_EXISTS, (error==false));
if (debug >= 2) { if (debug >= 2) {
message_publish(MSG_DEBUG, "%p tag=<%s> var_server sending:\n%s\n", &connection, connection.client_tag, buf1) ; message_publish(MSG_DEBUG, "%p tag=<%s> var_server sending:\n%s\n", &connection, connection.client_tag, buf1) ;
} }
@ -430,7 +430,7 @@ int Trick::VariableServerThread::send_list_size() {
tc_write(&connection, (char *) buf1, 12); tc_write(&connection, (char *) buf1, 12);
} else { } else {
// ascii // ascii
sprintf(buf1, "%d\t%d\n", VS_LIST_SIZE, var_count); snprintf(buf1, sizeof(buf1), "%d\t%d\n", VS_LIST_SIZE, var_count);
if (debug >= 2) { if (debug >= 2) {
message_publish(MSG_DEBUG, "%p tag=<%s> var_server sending number of event variables:\n%s\n", &connection, connection.client_tag, buf1) ; message_publish(MSG_DEBUG, "%p tag=<%s> var_server sending number of event variables:\n%s\n", &connection, connection.client_tag, buf1) ;
} }
@ -455,7 +455,7 @@ int Trick::VariableServerThread::transmit_file(std::string sie_file) {
if ((fp = fopen(sie_file.c_str() , "r")) == NULL ) { if ((fp = fopen(sie_file.c_str() , "r")) == NULL ) {
message_publish(MSG_ERROR,"Variable Server Error: Cannot open %s.\n", sie_file.c_str()) ; message_publish(MSG_ERROR,"Variable Server Error: Cannot open %s.\n", sie_file.c_str()) ;
sprintf(buffer, "%d\t-1\n", VS_SIE_RESOURCE) ; snprintf(buffer, sizeof(buffer), "%d\t-1\n", VS_SIE_RESOURCE) ;
tc_write(&connection , buffer , strlen(buffer)) ; tc_write(&connection , buffer , strlen(buffer)) ;
return(-1) ; return(-1) ;
} }
@ -463,7 +463,7 @@ int Trick::VariableServerThread::transmit_file(std::string sie_file) {
fseek(fp , 0L, SEEK_END) ; fseek(fp , 0L, SEEK_END) ;
file_size = ftell(fp) ; file_size = ftell(fp) ;
sprintf(buffer, "%d\t%u\n" , VS_SIE_RESOURCE, file_size) ; snprintf(buffer, sizeof(buffer), "%d\t%u\n" , VS_SIE_RESOURCE, file_size) ;
tc_write(&connection , buffer , strlen(buffer)) ; tc_write(&connection , buffer , strlen(buffer)) ;
rewind(fp) ; rewind(fp) ;

View File

@ -22,7 +22,6 @@ extern "C" {
int Trick::VariableServerThread::write_binary_data( int Start, char *buf1, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type) { int Trick::VariableServerThread::write_binary_data( int Start, char *buf1, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type) {
int vars = 0;
int i; int i;
int ret ; int ret ;
int HeaderSize, MessageSize; int HeaderSize, MessageSize;
@ -178,13 +177,13 @@ int Trick::VariableServerThread::write_binary_data( int Start, char *buf1, const
return i; return i;
} }
int Trick::VariableServerThread::write_ascii_data(char * dest_buf, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type ) { int Trick::VariableServerThread::write_ascii_data(char * dest_buf, size_t dest_buf_size, const std::vector<VariableReference *>& given_vars, VS_MESSAGE_TYPE message_type ) {
sprintf(dest_buf, "%d\t", message_type) ; snprintf(dest_buf, dest_buf_size, "%d\t", message_type) ;
for (int i = 0; i < given_vars.size(); i++) { for (unsigned long i = 0; i < given_vars.size(); i++) {
char curr_buf[MAX_MSG_LEN]; char curr_buf[MAX_MSG_LEN];
int ret = vs_format_ascii( given_vars[i] , curr_buf); int ret = vs_format_ascii( given_vars[i] , curr_buf, sizeof(curr_buf));
if (ret < 0) { if (ret < 0) {
message_publish(MSG_WARNING, "%p Variable Server string buffer[%d] too small for symbol %s, TRUNCATED IT.\n", message_publish(MSG_WARNING, "%p Variable Server string buffer[%d] too small for symbol %s, TRUNCATED IT.\n",
@ -279,7 +278,7 @@ int Trick::VariableServerThread::write_data() {
return 0; return 0;
} else { /* ascii mode */ } else { /* ascii mode */
return write_ascii_data(buf1, vars, VS_VAR_LIST ); return write_ascii_data(buf1, sizeof(buf1), vars, VS_VAR_LIST );
} }
} }
} }
@ -318,7 +317,7 @@ int Trick::VariableServerThread::write_data(std::vector<VariableReference *> giv
return 0; return 0;
} else { /* ascii mode */ } else { /* ascii mode */
return write_ascii_data(buf1, given_vars, VS_SEND_ONCE); return write_ascii_data(buf1, sizeof(buf1), given_vars, VS_SEND_ONCE);
} }
} }
} }

View File

@ -6,7 +6,7 @@
int Trick::VariableServerThread::write_stdio(int stream, std::string text) { int Trick::VariableServerThread::write_stdio(int stream, std::string text) {
char header[16] ; char header[16] ;
sprintf(header, "%-2d %1d %8d\n" , VS_STDIO, stream , (int)text.length()) ; snprintf(header, sizeof(header), "%-2d %1d %8d\n" , VS_STDIO, stream , (int)text.length()) ;
tc_write(&connection , (char *) header , strlen(header)) ; tc_write(&connection , (char *) header , strlen(header)) ;
tc_write(&connection , (char *) text.c_str() , text.length()) ; tc_write(&connection , (char *) text.c_str() , text.length()) ;
return 0 ; return 0 ;

View File

@ -22,7 +22,7 @@ size_t escape_str(const char *in_s, char *out_s);
#define MAX_VAL_STRLEN 2048 #define MAX_VAL_STRLEN 2048
int vs_format_ascii(Trick::VariableReference * var, char *value) { int vs_format_ascii(Trick::VariableReference * var, char *value, size_t value_size) {
/* for string types, return -1 if string is too big to fit in buffer (MAX_VAL_STRLEN) */ /* for string types, return -1 if string is too big to fit in buffer (MAX_VAL_STRLEN) */
REF2 * ref ; REF2 * ref ;
@ -41,7 +41,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
case TRICK_CHARACTER: case TRICK_CHARACTER:
if (ref->attr->num_index == ref->num_index) { if (ref->attr->num_index == ref->num_index) {
sprintf(value, "%s%d", value,(char)cv_convert_double(var->conversion_factor, *(char *)buf_ptr)); snprintf(value, value_size, "%s%d", value,(char)cv_convert_double(var->conversion_factor, *(char *)buf_ptr));
} else { } else {
/* All but last dim specified, leaves a char array */ /* All but last dim specified, leaves a char array */
escape_str((char *) buf_ptr, value); escape_str((char *) buf_ptr, value);
@ -50,7 +50,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
break; break;
case TRICK_UNSIGNED_CHARACTER: case TRICK_UNSIGNED_CHARACTER:
if (ref->attr->num_index == ref->num_index) { if (ref->attr->num_index == ref->num_index) {
sprintf(value, "%s%u", value,(unsigned char)cv_convert_double(var->conversion_factor,*(unsigned char *)buf_ptr)); snprintf(value, value_size, "%s%u", value,(unsigned char)cv_convert_double(var->conversion_factor,*(unsigned char *)buf_ptr));
} else { } else {
/* All but last dim specified, leaves a char array */ /* All but last dim specified, leaves a char array */
escape_str((char *) buf_ptr, value); escape_str((char *) buf_ptr, value);
@ -60,7 +60,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
case TRICK_WCHAR:{ case TRICK_WCHAR:{
if (ref->attr->num_index == ref->num_index) { if (ref->attr->num_index == ref->num_index) {
sprintf(value, "%s%d", value,*(wchar_t *) buf_ptr); snprintf(value, value_size, "%s%d", value,*(wchar_t *) buf_ptr);
} else { } else {
// convert wide char string char string // convert wide char string char string
size_t len = wcs_to_ncs_len((wchar_t *)buf_ptr) + 1 ; size_t len = wcs_to_ncs_len((wchar_t *)buf_ptr) + 1 ;
@ -98,16 +98,16 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
#if ( __linux | __sgi ) #if ( __linux | __sgi )
case TRICK_BOOLEAN: case TRICK_BOOLEAN:
sprintf(value, "%s%d", value,(unsigned char)cv_convert_double(var->conversion_factor,*(unsigned char *)buf_ptr)); snprintf(value, value_size, "%s%d", value,(unsigned char)cv_convert_double(var->conversion_factor,*(unsigned char *)buf_ptr));
break; break;
#endif #endif
case TRICK_SHORT: case TRICK_SHORT:
sprintf(value, "%s%d", value, (short)cv_convert_double(var->conversion_factor,*(short *)buf_ptr)); snprintf(value, value_size, "%s%d", value, (short)cv_convert_double(var->conversion_factor,*(short *)buf_ptr));
break; break;
case TRICK_UNSIGNED_SHORT: case TRICK_UNSIGNED_SHORT:
sprintf(value, "%s%u", value,(unsigned short)cv_convert_double(var->conversion_factor,*(unsigned short *)buf_ptr)); snprintf(value, value_size, "%s%u", value,(unsigned short)cv_convert_double(var->conversion_factor,*(unsigned short *)buf_ptr));
break; break;
case TRICK_INTEGER: case TRICK_INTEGER:
@ -115,18 +115,18 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
#if ( __sun | __APPLE__ ) #if ( __sun | __APPLE__ )
case TRICK_BOOLEAN: case TRICK_BOOLEAN:
#endif #endif
sprintf(value, "%s%d", value, (int)cv_convert_double(var->conversion_factor,*(int *)buf_ptr)); snprintf(value, value_size, "%s%d", value, (int)cv_convert_double(var->conversion_factor,*(int *)buf_ptr));
break; break;
case TRICK_BITFIELD: case TRICK_BITFIELD:
sprintf(value, "%d", GET_BITFIELD(buf_ptr, ref->attr->size, ref->attr->index[0].start, ref->attr->index[0].size)); snprintf(value, value_size, "%d", GET_BITFIELD(buf_ptr, ref->attr->size, ref->attr->index[0].start, ref->attr->index[0].size));
break; break;
case TRICK_UNSIGNED_BITFIELD: case TRICK_UNSIGNED_BITFIELD:
sprintf(value, "%u", GET_UNSIGNED_BITFIELD(buf_ptr, ref->attr->size, ref->attr->index[0].start, ref->attr->index[0].size)); snprintf(value, value_size, "%u", GET_UNSIGNED_BITFIELD(buf_ptr, ref->attr->size, ref->attr->index[0].start, ref->attr->index[0].size));
break; break;
case TRICK_UNSIGNED_INTEGER: case TRICK_UNSIGNED_INTEGER:
sprintf(value, "%s%u", value, (unsigned int)cv_convert_double(var->conversion_factor,*(unsigned int *)buf_ptr)); snprintf(value, value_size, "%s%u", value, (unsigned int)cv_convert_double(var->conversion_factor,*(unsigned int *)buf_ptr));
break; break;
case TRICK_LONG: { case TRICK_LONG: {
@ -134,7 +134,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
if (var->conversion_factor != cv_get_trivial()) { if (var->conversion_factor != cv_get_trivial()) {
l = (long)cv_convert_double(var->conversion_factor, l); l = (long)cv_convert_double(var->conversion_factor, l);
} }
sprintf(value, "%s%ld", value, l); snprintf(value, value_size, "%s%ld", value, l);
break; break;
} }
@ -143,16 +143,16 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
if (var->conversion_factor != cv_get_trivial()) { if (var->conversion_factor != cv_get_trivial()) {
ul = (unsigned long)cv_convert_double(var->conversion_factor, ul); ul = (unsigned long)cv_convert_double(var->conversion_factor, ul);
} }
sprintf(value, "%s%lu", value, ul); snprintf(value, value_size, "%s%lu", value, ul);
break; break;
} }
case TRICK_FLOAT: case TRICK_FLOAT:
sprintf(value, "%s%.8g", value, cv_convert_float(var->conversion_factor,*(float *)buf_ptr)); snprintf(value, value_size, "%s%.8g", value, cv_convert_float(var->conversion_factor,*(float *)buf_ptr));
break; break;
case TRICK_DOUBLE: case TRICK_DOUBLE:
sprintf(value, "%s%.16g", value, cv_convert_double(var->conversion_factor,*(double *)buf_ptr)); snprintf(value, value_size, "%s%.16g", value, cv_convert_double(var->conversion_factor,*(double *)buf_ptr));
break; break;
case TRICK_LONG_LONG: { case TRICK_LONG_LONG: {
@ -160,7 +160,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
if (var->conversion_factor != cv_get_trivial()) { if (var->conversion_factor != cv_get_trivial()) {
ll = (long long)cv_convert_double(var->conversion_factor, ll); ll = (long long)cv_convert_double(var->conversion_factor, ll);
} }
sprintf(value, "%s%lld", value, ll); snprintf(value, value_size, "%s%lld", value, ll);
break; break;
} }
@ -169,12 +169,12 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
if (var->conversion_factor != cv_get_trivial()) { if (var->conversion_factor != cv_get_trivial()) {
ull = (unsigned long long)cv_convert_double(var->conversion_factor, ull); ull = (unsigned long long)cv_convert_double(var->conversion_factor, ull);
} }
sprintf(value, "%s%llu", value, ull); snprintf(value, value_size, "%s%llu", value, ull);
break; break;
} }
case TRICK_NUMBER_OF_TYPES: case TRICK_NUMBER_OF_TYPES:
sprintf(value, "BAD_REF" ); snprintf(value, value_size, "BAD_REF" );
break; break;
default:{ default:{
@ -191,9 +191,9 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) {
if (ref->units) { if (ref->units) {
if ( ref->attr->mods & TRICK_MODS_UNITSDASHDASH ) { if ( ref->attr->mods & TRICK_MODS_UNITSDASHDASH ) {
sprintf(value, "%s {--}", value); snprintf(value, value_size, "%s {--}", value);
} else { } else {
sprintf(value, "%s {%s}", value, ref->units); snprintf(value, value_size, "%s {%s}", value, ref->units);
} }
} }
@ -225,21 +225,21 @@ size_t escape_str(const char *in_s, char *out_s)
work_s[1] = '\0'; work_s[1] = '\0';
} else { } else {
if (ch == '\a') { if (ch == '\a') {
sprintf(work_s, "\\a"); snprintf(work_s, sizeof(work_s), "\\a");
} else if (ch == '\b') { } else if (ch == '\b') {
sprintf(work_s, "\\b"); snprintf(work_s, sizeof(work_s), "\\b");
} else if (ch == '\f') { } else if (ch == '\f') {
sprintf(work_s, "\\f"); snprintf(work_s, sizeof(work_s), "\\f");
} else if (ch == '\n') { } else if (ch == '\n') {
sprintf(work_s, "\\n"); snprintf(work_s, sizeof(work_s), "\\n");
} else if (ch == '\r') { } else if (ch == '\r') {
sprintf(work_s, "\\n"); snprintf(work_s, sizeof(work_s), "\\n");
} else if (ch == '\t') { } else if (ch == '\t') {
sprintf(work_s, "\\t"); snprintf(work_s, sizeof(work_s), "\\t");
} else if (ch == '\v') { } else if (ch == '\v') {
sprintf(work_s, "\\v"); snprintf(work_s, sizeof(work_s), "\\v");
} else { } else {
sprintf(work_s, "\\x%02x", ch); snprintf(work_s, sizeof(work_s), "\\x%02x", ch);
} }
} }
out_len += strlen(work_s); out_len += strlen(work_s);

View File

@ -14,9 +14,9 @@ swig_double::swig_double() {
char * swig_double::__str__() { char * swig_double::__str__() {
if ( ! units.empty() && units.compare("1") ) { if ( ! units.empty() && units.compare("1") ) {
sprintf(str_output , "%g %s", value , units.c_str()) ; snprintf(str_output , sizeof(str_output), "%g %s", value , units.c_str()) ;
} else { } else {
sprintf(str_output , "%g", value ) ; snprintf(str_output , sizeof(str_output), "%g", value ) ;
} }
return(str_output) ; return(str_output) ;
} }

View File

@ -14,9 +14,9 @@ swig_int::swig_int() {
char * swig_int::__str__() { char * swig_int::__str__() {
if ( ! units.empty() && units.compare("1") ) { if ( ! units.empty() && units.compare("1") ) {
sprintf(str_output , "%lld %s", value , units.c_str()) ; snprintf(str_output , sizeof(str_output), "%lld %s", value , units.c_str()) ;
} else { } else {
sprintf(str_output , "%lld", value ) ; snprintf(str_output , sizeof(str_output), "%lld", value ) ;
} }
return(str_output) ; return(str_output) ;
} }
@ -1211,13 +1211,13 @@ PyObject * swig_int::__float__() {
PyObject * swig_int::__oct__() { PyObject * swig_int::__oct__() {
char temp[32] ; char temp[32] ;
sprintf(temp , "0%o" , (unsigned int)value) ; snprintf(temp, sizeof(temp), "0%o" , (unsigned int)value) ;
return PyString_FromString(temp) ; return PyString_FromString(temp) ;
} }
PyObject * swig_int::__hex__() { PyObject * swig_int::__hex__() {
char temp[32] ; char temp[32] ;
sprintf(temp , "0x%llx" , value) ; snprintf(temp, sizeof(temp), "0x%llx" , value) ;
return PyString_FromString(temp) ; return PyString_FromString(temp) ;
} }

View File

@ -31,7 +31,7 @@ int tc_accept_(TCDevice * listen_device, TCDevice * device, const char *file, in
length = sizeof(s_in); length = sizeof(s_in);
the_socket = accept(listen_device->socket, (struct sockaddr *) &s_in, &length); the_socket = accept(listen_device->socket, (struct sockaddr *) &s_in, &length);
sprintf(client_str, "(ID = %d tag = %s)", listen_device->client_id, listen_device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", listen_device->client_id, listen_device->client_tag);
/* Check for error conditon on accept */ /* Check for error conditon on accept */
if (the_socket == TRICKCOMM_INVALID_SOCKET) { if (the_socket == TRICKCOMM_INVALID_SOCKET) {
@ -128,7 +128,7 @@ int tc_accept_(TCDevice * listen_device, TCDevice * device, const char *file, in
} }
} }
sprintf(client_str, "(ID = %d tag = %s)", device->client_id, device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", device->client_id, device->client_tag);
trick_error_report(listen_device->error_handler, TRICK_ERROR_ADVISORY, trick_error_report(listen_device->error_handler, TRICK_ERROR_ADVISORY,
file, line, "tc_accept: %s: connected to client using port %d\n", client_str, device->port); file, line, "tc_accept: %s: connected to client using port %d\n", client_str, device->port);

View File

@ -23,7 +23,7 @@ int tc_blockio(TCDevice * device, TCCommBlocking blockflag)
} }
/* Status message */ /* Status message */
sprintf(client_str, "(ID = %d tag = %s)", device->client_id, device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", device->client_id, device->client_tag);
trick_error_report(device->error_handler, TRICK_ERROR_TRIVIAL, __FILE__, trick_error_report(device->error_handler, TRICK_ERROR_TRIVIAL, __FILE__,
__LINE__, "%s blockflag = %d\n", client_str, blockflag); __LINE__, "%s blockflag = %d\n", client_str, blockflag);

View File

@ -59,7 +59,7 @@ int tc_connect_(TCDevice * device, const char *file, int line)
if (device->client_tag[0] == '\0') { if (device->client_tag[0] == '\0') {
strcpy(device->client_tag, "<empty>"); strcpy(device->client_tag, "<empty>");
} }
sprintf(client_str, "(ID = %d tag = %s hostname = %s port = %d)", snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s hostname = %s port = %d)",
device->client_id, device->client_tag, device->hostname, device->port); device->client_id, device->client_tag, device->hostname, device->port);
#ifdef __WIN32__ #ifdef __WIN32__

View File

@ -23,7 +23,7 @@ int tc_disconnect(TCDevice * device)
/* Status message */ /* Status message */
sprintf(client_str, "(ID = %d tag = %s)", device->client_id, device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", device->client_id, device->client_tag);
trick_error_report(device->error_handler, TRICK_ERROR_TRIVIAL, __FILE__, __LINE__, "%s \n", client_str); trick_error_report(device->error_handler, TRICK_ERROR_TRIVIAL, __FILE__, __LINE__, "%s \n", client_str);

View File

@ -46,7 +46,7 @@ int tc_read_(TCDevice * device, char *buffer, int size, const char *file, int li
return (-1); return (-1);
} }
sprintf(client_str, "(ID = %d tag = %s)", device->client_id, device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", device->client_id, device->client_tag);
trick_error_report(device->error_handler, TRICK_ERROR_ALL, file, line, trick_error_report(device->error_handler, TRICK_ERROR_ALL, file, line,
"tc_read: %s reading %d bytes\n", client_str, size); "tc_read: %s reading %d bytes\n", client_str, size);
@ -85,7 +85,7 @@ int tc_read_(TCDevice * device, char *buffer, int size, const char *file, int li
} else if (tmp_nbytes == -1) { } else if (tmp_nbytes == -1) {
error = tc_errno; error = tc_errno;
if (error != TRICKCOMM_EAGAIN && error != TRICKCOMM_EWOULDBLOCK) { if (error != TRICKCOMM_EAGAIN && error != TRICKCOMM_EWOULDBLOCK) {
sprintf(error_str, "tc_read: %s %s (tc_errno = %d)", client_str, strerror(error), error); snprintf(error_str, sizeof(error_str), "tc_read: %s %s (tc_errno = %d)", client_str, strerror(error), error);
trick_error_report(device->error_handler, TRICK_ERROR_ALERT, file, line, error_str); trick_error_report(device->error_handler, TRICK_ERROR_ALERT, file, line, error_str);
tc_disconnect(device); tc_disconnect(device);
return (nbytes); return (nbytes);

View File

@ -41,7 +41,7 @@ int tc_write_(TCDevice * device, char *buffer, int size, const char *file, int l
return (-1); return (-1);
} }
sprintf(client_str, "(ID = %d tag = %s)", device->client_id, device->client_tag); snprintf(client_str, sizeof(client_str), "(ID = %d tag = %s)", device->client_id, device->client_tag);
trick_error_report(device->error_handler, TRICK_ERROR_ALL, file, line, "%s writing %d bytes\n", client_str, size); trick_error_report(device->error_handler, TRICK_ERROR_ALL, file, line, "%s writing %d bytes\n", client_str, size);
/* If this is a software blocking write get the current time from the system */ /* If this is a software blocking write get the current time from the system */
@ -62,7 +62,7 @@ int tc_write_(TCDevice * device, char *buffer, int size, const char *file, int l
if (tmp_nbytes < 0) { if (tmp_nbytes < 0) {
error = tc_errno; error = tc_errno;
if (error != TRICKCOMM_EAGAIN && error != TRICKCOMM_EWOULDBLOCK) { if (error != TRICKCOMM_EAGAIN && error != TRICKCOMM_EWOULDBLOCK) {
sprintf(error_str, "tc_write: %s %s (tc_errno = %d)", client_str, strerror(error), error); snprintf(error_str, sizeof(error_str), "tc_write: %s %s (tc_errno = %d)", client_str, strerror(error), error);
trick_error_report(device->error_handler, TRICK_ERROR_ALERT, file, line, error_str); trick_error_report(device->error_handler, TRICK_ERROR_ALERT, file, line, error_str);
tc_disconnect(device); tc_disconnect(device);
return (nbytes); return (nbytes);

View File

@ -162,7 +162,7 @@ void trick_error_func_default(TrickErrorHndlr * error_hndlr, /* In: Error obj
default: default:
if (msg != (char *) NULL) { if (msg != (char *) NULL) {
sprintf(unknown, "Unknown error level: %d! Something is " "seriously wrong!\n ", level); snprintf(unknown, sizeof(unknown), "Unknown error level: %d! Something is " "seriously wrong!\n ", level);
msg_buf = (char *) malloc(strlen(msg) + strlen(unknown) + 2); msg_buf = (char *) malloc(strlen(msg) + strlen(unknown) + 2);
strcpy(msg_buf, unknown); strcpy(msg_buf, unknown);
strcat(msg_buf, msg); strcat(msg_buf, msg);

View File

@ -40,7 +40,7 @@ int dLU_solver(double **A, /* In: The input matrix [A] */
if (mode == 0 || mode == 1) { if (mode == 0 || mode == 1) {
if (-TINY < A[0][0] && A[0][0] < TINY) { if (-TINY < A[0][0] && A[0][0] < TINY) {
sprintf(buf, "ERROR: Diagonal Element A[0][0] = %.17g " "is too small...\nEXITING...\n", A[0][0]); snprintf(buf, sizeof(buf), "ERROR: Diagonal Element A[0][0] = %.17g " "is too small...\nEXITING...\n", A[0][0]);
return (TM_DIAG_SMALL); return (TM_DIAG_SMALL);
} }
L[0][0] = sqrt(A[0][0]); L[0][0] = sqrt(A[0][0]);
@ -49,7 +49,7 @@ int dLU_solver(double **A, /* In: The input matrix [A] */
for (j = 1; j < n; j++) { for (j = 1; j < n; j++) {
if (-TINY < A[j][j] && A[j][j] < TINY) { if (-TINY < A[j][j] && A[j][j] < TINY) {
sprintf(buf, snprintf(buf, sizeof(buf),
"ERROR: Diagonal Element " "A[%d][%d] = %.17g is too small...\n" "EXITING...\n", j, j, A[j][j]); "ERROR: Diagonal Element " "A[%d][%d] = %.17g is too small...\n" "EXITING...\n", j, j, A[j][j]);
return (TM_DIAG_SMALL); return (TM_DIAG_SMALL);
} }

View File

@ -60,7 +60,7 @@ int tsm_init(TSMDevice * shm_device)
return (TSM_FAIL); return (TSM_FAIL);
} }
if (shm_device->key_file[0] == '\0') { if (shm_device->key_file[0] == '\0') {
sprintf(shm_device->key_file, "%s/trick_source/trick_utils/shm/src/tsm_init.c", getenv("TRICK_HOME")); snprintf(shm_device->key_file, sizeof(shm_device->key_file), "%s/trick_source/trick_utils/shm/src/tsm_init.c", getenv("TRICK_HOME"));
} }
//shm_device->key = ftok(shm_device->key_file, proj_id); //shm_device->key = ftok(shm_device->key_file, proj_id);
// we will use our own key generation in my_ftok // we will use our own key generation in my_ftok

View File

@ -102,23 +102,23 @@ size_t escape_to_ascii(const char *in, char *out, size_t outSize) {
state = ERROR_STATE; state = ERROR_STATE;
} else { // ASCII } else { // ASCII
if (ch == '\a') { if (ch == '\a') {
sprintf(ascii_elements, "\\a"); snprintf(ascii_elements, sizeof(ascii_elements), "\\a");
} else if (ch == '\b') { } else if (ch == '\b') {
sprintf(ascii_elements, "\\b"); snprintf(ascii_elements, sizeof(ascii_elements), "\\b");
} else if (ch == '\f') { } else if (ch == '\f') {
sprintf(ascii_elements, "\\f"); snprintf(ascii_elements, sizeof(ascii_elements), "\\f");
} else if (ch == '\n') { } else if (ch == '\n') {
sprintf(ascii_elements, "\\n"); snprintf(ascii_elements, sizeof(ascii_elements), "\\n");
} else if (ch == '\r') { } else if (ch == '\r') {
sprintf(ascii_elements, "\\r"); snprintf(ascii_elements, sizeof(ascii_elements), "\\r");
} else if (ch == '\t') { } else if (ch == '\t') {
sprintf(ascii_elements, "\\t"); snprintf(ascii_elements, sizeof(ascii_elements), "\\t");
} else if (ch == '\v') { } else if (ch == '\v') {
sprintf(ascii_elements, "\\v"); snprintf(ascii_elements, sizeof(ascii_elements), "\\v");
} else if (isprint(ch)) { } else if (isprint(ch)) {
sprintf(ascii_elements, "%c",ch); snprintf(ascii_elements, sizeof(ascii_elements), "%c",ch);
} else { } else {
sprintf(ascii_elements, "\\x%02x",ch); snprintf(ascii_elements, sizeof(ascii_elements), "\\x%02x",ch);
} }
size_t n_elements = strlen(ascii_elements); size_t n_elements = strlen(ascii_elements);
if (out != NULL) { if (out != NULL) {
@ -137,9 +137,9 @@ size_t escape_to_ascii(const char *in, char *out, size_t outSize) {
codePoint = (codePoint << 6) | (ch & 0x3f); // Extract low 6 bits codePoint = (codePoint << 6) | (ch & 0x3f); // Extract low 6 bits
state = 0; state = 0;
if (codePoint <= 0xffff) { if (codePoint <= 0xffff) {
sprintf(ascii_elements, "\\u%04x", codePoint); snprintf(ascii_elements, sizeof(ascii_elements), "\\u%04x", codePoint);
} else { } else {
sprintf(ascii_elements, "\\U%08x", codePoint); snprintf(ascii_elements, sizeof(ascii_elements), "\\U%08x", codePoint);
} }
size_t n_elements = strlen(ascii_elements); size_t n_elements = strlen(ascii_elements);
if (out != NULL) { if (out != NULL) {

View File

@ -208,7 +208,7 @@ int VariableServerSession::sendErrorMessage(const char* fmt, ... ) {
(void) vsnprintf(errText, MAX_MSG_SIZE, fmt, args); (void) vsnprintf(errText, MAX_MSG_SIZE, fmt, args);
va_end(args); va_end(args);
sprintf(msgText, "{ \"msg_type\" : \"error\",\n" snprintf(msgText, sizeof(msgText), "{ \"msg_type\" : \"error\",\n"
" \"error\" : \"%s\"}\n", errText); " \"error\" : \"%s\"}\n", errText);
mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, msgText, strlen(msgText)); mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, msgText, strlen(msgText));