From: Arun Persaud Date: Mon, 13 Sep 2010 03:04:03 +0000 (-0700) Subject: security fix: replaced sprintf with snprintf X-Git-Url: http://winboard.nl/cgi-bin?a=commitdiff_plain;h=e80c98c04e951e5026a24531cd6316be962636b9;p=xboard.git security fix: replaced sprintf with snprintf replaced most sprintf with snprintf. There are still some left where for example a pointer is used and is allocated in the line before, which should be fine... and some others. --- diff --git a/args.h b/args.h index 9d3530f..00126f9 100644 --- a/args.h +++ b/args.h @@ -2,7 +2,7 @@ * args.c -- Option parsing and saving for X and Windows versions of XBoard * * Copyright 1991 by Digital Equipment Corporation, Maynard, - * Massachusetts. + * Massachusetts. * * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2008, 2009, 2010 Free Software Foundation, Inc. @@ -49,16 +49,16 @@ * along with this program. If not, see http://www.gnu.org/licenses/. * * *------------------------------------------------------------------------ - ** See the file ChangeLog for a revision history. + ** See the file ChangeLog for a revision history. */ // Note: this file is not a normal header, but contains executable code // for #inclusion in winboard.c and xboard.c, rather than separate compilation, -// so that it can make use of the proper context of #defined symbols and +// so that it can make use of the proper context of #defined symbols and // declarations in those files. typedef enum { - ArgString, ArgInt, ArgFloat, ArgBoolean, ArgTrue, ArgFalse, ArgNone, + ArgString, ArgInt, ArgFloat, ArgBoolean, ArgTrue, ArgFalse, ArgNone, ArgColor, ArgAttribs, ArgFilename, ArgBoardSize, ArgFont, ArgCommSettings, ArgSettingsFilename, ArgX, ArgY, ArgZ // [HGM] placement: for window-placement options stored relative to main window @@ -129,7 +129,7 @@ typedef char GetFunc(void *getClosure); void ParseArgs(GetFunc get, void *cl); // [HGM] this is an exact duplicate of something in winboard.c. Move to backend.c? -char *defaultTextAttribs[] = +char *defaultTextAttribs[] = { COLOR_SHOUT, COLOR_SSHOUT, COLOR_CHANNEL1, COLOR_CHANNEL, COLOR_KIBITZ, COLOR_TELL, COLOR_CHALLENGE, COLOR_REQUEST, COLOR_SEEK, COLOR_NORMAL, @@ -238,7 +238,7 @@ ArgDescriptor argDescriptors[] = { { "xtelnet", ArgFalse, (void *) &appData.useTelnet, FALSE, INVALID }, { "-telnet", ArgFalse, (void *) &appData.useTelnet, FALSE, INVALID }, { "telnetProgram", ArgFilename, (void *) &appData.telnetProgram, FALSE, (ArgIniType) TELNET_PROGRAM }, - { "internetChessserverHelper", ArgFilename, (void *) &appData.icsHelper, + { "internetChessserverHelper", ArgFilename, (void *) &appData.icsHelper, FALSE, INVALID }, // for XB { "icshelper", ArgFilename, (void *) &appData.icsHelper, FALSE, (ArgIniType) "" }, { "seekGraph", ArgBoolean, (void *) &appData.seekGraph, TRUE, (ArgIniType) FALSE }, @@ -307,7 +307,7 @@ ArgDescriptor argDescriptors[] = { { "popup", ArgTrue, (void *) &appData.popupMoveErrors, FALSE, INVALID }, { "xpopup", ArgFalse, (void *) &appData.popupMoveErrors, FALSE, INVALID }, { "-popup", ArgFalse, (void *) &appData.popupMoveErrors, FALSE, INVALID }, - { "popUpErrors", ArgBoolean, (void *) &appData.popupMoveErrors, + { "popUpErrors", ArgBoolean, (void *) &appData.popupMoveErrors, FALSE, INVALID }, /* only so that old WinBoard.ini files from betas can be read */ { "clockFont", ArgFont, (void *) CLOCK_FONT, TRUE, INVALID }, { "messageFont", ArgFont, (void *) MESSAGE_FONT, !XBOARD, INVALID }, @@ -540,9 +540,9 @@ ArgDescriptor argDescriptors[] = { { "polyglotDir", ArgFilename, (void *) &appData.polyglotDir, TRUE, (ArgIniType) "" }, { "usePolyglotBook", ArgBoolean, (void *) &appData.usePolyglotBook, TRUE, (ArgIniType) FALSE }, { "polyglotBook", ArgFilename, (void *) &appData.polyglotBook, TRUE, (ArgIniType) "" }, - { "bookDepth", ArgInt, (void *) &appData.bookDepth, TRUE, (ArgIniType) 12 }, - { "bookVariation", ArgInt, (void *) &appData.bookStrength, TRUE, (ArgIniType) 50 }, - { "defaultHashSize", ArgInt, (void *) &appData.defaultHashSize, TRUE, (ArgIniType) 64 }, + { "bookDepth", ArgInt, (void *) &appData.bookDepth, TRUE, (ArgIniType) 12 }, + { "bookVariation", ArgInt, (void *) &appData.bookStrength, TRUE, (ArgIniType) 50 }, + { "defaultHashSize", ArgInt, (void *) &appData.defaultHashSize, TRUE, (ArgIniType) 64 }, { "defaultCacheSizeEGTB", ArgInt, (void *) &appData.defaultCacheSizeEGTB, TRUE, (ArgIniType) 4 }, { "defaultPathEGTB", ArgFilename, (void *) &appData.defaultPathEGTB, TRUE, (ArgIniType) "c:\\egtb" }, { "language", ArgFilename, (void *) &appData.language, TRUE, (ArgIniType) "" }, @@ -709,8 +709,12 @@ void ExitArgError(char *msg, char *badArg) { char buf[MSG_SIZ]; + int len; + + len = snprintf(buf,MSG_SIZ, "%s %s", msg, badArg); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "ExitArgError: buffer truncated. Input: msg=%s badArg=%s\n", msg, badArg); - sprintf(buf, "%s %s", msg, badArg); DisplayFatalError(buf, 0, 2); exit(2); } @@ -751,13 +755,19 @@ Boolean ParseSettingsFile(char *name, char **addr) { FILE *f; - int ok; char buf[MSG_SIZ], fullname[MSG_SIZ]; + int ok,len; + char buf[MSG_SIZ], fullname[MSG_SIZ]; + ok = MySearchPath(installDir, name, fullname); - if(!ok && strchr(name, '.') == NULL) { // [HGM] append default file-name extension '.ini' when needed - sprintf(buf, "%s.ini", name); - ok = MySearchPath(installDir, buf, fullname); - } + if(!ok && strchr(name, '.') == NULL) + { // append default file-name extension '.ini' when needed + len = snprintf(buf,MSG_SIZ, "%s.ini", name); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "ParseSettingsFile: buffer truncated. Input: name=%s \n",name); + + ok = MySearchPath(installDir, buf, fullname); + } if (ok) { f = fopen(fullname, "r"); if (f != NULL) { @@ -843,7 +853,7 @@ ParseArgs(GetFunc get, void *cl) case NULLCHAR: start = NULLCHAR; break; - + case '}': ch = get(cl); start = NULLCHAR; @@ -854,7 +864,7 @@ ParseArgs(GetFunc get, void *cl) ch = get(cl); break; } - } + } } else if (ch == '\'' || ch == '"') { // Quoting with ' ' or " ", with \ as escape character. // Inconvenient for long strings that may contain Windows filenames. @@ -947,7 +957,7 @@ ParseArgs(GetFunc get, void *cl) break; case ArgX: - *(int *) ad->argLoc = ValidateInt(argValue) + wpMain.x; // [HGM] placement: translate stored relative to absolute + *(int *) ad->argLoc = ValidateInt(argValue) + wpMain.x; // [HGM] placement: translate stored relative to absolute break; case ArgY: @@ -956,7 +966,7 @@ ParseArgs(GetFunc get, void *cl) case ArgZ: *(int *) ad->argLoc = ValidateInt(argValue); - EnsureOnScreen(&wpMain.x, &wpMain.y, minX, minY); + EnsureOnScreen(&wpMain.x, &wpMain.y, minX, minY); break; case ArgFloat: @@ -1005,7 +1015,7 @@ ParseArgs(GetFunc get, void *cl) ParseTextAttribs(cc, argValue); // [HGM] wrapper for platform independency } break; - + case ArgBoardSize: ParseBoardSize(ad->argLoc, argValue); break; @@ -1084,7 +1094,7 @@ ParseIcsTextMenu(char *icsTextMenuString) p = t + 1; } e++; - } + } } void @@ -1175,22 +1185,34 @@ InitAppData(char *lpCmdLine) char *p = StrStr(appData.firstChessProgram, "WBopt"); static char *f = "first"; char buf[MSG_SIZ], *q = buf; - if(p != NULL) { // engine command line contains WinBoard options - sprintf(buf, p+6, f, f, f, f, f, f, f, f, f, f); // replace %s in them by "first" + int len; + + if(p != NULL) + { // engine command line contains WinBoard options + len = snprintf(buf, MSG_SIZ, p+6, f, f, f, f, f, f, f, f, f, f); // replace %s in them by "first" + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitAppData: buffer truncated.\n"); + ParseArgs(StringGet, &q); p[-1] = 0; // cut them offengine command line - } + } } // now do same for second chess program if(appData.secondChessProgram != NULL) { char *p = StrStr(appData.secondChessProgram, "WBopt"); static char *s = "second"; char buf[MSG_SIZ], *q = buf; - if(p != NULL) { // engine command line contains WinBoard options - sprintf(buf, p+6, s, s, s, s, s, s, s, s, s, s); // replace %s in them by "first" + int len; + + if(p != NULL) + { // engine command line contains WinBoard options + len = snprintf(buf,MSG_SIZ, p+6, s, s, s, s, s, s, s, s, s, s); // replace %s in them by "first" + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitAppData: buffer truncated.\n"); + ParseArgs(StringGet, &q); p[-1] = 0; // cut them offengine command line - } + } } /* Propagate options that affect others */ @@ -1203,7 +1225,7 @@ InitAppData(char *lpCmdLine) if ((!appData.noChessProgram && !chessProgram && !appData.icsActive) || (appData.icsActive && *appData.icsHost == NULLCHAR) || (chessProgram && (*appData.firstChessProgram == NULLCHAR || - *appData.secondChessProgram == NULLCHAR))) + *appData.secondChessProgram == NULLCHAR))) PopUpStartupDialog(); /* Make sure save files land in the right (?) directory */ @@ -1325,7 +1347,7 @@ SaveSettings(char* name) fprintf(f, OPTCHAR "%s" SEPCHAR "%g\n", ad->argName, *(float *)ad->argLoc); break; case ArgBoolean: - fprintf(f, OPTCHAR "%s" SEPCHAR "%s\n", ad->argName, + fprintf(f, OPTCHAR "%s" SEPCHAR "%s\n", ad->argName, (*(Boolean *)ad->argLoc) ? "true" : "false"); break; case ArgTrue: @@ -1368,6 +1390,7 @@ GetArgValue(char *name) { // retrieve (as text) current value of string or int argument given by name // (this is used for maing the values available in the adapter command) ArgDescriptor *ad; + int len; for (ad = argDescriptors; ad->argName != NULL; ad++) if (strcmp(ad->argName, name) == 0) break; @@ -1378,12 +1401,19 @@ GetArgValue(char *name) case ArgString: case ArgFilename: strncpy(name, *(char**) ad->argLoc, MSG_SIZ); + return TRUE; case ArgInt: - sprintf(name, "%d", *(int*) ad->argLoc); + len = snprintf(name, MSG_SIZ, "%d", *(int*) ad->argLoc); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "GetArgValue: buffer truncated.\n"); + return TRUE; case ArgBoolean: - sprintf(name, "%s", *(Boolean*) ad->argLoc ? "true" : "false"); + len = snprintf(name, MSG_SIZ, "%s", *(Boolean*) ad->argLoc ? "true" : "false"); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "GetArgValue: buffer truncated.\n"); + return TRUE; default: ; } diff --git a/backend.c b/backend.c index 4eaa5b1..67a1c1a 100644 --- a/backend.c +++ b/backend.c @@ -315,7 +315,6 @@ safeStrCpy( char *dst, const char *src, size_t count ) /* see for example: https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/854-BSI.html * * usage: safeStrCpy( stringA, stringB, sizeof(stringA)/sizeof(stringA[0]); - * */ assert( dst != NULL ); @@ -825,25 +824,41 @@ InitBackEnd1() first.hasOwnBookUCI = appData.firstHasOwnBookUCI; /* [AS] */ second.hasOwnBookUCI = appData.secondHasOwnBookUCI; /* [AS] */ - if (appData.firstProtocolVersion > PROTOVER || - appData.firstProtocolVersion < 1) { - char buf[MSG_SIZ]; - sprintf(buf, _("protocol version %d not supported"), - appData.firstProtocolVersion); - DisplayFatalError(buf, 0, 2); - } else { - first.protocolVersion = appData.firstProtocolVersion; - } + if (appData.firstProtocolVersion > PROTOVER + || appData.firstProtocolVersion < 1) + { + char buf[MSG_SIZ]; + int len; - if (appData.secondProtocolVersion > PROTOVER || - appData.secondProtocolVersion < 1) { - char buf[MSG_SIZ]; - sprintf(buf, _("protocol version %d not supported"), - appData.secondProtocolVersion); - DisplayFatalError(buf, 0, 2); - } else { - second.protocolVersion = appData.secondProtocolVersion; - } + len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"), + appData.firstProtocolVersion); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd1: buffer truncated.\n"); + + DisplayFatalError(buf, 0, 2); + } + else + { + first.protocolVersion = appData.firstProtocolVersion; + } + + if (appData.secondProtocolVersion > PROTOVER + || appData.secondProtocolVersion < 1) + { + char buf[MSG_SIZ]; + int len; + + len = snprintf(buf, MSG_SIZ, _("protocol version %d not supported"), + appData.secondProtocolVersion); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd1: buffer truncated.\n"); + + DisplayFatalError(buf, 0, 2); + } + else + { + second.protocolVersion = appData.secondProtocolVersion; + } if (appData.icsActive) { appData.clockMode = TRUE; /* changes dynamically in ICS mode */ @@ -874,6 +889,8 @@ InitBackEnd1() if (!appData.icsActive) { char buf[MSG_SIZ]; + int len; + /* Check for variants that are supported only in ICS mode, or not at all. Some that are accepted here nevertheless have bugs; see comments below. @@ -882,8 +899,11 @@ InitBackEnd1() switch (variant) { case VariantBughouse: /* need four players and two boards */ case VariantKriegspiel: /* need to hide pieces and move details */ - /* case VariantFischeRandom: (Fabien: moved below) */ - sprintf(buf, _("Variant %s supported only in ICS mode"), appData.variant); + /* case VariantFischeRandom: (Fabien: moved below) */ + len = snprintf(buf,MSG_SIZ, _("Variant %s supported only in ICS mode"), appData.variant); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd1: buffer truncated.\n"); + DisplayFatalError(buf, 0, 2); return; @@ -898,7 +918,10 @@ InitBackEnd1() case Variant35: case Variant36: default: - sprintf(buf, _("Unknown variant name %s"), appData.variant); + len = snprintf(buf, MSG_SIZ, _("Unknown variant name %s"), appData.variant); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd1: buffer truncated.\n"); + DisplayFatalError(buf, 0, 2); return; @@ -1049,18 +1072,22 @@ ParseTimeControl(tc, ti, mps) long tc2; char buf[MSG_SIZ], buf2[MSG_SIZ], *mytc = tc; int min, sec=0; - + int len; + if(ti >= 0 && !strchr(tc, '+') && !strchr(tc, '/') ) mps = 0; if(!strchr(tc, '+') && !strchr(tc, '/') && sscanf(tc, "%d:%d", &min, &sec) >= 1) sprintf(mytc=buf2, "%d", 60*min+sec); // convert 'classical' min:sec tc string to seconds if(ti > 0) { + if(mps) - sprintf(buf, ":%d/%s+%d", mps, mytc, ti); - else sprintf(buf, ":%s+%d", mytc, ti); + snprintf(buf, MSG_SIZ, ":%d/%s+%d", mps, mytc, ti); + else + snprintf(buf, MSG_SIZ, ":%s+%d", mytc, ti); } else { if(mps) - sprintf(buf, ":%d/%s", mps, mytc); - else sprintf(buf, ":%s", mytc); + snprintf(buf, MSG_SIZ, ":%d/%s", mps, mytc); + else + snprintf(buf, MSG_SIZ, ":%s", mytc); } fullTimeControlString = StrSave(buf); // this should now be in PGN format @@ -1137,7 +1164,7 @@ InitBackEnd3 P((void)) { GameMode initialMode; char buf[MSG_SIZ]; - int err; + int err, len; InitChessProgram(&first, startedFromSetupPosition); @@ -1153,14 +1180,18 @@ InitBackEnd3 P((void)) ConsoleCreate(); #endif err = establish(); - if (err != 0) { - if (*appData.icsCommPort != NULLCHAR) { - sprintf(buf, _("Could not open comm port %s"), - appData.icsCommPort); - } else { - snprintf(buf, sizeof(buf), _("Could not connect to host %s, port %s"), + if (err != 0) + { + if (*appData.icsCommPort != NULLCHAR) + len = snprintf(buf, MSG_SIZ, _("Could not open comm port %s"), + appData.icsCommPort); + else + len = snprintf(buf, MSG_SIZ, _("Could not connect to host %s, port %s"), appData.icsHost, appData.icsPort); - } + + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd3: buffer truncated.\n"); + DisplayFatalError(buf, err, 1); return; } @@ -1205,7 +1236,10 @@ InitBackEnd3 P((void)) } else if (StrCaseCmp(appData.initialMode, "Training") == 0) { initialMode = Training; } else { - sprintf(buf, _("Unknown initialMode %s"), appData.initialMode); + len = snprintf(buf, MSG_SIZ, _("Unknown initialMode %s"), appData.initialMode); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "InitBackEnd3: buffer truncated.\n"); + DisplayFatalError(buf, 0, 2); return; } @@ -1631,6 +1665,7 @@ StringToVariant(e) VariantClass v = VariantNormal; int i, found = FALSE; char buf[MSG_SIZ]; + int len; if (!e) return v; @@ -1806,7 +1841,10 @@ StringToVariant(e) v = VariantNormal; break; default: - sprintf(buf, _("Unknown wild type %d"), wnum); + len = snprintf(buf, MSG_SIZ, _("Unknown wild type %d"), wnum); + if( (len > MSG_SIZ) && appData.debugMode ) + fprintf(debugFP, "StringToVariant: buffer truncated.\n"); + DisplayError(buf, 0); v = VariantUnknown; break; @@ -1946,7 +1984,7 @@ TelnetRequest(ddww, option) break; default: ddwwStr = buf1; - sprintf(buf1, "%d", ddww); + snprintf(buf1,sizeof(buf1)/sizeof(buf1[0]), "%d", ddww); break; } switch (option) { @@ -1955,7 +1993,7 @@ TelnetRequest(ddww, option) break; default: optionStr = buf2; - sprintf(buf2, "%d", option); + snprintf(buf2,sizeof(buf2)/sizeof(buf2[0]), "%d", option); break; } fprintf(debugFP, ">%s %s ", ddwwStr, optionStr); @@ -2169,7 +2207,7 @@ AddAd(char *handle, char *rating, int base, int inc, char rated, char *type, in if(v == VariantLoadable) type = "setup"; else type = VariantName(v); } - sprintf(buf, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext); + snprintf(buf, MSG_SIZ, "%s (%s) %d %d %c %s%s", handle, rating, base, inc, rated, type, ext); if(nrOfSeekAds < MAX_SEEK_ADS-1) { if(seekAdList[nrOfSeekAds]) free(seekAdList[nrOfSeekAds]); ratingList[nrOfSeekAds] = -1; // for if seeker has no rating @@ -2251,7 +2289,7 @@ DrawSeekGraph() DrawSeekAxis(hMargin+5*(i%500==0), yy, hMargin-5, yy); // rating ticks if(i%500 == 0) { char buf[MSG_SIZ]; - sprintf(buf, "%d", i); + snprintf(buf, MSG_SIZ, "%d", i); DrawSeekText(buf, hMargin+squareSize/8+7, yy); } } @@ -2261,7 +2299,7 @@ DrawSeekGraph() DrawSeekAxis(xx, h-1-vMargin, xx, h-6-vMargin-3*(i%10==0)); // TC ticks if(i<=5 || (i>40 ? i%20 : i%10) == 0) { char buf[MSG_SIZ]; - sprintf(buf, "%d", i); + snprintf(buf, MSG_SIZ, "%d", i); DrawSeekText(buf, xx-2-3*(i>9), h-1-vMargin/2); } } @@ -2299,7 +2337,7 @@ int SeekGraphClick(ClickType click, int x, int y, int moving) return TRUE; } // on press 'hit', only show info if(moving == 2) return TRUE; // ignore right up-clicks on dot - sprintf(buf, "play %d\n", seekNrList[closest]); + snprintf(buf, MSG_SIZ, "play %d\n", seekNrList[closest]); SendToICS(ics_prefix); SendToICS(buf); return TRUE; // let incoming board of started game pop down the graph @@ -2565,13 +2603,13 @@ read_from_ics(isr, closure, data, count, error) if (loggedOn && !intfSet) { if (ics_type == ICS_ICC) { - sprintf(str, + snprintf(str, MSG_SIZ, "/set-quietly interface %s\n/set-quietly style 12\n", programVersion); if(appData.seekGraph && appData.autoRefresh) // [HGM] seekgraph strcat(str, "/set-2 51 1\n/set seek 1\n"); } else if (ics_type == ICS_CHESSNET) { - sprintf(str, "/style 12\n"); + snprintf(str, MSG_SIZ, "/style 12\n"); } else { safeStrCpy(str, "alias $ @\n$set interface ", sizeof(str)/sizeof(str[0])); strcat(str, programVersion); @@ -2595,7 +2633,7 @@ read_from_ics(isr, closure, data, count, error) parse[parse_pos] = NULLCHAR; if(chattingPartner>=0) { char mess[MSG_SIZ]; - sprintf(mess, "%s%s", talker, parse); + snprintf(mess, MSG_SIZ, "%s%s", talker, parse); OutputChatMessage(chattingPartner, mess); chattingPartner = -1; next_out = i+1; // [HGM] suppress printing in ICS window @@ -2624,7 +2662,7 @@ read_from_ics(isr, closure, data, count, error) OutputKibitz(suppressKibitz, parse); } else { char tmp[MSG_SIZ]; - sprintf(tmp, _("your opponent kibitzes: %s"), parse); + snprintf(tmp, MSG_SIZ, _("your opponent kibitzes: %s"), parse); SendToPlayer(tmp, strlen(tmp)); } next_out = i+1; // [HGM] suppress printing in ICS window @@ -3167,7 +3205,7 @@ read_from_ics(isr, closure, data, count, error) /* Header for a move list -- second line */ /* Initial board will follow if this is a wild game */ if (gameInfo.event != NULL) free(gameInfo.event); - sprintf(str, "ICS %s %s match", star_match[0], star_match[1]); + snprintf(str, MSG_SIZ, "ICS %s %s match", star_match[0], star_match[1]); gameInfo.event = StrSave(str); /* [HGM] we switched variant. Translate boards if needed. */ VariantSwitch(boards[currentMove], StringToVariant(gameInfo.event)); @@ -3292,7 +3330,7 @@ read_from_ics(isr, closure, data, count, error) flipView = appData.flipView; DrawPosition(TRUE, boards[currentMove]); DisplayBothClocks(); - sprintf(str, "%s vs. %s", + snprintf(str, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); DisplayTitle(str); gameMode = IcsIdle; @@ -3362,7 +3400,7 @@ read_from_ics(isr, closure, data, count, error) } else { player = star_match[2]; } - sprintf(str, "%sobserve %s\n", + snprintf(str, MSG_SIZ, "%sobserve %s\n", ics_prefix, StripHighlightAndTitle(player)); SendToICS(str); @@ -3624,14 +3662,14 @@ read_from_ics(isr, closure, data, count, error) if (currentMove == 0 && gameMode == IcsPlayingWhite && appData.premoveWhite) { - sprintf(str, "%s\n", appData.premoveWhiteText); + snprintf(str, MSG_SIZ, "%s\n", appData.premoveWhiteText); if (appData.debugMode) fprintf(debugFP, "Sending premove:\n"); SendToICS(str); } else if (currentMove == 1 && gameMode == IcsPlayingBlack && appData.premoveBlack) { - sprintf(str, "%s\n", appData.premoveBlackText); + snprintf(str, MSG_SIZ, "%s\n", appData.premoveBlackText); if (appData.debugMode) fprintf(debugFP, "Sending premove:\n"); SendToICS(str); @@ -3682,7 +3720,7 @@ read_from_ics(isr, closure, data, count, error) will tell us whether this is really bug or zh */ if (ics_getting_history == H_FALSE) { ics_getting_history = H_REQUESTED; - sprintf(str, "%smoves %d\n", ics_prefix, gamenum); + snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum); SendToICS(str); } } @@ -3706,10 +3744,10 @@ read_from_ics(isr, closure, data, count, error) char wh[16], bh[16]; PackHolding(wh, white_holding); PackHolding(bh, black_holding); - sprintf(str, "[%s-%s] %s-%s", wh, bh, + snprintf(str, MSG_SIZ,"[%s-%s] %s-%s", wh, bh, gameInfo.white, gameInfo.black); } else { - sprintf(str, "%s [%s] vs. %s [%s]", + snprintf(str, MSG_SIZ, "%s [%s] vs. %s [%s]", gameInfo.white, white_holding, gameInfo.black, black_holding); } @@ -3903,7 +3941,7 @@ ParseBoard12(string) if(twoBoards) { partnerUp = 1; flipView = !flipView; } // [HGM] dual if(partnerUp) DrawPosition(FALSE, partnerBoard); if(twoBoards) { partnerUp = 0; flipView = !flipView; } // [HGM] dual - sprintf(partnerStatus, "W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000, + snprintf(partnerStatus, MSG_SIZ,"W: %d:%02d B: %d:%02d (%d-%d) %c", white_time/60000, (white_time%60000)/1000, (black_time/60000), (black_time%60000)/1000, white_stren, black_stren, to_play); DisplayMessage(partnerStatus, ""); partnerBoardValid = TRUE; @@ -3959,7 +3997,7 @@ ParseBoard12(string) will tell us whether this is really bug or zh */ if (ics_getting_history == H_FALSE) { ics_getting_history = H_REQUESTED; reqFlag = TRUE; - sprintf(str, "%smoves %d\n", ics_prefix, gamenum); + snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum); SendToICS(str); } } @@ -3982,7 +4020,7 @@ ParseBoard12(string) appData.getMoveList && !reqFlag) { /* Need to get game history */ ics_getting_history = H_REQUESTED; - sprintf(str, "%smoves %d\n", ics_prefix, gamenum); + snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum); SendToICS(str); } @@ -4000,7 +4038,7 @@ ParseBoard12(string) if (gamenum == gs_gamenum) { int klen = strlen(gs_kind); if (gs_kind[klen - 1] == '.') gs_kind[klen - 1] = NULLCHAR; - sprintf(str, "ICS %s", gs_kind); + snprintf(str, MSG_SIZ, "ICS %s", gs_kind); gameInfo.event = StrSave(str); } else { gameInfo.event = StrSave("ICS game"); @@ -4174,7 +4212,7 @@ ParseBoard12(string) type when starting to examine a game. But if we ask for the move list, the move list header will tell us */ ics_getting_history = H_REQUESTED; - sprintf(str, "%smoves %d\n", ics_prefix, gamenum); + snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum); SendToICS(str); } } else if (moveNum == forwardMostMove + 1 || moveNum == forwardMostMove @@ -4213,7 +4251,7 @@ ParseBoard12(string) } #endif ics_getting_history = H_REQUESTED; - sprintf(str, "%smoves %d\n", ics_prefix, gamenum); + snprintf(str, MSG_SIZ, "%smoves %d\n", ics_prefix, gamenum); SendToICS(str); } forwardMostMove = backwardMostMove = currentMove = moveNum; @@ -4275,7 +4313,7 @@ ParseBoard12(string) // str looks something like "Q/a1-a2"; kill the slash if(str[1] == '/') - sprintf(buf, "%c%s", str[0], str+2); + snprintf(buf, MSG_SIZ,"%c%s", str[0], str+2); else safeStrCpy(buf, str, sizeof(buf)/sizeof(buf[0])); // might be castling if((prom = strstr(move_str, "=")) && !strstr(buf, "=")) strcat(buf, prom); // long move lacks promo specification! @@ -4339,7 +4377,7 @@ ParseBoard12(string) if ((gameMode == IcsPlayingWhite && WhiteOnMove(moveNum)) || (gameMode == IcsPlayingBlack && !WhiteOnMove(moveNum))) { if (moveList[moveNum - 1][0] == NULLCHAR) { - sprintf(str, _("Couldn't parse move \"%s\" from ICS"), + snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str); DisplayError(str, 0); } else { @@ -4361,7 +4399,7 @@ ParseBoard12(string) } } else if (gameMode == IcsObserving || gameMode == IcsExamining) { if (moveList[moveNum - 1][0] == NULLCHAR) { - sprintf(str, _("Couldn't parse move \"%s\" from ICS"), move_str); + snprintf(str, MSG_SIZ, _("Couldn't parse move \"%s\" from ICS"), move_str); DisplayError(str, 0); } else { if(gameInfo.variant == currentlyInitializedVariant) // [HGM] refrain sending moves engine can't understand! @@ -4405,20 +4443,20 @@ ParseBoard12(string) gameInfo.variant != VariantCrazyhouse && !appData.noGUI) { if (tinyLayout || smallLayout) { if(gameInfo.variant == VariantNormal) - sprintf(str, "%s(%d) %s(%d) {%d %d}", + snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d}", gameInfo.white, white_stren, gameInfo.black, black_stren, basetime, increment); else - sprintf(str, "%s(%d) %s(%d) {%d %d w%d}", + snprintf(str, MSG_SIZ, "%s(%d) %s(%d) {%d %d w%d}", gameInfo.white, white_stren, gameInfo.black, black_stren, basetime, increment, (int) gameInfo.variant); } else { if(gameInfo.variant == VariantNormal) - sprintf(str, "%s (%d) vs. %s (%d) {%d %d}", + snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d}", gameInfo.white, white_stren, gameInfo.black, black_stren, basetime, increment); else - sprintf(str, "%s (%d) vs. %s (%d) {%d %d %s}", + snprintf(str, MSG_SIZ, "%s (%d) vs. %s (%d) {%d %d %s}", gameInfo.white, white_stren, gameInfo.black, black_stren, basetime, increment, VariantName(gameInfo.variant)); } @@ -4472,7 +4510,7 @@ GetMoveListEvent() char buf[MSG_SIZ]; if (appData.icsActive && gameMode != IcsIdle && ics_gamenum > 0) { ics_getting_history = H_REQUESTED; - sprintf(buf, "%smoves %d\n", ics_prefix, ics_gamenum); + snprintf(buf, MSG_SIZ, "%smoves %d\n", ics_prefix, ics_gamenum); SendToICS(buf); } } @@ -4519,7 +4557,7 @@ SendMoveToProgram(moveNum, cps) buf[len++] = '\n'; buf[len] = NULLCHAR; } else { - sprintf(buf, "%s\n", parseList[moveNum]); + snprintf(buf, MSG_SIZ,"%s\n", parseList[moveNum]); } SendToProgram(buf, cps); } else { @@ -4576,7 +4614,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar) switch (moveType) { default: - sprintf(user_move, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"), + snprintf(user_move, MSG_SIZ, _("say Internal error; bad moveType %d (%d,%d-%d,%d)"), (int)moveType, fromX, fromY, toX, toY); DisplayError(user_move + strlen("say "), 0); break; @@ -4588,7 +4626,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar) case WhiteHSideCastleFR: case BlackHSideCastleFR: /* POP Fabien */ - sprintf(user_move, "o-o\n"); + snprintf(user_move, MSG_SIZ, "o-o\n"); break; case WhiteQueenSideCastle: case BlackQueenSideCastle: @@ -4598,7 +4636,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar) case WhiteASideCastleFR: case BlackASideCastleFR: /* POP Fabien */ - sprintf(user_move, "o-o-o\n"); + snprintf(user_move, MSG_SIZ, "o-o-o\n"); break; case WhiteNonPromotion: case BlackNonPromotion: @@ -4607,21 +4645,21 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar) case WhitePromotion: case BlackPromotion: if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk) - sprintf(user_move, "%c%c%c%c=%c\n", + snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY, PieceToChar(WhiteFerz)); else if(gameInfo.variant == VariantGreat) - sprintf(user_move, "%c%c%c%c=%c\n", + snprintf(user_move, MSG_SIZ,"%c%c%c%c=%c\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY, PieceToChar(WhiteMan)); else - sprintf(user_move, "%c%c%c%c=%c\n", + snprintf(user_move, MSG_SIZ, "%c%c%c%c=%c\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY, promoChar); break; case WhiteDrop: case BlackDrop: - sprintf(user_move, "%c@%c%c\n", + snprintf(user_move, MSG_SIZ, "%c@%c%c\n", ToUpper(PieceToChar((ChessSquare) fromX)), AAA + toX, ONE + toY); break; @@ -4629,7 +4667,7 @@ SendMoveToICS(moveType, fromX, fromY, toX, toY, promoChar) case WhiteCapturesEnPassant: case BlackCapturesEnPassant: case IllegalMove: /* could be a variant we don't quite understand */ - sprintf(user_move, "%c%c%c%c\n", + snprintf(user_move, MSG_SIZ,"%c%c%c%c\n", AAA + fromX, ONE + fromY, AAA + toX, ONE + toY); break; } @@ -4651,43 +4689,43 @@ UploadGameEvent() char buf[MSG_SIZ], *p, *fen, command[MSG_SIZ], bsetup = 0; if(ics_type == ICS_ICC) { // on ICC match ourselves in applicable variant - sprintf(command, "match %s", ics_handle); + snprintf(command,MSG_SIZ, "match %s", ics_handle); } else { // on FICS we must first go to general examine mode safeStrCpy(command, "examine\nbsetup", sizeof(command)/sizeof(command[0])); // and specify variant within it with bsetups } if(gameInfo.variant != VariantNormal) { // try figure out wild number, as xboard names are not always valid on ICS for(i=1; i<=36; i++) { - sprintf(buf, "wild/%d", i); + snprintf(buf, MSG_SIZ, "wild/%d", i); if(StringToVariant(buf) == gameInfo.variant) break; } - if(i<=36 && ics_type == ICS_ICC) sprintf(buf, "%s w%d\n", command, i); - else if(i == 22) sprintf(buf, "%s fr\n", command); - else sprintf(buf, "%s %s\n", command, VariantName(gameInfo.variant)); - } else sprintf(buf, "%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine + if(i<=36 && ics_type == ICS_ICC) snprintf(buf, MSG_SIZ,"%s w%d\n", command, i); + else if(i == 22) snprintf(buf,MSG_SIZ, "%s fr\n", command); + else snprintf(buf, MSG_SIZ,"%s %s\n", command, VariantName(gameInfo.variant)); + } else snprintf(buf, MSG_SIZ,"%s\n", ics_type == ICS_ICC ? command : "examine\n"); // match yourself or examine SendToICS(ics_prefix); SendToICS(buf); if(startedFromSetupPosition || backwardMostMove != 0) { fen = PositionToFEN(backwardMostMove, NULL); if(ics_type == ICS_ICC) { // on ICC we can simply send a complete FEN to set everything - sprintf(buf, "loadfen %s\n", fen); + snprintf(buf, MSG_SIZ,"loadfen %s\n", fen); SendToICS(buf); } else { // FICS: everything has to set by separate bsetup commands p = strchr(fen, ' '); p[0] = NULLCHAR; // cut after board - sprintf(buf, "bsetup fen %s\n", fen); + snprintf(buf, MSG_SIZ,"bsetup fen %s\n", fen); SendToICS(buf); if(!WhiteOnMove(backwardMostMove)) { SendToICS("bsetup tomove black\n"); } i = (strchr(p+3, 'K') != NULL) + 2*(strchr(p+3, 'Q') != NULL); - sprintf(buf, "bsetup wcastle %s\n", castlingStrings[i]); + snprintf(buf, MSG_SIZ,"bsetup wcastle %s\n", castlingStrings[i]); SendToICS(buf); i = (strchr(p+3, 'k') != NULL) + 2*(strchr(p+3, 'q') != NULL); - sprintf(buf, "bsetup bcastle %s\n", castlingStrings[i]); + snprintf(buf, MSG_SIZ, "bsetup bcastle %s\n", castlingStrings[i]); SendToICS(buf); i = boards[backwardMostMove][EP_STATUS]; if(i >= 0) { // set e.p. - sprintf(buf, "bsetup eppos %c\n", i+AAA); + snprintf(buf, MSG_SIZ,"bsetup eppos %c\n", i+AAA); SendToICS(buf); } bsetup++; @@ -4698,7 +4736,7 @@ UploadGameEvent() } for(i = backwardMostMove; iuseSetboard) { char* fen = PositionToFEN(moveNum, cps->fenOverride); - sprintf(message, "setboard %s\n", fen); + snprintf(message, MSG_SIZ,"setboard %s\n", fen); SendToProgram(message, cps); free(fen); @@ -5522,10 +5560,10 @@ SendBoard(cps, moveNum) bp = &boards[moveNum][i][BOARD_LEFT]; for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) { if ((int) *bp < (int) BlackPawn) { - sprintf(message, "%c%c%c\n", PieceToChar(*bp), + snprintf(message, MSG_SIZ, "%c%c%c\n", PieceToChar(*bp), AAA + j, ONE + i); if(message[0] == '+' || message[0] == '~') { - sprintf(message, "%c%c%c+\n", + snprintf(message, MSG_SIZ,"%c%c%c+\n", PieceToChar((ChessSquare)(DEMOTED *bp)), AAA + j, ONE + i); } @@ -5544,10 +5582,10 @@ SendBoard(cps, moveNum) for (j = BOARD_LEFT; j < BOARD_RGHT; j++, bp++) { if (((int) *bp != (int) EmptySquare) && ((int) *bp >= (int) BlackPawn)) { - sprintf(message, "%c%c%c\n", ToUpper(PieceToChar(*bp)), + snprintf(message,MSG_SIZ, "%c%c%c\n", ToUpper(PieceToChar(*bp)), AAA + j, ONE + i); if(message[0] == '+' || message[0] == '~') { - sprintf(message, "%c%c%c+\n", + snprintf(message, MSG_SIZ,"%c%c%c+\n", PieceToChar((ChessSquare)(DEMOTED *bp)), AAA + j, ONE + i); } @@ -6102,10 +6140,10 @@ FinishMove(moveType, fromX, fromY, toX, toY, promoChar) gameMode = MachinePlaysBlack; StartClocks(); SetGameInfo(); - sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black); + snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); DisplayTitle(buf); if (first.sendName) { - sprintf(buf, "name %s\n", gameInfo.white); + snprintf(buf, MSG_SIZ,"name %s\n", gameInfo.white); SendToProgram(buf, &first); } StartClocks(); @@ -6990,7 +7028,7 @@ char *SendMoveToBookUser(int moveNr, ChessProgramState *cps, int initial) // after a book hit we never send 'go', and the code after the call to this routine // has '&& !bookHit' added to suppress potential sending there (based on 'firstMove'). char buf[MSG_SIZ]; - sprintf(buf, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it + snprintf(buf, MSG_SIZ, "%s%s\n", (cps->useUsermove ? "usermove " : ""), bookHit); // force book move into program supposed to play it SendToProgram(buf, cps); if(!initial) firstMove = FALSE; // normally we would clear the firstMove condition after return & sending 'go' } else if(initial) { // 'go' was needed irrespective of firstMove, and it has to be done in this routine @@ -7142,10 +7180,10 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h if (!ParseOneMove(machineMove, forwardMostMove, &moveType, &fromX, &fromY, &toX, &toY, &promoChar)) { /* Machine move could not be parsed; ignore it. */ - sprintf(buf1, _("Illegal move \"%s\" from %s machine"), + snprintf(buf1, MSG_SIZ*10, _("Illegal move \"%s\" from %s machine"), machineMove, cps->which); DisplayError(buf1, 0); - sprintf(buf1, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d", + snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to invalid move: %s (%c%c%c%c) res=%d", machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, moveType); if (gameMode == TwoMachinesPlay) { GameEnds(machineWhite ? BlackWins : WhiteWins, @@ -7170,7 +7208,7 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h fprintf(debugFP, "castling rights\n"); } if(moveType == IllegalMove) { - sprintf(buf1, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c", + snprintf(buf1, MSG_SIZ*10, "Xboard: Forfeit due to illegal move: %s (%c%c%c%c)%c", machineMove, fromX+AAA, fromY+ONE, toX+AAA, toY+ONE, 0); GameEnds(machineWhite ? BlackWins : WhiteWins, buf1, GE_XBOARD); @@ -7256,7 +7294,7 @@ FakeBookMove: // [HGM] book: we jump here to simulate machine moves after book h if(appData.autoKibitz && !appData.icsEngineAnalyze ) { /* [HGM] kibitz: send most-recent PV info to ICS */ char buf[3*MSG_SIZ]; - sprintf(buf, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n", + snprintf(buf, 3*MSG_SIZ, "kibitz !!! %+.2f/%d (%.2f sec, %u nodes, %.0f knps) PV=%s\n", programStats.score / 100., programStats.depth, programStats.time / 100., @@ -7497,7 +7535,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats. cps->analysisSupport = FALSE; cps->analyzing = FALSE; Reset(FALSE, TRUE); - sprintf(buf2, _("%s does not support analysis"), cps->tidy); + snprintf(buf2,MSG_SIZ, _("%s does not support analysis"), cps->tidy); DisplayError(buf2, 0); return; } @@ -7556,7 +7594,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats. DisplayMove(currentMove-1); /* before DisplayMoveError */ SwitchClocks(forwardMostMove-1); // [HGM] race DisplayBothClocks(); - sprintf(buf1, _("Illegal move \"%s\" (rejected by %s chess program)"), + snprintf(buf1, 10*MSG_SIZ, _("Illegal move \"%s\" (rejected by %s chess program)"), parseList[currentMove], cps->which); DisplayMoveError(buf1); DrawPosition(FALSE, boards[currentMove]); @@ -7911,13 +7949,13 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats. [AS] Protect the thinkOutput buffer from overflow... this is only useful if buf1 hasn't overflowed first! */ - sprintf(thinkOutput, "[%d]%c%+.2f %s%s", - plylev, - (gameMode == TwoMachinesPlay ? - ToUpper(cps->twoMachinesColor[0]) : ' '), - ((double) curscore) / 100.0, - prefixHint ? lastHint : "", - prefixHint ? " " : "" ); + snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "[%d]%c%+.2f %s%s", + plylev, + (gameMode == TwoMachinesPlay ? + ToUpper(cps->twoMachinesColor[0]) : ' '), + ((double) curscore) / 100.0, + prefixHint ? lastHint : "", + prefixHint ? " " : "" ); if( buf1[0] != NULLCHAR ) { unsigned max_len = sizeof(thinkOutput) - strlen(thinkOutput) - 1; @@ -7943,7 +7981,7 @@ if(appData.debugMode) fprintf(debugFP, "nodes = %d, %lld\n", (int) programStats. * if there is only 1 legal move */ sscanf(p, "(only move) %s", buf1); - sprintf(thinkOutput, "%s (only move)", buf1); + snprintf(thinkOutput, sizeof(thinkOutput)/sizeof(thinkOutput[0]), "%s (only move)", buf1); sprintf(programStats.movelist, "%s (only move)", buf1); programStats.depth = 1; programStats.nr_moves = 1; @@ -8152,7 +8190,7 @@ ParseGameHistory(game) break; case AmbiguousMove: /* bug? */ - sprintf(buf, _("Ambiguous move in ICS output: \"%s\""), yy_text); + snprintf(buf, MSG_SIZ, _("Ambiguous move in ICS output: \"%s\""), yy_text); if (appData.debugMode) { fprintf(debugFP, "Ambiguous move from ICS: '%s'\n", yy_text); fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth); @@ -8162,7 +8200,7 @@ ParseGameHistory(game) return; case ImpossibleMove: /* bug? */ - sprintf(buf, _("Illegal move in ICS output: \"%s\""), yy_text); + snprintf(buf, MSG_SIZ, _("Illegal move in ICS output: \"%s\""), yy_text); if (appData.debugMode) { fprintf(debugFP, "Impossible move from ICS: '%s'\n", yy_text); fprintf(debugFP, "board L=%d, R=%d, H=%d, holdings=%d\n", BOARD_LEFT, BOARD_RGHT, BOARD_HEIGHT, gameInfo.holdingsWidth); @@ -8695,7 +8733,7 @@ void SendEgtPath(ChessProgramState *cps) if( appData.defaultPathEGTB && appData.defaultPathEGTB[0] && strcmp(name, ",nalimov:") == 0 ) { // take nalimov path from the menu-changeable option first, if it is defined - sprintf(buf, "egtpath nalimov %s\n", appData.defaultPathEGTB); + snprintf(buf, MSG_SIZ, "egtpath nalimov %s\n", appData.defaultPathEGTB); SendToProgram(buf,cps); // send egtbpath command for nalimov } else if( (s = StrStr(appData.egtFormats, name+1)) == appData.egtFormats || @@ -8705,7 +8743,7 @@ void SendEgtPath(ChessProgramState *cps) while(*r && *r != ',') r++; // path info is everything upto next ';' or end of string c = *r; *r = 0; // temporarily null-terminate path info *--q = 0; // strip of trailig ':' from name - sprintf(buf, "egtpath %s %s\n", name+1, s); + snprintf(buf, MSG_SIZ, "egtpath %s %s\n", name+1, s); *r = c; SendToProgram(buf,cps); // send egtbpath command for this format } @@ -8726,12 +8764,12 @@ InitChessProgram(cps, setup) /* [HGM] some new WB protocol commands to configure engine are sent now, if engine supports them */ /* moved to before sending initstring in 4.3.15, so Polyglot can delay UCI 'isready' to recepton of 'new' */ if(cps->memSize) { /* [HGM] memory */ - sprintf(buf, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB); + snprintf(buf, MSG_SIZ, "memory %d\n", appData.defaultHashSize + appData.defaultCacheSizeEGTB); SendToProgram(buf, cps); } SendEgtPath(cps); /* [HGM] EGT */ if(cps->maxCores) { /* [HGM] SMP: (protocol specified must be last settings command before new!) */ - sprintf(buf, "cores %d\n", appData.smpCores); + snprintf(buf, MSG_SIZ, "cores %d\n", appData.smpCores); SendToProgram(buf, cps); } @@ -8744,7 +8782,7 @@ InitChessProgram(cps, setup) char *v = VariantName(gameInfo.variant); if (cps->protocolVersion != 1 && StrStr(cps->variants, v) == NULL) { /* [HGM] in protocol 1 we have to assume all variants valid */ - sprintf(buf, _("Variant %s not supported by %s"), v, cps->tidy); + snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), v, cps->tidy); DisplayFatalError(buf, 0, 1); return; } @@ -8768,14 +8806,14 @@ InitChessProgram(cps, setup) overruled = gameInfo.boardWidth != 10 || gameInfo.boardHeight != 8 || gameInfo.holdingsSize != 8; if(overruled) { - sprintf(b, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight, - gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name + snprintf(b, MSG_SIZ, "%dx%d+%d_%s", gameInfo.boardWidth, gameInfo.boardHeight, + gameInfo.holdingsSize, VariantName(gameInfo.variant)); // cook up sized variant name /* [HGM] varsize: try first if this defiant size variant is specifically known */ if(StrStr(cps->variants, b) == NULL) { // specific sized variant not known, check if general sizing allowed if (cps->protocolVersion != 1) { // for protocol 1 we cannot check and hope for the best if(StrStr(cps->variants, "boardsize") == NULL) { - sprintf(buf, "Board size %dx%d+%d not supported by %s", + snprintf(buf, MSG_SIZ, "Board size %dx%d+%d not supported by %s", gameInfo.boardWidth, gameInfo.boardHeight, gameInfo.holdingsSize, cps->tidy); DisplayFatalError(buf, 0, 1); return; @@ -8783,8 +8821,8 @@ InitChessProgram(cps, setup) /* [HGM] here we really should compare with the maximum supported board size */ } } - } else sprintf(b, "%s", VariantName(gameInfo.variant)); - sprintf(buf, "variant %s\n", b); + } else snprintf(b, MSG_SIZ,"%s", VariantName(gameInfo.variant)); + snprintf(buf, MSG_SIZ, "variant %s\n", b); SendToProgram(buf, cps); } currentlyInitializedVariant = gameInfo.variant; @@ -8823,7 +8861,7 @@ InitChessProgram(cps, setup) SendToProgram("easy\n", cps); } if (cps->usePing) { - sprintf(buf, "ping %d\n", ++cps->lastPing); + snprintf(buf, MSG_SIZ, "ping %d\n", ++cps->lastPing); SendToProgram(buf, cps); } cps->initDone = TRUE; @@ -8856,7 +8894,7 @@ StartChessProgram(cps) } if (err != 0) { - sprintf(buf, _("Startup failure on '%s'"), cps->program); + snprintf(buf, MSG_SIZ, _("Startup failure on '%s'"), cps->program); DisplayFatalError(buf, err, 1); cps->pr = NoProc; cps->isr = NULL; @@ -8865,7 +8903,7 @@ StartChessProgram(cps) cps->isr = AddInputSource(cps->pr, TRUE, ReceiveFromProgram, cps); if (cps->protocolVersion > 1) { - sprintf(buf, "xboard\nprotover %d\n", cps->protocolVersion); + snprintf(buf, MSG_SIZ, "xboard\nprotover %d\n", cps->protocolVersion); cps->nrOptions = 0; // [HGM] options: clear all engine-specific options cps->comboCnt = 0; // and values of combo boxes SendToProgram(buf, cps); @@ -9057,7 +9095,7 @@ GameEnds(result, resultDetails, whosays) result, (signed char)boards[forwardMostMove][EP_STATUS], forwardMostMove); } if(result != trueResult) { - sprintf(buf, "False win claim: '%s'", resultDetails); + snprintf(buf, MSG_SIZ, "False win claim: '%s'", resultDetails); result = claimer == 'w' ? BlackWins : WhiteWins; resultDetails = buf; } @@ -9068,7 +9106,7 @@ GameEnds(result, resultDetails, whosays) (claimer=='b')==(forwardMostMove&1)) ) { /* [HGM] verify: draws that were not flagged are false claims */ - sprintf(buf, "False draw claim: '%s'", resultDetails); + snprintf(buf, MSG_SIZ, "False draw claim: '%s'", resultDetails); result = claimer == 'w' ? BlackWins : WhiteWins; resultDetails = buf; } @@ -9090,7 +9128,7 @@ GameEnds(result, resultDetails, whosays) } if(k <= 1) { result = GameIsDrawn; - sprintf(buf, "%s but bare king", resultDetails); + snprintf(buf, MSG_SIZ, "%s but bare king", resultDetails); resultDetails = buf; } } @@ -9140,7 +9178,7 @@ GameEnds(result, resultDetails, whosays) gameMode == IcsPlayingBlack || gameMode == BeginningOfGame) { char buf[MSG_SIZ]; - sprintf(buf, "result %s {%s}\n", PGNResult(result), + snprintf(buf, MSG_SIZ, "result %s {%s}\n", PGNResult(result), resultDetails); if (first.pr != NoProc) { SendToProgram(buf, &first); @@ -9223,7 +9261,7 @@ GameEnds(result, resultDetails, whosays) SendToProgram("force\n", &first); if (first.usePing) { char buf[MSG_SIZ]; - sprintf(buf, "ping %d\n", ++first.lastPing); + snprintf(buf, MSG_SIZ, "ping %d\n", ++first.lastPing); SendToProgram(buf, &first); } } @@ -9249,7 +9287,7 @@ GameEnds(result, resultDetails, whosays) SendToProgram("force\n", &second); if (second.usePing) { char buf[MSG_SIZ]; - sprintf(buf, "ping %d\n", ++second.lastPing); + snprintf(buf, MSG_SIZ, "ping %d\n", ++second.lastPing); SendToProgram(buf, &second); } } @@ -9303,10 +9341,10 @@ GameEnds(result, resultDetails, whosays) return; } else { gameMode = nextGameMode; - sprintf(buf, _("Match %s vs. %s: final score %d-%d-%d"), - first.tidy, second.tidy, - first.matchWins, second.matchWins, - appData.matchGames - (first.matchWins + second.matchWins)); + snprintf(buf, MSG_SIZ, _("Match %s vs. %s: final score %d-%d-%d"), + first.tidy, second.tidy, + first.matchWins, second.matchWins, + appData.matchGames - (first.matchWins + second.matchWins)); popupRequested++; // [HGM] crash: postpone to after resetting endingGame } } @@ -9337,11 +9375,12 @@ FeedMovesToProgram(cps, upto) fprintf(debugFP, "Feeding %smoves %d through %d to %s chess program\n", startedFromSetupPosition ? "position and " : "", backwardMostMove, upto, cps->which); - if(currentlyInitializedVariant != gameInfo.variant) { char buf[MSG_SIZ]; + if(currentlyInitializedVariant != gameInfo.variant) { + char buf[MSG_SIZ]; // [HGM] variantswitch: make engine aware of new variant if(cps->protocolVersion > 1 && StrStr(cps->variants, VariantName(gameInfo.variant)) == NULL) return; // [HGM] refrain from feeding moves altogether if variant is unsupported! - sprintf(buf, "variant %s\n", VariantName(gameInfo.variant)); + snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant)); SendToProgram(buf, cps); currentlyInitializedVariant = gameInfo.variant; } @@ -9709,7 +9748,7 @@ LoadGameOneMove(readAhead) if (appData.testLegality) { if (appData.debugMode) fprintf(debugFP, "Parsed IllegalMove: %s\n", yy_text); - sprintf(move, _("Illegal move: %d.%s%s"), + snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"), (forwardMostMove / 2) + 1, WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text); DisplayError(move, 0); @@ -9729,7 +9768,7 @@ LoadGameOneMove(readAhead) case AmbiguousMove: if (appData.debugMode) fprintf(debugFP, "Parsed AmbiguousMove: %s\n", yy_text); - sprintf(move, _("Ambiguous move: %d.%s%s"), + snprintf(move, MSG_SIZ, _("Ambiguous move: %d.%s%s"), (forwardMostMove / 2) + 1, WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text); DisplayError(move, 0); @@ -9740,7 +9779,7 @@ LoadGameOneMove(readAhead) case ImpossibleMove: if (appData.debugMode) fprintf(debugFP, "Parsed ImpossibleMove (type = %d): %s\n", moveType, yy_text); - sprintf(move, _("Illegal move: %d.%s%s"), + snprintf(move, MSG_SIZ, _("Illegal move: %d.%s%s"), (forwardMostMove / 2) + 1, WhiteOnMove(forwardMostMove) ? " " : ".. ", yy_text); DisplayError(move, 0); @@ -10019,7 +10058,7 @@ LoadGame(f, gameNumber, title, useList) DisplayTitle(buf); } else if (*title != NULLCHAR) { if (gameNumber > 1) { - sprintf(buf, "%s %d", title, gameNumber); + snprintf(buf, MSG_SIZ, "%s %d", title, gameNumber); DisplayTitle(buf); } else { DisplayTitle(title); @@ -10560,7 +10599,7 @@ int i, j; } if (positionNumber > 1) { - sprintf(line, "%s %d", title, positionNumber); + snprintf(line, MSG_SIZ, "%s %d", title, positionNumber); DisplayTitle(line); } else { DisplayTitle(title); @@ -10780,15 +10819,14 @@ SaveGamePGN(f) } /* Format move number */ - if ((i % 2) == 0) { - sprintf(numtext, "%d.", (i - offset)/2 + 1); - } else { - if (newblock) { - sprintf(numtext, "%d...", (i - offset)/2 + 1); - } else { - numtext[0] = NULLCHAR; - } - } + if ((i % 2) == 0) + snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]),"%d.", (i - offset)/2 + 1); + else + if (newblock) + snprintf(numtext, sizeof(numtext)/sizeof(numtext[0]), "%d...", (i - offset)/2 + 1); + else + numtext[0] = NULLCHAR; + numlen = strlen(numtext); newblock = FALSE; @@ -10831,18 +10869,25 @@ SaveGamePGN(f) seconds = (pvInfoList[i].time+5)/10; // deci-seconds, rounded to nearest - if( seconds <= 0) buf[0] = 0; else - if( seconds < 30 ) sprintf(buf, " %3.1f%c", seconds/10., 0); else { - seconds = (seconds + 4)/10; // round to full seconds - if( seconds < 60 ) sprintf(buf, " %d%c", seconds, 0); else - sprintf(buf, " %d:%02d%c", seconds/60, seconds%60, 0); - } + if( seconds <= 0) + buf[0] = 0; + else + if( seconds < 30 ) + snprintf(buf, MSG_SIZ, " %3.1f%c", seconds/10., 0); + else + { + seconds = (seconds + 4)/10; // round to full seconds + if( seconds < 60 ) + snprintf(buf, MSG_SIZ, " %d%c", seconds, 0); + else + snprintf(buf, MSG_SIZ, " %d:%02d%c", seconds/60, seconds%60, 0); + } - sprintf( move_buffer, "{%s%.2f/%d%s}", - pvInfoList[i].score >= 0 ? "+" : "", - pvInfoList[i].score / 100.0, - pvInfoList[i].depth, - buf ); + snprintf( move_buffer, sizeof(move_buffer)/sizeof(move_buffer[0]),"{%s%.2f/%d%s}", + pvInfoList[i].score >= 0 ? "+" : "", + pvInfoList[i].score / 100.0, + pvInfoList[i].depth, + buf ); movelen = strlen(move_buffer); /* [HGM] pgn: line-break point after move */ @@ -11147,14 +11192,13 @@ RegisterMove() fprintf(debugFP, "Saving %s for game %d\n", cmailMove[lastLoadGameNumber - 1], lastLoadGameNumber); - sprintf(string, - "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber); + snprintf(string, MSG_SIZ, "%s.game.out.%d", appData.cmailGameName, lastLoadGameNumber); f = fopen(string, "w"); if (appData.oldSaveStyle) { SaveGameOldStyle(f); /* also closes the file */ - sprintf(string, "%s.pos.out", appData.cmailGameName); + snprintf(string, MSG_SIZ, "%s.pos.out", appData.cmailGameName); f = fopen(string, "w"); SavePosition(f, 0, NULL); /* also closes the file */ } else { @@ -11200,7 +11244,7 @@ MailMoveEvent() #if CMAIL_PROHIBIT_REMAIL if (cmailMailedMove) { - sprintf(msg, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName); + snprintf(msg, MSG_SIZ, _("You have already mailed a move.\nWait until a move arrives from your opponent.\nTo resend the same move, type\n\"cmail -remail -game %s\"\non the command line."), appData.cmailGameName); DisplayError(msg, 0); return; } @@ -11210,8 +11254,8 @@ MailMoveEvent() if ( cmailMailedMove || (nCmailMovesRegistered + nCmailResults == nCmailGames)) { - sprintf(string, partCommandString, - appData.debugMode ? " -v" : "", appData.cmailGameName); + snprintf(string, MSG_SIZ, partCommandString, + appData.debugMode ? " -v" : "", appData.cmailGameName); commandOutput = popen(string, "r"); if (commandOutput == NULL) { @@ -11241,10 +11285,10 @@ MailMoveEvent() if ( archived && ( (arcDir = (char *) getenv("CMAIL_ARCDIR")) != NULL)) { - sprintf(buffer, "%s/%s.%s.archive", - arcDir, - appData.cmailGameName, - gameInfo.date); + snprintf(buffer, MSG_SIZ, "%s/%s.%s.archive", + arcDir, + appData.cmailGameName, + gameInfo.date); LoadGameFromFile(buffer, 1, buffer, FALSE); cmailMsgLoaded = FALSE; } @@ -11277,17 +11321,17 @@ CmailMsg() if (!cmailMsgLoaded) return ""; if (cmailMailedMove) { - sprintf(cmailMsg, _("Waiting for reply from opponent\n")); + snprintf(cmailMsg, MSG_SIZ, _("Waiting for reply from opponent\n")); } else { /* Create a list of games left */ - sprintf(string, "["); + snprintf(string, MSG_SIZ, "["); for (i = 0; i < nCmailGames; i ++) { if (! ( cmailMoveRegistered[i] || (cmailResult[i] == CMAIL_OLD_RESULT))) { if (prependComma) { - sprintf(number, ",%d", i + 1); + snprintf(number, sizeof(number)/sizeof(number[0]), ",%d", i + 1); } else { - sprintf(number, "%d", i + 1); + snprintf(number, sizeof(number)/sizeof(number[0]), "%d", i + 1); prependComma = 1; } @@ -11299,41 +11343,36 @@ CmailMsg() if (nCmailMovesRegistered + nCmailResults == 0) { switch (nCmailGames) { case 1: - sprintf(cmailMsg, - _("Still need to make move for game\n")); + snprintf(cmailMsg, MSG_SIZ, _("Still need to make move for game\n")); break; case 2: - sprintf(cmailMsg, - _("Still need to make moves for both games\n")); + snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for both games\n")); break; default: - sprintf(cmailMsg, - _("Still need to make moves for all %d games\n"), - nCmailGames); + snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for all %d games\n"), + nCmailGames); break; } } else { switch (nCmailGames - nCmailMovesRegistered - nCmailResults) { case 1: - sprintf(cmailMsg, - _("Still need to make a move for game %s\n"), - string); + snprintf(cmailMsg, MSG_SIZ, _("Still need to make a move for game %s\n"), + string); break; case 0: if (nCmailResults == nCmailGames) { - sprintf(cmailMsg, _("No unfinished games\n")); + snprintf(cmailMsg, MSG_SIZ, _("No unfinished games\n")); } else { - sprintf(cmailMsg, _("Ready to send mail\n")); + snprintf(cmailMsg, MSG_SIZ, _("Ready to send mail\n")); } break; default: - sprintf(cmailMsg, - _("Still need to make moves for games %s\n"), - string); + snprintf(cmailMsg, MSG_SIZ, _("Still need to make moves for games %s\n"), + string); } } } @@ -11488,9 +11527,9 @@ EditCommentEvent() if (currentMove < 1 || parseList[currentMove - 1][0] == NULLCHAR) { safeStrCpy(title, _("Edit comment"), sizeof(title)/sizeof(title[0])); } else { - sprintf(title, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1, - WhiteOnMove(currentMove - 1) ? " " : ".. ", - parseList[currentMove - 1]); + snprintf(title, MSG_SIZ, _("Edit comment on %d.%s%s"), (currentMove - 1) / 2 + 1, + WhiteOnMove(currentMove - 1) ? " " : ".. ", + parseList[currentMove - 1]); } EditCommentPopUp(currentMove, title, commentList[currentMove]); @@ -11600,10 +11639,10 @@ MachineWhiteEvent() pausing = FALSE; ModeHighlight(); SetGameInfo(); - sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black); + snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); DisplayTitle(buf); if (first.sendName) { - sprintf(buf, "name %s\n", gameInfo.black); + snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black); SendToProgram(buf, &first); } if (first.sendTime) { @@ -11643,8 +11682,8 @@ MachineWhiteEvent() void MachineBlackEvent() { - char buf[MSG_SIZ]; - char *bookHit = NULL; + char buf[MSG_SIZ]; + char *bookHit = NULL; if (appData.noChessProgram || (gameMode == MachinePlaysBlack)) return; @@ -11677,10 +11716,10 @@ MachineBlackEvent() pausing = FALSE; ModeHighlight(); SetGameInfo(); - sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black); + snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); DisplayTitle(buf); if (first.sendName) { - sprintf(buf, "name %s\n", gameInfo.white); + snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white); SendToProgram(buf, &first); } if (first.sendTime) { @@ -11722,18 +11761,18 @@ DisplayTwoMachinesTitle() char buf[MSG_SIZ]; if (appData.matchGames > 0) { if (first.twoMachinesColor[0] == 'w') { - sprintf(buf, "%s vs. %s (%d-%d-%d)", - gameInfo.white, gameInfo.black, - first.matchWins, second.matchWins, - matchGame - 1 - (first.matchWins + second.matchWins)); + snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)", + gameInfo.white, gameInfo.black, + first.matchWins, second.matchWins, + matchGame - 1 - (first.matchWins + second.matchWins)); } else { - sprintf(buf, "%s vs. %s (%d-%d-%d)", - gameInfo.white, gameInfo.black, - second.matchWins, first.matchWins, - matchGame - 1 - (first.matchWins + second.matchWins)); + snprintf(buf, MSG_SIZ, "%s vs. %s (%d-%d-%d)", + gameInfo.white, gameInfo.black, + second.matchWins, first.matchWins, + matchGame - 1 - (first.matchWins + second.matchWins)); } } else { - sprintf(buf, "%s vs. %s", gameInfo.white, gameInfo.black); + snprintf(buf, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); } DisplayTitle(buf); } @@ -11819,12 +11858,12 @@ TwoMachinesEvent P((void)) SendToProgram(first.computerString, &first); if (first.sendName) { - sprintf(buf, "name %s\n", second.tidy); + snprintf(buf, MSG_SIZ, "name %s\n", second.tidy); SendToProgram(buf, &first); } SendToProgram(second.computerString, &second); if (second.sendName) { - sprintf(buf, "name %s\n", first.tidy); + snprintf(buf, MSG_SIZ, "name %s\n", first.tidy); SendToProgram(buf, &second); } @@ -12183,7 +12222,7 @@ EditPositionMenuEvent(selection, x, y) for (y = 0; y < BOARD_HEIGHT; y++) { if (gameMode == IcsExamining) { if (boards[currentMove][y][x] != EmptySquare) { - sprintf(buf, "%sx@%c%c\n", ics_prefix, + snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y); SendToICS(buf); } @@ -12209,7 +12248,7 @@ EditPositionMenuEvent(selection, x, y) case EmptySquare: if (gameMode == IcsExamining) { if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings - sprintf(buf, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y); + snprintf(buf, MSG_SIZ, "%sx@%c%c\n", ics_prefix, AAA + x, ONE + y); SendToICS(buf); } else { if(x < BOARD_LEFT || x >= BOARD_RGHT) { @@ -12262,8 +12301,8 @@ EditPositionMenuEvent(selection, x, y) defaultlabel: if (gameMode == IcsExamining) { if (x < BOARD_LEFT || x >= BOARD_RGHT) break; // [HGM] holdings - sprintf(buf, "%s%c@%c%c\n", ics_prefix, - PieceToChar(selection), AAA + x, ONE + y); + snprintf(buf, MSG_SIZ, "%s%c@%c%c\n", ics_prefix, + PieceToChar(selection), AAA + x, ONE + y); SendToICS(buf); } else { if(x < BOARD_LEFT || x >= BOARD_RGHT) { @@ -13020,11 +13059,11 @@ TimeControlTagValue() if (!appData.clockMode) { safeStrCpy(buf, "-", sizeof(buf)/sizeof(buf[0])); } else if (movesPerSession > 0) { - sprintf(buf, "%d/%ld", movesPerSession, timeControl/1000); + snprintf(buf, MSG_SIZ, "%d/%ld", movesPerSession, timeControl/1000); } else if (timeIncrement == 0) { - sprintf(buf, "%ld", timeControl/1000); + snprintf(buf, MSG_SIZ, "%ld", timeControl/1000); } else { - sprintf(buf, "%ld+%ld", timeControl/1000, timeIncrement/1000); + snprintf(buf, MSG_SIZ, "%ld+%ld", timeControl/1000, timeIncrement/1000); } return StrSave(buf); } @@ -13072,7 +13111,7 @@ SetGameInfo() gameInfo.date = PGNDate(); if (matchGame > 0) { char buf[MSG_SIZ]; - sprintf(buf, "%d", matchGame); + snprintf(buf, MSG_SIZ, "%d", matchGame); gameInfo.round = StrSave(buf); } else { gameInfo.round = StrSave("-"); @@ -13348,11 +13387,11 @@ SendToProgram(message, cps) outCount = OutputToProcess(cps->pr, message, count, &error); if (outCount < count && !exiting && !endingGame) { /* [HGM] crash: to not hang GameEnds() writing to deceased engines */ - sprintf(buf, _("Error writing to %s chess program"), cps->which); + snprintf(buf, MSG_SIZ, _("Error writing to %s chess program"), cps->which); if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */ if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) { gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */ - sprintf(buf, "%s program exits in draw position (%s)", cps->which, cps->program); + snprintf(buf, MSG_SIZ, "%s program exits in draw position (%s)", cps->which, cps->program); } else { gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins; } @@ -13377,13 +13416,12 @@ ReceiveFromProgram(isr, closure, message, count, error) if (isr != cps->isr) return; /* Killed intentionally */ if (count <= 0) { if (count == 0) { - sprintf(buf, - _("Error: %s chess program (%s) exited unexpectedly"), + snprintf(buf, MSG_SIZ, _("Error: %s chess program (%s) exited unexpectedly"), cps->which, cps->program); if(gameInfo.resultDetails==NULL) { /* [HGM] crash: if game in progress, give reason for abort */ if((signed char)boards[forwardMostMove][EP_STATUS] <= EP_DRAWS) { gameInfo.result = GameIsDrawn; /* [HGM] accept exit as draw claim */ - sprintf(buf, _("%s program exits in draw position (%s)"), cps->which, cps->program); + snprintf(buf, MSG_SIZ, _("%s program exits in draw position (%s)"), cps->which, cps->program); } else { gameInfo.result = cps->twoMachinesColor[0]=='w' ? BlackWins : WhiteWins; } @@ -13392,8 +13430,7 @@ ReceiveFromProgram(isr, closure, message, count, error) RemoveInputSource(cps->isr); if(!cps->userError || !appData.popupExitMessage) DisplayFatalError(buf, 0, 1); else errorExitStatus = 1; } else { - sprintf(buf, - _("Error reading from %s chess program (%s)"), + snprintf(buf, MSG_SIZ, _("Error reading from %s chess program (%s)"), cps->which, cps->program); RemoveInputSource(cps->isr); @@ -13478,12 +13515,12 @@ SendTimeControl(cps, mps, tc, inc, sd, st) /* GNU Chess 4 has no st command; uses level in a nonstandard way */ seconds = st % 60; if (seconds == 0) { - sprintf(buf, "level 1 %d\n", st/60); + snprintf(buf, MSG_SIZ, "level 1 %d\n", st/60); } else { - sprintf(buf, "level 1 %d:%02d\n", st/60, seconds); + snprintf(buf, MSG_SIZ, "level 1 %d:%02d\n", st/60, seconds); } } else { - sprintf(buf, "st %d\n", st); + snprintf(buf, MSG_SIZ, "st %d\n", st); } } else { /* Set conventional or incremental time control, using level command */ @@ -13491,10 +13528,10 @@ SendTimeControl(cps, mps, tc, inc, sd, st) /* Note old gnuchess bug -- minutes:seconds used to not work. Fixed in later versions, but still avoid :seconds when seconds is 0. */ - sprintf(buf, "level %d %ld %d\n", mps, tc/60000, inc/1000); + snprintf(buf, MSG_SIZ, "level %d %ld %d\n", mps, tc/60000, inc/1000); } else { - sprintf(buf, "level %d %ld:%02d %d\n", mps, tc/60000, - seconds, inc/1000); + snprintf(buf, MSG_SIZ, "level %d %ld:%02d %d\n", mps, tc/60000, + seconds, inc/1000); } } SendToProgram(buf, cps); @@ -13503,18 +13540,19 @@ SendTimeControl(cps, mps, tc, inc, sd, st) /* Orthogonally, limit search to given depth */ if (sd > 0) { if (cps->sdKludge) { - sprintf(buf, "depth\n%d\n", sd); + snprintf(buf, MSG_SIZ, "depth\n%d\n", sd); } else { - sprintf(buf, "sd %d\n", sd); + snprintf(buf, MSG_SIZ, "sd %d\n", sd); } SendToProgram(buf, cps); } if(cps->nps > 0) { /* [HGM] nps */ - if(cps->supportsNPS == FALSE) cps->nps = -1; // don't use if engine explicitly says not supported! + if(cps->supportsNPS == FALSE) + cps->nps = -1; // don't use if engine explicitly says not supported! else { - sprintf(buf, "nps %d\n", cps->nps); - SendToProgram(buf, cps); + snprintf(buf, MSG_SIZ, "nps %d\n", cps->nps); + SendToProgram(buf, cps); } } } @@ -13556,10 +13594,10 @@ SendTimeRemaining(cps, machineWhite) if (time <= 0) time = 1; if (otime <= 0) otime = 1; - sprintf(message, "time %ld\n", time); + snprintf(message, MSG_SIZ, "time %ld\n", time); SendToProgram(message, cps); - sprintf(message, "otim %ld\n", otime); + snprintf(message, MSG_SIZ, "otim %ld\n", otime); SendToProgram(message, cps); } @@ -13573,12 +13611,14 @@ BoolFeature(p, name, loc, cps) char buf[MSG_SIZ]; int len = strlen(name); int val; + if (strncmp((*p), name, len) == 0 && (*p)[len] == '=') { (*p) += len + 1; sscanf(*p, "%d", &val); *loc = (val != 0); - while (**p && **p != ' ') (*p)++; - sprintf(buf, "accepted %s\n", name); + while (**p && **p != ' ') + (*p)++; + snprintf(buf, MSG_SIZ, "accepted %s\n", name); SendToProgram(buf, cps); return TRUE; } @@ -13598,7 +13638,7 @@ IntFeature(p, name, loc, cps) (*p) += len + 1; sscanf(*p, "%d", loc); while (**p && **p != ' ') (*p)++; - sprintf(buf, "accepted %s\n", name); + snprintf(buf, MSG_SIZ, "accepted %s\n", name); SendToProgram(buf, cps); return TRUE; } @@ -13620,7 +13660,7 @@ StringFeature(p, name, loc, cps) sscanf(*p, "%[^\"]", loc); while (**p && **p != '\"') (*p)++; if (**p == '\"') (*p)++; - sprintf(buf, "accepted %s\n", name); + snprintf(buf, MSG_SIZ, "accepted %s\n", name); SendToProgram(buf, cps); return TRUE; } @@ -13696,7 +13736,7 @@ ParseOption(Option *opt, ChessProgramState *cps) if(cps->optionSettings && cps->optionSettings[0]) p = strstr(cps->optionSettings, opt->name); else p = NULL; if(p && (p == cps->optionSettings || p[-1] == ',')) { - sprintf(buf, "option %s", p); + snprintf(buf, MSG_SIZ, "option %s", p); if(p = strstr(buf, ",")) *p = 0; strcat(buf, "\n"); SendToProgram(buf, cps); @@ -13779,13 +13819,13 @@ ParseFeatures(args, cps) if (StringFeature(&p, "egt", &cps->egtFormats, cps)) continue; if (StringFeature(&p, "option", &(cps->option[cps->nrOptions].name), cps)) { if(!ParseOption(&(cps->option[cps->nrOptions++]), cps)) { // [HGM] options: add option feature - sprintf(buf, "rejected option %s\n", cps->option[--cps->nrOptions].name); + snprintf(buf, MSG_SIZ, "rejected option %s\n", cps->option[--cps->nrOptions].name); SendToProgram(buf, cps); continue; } if(cps->nrOptions >= MAX_OPTIONS) { cps->nrOptions--; - sprintf(buf, "%s engine has too many options\n", cps->which); + snprintf(buf, MSG_SIZ, "%s engine has too many options\n", cps->which); DisplayError(buf, 0); } continue; @@ -13795,7 +13835,7 @@ ParseFeatures(args, cps) /* unknown feature: complain and skip */ q = p; while (*q && *q != '=') q++; - sprintf(buf, "rejected %.*s\n", (int)(q-p), p); + snprintf(buf, MSG_SIZ,"rejected %.*s\n", (int)(q-p), p); SendToProgram(buf, cps); p = q; if (*p == '=') { @@ -13860,7 +13900,7 @@ NewSettingEvent(option, feature, command, value) char buf[MSG_SIZ]; if (gameMode == EditPosition) EditPositionDone(TRUE); - sprintf(buf, "%s%s %d\n", (option ? "option ": ""), command, value); + snprintf(buf, MSG_SIZ,"%s%s %d\n", (option ? "option ": ""), command, value); if(feature == NULL || *feature) SendToProgram(buf, &first); if (gameMode == TwoMachinesPlay) { if(feature == NULL || feature[(int*)&second - (int*)&first]) SendToProgram(buf, &second); @@ -13942,9 +13982,9 @@ DisplayMove(moveNumber) if (moveNumber == forwardMostMove - 1 && gameInfo.resultDetails != NULL) { if (gameInfo.resultDetails[0] == NULLCHAR) { - sprintf(res, " %s", PGNResult(gameInfo.result)); + snprintf(res, MSG_SIZ, " %s", PGNResult(gameInfo.result)); } else { - sprintf(res, " {%s} %s", + snprintf(res, MSG_SIZ, " {%s} %s", T_(gameInfo.resultDetails), PGNResult(gameInfo.result)); } } else { @@ -13954,7 +13994,7 @@ DisplayMove(moveNumber) if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) { DisplayMessage(res, cpThinkOutput); } else { - sprintf(message, "%d.%s%s%s", moveNumber / 2 + 1, + snprintf(message, MSG_SIZ, "%d.%s%s%s", moveNumber / 2 + 1, WhiteOnMove(moveNumber) ? " " : ".. ", parseList[moveNumber], res); DisplayMessage(message, cpThinkOutput); @@ -13973,7 +14013,7 @@ DisplayComment(moveNumber, text) if (moveNumber < 0 || parseList[moveNumber][0] == NULLCHAR) { safeStrCpy(title, "Comment", sizeof(title)/sizeof(title[0])); } else { - sprintf(title, "Comment on %d.%s%s", moveNumber / 2 + 1, + snprintf(title,MSG_SIZ, "Comment on %d.%s%s", moveNumber / 2 + 1, WhiteOnMove(moveNumber) ? " " : ".. ", parseList[moveNumber]); } @@ -13981,7 +14021,7 @@ DisplayComment(moveNumber, text) if(moveNumber >= 0 && (depth = pvInfoList[moveNumber].depth) > 0) { if(text == NULL) text = ""; score = pvInfoList[moveNumber].score; - sprintf(buf, "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100., + snprintf(buf,sizeof(buf)/sizeof(buf[0]), "%s%.2f/%d %d\n%s", score>0 ? "+" : "", score/100., depth, (pvInfoList[moveNumber].time+50)/100, text); text = buf; } @@ -14438,7 +14478,7 @@ TimeString(ms) /* convert milliseconds to tenths, rounding up */ double tenths = floor( ((double)(ms + 99L)) / 100.00 ); - sprintf(buf, " %03.1f ", tenths/10.0); + snprintf(buf,sizeof(buf)/sizeof(buf[0]), " %03.1f ", tenths/10.0); return buf; } @@ -14460,12 +14500,12 @@ TimeString(ms) second = second % 60; if (day > 0) - sprintf(buf, " %s%ld:%02ld:%02ld:%02ld ", + snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld:%02ld ", sign, day, hour, minute, second); else if (hour > 0) - sprintf(buf, " %s%ld:%02ld:%02ld ", sign, hour, minute, second); + snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%ld:%02ld:%02ld ", sign, hour, minute, second); else - sprintf(buf, " %s%2ld:%02ld ", sign, minute, second); + snprintf(buf, sizeof(buf)/sizeof(buf[0]), " %s%2ld:%02ld ", sign, minute, second); return buf; } @@ -14576,7 +14616,7 @@ PGNDate() clock = time((time_t *)NULL); tm = localtime(&clock); - sprintf(buf, "%04d.%02d.%02d", + snprintf(buf, MSG_SIZ, "%04d.%02d.%02d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); return StrSave(buf); } @@ -15178,12 +15218,13 @@ PopTail(Boolean annotate) nrMoves = savedLast[storedGames] - currentMove; if(annotate) { int cnt = 10; - if(!WhiteOnMove(currentMove)) sprintf(buf, "(%d...", currentMove+2>>1); + if(!WhiteOnMove(currentMove)) + snprintf(buf, sizeof(buf)/sizeof(buf[0]),"(%d...", currentMove+2>>1); else safeStrCpy(buf, "(", sizeof(buf)/sizeof(buf[0])); for(i=currentMove; i>1, SavePart(parseList[i])); - else sprintf(moveBuf, " %s", SavePart(parseList[i])); + snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0]), " %d. %s", i+2>>1, SavePart(parseList[i])); + else snprintf(moveBuf, sizeof(moveBuf)/sizeof(moveBuf[0])," %s", SavePart(parseList[i])); strcat(buf, moveBuf); if(commentList[i]) { strcat(buf, " "); strcat(buf, commentList[i]); } if(!--cnt) { strcat(buf, "\n"); cnt = 10; } diff --git a/childio.c b/childio.c index e0de2b6..31512a8 100644 --- a/childio.c +++ b/childio.c @@ -209,7 +209,7 @@ int PseudoTTY(pty_name) #ifdef PTY_NAME_SPRINTF PTY_NAME_SPRINTF #else - sprintf (pty_name, "/dev/pty%c%x", c, i); + sprintf (pty_name, "/dev/pty%c%x", c, i); #endif /* no PTY_NAME_SPRINTF */ #ifdef PTY_OPEN @@ -233,7 +233,7 @@ int PseudoTTY(pty_name) #ifdef PTY_TTY_NAME_SPRINTF PTY_TTY_NAME_SPRINTF #else - sprintf (pty_name, "/dev/tty%c%x", c, i); + sprintf (pty_name, "/dev/tty%c%x", c, i); #endif /* no PTY_TTY_NAME_SPRINTF */ #ifndef UNIPLUS if (access (pty_name, 6) != 0) diff --git a/engineoutput.c b/engineoutput.c index cf17e41..22b008c 100644 --- a/engineoutput.c +++ b/engineoutput.c @@ -349,7 +349,7 @@ static void UpdateControls( EngineOutputData * ed ) // int isPondering = FALSE; char s_label[MAX_NAME_LENGTH + 32]; - + char * name = ed->name; /* Label */ @@ -402,7 +402,7 @@ static void UpdateControls( EngineOutputData * ed ) strncpy( mov, ed->hint, sizeof(mov) ); mov[ sizeof(mov)-1 ] = '\0'; - sprintf( buf, "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index, + snprintf( buf, sizeof(buf)/sizeof(buf[0]), "[%d] %d/%d: %s [%02d:%02d:%02d]", ed->depth, ed->an_move_index, ed->an_move_count, mov, time_mins / 60, time_mins % 60, time_secs % 60 ); } @@ -421,10 +421,10 @@ static void UpdateControls( EngineOutputData * ed ) unsigned long nps_100 = ed->nodes / ed->time; if( nps_100 < 100000 ) { - sprintf( s_label, "NPS: %lu", nps_100 * 100 ); + snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %lu", nps_100 * 100 ); } else { - sprintf( s_label, "NPS: %.1fk", nps_100 / 10.0 ); + snprintf( s_label, sizeof(s_label)/sizeof(s_label[0]), "NPS: %.1fk", nps_100 / 10.0 ); } } @@ -442,26 +442,28 @@ static void UpdateControls( EngineOutputData * ed ) /* Nodes */ if( ed->nodes < 1000000 ) { - sprintf( s_nodes, u64Display, ed->nodes ); + snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), u64Display, ed->nodes ); } else { - sprintf( s_nodes, "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 ); + snprintf( s_nodes, sizeof(s_nodes)/sizeof(s_nodes[0]), "%.1fM", u64ToDouble(ed->nodes) / 1000000.0 ); } /* Score */ if( ed->score > 0 ) { - sprintf( s_score, "+%.2f", ed->score / 100.0 ); + snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "+%.2f", ed->score / 100.0 ); } else { - sprintf( s_score, "%.2f", ed->score / 100.0 ); + snprintf( s_score, sizeof(s_score)/sizeof(s_score[0]), "%.2f", ed->score / 100.0 ); } /* Time */ - sprintf( s_time, "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent ); + snprintf( s_time, sizeof(s_time)/sizeof(s_time[0]), "%d:%02d.%02d", time_secs / 60, time_secs % 60, time_cent ); /* Put all together... */ - if(ed->nodes == 0 && ed->score == 0 && ed->time == 0) sprintf( buf, "%3d\t", ed->depth ); else - sprintf( buf, "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time ); + if(ed->nodes == 0 && ed->score == 0 && ed->time == 0) + snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t", ed->depth ); + else + snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%3d\t%s\t%s\t%s\t", ed->depth, s_score, s_nodes, s_time ); /* Add PV */ buflen = strlen(buf); diff --git a/gamelist.c b/gamelist.c index 07619f2..028b961 100644 --- a/gamelist.c +++ b/gamelist.c @@ -435,7 +435,7 @@ char * GameListLine( int number, GameInfo * gameInfo ) break; case GLT_WHITE_ELO: if( gameInfo->whiteRating > 0 ) - sprintf( buf, "%d", gameInfo->whiteRating ); + sprintf( buf, "%d", gameInfo->whiteRating ); else safeStrCpy( buf, "?" , 2*MSG_SIZ); break; diff --git a/pgntags.c b/pgntags.c index 0a70df2..82dfc1d 100644 --- a/pgntags.c +++ b/pgntags.c @@ -155,41 +155,41 @@ static char *PGNTagsStatic(gameInfo) buf[0] = NULLCHAR; - sprintf(buf1, "[Event \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[Event \"%s\"]\n", gameInfo->event ? gameInfo->event : "?"); strcat(buf, buf1); - sprintf(buf1, "[Site \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[Site \"%s\"]\n", gameInfo->site ? gameInfo->site : "?"); strcat(buf, buf1); - sprintf(buf1, "[Date \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[Date \"%s\"]\n", gameInfo->date ? gameInfo->date : "?"); strcat(buf, buf1); - sprintf(buf1, "[Round \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[Round \"%s\"]\n", gameInfo->round ? gameInfo->round : "-"); strcat(buf, buf1); - sprintf(buf1, "[White \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[White \"%s\"]\n", gameInfo->white ? gameInfo->white : "?"); strcat(buf, buf1); - sprintf(buf1, "[Black \"%s\"]\n", + snprintf(buf1, MSG_SIZ, "[Black \"%s\"]\n", gameInfo->black ? gameInfo->black : "?"); strcat(buf, buf1); - sprintf(buf1, "[Result \"%s\"]\n", PGNResult(gameInfo->result)); + snprintf(buf1, MSG_SIZ, "[Result \"%s\"]\n", PGNResult(gameInfo->result)); strcat(buf, buf1); - + if (gameInfo->whiteRating >= 0 ) { - sprintf(buf1, "[WhiteElo \"%d\"]\n", gameInfo->whiteRating ); + snprintf(buf1, MSG_SIZ, "[WhiteElo \"%d\"]\n", gameInfo->whiteRating ); strcat(buf, buf1); } if ( gameInfo->blackRating >= 0 ) { - sprintf(buf1, "[BlackElo \"%d\"]\n", gameInfo->blackRating ); + snprintf(buf1, MSG_SIZ, "[BlackElo \"%d\"]\n", gameInfo->blackRating ); strcat(buf, buf1); - } + } if (gameInfo->timeControl != NULL) { - sprintf(buf1, "[TimeControl \"%s\"]\n", gameInfo->timeControl); + snprintf(buf1, MSG_SIZ, "[TimeControl \"%s\"]\n", gameInfo->timeControl); strcat(buf, buf1); } if (gameInfo->variant != VariantNormal) { - sprintf(buf1, "[Variant \"%s\"]\n", VariantName(gameInfo->variant)); + snprintf(buf1, MSG_SIZ, "[Variant \"%s\"]\n", VariantName(gameInfo->variant)); strcat(buf, buf1); } if (gameInfo->extraTags != NULL) { @@ -199,7 +199,7 @@ static char *PGNTagsStatic(gameInfo) } - + /* Print game info */ void PrintPGNTags(fp, gameInfo) @@ -235,7 +235,7 @@ char *PGNResult(result) case GameIsDrawn: return "1/2-1/2"; } -} +} /* Returns 0 for success, nonzero for error */ int @@ -256,7 +256,7 @@ ReplaceTags(tags, gameInfo) } else if (moveType == PGNTag) { err = ParsePGNTag(yy_text, gameInfo); if (err != 0) return err; - } + } } /* just one problem...if there is a result in the new tags, * DisplayMove() won't ever show it because ClearGameInfo() set diff --git a/pixmaps/convert.c b/pixmaps/convert.c index 2a82f91..f2c3afa 100644 --- a/pixmaps/convert.c +++ b/pixmaps/convert.c @@ -9,8 +9,8 @@ int sizeList[] = { 21, 25, 29, 33, 37, 40, 45, 49, 54, 58, 64, 72, 80, 87, 95, 108, 116, 129 }; -char *(pieceList[]) = {"p", "n", "b", "r", "q", "f", "e", "as", "c", "w", "m", - "o", "h", "a", "dk", "g", "d", "v", "l", "s", "u", "k", +char *(pieceList[]) = {"p", "n", "b", "r", "q", "f", "e", "as", "c", "w", "m", + "o", "h", "a", "dk", "g", "d", "v", "l", "s", "u", "k", "wp", "wl", "wn", "ws", "cv", NULL }; char kindList[] = "sow"; @@ -64,7 +64,7 @@ FloodFill(char a[130][130], int size, int x, int y) if(x < size-1) FloodFill(a, size, x+1, y); if(y < size-1) FloodFill(a, size, x, y+1); } - + } void Save(FILE *f, char *name, char data[130][130], int size, char *col, int depth) @@ -92,7 +92,10 @@ char data[130][130], oData[130][130], sData[130][130], wData[130][130]; main(int argc, char **argv) { - int i, j, k, d, cnt, p, s, t; char c, h, w, name[80], buf[80], transparent; + +#define BUFLEN 80 + + int i, j, k, d, cnt, p, s, t; char c, h, w, name[BUFLEN], buf[BUFLEN], transparent; FILE *f; transparent = argc > 1 && !strcmp(argv[1], "-t"); @@ -101,20 +104,20 @@ main(int argc, char **argv) // Load the 3 kinds of Windows monochrome bitmaps (outline, solid, white fill) - sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'o'); + snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'o'); printf("try %s\n", buf); f = fopen(buf, "rb"); if(f == NULL) continue; Load(f, oData, buf); - sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 's'); + snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 's'); f = fopen(buf, "rb"); if(f == NULL) continue; Load(f, sData, buf); - sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'w'); + snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", pieceList[p], sizeList[s], 'w'); if(pieceList[p][0]=='w') - sprintf(buf, "../winboard/bitmaps/%s%d%c.bmp", "w", sizeList[s], 'w'); + snprintf(buf, BUFLEN, "../winboard/bitmaps/%s%d%c.bmp", "w", sizeList[s], 'w'); f = fopen(buf, "rb"); if(f == NULL) continue; Load(f, wData, buf); @@ -133,13 +136,13 @@ main(int argc, char **argv) FloodFill(data, d, d-1, d-1); } - sprintf(buf, "%s%s%d.xpm", pieceList[p], "dd", d); - sprintf(name, "%s%s%d", pieceList[p], "dd", d); + snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "dd", d); + snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "dd", d); f = fopen(buf, "w"); Save(f, name, data, d, "c green s dark_square", 3); - sprintf(buf, "%s%s%d.xpm", pieceList[p], "dl", d); - sprintf(name, "%s%s%d", pieceList[p], "dl", d); + snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "dl", d); + snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "dl", d); f = fopen(buf, "w"); Save(f, name, data, d, "c gray s light_square", 3); // silly duplication; pixmap is te same, but other color @@ -149,13 +152,13 @@ main(int argc, char **argv) Paint(data, wData, d, 'X'); // overay with white-filler piece bitmap Paint(data, oData, d, ' '); // overay with outline piece bitmaps - sprintf(buf, "%s%s%d.xpm", pieceList[p], "ld", d); - sprintf(name, "%s%s%d", pieceList[p], "ld", d); + snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "ld", d); + snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "ld", d); f = fopen(buf, "w"); Save(f, name, data, d, "c green s dark_square", 3); - sprintf(buf, "%s%s%d.xpm", pieceList[p], "ll", d); - sprintf(name, "%s%s%d", pieceList[p], "ll", d); + snprintf(buf, BUFLEN, "%s%s%d.xpm", pieceList[p], "ll", d); + snprintf(name, BUFLEN, "%s%s%d", pieceList[p], "ll", d); f = fopen(buf, "w"); Save(f, name, data, d, "c gray s light_square", 3); diff --git a/winboard/help.c b/winboard/help.c index 228e493..b114497 100644 --- a/winboard/help.c +++ b/winboard/help.c @@ -60,7 +60,7 @@ HtmlHelp( HWND hwnd, LPCSTR helpFile, UINT action, DWORD_PTR data ) siStartInfo.hStdOutput = NULL; siStartInfo.hStdError = debugFP; - sprintf(buf, "Hh.exe %s", helpFile); + snprintf(buf, sizeof(buf)/sizeof(buf[0]),"Hh.exe %s", helpFile); // ignore the other parameters; just start the viewer with the help file if( CreateProcess(NULL, diff --git a/winboard/jaws.c b/winboard/jaws.c index 8d7e42c..da9950d 100644 --- a/winboard/jaws.c +++ b/winboard/jaws.c @@ -92,7 +92,7 @@ char *squareToNum[] = {"naught", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; char *ordinals[] = {"zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth"}; char *pieceToName[] = { - "White Pawn", "White Knight", "White Bishop", "White Rook", "White Queen", + "White Pawn", "White Knight", "White Bishop", "White Rook", "White Queen", "White Guard", "White Elephant", "White Arch Bishop", "White Chancellor", "White General", "White Man", "White Cannon", "White Night Rider", "White Crowned Bishop", "White Crowned Rook", "White Grass Hopper", "White Veteran", @@ -108,13 +108,13 @@ char *pieceToName[] = { }; char *pieceTypeName[] = { - "Pawn", "Knight", "Bishop", "Rook", "Queen", + "Pawn", "Knight", "Bishop", "Rook", "Queen", "Guard", "Elephant", "Arch Bishop", "Chancellor", "General", "Man", "Cannon", "Night Rider", "Crowned Bishop", "Crowned Rook", "Grass Hopper", "Veteran", "Falcon", "Amazon", "Snake", "Unicorn", "King", - "Pawn", "Knight", "Bishop", "Rook", "Queen", + "Pawn", "Knight", "Bishop", "Rook", "Queen", "Guard", "Elephant", "Arch Bishop", "Chancellor", "General", "Man", "Cannon", "Night Rider", "Crowned Bishop", "Crowned Rook", "Grass Hopper", "Veteran", @@ -230,14 +230,14 @@ AdaptMenu() helpMenuInfo.cbSize = sizeof(helpMenuInfo); menuMain = GetMenu(hwndMain); menuJAWS = CreatePopupMenu(); - + for(i=0; menuItemJAWS[i].name; i++) { - if(menuItemJAWS[i].name[0] == '-') + if(menuItemJAWS[i].name[0] == '-') AppendMenu(menuJAWS, MF_SEPARATOR, (UINT_PTR) 0, NULL); - else AppendMenu(menuJAWS, MF_ENABLED|MF_STRING, + else AppendMenu(menuJAWS, MF_ENABLED|MF_STRING, (UINT_PTR) menuItemJAWS[i].code, (LPCTSTR) menuItemJAWS[i].name); } - InsertMenu(menuMain, 5, MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING, + InsertMenu(menuMain, 5, MF_BYPOSITION|MF_POPUP|MF_ENABLED|MF_STRING, (UINT_PTR) menuJAWS, "&JAWS"); oldMenuItemState[6] = oldMenuItemState[5]; DrawMenuBar(hwndMain); @@ -248,7 +248,7 @@ InitJAWS() { // to be called at beginning of WinMain, after InitApplication and InitInstance HINSTANCE hApi = LoadLibrary("jfwapi32.dll"); if(!hApi) { - DisplayInformation("Missing jfwapi32.dll"); + DisplayInformation("Missing jfwapi32.dll"); return (FALSE); } @@ -331,7 +331,7 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) if(currentPiece != EmptySquare) { char buf[MSG_SIZ]; n = boards[currentMove][fromY][1]; - sprintf(buf, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s"); + snprintf(buf, MSG_SIZ, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s"); SayString(buf, TRUE); } } else @@ -340,7 +340,7 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) if(currentPiece != EmptySquare) { char buf[MSG_SIZ]; n = boards[currentMove][fromY][BOARD_WIDTH-2]; - sprintf(buf, "%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s"); + snprintf(buf, MSG)SIZ,"%d %s%s", n, PieceToName(currentPiece,0), n == 1 ? "" : "s"); SayString(buf, TRUE); } } else @@ -350,8 +350,8 @@ KeyboardEvent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) ynum = SquareToNum(fromY); if(currentPiece != EmptySquare) { // SayString(piece[0] == 'W' ? "white" : "black", TRUE); - sprintf(buf, "%s %s %s", xchar, ynum, piece); - } else sprintf(buf, "%s %s", xchar, ynum); + snprintf(buf, MSG_SIZ, "%s %s %s", xchar, ynum, piece); + } else snprintf(buf, MSG_SIZ, "%s %s", xchar, ynum); SayString(buf, TRUE); } return; @@ -481,15 +481,15 @@ PossibleAttacked() VOID ReadRow() { - ChessSquare currentpiece; + ChessSquare currentpiece; char *piece, *xchar, *ynum ; int xPos, count=0; ynum = SquareToNum(fromY); - + if(fromY < 0) return; for (xPos=BOARD_LEFT; xPos=BOARD_LEFT) { - currentpiece = boards[currentMove][yPos][xPos]; + currentpiece = boards[currentMove][yPos][xPos]; piece = PieceToName(currentpiece,1); xchar = SquareToChar(xPos); ynum = SquareToNum(yPos); @@ -582,10 +582,10 @@ SayUpperDiagnols() VOID SayLowerDiagnols() { - ChessSquare currentpiece; + ChessSquare currentpiece; char *piece, *xchar, *ynum ; int yPos, xPos; - + if(fromX < 0 || fromY < 0) return; if(fromX < BOARD_RGHT-1 && fromY > 0) { @@ -593,7 +593,7 @@ SayLowerDiagnols() yPos = fromY-1; xPos = fromX+1; while(yPos>=0 && xPos=0 && xPos>=BOARD_LEFT) { - currentpiece = boards[currentMove][yPos][xPos]; + currentpiece = boards[currentMove][yPos][xPos]; piece = PieceToName(currentpiece,1); xchar = SquareToChar(xPos); ynum = SquareToNum(yPos); @@ -628,11 +628,11 @@ SayLowerDiagnols() VOID SayKnightMoves() { - ChessSquare currentpiece, oldpiece; + ChessSquare currentpiece, oldpiece; char *piece, *xchar, *ynum ; oldpiece = boards[currentMove][fromY][fromX]; - if(oldpiece == WhiteKnight || oldpiece == BlackKnight) + if(oldpiece == WhiteKnight || oldpiece == BlackKnight) SayString("The possible squares a Knight could move to are", FALSE); else SayString("The squares a Knight could possibly attack from are", FALSE); @@ -666,7 +666,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY+1 < BOARD_HEIGHT && fromX+2 < BOARD_RGHT) { currentpiece = boards[currentMove][fromY+1][fromX+2]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -681,7 +681,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY-1 >= 0 && fromX+2 < BOARD_RGHT) { currentpiece = boards[currentMove][fromY-1][fromX+2]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -696,7 +696,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY-2 >= 0 && fromX+1 < BOARD_RGHT) { currentpiece = boards[currentMove][fromY-2][fromX+1]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -711,7 +711,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY-2 >= 0 && fromX-1 >= BOARD_LEFT) { currentpiece = boards[currentMove][fromY-2][fromX-1]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -726,7 +726,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY-1 >= 0 && fromX-2 >= BOARD_LEFT) { currentpiece = boards[currentMove][fromY-1][fromX-2]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -741,7 +741,7 @@ SayKnightMoves() SayString(piece, FALSE); } } - + if (fromY+1 < BOARD_HEIGHT && fromX-2 >= BOARD_LEFT) { currentpiece = boards[currentMove][fromY+1][fromX-2]; if(((oldpiece == WhiteKnight) && (currentpiece > WhiteKing)) @@ -761,7 +761,7 @@ SayKnightMoves() VOID SayPieces(ChessSquare p) { - ChessSquare currentpiece; + ChessSquare currentpiece; char *piece, *xchar, *ynum ; int yPos, xPos, count = 0; char buf[50]; @@ -769,13 +769,13 @@ SayPieces(ChessSquare p) if(p == WhitePlay) SayString("White pieces", FALSE); else if(p == BlackPlay) SayString("Black pieces", FALSE); else if(p == EmptySquare) SayString("Pieces", FALSE); else { - sprintf(buf, "%ss", PieceToName(p,1)); + snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%ss", PieceToName(p,1)); SayString(buf, FALSE); } SayString("are located", FALSE); for(yPos=0; yPos= BlackPawn && currentpiece <= BlackKing || p == WhitePlay && currentpiece >= WhitePawn && currentpiece <= WhiteKing ) piece = PieceToName(currentpiece,0); @@ -784,7 +784,7 @@ SayPieces(ChessSquare p) else if(p == currentpiece) piece = NULL; else continue; - + if(count == 0) SayString("at", FALSE); xchar = SquareToChar(xPos); ynum = SquareToNum(yPos); @@ -804,7 +804,7 @@ SayCurrentPos() char *piece, *xchar, *ynum ; if(fromX < BOARD_LEFT) { SayString("You strayed into the white holdings", FALSE); return; } if(fromX >= BOARD_RGHT) { SayString("You strayed into the black holdings", FALSE); return; } - currentpiece = boards[currentMove][fromY][fromX]; + currentpiece = boards[currentMove][fromY][fromX]; piece = PieceToName(currentpiece,1); ynum = SquareToNum(fromY); xchar = SquareToChar(fromX); @@ -814,7 +814,7 @@ SayCurrentPos() SayString(piece, FALSE); if(((fromX-BOARD_LEFT) ^ fromY)&1) SayString("on a light square",FALSE); - else + else SayString("on a dark square",FALSE); PossibleAttacked(); @@ -827,28 +827,32 @@ SayAllBoard() int Xpos, Ypos; ChessSquare currentpiece; char *piece, *ynum ; - + if(gameInfo.holdingsWidth) { int first = 0; for(Ypos=0; Ypos=BOARD_HEIGHT - gameInfo.holdingsSize; Ypos--) { int n = boards[currentMove][Ypos][1]; - if(n) { char buf[MSG_SIZ]; - if(!first++) SayString("black holds", FALSE); - currentpiece = boards[currentMove][Ypos][0]; - piece = PieceToName(currentpiece,0); - sprintf(buf, "%d %s%s", n, piece, (n==1 ? "" : "s") ); - SayString(buf, FALSE); + if(n) { + char buf[MSG_SIZ]; + if(!first++) + SayString("black holds", FALSE); + currentpiece = boards[currentMove][Ypos][0]; + piece = PieceToName(currentpiece,0); + snprintf(buf, MSG_SIZ, "%d %s%s", n, piece, (n==1 ? "" : "s") ); + SayString(buf, FALSE); } } } @@ -858,16 +862,17 @@ SayAllBoard() SayString(ynum, FALSE); SayString("rank", FALSE); for(Xpos=BOARD_LEFT; Xpos 1) { - sprintf(buf, "%d %ss", count, piece); - } else sprintf(buf, "%s", piece); + if(count > 1) + snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%d %ss", count, piece); + else + snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s", piece); Xpos--; SayString(buf, FALSE); } else { @@ -877,9 +882,9 @@ SayAllBoard() if(Xpos == BOARD_RGHT && oldX == BOARD_LEFT) SayString("all", FALSE); else{ - if(count > 1) { + if(count > 1) { char buf[10]; - sprintf(buf, "%d", count); + snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%d", count); SayString(buf, FALSE); } Xpos--; @@ -888,7 +893,7 @@ SayAllBoard() } } } - + } VOID @@ -903,12 +908,12 @@ SayWhosTurn() SayString("It is your opponents turn", FALSE); else SayString("It is your turn", FALSE); } else { - if(WhiteOnMove(currentMove)) + if(WhiteOnMove(currentMove)) SayString("White is on move here", FALSE); else SayString("Black is on move here", FALSE); } } - + extern char *commentList[]; VOID @@ -947,7 +952,7 @@ SayMachineMove(int evenIfDuplicate) c = 'W'; break; case IcsPlayingBlack: case MachinePlaysBlack: - c = 'B'; + c = 'B'; default: break; } @@ -955,7 +960,7 @@ SayMachineMove(int evenIfDuplicate) if(c != lastMover && !evenIfDuplicate) return; // line is thinking output of future move, ignore. if(2*moveNr - (dotCount < 2) == previousMove) return; // do not repeat same move; likely ponder output - sprintf(buf, "score %s %d at %d ply", + snprintf(buf, MSG_SIZ, "score %s %d at %d ply", score > 0 ? "plus" : score < 0 ? "minus" : "", (int) (fabs(score)*100+0.5), depth ); @@ -981,16 +986,16 @@ SayMachineMove(int evenIfDuplicate) n = 2*moveNr - (dotCount < 2); - if(previousMove != 2*moveNr + (dotCount > 1) || evenIfDuplicate) { + if(previousMove != 2*moveNr + (dotCount > 1) || evenIfDuplicate) { char number[20]; previousMove = 2*moveNr + (dotCount > 1); // remember move nr of move last spoken - sprintf(number, "%d", moveNr); + snprintf(number, sizeof(number)/sizeof(number[0]),"%d", moveNr); yPos = CoordToNum(messageText[len-1]); /* turn char coords to ints */ xPos = CoordToNum(messageText[len-2]); if(xPos < 0 || xPos > 11) return; // prevent crashes if no coord string available to speak if(yPos < 0 || yPos > 9) return; - currentpiece = boards[n][yPos][xPos]; + currentpiece = boards[n][yPos][xPos]; piece = PieceToName(currentpiece,0); ynum = SquareToNum(yPos); xchar = SquareToChar(xPos); @@ -1044,8 +1049,8 @@ SayMachineMove(int evenIfDuplicate) if(StrStr(messageText, " 1/2-1/2")) p = "game ends in a draw"; if(comment[0]) { if(p) { - if(!StrCaseStr(comment, "draw") && - !StrCaseStr(comment, "white") && + if(!StrCaseStr(comment, "draw") && + !StrCaseStr(comment, "white") && !StrCaseStr(comment, "black") ) { SayString(p, FALSE); SayString("due to", FALSE); @@ -1074,11 +1079,11 @@ SayClockTime() suppressClocks = 1; // if user is using alt+T command, no reason to display them if(abs(lastWhiteTime - whiteTimeRemaining) < 1000 && abs(lastBlackTime - blackTimeRemaining) < 1000) suppressClocks = 0; // back on after two requests in rapid succession - sprintf(buf1, "%s", TimeString(whiteTimeRemaining)); + snprintf(buf1, sizeof(buf1)/sizeof(buf1[0]),"%s", TimeString(whiteTimeRemaining)); str1 = buf1; SayString("White clock", FALSE); SayString(str1, FALSE); - sprintf(buf2, "%s", TimeString(blackTimeRemaining)); + snprintf(buf2, sizeof(buf2)/sizeof(buf2[0]), "%s", TimeString(blackTimeRemaining)); str2 = buf2; SayString("Black clock", FALSE); SayString(str2, FALSE); @@ -1101,7 +1106,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { ChessSquare currentpiece; char *piece; - + static BOOLEAN sameAgain = FALSE; switch (message) { case WM_KEYDOWN: @@ -1112,20 +1117,20 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) break; } else if(oldFromX != -1) { - + ChessSquare pdown, pup; pdown = boards[currentMove][oldFromY][oldFromX]; pup = boards[currentMove][fromY][fromX]; - + if (gameMode == EditPosition || !((WhitePawn <= pdown && pdown <= WhiteKing && WhitePawn <= pup && pup <= WhiteKing) || (BlackPawn <= pdown && pdown <= BlackKing && BlackPawn <= pup && pup <= BlackKing))) { /* EditPosition, empty square, or different color piece; - click-click move is possible */ + click-click move is possible */ char promoChoice = NULLCHAR; - + if (HasPromotionChoice(oldFromX, oldFromY, fromX, fromY, &promoChoice)) { if (appData.alwaysPromoteToQueen) { UserMoveEvent(oldFromX, oldFromY, fromX, fromY, 'q'); @@ -1134,7 +1139,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) toX = fromX; toY = fromY; fromX = oldFromX; fromY = oldFromY; PromotionPopup(hwnd); fromX = toX; fromY = toY; - } + } } else { UserMoveEvent(oldFromX, oldFromY, fromX, fromY, promoChoice); @@ -1142,13 +1147,13 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) oldFromX = oldFromY = -1; break; } - + } /* First downclick, or restart on a square with same color piece */ if (OKToStartUserMove(fromX, fromY)) { oldFromX = fromX; oldFromY = fromY; - currentpiece = boards[currentMove][fromY][fromX]; + currentpiece = boards[currentMove][fromY][fromX]; piece = PieceToName(currentpiece,1); SayString(piece, FALSE); SayString("selected", FALSE); @@ -1164,7 +1169,7 @@ KeyboardMove(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) if (sameAgain) { /* Clicked same square twice: abort click-click move */ oldFromX = oldFromY = -1; - currentpiece = boards[currentMove][fromY][fromX]; + currentpiece = boards[currentMove][fromY][fromX]; piece = PieceToName(currentpiece,0); SayString(piece, FALSE); SayString("unselected", FALSE); diff --git a/winboard/wchat.c b/winboard/wchat.c index 1f78605..1da04b7 100644 --- a/winboard/wchat.c +++ b/winboard/wchat.c @@ -3,7 +3,7 @@ * * Author: H.G.Muller (August 2009) * - * Copyright 2009, 2010 Free Software Foundation, Inc. + * Copyright 2009, 2010 Free Software Foundation, Inc. * * ------------------------------------------------------------------------ * @@ -193,7 +193,7 @@ LRESULT CALLBACK ChatProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam if(partner<0) { for(i=0; i is pressed while editing the filter, it's better to apply the filter rather than selecting the current game. @@ -287,16 +287,16 @@ LRESULT CALLBACK ChatProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam // from here on it could be back-end SaveInHistory(mess); if(!strcmp("whispers", chatPartner[partner])) - sprintf(buf, "whisper %s\n", mess); // WHISPER box uses "whisper" to send + snprintf(buf, MSG_SIZ, "whisper %s\n", mess); // WHISPER box uses "whisper" to send else if(!strcmp("shouts", chatPartner[partner])) - sprintf(buf, "shout %s\n", mess); // SHOUT box uses "shout" to send + snprintf(buf, MSG_SIZ, "shout %s\n", mess); // SHOUT box uses "shout" to send else { if(!atoi(chatPartner[partner])) { - sprintf(buf, "> %s\r\n", mess); // echo only tells to handle, not channel + snprintf(buf, MSG_SIZ, "> %s\r\n", mess); // echo only tells to handle, not channel InsertIntoMemo(hDlg, buf); - sprintf(buf, "xtell %s %s\n", chatPartner[partner], mess); + snprintf(buf, MSG_SIZ, "xtell %s %s\n", chatPartner[partner], mess); } else - sprintf(buf, "tell %s %s\n", chatPartner[partner], mess); + snprintf(buf, MSG_SIZ, "tell %s %s\n", chatPartner[partner], mess); } SendToICS(buf); break; @@ -360,12 +360,12 @@ void ChatPopUp(char *icsHandle) { FARPROC lpProc; int i, partner = -1; - + CheckMenuItem(GetMenu(hwndMain), IDM_NewChat, MF_CHECKED); for(i=0; iwhite_wins, stats->black_wins, stats->drawn ); @@ -153,7 +153,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) static SnapData sd; switch (message) { - case WM_INITDIALOG: + case WM_INITDIALOG: Translate(hDlg, DLG_GameList); GetWindowText( hDlg, szDlgTitle, sizeof(szDlgTitle) ); szDlgTitle[ sizeof(szDlgTitle)-1 ] = '\0'; @@ -203,13 +203,13 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) newSizeX, newSizeY); sizeX = newSizeX; sizeY = newSizeY; - } else + } else GetActualPlacement( gameListDialog, &wpGameList ); } GameListUpdateTitle( hDlg, _("Game List"), count, ((ListGame *) gameList.tailPred)->number, &stats ); // [HGM] always update title return FALSE; - + case WM_SIZE: newSizeX = LOWORD(lParam); newSizeY = HIWORD(lParam); @@ -230,7 +230,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case WM_EXITSIZEMOVE: return OnExitSizeMove( &sd, hDlg, wParam, lParam ); - + case WM_GETMINMAXINFO: /* Prevent resizing window too small */ mmi = (MINMAXINFO *) lParam; @@ -239,7 +239,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) break; case WM_COMMAND: - /* + /* [AS] If is pressed while editing the filter, it's better to apply the filter rather than selecting the current game. @@ -270,7 +270,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) return TRUE; } break; /* load the game*/ - + case OPT_GameListNext: nItem = SendDlgItemMessage(hDlg, OPT_GameListText, LB_GETCURSEL, 0, 0); nItem++; @@ -281,7 +281,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) } SendDlgItemMessage(hDlg, OPT_GameListText, LB_SETCURSEL, nItem, 0); break; /* load the game*/ - + case OPT_GameListPrev: nItem = SendDlgItemMessage(hDlg, OPT_GameListText, LB_GETCURSEL, 0, 0); nItem--; @@ -297,7 +297,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case IDC_GameListDoFilter: { char filter[MAX_FILTER_LENGTH+1]; - + if( GetDlgItemText( hDlg, IDC_GameListFilter, filter, sizeof(filter) ) >= 0 ) { filter[ sizeof(filter)-1 ] = '\0'; count = GameListToListBox( hDlg, TRUE, filter, &stats ); @@ -311,13 +311,13 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case OPT_GameListClose: GameListPopDown(); return TRUE; - + case OPT_GameListText: switch (HIWORD(wParam)) { case LBN_DBLCLK: nItem = SendMessage((HWND) lParam, LB_GETCURSEL, 0, 0); break; /* load the game*/ - + default: return FALSE; } @@ -376,7 +376,7 @@ GameListDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) VOID GameListPopUp(FILE *fp, char *filename) { FARPROC lpProc; - + gameFile = fp; if (gameFileName != filename) { if (gameFileName) free(gameFileName); @@ -407,7 +407,7 @@ VOID GameListPopDown(void) VOID GameListHighlight(int index) { if (gameListDialog == NULL) return; - SendDlgItemMessage(gameListDialog, OPT_GameListText, + SendDlgItemMessage(gameListDialog, OPT_GameListText, LB_SETCURSEL, index - 1, 0); } diff --git a/winboard/winboard.c b/winboard/winboard.c index 6f5e32e..b535d44 100644 --- a/winboard/winboard.c +++ b/winboard/winboard.c @@ -344,7 +344,7 @@ LoadLanguageFile(char *name) char buf[MSG_SIZ]; if(!name || name[0] == NULLCHAR) return; - sprintf(buf, "%s%s", name, strchr(name, '.') ? "" : ".lng"); // auto-append lng extension + snprintf(buf, MSG_SIZ, "%s%s", name, strchr(name, '.') ? "" : ".lng"); // auto-append lng extension if(!strcmp(buf, oldLanguage)) { barbaric = 1; return; } // this language already loaded; just switch on if((f = fopen(buf, "r")) == NULL) return; while((k = fgetc(f)) != EOF) { @@ -430,7 +430,7 @@ TranslateMenus(int addLanguage) for(j=GetMenuItemCount(subMenu)-1; j>=0; j--){ char buf[MSG_SIZ]; UINT k = GetMenuItemID(subMenu, j); - if(menuText[i][j]) + if(menuText[i][j]) safeStrCpy(buf, menuText[i][j], sizeof(buf)/sizeof(buf[0]) ); else { GetMenuString(subMenu, j, buf, MSG_SIZ, MF_BYPOSITION); menuText[i][j] = strdup(buf); // remember original on first change @@ -881,7 +881,7 @@ SetUserLogo() if(appData.autoLogo) { curName = UserName(); if(strcmp(curName, oldUserName)) { - sprintf(oldUserName, "logos\\%s.bmp", curName); + snprintf(oldUserName, MSG_SIZ, "logos\\%s.bmp", curName); userLogo = LoadImage( 0, oldUserName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); safeStrCpy(oldUserName, curName, sizeof(oldUserName)/sizeof(oldUserName[0]) ); } @@ -1004,7 +1004,7 @@ InitInstance(HINSTANCE hInstance, int nCmdShow, LPSTR lpCmdLine) } else if(appData.autoLogo) { if(appData.firstDirectory && appData.firstDirectory[0]) { char buf[MSG_SIZ]; - sprintf(buf, "%s/logo.bmp", appData.firstDirectory); + snprintf(buf, MSG_SIZ, "%s/logo.bmp", appData.firstDirectory); first.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); } } @@ -1018,11 +1018,11 @@ InitInstance(HINSTANCE hInstance, int nCmdShow, LPSTR lpCmdLine) } else if(appData.autoLogo) { char buf[MSG_SIZ]; if(appData.icsActive) { // [HGM] logo: in ICS mode second can be used for ICS - sprintf(buf, "logos\\%s.bmp", appData.icsHost); + snprintf(buf, MSG_SIZ, "logos\\%s.bmp", appData.icsHost); second.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); } else if(appData.secondDirectory && appData.secondDirectory[0]) { - sprintf(buf, "%s\\logo.bmp", appData.secondDirectory); + snprintf(buf, MSG_SIZ, "%s\\logo.bmp", appData.secondDirectory); second.programLogo = LoadImage( 0, buf, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE ); } } @@ -1289,7 +1289,7 @@ ParseColorName(char *name) &red, &green, &blue); } if (count != 3) { - sprintf(buf, _("Can't parse color name %s"), name); + snprintf(buf, MSG_SIZ, _("Can't parse color name %s"), name); DisplayError(buf, 0); return RGB(0, 0, 0); } @@ -2061,7 +2061,7 @@ DoLoadBitmap(HINSTANCE hinst, char *piece, int squareSize, char *suffix) { char name[128]; - sprintf(name, "%s%d%s", piece, squareSize, suffix); + snprintf(name, sizeof(name)/sizeof(name[0]), "%s%d%s", piece, squareSize, suffix); if (gameInfo.event && strcmp(gameInfo.event, "Easter Egg Hunt") == 0 && strcmp(name, "k80s") == 0) { @@ -2235,9 +2235,9 @@ InitDrawingSizes(BoardSize boardSize, int flags) /* Get text area sizes */ hdc = GetDC(hwndMain); if (appData.clockMode) { - sprintf(buf, _("White: %s"), TimeString(23*60*60*1000L)); + snprintf(buf, MSG_SIZ, _("White: %s"), TimeString(23*60*60*1000L)); } else { - sprintf(buf, _("White")); + snprintf(buf, MSG_SIZ, _("White")); } oldFont = SelectObject(hdc, font[boardSize][CLOCK_FONT]->hf); GetTextExtentPoint(hdc, buf, strlen(buf), &clockSize); @@ -4012,7 +4012,7 @@ SetupDropMenu(HMENU hmenu) dropEnables[i].piece); count = 0; while (p && *p++ == dropEnables[i].piece) count++; - sprintf(item, "%s %d", T_(dropEnables[i].name), count); + snprintf(item, MSG_SIZ, "%s %d", T_(dropEnables[i].name), count); enable = count > 0 || !appData.testLegality /*!!temp:*/ || (gameInfo.variant == VariantCrazyhouse && !appData.icsActive); @@ -4835,14 +4835,14 @@ WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) case IDM_AnalysisMode: if (!first.analysisSupport) { - sprintf(buf, _("%s does not support analysis"), first.tidy); + snprintf(buf, MSG_SIZ, _("%s does not support analysis"), first.tidy); DisplayError(buf, 0); } else { SAY("analyzing current position"); /* [DM] icsEngineAnlyze [HGM] Why is this front-end??? */ if (appData.icsActive) { if (gameMode != IcsObserving) { - sprintf(buf, "You are not observing a game"); + snprintf(buf, MSG_SIZ, "You are not observing a game"); DisplayError(buf, 0); /* secure check */ if (appData.icsEngineAnalyze) { @@ -4872,7 +4872,7 @@ WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) case IDM_AnalyzeFile: if (!first.analysisSupport) { char buf[MSG_SIZ]; - sprintf(buf, _("%s does not support analysis"), first.tidy); + snprintf(buf, MSG_SIZ, _("%s does not support analysis"), first.tidy); DisplayError(buf, 0); } else { if (!appData.showThinking) ToggleShowThinking(); @@ -5595,7 +5595,7 @@ MyLoadSound(MySound *ms) } if (!ok) { char buf[MSG_SIZ]; - sprintf(buf, _("Error loading sound %s"), ms->name); + snprintf(buf, MSG_SIZ, _("Error loading sound %s"), ms->name); DisplayError(buf, GetLastError()); } return ok; @@ -5990,10 +5990,10 @@ InitEngineBox(HWND hDlg, HWND hwndCombo, char* nthcp, char* nthd, char* nthdir, InitComboStringsFromOption(hwndCombo, nthnames); q = QuoteForFilename(nthcp); - sprintf(buf, "%s%s%s", q, nthcp, q); + snprintf(buf, MSG_SIZ, "%s%s%s", q, nthcp, q); if (*nthdir != NULLCHAR) { q = QuoteForFilename(nthdir); - sprintf(buf + strlen(buf), " /%s=%s%s%s", nthd, q, nthdir, q); + snprintf(buf + strlen(buf), MSG_SIZ, " /%s=%s%s%s", nthd, q, nthdir, q); } if (*nthcp == NULLCHAR) { SendMessage(hwndCombo, CB_SETCURSEL, (WPARAM) 0, (LPARAM) 0); @@ -6024,7 +6024,7 @@ StartupDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) secondChessProgramNames); hwndCombo = GetDlgItem(hDlg, OPT_ChessServerName); InitComboStringsFromOption(hwndCombo, icsNames); - sprintf(buf, "%s /icsport=%s", appData.icsHost, appData.icsPort); + snprintf(buf, MSG_SIZ, "%s /icsport=%s", appData.icsHost, appData.icsPort); if (*appData.icsHelper != NULLCHAR) { char *q = QuoteForFilename(appData.icsHelper); sprintf(buf + strlen(buf), " /icshelper=%s%s%s", q, appData.icsHelper, q); @@ -6464,7 +6464,7 @@ TypeInNameDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) SetUserLogo(); SetGameInfo(); if(gameMode == MachinePlaysWhite || gameMode == MachinePlaysBlack) { - sprintf(move, "%s vs. %s", gameInfo.white, gameInfo.black); + snprintf(move, MSG_SIZ, "%s vs. %s", gameInfo.white, gameInfo.black); DisplayTitle(move); } @@ -6795,12 +6795,12 @@ CommandX(HWND hwnd, char *command, BOOLEAN getname, BOOLEAN immediate) SendMessage(hwnd, EM_GETSELTEXT, 0, (LPARAM) name); } if (immediate) { - sprintf(buf, "%s %s", command, name); + snprintf(buf, MSG_SIZ, "%s %s", command, name); SetWindowText(hInput, buf); SendMessage(hInput, WM_CHAR, '\r', 0); } else { if(!strcmp(command, "chat")) { ChatPopUp(name); return; } - sprintf(buf, "%s %s ", command, name); /* trailing space */ + snprintf(buf, MSG_SIZ, "%s %s ", command, name); /* trailing space */ SetWindowText(hInput, buf); sel.cpMin = 999999; sel.cpMax = 999999; @@ -7366,7 +7366,8 @@ DisplayHoldingsCount(HDC hdc, int x, int y, int rightAlign, int copyNumber) HFONT oldFont; RECT rect; - if(copyNumber > 1) sprintf(buf, "%d", copyNumber); else buf[0] = 0; + if(copyNumber > 1) + snprintf(buf, sizeof(buf)/sizeof(buf[0]),"%d", copyNumber); else buf[0] = 0; oldFg = SetTextColor(hdc, RGB(255, 255, 255)); /* white */ oldBg = SetBkColor(hdc, RGB(0, 0, 0)); /* black */ @@ -7399,9 +7400,9 @@ DisplayAClock(HDC hdc, int timeRemaining, int highlight, if (appData.clockMode) { if (tinyLayout) - sprintf(buf, "%c %s %s", color[0], TimeString(timeRemaining), flagFell); + snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%c %s %s", color[0], TimeString(timeRemaining), flagFell); else - sprintf(buf, "%s:%c%s %s", color, (logoHeight>0 ? 0 : ' '), TimeString(timeRemaining), flagFell); + snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s:%c%s %s", color, (logoHeight>0 ? 0 : ' '), TimeString(timeRemaining), flagFell); str = buf; } else { str = color; @@ -7423,7 +7424,7 @@ DisplayAClock(HDC hdc, int timeRemaining, int highlight, rect, str, strlen(str), NULL); if(logoHeight > 0 && appData.clockMode) { RECT r; - sprintf(buf, "%s %s", buf+7, flagFell); + snprintf(buf, sizeof(buf)/sizeof(buf[0]), "%s %s", buf+7, flagFell); r.top = rect->top + logoHeight/2; r.left = rect->left; r.right = rect->right; @@ -8056,7 +8057,7 @@ DisplayTitle(char *str) host = "ICS"; else host = appData.icsHost; - sprintf(title, "%s: %s", szTitle, host); + snprintf(title, MSG_SIZ, "%s: %s", szTitle, host); } else if (appData.noChessProgram) { safeStrCpy(title, szTitle, sizeof(title)/sizeof(title[0]) ); } else { @@ -8121,14 +8122,14 @@ DisplayError(char *str, int error) NULL, error, LANG_NEUTRAL, (LPSTR) buf2, MSG_SIZ, NULL); if (len > 0) { - sprintf(buf, "%s:\n%s", str, buf2); + snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, buf2); } else { ErrorMap *em = errmap; while (em->err != 0 && em->err != error) em++; if (em->err != 0) { - sprintf(buf, "%s:\n%s", str, em->msg); + snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, em->msg); } else { - sprintf(buf, "%s:\nError code %d", str, error); + snprintf(buf, 2*MSG_SIZ, "%s:\nError code %d", str, error); } } } @@ -8163,14 +8164,14 @@ DisplayFatalError(char *str, int error, int exitStatus) NULL, error, LANG_NEUTRAL, (LPSTR) buf2, MSG_SIZ, NULL); if (len > 0) { - sprintf(buf, "%s:\n%s", str, buf2); + snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, buf2); } else { ErrorMap *em = errmap; while (em->err != 0 && em->err != error) em++; if (em->err != 0) { - sprintf(buf, "%s:\n%s", str, em->msg); + snprintf(buf, 2*MSG_SIZ, "%s:\n%s", str, em->msg); } else { - sprintf(buf, "%s:\nError code %d", str, error); + snprintf(buf, 2*MSG_SIZ, "%s:\nError code %d", str, error); } } str = buf; @@ -8301,7 +8302,7 @@ LRESULT CALLBACK NewGameFRC_Proc(HWND hDlg, UINT message, WPARAM wParam, LPARAM } return TRUE; case IDC_NFG_Random: - sprintf( buf, "%d", myrandom() ); /* [HGM] shuffle: no longer limit to 960 */ + snprintf( buf, sizeof(buf)/sizeof(buf[0]), "%d", myrandom() ); /* [HGM] shuffle: no longer limit to 960 */ SetDlgItemText(hDlg, IDC_NFG_Edit, buf ); return TRUE; } @@ -8453,7 +8454,7 @@ DisplayIcsInteractionTitle(char *str) { char consoleTitle[MSG_SIZ]; - sprintf(consoleTitle, "%s: %s", szConsoleTitle, str); + snprintf(consoleTitle, MSG_SIZ, "%s: %s", szConsoleTitle, str); SetWindowText(hwndConsole, consoleTitle); } @@ -9019,9 +9020,9 @@ OpenTelnet(char *host, char *port, ProcRef *pr) char cmdLine[MSG_SIZ]; if (port[0] == NULLCHAR) { - sprintf(cmdLine, "%s %s", appData.telnetProgram, host); + snprintf(cmdLine, MSG_SIZ, "%s %s", appData.telnetProgram, host); } else { - sprintf(cmdLine, "%s %s %s", appData.telnetProgram, host, port); + snprintf(cmdLine, MSG_SIZ, "%s %s %s", appData.telnetProgram, host, port); } return StartChildProcess(cmdLine, "", pr); } @@ -9120,7 +9121,7 @@ OpenCommPort(char *name, ProcRef *pr) char fullname[MSG_SIZ]; if (*name != '\\') - sprintf(fullname, "\\\\.\\%s", name); + snprintf(fullname, MSG_SIZ, "\\\\.\\%s", name); else safeStrCpy(fullname, name, sizeof(fullname)/sizeof(fullname[0]) ); @@ -9292,7 +9293,7 @@ OpenRcmd(char* host, char* user, char* cmd, ProcRef* pr) break; } prevStderrPort = fromPort; // remember port used - sprintf(stderrPortStr, "%d", fromPort); + snprintf(stderrPortStr, MSG_SIZ, "%d", fromPort); if (send(s, stderrPortStr, strlen(stderrPortStr) + 1, 0) == SOCKET_ERROR) { err = WSAGetLastError(); diff --git a/winboard/woptions.c b/winboard/woptions.c index 9460aa0..2913b68 100644 --- a/winboard/woptions.c +++ b/winboard/woptions.c @@ -54,7 +54,7 @@ extern HINSTANCE hInst; /* current instance */ extern HWND hwndMain; /* root window*/ extern BOOLEAN alwaysOnTop; extern RECT boardRect; -extern COLORREF lightSquareColor, darkSquareColor, whitePieceColor, +extern COLORREF lightSquareColor, darkSquareColor, whitePieceColor, blackPieceColor, highlightSquareColor, premoveHighlightColor; extern HPALETTE hPal; extern BoardSize boardSize; @@ -100,15 +100,15 @@ LRESULT CALLBACK SaveOptions(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK TimeControl(HWND, UINT, WPARAM, LPARAM); VOID ChangeBoardSize(BoardSize newSize); VOID PaintSampleSquare( - HWND hwnd, - int ctrlid, - COLORREF squareColor, + HWND hwnd, + int ctrlid, + COLORREF squareColor, COLORREF pieceColor, COLORREF squareOutlineColor, COLORREF pieceDetailColor, BOOL isWhitePiece, BOOL isMono, - HBITMAP pieces[3] + HBITMAP pieces[3] ); VOID PaintColorBlock(HWND hwnd, int ctrlid, COLORREF color); VOID SetBoardOptionEnables(HWND hDlg); @@ -196,9 +196,9 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) appData.icsActive || !appData.noChessProgram); EnableWindow(GetDlgItem(hDlg, OPT_PonderNextMove), !appData.noChessProgram); - EnableWindow(GetDlgItem(hDlg, OPT_PeriodicUpdates), + EnableWindow(GetDlgItem(hDlg, OPT_PeriodicUpdates), !appData.noChessProgram && !appData.icsActive); - EnableWindow(GetDlgItem(hDlg, OPT_ShowThinking), + EnableWindow(GetDlgItem(hDlg, OPT_ShowThinking), !appData.noChessProgram); return TRUE; @@ -207,7 +207,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) switch (LOWORD(wParam)) { case IDOK: /* Read changed options from the dialog box */ - + #define IS_CHECKED(x) (Boolean)IsDlgButtonChecked(hDlg, (x)) alwaysOnTop = IS_CHECKED(OPT_AlwaysOnTop); @@ -250,7 +250,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) ClearHighlights(); DrawPosition(FALSE, NULL); } - /* + /* * for some reason the redraw seems smoother when we invalidate * the board rect after the call to EndDialog() */ @@ -261,7 +261,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) InitDrawingSizes(boardSize, 0); } else if (oldShowButtonBar != appData.showButtonBar) { InitDrawingSizes(boardSize, 0); - } else if ((oldShowCoords != appData.showCoords) || + } else if ((oldShowCoords != appData.showCoords) || (oldBlindfold != appData.blindfold)) { InvalidateRect(hwndMain, &boardRect, FALSE); } @@ -278,7 +278,7 @@ GeneralOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) return FALSE; } -VOID +VOID GeneralOptionsPopup(HWND hwnd) { FARPROC lpProc; @@ -307,15 +307,15 @@ ChangeBoardSize(BoardSize newSize) VOID PaintSampleSquare( - HWND hwnd, - int ctrlid, - COLORREF squareColor, + HWND hwnd, + int ctrlid, + COLORREF squareColor, COLORREF pieceColor, COLORREF squareOutlineColor, COLORREF pieceDetailColor, BOOL isWhitePiece, BOOL isMono, - HBITMAP pieces[3] + HBITMAP pieces[3] ) { HBRUSH brushSquare; @@ -358,15 +358,15 @@ PaintSampleSquare( brushPiece = CreateSolidBrush(pieceColor); brushPieceDetail = CreateSolidBrush(pieceDetailColor); - /* - * first draw the rectangle + /* + * first draw the rectangle */ pen = CreatePen(PS_SOLID, BORDER, squareOutlineColor); oldPen = (HPEN) SelectObject(hdcMem, pen); oldBrushSquare = (HBRUSH)SelectObject(hdcMem, brushSquare); Rectangle(hdcMem, rect.left, rect.top, rect.right, rect.bottom); - /* + /* * now draw the piece */ if (isMono) { @@ -378,23 +378,23 @@ PaintSampleSquare( if (isWhitePiece) { oldBitmapTemp = SelectObject(hdcTemp, pieces[WHITE]); oldBrushPiece = SelectObject(hdcMem, brushPiece); - BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, + BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, hdcTemp, 0, 0, 0x00B8074A); /* Use black for outline of white pieces */ SelectObject(hdcTemp, pieces[OUTLINE]); - BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, + BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, hdcTemp, 0, 0, SRCAND); } else { /* Use square color for details of black pieces */ oldBitmapTemp = SelectObject(hdcTemp, pieces[SOLID]); oldBrushPiece = SelectObject(hdcMem, brushPiece); - BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, + BitBlt(hdcMem, x, y, SAMPLE_SQ_SIZE, SAMPLE_SQ_SIZE, hdcTemp, 0, 0, 0x00B8074A); } SelectObject(hdcMem, oldBrushPiece); SelectObject(hdcTemp, oldBitmapTemp); } - /* + /* * copy the memory dc to the screen */ SelectObject(hdcMem, bufferBitmap); @@ -403,7 +403,7 @@ PaintSampleSquare( rect.bottom - rect.top, hdcMem, rect.left, rect.top, SRCCOPY); SelectObject(hdcMem, oldBitmapMem); - /* + /* * clean up */ SelectObject(hdcMem, oldBrushPiece); @@ -466,7 +466,7 @@ SetBoardOptionEnables(HWND hDlg) } } -BoardSize +BoardSize BoardOptionsWhichRadio(HWND hDlg) { return (IsDlgButtonChecked(hDlg, OPT_SizeTiny) ? SizeTiny : @@ -572,7 +572,7 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) pieces[0] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "s"); pieces[1] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "w"); pieces[2] = DoLoadBitmap(hInst, "n", SAMPLE_SQ_SIZE, "o"); - + lsc = lightSquareColor; dsc = darkSquareColor; wpc = whitePieceColor; @@ -604,7 +604,7 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case WM_COMMAND: /* message: received a command */ switch (LOWORD(wParam)) { case IDOK: - /* + /* * if we call EndDialog() after the call to ChangeBoardSize(), * then ChangeBoardSize() does not take effect, although the new * boardSize is saved. Go figure... @@ -657,42 +657,42 @@ BoardOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) return TRUE; case OPT_ChooseLightSquareColor: - if (ChangeColor(hDlg, &lsc)) + if (ChangeColor(hDlg, &lsc)) PaintColorBlock(hDlg, OPT_LightSquareColor, lsc); PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc, TRUE, mono, pieces); break; case OPT_ChooseDarkSquareColor: - if (ChangeColor(hDlg, &dsc)) + if (ChangeColor(hDlg, &dsc)) PaintColorBlock(hDlg, OPT_DarkSquareColor, dsc); PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc, FALSE, mono, pieces); break; case OPT_ChooseWhitePieceColor: - if (ChangeColor(hDlg, &wpc)) + if (ChangeColor(hDlg, &wpc)) PaintColorBlock(hDlg, OPT_WhitePieceColor, wpc); PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc, TRUE, mono, pieces); break; case OPT_ChooseBlackPieceColor: - if (ChangeColor(hDlg, &bpc)) + if (ChangeColor(hDlg, &bpc)) PaintColorBlock(hDlg, OPT_BlackPieceColor, bpc); PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc, FALSE, mono, pieces); break; case OPT_ChooseHighlightSquareColor: - if (ChangeColor(hDlg, &hsc)) + if (ChangeColor(hDlg, &hsc)) PaintColorBlock(hDlg, OPT_HighlightSquareColor, hsc); PaintSampleSquare(hDlg, OPT_SampleLightSquare, lsc, wpc, hsc, bpc, TRUE, mono, pieces); break; case OPT_ChoosePremoveHighlightColor: - if (ChangeColor(hDlg, &phc)) + if (ChangeColor(hDlg, &phc)) PaintColorBlock(hDlg, OPT_PremoveHighlightColor, phc); PaintSampleSquare(hDlg, OPT_SampleDarkSquare, dsc, bpc, phc, wpc, FALSE, mono, pieces); @@ -908,7 +908,7 @@ NewVariantDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case WM_COMMAND: /* message: received a command */ switch (LOWORD(wParam)) { case IDOK: - /* + /* * if we call EndDialog() after the call to ChangeBoardSize(), * then ChangeBoardSize() does not take effect, although the new * boardSize is saved. Go figure... @@ -916,16 +916,17 @@ NewVariantDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) EndDialog(hDlg, TRUE); v = VariantWhichRadio(hDlg); - if(!appData.noChessProgram) { char *name = VariantName(v), buf[MSG_SIZ]; + if(!appData.noChessProgram) { + char *name = VariantName(v), buf[MSG_SIZ]; if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) { - /* [HGM] in protocol 2 we check if variant is suported by engine */ - sprintf(buf, _("Variant %s not supported by %s"), name, first.tidy); - DisplayError(buf, 0); - return TRUE; /* treat as _("Cancel") if first engine does not support it */ + /* [HGM] in protocol 2 we check if variant is suported by engine */ + snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), name, first.tidy); + DisplayError(buf, 0); + return TRUE; /* treat as _("Cancel") if first engine does not support it */ } else if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) { - sprintf(buf, _("Warning: second engine (%s) does not support this!"), second.tidy); - DisplayError(buf, 0); /* use of second engine is optional; only warn user */ + snprintf(buf, MSG_SIZ, r_("Warning: second engine (%s) does not support this!"), second.tidy); + DisplayError(buf, 0); /* use of second engine is optional; only warn user */ } } @@ -1038,12 +1039,12 @@ UpdateSampleText(HWND hDlg, int id, MyColorizeAttribs *mca) { CHARFORMAT cf; cf.cbSize = sizeof(CHARFORMAT); - cf.dwMask = + cf.dwMask = CFM_COLOR|CFM_CHARSET|CFM_BOLD|CFM_ITALIC|CFM_UNDERLINE|CFM_STRIKEOUT|CFM_FACE|CFM_SIZE; cf.crTextColor = mca->color; cf.dwEffects = mca->effects; safeStrCpy(cf.szFaceName, font[boardSize][CONSOLE_FONT]->mfp.faceName, sizeof(cf.szFaceName)/sizeof(cf.szFaceName[0]) ); - /* + /* * The 20.0 below is in fact documented. yHeight is expressed in twips. * A twip is 1/20 of a font's point size. See documentation of CHARFORMAT. * --msw @@ -1075,8 +1076,8 @@ ColorizeTextDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) CheckDlgButton(hDlg, OPT_Strikeout, (mca.effects & CFE_STRIKEOUT) != 0); /* get the current background color from the parent window */ - SendMessage(GetWindow(hDlg, GW_OWNER),WM_COMMAND, - (WPARAM)WM_USER_GetConsoleBackground, + SendMessage(GetWindow(hDlg, GW_OWNER),WM_COMMAND, + (WPARAM)WM_USER_GetConsoleBackground, (LPARAM)&background); /* set the background color */ @@ -1099,7 +1100,7 @@ ColorizeTextDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) cf.cbSize = sizeof(CHARFORMAT); cf.dwMask = CFM_COLOR; cf.crTextColor = mca.color; - SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, + SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf); } EndDialog(hDlg, TRUE); @@ -1203,7 +1204,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) #undef CHECK_BOX - sprintf(buf, "%d", appData.icsAlarmTime / 1000); + snprintf(buf, MSG_SIZ, "%d", appData.icsAlarmTime / 1000); SetDlgItemText(hDlg, OPT_IcsAlarmTime, buf); SetDlgItemText(hDlg, OPT_PremoveWhiteText, appData.premoveWhiteText); SetDlgItemText(hDlg, OPT_PremoveBlackText, appData.premoveBlackText); @@ -1248,7 +1249,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case WM_COMMAND: /* message: received a command */ switch (LOWORD(wParam)) { - case WM_USER_GetConsoleBackground: + case WM_USER_GetConsoleBackground: /* the ColorizeTextDialog needs the current background color */ colorref = (COLORREF *)lParam; *colorref = cbc; @@ -1313,20 +1314,20 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) cf.dwMask = CFM_COLOR; cf.crTextColor = ParseColorName(COLOR_NORMAL); - SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, + SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&cf); - SendDlgItemMessage(hwndConsole, OPT_ConsoleText, + SendDlgItemMessage(hwndConsole, OPT_ConsoleText, EM_SETBKGNDCOLOR, FALSE, background); - SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, + SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, EM_SETBKGNDCOLOR, FALSE, background); } if (cbc != consoleBackgroundColor) { consoleBackgroundColor = cbc; if (appData.colorize) { - SendDlgItemMessage(hwndConsole, OPT_ConsoleText, + SendDlgItemMessage(hwndConsole, OPT_ConsoleText, EM_SETBKGNDCOLOR, FALSE, consoleBackgroundColor); - SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, + SendDlgItemMessage(hwndConsole, OPT_ConsoleInput, EM_SETBKGNDCOLOR, FALSE, consoleBackgroundColor); } } @@ -1355,7 +1356,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case OPT_ChooseChannel1Color: ColorizeTextPopup(hDlg, ColorChannel1); - UpdateSampleText(hDlg, OPT_SampleChannel1, + UpdateSampleText(hDlg, OPT_SampleChannel1, &colorizeAttribs[ColorChannel1]); break; @@ -1411,7 +1412,7 @@ IcsOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case OPT_DefaultColors: for (i=0; i < NColorClasses - 1; i++) - ParseAttribs(&mca[i].color, + ParseAttribs(&mca[i].color, &mca[i].effects, defaultTextAttribs[i]); @@ -1476,21 +1477,21 @@ SetSampleFontText(HWND hwnd, int id, const MyFont *mf) POINT center; int len; - len = sprintf(buf, "%.0f pt. %s%s%s\n", - mf->mfp.pointSize, mf->mfp.faceName, - mf->mfp.bold ? " bold" : "", - mf->mfp.italic ? " italic" : ""); + len = snprintf(buf, MSG_SIZ, "%.0f pt. %s%s%s\n", + mf->mfp.pointSize, mf->mfp.faceName, + mf->mfp.bold ? " bold" : "", + mf->mfp.italic ? " italic" : ""); SetDlgItemText(hwnd, id, buf); hControl = GetDlgItem(hwnd, id); hdc = GetDC(hControl); SetMapMode(hdc, MM_TEXT); /* 1 pixel == 1 logical unit */ oldFont = SelectObject(hdc, mf->hf); - + /* get number of logical units necessary to display font name */ GetTextExtentPoint32(hdc, buf, len, &size); - /* calculate formatting rectangle in the rich edit control. + /* calculate formatting rectangle in the rich edit control. * May be larger or smaller than the actual control. */ GetClientRect(hControl, &rectClient); @@ -1616,7 +1617,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) if (commentDialog) { SendDlgItemMessage(commentDialog, OPT_CommentText, - WM_SETFONT, (WPARAM)font[boardSize][COMMENT_FONT]->hf, + WM_SETFONT, (WPARAM)font[boardSize][COMMENT_FONT]->hf, MAKELPARAM(TRUE, 0)); GetClientRect(GetDlgItem(commentDialog, OPT_CommentText), &rect); InvalidateRect(commentDialog, &rect, TRUE); @@ -1624,7 +1625,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) if (editTagsDialog) { SendDlgItemMessage(editTagsDialog, OPT_TagsText, - WM_SETFONT, (WPARAM)font[boardSize][EDITTAGS_FONT]->hf, + WM_SETFONT, (WPARAM)font[boardSize][EDITTAGS_FONT]->hf, MAKELPARAM(TRUE, 0)); GetClientRect(GetDlgItem(editTagsDialog, OPT_TagsText), &rect); InvalidateRect(editTagsDialog, &rect, TRUE); @@ -1632,7 +1633,7 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) if( moveHistoryDialog != NULL ) { SendDlgItemMessage(moveHistoryDialog, IDC_MoveHistory, - WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, + WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, MAKELPARAM(TRUE, 0)); SendMessage( moveHistoryDialog, WM_INITDIALOG, 0, 0 ); // InvalidateRect(editTagsDialog, NULL, TRUE); // [HGM] this ws improperly cloned? @@ -1640,10 +1641,10 @@ FontOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) if( engineOutputDialog != NULL ) { SendDlgItemMessage(engineOutputDialog, IDC_EngineMemo1, - WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, + WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, MAKELPARAM(TRUE, 0)); SendDlgItemMessage(engineOutputDialog, IDC_EngineMemo2, - WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, + WM_SETFONT, (WPARAM)font[boardSize][MOVEHISTORY_FONT]->hf, MAKELPARAM(TRUE, 0)); } @@ -1796,7 +1797,7 @@ InitSoundCombo(HWND hwndCombo, SoundComboData *scd) while (scd->label) { err = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM) T_(scd->label)); if (err != cnt++) { - sprintf(buf, "InitSoundCombo(): err '%d', cnt '%d'\n", + snprintf(buf, MSG_SIZ, "InitSoundCombo(): err '%d', cnt '%d'\n", (int)err, (int)cnt); MessageBox(NULL, buf, NULL, MB_OK); } @@ -1857,7 +1858,7 @@ void DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name) { int radio; - /* + /* * I think it's best to clear the combo and edit boxes. It looks stupid * to have a value from another sound event sitting there grayed out. */ @@ -1883,7 +1884,7 @@ DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name) radio = OPT_NoSound; } else { radio = OPT_BuiltInSound; - if (SendMessage(hCombo, CB_SELECTSTRING, (WPARAM) -1, + if (SendMessage(hCombo, CB_SELECTSTRING, (WPARAM) -1, (LPARAM) (name + 1)) == CB_ERR) { SendMessage(hCombo, CB_SETCURSEL, (WPARAM) -1, (LPARAM) 0); SendMessage(hCombo, WM_SETTEXT, (WPARAM) 0, (LPARAM) (name + 1)); @@ -1898,7 +1899,7 @@ DisplaySelectedSound(HWND hDlg, HWND hCombo, const char *name) SoundDialogSetEnables(hDlg, radio); CheckRadioButton(hDlg, OPT_NoSound, OPT_WavFile, radio); } - + char *builtInSoundNames[] = BUILT_IN_SOUND_NAMES; @@ -1940,16 +1941,16 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) case WM_COMMAND: /* message: received a command */ - if (((HWND)lParam == hSoundCombo) && + if (((HWND)lParam == hSoundCombo) && (HIWORD(wParam) == CBN_SELCHANGE)) { - /* + /* * the user has selected a new sound event. We must store the name for * the previously selected event, then retrieve the name for the - * newly selected event and update the dialog. + * newly selected event and update the dialog. */ radio = SoundDialogWhichRadio(hDlg); newName = strdup(SoundDialogGetName(hDlg, radio)); - + if (strcmp(newName, soundComboData[index].name) != 0) { free(soundComboData[index].name); soundComboData[index].name = newName; @@ -1960,13 +1961,13 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) /* now get the settings for the newly selected event */ index = SendMessage(hSoundCombo, CB_GETCURSEL, (WPARAM)0, (LPARAM)0); DisplaySelectedSound(hDlg, hBISN, soundComboData[index].name); - + return TRUE; } switch (LOWORD(wParam)) { case IDOK: - /* - * save the name for the currently selected sound event + /* + * save the name for the currently selected sound event */ radio = SoundDialogWhichRadio(hDlg); newName = strdup(SoundDialogGetName(hDlg, radio)); @@ -1990,7 +1991,7 @@ SoundOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) } for ( cc = (ColorClass)0; cc < NColorClasses - 2; cc++) { index = (int)cc + (int)NSoundClasses; - if (strcmp(soundComboData[index].name, + if (strcmp(soundComboData[index].name, textAttribs[cc].sound.name) != 0) { free(textAttribs[cc].sound.name); textAttribs[cc].sound.name = strdup(soundComboData[index].name); @@ -2171,7 +2172,7 @@ VOID PrintCommSettings(FILE *f, char *name, DCB *dcb) { char *flow = "??", *parity = "??", *stopBits = "??"; ComboData *cd; - + cd = cdParity; while (cd->label != NULL) { if (dcb->Parity == cd->value) { @@ -2261,7 +2262,7 @@ CommPortOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) hwndCombo = GetDlgItem(hDlg, OPT_DataRate); InitCombo(hwndCombo, cdDataRate); - sprintf(buf, "%u", (int)dcb.BaudRate); + snprintf(buf, MSG_SIZ, "%u", (int)dcb.BaudRate); if (SendMessage(hwndCombo, CB_SELECTSTRING, (WPARAM) -1, (LPARAM) buf) == CB_ERR) { SendMessage(hwndCombo, CB_SETCURSEL, (WPARAM) -1, (LPARAM) 0); SendMessage(hwndCombo, WM_SETTEXT, (WPARAM) 0, (LPARAM) buf); @@ -2367,7 +2368,7 @@ CommPortOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) } if (!SetCommState(hCommPort, (LPDCB) &dcb)) { err = GetLastError(); - switch(MessageBox(hDlg, + switch(MessageBox(hDlg, "Failed to set comm port state;\r\ninvalid options?", _("Option Error"), MB_ABORTRETRYIGNORE|MB_ICONQUESTION)) { case IDABORT: @@ -2436,7 +2437,7 @@ LoadOptions(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) /* Initialize the dialog items */ if (appData.timeDelay >= 0.0) { CheckDlgButton(hDlg, OPT_Autostep, TRUE); - sprintf(buf, "%.2g", appData.timeDelay); + snprintf(buf, MSG_SIZ, "%.2g", appData.timeDelay); SetDlgItemText(hDlg, OPT_ASTimeDelay, buf); } else { CheckDlgButton(hDlg, OPT_Autostep, FALSE); @@ -2476,7 +2477,7 @@ LoadOptions(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) } -VOID +VOID LoadOptionsPopup(HWND hwnd) { FARPROC lpProc = MakeProcInstance((FARPROC)LoadOptions, hInst); @@ -2584,9 +2585,9 @@ SaveOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) return TRUE; case OPT_AVBrowse: - f = OpenFileDialog(hDlg, "a", NULL, - appData.oldSaveStyle ? "gam" : "pgn", - GAME_FILT, _("Browse for Auto Save File"), + f = OpenFileDialog(hDlg, "a", NULL, + appData.oldSaveStyle ? "gam" : "pgn", + GAME_FILT, _("Browse for Auto Save File"), NULL, NULL, buf); if (f != NULL) { fclose(f); @@ -2975,7 +2976,7 @@ LRESULT CALLBACK UciOptionsDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM case IDC_BrowseForBook: { - char filter[] = { + char filter[] = { 'A','l','l',' ','F','i','l','e','s', 0, '*','.','*', 0, 'B','I','N',' ','F','i','l','e','s', 0, diff --git a/winboard/wsettings.c b/winboard/wsettings.c index a250e2e..a5d6ce6 100644 --- a/winboard/wsettings.c +++ b/winboard/wsettings.c @@ -1,7 +1,7 @@ /* * Engine-settings dialog. The complexity come from an attempt to present the engine-defined options * in a nicey formatted layout. To this end we first run a back-end pre-formatter, which will distribute - * the controls over two columns (the minimum required, as some are double width). It also takes care of + * the controls over two columns (the minimum required, as some are double width). It also takes care of * grouping options that start with the same word (mainly for "Polyglot ..." options). It assigns relative * suitability to break points between lines, and in the end decides if and where to break up the list * for display in multiple (2*N) columns. @@ -104,7 +104,7 @@ LayoutOptions(int firstOption, int endOption, char *groupName, Option *optionLis nextOption++; } // We now must be at the end, or looking at a spin or textbox (in nextType) - if(!stop) + if(!stop) nextType = Button; // kudge to flush remaining checks and combos undistorted // Take a new line if a spin follows combos or checks, or when we encounter a textbox if((combos+checks || nextType == TextBox) && layout&1) { @@ -122,7 +122,7 @@ LayoutOptions(int firstOption, int endOption, char *groupName, Option *optionLis if(nextType == TextBox && lastType == ComboBox) checkList[checks++] = comboList[--combos]; // Now append the checks behind the (remaining) combos to treat them as one group - for(i=0; i< checks; i++) + for(i=0; i< checks; i++) comboList[combos++] = checkList[i]; // emit the consecutive checks and combos in two columns right = combos/2; // rounded down if odd! @@ -189,7 +189,7 @@ DesignOptionDialog(ChessProgramState *cps) if( cps->option[k].name[j] != cps->option[k+groupSize].name[j]) break; groupNameLength = j; groupSize++; - + } if(groupSize > 3) { // We found a group to terminates the current section @@ -203,7 +203,7 @@ DesignOptionDialog(ChessProgramState *cps) } if(n != k) LayoutOptions(n, k, "", cps->option); // flush remaining solitary options // decide if and where we break into two column pairs - + // Emit buttons and add OK and cancel // for(k=0; kwhich), cps->tidy); + snprintf(title, MSG_SIZ, _("%s Engine Settings (%s)"), T_(cps->which), cps->tidy); title[0] &= ~32; // capitalize SetWindowText( hDlg, title); - for(i=0; ioption[j].name, new); else - if(changed == 1) sprintf(buf, "option %s=%s\n", cps->option[j].name, newText); + if(changed == 2) + snprintf(buf, MSG_SIZ, "option %s=%d\n", cps->option[j].name, new); else + if(changed == 1) + snprintf(buf, MSG_SIZ, "option %s=%s\n", cps->option[j].name, newText); if(changed) SendToProgram(buf, cps); } } @@ -376,7 +378,7 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa return TRUE; case IDCANCEL: - EndDialog( hDlg, 1 ); + EndDialog( hDlg, 1 ); return TRUE; default: @@ -385,10 +387,10 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa if( i>=2000 && i < 2000+2*(layout+buttons)) { j = layoutList[(i - 2000)/2]; if(j == -2) { - char filter[] = + char filter[] = "All files\0*.*\0BIN Files\0*.bin\0LOG Files\0*.log\0INI Files\0*.ini\0\0"; /* -{ +{ 'A','l','l',' ','F','i','l','e','s', 0, '*','.','*', 0, 'B','I','N',' ','F','i','l','e','s', 0, @@ -418,7 +420,7 @@ LRESULT CALLBACK SettingsProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lPa if( activeCps->option[j].type == SaveButton) GetOptionValues(hDlg, activeCps); else if( activeCps->option[j].type != Button) break; - sprintf(buf, "option %s\n", activeCps->option[j].name); + snprintf(buf, MSG_SIZ, "option %s\n", activeCps->option[j].name); SendToProgram(buf, activeCps); } break; @@ -484,7 +486,7 @@ void AddOption(int x, int y, Control type, int i) case Message: break; } - + } void @@ -495,7 +497,7 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps) template.header.cdit = 0; template.header.cx = 307; buttonRows = (buttons + 1 + 3)/4; // 4 per row, rounded up - if(nr > 50) { + if(nr > 50) { breakPoint = (nr+2*buttonRows+1)/2 & ~1; template.header.cx = 625; } @@ -503,9 +505,9 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps) for(i=0; i>1)-2, 301, 13*(boxList[k+1]-boxList[k]>>1)+8, + AddControl(x+2, y+13*(i>>1)-2, 301, 13*(boxList[k+1]-boxList[k]>>1)+8, 0x0082, WS_VISIBLE | WS_CHILD | SS_BLACKFRAME, 2400); - AddControl(x+60, y+13*(i>>1)-6, 10*groupNameList[k]/3, 10, + AddControl(x+60, y+13*(i>>1)-6, 10*groupNameList[k]/3, 10, 0x0082, SS_ENDELLIPSIS | WS_VISIBLE | WS_CHILD, 2*(i+MAX_OPTIONS)); } j = layoutList[i]; @@ -530,7 +532,7 @@ CreateDialogTemplate(int *layoutList, int nr, ChessProgramState *cps) template.header.style &= ~WS_VSCROLL; } -void +void EngineOptionsPopup(HWND hwnd, ChessProgramState *cps) { FARPROC lpProc = MakeProcInstance( (FARPROC) SettingsProc, hInst ); diff --git a/xboard.c b/xboard.c index 849ab40..e9925ae 100644 --- a/xboard.c +++ b/xboard.c @@ -1594,8 +1594,9 @@ ConvertToLine(int argc, char **argv) for(i=1; i (int)WhiteKing ? "w" : "", - pieceBitmapNames[piece], - ss, kind == SOLID ? 's' : 'o'); - ReadBitmap(&pieceBitmap2[kind][piece], buf, NULL, ss, ss); - if(piece <= (int)WhiteKing) - pieceBitmap[kind][piece] = pieceBitmap2[kind][piece]; + snprintf(buf, MSG_SIZ, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "", + pieceBitmapNames[piece], + ss, kind == SOLID ? 's' : 'o'); + ReadBitmap(&pieceBitmap2[kind][piece], buf, NULL, ss, ss); + if(piece <= (int)WhiteKing) + pieceBitmap[kind][piece] = pieceBitmap2[kind][piece]; } } @@ -3530,13 +3531,13 @@ void CreatePieces() for (kind = SOLID; kind <= (appData.monoMode ? OUTLINE : SOLID); kind++) { for (piece = (int) WhitePawn; piece <= (int) WhiteKing + 4; piece++) { - sprintf(buf, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "", - pieceBitmapNames[piece], - ss, kind == SOLID ? 's' : 'o'); - ReadBitmap(&pieceBitmap2[kind][piece], buf, - bib->bits[kind][piece], ss, ss); - if(piece <= (int)WhiteKing) - pieceBitmap[kind][piece] = pieceBitmap2[kind][piece]; + snprintf(buf, MSG_SIZ, "%s%c%u%c.bm", piece > (int)WhiteKing ? "w" : "", + pieceBitmapNames[piece], + ss, kind == SOLID ? 's' : 'o'); + ReadBitmap(&pieceBitmap2[kind][piece], buf, + bib->bits[kind][piece], ss, ss); + if(piece <= (int)WhiteKing) + pieceBitmap[kind][piece] = pieceBitmap2[kind][piece]; } } @@ -5991,7 +5992,7 @@ void AnalyzeModeProc(w, event, prms, nprms) /* [DM] icsEngineAnalyze [HGM] This is horrible code; reverse the gameMode and isEngineAnalyze tests! */ if (appData.icsActive) { if (gameMode != IcsObserving) { - sprintf(buf,_("You are not observing a game")); + snprintf(buf, MSG_SIZ, _("You are not observing a game")); DisplayError(buf, 0); /* secure check */ if (appData.icsEngineAnalyze) { @@ -7433,18 +7434,18 @@ Colorize(cc, continuation) if (textColors[(int)cc].bg > 0) { if (textColors[(int)cc].fg > 0) { - sprintf(buf, "\033[0;%d;%d;%dm", textColors[(int)cc].attr, - textColors[(int)cc].fg, textColors[(int)cc].bg); + snprintf(buf, MSG_SIZ, "\033[0;%d;%d;%dm", textColors[(int)cc].attr, + textColors[(int)cc].fg, textColors[(int)cc].bg); } else { - sprintf(buf, "\033[0;%d;%dm", textColors[(int)cc].attr, - textColors[(int)cc].bg); + snprintf(buf, MSG_SIZ, "\033[0;%d;%dm", textColors[(int)cc].attr, + textColors[(int)cc].bg); } } else { if (textColors[(int)cc].fg > 0) { - sprintf(buf, "\033[0;%d;%dm", textColors[(int)cc].attr, + snprintf(buf, MSG_SIZ, "\033[0;%d;%dm", textColors[(int)cc].attr, textColors[(int)cc].fg); } else { - sprintf(buf, "\033[0;%dm", textColors[(int)cc].attr); + snprintf(buf, MSG_SIZ, "\033[0;%dm", textColors[(int)cc].attr); } } count = strlen(buf); @@ -7713,11 +7714,11 @@ DisplayTimerLabel(w, color, timer, highlight) foregroundOrWarningColor = lowTimeWarningColor; if (appData.clockMode) { - sprintf(buf, "%s: %s", color, TimeString(timer)); - XtSetArg(args[0], XtNlabel, buf); + snprintf(buf, MSG_SIZ, "%s: %s", color, TimeString(timer)); + XtSetArg(args[0], XtNlabel, buf); } else { - sprintf(buf, "%s ", color); - XtSetArg(args[0], XtNlabel, buf); + snprintf(buf, MSG_SIZ, "%s ", color); + XtSetArg(args[0], XtNlabel, buf); } if (highlight) { diff --git a/xoptions.c b/xoptions.c index 630903a..92643c1 100644 --- a/xoptions.c +++ b/xoptions.c @@ -131,11 +131,11 @@ void ShuffleCallback(w, client_data, call_data) String name; Widget w2; Arg args[16]; - char buf[80]; - + char buf[MSG_SIZ]; + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _("cancel")) == 0) { ShufflePopDown(); return; @@ -147,7 +147,7 @@ void ShuffleCallback(w, client_data, call_data) return; } if (strcmp(name, _("random")) == 0) { - sprintf(buf, "%d", rand()); + snprintf(buf, MSG_SIZ, "%d", rand()); XtSetArg(args[0],XtNvalue, buf); // erase bad (non-numeric) value XtSetValues(XtParent(w), args, 1); return; @@ -156,7 +156,7 @@ void ShuffleCallback(w, client_data, call_data) int nr; String name; name = XawDialogGetValueString(w2 = XtParent(w)); if(sscanf(name ,"%d",&nr) != 1) { - sprintf(buf, "%d", appData.defaultFrcPosition); + snprintf(buf, MSG_SIZ, "%d", appData.defaultFrcPosition); XtSetArg(args[0],XtNvalue, buf); // erase bad (non-numeric) value XtSetValues(w2, args, 1); return; @@ -177,27 +177,27 @@ void ShufflePopUp() int x, y, i; int win_x, win_y; unsigned int mask; - char def[80]; - + char def[MSG_SIZ]; + i = 0; XtSetArg(args[i], XtNresizable, True); i++; XtSetArg(args[i], XtNwidth, DIALOG_SIZE); i++; shuffleShell = popup = XtCreatePopupShell(_("New Shuffle Game"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); - - sprintf(def, "%d\n", appData.defaultFrcPosition); + + snprintf(def, MSG_SIZ, "%d\n", appData.defaultFrcPosition); i = 0; XtSetArg(args[i], XtNlabel, _("Start-position number:")); i++; XtSetArg(args[i], XtNvalue, def); i++; XtSetArg(args[i], XtNborderWidth, 0); i++; dialog = XtCreateManagedWidget(_("Shuffle"), dialogWidgetClass, layout, args, i); - + // XtSetArg(args[0], XtNeditType, XawtextEdit); // [HGM] can't get edit to work decently // XtSetArg(args[1], XtNuseStringInPlace, False); // XtSetValues(dialog, args, 2); @@ -206,20 +206,20 @@ void ShufflePopUp() XawDialogAddButton(dialog, _("cancel"), ShuffleCallback, (XtPointer) dialog); XawDialogAddButton(dialog, _("random"), ShuffleCallback, (XtPointer) dialog); XawDialogAddButton(dialog, _("off"), ShuffleCallback, (XtPointer) dialog); - + XtRealizeWidget(popup); CatchDeleteWindow(popup, "ShufflePopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); shuffleUp = True; - + edit = XtNameToWidget(dialog, "*value"); XtSetKeyboardFocus(popup, edit); @@ -261,12 +261,12 @@ void TimeControlCallback(w, client_data, call_data) String name, txt; Widget w2; Arg args[16]; - char buf[80]; + char buf[MSG_SIZ]; int j; XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _("classical")) == 0) { if(tcInc == 0) return; j=0; @@ -281,7 +281,7 @@ void TimeControlCallback(w, client_data, call_data) XtGetValues(tcData, args, j); tcIncrement = 0; sscanf(name, "%d", &tcIncrement); } - sprintf(buf, "%d", tcMoves); + snprintf(buf, MSG_SIZ, "%d", tcMoves); j=0; XtSetArg(args[j], XtNstring, buf); j++; XtSetValues(tcData, args, j); @@ -302,7 +302,7 @@ void TimeControlCallback(w, client_data, call_data) XtGetValues(tcData, args, j); tcMoves = appData.movesPerSession; sscanf(name, "%d", &tcMoves); } - sprintf(buf, "%d", tcIncrement); + snprintf(buf, MSG_SIZ, "%d", tcIncrement); j=0; XtSetArg(args[j], XtNstring, buf); j++; XtSetValues(tcData, args, j); @@ -369,10 +369,10 @@ void TimeControlCallback(w, client_data, call_data) } XtSetArg(args[0], XtNstring, &txt); XtGetValues(tcOdds1, args, 1); - appData.firstTimeOdds = first.timeOdds + appData.firstTimeOdds = first.timeOdds = (sscanf(txt, "%d", &j) == 1 && j > 0) ? j : 1; XtGetValues(tcOdds2, args, 1); - appData.secondTimeOdds = second.timeOdds + appData.secondTimeOdds = second.timeOdds = (sscanf(txt, "%d", &j) == 1 && j > 0) ? j : 1; Reset(True, True); @@ -389,12 +389,12 @@ void TimeControlPopUp() int x, y, i, j; int win_x, win_y; unsigned int mask; - char def[80]; - + char def[MSG_SIZ]; + tcInc = searchTime > 0 ? 2 : (appData.timeIncrement >= 0); tcMoves = appData.movesPerSession; tcIncrement = appData.timeIncrement; if(!tcInc) tcIncrement = 0; - sprintf(def, "%d", tcInc ? tcIncrement : tcMoves); + snprintf(def, MSG_SIZ, "%d", tcInc ? tcIncrement : tcMoves); i = 0; XtSetArg(args[i], XtNresizable, True); i++; @@ -402,15 +402,15 @@ void TimeControlPopUp() TimeControlShell = popup = XtCreatePopupShell(_("TimeControl Menu"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); - + form = XtCreateManagedWidget(layoutName, formWidgetClass, layout, formArgs, XtNumber(formArgs)); - + j = 0; // XtSetArg(args[j], XtNwidth, (XtArgVal) 300); j++; // XtSetArg(args[j], XtNheight, (XtArgVal) 85); j++; @@ -532,7 +532,7 @@ void TimeControlPopUp() XtSetArg(args[j], XtNright, XtChainLeft); j++; XtSetArg(args[j], XtNstate, tcInc==0); j++; b_clas= XtCreateManagedWidget(_("classical"), toggleWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_clas, XtNcallback, TimeControlCallback, (XtPointer) 0); j=0; @@ -545,7 +545,7 @@ void TimeControlPopUp() XtSetArg(args[j], XtNright, XtChainLeft); j++; XtSetArg(args[j], XtNstate, tcInc==1); j++; b_inc = XtCreateManagedWidget(_("incremental"), toggleWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_inc, XtNcallback, TimeControlCallback, (XtPointer) 0); j=0; @@ -558,7 +558,7 @@ void TimeControlPopUp() XtSetArg(args[j], XtNright, XtChainLeft); j++; XtSetArg(args[j], XtNstate, tcInc==2); j++; b_inc = XtCreateManagedWidget(_("fixed time"), toggleWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_inc, XtNcallback, TimeControlCallback, (XtPointer) 0); j=0; @@ -569,7 +569,7 @@ void TimeControlPopUp() XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; b_ok= XtCreateManagedWidget(_(" OK "), commandWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_ok, XtNcallback, TimeControlCallback, (XtPointer) 0); j=0; @@ -580,22 +580,22 @@ void TimeControlPopUp() XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; b_cancel= XtCreateManagedWidget(_("cancel"), commandWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_cancel, XtNcallback, TimeControlPopDown, (XtPointer) 0); XtRealizeWidget(popup); CatchDeleteWindow(popup, "TimeControlPopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); TimeControlUp = True; - + previous = NULL; SetFocus(tcTime, popup, (XEvent*) NULL, False); // XtSetKeyboardFocus(popup, tcTime); @@ -648,10 +648,10 @@ void EngineCallback(w, client_data, call_data) Arg args[16]; char buf[80]; int j; - + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _("OK")) == 0) { // read all switches appData.periodicUpdates = ReadToggle(w1); @@ -663,7 +663,7 @@ void EngineCallback(w, client_data, call_data) appData.materialDraws = ReadToggle(w7); appData.trivialDraws = ReadToggle(w8); - // adjust setting in other menu for duplicates + // adjust setting in other menu for duplicates // (perhaps duplicates should be removed from general Option Menu?) // XtSetArg(args[0], XtNleftBitmap, appData.showThinking ? xMarkPixmap : None); // XtSetValues(XtNameToWidget(menuBarWidget, @@ -674,7 +674,7 @@ void EngineCallback(w, client_data, call_data) XtGetValues(engDrawMoves, args, 1); if(sscanf(name, "%d", &j) == 1) appData.adjudicateDrawMoves = j; XtGetValues(engThreshold, args, 1); - if(sscanf(name, "%d", &j) == 1) + if(sscanf(name, "%d", &j) == 1) adjudicateLossThreshold = appData.adjudicateLossThreshold = -j; // inverted! XtGetValues(engRule, args, 1); if(sscanf(name, "%d", &j) == 1) appData.ruleMoves = j; @@ -690,17 +690,17 @@ void EngineCallback(w, client_data, call_data) void EnginePopUp() { Arg args[16]; - Widget popup, layout, form, edit, b_ok, b_cancel, b_clas, b_inc, s1; + Widget popup, layout, form, edit, b_ok, b_cancel, b_clas, b_inc, s1; Window root, child; int x, y, i, j, width; int win_x, win_y; unsigned int mask; - char def[80]; - + char def[MSG_SIZ]; + tcInc = (appData.timeIncrement >= 0); tcMoves = appData.movesPerSession; tcIncrement = appData.timeIncrement; if(!tcInc) tcIncrement = 0; - sprintf(def, "%d", tcInc ? tcIncrement : tcMoves); + snprintf(def, MSG_SIZ, "%d", tcInc ? tcIncrement : tcMoves); i = 0; XtSetArg(args[i], XtNresizable, True); i++; @@ -708,15 +708,15 @@ void EnginePopUp() EngineShell = popup = XtCreatePopupShell(_("Adjudications"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); - + form = XtCreateManagedWidget(layoutName, formWidgetClass, layout, formArgs, XtNumber(formArgs)); - + j = 0; // XtSetArg(args[j], XtNwidth, (XtArgVal) 250); j++; // XtSetArg(args[j], XtNheight, (XtArgVal) 400); j++; @@ -769,7 +769,7 @@ void EnginePopUp() XtSetArg(args[1], XtNborderWidth, (XtArgVal) 0); XtSetValues(s1, args, 2); - sprintf(def, "%d", appData.adjudicateDrawMoves); + snprintf(def, MSG_SIZ, "%d", appData.adjudicateDrawMoves); j= 0; XtSetArg(args[j], XtNborderWidth, 1); j++; XtSetArg(args[j], XtNfromVert, w8); j++; @@ -801,7 +801,7 @@ void EnginePopUp() // XtSetArg(args[j], XtNheight, 20); j++; tcMess1 = XtCreateManagedWidget("TCtext", labelWidgetClass, form, args, j); - sprintf(def, "%d", -appData.adjudicateLossThreshold); // inverted! + snprintf(def, MSG_SIZ, "%d", -appData.adjudicateLossThreshold); // inverted! j= 0; XtSetArg(args[j], XtNborderWidth, 1); j++; XtSetArg(args[j], XtNfromVert, engDrawMoves); j++; @@ -833,7 +833,7 @@ void EnginePopUp() // XtSetArg(args[j], XtNheight, 20); j++; tcMess2 = XtCreateManagedWidget("MPStext", labelWidgetClass, form, args, j); - sprintf(def, "%d", appData.ruleMoves); + snprintf(def, MSG_SIZ, "%d", appData.ruleMoves); j= 0; XtSetArg(args[j], XtNborderWidth, 1); j++; XtSetArg(args[j], XtNfromVert, engThreshold); j++; @@ -865,7 +865,7 @@ void EnginePopUp() // XtSetArg(args[j], XtNheight, 20); j++; tcMess1 = XtCreateManagedWidget("TCtext", labelWidgetClass, form, args, j); - sprintf(def, "%d", appData.drawRepeats); + snprintf(def, MSG_SIZ, "%d", appData.drawRepeats); j= 0; XtSetArg(args[j], XtNborderWidth, 1); j++; XtSetArg(args[j], XtNfromVert, engRule); j++; @@ -904,7 +904,7 @@ void EnginePopUp() XtSetArg(args[j], XtNtop, XtChainBottom); j++; XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; - b_ok= XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); + b_ok= XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); XtAddCallback(b_ok, XtNcallback, EngineCallback, (XtPointer) 0); j=0; @@ -915,22 +915,22 @@ void EnginePopUp() XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; b_cancel= XtCreateManagedWidget(_("cancel"), commandWidgetClass, - form, args, j); + form, args, j); XtAddCallback(b_cancel, XtNcallback, EnginePopDown, (XtPointer) 0); XtRealizeWidget(popup); CatchDeleteWindow(popup, "EnginePopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); EngineUp = True; - + previous = NULL; SetFocus(engThreshold, popup, (XEvent*) NULL, False); } @@ -1006,27 +1006,27 @@ void NewVariantCallback(w, client_data, call_data) String name; Widget w2; Arg args[16]; - char buf[80]; + char buf[MSG_SIZ]; VariantClass v; - + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _(" OK ")) == 0) { int nr = (intptr_t) XawToggleGetCurrent(buttonDesc[0].handle) - 1; if(nr < 0) return; v = buttonDesc[nr].variant; - if(!appData.noChessProgram) { + if(!appData.noChessProgram) { char *name = VariantName(v), buf[MSG_SIZ]; if (first.protocolVersion > 1 && StrStr(first.variants, name) == NULL) { /* [HGM] in protocol 2 we check if variant is suported by engine */ - sprintf(buf, _("Variant %s not supported by %s"), name, first.tidy); + snprintf(buf, MSG_SIZ, _("Variant %s not supported by %s"), name, first.tidy); DisplayError(buf, 0); // NewVariantPopDown(); return; /* ignore OK if first engine does not support it */ } else if (second.initDone && second.protocolVersion > 1 && StrStr(second.variants, name) == NULL) { - sprintf(buf, _("Warning: second engine (%s) does not support this!"), second.tidy); + snprintf(buf, MSG_SIZ, _("Warning: second engine (%s) does not support this!"), second.tidy); DisplayError(buf, 0); /* use of second engine is optional; only warn user */ } } @@ -1061,15 +1061,15 @@ void NewVariantPopUp() NewVariantShell = popup = XtCreatePopupShell(_("NewVariant Menu"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); - + form = XtCreateManagedWidget("form", formWidgetClass, layout, formArgs, XtNumber(formArgs)); - + for(i = 0; buttonDesc[i].name != NULL; i++) { Pixel buttonColor; if (!appData.monoMode) { @@ -1082,7 +1082,7 @@ void NewVariantPopUp() buttonColor = *(Pixel *) vTo.addr; } } - + j = 0; XtSetArg(args[j], XtNradioGroup, last); j++; XtSetArg(args[j], XtNwidth, 125); j++; @@ -1105,7 +1105,7 @@ void NewVariantPopUp() XtSetArg(args[j], XtNtop, XtChainBottom); j++; XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; - b_cancel= XtCreateManagedWidget(_("CANCEL"), commandWidgetClass, form, args, j); + b_cancel= XtCreateManagedWidget(_("CANCEL"), commandWidgetClass, form, args, j); XtAddCallback(b_cancel, XtNcallback, NewVariantPopDown, (XtPointer) 0); j=0; @@ -1117,7 +1117,7 @@ void NewVariantPopUp() XtSetArg(args[j], XtNtop, XtChainBottom); j++; XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; - b_ok= XtCreateManagedWidget(_(" OK "), commandWidgetClass, form, args, j); + b_ok= XtCreateManagedWidget(_(" OK "), commandWidgetClass, form, args, j); XtAddCallback(b_ok, XtNcallback, NewVariantCallback, (XtPointer) 0); j=0; @@ -1136,14 +1136,14 @@ void NewVariantPopUp() XtRealizeWidget(popup); CatchDeleteWindow(popup, "NewVariantPopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); NewVariantUp = True; } @@ -1195,10 +1195,10 @@ void UciCallback(w, client_data, call_data) Arg args[16]; char buf[80]; int oldCores = appData.smpCores, ponder = 0; - + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _("OK")) == 0) { int nr, i, j; String name; for(i=0; i<6; i++) { @@ -1208,7 +1208,7 @@ void UciCallback(w, client_data, call_data) if(name) *(char**) controlDesc[i].ptr = strdup(name); } else { - if(sscanf(name, "%d", &j) == 1) + if(sscanf(name, "%d", &j) == 1) *(int*) controlDesc[i].ptr = j; } } @@ -1221,7 +1221,7 @@ void UciCallback(w, client_data, call_data) XtSetArg(args[0], XtNstate, &ponder); XtGetValues(w4, args, 1); - // adjust setting in other menu for duplicates + // adjust setting in other menu for duplicates // (perhaps duplicates should be removed from general Option Menu?) XtSetArg(args[0], XtNleftBitmap, ponder ? xMarkPixmap : None); XtSetValues(XtNameToWidget(menuBarWidget, @@ -1248,24 +1248,24 @@ void UciPopUp() int x, y, i, j; int win_x, win_y; unsigned int mask; - char def[80]; - + char def[MSG_SIZ]; + i = 0; XtSetArg(args[i], XtNresizable, True); i++; // XtSetArg(args[i], XtNwidth, 300); i++; UciShell = popup = XtCreatePopupShell(_("Engine Settings"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); - - + + form = XtCreateManagedWidget("form", formWidgetClass, layout, formArgs, XtNumber(formArgs)); - + j = 0; XtSetArg(args[j], XtNtop, XtChainTop); j++; XtSetArg(args[j], XtNbottom, XtChainTop); j++; @@ -1291,10 +1291,10 @@ void UciPopUp() XtSetArg(args[j], XtNwidth, i&1 ? 245 : 50); j++; XtSetArg(args[j], XtNinsertPosition, 9999); j++; if(i&1) { - XtSetArg(args[j], XtNstring, * (char**) controlDesc[i].ptr ? + XtSetArg(args[j], XtNstring, * (char**) controlDesc[i].ptr ? * (char**) controlDesc[i].ptr : ""); j++; } else { - sprintf(def, "%d", * (int*) controlDesc[i].ptr); + snprintf(def, MSG_SIZ, "%d", * (int*) controlDesc[i].ptr); XtSetArg(args[j], XtNstring, def); j++; } XtSetArg(args[j], XtNfromHoriz, upperLeft); j++; @@ -1310,7 +1310,7 @@ void UciPopUp() XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; XtSetArg(args[j], XtNstate, appData.ponderNextMove); j++; - w4 = XtCreateManagedWidget(_("Ponder"), toggleWidgetClass, form, args, j); + w4 = XtCreateManagedWidget(_("Ponder"), toggleWidgetClass, form, args, j); j=0; XtSetArg(args[j], XtNfromVert, last); j++; @@ -1318,41 +1318,41 @@ void UciPopUp() XtSetArg(args[j], XtNtop, XtChainBottom); j++; XtSetArg(args[j], XtNleft, XtChainLeft); j++; XtSetArg(args[j], XtNright, XtChainLeft); j++; - b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); + b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); XtAddCallback(b_ok, XtNcallback, UciCallback, (XtPointer) 0); XtSetArg(args[j], XtNfromHoriz, b_ok); j++; - b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j); + b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j); XtAddCallback(b_cancel, XtNcallback, UciPopDown, (XtPointer) 0); j = 5; XtSetArg(args[j], XtNfromHoriz, upperLeft); j++; XtSetArg(args[j], XtNstate, appData.usePolyglotBook); j++; - w1 = XtCreateManagedWidget(_(" use book "), toggleWidgetClass, form, args, j); + w1 = XtCreateManagedWidget(_(" use book "), toggleWidgetClass, form, args, j); // XtAddCallback(w1, XtNcallback, UciCallback, (XtPointer) 0); j = 5; XtSetArg(args[j], XtNfromHoriz, w1); j++; XtSetArg(args[j], XtNstate, appData.firstHasOwnBookUCI); j++; - w2 = XtCreateManagedWidget(_("own book 1"), toggleWidgetClass, form, args, j); + w2 = XtCreateManagedWidget(_("own book 1"), toggleWidgetClass, form, args, j); // XtAddCallback(w2, XtNcallback, UciCallback, (XtPointer) 0); j = 5; XtSetArg(args[j], XtNfromHoriz, w2); j++; XtSetArg(args[j], XtNstate, appData.secondHasOwnBookUCI); j++; - w3 = XtCreateManagedWidget(_("own book 2"), toggleWidgetClass, form, args, j); + w3 = XtCreateManagedWidget(_("own book 2"), toggleWidgetClass, form, args, j); // XtAddCallback(w3, XtNcallback, UciCallback, (XtPointer) 0); XtRealizeWidget(popup); CatchDeleteWindow(popup, "UciPopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); UciUp = True; @@ -1397,10 +1397,10 @@ void SpinCallback(w, client_data, call_data) char buf[MSG_SIZ]; int i, j; int data = (intptr_t) client_data; - + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + j = 0; XtSetArg(args[0], XtNstring, &val); XtGetValues(currentCps->option[data].handle, args, 1); @@ -1411,7 +1411,7 @@ void SpinCallback(w, client_data, call_data) if (strcmp(name, "-") == 0) { if(--j < currentCps->option[data].min) return; } else return; - sprintf(buf, "%d", j); + snprintf(buf, MSG_SIZ, "%d", j); XtSetArg(args[0], XtNstring, buf); XtSetValues(currentCps->option[data].handle, args, 1); } @@ -1426,10 +1426,10 @@ void SettingsCallback(w, client_data, call_data) char buf[MSG_SIZ]; int i, j; int data = (intptr_t) client_data; - + XtSetArg(args[0], XtNlabel, &name); XtGetValues(w, args, 1); - + if (strcmp(name, _("cancel")) == 0) { SettingsPopDown(); return; @@ -1444,7 +1444,7 @@ void SettingsCallback(w, client_data, call_data) XtGetValues(currentCps->option[i].handle, args, 1); if(strcmp(currentCps->option[i].textValue, val)) { safeStrCpy(currentCps->option[i].textValue, val, sizeof(currentCps->option[i].textValue)/sizeof(currentCps->option[i].textValue[0])); - sprintf(buf, "option %s=%s\n", currentCps->option[i].name, val); + snprintf(buf, MSG_SIZ, "option %s=%s\n", currentCps->option[i].name, val); SendToProgram(buf, currentCps); } break; @@ -1456,7 +1456,7 @@ void SettingsCallback(w, client_data, call_data) if(j < currentCps->option[i].min) j = currentCps->option[i].min; if(currentCps->option[i].value != j) { currentCps->option[i].value = j; - sprintf(buf, "option %s=%d\n", currentCps->option[i].name, j); + snprintf(buf, MSG_SIZ, "option %s=%d\n", currentCps->option[i].name, j); SendToProgram(buf, currentCps); } break; @@ -1466,14 +1466,14 @@ void SettingsCallback(w, client_data, call_data) XtGetValues(currentCps->option[i].handle, args, 1); if(currentCps->option[i].value != j) { currentCps->option[i].value = j; - sprintf(buf, "option %s=%d\n", currentCps->option[i].name, j); + snprintf(buf, MSG_SIZ, "option %s=%d\n", currentCps->option[i].name, j); SendToProgram(buf, currentCps); } break; case ComboBox: if(currentCps->option[i].value != values[i]) { currentCps->option[i].value = values[i]; - sprintf(buf, "option %s=%s\n", currentCps->option[i].name, + snprintf(buf, MSG_SIZ, "option %s=%s\n", currentCps->option[i].name, ((char**)currentCps->option[i].textValue)[values[i]]); SendToProgram(buf, currentCps); } @@ -1481,13 +1481,13 @@ void SettingsCallback(w, client_data, call_data) } } if(data) { // send save-button command to engine - sprintf(buf, "option %s\n", name); - SendToProgram(buf, currentCps); + snprintf(buf, MSG_SIZ, "option %s\n", name); + SendToProgram(buf, currentCps); } SettingsPopDown(); return; } - sprintf(buf, "option %s\n", name); + snprintf(buf, MSG_SIZ, "option %s\n", name); SendToProgram(buf, currentCps); } @@ -1528,7 +1528,7 @@ void CreateComboPopup(parent, name, n, mb) (caddr_t)(intptr_t) (256*n+i)); i++; } -} +} void SettingsPopUp(ChessProgramState *cps) { @@ -1538,7 +1538,7 @@ void SettingsPopUp(ChessProgramState *cps) int x, y, i, j, height, width, h, c; int win_x, win_y, maxWidth, maxTextWidth; unsigned int mask; - char def[80], *p, *q; + char def[MSG_SIZ], *p, *q; static char pane[6] = "paneX"; Widget texts[100], forelast = NULL, anchor, widest; @@ -1553,7 +1553,7 @@ void SettingsPopUp(ChessProgramState *cps) SettingsShell = popup = XtCreatePopupShell(_("Settings Menu"), transientShellWidgetClass, shellWidget, args, i); - + layout = XtCreateManagedWidget(layoutName, formWidgetClass, popup, layoutArgs, XtNumber(layoutArgs)); @@ -1566,7 +1566,7 @@ void SettingsPopUp(ChessProgramState *cps) XtSetArg(args[j], XtNfromHoriz, leftMargin); j++; XtSetValues(form, args, j); leftMargin = form; - + last = widest = NULL; anchor = forelast; for(h=0; h= cps->nrOptions) break; switch(cps->option[i].type) { case Spin: - sprintf(def, "%d", cps->option[i].value); + snprintf(def, MSG_SIZ, "%d", cps->option[i].value); case TextBox: j=0; XtSetArg(args[j], XtNfromVert, last); j++; XtSetArg(args[j], XtNborderWidth, 0); j++; XtSetArg(args[j], XtNjustify, XtJustifyLeft); j++; texts[h] = - dialog = XtCreateManagedWidget(cps->option[i].name, labelWidgetClass, form, args, j); + dialog = XtCreateManagedWidget(cps->option[i].name, labelWidgetClass, form, args, j); j=0; XtSetArg(args[j], XtNfromVert, last); j++; XtSetArg(args[j], XtNfromHoriz, dialog); j++; @@ -1596,7 +1596,7 @@ void SettingsPopUp(ChessProgramState *cps) XtSetArg(args[j], XtNinsertPosition, 9999); j++; edit = last; cps->option[i].handle = (void*) - (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j)); + (textField = last = XtCreateManagedWidget("text", asciiTextWidgetClass, form, args, j)); XtAddEventHandler(last, ButtonPressMask, False, SetFocus, (XtPointer) popup); if(cps->option[i].type == TextBox) break; @@ -1625,8 +1625,8 @@ void SettingsPopUp(ChessProgramState *cps) XtSetArg(args[j], XtNwidth, 10); j++; XtSetArg(args[j], XtNheight, 10); j++; XtSetArg(args[j], XtNstate, cps->option[i].value); j++; - cps->option[i].handle = (void*) - (dialog = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j)); + cps->option[i].handle = (void*) + (dialog = XtCreateManagedWidget(" ", toggleWidgetClass, form, args, j)); j=0; XtSetArg(args[j], XtNfromVert, last); j++; XtSetArg(args[j], XtNfromHoriz, dialog); j++; @@ -1639,8 +1639,8 @@ void SettingsPopUp(ChessProgramState *cps) j=0; XtSetArg(args[j], XtNfromVert, last); j++; XtSetArg(args[j], XtNstate, cps->option[i].value); j++; - cps->option[i].handle = (void*) - (dialog = last = XtCreateManagedWidget(cps->option[i].name, commandWidgetClass, form, args, j)); + cps->option[i].handle = (void*) + (dialog = last = XtCreateManagedWidget(cps->option[i].name, commandWidgetClass, form, args, j)); XtAddCallback(last, XtNcallback, SettingsCallback, (XtPointer)(intptr_t) (cps->option[i].type == SaveButton)); break; @@ -1657,8 +1657,8 @@ void SettingsPopUp(ChessProgramState *cps) XtSetArg(args[j], XtNwidth, 100); j++; XtSetArg(args[j], XtNmenuName, XtNewString(cps->option[i].name)); j++; XtSetArg(args[j], XtNlabel, ((char**)cps->option[i].textValue)[cps->option[i].value]); j++; - cps->option[i].handle = (void*) - (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j)); + cps->option[i].handle = (void*) + (last = XtCreateManagedWidget(" ", menuButtonWidgetClass, form, args, j)); CreateComboPopup(last, cps->option[i].name, i, (char **) cps->option[i].textValue); values[i] = cps->option[i].value; break; @@ -1708,23 +1708,23 @@ void SettingsPopUp(ChessProgramState *cps) XtSetArg(args[j], XtNleft, XtChainRight); j++; XtSetArg(args[j], XtNright, XtChainRight); j++; XtSetArg(args[j], XtNfromHoriz, widest ? widest : dialog); j++; - b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); + b_ok = XtCreateManagedWidget(_("OK"), commandWidgetClass, form, args, j); XtAddCallback(b_ok, XtNcallback, SettingsCallback, (XtPointer) 0); XtSetArg(args[j-1], XtNfromHoriz, b_ok); - b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j); + b_cancel = XtCreateManagedWidget(_("cancel"), commandWidgetClass, form, args, j); XtAddCallback(b_cancel, XtNcallback, SettingsPopDown, (XtPointer) 0); XtRealizeWidget(popup); CatchDeleteWindow(popup, "SettingsPopDown"); - + XQueryPointer(xDisplay, xBoardWindow, &root, &child, &x, &y, &win_x, &win_y, &mask); - + XtSetArg(args[0], XtNx, x - 10); XtSetArg(args[1], XtNy, y - 30); XtSetValues(popup, args, 2); - + XtPopup(popup, XtGrabExclusive); SettingsUp = True; diff --git a/zic2xpm.c b/zic2xpm.c index d309e83..c2cda05 100644 --- a/zic2xpm.c +++ b/zic2xpm.c @@ -115,6 +115,7 @@ typedef struct { } z2xpm; #define NR_ZIICS_COLORS 4 +#define BUFLEN 100 /* SHOWSETS.PAS (from ZIICS) states that images may only use color numbers 0, 2, 14, and 15 */ @@ -441,7 +442,7 @@ int process_file_xim( filename ) int nr_pieces = 6; int nr_kinds = 4; FILE *fp; - char buf[100]; + char buf[BUFLEN]; src_name = filename; @@ -478,18 +479,18 @@ int process_file_xim( filename ) { printf( "." ); /* Form output filename -- .xim */ - sprintf(buf, "%c%s%d.xim", pieces[piece], prefixes[kind], w); + snprintf(buf, BUFLEN, "%c%s%d.xim", pieces[piece], prefixes[kind], w); create_piece_xim( buf, fp, w, h ); } printf("\n"); } /* Write the light & dark squares */ - sprintf( buf, "lsq%d.xim", w ); + snprintf( buf, BUFLEN, "lsq%d.xim", w ); printf("Light Square" ); create_piece_xim( buf, fp, w, h ); - sprintf( buf, "dsq%d.xim", w ); + snprintf( buf, BUFLEN, "dsq%d.xim", w ); printf("\nDark Square" ); create_piece_xim( buf, fp, w, h ); printf("\n"); @@ -508,7 +509,7 @@ int process_file_xpm( filename ) int nr_pieces = 6; int nr_kinds = 4; FILE *fp; - char buf[100]; + char buf[BUFLEN]; src_name = filename; @@ -545,18 +546,18 @@ int process_file_xpm( filename ) { printf( "." ); /* Form output filename -- .xpm */ - sprintf(buf, "%c%s%d.xpm", pieces[piece], prefixes[kind], w); + snprintf(buf, BUFLEN, "%c%s%d.xpm", pieces[piece], prefixes[kind], w); create_piece_xpm( buf, fp, w, h ); } printf("\n"); } /* Write the light & dark squares */ - sprintf( buf, "lsq%d.xpm", w ); + snprintf( buf, BUFLEN, "lsq%d.xpm", w ); printf("Light Square" ); create_piece_xpm( buf, fp, w, h ); - sprintf( buf, "dsq%d.xpm", w ); + snprintf( buf, BUFLEN, "dsq%d.xpm", w ); printf("\nDark Square" ); create_piece_xpm( buf, fp, w, h ); printf("\n"); diff --git a/zippy.c b/zippy.c index 849bdb1..9fdedc5 100644 --- a/zippy.c +++ b/zippy.c @@ -422,7 +422,7 @@ int ZippyControl(buf, i) (gameMode == IcsPlayingBlack && StrCaseCmp(player, gameInfo.white) == 0)) { - sprintf(reply, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n", + snprintf(reply, MSG_SIZ, "%ssay This computer does not play Crafty clones\n%sabort\n%s+noplay %s\n", ics_prefix, ics_prefix, ics_prefix, player); SendToICS(reply); } @@ -452,17 +452,17 @@ int ZippyControl(buf, i) looking_at(buf, i, "* tells you: [automatic message] I chose you"))) { player = StripHighlightAndTitle(star_match[0]); if (appData.zippyBughouse > 1 && first.initDone) { - sprintf(reply, "%spartner %s\n", ics_prefix, player); + snprintf(reply, MSG_SIZ,"%spartner %s\n", ics_prefix, player); SendToICS(reply); if (strcmp(zippyPartner, player) != 0) { safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0])); SendToProgram(reply + strlen(ics_prefix), &first); } } else if (appData.zippyBughouse > 0) { - sprintf(reply, "%sdecline %s\n", ics_prefix, player); + snprintf(reply, MSG_SIZ, "%sdecline %s\n", ics_prefix, player); SendToICS(reply); } else { - sprintf(reply, "%stell %s This computer cannot play bughouse\n", + snprintf(reply, MSG_SIZ, "%stell %s This computer cannot play bughouse\n", ics_prefix, player); SendToICS(reply); } @@ -472,7 +472,7 @@ int ZippyControl(buf, i) if (appData.zippyPlay && appData.zippyBughouse && first.initDone && looking_at(buf, i, "* agrees to be your partner")) { player = StripHighlightAndTitle(star_match[0]); - sprintf(reply, "partner %s\n", player); + snprintf(reply, MSG_SIZ, "partner %s\n", player); if (strcmp(zippyPartner, player) != 0) { safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0])); SendToProgram(reply, &first); @@ -507,10 +507,10 @@ int ZippyControl(buf, i) player = StripHighlightAndTitle(star_match[0]); if (strcmp(zippyPartner, player) != 0) { safeStrCpy(zippyPartner, player, sizeof(zippyPartner)/sizeof(zippyPartner[0])); - sprintf(reply, "partner %s\n", player); + snprintf(reply, MSG_SIZ, "partner %s\n", player); SendToProgram(reply, &first); } - sprintf(reply, "ptell %s\n", star_match[1]); + snprintf(reply, MSG_SIZ, "ptell %s\n", star_match[1]); SendToProgram(reply, &first); return TRUE; } @@ -538,7 +538,7 @@ int ZippyControl(buf, i) strlen(appData.zippyWrongPassword)) == 0) { p = star_match[1] + strlen(appData.zippyWrongPassword); while (*p == ' ') p++; - sprintf(reply, "wrong %s\n", player); + snprintf(reply, MSG_SIZ, "wrong %s\n", player); SendToICS(reply); } else if (appData.zippyBughouse && first.initDone && strcmp(player, zippyPartner) == 0) { @@ -547,12 +547,12 @@ int ZippyControl(buf, i) SendToProgram("\n", &first); } else if (strncmp(star_match[1], HI, 6) == 0) { extern char* programVersion; - sprintf(reply, "%stell %s %s\n", + snprintf(reply, MSG_SIZ, "%stell %s %s\n", ics_prefix, player, programVersion); SendToICS(reply); } else if (strncmp(star_match[1], "W0W!! ", 6) == 0) { extern char* programVersion; - sprintf(reply, "%stell %s %s\n", ics_prefix, + snprintf(reply, MSG_SIZ, "%stell %s %s\n", ics_prefix, player, programVersion); SendToICS(reply); } else if (appData.zippyTalk && (((unsigned) random() % 10) < 9)) { @@ -573,7 +573,7 @@ int ZippyControl(buf, i) if (looking_at(buf, i, "* spoofs you:")) { player = StripHighlightAndTitle(star_match[0]); - sprintf(reply, "spoofedby %s\n", player); + snprintf(reply, MSG_SIZ, "spoofedby %s\n", player); SendToICS(reply); } @@ -598,7 +598,7 @@ int ZippyConverse(buf, i) return TRUE; } else if (appData.zippyPinhead[0] != NULLCHAR && StrCaseStr(star_match[1], appData.zippyPinhead) != NULL) { - sprintf(reply, "insult %s\n", player); + snprintf(reply, MSG_SIZ, "insult %s\n", player); SendToICS(reply); } else if (ZippyCalled(star_match[1])) { Speak("shout", NULL); @@ -693,7 +693,7 @@ int ZippyConverse(buf, i) atoi(star_match[0]) != 0) || looking_at(buf, i, "* has left a message for you") || looking_at(buf, i, "* just sent you a message")) { - sprintf(reply, "%smessages\n%sclearmessages *\n", + snprintf(reply, MSG_SIZ, "%smessages\n%sclearmessages *\n", ics_prefix, ics_prefix); SendToICS(reply); return TRUE; @@ -703,7 +703,7 @@ int ZippyConverse(buf, i) if (((unsigned) random() % 3) == 0) { char *player = StripHighlightAndTitle(star_match[0]); safeStrCpy(lastgreet, player, sizeof(lastgreet)/sizeof(lastgreet[0])); - sprintf(reply, "greet %s\n", player); + snprintf(reply, MSG_SIZ, "greet %s\n", player); SendToICS(reply); Speak("tell", player); } @@ -712,7 +712,7 @@ int ZippyConverse(buf, i) if (looking_at(buf, i, "Notification: * has departed")) { if (((unsigned) random() % 3) == 0) { char *player = StripHighlightAndTitle(star_match[0]); - sprintf(reply, "farewell %s\n", player); + snprintf(reply, MSG_SIZ, "farewell %s\n", player); SendToICS(reply); } } @@ -720,7 +720,7 @@ int ZippyConverse(buf, i) if (looking_at(buf, i, "Not sent -- * is censoring you")) { char *player = StripHighlightAndTitle(star_match[0]); if (strcmp(player, lastgreet) == 0) { - sprintf(reply, "%s-notify %s\n", ics_prefix, player); + snprintf(reply, MSG_SIZ, "%s-notify %s\n", ics_prefix, player); SendToICS(reply); } } @@ -793,7 +793,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent) easier to use the ICS formula feature instead. */ if (variant == VariantLoadable) { - sprintf(buf, + snprintf(buf, MSG_SIZ, "%stell %s This computer can't play wild type %s\n%sdecline %s\n", ics_prefix, opponent, swild, ics_prefix, opponent); SendToICS(buf); @@ -802,7 +802,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent) if (StrStr(appData.zippyVariants, varname) == NULL || ((i=first.protocolVersion) != 1 && StrStr(first.variants, varname) == NULL) /* [HGM] zippyvar */ ) { - sprintf(buf, + snprintf(buf, MSG_SIZ, "%stell %s This computer can't play %s [%s], only %s\n%sdecline %s\n", ics_prefix, opponent, swild, varname, i ? first.variants : appData.zippyVariants, /* [HGM] zippyvar */ @@ -824,7 +824,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent) strcmp(opponent, zippyLastOpp) == 0 && zippyConsecGames >= appData.zippyMaxGames && difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) { - sprintf(buf, "%stell %s Sorry, you have just played %d consecutive games against %s. To give others a chance, please wait %d seconds or until someone else has played.\n%sdecline %s\n", + snprintf(buf, MSG_SIZ, "%stell %s Sorry, you have just played %d consecutive games against %s. To give others a chance, please wait %d seconds or until someone else has played.\n%sdecline %s\n", ics_prefix, opponent, zippyConsecGames, ics_handle, appData.zippyReplayTimeout, ics_prefix, opponent); SendToICS(buf); @@ -834,7 +834,7 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent) /* [HGM] aborter: opponent is cheater that aborts games he doesn't like on first move. Make him wait */ if (strcmp(opponent, zippyOffender) == 0 && difftime(time(0), zippyLastGameEnd) < appData.zippyReplayTimeout) { - sprintf(buf, "%stell %s Sorry, your previous game against %s was rather short. " + snprintf(buf, MSG_SIZ, "%stell %s Sorry, your previous game against %s was rather short. " " It will wait %d seconds to see if a tougher opponent comes along.\n%sdecline %s\n", ics_prefix, opponent, ics_handle, appData.zippyReplayTimeout, ics_prefix, opponent); @@ -844,13 +844,13 @@ void ZippyHandleChallenge(srated, swild, sbase, sincrement, opponent) /* Engine not yet initialized or still thinking about last game? */ if (!first.initDone || first.lastPing != first.lastPong) { - sprintf(buf, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n", + snprintf(buf, MSG_SIZ, "%stell %s I'm not quite ready for a new game yet; try again soon.\n%sdecline %s\n", ics_prefix, opponent, ics_prefix, opponent); SendToICS(buf); return; } - sprintf(buf, "%saccept %s\n", ics_prefix, opponent); + snprintf(buf, MSG_SIZ, "%saccept %s\n", ics_prefix, opponent); SendToICS(buf); if (appData.zippyTalk) { Speak("tell", opponent); @@ -999,7 +999,7 @@ void ZippyFirstBoard(moveNum, basetime, increment) /* Send the variant command if needed */ if (gameInfo.variant != VariantNormal) { - sprintf(buf, "variant %s\n", VariantName(gameInfo.variant)); + snprintf(buf, MSG_SIZ, "variant %s\n", VariantName(gameInfo.variant)); SendToProgram(buf, &first); } @@ -1010,7 +1010,7 @@ void ZippyFirstBoard(moveNum, basetime, increment) sentPos = TRUE; } - sprintf(buf, "level 0 %d %d\n", basetime, increment); + snprintf(buf, MSG_SIZ, "level 0 %d %d\n", basetime, increment); SendToProgram(buf, &first); /* Count consecutive games from one opponent */ @@ -1038,11 +1038,11 @@ void ZippyFirstBoard(moveNum, basetime, increment) firstMove = FALSE; if (gameMode == IcsPlayingWhite) { if (first.sendName) { - sprintf(buf, "name %s\n", gameInfo.black); + snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.black); SendToProgram(buf, &first); } safeStrCpy(ics_handle, gameInfo.white, MSG_SIZ); - sprintf(buf, "rating %d %d\n", w, b); + snprintf(buf, MSG_SIZ, "rating %d %d\n", w, b); SendToProgram(buf, &first); if (sentPos) { /* Position sent above, engine is in force mode */ @@ -1089,11 +1089,11 @@ void ZippyFirstBoard(moveNum, basetime, increment) } } else if (gameMode == IcsPlayingBlack) { if (first.sendName) { - sprintf(buf, "name %s\n", gameInfo.white); + snprintf(buf, MSG_SIZ, "name %s\n", gameInfo.white); SendToProgram(buf, &first); } safeStrCpy(ics_handle, gameInfo.black, MSG_SIZ); - sprintf(buf, "rating %d %d\n", b, w); + snprintf(buf, MSG_SIZ, "rating %d %d\n", b, w); SendToProgram(buf, &first); if (sentPos) { /* Position sent above, engine is in force mode */ @@ -1148,7 +1148,7 @@ ZippyHoldings(white_holding, black_holding, new_piece) { char buf[MSG_SIZ]; if (gameMode != IcsPlayingBlack && gameMode != IcsPlayingWhite) return; - sprintf(buf, "holding [%s] [%s] %s\n", + snprintf(buf, MSG_SIZ, "holding [%s] [%s] %s\n", white_holding, black_holding, new_piece); SendToProgram(buf, &first); }