From 2a03ff5cf442ca410b2799488e63a1c8044eea4e Mon Sep 17 00:00:00 2001 From: jmpenn Date: Tue, 15 Nov 2022 15:00:05 -0600 Subject: [PATCH] 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 --- docs/documentation/web/Extend-ws-api.md | 4 +- include/trick/DataRecordGroup.hh | 3 + include/trick/FrameLog.hh | 2 +- include/trick/VariableServer.hh | 2 +- include/trick/VariableServerThread.hh | 2 +- .../src/SegmentedExecutive.cpp | 2 +- .../S_overrides.mk | 9 ++- .../models/sched/src/sched_amf.c | 4 +- .../models/varserv/src/VS_init.cpp | 2 +- .../models/varserv/src/VS_tests.cpp | 38 ++++++------- .../Cannon/models/httpMethods/TimeSession.cpp | 5 +- .../models/graphics/cpp/main.cpp | 9 +-- .../models/Sun/src/sun_pred_fast_display.c | 10 ++-- .../models/Sun/src/sun_pred_slow_display.c | 10 ++-- .../codegen/Interface_Code_Gen/Utilities.cpp | 5 +- .../data_products/Apps/Trk2csv/trk2ascii.cpp | 10 ++-- .../DPX/APPS/FXPLOT/fermi_view.cpp | 2 +- .../DPX/APPS/FXPLOT/page_view_node.cpp | 13 +++-- .../DPX/APPS/FXPLOT/plot_view_node.cpp | 8 +-- .../DPX/APPS/FXPLOT/product_view_node.cpp | 4 +- .../DPX/APPS/FXPLOT/table_view_node.cpp | 2 +- .../DPX/APPS/GXPLOT/gp_view_page_node.cpp | 12 ++-- .../DPX/test/unit_test/DPC_test.cpp | 2 +- .../DPX/test/unit_test/DS_test.cpp | 2 +- .../data_products/EQParse/eqparse_error.c | 2 +- .../data_products/EQParse/eqparse_fillno.c | 2 +- .../data_products/Log/DataStreamFactory.cpp | 20 ++++--- .../data_products/Log/ExternalProgram.cpp | 2 +- trick_source/data_products/Log/darwin_dl.c | 4 +- trick_source/data_products/Log/log.cpp | 18 +++--- .../data_products/Log/parseLogHeader.cpp | 2 +- .../ClassicCheckPointerAgent.cpp | 23 +++++--- .../CheckPointAgent/input_parser.y | 28 +++++----- .../CommandLineArguments.cpp | 7 +-- .../sim_services/DataRecord/DRAscii.cpp | 35 ++++++------ .../DataRecord/DataRecordGroup.cpp | 8 +-- .../Executive/Executive_fpe_handler.cpp | 10 ++-- .../Executive/Executive_process_sim_args.cpp | 2 +- .../Executive/Executive_signal_handler.cpp | 4 +- .../Executive_write_s_job_execution.cpp | 2 +- .../Executive_write_s_run_summary.cpp | 2 +- .../sim_services/FrameLog/FrameLog.cpp | 8 +-- .../sim_services/InputProcessor/MTV.cpp | 18 +++--- .../MemoryManager_get_stl_dependencies.cpp | 4 +- .../MemoryManager_restore_stls.cpp | 4 +- .../MemoryManager_write_checkpoint.cpp | 4 +- .../sim_services/MemoryManager/ref_parser.y | 2 +- .../sim_services/MemoryManager/wcs_ext.c | 28 +++++----- .../sim_services/Message/MessagePublisher.cpp | 4 +- .../MonteCarlo/MonteVarCalculated.cpp | 14 ++--- .../sim_services/MonteCarlo/MonteVarFile.cpp | 4 +- .../MonteCarlo/MonteVarRandom.cpp | 10 ++-- .../RealtimeSync/RealtimeSync.cpp | 2 +- trick_source/sim_services/Timer/ITimer.cpp | 2 +- .../VariableServerListenThread.cpp | 2 +- .../VariableServerThread_commands.cpp | 8 +-- .../VariableServerThread_write_data.cpp | 13 ++--- .../VariableServerThread_write_stdio.cpp | 2 +- .../VariableServer/vs_format_ascii.cpp | 56 +++++++++---------- trick_source/trick_swig/swig_double.cpp | 4 +- trick_source/trick_swig/swig_int.cpp | 8 +-- trick_source/trick_utils/comm/src/tc_accept.c | 4 +- .../trick_utils/comm/src/tc_blockio.c | 2 +- .../trick_utils/comm/src/tc_connect.c | 2 +- .../trick_utils/comm/src/tc_disconnect.c | 2 +- trick_source/trick_utils/comm/src/tc_read.c | 4 +- trick_source/trick_utils/comm/src/tc_write.c | 4 +- .../trick_utils/comm/src/trick_error_hndlr.c | 2 +- .../trick_utils/math/src/dLU_solver.c | 4 +- trick_source/trick_utils/shm/src/tsm_init.c | 2 +- .../trick_utils/unicode/src/unicode_utils.c | 22 ++++---- .../CivetServer/src/VariableServerSession.cpp | 2 +- 72 files changed, 303 insertions(+), 277 deletions(-) diff --git a/docs/documentation/web/Extend-ws-api.md b/docs/documentation/web/Extend-ws-api.md index 223c83e6..13c35b7e 100644 --- a/docs/documentation/web/Extend-ws-api.md +++ b/docs/documentation/web/Extend-ws-api.md @@ -148,7 +148,7 @@ void TimeSession::sendMessage() { int month = theTime->tm_mon + 1; 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)); } @@ -270,4 +270,4 @@ To test your new web socket interface, put the following ```time.html``` file in ``` -Continue to [Simulation Utilities](../simulation_utilities/Simulation-Utilities) \ No newline at end of file +Continue to [Simulation Utilities](../simulation_utilities/Simulation-Utilities) diff --git a/include/trick/DataRecordGroup.hh b/include/trick/DataRecordGroup.hh index 34869ffe..ac5631e7 100644 --- a/include/trick/DataRecordGroup.hh +++ b/include/trick/DataRecordGroup.hh @@ -127,6 +127,9 @@ namespace Trick { /** Buffer to hold formatted data ready for disk or other destination.\n */ char * writer_buff ; /**< trick_io(**) trick_units(--) */ + /** Size of the writer_buff. */ + size_t writer_buff_size; + /** Little_endian or big_endian indicator.\n */ std::string byte_order; /**< trick_io(*io) trick_units(--) */ diff --git a/include/trick/FrameLog.hh b/include/trick/FrameLog.hh index 63a42594..edff7600 100644 --- a/include/trick/FrameLog.hh +++ b/include/trick/FrameLog.hh @@ -44,7 +44,7 @@ namespace Trick { /** Data recording group for logging frame/overrun time.\n 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 */ Trick::timeline_t **timeline; /**< trick_io(**) */ /** Non-Cyclic jobs timeline to log, dimensioned as [num_threads][tl_max_samples].\n */ diff --git a/include/trick/VariableServer.hh b/include/trick/VariableServer.hh index cd2cb5ce..c65951b0 100644 --- a/include/trick/VariableServer.hh +++ b/include/trick/VariableServer.hh @@ -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() ; diff --git a/include/trick/VariableServerThread.hh b/include/trick/VariableServerThread.hh index cb133c2d..c92ef72c 100644 --- a/include/trick/VariableServerThread.hh +++ b/include/trick/VariableServerThread.hh @@ -456,7 +456,7 @@ namespace Trick { /** @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& given_vars, VS_MESSAGE_TYPE message_type ); + int write_ascii_data(char * dest_buf, size_t dest_buf_size, const std::vector& given_vars, VS_MESSAGE_TYPE message_type ); /** @brief Construct a variable reference from the string in_name and handle error checking diff --git a/test/SIM_segments/models/SegmentedExecutive/src/SegmentedExecutive.cpp b/test/SIM_segments/models/SegmentedExecutive/src/SegmentedExecutive.cpp index 6efda5e5..6c72684f 100644 --- a/test/SIM_segments/models/SegmentedExecutive/src/SegmentedExecutive.cpp +++ b/test/SIM_segments/models/SegmentedExecutive/src/SegmentedExecutive.cpp @@ -154,7 +154,7 @@ int Trick::SegmentedExecutive::write_s_job_execution(FILE *fp) { /* Get full path to S_job_execution */ 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. */ if ((fp = fopen(buf, "a")) == NULL) { diff --git a/test/SIM_target_specific_variables/S_overrides.mk b/test/SIM_target_specific_variables/S_overrides.mk index 11dd3924..372dc22d 100644 --- a/test/SIM_target_specific_variables/S_overrides.mk +++ b/test/SIM_target_specific_variables/S_overrides.mk @@ -2,7 +2,14 @@ MODELS :=$(CURDIR)/models # Warn about comment markers /* within comments and make them errors, causing # 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 diff --git a/test/SIM_test_sched/models/sched/src/sched_amf.c b/test/SIM_test_sched/models/sched/src/sched_amf.c index ed2dfdc4..a4fb2b61 100644 --- a/test/SIM_test_sched/models/sched/src/sched_amf.c +++ b/test/SIM_test_sched/models/sched/src/sched_amf.c @@ -21,13 +21,13 @@ int sched_amf( if ( S->amf == 2 ) { /* 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, ""); i++; S->amf = 1 ; } else { /* 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, ". "); i++; S->amf = 3 ; diff --git a/test/SIM_test_varserv/models/varserv/src/VS_init.cpp b/test/SIM_test_varserv/models/varserv/src/VS_init.cpp index 3d117024..2e49f649 100644 --- a/test/SIM_test_varserv/models/varserv/src/VS_init.cpp +++ b/test/SIM_test_varserv/models/varserv/src/VS_init.cpp @@ -37,7 +37,7 @@ int VSTest::init() { // default cycle rate 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); return (0); diff --git a/test/SIM_test_varserv/models/varserv/src/VS_tests.cpp b/test/SIM_test_varserv/models/varserv/src/VS_tests.cpp index 69ce5bfd..a8bc32a3 100644 --- a/test/SIM_test_varserv/models/varserv/src/VS_tests.cpp +++ b/test/SIM_test_varserv/models/varserv/src/VS_tests.cpp @@ -39,7 +39,7 @@ int VSTest::testUnits() { int result; // 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); std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl; vs_read(); @@ -47,21 +47,21 @@ int VSTest::testUnits() { TRICK_EXPECT_EQ(result, 0, suite, "VariableInvalidUnits") // 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_read(); result = strcmp_IgnoringWhiteSpace("0 -1234 -123456 {m}", got_read); TRICK_EXPECT_EQ(result, 0, suite, "VariableAddUnits") // 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_read(); result = strcmp_IgnoringWhiteSpace("0 -1234 -405039 {ft}", got_read); TRICK_EXPECT_EQ(result, 0, suite, "VariableChangeUnits") // CLEAR VARIABLE SERVER - sprintf(msg,"trick.var_clear()\n"); + snprintf(msg, sizeof(msg), "trick.var_clear()\n"); vs_write(msg); } @@ -71,7 +71,7 @@ int VSTest::testAddRemove() { int result; // 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_read(); std::cout << got_read << std::endl; @@ -83,14 +83,14 @@ int VSTest::testAddRemove() { TRICK_EXPECT_EQ(result, 0, suite, "VariableAddCyclic") // 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_read(); result = strcmp_IgnoringWhiteSpace("0 -1234", got_read); TRICK_EXPECT_EQ(result, 0, suite, "VariableRemove") // CLEAR VARIABLE SERVER - sprintf(msg,"trick.var_clear()\n"); + snprintf(msg, sizeof(msg), "trick.var_clear()\n"); vs_write(msg); vs_read(); TRICK_EXPECT_EQ(strcmp(got_read, ""), 0, suite, "VariableClear") @@ -104,7 +104,7 @@ int VSTest::testSendOnce() { int result; // 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_read(); result = strcmp_IgnoringWhiteSpace("5 -123456", got_read); @@ -112,14 +112,14 @@ int VSTest::testSendOnce() { trick_test_add_parent( suite , "VariableSendOnce" , ""); // 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_read(); result = strcmp_IgnoringWhiteSpace("5 0 1 2", got_read); TRICK_EXPECT_EQ(result, 0, suite, "VariableSendOnceList") // 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); std::cerr << "The purpose of this test is to cause an error. Error messages are expected." << std::endl; vs_read(); @@ -133,7 +133,7 @@ int VSTest::testExists() { int result; // 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_read(); result = strcmp_IgnoringWhiteSpace("1 1",got_read); @@ -141,14 +141,14 @@ int VSTest::testExists() { trick_test_add_parent( suite , "VariableExists" , "3587464751"); // 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_read(); std::cout << "Check variable doesn't exist: " << got_read << std::endl; result = strcmp_IgnoringWhiteSpace("1 0",got_read); TRICK_EXPECT_EQ(result, 0, suite, "VariableNotExists") - sprintf(msg,"trick.var_clear()\n"); + snprintf(msg, sizeof(msg), "trick.var_clear()\n"); vs_write(msg); return(0); @@ -159,13 +159,13 @@ int VSTest::testPause() { char suite[] = "VariableServerTest"; 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); - sprintf(msg,"trick.var_add(\"vsx.vst.i\")\n"); + snprintf(msg, sizeof(msg), "trick.var_add(\"vsx.vst.i\")\n"); vs_write(msg); // PAUSE - sprintf(msg,"trick.var_pause()\n"); + snprintf(msg, sizeof(msg), "trick.var_pause()\n"); vs_write(msg); vs_read(); vs_read(); @@ -173,7 +173,7 @@ int VSTest::testPause() { trick_test_add_parent( suite , "VariablePause" , "964174074"); // SEND - sprintf(msg,"trick.var_send()\n"); + snprintf(msg, sizeof(msg), "trick.var_send()\n"); vs_write(msg); vs_read(); result = strcmp_IgnoringWhiteSpace("0 123456 1234.5677", got_read); @@ -185,7 +185,7 @@ int VSTest::testPause() { trick_test_add_parent( suite , "VariableSendNoCyclic" , "67211805"); // UNPAUSE - sprintf(msg,"trick.var_unpause()\n"); + snprintf(msg, sizeof(msg), "trick.var_unpause()\n"); vs_write(msg); vs_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_test_add_parent( suite , "VariableUnpauseCyclic" , "964174074"); - sprintf(msg,"trick.var_clear()\n"); + snprintf(msg, sizeof(msg), "trick.var_clear()\n"); vs_write(msg); return(0); diff --git a/trick_sims/Cannon/models/httpMethods/TimeSession.cpp b/trick_sims/Cannon/models/httpMethods/TimeSession.cpp index 92a2cf24..8d11d423 100644 --- a/trick_sims/Cannon/models/httpMethods/TimeSession.cpp +++ b/trick_sims/Cannon/models/httpMethods/TimeSession.cpp @@ -32,7 +32,7 @@ void TimeSession::sendMessage() { int month = theTime->tm_mon + 1; 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)); } @@ -52,4 +52,5 @@ int TimeSession::handleMessage(const std::string& client_msg) { WebSocketSession* makeTimeSession( struct mg_connection *nc ) { std::cerr << "DEBUG: Creating new TimeSession." << std::endl; return new TimeSession(nc); -} \ No newline at end of file +} + diff --git a/trick_sims/SIM_billiards/models/graphics/cpp/main.cpp b/trick_sims/SIM_billiards/models/graphics/cpp/main.cpp index a444675c..f0e98769 100644 --- a/trick_sims/SIM_billiards/models/graphics/cpp/main.cpp +++ b/trick_sims/SIM_billiards/models/graphics/cpp/main.cpp @@ -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 std::string format(const std::string& formatString, int num) { - char *buf = (char *)malloc(formatString.size() + 10); - sprintf(buf, formatString.c_str(), num); + size_t buf_len = formatString.size() + 10; + char *buf = (char *)malloc(buf_len); + snprintf(buf, buf_len, formatString.c_str(), num); return std::string(buf); } @@ -697,7 +698,7 @@ int main(int argc, char *argv[]) std::string templateString = "dyn.table.applyCueForce(%.3f, %.3f) \n"; char buf[128]; - sprintf(buf, templateString.c_str(), mouseX, mouseY); + snprintf(buf, sizeof(buf), templateString.c_str(), mouseX, mouseY); cueRequest += std::string(buf); socket << cueRequest; 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"; for (int i = 0; i < numBalls; i++) { char buf[128]; - sprintf(buf, templateString, i, i, i); + snprintf(buf, sizeof(buf), templateString, i, i, i); positionRequest += std::string(buf); } socket << positionRequest; diff --git a/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c b/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c index 66722386..fa9a7cbb 100644 --- a/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c +++ b/trick_sims/SIM_sun/models/Sun/src/sun_pred_fast_display.c @@ -55,17 +55,15 @@ int sun_pred_fast_display( char message[500]; 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); - // sprintf(tmp_s," %ls %.6f",S->label_JD, S->JD); - // strcat(message,tmp_s); 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 { - 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); - 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); send_hs(stdout,"%s\n",message); diff --git a/trick_sims/SIM_sun/models/Sun/src/sun_pred_slow_display.c b/trick_sims/SIM_sun/models/Sun/src/sun_pred_slow_display.c index 4b82cc0e..c95d6af2 100644 --- a/trick_sims/SIM_sun/models/Sun/src/sun_pred_slow_display.c +++ b/trick_sims/SIM_sun/models/Sun/src/sun_pred_slow_display.c @@ -55,15 +55,15 @@ int sun_pred_slow_display( char message[500]; message[0] = '\0'; - sprintf(tmp_s,"%lc",POSITION_INDICATOR); + snprintf(tmp_s, sizeof(tmp_s), "%lc",POSITION_INDICATOR); 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); - 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); - 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); - 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); send_hs(stdout,"%s\n",message); diff --git a/trick_source/codegen/Interface_Code_Gen/Utilities.cpp b/trick_source/codegen/Interface_Code_Gen/Utilities.cpp index 0155f468..39bec7d5 100644 --- a/trick_source/codegen/Interface_Code_Gen/Utilities.cpp +++ b/trick_source/codegen/Interface_Code_Gen/Utilities.cpp @@ -150,8 +150,9 @@ char * almostRealPath( const char * in_path ) { char * final_path = NULL ; resolved_path = realpath( dir , resolved_path) ; if ( resolved_path != NULL ) { - final_path = (char *)malloc(strlen(resolved_path) + strlen(file) + 2) ; - sprintf(final_path,"%s/%s", resolved_path , file ) ; + size_t final_path_len = strlen(resolved_path) + strlen(file) + 2; + final_path = (char *)malloc(final_path_len) ; + snprintf(final_path, final_path_len, "%s/%s", resolved_path , file ) ; free(resolved_path) ; } free(file_copy_path) ; diff --git a/trick_source/data_products/Apps/Trk2csv/trk2ascii.cpp b/trick_source/data_products/Apps/Trk2csv/trk2ascii.cpp index 57f09842..9b82e866 100644 --- a/trick_source/data_products/Apps/Trk2csv/trk2ascii.cpp +++ b/trick_source/data_products/Apps/Trk2csv/trk2ascii.cpp @@ -179,14 +179,14 @@ int main(int argc, char* argv[]) done = 0; while ( !done ) { current_line.clear(); - sprintf(buf, "%8s", ""); + snprintf(buf, sizeof(buf), "%8s", ""); current_line.append(buf); for ( idx = 0; idx < ds_list.size(); idx++ ) { if ( ds_list[idx]->get( &t, &y) == 0 ) { done = 1; break; } - sprintf(buf, "%.15G", y); + snprintf(buf, sizeof(buf), "%.15G", y); current_line.append(buf); } current_line.append(""); @@ -228,14 +228,14 @@ int main(int argc, char* argv[]) break; } if ( idx != 0) { - sprintf(buf, "%s", delimiter.c_str()); + snprintf(buf, sizeof(buf), "%s", delimiter.c_str()); current_line.append(buf); } if ( Format == FIX ) { - sprintf(buf, "%20.16g", y); + snprintf(buf, sizeof(buf), "%20.16g", y); current_line.append(buf); } else { - sprintf(buf, "%.15G", y); + snprintf(buf, sizeof(buf), "%.15G", y); current_line.append(buf); } } diff --git a/trick_source/data_products/DPX/APPS/FXPLOT/fermi_view.cpp b/trick_source/data_products/DPX/APPS/FXPLOT/fermi_view.cpp index 67261890..043a507c 100644 --- a/trick_source/data_products/DPX/APPS/FXPLOT/fermi_view.cpp +++ b/trick_source/data_products/DPX/APPS/FXPLOT/fermi_view.cpp @@ -32,7 +32,7 @@ fermi_view::fermi_view(Widget TopLevel) { trick_home = getenv("TRICK_HOME"); 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); } else { std::cerr << "ERROR: $TRICK_HOME is not set." << std::endl; diff --git a/trick_source/data_products/DPX/APPS/FXPLOT/page_view_node.cpp b/trick_source/data_products/DPX/APPS/FXPLOT/page_view_node.cpp index 5aab5308..f7b33c68 100644 --- a/trick_source/data_products/DPX/APPS/FXPLOT/page_view_node.cpp +++ b/trick_source/data_products/DPX/APPS/FXPLOT/page_view_node.cpp @@ -204,7 +204,7 @@ void PageViewNode::pdf_file_cb(Widget w, XtPointer client_data, XtPointer call_d page_view_node->generate_PS(tmp_file); // 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); XtFree(file_name); @@ -234,8 +234,9 @@ int PageViewNode::exists_program(const char *programName) strptr = path; while ((tokptr = strtok(strptr, ":")) != NULL) { - program = (char *) malloc(strlen(tokptr) + strlen(programName) + 2); - sprintf(program, "%s/%s", tokptr, programName); + size_t program_len = strlen(tokptr) + strlen(programName) + 2; + program = (char *) malloc( program_len); + snprintf(program, program_len, "%s/%s", tokptr, programName); if (access(program, F_OK | X_OK) == 0) { free(program); return (1); @@ -492,12 +493,12 @@ void PageViewNode::print() { if (!strcmp(trick_print_cmd, "lpr")) { 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 { - 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 { - 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; diff --git a/trick_source/data_products/DPX/APPS/FXPLOT/plot_view_node.cpp b/trick_source/data_products/DPX/APPS/FXPLOT/plot_view_node.cpp index 9eec3490..df3d7640 100644 --- a/trick_source/data_products/DPX/APPS/FXPLOT/plot_view_node.cpp +++ b/trick_source/data_products/DPX/APPS/FXPLOT/plot_view_node.cpp @@ -129,18 +129,18 @@ static void print_plot_cb(Widget w, XtPointer client_data, XtPointer call_data) if (!strcmp(trick_print_cmd, "lpr")) { 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 { - 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 { - 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; sys_ret = system( system_cmd); 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); } diff --git a/trick_source/data_products/DPX/APPS/FXPLOT/product_view_node.cpp b/trick_source/data_products/DPX/APPS/FXPLOT/product_view_node.cpp index 31fc7023..0541271e 100644 --- a/trick_source/data_products/DPX/APPS/FXPLOT/product_view_node.cpp +++ b/trick_source/data_products/DPX/APPS/FXPLOT/product_view_node.cpp @@ -61,9 +61,9 @@ void ProductViewNode::generate_PS(const char* file_name) { for (ii=0 ; ii 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 { - 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); std::cout << "Generating " << indexedFileName << " ..." << std::endl; diff --git a/trick_source/data_products/DPX/APPS/FXPLOT/table_view_node.cpp b/trick_source/data_products/DPX/APPS/FXPLOT/table_view_node.cpp index 8de0918a..03f8b818 100644 --- a/trick_source/data_products/DPX/APPS/FXPLOT/table_view_node.cpp +++ b/trick_source/data_products/DPX/APPS/FXPLOT/table_view_node.cpp @@ -301,7 +301,7 @@ TableViewNode::TableViewNode( Widget Toplevel, DPC_table* Table, int Xpos, int Y } else { // Parse succeeded. 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_data_format[colix] = strdup(user_format); column_width[colix] = width; diff --git a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_page_node.cpp b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_page_node.cpp index 5a3a77ab..e5a75e1e 100644 --- a/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_page_node.cpp +++ b/trick_source/data_products/DPX/APPS/GXPLOT/gp_view_page_node.cpp @@ -307,27 +307,27 @@ static void layout_page (GPViewPageNode* gp_view_page_node ) { // CALCULATE PLOT WIDTH 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("", value_text); // CALCULATE PLOT HEIGHT 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("", value_text); for (plot_ix=0; plot_ix< number_of_plots; plot_ix++) { float x,y; char key_text[20]; - sprintf(key_text, "", plot_ix); + snprintf(key_text, sizeof(key_text), "", plot_ix); 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); - sprintf(key_text, "", plot_ix); + snprintf(key_text, sizeof(key_text), "", plot_ix); 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); } } diff --git a/trick_source/data_products/DPX/test/unit_test/DPC_test.cpp b/trick_source/data_products/DPX/test/unit_test/DPC_test.cpp index c9a6be7e..71bea4e0 100644 --- a/trick_source/data_products/DPX/test/unit_test/DPC_test.cpp +++ b/trick_source/data_products/DPX/test/unit_test/DPC_test.cpp @@ -109,7 +109,7 @@ std::string DPCTest::parseDPCData(const char* name) { for ( product_ix = 0; product_ix < n_product_files; product_ix++ ) { DPC_product *product; 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; try { diff --git a/trick_source/data_products/DPX/test/unit_test/DS_test.cpp b/trick_source/data_products/DPX/test/unit_test/DS_test.cpp index fb2fc4dd..56f6ac27 100644 --- a/trick_source/data_products/DPX/test/unit_test/DS_test.cpp +++ b/trick_source/data_products/DPX/test/unit_test/DS_test.cpp @@ -345,7 +345,7 @@ TEST_F(DSTest, DataStream_Delta) { const char* a = "sun_predictor.sun.solar_azimuth:../TEST_DATA/BUNCHORUNS/RUN1"; 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(); testds = data_stream_factory->create(RUN_dir, DeltaName, "s_simtime"); diff --git a/trick_source/data_products/EQParse/eqparse_error.c b/trick_source/data_products/EQParse/eqparse_error.c index 922f7b94..b4511c1e 100644 --- a/trick_source/data_products/EQParse/eqparse_error.c +++ b/trick_source/data_products/EQParse/eqparse_error.c @@ -19,7 +19,7 @@ char *eqperror(int code) errorprintout = ( char* ) malloc ( 128 ) ; - sprintf(errorprintout,"\nError %d in eqparse.c:",code) ; + snprintf(errorprintout, 128, "\nError %d in eqparse.c:",code) ; switch (code){ case 1: strcat(errorprintout,"\nSyntax Error: ) Expected") ; diff --git a/trick_source/data_products/EQParse/eqparse_fillno.c b/trick_source/data_products/EQParse/eqparse_fillno.c index 9ea80b9f..15d1637e 100644 --- a/trick_source/data_products/EQParse/eqparse_fillno.c +++ b/trick_source/data_products/EQParse/eqparse_fillno.c @@ -57,7 +57,7 @@ stack fillno(stack1 * no, stack stk, double value) tmp_no = revers_stk(tmp_no); for (j = 0; j < i; j++) { tmp_no = pop(tmp_no, &ch); - sprintf(num, "%s%c", num, ch); + snprintf(num, sizeof(numstr), "%s%c", num, ch); } x = atof(num); #ifdef DEBUG diff --git a/trick_source/data_products/Log/DataStreamFactory.cpp b/trick_source/data_products/Log/DataStreamFactory.cpp index 9cfc0029..25965c0b 100644 --- a/trick_source/data_products/Log/DataStreamFactory.cpp +++ b/trick_source/data_products/Log/DataStreamFactory.cpp @@ -61,8 +61,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir, while ((dp = readdir(dirp)) != NULL) { len = strlen(dp->d_name); if ( !strcmp( &(dp->d_name[len - 3]) , ".h5")) { - full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; - sprintf(full_path, "%s/%s" , runDir.c_str() , dp->d_name); + size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2; + 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()) ) { closedir(dirp) ; 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) { len = strlen(dp->d_name); if ( !strcmp( &(dp->d_name[len - 4]) , ".trk")) { - full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; - sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); + size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2; + 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()) ) { closedir(dirp) ; stream = new TrickBinary(full_path , (char *)paramName.c_str()) ; @@ -96,8 +98,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir, while ((dp = readdir(dirp)) != NULL) { len = strlen(dp->d_name); if ( !strcmp( &(dp->d_name[len - 4]) , ".csv")) { - full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; - sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); + size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2; + 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()) ) { closedir(dirp) ; stream = new Csv(full_path , (char *)paramName.c_str()) ; @@ -113,8 +116,9 @@ DataStream* DataStreamFactory::create( const char* iRunDir, while ((dp = readdir(dirp)) != NULL) { len = strlen(dp->d_name); if ( !strcmp( &(dp->d_name[len - 4]) , ".mat")) { - full_path = (char*) malloc (runDir.length() + strlen(dp->d_name) + 2) ; - sprintf(full_path, "%s/%s", runDir.c_str(), dp->d_name); + size_t full_path_len = runDir.length() + strlen(dp->d_name) + 2; + 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 , (char *)paramName.c_str(), (char *)timeName ) ) { diff --git a/trick_source/data_products/Log/ExternalProgram.cpp b/trick_source/data_products/Log/ExternalProgram.cpp index faf79f8b..959f4bb3 100644 --- a/trick_source/data_products/Log/ExternalProgram.cpp +++ b/trick_source/data_products/Log/ExternalProgram.cpp @@ -18,7 +18,7 @@ ExternalProgram::ExternalProgram( const char* sharedLibName, // Open up external plugin program progHandle_ = dlopen(sharedLibName, RTLD_LAZY); 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); fputs(msg, stderr); exit(1); diff --git a/trick_source/data_products/Log/darwin_dl.c b/trick_source/data_products/Log/darwin_dl.c index 09402b66..04f8303d 100644 --- a/trick_source/data_products/Log/darwin_dl.c +++ b/trick_source/data_products/Log/darwin_dl.c @@ -39,7 +39,7 @@ void *dlsym(void *handle, char *funcname) NSSymbol symbol; int cb = strlen(funcname) + 2; char *symname = (char *) alloca(cb); - sprintf(symname, "_%s", funcname); + snprintf(symname, cb, "_%s", funcname); dyn_error = NULL; @@ -47,7 +47,7 @@ void *dlsym(void *handle, char *funcname) if (symbol) { return (void *) NSAddressOfSymbol(symbol); } else { - sprintf(dyn_buf, "Symbol [%s] not found", symname); + snprintf(dyn_buf, sizeof(dyn_buf), "Symbol [%s] not found", symname); dyn_error = dyn_buf; return (void *) NULL; } diff --git a/trick_source/data_products/Log/log.cpp b/trick_source/data_products/Log/log.cpp index 96ed8f59..b51b0f1a 100644 --- a/trick_source/data_products/Log/log.cpp +++ b/trick_source/data_products/Log/log.cpp @@ -375,18 +375,18 @@ int LogData::openCurrBinaryFile() // Construct extension if (currBinExtension_ < 10) { - sprintf(extension, "00%d", currBinExtension_); + snprintf(extension, sizeof(extension), "00%d", currBinExtension_); } else if (currBinExtension_ < 100) { - sprintf(extension, "0%d", currBinExtension_); + snprintf(extension, sizeof(extension), "0%d", currBinExtension_); } else { - sprintf(extension, "%d", currBinExtension_); + snprintf(extension, sizeof(extension), "%d", currBinExtension_); } // Construct binary filename len = strlen(binFilePath_) + strlen(binFileName_) + strlen(extension) + 3; 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 if (access(file, F_OK | R_OK) == -1) { @@ -454,11 +454,11 @@ int LogData::getNumRecords() // Construct extension if (ii < 10) { - sprintf(extension, "00%d", ii); + snprintf(extension, sizeof(extension), "00%d", ii); } else if (ii < 100) { - sprintf(extension, "0%d", ii); + snprintf(extension, sizeof(extension), "0%d", ii); } else { - sprintf(extension, "%d", ii); + snprintf(extension, sizeof(extension), "%d", ii); } // Allocate & construct file name @@ -466,7 +466,7 @@ int LogData::getNumRecords() len = strlen(binFilePath_) + strlen(binFileName_) + strlen(extension) + 3; file = new char[len]; - sprintf(file, "%s/%s.%s", binFilePath_, + snprintf(file, len, "%s/%s.%s", binFilePath_, binFileName_, extension); fpTmp = fopen(file, "r"); @@ -1487,7 +1487,7 @@ int LogGroup::getHeaders() len = strlen(dp->d_name) + strlen(pathToBinaryData_) + 2 ; full_header_name = (char*) malloc ( len ) ; - sprintf(full_header_name, "%s/%s", + snprintf(full_header_name, len, "%s/%s", pathToBinaryData_, dp->d_name); if (!strncmp(dp->d_name, "log_", 4) && is04BinaryHeader_(full_header_name)) { diff --git a/trick_source/data_products/Log/parseLogHeader.cpp b/trick_source/data_products/Log/parseLogHeader.cpp index 05056781..55f0db18 100644 --- a/trick_source/data_products/Log/parseLogHeader.cpp +++ b/trick_source/data_products/Log/parseLogHeader.cpp @@ -56,7 +56,7 @@ int LogGroup::parseLogHeaders() headerName = new char[len]; // Full path of log header - sprintf(headerName, "%s/%s", pathToBinaryData_, headers_[i]); + snprintf(headerName, len, "%s/%s", pathToBinaryData_, headers_[i]); // Open log header if ((fp_ = fopen(headerName, "r")) == NULL) { diff --git a/trick_source/sim_services/CheckPointAgent/ClassicCheckPointerAgent.cpp b/trick_source/sim_services/CheckPointAgent/ClassicCheckPointerAgent.cpp index 466fb4d4..675a28e1 100644 --- a/trick_source/sim_services/CheckPointAgent/ClassicCheckPointerAgent.cpp +++ b/trick_source/sim_services/CheckPointAgent/ClassicCheckPointerAgent.cpp @@ -228,12 +228,11 @@ static int getCompositeSubReference( char* reference_name /* destination buffer of composite subreference */ ) { - int j, k, m; + int j, m; long offset; int my_index[9]; int ret; int size, last_size; - int temp_size; char* rAddr = (char*)reference_address; char* sAddr = (char*)structure_address; @@ -263,7 +262,7 @@ static int getCompositeSubReference( if (referenceOffset == 0) { reference_name[0] = '\0' ; } else if (referenceOffset > 0) { - sprintf(reference_name, " + %ld" , referenceOffset); + snprintf(reference_name, (size_t)256, " + %ld" , referenceOffset); } else { return 1; // ERROR } @@ -273,7 +272,7 @@ static int getCompositeSubReference( /******************************************************************************/ /* 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 (Ai->type != TRICK_STRUCTURED) { @@ -310,7 +309,9 @@ static int getCompositeSubReference( } 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; } @@ -325,7 +326,9 @@ static int getCompositeSubReference( ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset, (ATTRIBUTES *) Ai->attr, buf); 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 { return 1; // ERROR. } @@ -354,7 +357,9 @@ static int getCompositeSubReference( 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 */ @@ -379,7 +384,9 @@ static int getCompositeSubReference( ret = getCompositeSubReference( rAddr, left_type, sAddr + Ai->offset + offset, (ATTRIBUTES *) Ai->attr, buf); 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 { return 1; // ERROR } diff --git a/trick_source/sim_services/CheckPointAgent/input_parser.y b/trick_source/sim_services/CheckPointAgent/input_parser.y index 476cb28e..ad6de413 100644 --- a/trick_source/sim_services/CheckPointAgent/input_parser.y +++ b/trick_source/sim_services/CheckPointAgent/input_parser.y @@ -348,8 +348,9 @@ units_string: NAME { $$ = $1; } | NAME '.' NAME '.' { - $$ = (char*)malloc( strlen($1) + strlen($3) + 3 ); - sprintf($$, "%s.%s.", $1,$3); + size_t m_size = strlen($1) + strlen($3) + 3; + $$ = (char*)malloc(m_size); + snprintf($$, m_size, "%s.%s.", $1,$3); free($1); free($3); } @@ -358,23 +359,24 @@ units_string: NAME { } | I_CON { if ($1 == 1) { - $$ = (char*)malloc(2); - sprintf($$, "1"); + size_t m_size = 2; + $$ = (char*)malloc(m_size); + snprintf($$, m_size, "1"); } else { return (MM_INVALID_UNITS); } } | units_string '*' NAME { - int len = strlen($1) + strlen($3); - $$ = (char*)malloc((size_t)len+2) ; - sprintf($$, "%s*%s",$1,$3); + size_t m_size = strlen($1) + strlen($3) + 2; + $$ = (char*)malloc(m_size) ; + snprintf($$, m_size, "%s*%s",$1,$3); free($1); free($3); } | units_string '/' NAME { - int len = strlen($1) + strlen($3); - $$ = (char*)malloc((size_t)len+2) ; - sprintf($$, "%s/%s",$1,$3); + size_t m_size = strlen($1) + strlen($3) + 2; + $$ = (char*)malloc(m_size) ; + snprintf($$, m_size, "%s/%s",$1,$3); free($1); free($3); } @@ -432,7 +434,7 @@ param: NAME { $$.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); strcpy($$.reference , temp) ; @@ -469,9 +471,9 @@ param: NAME { $$.num_index_left = $$.attr->num_index; if ($2 == 1) { - sprintf(temp , "%s->%s" , $$.reference, $3) ; + snprintf(temp ,sizeof(temp), "%s->%s" , $$.reference, $3) ; } else { - sprintf(temp , "%s.%s" , $$.reference, $3) ; + snprintf(temp ,sizeof(temp), "%s.%s" , $$.reference, $3) ; } } else { diff --git a/trick_source/sim_services/CommandLineArguments/CommandLineArguments.cpp b/trick_source/sim_services/CommandLineArguments/CommandLineArguments.cpp index 8926d030..5a431fa8 100644 --- a/trick_source/sim_services/CommandLineArguments/CommandLineArguments.cpp +++ b/trick_source/sim_services/CommandLineArguments/CommandLineArguments.cpp @@ -119,11 +119,10 @@ int Trick::CommandLineArguments::process_sim_args(int nargs , char **args) { char *buf, *buf2; size_t found ; - int ii ; argc = nargs ; 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]) ; } @@ -195,7 +194,7 @@ int Trick::CommandLineArguments::process_sim_args(int nargs , char **args) { 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 (ii == ( argc - 1 )) { 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) ; 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_hour , curr_time->tm_min , curr_time->tm_sec ); diff --git a/trick_source/sim_services/DataRecord/DRAscii.cpp b/trick_source/sim_services/DataRecord/DRAscii.cpp index 6635c6f6..1d6f80ce 100644 --- a/trick_source/sim_services/DataRecord/DRAscii.cpp +++ b/trick_source/sim_services/DataRecord/DRAscii.cpp @@ -56,7 +56,8 @@ int Trick::DRAscii::format_specific_init() { } /* 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 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) ; + size_t writer_buf_spare = writer_buff + writer_buff_size - buf; + switch (DI->ref->attr->type) { case TRICK_CHARACTER: - sprintf(buf, "%c", *((char *) address)); + snprintf(buf, writer_buf_spare, "%c", *((char *) address)); break; case TRICK_UNSIGNED_CHARACTER: #if ( __linux | __sgi ) case TRICK_BOOLEAN: #endif - sprintf(buf, "%u", *((unsigned char *) address)); + snprintf(buf, writer_buf_spare, "%u", *((unsigned char *) address)); break; case TRICK_STRING: - sprintf(buf, "%s", *((char **) address)); + snprintf(buf, writer_buf_spare, "%s", *((char **) address)); break; case TRICK_SHORT: - sprintf(buf, "%d", *((short *) address)); + snprintf(buf, writer_buf_spare, "%d", *((short *) address)); break; case TRICK_UNSIGNED_SHORT: - sprintf(buf, "%u", *((unsigned short *) address)); + snprintf(buf, writer_buf_spare, "%u", *((unsigned short *) address)); break; case TRICK_ENUMERATED: @@ -211,45 +214,45 @@ int Trick::DRAscii::copy_data_ascii_item( Trick::DataRecordBuffer * DI, int item #if ( __sun | __APPLE__ ) case TRICK_BOOLEAN: #endif - sprintf(buf, "%d", *((int *) address)); + snprintf(buf, writer_buf_spare, "%d", *((int *) address)); break; case TRICK_UNSIGNED_INTEGER: - sprintf(buf, "%u", *((unsigned int *) address)); + snprintf(buf, writer_buf_spare, "%u", *((unsigned int *) address)); break; case TRICK_LONG: - sprintf(buf, "%ld", *((long *) address)); + snprintf(buf, writer_buf_spare, "%ld", *((long *) address)); break; case TRICK_UNSIGNED_LONG: - sprintf(buf, "%lu", *((unsigned long *) address)); + snprintf(buf, writer_buf_spare, "%lu", *((unsigned long *) address)); break; 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; 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; case TRICK_BITFIELD: 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; 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); - sprintf(buf, "%lu", bf); + snprintf(buf, writer_buf_spare, "%lu", bf); break; case TRICK_LONG_LONG: - sprintf(buf, "%lld", *((long long *) address)); + snprintf(buf, writer_buf_spare, "%lld", *((long long *) address)); break; case TRICK_UNSIGNED_LONG_LONG: - sprintf(buf, "%llu", *((unsigned long long *) address)); + snprintf(buf, writer_buf_spare, "%llu", *((unsigned long long *) address)); break; default: break; diff --git a/trick_source/sim_services/DataRecord/DataRecordGroup.cpp b/trick_source/sim_services/DataRecord/DataRecordGroup.cpp index 8ccabf6b..7429d24a 100644 --- a/trick_source/sim_services/DataRecord/DataRecordGroup.cpp +++ b/trick_source/sim_services/DataRecord/DataRecordGroup.cpp @@ -449,28 +449,28 @@ int Trick::DataRecordGroup::checkpoint() { void Trick::DataRecordGroup::clear_checkpoint_vars() { 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) ; } 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) ; } 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) ; } 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) ; diff --git a/trick_source/sim_services/Executive/Executive_fpe_handler.cpp b/trick_source/sim_services/Executive/Executive_fpe_handler.cpp index 3d3a0948..127693bb 100644 --- a/trick_source/sim_services/Executive/Executive_fpe_handler.cpp +++ b/trick_source/sim_services/Executive/Executive_fpe_handler.cpp @@ -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. - 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 char command[1024]; 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); } 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()); system(command); } @@ -90,11 +90,11 @@ void Trick::Executive::fpe_handler(siginfo_t * sip __attribute__((unused)) ) { if (_NSGetExecutablePath(path, &size) == 0 ) { if (attach_debugger == true) { 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); } else if (stack_trace == true ) { 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()); system(command); } diff --git a/trick_source/sim_services/Executive/Executive_process_sim_args.cpp b/trick_source/sim_services/Executive/Executive_process_sim_args.cpp index 342a4191..10c61d00 100644 --- a/trick_source/sim_services/Executive/Executive_process_sim_args.cpp +++ b/trick_source/sim_services/Executive/Executive_process_sim_args.cpp @@ -37,7 +37,7 @@ int Trick::Executive::process_sim_args() { argv = command_line_args_get_argv() ; /* Save off a usage statement for messages */ - sprintf(buf, "%s", "\n\n" + snprintf(buf, sizeof(buf), "%s", "\n\n" "USAGE: S_main_.exe [option...]\n\n" " RUN_/\n" " Every Trick simulation needs an input file.\n" diff --git a/trick_source/sim_services/Executive/Executive_signal_handler.cpp b/trick_source/sim_services/Executive/Executive_signal_handler.cpp index fb0502f6..8d5cb67f 100644 --- a/trick_source/sim_services/Executive/Executive_signal_handler.cpp +++ b/trick_source/sim_services/Executive/Executive_signal_handler.cpp @@ -62,10 +62,10 @@ void Trick::Executive::signal_handler(int sig) { #if __linux char command[1024]; 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); } 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()); system(command); } diff --git a/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp b/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp index 79bcc9ee..3e085229 100644 --- a/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp +++ b/trick_source/sim_services/Executive/Executive_write_s_job_execution.cpp @@ -37,7 +37,7 @@ int Trick::Executive::write_s_job_execution(FILE *fp) { /* Get full path to S_job_execution */ 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 */ if (access(output_dir.c_str(), F_OK) != 0) { diff --git a/trick_source/sim_services/Executive/Executive_write_s_run_summary.cpp b/trick_source/sim_services/Executive/Executive_write_s_run_summary.cpp index 3530057c..e5a9bb99 100644 --- a/trick_source/sim_services/Executive/Executive_write_s_run_summary.cpp +++ b/trick_source/sim_services/Executive/Executive_write_s_run_summary.cpp @@ -31,7 +31,7 @@ int Trick::Executive::write_s_run_summary(FILE *fp) { /* Get full path to S_run_summary */ 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. */ if ((fp = fopen(buf, "w")) == NULL) { diff --git a/trick_source/sim_services/FrameLog/FrameLog.cpp b/trick_source/sim_services/FrameLog/FrameLog.cpp index 95faa7b9..b380f11b 100644 --- a/trick_source/sim_services/FrameLog/FrameLog.cpp +++ b/trick_source/sim_services/FrameLog/FrameLog.cpp @@ -578,7 +578,7 @@ int Trick::FrameLog::shutdown() { /** @li Manually create the log_timeline and log_timeline_init files from saved timeline data. */ 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) { message_publish(MSG_ERROR, "Could not open log_timeline.csv file for Job Timeline Logging\n") ; exit(0); @@ -590,7 +590,7 @@ int Trick::FrameLog::shutdown() { } 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) { message_publish(MSG_ERROR, "Could not open log_timeline_init.csv file for Job Timeline Logging\n") ; exit(0); @@ -737,7 +737,7 @@ int Trick::FrameLog::create_DP_job_files() { std::vector::iterator job_iterator; FILE *fpx; - int pages, plots, total_plots, vcells, dot; + unsigned int pages, plots, total_plots, vcells, dot; char *bg_color; double time_scale; std::string DP_buff; @@ -830,7 +830,7 @@ int Trick::FrameLog::create_DP_job_files() { if ( ii == 0 ) { DP_buff = DP_dir + "/DP_rt_userjobs.xml"; } else { - sprintf(numstr, "%d", ii); + snprintf(numstr, sizeof(numstr), "%d", ii); DP_buff = DP_dir + "/DP_rt_userjobs_C" + numstr + ".xml"; } diff --git a/trick_source/sim_services/InputProcessor/MTV.cpp b/trick_source/sim_services/InputProcessor/MTV.cpp index e2767c64..414b0f32 100644 --- a/trick_source/sim_services/InputProcessor/MTV.cpp +++ b/trick_source/sim_services/InputProcessor/MTV.cpp @@ -100,28 +100,28 @@ int Trick::MTV::send_event_data() { int jj; 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); - sprintf(varname, "%s[%u][0].active", mtv_name,ii); + snprintf(varname, sizeof(varname), "%s[%u][0].active", mtv_name,ii); 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); - 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); - 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); - 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); 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); } 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); } 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); } } diff --git a/trick_source/sim_services/MemoryManager/MemoryManager_get_stl_dependencies.cpp b/trick_source/sim_services/MemoryManager/MemoryManager_get_stl_dependencies.cpp index dbd3afe2..8f111bcb 100644 --- a/trick_source/sim_services/MemoryManager/MemoryManager_get_stl_dependencies.cpp +++ b/trick_source/sim_services/MemoryManager/MemoryManager_get_stl_dependencies.cpp @@ -130,7 +130,7 @@ void Trick::MemoryManager::get_stl_dependencies_in_arrayed_class( curr_dim_size = attr->index[curr_dim].size; for (ii = 0; ii < curr_dim_size; ii++) { char index[16] ; - sprintf(index, "[%d]", ii) ; + snprintf(index, sizeof(index), "[%d]", ii) ; 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); } else { @@ -183,7 +183,7 @@ void Trick::MemoryManager::get_stl_dependencies_in_intrinsic( std::string name , int ii; for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) { 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); } } diff --git a/trick_source/sim_services/MemoryManager/MemoryManager_restore_stls.cpp b/trick_source/sim_services/MemoryManager/MemoryManager_restore_stls.cpp index fe849792..49d0c801 100644 --- a/trick_source/sim_services/MemoryManager/MemoryManager_restore_stls.cpp +++ b/trick_source/sim_services/MemoryManager/MemoryManager_restore_stls.cpp @@ -135,7 +135,7 @@ void Trick::MemoryManager::restore_stls_in_arrayed_class( curr_dim_size = attr->index[curr_dim].size; for (ii = 0; ii < curr_dim_size; ii++) { char index[16] ; - sprintf(index, "[%d]", ii) ; + snprintf(index, sizeof(index), "[%d]", ii) ; if (curr_dim < attr->num_index - 1) { restore_stls_in_arrayed_class( name + index, address, attr, curr_dim + 1, offset * curr_dim_size + ii); } else { @@ -188,7 +188,7 @@ void Trick::MemoryManager::restore_stls_in_intrinsic( std::string name , void* a int ii; for (ii=0 ; ii< attr->index[curr_dim].size ; ii++) { 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); } } diff --git a/trick_source/sim_services/MemoryManager/MemoryManager_write_checkpoint.cpp b/trick_source/sim_services/MemoryManager/MemoryManager_write_checkpoint.cpp index 141ba0ba..dc2145ba 100644 --- a/trick_source/sim_services/MemoryManager/MemoryManager_write_checkpoint.cpp +++ b/trick_source/sim_services/MemoryManager/MemoryManager_write_checkpoint.cpp @@ -35,10 +35,10 @@ void Trick::MemoryManager::execute_checkpoint( std::ostream& out_s ) { /** Generate temporary names for anonymous variables. */ if (alloc_info->name == NULL) { 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); } 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); /** @b NOTE: We should not write declarations for external anonymous variables, because we should not reload them.*/ diff --git a/trick_source/sim_services/MemoryManager/ref_parser.y b/trick_source/sim_services/MemoryManager/ref_parser.y index c43c4d03..e7b9485a 100644 --- a/trick_source/sim_services/MemoryManager/ref_parser.y +++ b/trick_source/sim_services/MemoryManager/ref_parser.y @@ -170,7 +170,7 @@ param: NAME { /* create a new reference string because previous nodes may refer to old strings */ $$.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) ; strcpy($$.reference , temp) ; diff --git a/trick_source/sim_services/MemoryManager/wcs_ext.c b/trick_source/sim_services/MemoryManager/wcs_ext.c index 0b06a81f..9ec362e0 100644 --- a/trick_source/sim_services/MemoryManager/wcs_ext.c +++ b/trick_source/sim_services/MemoryManager/wcs_ext.c @@ -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. */ if (wcint == '\'') { - sprintf(work_s, "\\\'"); + snprintf(work_s, sizeof(work_s), "\\\'"); } else if (wcint == '\"') { - sprintf(work_s, "\\\""); + snprintf(work_s, sizeof(work_s), "\\\""); } else if (wcint == '\?') { - sprintf(work_s, "\\\?"); + snprintf(work_s, sizeof(work_s), "\\\?"); } else if (wcint == '\\') { - sprintf(work_s, "\\\\"); + snprintf(work_s, sizeof(work_s), "\\\\"); } else { len = wcrtomb(work_s, (wchar_t) wcint, NULL); 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. */ if (wcint <= 0xFF) { if (wcint == '\a') { - sprintf(work_s, "\\a"); + snprintf(work_s, sizeof(work_s), "\\a"); } else if (wcint == '\b') { - sprintf(work_s, "\\b"); + snprintf(work_s, sizeof(work_s), "\\b"); } else if (wcint == '\f') { - sprintf(work_s, "\\f"); + snprintf(work_s, sizeof(work_s), "\\f"); } else if (wcint == '\n') { - sprintf(work_s, "\\n"); + snprintf(work_s, sizeof(work_s), "\\n"); } else if (wcint == '\r') { - sprintf(work_s, "\\n"); + snprintf(work_s, sizeof(work_s), "\\n"); } else if (wcint == '\t') { - sprintf(work_s, "\\t"); + snprintf(work_s, sizeof(work_s), "\\t"); } else if (wcint == '\v') { - sprintf(work_s, "\\v"); + snprintf(work_s, sizeof(work_s), "\\v"); } else { - sprintf(work_s, "\\x%02x", wcint); + snprintf(work_s, sizeof(work_s), "\\x%02x", wcint); } } else if (wcint <= 0xFFFF) { - sprintf(work_s, "\\u%04X", wcint); + snprintf(work_s, sizeof(work_s), "\\u%04X", wcint); } else { - sprintf(work_s, "\\U%08X", wcint); + snprintf(work_s, sizeof(work_s), "\\U%08X", wcint); } } diff --git a/trick_source/sim_services/Message/MessagePublisher.cpp b/trick_source/sim_services/Message/MessagePublisher.cpp index 3e108084..3a108f95 100644 --- a/trick_source/sim_services/Message/MessagePublisher.cpp +++ b/trick_source/sim_services/Message/MessagePublisher.cpp @@ -27,7 +27,7 @@ Trick::MessagePublisher::MessagePublisher() { void Trick::MessagePublisher::set_print_format() { 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() { @@ -52,7 +52,7 @@ int Trick::MessagePublisher::publish(int level , std::string message) { date = time(NULL) ; strftime(date_buf, (size_t) 20, "%Y/%m/%d,%H:%M:%S", localtime(&date)); (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 , (long long)((double)(tics % tics_per_sec) * (double)(pow(10 , num_digits)/tics_per_sec)) ) ; header = header_buf ; diff --git a/trick_source/sim_services/MonteCarlo/MonteVarCalculated.cpp b/trick_source/sim_services/MonteCarlo/MonteVarCalculated.cpp index ee067d4e..34be915d 100644 --- a/trick_source/sim_services/MonteCarlo/MonteVarCalculated.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteVarCalculated.cpp @@ -34,36 +34,36 @@ std::string Trick::MonteVarCalculated::get_next_value() { switch (ref2->attr->type) { case TRICK_CHARACTER: case TRICK_UNSIGNED_CHARACTER: - sprintf(buffer, "%d", *(char *)ref2->address); + snprintf(buffer, sizeof(buffer), "%d", *(char *)ref2->address); value = buffer; break; case TRICK_SHORT: case TRICK_UNSIGNED_SHORT: - sprintf(buffer, "%d", *(short *)ref2->address); + snprintf(buffer, sizeof(buffer), "%d", *(short *)ref2->address); value = buffer; break; case TRICK_INTEGER: case TRICK_UNSIGNED_INTEGER: case TRICK_LONG: case TRICK_UNSIGNED_LONG: - sprintf(buffer, "%ld", *(long *)ref2->address); + snprintf(buffer, sizeof(buffer), "%ld", *(long *)ref2->address); value = buffer; break; case TRICK_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; break; case TRICK_FLOAT: - sprintf(buffer, "%.15g", *(float *)ref2->address); + snprintf(buffer, sizeof(buffer), "%.15g", *(float *)ref2->address); value = buffer; break; case TRICK_DOUBLE: - sprintf(buffer, "%.15g", *(double *)ref2->address); + snprintf(buffer, sizeof(buffer), "%.15g", *(double *)ref2->address); value = buffer; break; default: - sprintf(buffer, "#Unsupported value type %d", ref2->attr->type) ; + snprintf(buffer, sizeof(buffer), "#Unsupported value type %d", ref2->attr->type) ; break ; } diff --git a/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp b/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp index 0ec9ed86..ee0e1c79 100644 --- a/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteVarFile.cpp @@ -72,7 +72,7 @@ std::string Trick::MonteVarFile::get_next_value() { // Verify the input column number is valid. if ((column == 0) || (column > ntokens)) { 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); } @@ -105,7 +105,7 @@ std::string Trick::MonteVarFile::get_next_value() { } 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); return NULL; diff --git a/trick_source/sim_services/MonteCarlo/MonteVarRandom.cpp b/trick_source/sim_services/MonteCarlo/MonteVarRandom.cpp index 861b350a..3c36f07a 100644 --- a/trick_source/sim_services/MonteCarlo/MonteVarRandom.cpp +++ b/trick_source/sim_services/MonteCarlo/MonteVarRandom.cpp @@ -178,14 +178,14 @@ std::string Trick::MonteVarRandom::get_next_value() { } if (count >= 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); } } else { if (trick_gsl_rand(&randist, &return_value) != 0) { 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); } } @@ -194,16 +194,16 @@ std::string Trick::MonteVarRandom::get_next_value() { case TRICK_GSL_POISSON: // STL returns int, GSL returns unsigned int if (stlGenPtr) { - sprintf(buffer, " %d", return_value.ii); + snprintf(buffer, sizeof(buffer), " %d", return_value.ii); } else { - sprintf(buffer, " %u", return_value.ui); + snprintf(buffer, sizeof(buffer), " %u", return_value.ui); } value = buffer; break; case TRICK_GSL_GAUSS: case TRICK_GSL_FLAT: default: - sprintf(buffer, "%.15g", return_value.d); + snprintf(buffer, sizeof(buffer), "%.15g", return_value.d); value = buffer; break; } diff --git a/trick_source/sim_services/RealtimeSync/RealtimeSync.cpp b/trick_source/sim_services/RealtimeSync/RealtimeSync.cpp index 55ee2279..2dfa1bef 100644 --- a/trick_source/sim_services/RealtimeSync/RealtimeSync.cpp +++ b/trick_source/sim_services/RealtimeSync/RealtimeSync.cpp @@ -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); exec_freeze() ; } else { - sprintf(buf, "\nMaximum overrun condition exceeded:\n" + snprintf(buf, sizeof(buf), "\nMaximum overrun condition exceeded:\n" "consecutive overruns/allowed overruns: %d/%d\n" "total overrun time/allowed time: %f/%g\n", frame_overrun_cnt, rt_max_overrun_cnt, diff --git a/trick_source/sim_services/Timer/ITimer.cpp b/trick_source/sim_services/Timer/ITimer.cpp index 7adf091b..597f9d7d 100644 --- a/trick_source/sim_services/Timer/ITimer.cpp +++ b/trick_source/sim_services/Timer/ITimer.cpp @@ -119,7 +119,7 @@ int Trick::ITimer::start(double in_frame_time) { active = true ; } else { 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); } } diff --git a/trick_source/sim_services/VariableServer/VariableServerListenThread.cpp b/trick_source/sim_services/VariableServer/VariableServerListenThread.cpp index 46d6bc07..00f6e868 100644 --- a/trick_source/sim_services/VariableServer/VariableServerListenThread.cpp +++ b/trick_source/sim_services/VariableServer/VariableServerListenThread.cpp @@ -182,7 +182,7 @@ void * Trick::VariableServerListenThread::thread_body() { vst->wait_for_accept() ; pthread_mutex_unlock(&restart_pause) ; } 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() , command_line_args_get_input_file() , version.c_str() , user_tag.c_str(), (unsigned short)listen_dev.port ) ; diff --git a/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp b/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp index 87585492..8708e316 100644 --- a/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp +++ b/trick_source/sim_services/VariableServer/VariableServerThread_commands.cpp @@ -236,7 +236,7 @@ int Trick::VariableServerThread::var_exists(std::string in_name) { tc_write(&connection, (char *) buf1, 5); } else { /* 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) { 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); } else { // 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) { 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 ) { 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)) ; return(-1) ; } @@ -463,7 +463,7 @@ int Trick::VariableServerThread::transmit_file(std::string sie_file) { fseek(fp , 0L, SEEK_END) ; 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)) ; rewind(fp) ; diff --git a/trick_source/sim_services/VariableServer/VariableServerThread_write_data.cpp b/trick_source/sim_services/VariableServer/VariableServerThread_write_data.cpp index 59a064ec..651e1462 100644 --- a/trick_source/sim_services/VariableServer/VariableServerThread_write_data.cpp +++ b/trick_source/sim_services/VariableServer/VariableServerThread_write_data.cpp @@ -22,7 +22,6 @@ extern "C" { int Trick::VariableServerThread::write_binary_data( int Start, char *buf1, const std::vector& given_vars, VS_MESSAGE_TYPE message_type) { - int vars = 0; int i; int ret ; int HeaderSize, MessageSize; @@ -178,13 +177,13 @@ int Trick::VariableServerThread::write_binary_data( int Start, char *buf1, const return i; } -int Trick::VariableServerThread::write_ascii_data(char * dest_buf, const std::vector& given_vars, VS_MESSAGE_TYPE message_type ) { +int Trick::VariableServerThread::write_ascii_data(char * dest_buf, size_t dest_buf_size, const std::vector& 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]; - 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) { 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; } 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 giv return 0; } 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); } } } diff --git a/trick_source/sim_services/VariableServer/VariableServerThread_write_stdio.cpp b/trick_source/sim_services/VariableServer/VariableServerThread_write_stdio.cpp index 462bd6a0..684f44d6 100644 --- a/trick_source/sim_services/VariableServer/VariableServerThread_write_stdio.cpp +++ b/trick_source/sim_services/VariableServer/VariableServerThread_write_stdio.cpp @@ -6,7 +6,7 @@ int Trick::VariableServerThread::write_stdio(int stream, std::string text) { 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 *) text.c_str() , text.length()) ; return 0 ; diff --git a/trick_source/sim_services/VariableServer/vs_format_ascii.cpp b/trick_source/sim_services/VariableServer/vs_format_ascii.cpp index 8c4d7559..56855ac7 100644 --- a/trick_source/sim_services/VariableServer/vs_format_ascii.cpp +++ b/trick_source/sim_services/VariableServer/vs_format_ascii.cpp @@ -22,7 +22,7 @@ size_t escape_str(const char *in_s, char *out_s); #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) */ REF2 * ref ; @@ -41,7 +41,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { case TRICK_CHARACTER: 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 { /* All but last dim specified, leaves a char array */ escape_str((char *) buf_ptr, value); @@ -50,7 +50,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { break; case TRICK_UNSIGNED_CHARACTER: 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 { /* All but last dim specified, leaves a char array */ escape_str((char *) buf_ptr, value); @@ -60,7 +60,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { case TRICK_WCHAR:{ 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 { // convert wide char string char string 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 ) 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; #endif 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; 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; case TRICK_INTEGER: @@ -115,18 +115,18 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { #if ( __sun | __APPLE__ ) case TRICK_BOOLEAN: #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; 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; 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; 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; case TRICK_LONG: { @@ -134,7 +134,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { if (var->conversion_factor != cv_get_trivial()) { l = (long)cv_convert_double(var->conversion_factor, l); } - sprintf(value, "%s%ld", value, l); + snprintf(value, value_size, "%s%ld", value, l); break; } @@ -143,16 +143,16 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { if (var->conversion_factor != cv_get_trivial()) { 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; } 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; 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; case TRICK_LONG_LONG: { @@ -160,7 +160,7 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { if (var->conversion_factor != cv_get_trivial()) { 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; } @@ -169,12 +169,12 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { if (var->conversion_factor != cv_get_trivial()) { 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; } case TRICK_NUMBER_OF_TYPES: - sprintf(value, "BAD_REF" ); + snprintf(value, value_size, "BAD_REF" ); break; default:{ @@ -191,9 +191,9 @@ int vs_format_ascii(Trick::VariableReference * var, char *value) { if (ref->units) { if ( ref->attr->mods & TRICK_MODS_UNITSDASHDASH ) { - sprintf(value, "%s {--}", value); + snprintf(value, value_size, "%s {--}", value); } 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'; } else { if (ch == '\a') { - sprintf(work_s, "\\a"); + snprintf(work_s, sizeof(work_s), "\\a"); } else if (ch == '\b') { - sprintf(work_s, "\\b"); + snprintf(work_s, sizeof(work_s), "\\b"); } else if (ch == '\f') { - sprintf(work_s, "\\f"); + snprintf(work_s, sizeof(work_s), "\\f"); } else if (ch == '\n') { - sprintf(work_s, "\\n"); + snprintf(work_s, sizeof(work_s), "\\n"); } else if (ch == '\r') { - sprintf(work_s, "\\n"); + snprintf(work_s, sizeof(work_s), "\\n"); } else if (ch == '\t') { - sprintf(work_s, "\\t"); + snprintf(work_s, sizeof(work_s), "\\t"); } else if (ch == '\v') { - sprintf(work_s, "\\v"); + snprintf(work_s, sizeof(work_s), "\\v"); } else { - sprintf(work_s, "\\x%02x", ch); + snprintf(work_s, sizeof(work_s), "\\x%02x", ch); } } out_len += strlen(work_s); diff --git a/trick_source/trick_swig/swig_double.cpp b/trick_source/trick_swig/swig_double.cpp index 3149a04e..8e509066 100644 --- a/trick_source/trick_swig/swig_double.cpp +++ b/trick_source/trick_swig/swig_double.cpp @@ -14,9 +14,9 @@ swig_double::swig_double() { char * swig_double::__str__() { 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 { - sprintf(str_output , "%g", value ) ; + snprintf(str_output , sizeof(str_output), "%g", value ) ; } return(str_output) ; } diff --git a/trick_source/trick_swig/swig_int.cpp b/trick_source/trick_swig/swig_int.cpp index ea26243d..ee5b9bcd 100644 --- a/trick_source/trick_swig/swig_int.cpp +++ b/trick_source/trick_swig/swig_int.cpp @@ -14,9 +14,9 @@ swig_int::swig_int() { char * swig_int::__str__() { 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 { - sprintf(str_output , "%lld", value ) ; + snprintf(str_output , sizeof(str_output), "%lld", value ) ; } return(str_output) ; } @@ -1211,13 +1211,13 @@ PyObject * swig_int::__float__() { PyObject * swig_int::__oct__() { char temp[32] ; - sprintf(temp , "0%o" , (unsigned int)value) ; + snprintf(temp, sizeof(temp), "0%o" , (unsigned int)value) ; return PyString_FromString(temp) ; } PyObject * swig_int::__hex__() { char temp[32] ; - sprintf(temp , "0x%llx" , value) ; + snprintf(temp, sizeof(temp), "0x%llx" , value) ; return PyString_FromString(temp) ; } diff --git a/trick_source/trick_utils/comm/src/tc_accept.c b/trick_source/trick_utils/comm/src/tc_accept.c index 53be7d09..2d076f27 100644 --- a/trick_source/trick_utils/comm/src/tc_accept.c +++ b/trick_source/trick_utils/comm/src/tc_accept.c @@ -31,7 +31,7 @@ int tc_accept_(TCDevice * listen_device, TCDevice * device, const char *file, in length = sizeof(s_in); 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 */ 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, file, line, "tc_accept: %s: connected to client using port %d\n", client_str, device->port); diff --git a/trick_source/trick_utils/comm/src/tc_blockio.c b/trick_source/trick_utils/comm/src/tc_blockio.c index ade19f51..dd1e124d 100644 --- a/trick_source/trick_utils/comm/src/tc_blockio.c +++ b/trick_source/trick_utils/comm/src/tc_blockio.c @@ -23,7 +23,7 @@ int tc_blockio(TCDevice * device, TCCommBlocking blockflag) } /* 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 blockflag = %d\n", client_str, blockflag); diff --git a/trick_source/trick_utils/comm/src/tc_connect.c b/trick_source/trick_utils/comm/src/tc_connect.c index 976b9e93..adcc35a1 100644 --- a/trick_source/trick_utils/comm/src/tc_connect.c +++ b/trick_source/trick_utils/comm/src/tc_connect.c @@ -59,7 +59,7 @@ int tc_connect_(TCDevice * device, const char *file, int line) if (device->client_tag[0] == '\0') { strcpy(device->client_tag, ""); } - 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); #ifdef __WIN32__ diff --git a/trick_source/trick_utils/comm/src/tc_disconnect.c b/trick_source/trick_utils/comm/src/tc_disconnect.c index a640f344..81858f2e 100644 --- a/trick_source/trick_utils/comm/src/tc_disconnect.c +++ b/trick_source/trick_utils/comm/src/tc_disconnect.c @@ -23,7 +23,7 @@ int tc_disconnect(TCDevice * device) /* 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); diff --git a/trick_source/trick_utils/comm/src/tc_read.c b/trick_source/trick_utils/comm/src/tc_read.c index 33a9e009..82994d65 100644 --- a/trick_source/trick_utils/comm/src/tc_read.c +++ b/trick_source/trick_utils/comm/src/tc_read.c @@ -46,7 +46,7 @@ int tc_read_(TCDevice * device, char *buffer, int size, const char *file, int li 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, "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) { error = tc_errno; 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); tc_disconnect(device); return (nbytes); diff --git a/trick_source/trick_utils/comm/src/tc_write.c b/trick_source/trick_utils/comm/src/tc_write.c index 51058c93..ecd4a692 100644 --- a/trick_source/trick_utils/comm/src/tc_write.c +++ b/trick_source/trick_utils/comm/src/tc_write.c @@ -41,7 +41,7 @@ int tc_write_(TCDevice * device, char *buffer, int size, const char *file, int l 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); /* 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) { error = tc_errno; 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); tc_disconnect(device); return (nbytes); diff --git a/trick_source/trick_utils/comm/src/trick_error_hndlr.c b/trick_source/trick_utils/comm/src/trick_error_hndlr.c index 531202b6..09a4b907 100644 --- a/trick_source/trick_utils/comm/src/trick_error_hndlr.c +++ b/trick_source/trick_utils/comm/src/trick_error_hndlr.c @@ -162,7 +162,7 @@ void trick_error_func_default(TrickErrorHndlr * error_hndlr, /* In: Error obj default: 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); strcpy(msg_buf, unknown); strcat(msg_buf, msg); diff --git a/trick_source/trick_utils/math/src/dLU_solver.c b/trick_source/trick_utils/math/src/dLU_solver.c index 07798415..d662896e 100644 --- a/trick_source/trick_utils/math/src/dLU_solver.c +++ b/trick_source/trick_utils/math/src/dLU_solver.c @@ -40,7 +40,7 @@ int dLU_solver(double **A, /* In: The input matrix [A] */ if (mode == 0 || mode == 1) { 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); } 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++) { 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]); return (TM_DIAG_SMALL); } diff --git a/trick_source/trick_utils/shm/src/tsm_init.c b/trick_source/trick_utils/shm/src/tsm_init.c index 40ffc374..b2532afc 100644 --- a/trick_source/trick_utils/shm/src/tsm_init.c +++ b/trick_source/trick_utils/shm/src/tsm_init.c @@ -60,7 +60,7 @@ int tsm_init(TSMDevice * shm_device) return (TSM_FAIL); } 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); // we will use our own key generation in my_ftok diff --git a/trick_source/trick_utils/unicode/src/unicode_utils.c b/trick_source/trick_utils/unicode/src/unicode_utils.c index 2fab5f1f..6289d38c 100644 --- a/trick_source/trick_utils/unicode/src/unicode_utils.c +++ b/trick_source/trick_utils/unicode/src/unicode_utils.c @@ -102,23 +102,23 @@ size_t escape_to_ascii(const char *in, char *out, size_t outSize) { state = ERROR_STATE; } else { // ASCII if (ch == '\a') { - sprintf(ascii_elements, "\\a"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\a"); } else if (ch == '\b') { - sprintf(ascii_elements, "\\b"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\b"); } else if (ch == '\f') { - sprintf(ascii_elements, "\\f"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\f"); } else if (ch == '\n') { - sprintf(ascii_elements, "\\n"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\n"); } else if (ch == '\r') { - sprintf(ascii_elements, "\\r"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\r"); } else if (ch == '\t') { - sprintf(ascii_elements, "\\t"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\t"); } else if (ch == '\v') { - sprintf(ascii_elements, "\\v"); + snprintf(ascii_elements, sizeof(ascii_elements), "\\v"); } else if (isprint(ch)) { - sprintf(ascii_elements, "%c",ch); + snprintf(ascii_elements, sizeof(ascii_elements), "%c",ch); } else { - sprintf(ascii_elements, "\\x%02x",ch); + snprintf(ascii_elements, sizeof(ascii_elements), "\\x%02x",ch); } size_t n_elements = strlen(ascii_elements); 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 state = 0; if (codePoint <= 0xffff) { - sprintf(ascii_elements, "\\u%04x", codePoint); + snprintf(ascii_elements, sizeof(ascii_elements), "\\u%04x", codePoint); } else { - sprintf(ascii_elements, "\\U%08x", codePoint); + snprintf(ascii_elements, sizeof(ascii_elements), "\\U%08x", codePoint); } size_t n_elements = strlen(ascii_elements); if (out != NULL) { diff --git a/trick_source/web/CivetServer/src/VariableServerSession.cpp b/trick_source/web/CivetServer/src/VariableServerSession.cpp index e3c1a5ea..85c0ddfc 100644 --- a/trick_source/web/CivetServer/src/VariableServerSession.cpp +++ b/trick_source/web/CivetServer/src/VariableServerSession.cpp @@ -208,7 +208,7 @@ int VariableServerSession::sendErrorMessage(const char* fmt, ... ) { (void) vsnprintf(errText, MAX_MSG_SIZE, fmt, args); va_end(args); - sprintf(msgText, "{ \"msg_type\" : \"error\",\n" + snprintf(msgText, sizeof(msgText), "{ \"msg_type\" : \"error\",\n" " \"error\" : \"%s\"}\n", errText); mg_websocket_write(connection, MG_WEBSOCKET_OPCODE_TEXT, msgText, strlen(msgText));