From 191fecdc87592dfea94718bc716551c72f072c33 Mon Sep 17 00:00:00 2001
From: "jan.nijtmans" <nijtmans@users.sourceforge.net>
Date: Thu, 30 Mar 2023 15:19:44 +0000
Subject: Fix [0cb3554903]: macOS 13 SDK deprecates sprintf(). But better not
 use it on other platforms either.

---
 compat/zlib/contrib/minizip/minizip.c |  5 ++-
 doc/refchan.n                         |  2 +-
 generic/regcomp.c                     |  4 +-
 generic/regerror.c                    |  6 +--
 generic/tcl.h                         |  2 +-
 generic/tclBasic.c                    |  4 +-
 generic/tclCkalloc.c                  |  2 +-
 generic/tclClock.c                    |  6 +--
 generic/tclCompCmdsSZ.c               |  6 +--
 generic/tclCompile.h                  |  2 +-
 generic/tclDisassemble.c              | 20 +++++-----
 generic/tclHash.c                     |  8 ++--
 generic/tclIO.c                       | 12 +++---
 generic/tclIORChan.c                  |  2 +-
 generic/tclInt.h                      |  1 +
 generic/tclInterp.c                   |  2 +-
 generic/tclLiteral.c                  |  8 ++--
 generic/tclOO.c                       |  2 +-
 generic/tclObj.c                      |  8 ++--
 generic/tclPipe.c                     |  4 +-
 generic/tclRegexp.c                   |  2 +-
 generic/tclStrToD.c                   |  2 +-
 generic/tclStringObj.c                |  6 +--
 generic/tclTest.c                     | 54 +++++++++++++--------------
 generic/tclTestObj.c                  |  2 +-
 generic/tclTestProcBodyObj.c          |  4 +-
 generic/tclThreadAlloc.c              |  4 +-
 generic/tclThreadTest.c               |  4 +-
 generic/tclUtil.c                     |  4 +-
 generic/tclZlib.c                     |  6 +--
 unix/dltest/pkgb.c                    |  5 ++-
 unix/tclUnixChan.c                    | 12 +++---
 unix/tclUnixInit.c                    |  4 +-
 unix/tclUnixPipe.c                    |  6 +--
 unix/tclUnixSock.c                    |  8 ++--
 unix/tclUnixTest.c                    |  2 +-
 unix/tclUnixThrd.c                    |  2 +-
 win/tclWinChan.c                      |  5 ++-
 win/tclWinConsole.c                   | 17 ++++-----
 win/tclWinFCmd.c                      | 18 ++++-----
 win/tclWinFile.c                      |  2 +-
 win/tclWinInit.c                      | 70 ++++++-----------------------------
 win/tclWinInt.h                       |  2 -
 win/tclWinPipe.c                      | 22 +++++------
 win/tclWinReg.c                       |  4 +-
 win/tclWinSerial.c                    | 27 +++++++-------
 win/tclWinSock.c                      |  8 ++--
 win/tclWinThrd.c                      | 14 +++----
 48 files changed, 192 insertions(+), 230 deletions(-)

diff --git a/compat/zlib/contrib/minizip/minizip.c b/compat/zlib/contrib/minizip/minizip.c
index be1774f..0f0112b 100644
--- a/compat/zlib/contrib/minizip/minizip.c
+++ b/compat/zlib/contrib/minizip/minizip.c
@@ -66,6 +66,9 @@
 #ifdef _WIN32
         #define USEWIN32IOAPI
         #include "iowin32.h"
+#       if defined(_MSC_VER)
+#           define snprintf _snprintf
+#       endif
 #endif
 
 
@@ -375,7 +378,7 @@ void addPathToZip(zipFile zf, const char *filenameinzip, const char *password, i
         tinydir_readfile_n(&dir, &file, i);
         if(strcmp(file.name,".")==0) continue;
         if(strcmp(file.name,"..")==0) continue;
-        sprintf(newname,"%.*s/%.*s", MAXFILENAME, dir.path, MAXFILENAME, file.name);
+        snprintf(newname, sizeof(newname), "%.*s/%.*s", MAXFILENAME, dir.path, MAXFILENAME, file.name);
         if (file.is_dir)
         {
             addPathToZip(zf,newname,password,opt_exclude_path,opt_compress_level);
diff --git a/doc/refchan.n b/doc/refchan.n
index 1e7e733..edc9974 100644
--- a/doc/refchan.n
+++ b/doc/refchan.n
@@ -54,7 +54,7 @@ here, then the \fBfinalize\fR subcommand will not be called.
 The \fImode\fR argument tells the handler whether the channel was
 opened for reading, writing, or both. It is a list containing any of
 the strings \fBread\fR or \fBwrite\fR. The list may be empty, but
-will usually contain at least one element. 
+will usually contain at least one element.
 .PP
 The subcommand must throw an error if the chosen mode is not
 supported by the \fIcmdPrefix\fR.
diff --git a/generic/regcomp.c b/generic/regcomp.c
index d828b44..1d13876 100644
--- a/generic/regcomp.c
+++ b/generic/regcomp.c
@@ -2186,9 +2186,9 @@ stid(
 	return "unable";
     }
     if (t->id != 0) {
-	sprintf(buf, "%d", t->id);
+	snprintf(buf, bufsize, "%d", t->id);
     } else {
-	sprintf(buf, "%p", t);
+	snprintf(buf, bufsize, "%p", t);
     }
     return buf;
 }
diff --git a/generic/regerror.c b/generic/regerror.c
index f783217..361bd29 100644
--- a/generic/regerror.c
+++ b/generic/regerror.c
@@ -74,7 +74,7 @@ regerror(
 		break;
 	    }
 	}
-	sprintf(convbuf, "%d", r->code); /* -1 for unknown */
+	snprintf(convbuf, sizeof(convbuf), "%d", r->code); /* -1 for unknown */
 	msg = convbuf;
 	break;
     case REG_ITOA:		/* Convert number to name */
@@ -87,7 +87,7 @@ regerror(
 	if (r->code >= 0) {
 	    msg = r->name;
 	} else {		/* Unknown; tell him the number */
-	    sprintf(convbuf, "REG_%u", (unsigned)icode);
+	    snprintf(convbuf, sizeof(convbuf), "REG_%u", (unsigned)icode);
 	    msg = convbuf;
 	}
 	break;
@@ -100,7 +100,7 @@ regerror(
 	if (r->code >= 0) {
 	    msg = r->explain;
 	} else {		/* Unknown; say so */
-	    sprintf(convbuf, unk, code);
+	    snprintf(convbuf, sizeof(convbuf), unk, code);
 	    msg = convbuf;
 	}
 	break;
diff --git a/generic/tcl.h b/generic/tcl.h
index 8b7c4ed..942ca72 100644
--- a/generic/tcl.h
+++ b/generic/tcl.h
@@ -393,7 +393,7 @@ typedef long LONG;
  *
  * Note on converting between Tcl_WideInt and strings. This implementation (in
  * tclObj.c) depends on the function
- * sprintf(...,"%" TCL_LL_MODIFIER "d",...).
+ * snprintf(...,"%" TCL_LL_MODIFIER "d",...).
  */
 
 #if !defined(TCL_WIDE_INT_TYPE)&&!defined(TCL_WIDE_INT_IS_LONG)
diff --git a/generic/tclBasic.c b/generic/tclBasic.c
index e075701..63e7d75 100644
--- a/generic/tclBasic.c
+++ b/generic/tclBasic.c
@@ -1090,7 +1090,7 @@ Tcl_CallWhenDeleted(
     AssocData *dPtr = (AssocData *)ckalloc(sizeof(AssocData));
     Tcl_HashEntry *hPtr;
 
-    sprintf(buffer, "Assoc Data Key #%d", *assocDataCounterPtr);
+    snprintf(buffer, sizeof(buffer), "Assoc Data Key #%d", *assocDataCounterPtr);
     (*assocDataCounterPtr)++;
 
     if (iPtr->assocData == NULL) {
@@ -6348,7 +6348,7 @@ ProcessUnexpectedResult(
 	Tcl_SetObjResult(interp, Tcl_ObjPrintf(
 		"command returned bad code: %d", returnCode));
     }
-    sprintf(buf, "%d", returnCode);
+    snprintf(buf, sizeof(buf), "%d", returnCode);
     Tcl_SetErrorCode(interp, "TCL", "UNEXPECTED_RESULT_CODE", buf, NULL);
 }
 
diff --git a/generic/tclCkalloc.c b/generic/tclCkalloc.c
index 20285eb..986798d 100644
--- a/generic/tclCkalloc.c
+++ b/generic/tclCkalloc.c
@@ -183,7 +183,7 @@ TclDumpMemoryInfo(
     if (clientData == NULL) {
         return 0;
     }
-    sprintf(buf,
+    snprintf(buf, sizeof(buf),
 	    "total mallocs             %10d\n"
 	    "total frees               %10d\n"
 	    "current packets allocated %10d\n"
diff --git a/generic/tclClock.c b/generic/tclClock.c
index 13a5c65..d379762 100644
--- a/generic/tclClock.c
+++ b/generic/tclClock.c
@@ -1105,12 +1105,12 @@ ConvertUTCToLocalUsingC(
     } else {
 	*buffer = '+';
     }
-    sprintf(buffer+1, "%02d", diff / 3600);
+    snprintf(buffer+1, sizeof(buffer) - 1, "%02d", diff / 3600);
     diff %= 3600;
-    sprintf(buffer+3, "%02d", diff / 60);
+    snprintf(buffer+3, sizeof(buffer) - 3, "%02d", diff / 60);
     diff %= 60;
     if (diff > 0) {
-	sprintf(buffer+5, "%02d", diff);
+	snprintf(buffer+5, sizeof(buffer) - 5, "%02d", diff);
     }
     fields->tzName = Tcl_NewStringObj(buffer, -1);
     Tcl_IncrRefCount(fields->tzName);
diff --git a/generic/tclCompCmdsSZ.c b/generic/tclCompCmdsSZ.c
index db01dcd..5c2a0b6 100644
--- a/generic/tclCompCmdsSZ.c
+++ b/generic/tclCompCmdsSZ.c
@@ -837,7 +837,7 @@ TclCompileStringLenCmd(
 	char buf[TCL_INTEGER_SPACE];
 	int len = Tcl_GetCharLength(objPtr);
 
-	len = sprintf(buf, "%d", len);
+	len = snprintf(buf, sizeof(buf), "%d", len);
 	PushLiteral(envPtr, buf, len);
     } else {
 	SetLineInformation(1);
@@ -3073,7 +3073,7 @@ IssueTryClausesInstructions(
 
     for (i=0 ; i<numHandlers ; i++) {
 	noError[i] = -1;
-	sprintf(buf, "%d", matchCodes[i]);
+	snprintf(buf, sizeof(buf), "%d", matchCodes[i]);
 	OP(				DUP);
 	PushLiteral(envPtr, buf, strlen(buf));
 	OP(				EQ);
@@ -3285,7 +3285,7 @@ IssueTryClausesFinallyInstructions(
 	int noTrapError, trapError;
 	const char *p;
 
-	sprintf(buf, "%d", matchCodes[i]);
+	snprintf(buf, sizeof(buf), "%d", matchCodes[i]);
 	OP(				DUP);
 	PushLiteral(envPtr, buf, strlen(buf));
 	OP(				EQ);
diff --git a/generic/tclCompile.h b/generic/tclCompile.h
index 997f08e..bf814e8 100644
--- a/generic/tclCompile.h
+++ b/generic/tclCompile.h
@@ -1841,7 +1841,7 @@ MODULE_SCOPE void TclDTraceInfo(Tcl_Obj *info, const char **args, int *argsi);
     FILE *tclDTraceDebugLog = NULL;				\
     void TclDTraceOpenDebugLog(void) {				\
 	char n[35];						\
-	sprintf(n, "/tmp/tclDTraceDebug-%lu.log",		\
+	snprintf(n, sizeof(n), "/tmp/tclDTraceDebug-%lu.log",		\
 		(unsigned long) getpid());			\
 	tclDTraceDebugLog = fopen(n, "a");			\
     }
diff --git a/generic/tclDisassemble.c b/generic/tclDisassemble.c
index 4a61f69..4cae594 100644
--- a/generic/tclDisassemble.c
+++ b/generic/tclDisassemble.c
@@ -267,8 +267,8 @@ DisassembleByteCodeObj(
      * Print header lines describing the ByteCode.
      */
 
-    sprintf(ptrBuf1, "%p", codePtr);
-    sprintf(ptrBuf2, "%p", iPtr);
+    snprintf(ptrBuf1, sizeof(ptrBuf1), "%p", codePtr);
+    snprintf(ptrBuf2, sizeof(ptrBuf1), "%p", iPtr);
     Tcl_AppendPrintfToObj(bufferObj,
 	    "ByteCode 0x%s, refCt %u, epoch %u, interp 0x%s (epoch %u)\n",
 	    ptrBuf1, codePtr->refCount, codePtr->compileEpoch, ptrBuf2,
@@ -314,7 +314,7 @@ DisassembleByteCodeObj(
 	Proc *procPtr = codePtr->procPtr;
 	int numCompiledLocals = procPtr->numCompiledLocals;
 
-	sprintf(ptrBuf1, "%p", procPtr);
+	snprintf(ptrBuf1, sizeof(ptrBuf1), "%p", procPtr);
 	Tcl_AppendPrintfToObj(bufferObj,
 		"  Proc 0x%s, refCt %d, args %d, compiled locals %d\n",
 		ptrBuf1, procPtr->refCount, procPtr->numArgs,
@@ -564,22 +564,22 @@ FormatInstruction(
 	case OPERAND_UINT4:
 	    opnd = TclGetUInt4AtPtr(pc+numBytes); numBytes += 4;
 	    if (opCode == INST_START_CMD) {
-		sprintf(suffixBuffer+strlen(suffixBuffer),
+		snprintf(suffixBuffer+strlen(suffixBuffer), sizeof(suffixBuffer) - strlen(suffixBuffer),
 			", %u cmds start here", opnd);
 	    }
 	    Tcl_AppendPrintfToObj(bufferObj, "%u ", (unsigned) opnd);
 	    break;
 	case OPERAND_OFFSET1:
 	    opnd = TclGetInt1AtPtr(pc+numBytes); numBytes++;
-	    sprintf(suffixBuffer, "pc %u", pcOffset+opnd);
+	    snprintf(suffixBuffer, sizeof(suffixBuffer), "pc %u", pcOffset+opnd);
 	    Tcl_AppendPrintfToObj(bufferObj, "%+d ", opnd);
 	    break;
 	case OPERAND_OFFSET4:
 	    opnd = TclGetInt4AtPtr(pc+numBytes); numBytes += 4;
 	    if (opCode == INST_START_CMD) {
-		sprintf(suffixBuffer, "next cmd at pc %u", pcOffset+opnd);
+		snprintf(suffixBuffer, sizeof(suffixBuffer), "next cmd at pc %u", pcOffset+opnd);
 	    } else {
-		sprintf(suffixBuffer, "pc %u", pcOffset+opnd);
+		snprintf(suffixBuffer, sizeof(suffixBuffer), "pc %u", pcOffset+opnd);
 	    }
 	    Tcl_AppendPrintfToObj(bufferObj, "%+d ", opnd);
 	    break;
@@ -625,9 +625,9 @@ FormatInstruction(
 		    localPtr = localPtr->nextPtr;
 		}
 		if (TclIsVarTemporary(localPtr)) {
-		    sprintf(suffixBuffer, "temp var %u", (unsigned) opnd);
+		    snprintf(suffixBuffer, sizeof(suffixBuffer), "temp var %u", (unsigned) opnd);
 		} else {
-		    sprintf(suffixBuffer, "var ");
+		    snprintf(suffixBuffer, sizeof(suffixBuffer), "var ");
 		    suffixSrc = localPtr->name;
 		}
 	    }
@@ -827,7 +827,7 @@ UpdateStringOfInstName(
     int len;
 
     if ((inst < 0) || (inst > LAST_INST_OPCODE)) {
-        sprintf(buf, "inst_%d", inst);
+        snprintf(buf, sizeof(buf), "inst_%d", inst);
         s = buf;
     } else {
         s = (char *) tclInstructionTable[objPtr->internalRep.longValue].name;
diff --git a/generic/tclHash.c b/generic/tclHash.c
index 709831d..f4b0a47 100644
--- a/generic/tclHash.c
+++ b/generic/tclHash.c
@@ -678,18 +678,18 @@ Tcl_HashStats(
      */
 
     result = ckalloc((NUM_COUNTERS * 60) + 300);
-    sprintf(result, "%d entries in table, %d buckets\n",
+    snprintf(result, 60, "%d entries in table, %d buckets\n",
 	    tablePtr->numEntries, tablePtr->numBuckets);
     p = result + strlen(result);
     for (i = 0; i < NUM_COUNTERS; i++) {
-	sprintf(p, "number of buckets with %d entries: %d\n",
+	snprintf(p, 60, "number of buckets with %d entries: %d\n",
 		i, count[i]);
 	p += strlen(p);
     }
-    sprintf(p, "number of buckets with %d or more entries: %d\n",
+    snprintf(p, 60, "number of buckets with %d or more entries: %d\n",
 	    NUM_COUNTERS, overflow);
     p += strlen(p);
-    sprintf(p, "average search distance for entry: %.1f", average);
+    snprintf(p, 60, "average search distance for entry: %.1f", average);
     return result;
 }
 
diff --git a/generic/tclIO.c b/generic/tclIO.c
index 55b6bdc..b9223d9 100644
--- a/generic/tclIO.c
+++ b/generic/tclIO.c
@@ -7752,7 +7752,7 @@ Tcl_GetChannelOption(
     Tcl_DString *dsPtr)		/* Where to store value(s). */
 {
     size_t len;			/* Length of optionName string. */
-    char optionVal[128];	/* Buffer for sprintf. */
+    char optionVal[128];	/* Buffer for snprintf. */
     Channel *chanPtr = (Channel *) chan;
     ChannelState *statePtr = chanPtr->state;
 				/* State info for channel */
@@ -7859,9 +7859,10 @@ Tcl_GetChannelOption(
 	    if (statePtr->inEofChar == 0) {
 		Tcl_DStringAppendElement(dsPtr, "");
 	    } else {
-		char buf[4];
+		char buf[2];
 
-		sprintf(buf, "%c", statePtr->inEofChar);
+		buf[1] = '\0';
+		buf[0] = statePtr->inEofChar;
 		Tcl_DStringAppendElement(dsPtr, buf);
 	    }
 	}
@@ -7869,9 +7870,10 @@ Tcl_GetChannelOption(
 	    if (statePtr->outEofChar == 0) {
 		Tcl_DStringAppendElement(dsPtr, "");
 	    } else {
-		char buf[4];
+		char buf[2];
 
-		sprintf(buf, "%c", statePtr->outEofChar);
+		buf[1] = '\0';
+		buf[0] = statePtr->outEofChar;
 		Tcl_DStringAppendElement(dsPtr, buf);
 	    }
 	}
diff --git a/generic/tclIORChan.c b/generic/tclIORChan.c
index 482b0d5..c43cde8 100644
--- a/generic/tclIORChan.c
+++ b/generic/tclIORChan.c
@@ -3209,7 +3209,7 @@ ForwardProc(
 		 */
 
 		char *buf = (char *)ckalloc(200);
-		sprintf(buf,
+		snprintf(buf, 200,
 			"{Expected list with even number of elements, got %d %s instead}",
 			listc, (listc == 1 ? "element" : "elements"));
 
diff --git a/generic/tclInt.h b/generic/tclInt.h
index 3fa9a11..0a48039 100644
--- a/generic/tclInt.h
+++ b/generic/tclInt.h
@@ -121,6 +121,7 @@ typedef int ptrdiff_t;
 
 #if defined(_WIN32) && defined(_MSC_VER)
 #   define vsnprintf _vsnprintf
+#   define snprintf _snprintf
 #endif
 
 /*
diff --git a/generic/tclInterp.c b/generic/tclInterp.c
index 3ba27a1..62feaf1 100644
--- a/generic/tclInterp.c
+++ b/generic/tclInterp.c
@@ -803,7 +803,7 @@ NRInterpCmd(
 	    for (i = 0; ; i++) {
 		Tcl_CmdInfo cmdInfo;
 
-		sprintf(buf, "interp%d", i);
+		snprintf(buf, sizeof(buf), "interp%d", i);
 		if (Tcl_GetCommandInfo(interp, buf, &cmdInfo) == 0) {
 		    break;
 		}
diff --git a/generic/tclLiteral.c b/generic/tclLiteral.c
index 35c54be..5dab6d1 100644
--- a/generic/tclLiteral.c
+++ b/generic/tclLiteral.c
@@ -1120,18 +1120,18 @@ TclLiteralStats(
      */
 
     result = (char *)ckalloc(NUM_COUNTERS*60 + 300);
-    sprintf(result, "%d entries in table, %d buckets\n",
+    snprintf(result, 60, "%d entries in table, %d buckets\n",
 	    tablePtr->numEntries, tablePtr->numBuckets);
     p = result + strlen(result);
     for (i=0 ; i<NUM_COUNTERS ; i++) {
-	sprintf(p, "number of buckets with %d entries: %d\n",
+	snprintf(p, 60, "number of buckets with %d entries: %d\n",
 		i, count[i]);
 	p += strlen(p);
     }
-    sprintf(p, "number of buckets with %d or more entries: %d\n",
+    snprintf(p, 60, "number of buckets with %d or more entries: %d\n",
 	    NUM_COUNTERS, overflow);
     p += strlen(p);
-    sprintf(p, "average search distance for entry: %.1f", average);
+    snprintf(p, 60, "average search distance for entry: %.1f", average);
     return result;
 }
 #endif /*TCL_COMPILE_STATS*/
diff --git a/generic/tclOO.c b/generic/tclOO.c
index 043aa4c..b28efd8 100644
--- a/generic/tclOO.c
+++ b/generic/tclOO.c
@@ -661,7 +661,7 @@ AllocObject(
     while (1) {
 	char objName[10 + TCL_INTEGER_SPACE];
 
-	sprintf(objName, "::oo::Obj%d", ++fPtr->tsdPtr->nsCount);
+	snprintf(objName, sizeof(objName), "::oo::Obj%d", ++fPtr->tsdPtr->nsCount);
 	oPtr->namespacePtr = Tcl_CreateNamespace(interp, objName, oPtr, NULL);
 	if (oPtr->namespacePtr != NULL) {
 	    creationEpoch = fPtr->tsdPtr->nsCount;
diff --git a/generic/tclObj.c b/generic/tclObj.c
index 0fce557..fde12f6 100644
--- a/generic/tclObj.c
+++ b/generic/tclObj.c
@@ -2877,13 +2877,13 @@ UpdateStringOfWideInt(
     Tcl_WideInt wideVal = objPtr->internalRep.wideValue;
 
     /*
-     * Note that sprintf will generate a compiler warning under Mingw claiming
+     * Note that snprintf will generate a compiler warning under Mingw claiming
      * %I64 is an unknown format specifier. Just ignore this warning. We can't
      * use %L as the format specifier since that gets printed as a 32 bit
      * value.
      */
 
-    sprintf(buffer, "%" TCL_LL_MODIFIER "d", wideVal);
+    snprintf(buffer, sizeof(buffer), "%" TCL_LL_MODIFIER "d", wideVal);
     len = strlen(buffer);
     objPtr->bytes = (char *)ckalloc(len + 1);
     memcpy(objPtr->bytes, buffer, len + 1);
@@ -4496,7 +4496,7 @@ Tcl_RepresentationCmd(
      * "1872361827361287"
      */
 
-    sprintf(ptrBuffer, "%p", (void *) objv[1]);
+    snprintf(ptrBuffer, sizeof(ptrBuffer), "%p", (void *) objv[1]);
     descObj = Tcl_ObjPrintf("value is a %s with a refcount of %d,"
             " object pointer at %s",
             objv[1]->typePtr ? objv[1]->typePtr->name : "pure string",
@@ -4521,7 +4521,7 @@ Tcl_RepresentationCmd(
 	objv[1]->internalRep.twoPtrValue.ptr2 = NULL;
     }
     if (objv[1]->typePtr) {
-	sprintf(ptrBuffer, "%p:%p",
+	snprintf(ptrBuffer, sizeof(ptrBuffer), "%p:%p",
 		(void *) objv[1]->internalRep.twoPtrValue.ptr1,
 		(void *) objv[1]->internalRep.twoPtrValue.ptr2);
 	Tcl_AppendPrintfToObj(descObj, ", internal representation %s",
diff --git a/generic/tclPipe.c b/generic/tclPipe.c
index f5c82f1..9bb8997 100644
--- a/generic/tclPipe.c
+++ b/generic/tclPipe.c
@@ -323,10 +323,10 @@ TclCleanupChildren(
 	    char msg1[TCL_INTEGER_SPACE], msg2[TCL_INTEGER_SPACE];
 
 	    result = TCL_ERROR;
-	    sprintf(msg1, "%lu", resolvedPid);
+	    snprintf(msg1, sizeof(msg1), "%lu", resolvedPid);
 	    if (WIFEXITED(waitStatus)) {
 		if (interp != NULL) {
-		    sprintf(msg2, "%u", WEXITSTATUS(waitStatus));
+		    snprintf(msg2, sizeof(msg2), "%u", WEXITSTATUS(waitStatus));
 		    Tcl_SetErrorCode(interp, "CHILDSTATUS", msg1, msg2, NULL);
 		}
 		abnormalExit = 1;
diff --git a/generic/tclRegexp.c b/generic/tclRegexp.c
index bd923ba..3259b48 100644
--- a/generic/tclRegexp.c
+++ b/generic/tclRegexp.c
@@ -730,7 +730,7 @@ TclRegError(
     p = (n > sizeof(buf)) ? "..." : "";
     Tcl_SetObjResult(interp, Tcl_ObjPrintf("%s%s%s", msg, buf, p));
 
-    sprintf(cbuf, "%d", status);
+    snprintf(cbuf, sizeof(cbuf), "%d", status);
     (void) TclReError(REG_ITOA, cbuf, sizeof(cbuf));
     Tcl_SetErrorCode(interp, "REGEXP", cbuf, buf, NULL);
 }
diff --git a/generic/tclStrToD.c b/generic/tclStrToD.c
index c55554c..fd3170a 100644
--- a/generic/tclStrToD.c
+++ b/generic/tclStrToD.c
@@ -5145,7 +5145,7 @@ TclFormatNaN(
     *buffer++ = 'N';
     bitwhack.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
     if (bitwhack.iv != 0) {
-	sprintf(buffer, "(%" TCL_LL_MODIFIER "x)", bitwhack.iv);
+	snprintf(buffer, TCL_DOUBLE_SPACE, "(%" TCL_LL_MODIFIER "x)", bitwhack.iv);
     } else {
 	*buffer = '\0';
     }
diff --git a/generic/tclStringObj.c b/generic/tclStringObj.c
index 720ed44..b42eeb3 100644
--- a/generic/tclStringObj.c
+++ b/generic/tclStringObj.c
@@ -2483,14 +2483,14 @@ Tcl_AppendFormatToObj(
 		*p++ = '+';
 	    }
 	    if (width) {
-		p += sprintf(p, "%d", width);
+		p += snprintf(p, TCL_INTEGER_SPACE, "%d", width);
 		if (width > length) {
 		    length = width;
 		}
 	    }
 	    if (gotPrecision) {
 		*p++ = '.';
-		p += sprintf(p, "%d", precision);
+		p += snprintf(p, TCL_INTEGER_SPACE, "%d", precision);
 		if (precision > INT_MAX - length) {
 		    msg = overflow;
 		    errCode = "OVERFLOW";
@@ -2514,7 +2514,7 @@ Tcl_AppendFormatToObj(
 		goto errorMsg;
 	    }
 	    bytes = TclGetString(segment);
-	    if (!Tcl_AttemptSetObjLength(segment, sprintf(bytes, spec, d))) {
+	    if (!Tcl_AttemptSetObjLength(segment, snprintf(bytes, segment->length, spec, d))) {
 		msg = overflow;
 		errCode = "OVERFLOW";
 		goto errorMsg;
diff --git a/generic/tclTest.c b/generic/tclTest.c
index 2b4b24f..e7af185 100644
--- a/generic/tclTest.c
+++ b/generic/tclTest.c
@@ -1110,7 +1110,7 @@ TestcmdtokenCmd(
     if (strcmp(argv[1], "create") == 0) {
 	token = Tcl_CreateCommand(interp, argv[2], CmdProc1,
 		(ClientData) "original", NULL);
-	sprintf(buf, "%p", (void *)token);
+	snprintf(buf, sizeof(buf), "%p", (void *)token);
 	Tcl_SetResult(interp, buf, TCL_VOLATILE);
     } else if (strcmp(argv[1], "name") == 0) {
 	Tcl_Obj *objPtr;
@@ -1864,6 +1864,19 @@ static int UtfExtWrapper(
     int flags;
     Tcl_Obj **flagObjs;
     int nflags;
+    static const struct {
+	const char *flagKey;
+	int flag;
+    } flagMap[] = {
+	{"start", TCL_ENCODING_START},
+	{"end", TCL_ENCODING_END},
+	{"stoponerror", TCL_ENCODING_STOPONERROR},
+	{"noterminate", TCL_ENCODING_NO_TERMINATE},
+	{"charlimit", TCL_ENCODING_CHAR_LIMIT},
+	{NULL, 0}
+    };
+    int i;
+    Tcl_WideInt wide;
 
     if (objc < 7 || objc > 10) {
         Tcl_WrongNumArgs(interp,
@@ -1882,18 +1895,6 @@ static int UtfExtWrapper(
 	return TCL_ERROR;
     }
 
-    struct {
-	const char *flagKey;
-	int flag;
-    } flagMap[] = {
-	{"start", TCL_ENCODING_START},
-	{"end", TCL_ENCODING_END},
-	{"stoponerror", TCL_ENCODING_STOPONERROR},
-	{"noterminate", TCL_ENCODING_NO_TERMINATE},
-	{"charlimit", TCL_ENCODING_CHAR_LIMIT},
-	{NULL, 0}
-    };
-    int i;
     for (i = 0; i < nflags; ++i) {
 	int flag;
 	if (Tcl_GetIntFromObj(NULL, flagObjs[i], &flag) == TCL_OK) {
@@ -1914,7 +1915,6 @@ static int UtfExtWrapper(
     }
 
     /* Assumes state is integer if not "" */
-    Tcl_WideInt wide;
     if (Tcl_GetWideIntFromObj(interp, objv[5], &wide) == TCL_OK) {
         encState = (Tcl_EncodingState)(size_t)wide;
         encStatePtr = &encState;
@@ -2538,7 +2538,7 @@ ExitProcOdd(
     char buf[16 + TCL_INTEGER_SPACE];
     int len;
 
-    sprintf(buf, "odd %d\n", (int)PTR2INT(clientData));
+    snprintf(buf, sizeof(buf), "odd %d\n", (int)PTR2INT(clientData));
     len = strlen(buf);
     if (len != (int) write(1, buf, len)) {
 	Tcl_Panic("ExitProcOdd: unable to write to stdout");
@@ -2552,7 +2552,7 @@ ExitProcEven(
     char buf[16 + TCL_INTEGER_SPACE];
     int len;
 
-    sprintf(buf, "even %d\n", (int)PTR2INT(clientData));
+    snprintf(buf, sizeof(buf), "even %d\n", (int)PTR2INT(clientData));
     len = strlen(buf);
     if (len != (int) write(1, buf, len)) {
 	Tcl_Panic("ExitProcEven: unable to write to stdout");
@@ -2597,7 +2597,7 @@ TestexprlongCmd(
     if (result != TCL_OK) {
 	return result;
     }
-    sprintf(buf, ": %ld", exprResult);
+    snprintf(buf, sizeof(buf), ": %ld", exprResult);
     Tcl_AppendResult(interp, buf, NULL);
     return TCL_OK;
 }
@@ -2639,7 +2639,7 @@ TestexprlongobjCmd(
     if (result != TCL_OK) {
 	return result;
     }
-    sprintf(buf, ": %ld", exprResult);
+    snprintf(buf, sizeof(buf), ": %ld", exprResult);
     Tcl_AppendResult(interp, buf, NULL);
     return TCL_OK;
 }
@@ -4089,7 +4089,7 @@ TestregexpObjCmd(
 
 	    varName = Tcl_GetString(objv[2]);
 	    TclRegExpRangeUniChar(regExpr, -1, &start, &end);
-	    sprintf(resinfo, "%d %d", start, end-1);
+	    snprintf(resinfo, sizeof(resinfo), "%d %d", start, end-1);
 	    value = Tcl_SetVar(interp, varName, resinfo, 0);
 	    if (value == NULL) {
 		Tcl_AppendResult(interp, "couldn't set variable \"",
@@ -4103,7 +4103,7 @@ TestregexpObjCmd(
 
 	    Tcl_RegExpGetInfo(regExpr, &info);
 	    varName = Tcl_GetString(objv[2]);
-	    sprintf(resinfo, "%ld", info.extendStart);
+	    snprintf(resinfo, sizeof(resinfo), "%ld", info.extendStart);
 	    value = Tcl_SetVar(interp, varName, resinfo, 0);
 	    if (value == NULL) {
 		Tcl_AppendResult(interp, "couldn't set variable \"",
@@ -4998,15 +4998,15 @@ GetTimesObjCmd(
     fprintf(stderr, "   %.3f usec per Tcl_GetInt of \"12345\"\n",
 	    timePer/100000);
 
-    /* sprintf 100000 times */
-    fprintf(stderr, "sprintf of 12345 100000 times\n");
+    /* snprintf 100000 times */
+    fprintf(stderr, "snprintf of 12345 100000 times\n");
     Tcl_GetTime(&start);
     for (i = 0;  i < 100000;  i++) {
-	sprintf(newString, "%d", 12345);
+	snprintf(newString, sizeof(newString), "%d", 12345);
     }
     Tcl_GetTime(&stop);
     timePer = (stop.sec - start.sec)*1000000 + (stop.usec - start.usec);
-    fprintf(stderr, "   %.3f usec per sprintf of 12345\n",
+    fprintf(stderr, "   %.3f usec per snprintf of 12345\n",
 	    timePer/100000);
 
     /* hashtable lookup 100000 times */
@@ -5642,7 +5642,7 @@ TestChannelCmd(
     Tcl_Channel chan;		/* The opaque type. */
     size_t len;			/* Length of subcommand string. */
     int IOQueued;		/* How much IO is queued inside channel? */
-    char buf[TCL_INTEGER_SPACE];/* For sprintf. */
+    char buf[TCL_INTEGER_SPACE];/* For snprintf. */
     int mode;			/* rw mode of the channel */
 
     if (argc < 2) {
@@ -6432,10 +6432,10 @@ TestGetIndexFromObjStructObjCmd(
     }
     if (idx != target) {
 	char buffer[64];
-	sprintf(buffer, "%d", idx);
+	snprintf(buffer, sizeof(buffer), "%d", idx);
 	Tcl_AppendResult(interp, "index value comparison failed: got ",
 		buffer, NULL);
-	sprintf(buffer, "%d", target);
+	snprintf(buffer, sizeof(buffer), "%d", target);
 	Tcl_AppendResult(interp, " when ", buffer, " expected", NULL);
 	return TCL_ERROR;
     }
diff --git a/generic/tclTestObj.c b/generic/tclTestObj.c
index b1a0afa..8d8c0c8 100644
--- a/generic/tclTestObj.c
+++ b/generic/tclTestObj.c
@@ -1535,7 +1535,7 @@ CheckIfVarUnset(
     if (varPtr[varIndex] == NULL) {
 	char buf[32 + TCL_INTEGER_SPACE];
 
-	sprintf(buf, "variable %d is unset (NULL)", varIndex);
+	snprintf(buf, sizeof(buf), "variable %d is unset (NULL)", varIndex);
 	Tcl_ResetResult(interp);
 	Tcl_AppendToObj(Tcl_GetObjResult(interp), buf, -1);
 	return 1;
diff --git a/generic/tclTestProcBodyObj.c b/generic/tclTestProcBodyObj.c
index fba2844..45dea21 100644
--- a/generic/tclTestProcBodyObj.c
+++ b/generic/tclTestProcBodyObj.c
@@ -146,14 +146,14 @@ RegisterCommand(
     char buf[128];
 
     if (cmdTablePtr->exportIt) {
-	sprintf(buf, "namespace eval %s { namespace export %s }",
+	snprintf(buf, sizeof(buf), "namespace eval %s { namespace export %s }",
 		namespace, cmdTablePtr->cmdName);
 	if (Tcl_EvalEx(interp, buf, -1, 0) != TCL_OK) {
 	    return TCL_ERROR;
 	}
     }
 
-    sprintf(buf, "%s::%s", namespace, cmdTablePtr->cmdName);
+    snprintf(buf, sizeof(buf), "%s::%s", namespace, cmdTablePtr->cmdName);
     Tcl_CreateObjCommand(interp, buf, cmdTablePtr->proc, 0, 0);
     return TCL_OK;
 }
diff --git a/generic/tclThreadAlloc.c b/generic/tclThreadAlloc.c
index 5a1e8ca..33dc480 100644
--- a/generic/tclThreadAlloc.c
+++ b/generic/tclThreadAlloc.c
@@ -676,11 +676,11 @@ Tcl_GetMemoryInfo(
 	if (cachePtr == sharedPtr) {
 	    Tcl_DStringAppendElement(dsPtr, "shared");
 	} else {
-	    sprintf(buf, "thread%p", cachePtr->owner);
+	    snprintf(buf, sizeof(buf), "thread%p", cachePtr->owner);
 	    Tcl_DStringAppendElement(dsPtr, buf);
 	}
 	for (n = 0; n < NBUCKETS; ++n) {
-	    sprintf(buf, "%lu %ld %ld %ld %ld %ld %ld",
+	    snprintf(buf, sizeof(buf), "%lu %ld %ld %ld %ld %ld %ld",
 		    (unsigned long) bucketInfo[n].blockSize,
 		    cachePtr->buckets[n].numFree,
 		    cachePtr->buckets[n].numRemoves,
diff --git a/generic/tclThreadTest.c b/generic/tclThreadTest.c
index ff18077..4493822 100644
--- a/generic/tclThreadTest.c
+++ b/generic/tclThreadTest.c
@@ -371,7 +371,7 @@ ThreadObjCmd(
 	} else {
 	    char buf[20];
 
-	    sprintf(buf, "%" TCL_LL_MODIFIER "d", id);
+	    snprintf(buf, sizeof(buf), "%" TCL_LL_MODIFIER "d", id);
 	    Tcl_AppendResult(interp, "cannot join thread ", buf, NULL);
 	}
 	return result;
@@ -654,7 +654,7 @@ ThreadErrorProc(
     char *script;
     char buf[TCL_DOUBLE_SPACE+1];
 
-    sprintf(buf, "%" TCL_LL_MODIFIER "d", (Tcl_WideInt)(size_t)Tcl_GetCurrentThread());
+    snprintf(buf, sizeof(buf), "%" TCL_LL_MODIFIER "d", (Tcl_WideInt)(size_t)Tcl_GetCurrentThread());
 
     errorInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY);
     if (errorProcString == NULL) {
diff --git a/generic/tclUtil.c b/generic/tclUtil.c
index aee2b15..d3e88d4 100644
--- a/generic/tclUtil.c
+++ b/generic/tclUtil.c
@@ -3320,9 +3320,9 @@ Tcl_PrintDouble(
 	 */
 
 	if (*precisionPtr == 0) {
-	    sprintf(dst, "e%+d", exponent);
+	    snprintf(dst, TCL_DOUBLE_SPACE, "e%+d", exponent);
 	} else {
-	    sprintf(dst, "e%+03d", exponent);
+	    snprintf(dst, TCL_DOUBLE_SPACE, "e%+03d", exponent);
 	}
     } else {
 	/*
diff --git a/generic/tclZlib.c b/generic/tclZlib.c
index cbff7b7..c9b4cbc 100644
--- a/generic/tclZlib.c
+++ b/generic/tclZlib.c
@@ -289,7 +289,7 @@ ConvertError(
     case Z_NEED_DICT:
 	codeStr = "NEED_DICT";
 	codeStr2 = codeStrBuf;
-	sprintf(codeStrBuf, "%lu", adler);
+	snprintf(codeStrBuf, sizeof(codeStrBuf), "%lu", adler);
 	break;
 
 	/*
@@ -310,7 +310,7 @@ ConvertError(
     default:
 	codeStr = "UNKNOWN";
 	codeStr2 = codeStrBuf;
-	sprintf(codeStrBuf, "%d", code);
+	snprintf(codeStrBuf, sizeof(codeStrBuf), "%d", code);
 	break;
     }
     Tcl_SetObjResult(interp, Tcl_NewStringObj(zError(code), -1));
@@ -3419,7 +3419,7 @@ ZlibTransformGetOption(
 	    crc = cd->inStream.adler;
 	}
 
-	sprintf(buf, "%lu", crc);
+	snprintf(buf, sizeof(buf), "%lu", crc);
 	if (optionName == NULL) {
 	    Tcl_DStringAppendElement(dsPtr, "-checksum");
 	    Tcl_DStringAppendElement(dsPtr, buf);
diff --git a/unix/dltest/pkgb.c b/unix/dltest/pkgb.c
index 8d8d123..e66c9ec 100644
--- a/unix/dltest/pkgb.c
+++ b/unix/dltest/pkgb.c
@@ -13,6 +13,9 @@
 
 #undef STATIC_BUILD
 #include "tcl.h"
+#if defined(_WIN32) && defined(_MSC_VER)
+#   define snprintf _snprintf
+#endif
 
 /*
  * Prototypes for procedures defined later in this file:
@@ -63,7 +66,7 @@ Pkgb_SubObjCmd(
     if ((Tcl_GetIntFromObj(interp, objv[1], &first) != TCL_OK)
 	    || (Tcl_GetIntFromObj(interp, objv[2], &second) != TCL_OK)) {
 	char buf[TCL_INTEGER_SPACE];
-	sprintf(buf, "%d", Tcl_GetErrorLine(interp));
+	snprintf(buf, sizeof(buf), "%d", Tcl_GetErrorLine(interp));
 	Tcl_AppendResult(interp, " in line: ", buf, NULL);
 	return TCL_ERROR;
     }
diff --git a/unix/tclUnixChan.c b/unix/tclUnixChan.c
index b49dde7..9330207 100644
--- a/unix/tclUnixChan.c
+++ b/unix/tclUnixChan.c
@@ -838,7 +838,7 @@ TtyGetOptionProc(
 
 	valid = 1;
 	TtyGetAttributes(fsPtr->fd, &tty);
-	sprintf(buf, "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop);
+	snprintf(buf, sizeof(buf), "%d,%c,%d,%d", tty.baud, tty.parity, tty.data, tty.stop);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
 
@@ -885,9 +885,9 @@ TtyGetOptionProc(
 	inBuffered = Tcl_InputBuffered(fsPtr->channel);
 	outBuffered = Tcl_OutputBuffered(fsPtr->channel);
 
-	sprintf(buf, "%d", inBuffered+inQueue);
+	snprintf(buf, sizeof(buf), "%d", inBuffered+inQueue);
 	Tcl_DStringAppendElement(dsPtr, buf);
-	sprintf(buf, "%d", outBuffered+outQueue);
+	snprintf(buf, sizeof(buf), "%d", outBuffered+outQueue);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
 
@@ -1439,7 +1439,7 @@ TclpOpenFileChannel(
 
     fcntl(fd, F_SETFD, FD_CLOEXEC);
 
-    sprintf(channelName, "file%d", fd);
+    snprintf(channelName, sizeof(channelName), "file%d", fd);
 
 #ifdef SUPPORTS_TTY
     if (strcmp(native, "/dev/tty") != 0 && isatty(fd)) {
@@ -1531,7 +1531,7 @@ Tcl_MakeFileChannel(
 #ifdef SUPPORTS_TTY
     if (isatty(fd)) {
 	channelTypePtr = &ttyChannelType;
-	sprintf(channelName, "serial%d", fd);
+	snprintf(channelName, sizeof(channelName), "serial%d", fd);
     } else
 #endif /* SUPPORTS_TTY */
     if ((getsockname(fd, (struct sockaddr *)&sockaddr, &sockaddrLen) == 0)
@@ -1540,7 +1540,7 @@ Tcl_MakeFileChannel(
 	return TclpMakeTcpClientChannelMode(INT2PTR(fd), mode);
     } else {
 	channelTypePtr = &fileChannelType;
-	sprintf(channelName, "file%d", fd);
+	snprintf(channelName, sizeof(channelName), "file%d", fd);
     }
 
     fsPtr = ckalloc(sizeof(FileState));
diff --git a/unix/tclUnixInit.c b/unix/tclUnixInit.c
index 47b8df3..2aae158 100644
--- a/unix/tclUnixInit.c
+++ b/unix/tclUnixInit.c
@@ -500,7 +500,7 @@ TclpInitLibraryPath(
 	 * installed.
 	 */
 
-	sprintf(installLib, "lib/tcl%s", TCL_VERSION);
+	snprintf(installLib, sizeof(installLib), "lib/tcl%s", TCL_VERSION);
 
 	/*
 	 * If TCL_LIBRARY is set, search there.
@@ -899,7 +899,7 @@ TclpSetVariables(
 	osInfo.dwMajorVersion = 11;
     }
     Tcl_SetVar2(interp, "tcl_platform", "os", "Windows NT", TCL_GLOBAL_ONLY);
-    sprintf(buffer, "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
+    snprintf(buffer, sizeof(buffer), "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
     Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
     if (sysInfo.wProcessorArchitecture < NUMPROCESSORS) {
 	Tcl_SetVar2(interp, "tcl_platform", "machine",
diff --git a/unix/tclUnixPipe.c b/unix/tclUnixPipe.c
index d5cb765..9d27632 100644
--- a/unix/tclUnixPipe.c
+++ b/unix/tclUnixPipe.c
@@ -475,7 +475,7 @@ TclpCreateProcess(
 		|| (!joinThisError && !SetupStdFile(errorFile, TCL_STDERR))
 		|| (joinThisError &&
 			((dup2(1,2) == -1) || (fcntl(2, F_SETFD, 0) != 0)))) {
-	    sprintf(errSpace,
+	    snprintf(errSpace, sizeof(errSpace),
 		    "%dforked process couldn't set up input/output", errno);
 	    len = strlen(errSpace);
 	    if (len != (size_t) write(fd, errSpace, len)) {
@@ -490,7 +490,7 @@ TclpCreateProcess(
 
 	RestoreSignals();
 	execvp(newArgv[0], newArgv);			/* INTL: Native. */
-	sprintf(errSpace, "%dcouldn't execute \"%.150s\"", errno, argv[0]);
+	snprintf(errSpace, sizeof(errSpace), "%dcouldn't execute \"%.150s\"", errno, argv[0]);
 	len = strlen(errSpace);
 	if (len != (size_t) write(fd, errSpace, len)) {
 	    Tcl_Panic("TclpCreateProcess: unable to write to errPipeOut");
@@ -782,7 +782,7 @@ TclpCreateCommandChannel(
      * natural to use "pipe%d".
      */
 
-    sprintf(channelName, "file%d", channelId);
+    snprintf(channelName, sizeof(channelName), "file%d", channelId);
     statePtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
 	    statePtr, mode);
     return statePtr->channel;
diff --git a/unix/tclUnixSock.c b/unix/tclUnixSock.c
index ffb70e1..3c56a5e 100644
--- a/unix/tclUnixSock.c
+++ b/unix/tclUnixSock.c
@@ -1428,7 +1428,7 @@ Tcl_OpenTcpClient(
         return NULL;
     }
 
-    sprintf(channelName, SOCK_TEMPLATE, (long)statePtr);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)statePtr);
 
     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
             statePtr, TCL_READABLE | TCL_WRITABLE);
@@ -1495,7 +1495,7 @@ TclpMakeTcpClientChannelMode(
     statePtr->fds.fd = PTR2INT(sock);
     statePtr->flags = 0;
 
-    sprintf(channelName, SOCK_TEMPLATE, (long)statePtr);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)statePtr);
 
     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 	    statePtr, mode);
@@ -1654,7 +1654,7 @@ Tcl_OpenTcpServer(
             memset(statePtr, 0, sizeof(TcpState));
             statePtr->acceptProc = acceptProc;
             statePtr->acceptProcData = acceptProcData;
-            sprintf(channelName, SOCK_TEMPLATE, (long) statePtr);
+            snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long) statePtr);
             newfds = &statePtr->fds;
         } else {
             newfds = (TcpFdList *)ckalloc(sizeof(TcpFdList));
@@ -1747,7 +1747,7 @@ TcpAccept(
     newSockState->flags = 0;
     newSockState->fds.fd = newsock;
 
-    sprintf(channelName, SOCK_TEMPLATE, (long)newSockState);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, (long)newSockState);
     newSockState->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 	    newSockState, TCL_READABLE | TCL_WRITABLE);
 
diff --git a/unix/tclUnixTest.c b/unix/tclUnixTest.c
index c5ac52a..9b89b2f 100644
--- a/unix/tclUnixTest.c
+++ b/unix/tclUnixTest.c
@@ -202,7 +202,7 @@ TestfilehandlerCmd(
 		    argv[0], " counts index\"", NULL);
 	    return TCL_ERROR;
 	}
-	sprintf(buf, "%d %d", pipePtr->readCount, pipePtr->writeCount);
+	snprintf(buf, sizeof(buf), "%d %d", pipePtr->readCount, pipePtr->writeCount);
 	Tcl_AppendResult(interp, buf, NULL);
     } else if (strcmp(argv[1], "create") == 0) {
 	if (argc != 5) {
diff --git a/unix/tclUnixThrd.c b/unix/tclUnixThrd.c
index afb795d..e4a3c68 100644
--- a/unix/tclUnixThrd.c
+++ b/unix/tclUnixThrd.c
@@ -667,7 +667,7 @@ TclpInetNtoa(
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
     unsigned char *b = (unsigned char*) &addr.s_addr;
 
-    sprintf(tsdPtr->nabuf, "%u.%u.%u.%u", b[0], b[1], b[2], b[3]);
+    snprintf(tsdPtr->nabuf, sizeof(tsdPtr->nabuf), "%u.%u.%u.%u", b[0], b[1], b[2], b[3]);
     return tsdPtr->nabuf;
 #else
     return inet_ntoa(addr);
diff --git a/win/tclWinChan.c b/win/tclWinChan.c
index 3a3eba4..72a71ab 100644
--- a/win/tclWinChan.c
+++ b/win/tclWinChan.c
@@ -98,6 +98,9 @@ static int		FileTruncateProc(ClientData instanceData,
 			    Tcl_WideInt length);
 static DWORD		FileGetType(HANDLE handle);
 static int		NativeIsComPort(const WCHAR *nativeName);
+static Tcl_Channel TclWinOpenFileChannel(HANDLE handle, char *channelName,
+			    int permissions, int appendMode);
+
 /*
  * This structure describes the channel type structure for file based IO.
  */
@@ -1382,7 +1385,7 @@ TclWinOpenFileChannel(
     infoPtr->flags = appendMode;
     infoPtr->handle = handle;
     infoPtr->dirty = 0;
-    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
+    snprintf(channelName, 16 + TCL_INTEGER_SPACE, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&fileChannelType, channelName,
 	    infoPtr, permissions);
diff --git a/win/tclWinConsole.c b/win/tclWinConsole.c
index 41a05ad..b9b81f8 100644
--- a/win/tclWinConsole.c
+++ b/win/tclWinConsole.c
@@ -460,7 +460,7 @@ ConsoleCheckProc(
 	}
 
 	if (needEvent) {
-	    ConsoleEvent *evPtr = ckalloc(sizeof(ConsoleEvent));
+	    ConsoleEvent *evPtr = (ConsoleEvent *)ckalloc(sizeof(ConsoleEvent));
 
 	    infoPtr->flags |= CONSOLE_PENDING;
 	    evPtr->header.proc = ConsoleEventProc;
@@ -492,7 +492,7 @@ ConsoleBlockModeProc(
     int mode)			/* TCL_MODE_BLOCKING or
 				 * TCL_MODE_NONBLOCKING. */
 {
-    ConsoleInfo *infoPtr = instanceData;
+    ConsoleInfo *infoPtr = (ConsoleInfo *)instanceData;
 
     /*
      * Consoles on Windows can not be switched between blocking and
@@ -531,7 +531,7 @@ ConsoleCloseProc(
     ClientData instanceData,	/* Pointer to ConsoleInfo structure. */
     Tcl_Interp *interp)		/* For error reporting. */
 {
-    ConsoleInfo *consolePtr = instanceData;
+    ConsoleInfo *consolePtr = (ConsoleInfo *)instanceData;
     int errorCode = 0;
     ConsoleInfo *infoPtr, **nextPtrPtr;
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
@@ -650,7 +650,7 @@ ConsoleInputProc(
 				 * buffer? */
     int *errorCode)		/* Where to store error code. */
 {
-    ConsoleInfo *infoPtr = instanceData;
+    ConsoleInfo *infoPtr = (ConsoleInfo *)instanceData;
     DWORD count, bytesRead = 0;
     int result;
 
@@ -1121,7 +1121,7 @@ ConsoleReaderThread(
 {
     TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *)arg;
     ConsoleInfo *infoPtr = NULL; /* access info only after success init/wait */
-    HANDLE *handle = NULL;
+    HANDLE handle = NULL;
     ConsoleThreadInfo *threadInfo = NULL;
     int done = 0;
 
@@ -1218,7 +1218,7 @@ ConsoleWriterThread(
 {
     TclPipeThreadInfo *pipeTI = (TclPipeThreadInfo *)arg;
     ConsoleInfo *infoPtr = NULL; /* access info only after success init/wait */
-    HANDLE *handle = NULL;
+    HANDLE handle = NULL;
     ConsoleThreadInfo *threadInfo = NULL;
     DWORD count, toWrite;
     char *buf;
@@ -1311,7 +1311,6 @@ TclWinOpenConsoleChannel(
     char *channelName,
     int permissions)
 {
-    char encoding[4 + TCL_INTEGER_SPACE];
     ConsoleInfo *infoPtr;
     DWORD modes;
 
@@ -1328,8 +1327,6 @@ TclWinOpenConsoleChannel(
     infoPtr->handle = handle;
     infoPtr->channel = (Tcl_Channel) NULL;
 
-    wsprintfA(encoding, "cp%d", GetConsoleCP());
-
     infoPtr->threadId = Tcl_GetCurrentThread();
 
     /*
@@ -1338,7 +1335,7 @@ TclWinOpenConsoleChannel(
      * for instance).
      */
 
-    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
+    snprintf(channelName, TCL_INTEGER_SPACE + 4, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName,
 	    infoPtr, permissions);
diff --git a/win/tclWinFCmd.c b/win/tclWinFCmd.c
index 86fea7e..595f6b7 100644
--- a/win/tclWinFCmd.c
+++ b/win/tclWinFCmd.c
@@ -145,8 +145,8 @@ TclpObjRenameFile(
     Tcl_Obj *srcPathPtr,
     Tcl_Obj *destPathPtr)
 {
-    return DoRenameFile(Tcl_FSGetNativePath(srcPathPtr),
-	    Tcl_FSGetNativePath(destPathPtr));
+    return DoRenameFile((WCHAR *)Tcl_FSGetNativePath(srcPathPtr),
+	    (WCHAR *)Tcl_FSGetNativePath(destPathPtr));
 }
 
 static int
@@ -534,8 +534,8 @@ TclpObjCopyFile(
     Tcl_Obj *srcPathPtr,
     Tcl_Obj *destPathPtr)
 {
-    return DoCopyFile(Tcl_FSGetNativePath(srcPathPtr),
-	    Tcl_FSGetNativePath(destPathPtr));
+    return DoCopyFile((WCHAR *)Tcl_FSGetNativePath(srcPathPtr),
+	    (WCHAR *)Tcl_FSGetNativePath(destPathPtr));
 }
 
 static int
@@ -749,7 +749,7 @@ TclpDeleteFile(
     const void *nativePath)	/* Pathname of file to be removed (native). */
 {
     DWORD attr;
-    const WCHAR *path = nativePath;
+    const WCHAR *path = (const WCHAR *)nativePath;
 
     /*
      * The DeleteFile API acts differently under Win95/98 and NT WRT NULL and
@@ -854,7 +854,7 @@ int
 TclpObjCreateDirectory(
     Tcl_Obj *pathPtr)
 {
-    return DoCreateDirectory(Tcl_FSGetNativePath(pathPtr));
+    return DoCreateDirectory((WCHAR *)Tcl_FSGetNativePath(pathPtr));
 }
 
 static int
@@ -988,7 +988,7 @@ TclpObjRemoveDirectory(
 	ret = DoRemoveDirectory(&native, recursive, &ds);
 	Tcl_DStringFree(&native);
     } else {
-	ret = DoRemoveJustDirectory(Tcl_FSGetNativePath(pathPtr), 0, &ds);
+	ret = DoRemoveJustDirectory((WCHAR *)Tcl_FSGetNativePath(pathPtr), 0, &ds);
     }
 
     if (ret != TCL_OK) {
@@ -1506,7 +1506,7 @@ GetWinFileAttributes(
     const WCHAR *nativeName;
     int attr;
 
-    nativeName = Tcl_FSGetNativePath(fileName);
+    nativeName = (WCHAR *)Tcl_FSGetNativePath(fileName);
     result = GetFileAttributesW(nativeName);
 
     if (result == 0xFFFFFFFF) {
@@ -1833,7 +1833,7 @@ SetWinFileAttributes(
     int yesNo, result;
     const WCHAR *nativeName;
 
-    nativeName = Tcl_FSGetNativePath(fileName);
+    nativeName = (WCHAR *)Tcl_FSGetNativePath(fileName);
     fileAttributes = old = GetFileAttributesW(nativeName);
 
     if (fileAttributes == 0xFFFFFFFF) {
diff --git a/win/tclWinFile.c b/win/tclWinFile.c
index a6f27c9..efd2104 100644
--- a/win/tclWinFile.c
+++ b/win/tclWinFile.c
@@ -946,7 +946,7 @@ TclpMatchInDirectory(
 	    WIN32_FILE_ATTRIBUTE_DATA data;
 	    const char *str = Tcl_GetStringFromObj(norm,&len);
 
-	    native = Tcl_FSGetNativePath(pathPtr);
+	    native = (WCHAR *)Tcl_FSGetNativePath(pathPtr);
 
 	    if (GetFileAttributesExW(native,
 		    GetFileExInfoStandard, &data) != TRUE) {
diff --git a/win/tclWinInit.c b/win/tclWinInit.c
index 582c700..3aadf7a 100644
--- a/win/tclWinInit.c
+++ b/win/tclWinInit.c
@@ -4,7 +4,7 @@
  *	Contains the Windows-specific interpreter initialization functions.
  *
  * Copyright (c) 1994-1997 Sun Microsystems, Inc.
- * Copyright (c) 1998-1999 by Scriptics Corporation.
+ * Copyright (c) 1998-1999 Scriptics Corporation.
  * All rights reserved.
  *
  * See the file "license.terms" for information on usage and redistribution of
@@ -64,12 +64,6 @@ static ProcessGlobalValue sourceLibraryDir =
 	{0, 0, NULL, NULL, InitializeSourceLibraryDir, NULL, NULL};
 
 static void		AppendEnvironment(Tcl_Obj *listPtr, const char *lib);
-
-#if TCL_UTF_MAX < 4
-static void		ToUtf(const WCHAR *wSrc, char *dst);
-#else
-#define ToUtf(wSrc, dst) WideCharToMultiByte(CP_UTF8, 0, wSrc, -1, dst, MAX_PATH * TCL_UTF_MAX, NULL, NULL)
-#endif
 
 /*
  *---------------------------------------------------------------------------
@@ -163,7 +157,7 @@ TclpInitLibraryPath(
      * installed DLL.
      */
 
-    sprintf(installLib, "lib/tcl%s", TCL_VERSION);
+    snprintf(installLib, sizeof(installLib), "lib/tcl%s", TCL_VERSION);
 
     /*
      * Look for the library relative to the TCL_LIBRARY env variable. If the
@@ -250,12 +244,8 @@ AppendEnvironment(
      * this is a unicode string.
      */
 
-    if (GetEnvironmentVariableW(L"TCL_LIBRARY", wBuf, MAX_PATH) == 0) {
-	buf[0] = '\0';
-	GetEnvironmentVariableA("TCL_LIBRARY", buf, MAX_PATH);
-    } else {
-	ToUtf(wBuf, buf);
-    }
+    GetEnvironmentVariableW(L"TCL_LIBRARY", wBuf, MAX_PATH);
+    WideCharToMultiByte(CP_UTF8, 0, wBuf, -1, buf, MAX_PATH * 3, NULL, NULL);
 
     if (buf[0] != '\0') {
 	objPtr = Tcl_NewStringObj(buf, -1);
@@ -317,11 +307,8 @@ InitializeDefaultLibraryDir(
     char name[(MAX_PATH + LIBRARY_SIZE) * 3];
     char *end, *p;
 
-    if (GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR)) == 0) {
-	GetModuleFileNameA(hModule, name, sizeof(name));
-    } else {
-	ToUtf(wName, name);
-    }
+    GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR));
+    WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, sizeof(name), NULL, NULL);
 
     end = strrchr(name, '\\');
     *end = '\0';
@@ -332,7 +319,7 @@ InitializeDefaultLibraryDir(
     *end = '\\';
 
     TclWinNoBackslash(name);
-    sprintf(end + 1, "lib/tcl%s", TCL_VERSION);
+    snprintf(end + 1, LIBRARY_SIZE, "lib/tcl%s", TCL_VERSION);
     *lengthPtr = strlen(name);
     *valuePtr = (char *)ckalloc(*lengthPtr + 1);
     *encodingPtr = NULL;
@@ -368,11 +355,8 @@ InitializeSourceLibraryDir(
     char name[(MAX_PATH + LIBRARY_SIZE) * 3];
     char *end, *p;
 
-    if (GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR)) == 0) {
-	GetModuleFileNameA(hModule, name, sizeof(name));
-    } else {
-	ToUtf(wName, name);
-    }
+    GetModuleFileNameW(hModule, wName, sizeof(wName)/sizeof(WCHAR));
+    WideCharToMultiByte(CP_UTF8, 0, wName, -1, name, sizeof(name), NULL, NULL);
 
     end = strrchr(name, '\\');
     *end = '\0';
@@ -383,7 +367,7 @@ InitializeSourceLibraryDir(
     *end = '\\';
 
     TclWinNoBackslash(name);
-    sprintf(end + 1, "../library");
+    snprintf(end + 1, LIBRARY_SIZE, "../library");
     *lengthPtr = strlen(name);
     *valuePtr = (char *)ckalloc(*lengthPtr + 1);
     *encodingPtr = NULL;
@@ -393,36 +377,6 @@ InitializeSourceLibraryDir(
 /*
  *---------------------------------------------------------------------------
  *
- * ToUtf --
- *
- *	Convert a wchar string to a UTF string.
- *
- * Results:
- *	None.
- *
- * Side effects:
- *	None.
- *
- *---------------------------------------------------------------------------
- */
-
-#if TCL_UTF_MAX < 4
-static void
-ToUtf(
-    const WCHAR *wSrc,
-    char *dst)
-{
-    while (*wSrc != '\0') {
-	dst += Tcl_UniCharToUtf(*wSrc, dst);
-	wSrc++;
-    }
-    *dst = '\0';
-}
-#endif
-
-/*
- *---------------------------------------------------------------------------
- *
  * TclpSetInitialEncodings --
  *
  *	Based on the locale, determine the encoding of the operating system
@@ -471,7 +425,7 @@ Tcl_GetEncodingNameFromEnvironment(
 	Tcl_DStringAppend(bufPtr, "utf-8", 5);
     } else {
 	Tcl_DStringSetLength(bufPtr, 2+TCL_INTEGER_SPACE);
-	wsprintfA(Tcl_DStringValue(bufPtr), "cp%d", GetACP());
+	snprintf(Tcl_DStringValue(bufPtr), 2+TCL_INTEGER_SPACE, "cp%d", GetACP());
 	Tcl_DStringSetLength(bufPtr, strlen(Tcl_DStringValue(bufPtr)));
     }
     return Tcl_DStringValue(bufPtr);
@@ -555,7 +509,7 @@ TclpSetVariables(
     if (osInfo.dwMajorVersion == 10 && osInfo.dwBuildNumber >= 22000) {
 	osInfo.dwMajorVersion = 11;
     }
-    wsprintfA(buffer, "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
+    snprintf(buffer, sizeof(buffer), "%ld.%ld", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
     Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
     if (sys.oemId.wProcessorArchitecture < NUMPROCESSORS) {
 	Tcl_SetVar2(interp, "tcl_platform", "machine",
diff --git a/win/tclWinInt.h b/win/tclWinInt.h
index 7aac7d0..b7974b8 100644
--- a/win/tclWinInt.h
+++ b/win/tclWinInt.h
@@ -79,8 +79,6 @@ MODULE_SCOPE void	TclWinInit(HINSTANCE hInst);
 MODULE_SCOPE TclFile	TclWinMakeFile(HANDLE handle);
 MODULE_SCOPE Tcl_Channel TclWinOpenConsoleChannel(HANDLE handle,
 			    char *channelName, int permissions);
-MODULE_SCOPE Tcl_Channel TclWinOpenFileChannel(HANDLE handle, char *channelName,
-			    int permissions, int appendMode);
 MODULE_SCOPE Tcl_Channel TclWinOpenSerialChannel(HANDLE handle,
 			    char *channelName, int permissions);
 MODULE_SCOPE HANDLE	TclWinSerialOpen(HANDLE handle, const WCHAR *name,
diff --git a/win/tclWinPipe.c b/win/tclWinPipe.c
index 00bc9fe..6c1331f 100644
--- a/win/tclWinPipe.c
+++ b/win/tclWinPipe.c
@@ -402,7 +402,7 @@ PipeCheckProc(
 
 	if (needEvent) {
 	    infoPtr->flags |= PIPE_PENDING;
-	    evPtr = ckalloc(sizeof(PipeEvent));
+	    evPtr = (PipeEvent *)ckalloc(sizeof(PipeEvent));
 	    evPtr->header.proc = PipeEventProc;
 	    evPtr->infoPtr = infoPtr;
 	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
@@ -433,7 +433,7 @@ TclWinMakeFile(
 {
     WinFile *filePtr;
 
-    filePtr = ckalloc(sizeof(WinFile));
+    filePtr = (WinFile *)ckalloc(sizeof(WinFile));
     filePtr->type = WIN_FILE;
     filePtr->handle = handle;
 
@@ -1775,7 +1775,7 @@ TclpCreateCommandChannel(
     Tcl_Pid *pidPtr)		/* An array of process identifiers. */
 {
     char channelName[16 + TCL_INTEGER_SPACE];
-    PipeInfo *infoPtr = ckalloc(sizeof(PipeInfo));
+    PipeInfo *infoPtr = (PipeInfo *)ckalloc(sizeof(PipeInfo));
 
     PipeInit();
 
@@ -1834,7 +1834,7 @@ TclpCreateCommandChannel(
      * unique, in case channels share handles (stdin/stdout).
      */
 
-    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
+    snprintf(channelName, sizeof(channelName), "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
     infoPtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
 	    infoPtr, infoPtr->validMask);
 
@@ -1929,7 +1929,7 @@ TclGetAndDetachPids(
 	return;
     }
 
-    pipePtr = Tcl_GetChannelInstanceData(chan);
+    pipePtr = (PipeInfo *)Tcl_GetChannelInstanceData(chan);
     TclNewObj(pidsObj);
     for (i = 0; i < pipePtr->numPids; i++) {
 	Tcl_ListObjAppendElement(NULL, pidsObj,
@@ -2315,7 +2315,7 @@ PipeOutputProc(
 		ckfree(infoPtr->writeBuf);
 	    }
 	    infoPtr->writeBufLen = toWrite;
-	    infoPtr->writeBuf = ckalloc(toWrite);
+	    infoPtr->writeBuf = (char *)ckalloc(toWrite);
 	}
 	memcpy(infoPtr->writeBuf, buf, toWrite);
 	infoPtr->toWrite = toWrite;
@@ -2723,7 +2723,7 @@ TclWinAddProcess(
     void *hProcess,		/* Handle to process */
     unsigned long id)		/* Global process identifier */
 {
-    ProcInfo *procPtr = ckalloc(sizeof(ProcInfo));
+    ProcInfo *procPtr = (ProcInfo *)ckalloc(sizeof(ProcInfo));
 
     PipeInit();
 
@@ -2823,7 +2823,7 @@ WaitForRead(
 				 * or not. */
 {
     DWORD timeout, count;
-    HANDLE *handle = ((WinFile *) infoPtr->readFile)->handle;
+    HANDLE handle = ((WinFile *) infoPtr->readFile)->handle;
 
     while (1) {
 	/*
@@ -3243,7 +3243,7 @@ TclpOpenTemporaryFile(
     do {
 	char number[TCL_INTEGER_SPACE + 4];
 
-	sprintf(number, "%d.TMP", counter);
+	snprintf(number, sizeof(number), "%d.TMP", counter);
 	counter = (unsigned short) (counter + 1);
 	Tcl_WinUtfToTChar(number, strlen(number), &buf);
 	Tcl_DStringSetLength(&buf, Tcl_DStringLength(&buf) + 1);
@@ -3295,9 +3295,9 @@ TclPipeThreadCreateTI(
 {
     TclPipeThreadInfo *pipeTI;
 #ifndef _PTI_USE_CKALLOC
-    pipeTI = malloc(sizeof(TclPipeThreadInfo));
+    pipeTI = (TclPipeThreadInfo *)malloc(sizeof(TclPipeThreadInfo));
 #else
-    pipeTI = ckalloc(sizeof(TclPipeThreadInfo));
+    pipeTI = (TclPipeThreadInfo *)ckalloc(sizeof(TclPipeThreadInfo));
 #endif /* !_PTI_USE_CKALLOC */
     pipeTI->evControl = CreateEventW(NULL, FALSE, FALSE, NULL);
     pipeTI->state = PTI_STATE_IDLE;
diff --git a/win/tclWinReg.c b/win/tclWinReg.c
index cd4ab33..87b33e1 100644
--- a/win/tclWinReg.c
+++ b/win/tclWinReg.c
@@ -1498,7 +1498,7 @@ AppendSystemError(
 	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (WCHAR *) tMsgPtrPtr,
 	    0, NULL);
     if (length == 0) {
-	sprintf(msgBuf, "unknown error: %ld", error);
+	snprintf(msgBuf, sizeof(msgBuf), "unknown error: %ld", error);
 	msg = msgBuf;
     } else {
 	char *msgPtr;
@@ -1524,7 +1524,7 @@ AppendSystemError(
 	msg = msgPtr;
     }
 
-    sprintf(id, "%ld", error);
+    snprintf(id, sizeof(id), "%ld", error);
     Tcl_SetErrorCode(interp, "WINDOWS", id, msg, NULL);
     Tcl_AppendToObj(resultPtr, msg, length);
     Tcl_SetObjResult(interp, resultPtr);
diff --git a/win/tclWinSerial.c b/win/tclWinSerial.c
index d7fa9f5..53d2daf 100644
--- a/win/tclWinSerial.c
+++ b/win/tclWinSerial.c
@@ -524,7 +524,7 @@ SerialCheckProc(
 
 	if (needEvent) {
 	    infoPtr->flags |= SERIAL_PENDING;
-	    evPtr = ckalloc(sizeof(SerialEvent));
+	    evPtr = (SerialEvent *)ckalloc(sizeof(SerialEvent));
 	    evPtr->header.proc = SerialEventProc;
 	    evPtr->infoPtr = infoPtr;
 	    Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
@@ -1036,7 +1036,7 @@ SerialOutputProc(
 		ckfree(infoPtr->writeBuf);
 	    }
 	    infoPtr->writeBufLen = toWrite;
-	    infoPtr->writeBuf = ckalloc(toWrite);
+	    infoPtr->writeBuf = (char *)ckalloc(toWrite);
 	}
 	memcpy(infoPtr->writeBuf, buf, toWrite);
 	infoPtr->toWrite = toWrite;
@@ -1435,7 +1435,7 @@ TclWinOpenSerialChannel(
 
     SerialInit();
 
-    infoPtr = ckalloc(sizeof(SerialInfo));
+    infoPtr = (SerialInfo *)ckalloc(sizeof(SerialInfo));
     memset(infoPtr, 0, sizeof(SerialInfo));
 
     infoPtr->validMask = permissions;
@@ -1456,7 +1456,7 @@ TclWinOpenSerialChannel(
      * are shared between multiple channels (stdin/stdout).
      */
 
-    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
+    snprintf(channelName, 16 + TCL_INTEGER_SPACE, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&serialChannelType, channelName,
 	    infoPtr, permissions);
@@ -1544,7 +1544,7 @@ SerialErrorStr(
     if (error & ~((DWORD) (SERIAL_READ_ERRORS | SERIAL_WRITE_ERRORS))) {
 	char buf[TCL_INTEGER_SPACE + 1];
 
-	wsprintfA(buf, "%d", error);
+	snprintf(buf, sizeof(buf), "%ld", error);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
 }
@@ -2041,7 +2041,7 @@ SerialGetOptionProc(
 	stop = (dcb.StopBits == ONESTOPBIT) ? "1" :
 		(dcb.StopBits == ONE5STOPBITS) ? "1.5" : "2";
 
-	wsprintfA(buf, "%d,%c,%d,%s", dcb.BaudRate, parity,
+	snprintf(buf, sizeof(buf), "%ld,%c,%d,%s", dcb.BaudRate, parity,
 		dcb.ByteSize, stop);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
@@ -2057,7 +2057,7 @@ SerialGetOptionProc(
 	char buf[TCL_INTEGER_SPACE + 1];
 
 	valid = 1;
-	wsprintfA(buf, "%d", infoPtr->blockTime);
+	snprintf(buf, sizeof(buf), "%d", infoPtr->blockTime);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
 
@@ -2073,9 +2073,9 @@ SerialGetOptionProc(
 	char buf[TCL_INTEGER_SPACE + 1];
 	valid = 1;
 
-	wsprintfA(buf, "%d", infoPtr->sysBufRead);
+	snprintf(buf, sizeof(buf), "%ld", infoPtr->sysBufRead);
 	Tcl_DStringAppendElement(dsPtr, buf);
-	wsprintfA(buf, "%d", infoPtr->sysBufWrite);
+	snprintf(buf, sizeof(buf), "%ld", infoPtr->sysBufWrite);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
     if (len == 0) {
@@ -2102,9 +2102,10 @@ SerialGetOptionProc(
 	    }
 	    return TCL_ERROR;
 	}
-	sprintf(buf, "%c", dcb.XonChar);
+	buf[1] = '\0';
+	buf[0] = dcb.XonChar;
 	Tcl_DStringAppendElement(dsPtr, buf);
-	sprintf(buf, "%c", dcb.XoffChar);
+	buf[0] = dcb.XoffChar;
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
     if (len == 0) {
@@ -2156,9 +2157,9 @@ SerialGetOptionProc(
 	count = (int) cStat.cbOutQue + infoPtr->writeQueue;
 	LeaveCriticalSection(&infoPtr->csWrite);
 
-	wsprintfA(buf, "%d", inBuffered + cStat.cbInQue);
+	snprintf(buf, sizeof(buf), "%ld", inBuffered + cStat.cbInQue);
 	Tcl_DStringAppendElement(dsPtr, buf);
-	wsprintfA(buf, "%d", outBuffered + count);
+	snprintf(buf, sizeof(buf), "%d", outBuffered + count);
 	Tcl_DStringAppendElement(dsPtr, buf);
     }
 
diff --git a/win/tclWinSock.c b/win/tclWinSock.c
index 09b5d52..1c13479 100644
--- a/win/tclWinSock.c
+++ b/win/tclWinSock.c
@@ -2072,7 +2072,7 @@ Tcl_OpenTcpClient(
 	return NULL;
     }
 
-    sprintf(channelName, SOCK_TEMPLATE, statePtr);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
 
     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 	    statePtr, (TCL_READABLE | TCL_WRITABLE));
@@ -2133,7 +2133,7 @@ Tcl_MakeTcpClientChannel(
     statePtr->selectEvents = FD_READ | FD_CLOSE | FD_WRITE;
     SendSelectMessage(tsdPtr, SELECT, statePtr);
 
-    sprintf(channelName, SOCK_TEMPLATE, statePtr);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
     statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 	    statePtr, (TCL_READABLE | TCL_WRITABLE));
     Tcl_SetChannelOption(NULL, statePtr->channel, "-translation", "auto crlf");
@@ -2296,7 +2296,7 @@ Tcl_OpenTcpServer(
 
 	statePtr->acceptProc = acceptProc;
 	statePtr->acceptProcData = acceptProcData;
-	sprintf(channelName, SOCK_TEMPLATE, statePtr);
+	snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, statePtr);
 	statePtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 		statePtr, 0);
 	/*
@@ -2381,7 +2381,7 @@ TcpAccept(
     newInfoPtr->selectEvents = (FD_READ | FD_WRITE | FD_CLOSE);
     SendSelectMessage(tsdPtr, SELECT, newInfoPtr);
 
-    sprintf(channelName, SOCK_TEMPLATE, newInfoPtr);
+    snprintf(channelName, sizeof(channelName), SOCK_TEMPLATE, newInfoPtr);
     newInfoPtr->channel = Tcl_CreateChannel(&tcpChannelType, channelName,
 	    newInfoPtr, (TCL_READABLE | TCL_WRITABLE));
     if (Tcl_SetChannelOption(NULL, newInfoPtr->channel, "-translation",
diff --git a/win/tclWinThrd.c b/win/tclWinThrd.c
index 44b5f6c..65c4b3c 100644
--- a/win/tclWinThrd.c
+++ b/win/tclWinThrd.c
@@ -574,7 +574,7 @@ Tcl_MutexLock(
 	 */
 
 	if (*mutexPtr == NULL) {
-	    csPtr = ckalloc(sizeof(CRITICAL_SECTION));
+	    csPtr = (CRITICAL_SECTION *)ckalloc(sizeof(CRITICAL_SECTION));
 	    InitializeCriticalSection(csPtr);
 	    *mutexPtr = (Tcl_Mutex)csPtr;
 	    TclRememberMutex(mutexPtr);
@@ -717,7 +717,7 @@ Tcl_ConditionWait(
 	 */
 
 	if (*condPtr == NULL) {
-	    winCondPtr = ckalloc(sizeof(WinCondition));
+	    winCondPtr = (WinCondition *)ckalloc(sizeof(WinCondition));
 	    InitializeCriticalSection(&winCondPtr->condLock);
 	    winCondPtr->firstPtr = NULL;
 	    winCondPtr->lastPtr = NULL;
@@ -946,7 +946,7 @@ TclpNewAllocMutex(void)
 {
     struct allocMutex *lockPtr;
 
-    lockPtr = malloc(sizeof(struct allocMutex));
+    lockPtr = (struct allocMutex *)malloc(sizeof(struct allocMutex));
     if (lockPtr == NULL) {
 	Tcl_Panic("could not allocate lock");
     }
@@ -1045,7 +1045,7 @@ TclpThreadCreateKey(void)
 {
     DWORD *key;
 
-    key = TclpSysAlloc(sizeof *key, 0);
+    key = (DWORD *)TclpSysAlloc(sizeof *key, 0);
     if (key == NULL) {
 	Tcl_Panic("unable to allocate thread key!");
     }
@@ -1063,7 +1063,7 @@ void
 TclpThreadDeleteKey(
     void *keyPtr)
 {
-    DWORD *key = keyPtr;
+    DWORD *key = (DWORD *)keyPtr;
 
     if (!TlsFree(*key)) {
 	Tcl_Panic("unable to delete key");
@@ -1077,7 +1077,7 @@ TclpThreadSetGlobalTSD(
     void *tsdKeyPtr,
     void *ptr)
 {
-    DWORD *key = tsdKeyPtr;
+    DWORD *key = (DWORD *)tsdKeyPtr;
 
     if (!TlsSetValue(*key, ptr)) {
 	Tcl_Panic("unable to set global TSD value");
@@ -1088,7 +1088,7 @@ void *
 TclpThreadGetGlobalTSD(
     void *tsdKeyPtr)
 {
-    DWORD *key = tsdKeyPtr;
+    DWORD *key = (DWORD *)tsdKeyPtr;
 
     return TlsGetValue(*key);
 }
-- 
cgit v0.12