diff --git a/runtime/compiler/compile/J9Compilation.cpp b/runtime/compiler/compile/J9Compilation.cpp index 70cdd1dd695..9853d7a3a67 100644 --- a/runtime/compiler/compile/J9Compilation.cpp +++ b/runtime/compiler/compile/J9Compilation.cpp @@ -325,7 +325,7 @@ J9::Compilation::allocateCompYieldStatsMatrix() for (int32_t j=0; j < (int32_t)LAST_CONTEXT; j++) { char buffer[128]; - sprintf(buffer, "%d-%d", i,j); + snprintf(buffer, sizeof(buffer), "%d-%d", i,j); _compYieldStatsMatrix[i][j].setName(buffer); } } diff --git a/runtime/compiler/compile/J9SymbolReferenceTable.cpp b/runtime/compiler/compile/J9SymbolReferenceTable.cpp index b479f863e88..c155c2496a3 100644 --- a/runtime/compiler/compile/J9SymbolReferenceTable.cpp +++ b/runtime/compiler/compile/J9SymbolReferenceTable.cpp @@ -636,7 +636,7 @@ J9::SymbolReferenceTable::methodSymRefWithSignature(TR::SymbolReference *origina int32_t fullSignatureLength = originalMethod->classNameLength() + 1 + originalMethod->nameLength() + effectiveSignatureLength; char *fullSignature = (char*)trMemory()->allocateMemory(1 + fullSignatureLength, stackAlloc); - sprintf(fullSignature, "%.*s.%.*s%.*s", originalMethod->classNameLength(), originalMethod->classNameChars(), originalMethod->nameLength(), originalMethod->nameChars(), effectiveSignatureLength, effectiveSignature); + snprintf(fullSignature, 1 + fullSignatureLength, "%.*s.%.*s%.*s", originalMethod->classNameLength(), originalMethod->classNameChars(), originalMethod->nameLength(), originalMethod->nameChars(), effectiveSignatureLength, effectiveSignature); TR_ASSERT(strlen(fullSignature) == fullSignatureLength, "Computed fullSignatureLength must match actual length of fullSignature"); CS2::HashIndex hashIndex = 0; static char *ignoreMBSCache = feGetEnv("TR_ignoreMBSCache"); diff --git a/runtime/compiler/control/CompilationThread.cpp b/runtime/compiler/control/CompilationThread.cpp index f26b2ef7c62..8d58e7c3c93 100644 --- a/runtime/compiler/control/CompilationThread.cpp +++ b/runtime/compiler/control/CompilationThread.cpp @@ -1128,8 +1128,8 @@ TR::CompilationInfoPerThread::CompilationInfoPerThread(TR::CompilationInfo &comp // NOTE: // the (char *) casts are done because on Z, sprintf expects // a (char *) instead of a (const char *) - sprintf(_activeThreadName, (char *) selectedActiveThreadName, getCompThreadId()); - sprintf(_suspendedThreadName, (char *) selectedSuspendedThreadName, getCompThreadId()); + snprintf(_activeThreadName, activeThreadNameLength, (char *) selectedActiveThreadName, getCompThreadId()); + snprintf(_suspendedThreadName, suspendedThreadNameLength, (char *) selectedSuspendedThreadName, getCompThreadId()); _initializationSucceeded = true; } diff --git a/runtime/compiler/control/DLLMain.cpp b/runtime/compiler/control/DLLMain.cpp index f528061b84d..b9ebf32dc81 100644 --- a/runtime/compiler/control/DLLMain.cpp +++ b/runtime/compiler/control/DLLMain.cpp @@ -631,7 +631,7 @@ IDATA J9VMDllMain(J9JavaVM* vm, IDATA stage, void * reserved) continue; //char threadName[32]; // make sure the name below does not exceed 32 chars - //sprintf(threadName, "JIT Compilation Thread-%d", curCompThreadInfoPT->getCompThreadId()); + //snprintf(threadName, sizeof(threadName), "JIT Compilation Thread-%d", curCompThreadInfoPT->getCompThreadId()); char *threadName = ( curCompThreadInfoPT->compilationThreadIsActive() ? diff --git a/runtime/compiler/control/HookedByTheJit.cpp b/runtime/compiler/control/HookedByTheJit.cpp index ad8a64bc9bb..7c6bcaca645 100644 --- a/runtime/compiler/control/HookedByTheJit.cpp +++ b/runtime/compiler/control/HookedByTheJit.cpp @@ -199,7 +199,7 @@ TR::OptionSet *findOptionSet(J9Method *method, bool isAOT) if (methodSignature) { - sprintf(methodSignature, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); + snprintf(methodSignature, len, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); TR_FilterBST * filter = 0; if (TR::Options::getDebug() && TR::Options::getDebug()->getCompilationFilters()) @@ -469,7 +469,7 @@ static void jitHookInitializeSendTarget(J9HookInterface * * hook, UDATA eventNum if (sigLen < 1024) { char sigC[1024]; - sigLen = sprintf(sigC, "%.*s.%.*s%.*s", + sigLen = snprintf(sigC, sizeof(sigC), "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); @@ -746,7 +746,7 @@ static void jitHookInitializeSendTarget(J9HookInterface * * hook, UDATA eventNum J9UTF8 * className = J9ROMCLASS_CLASSNAME(J9_CLASS_FROM_METHOD(method)->romClass); J9UTF8 * name = J9ROMMETHOD_NAME(J9_ROM_METHOD_FROM_RAM_METHOD(method)); J9UTF8 * signature = J9ROMMETHOD_SIGNATURE(J9_ROM_METHOD_FROM_RAM_METHOD(method)); - int32_t sigLen = sprintf(buf, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); + int32_t sigLen = snprintf(buf, sizeof(buf), "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); printf("Initial: Signature %s Count %d isLoopy %d isAOT %" OMR_PRIuPTR " is in SCC %d SCCContainsProfilingInfo %d \n",buf,TR::CompilationInfo::getInvocationCount(method),J9ROMMETHOD_HAS_BACKWARDS_BRANCHES(romMethod), TR::Options::sharedClassCache() ? jitConfig->javaVM->sharedClassConfig->existsCachedCodeForROMMethod(vmThread, romMethod) : 0, TR::Options::sharedClassCache() ? TR_J9VMBase::get(jitConfig, vmThread, TR_J9VMBase::AOT_VM)->sharedCache()->isClassInSharedCache(J9_CLASS_FROM_METHOD(method)) : 0,containsInfo) ; fflush(stdout); @@ -1740,7 +1740,7 @@ static void initThreadAfterCreation(J9VMThread *vmThread) char fileName[64]; IDATA tracefp= -1; - sprintf(fileName, "%s_" POINTER_PRINTF_FORMAT, pJitConfig->itraceFileNamePrefix, vmThread); + snprintf(fileName, sizeof(fileName), "%s_" POINTER_PRINTF_FORMAT, pJitConfig->itraceFileNamePrefix, vmThread); if ((tracefp = j9file_open(fileName, EsOpenWrite | EsOpenAppend | EsOpenCreate, 0644)) == -1) { diff --git a/runtime/compiler/control/J9CompilationStrategy.cpp b/runtime/compiler/control/J9CompilationStrategy.cpp index 0d05ef5267d..1e4fce80c03 100644 --- a/runtime/compiler/control/J9CompilationStrategy.cpp +++ b/runtime/compiler/control/J9CompilationStrategy.cpp @@ -238,6 +238,7 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) int32_t totalSampleCount = TR::Recompilation::globalSampleCount; char msg[350]; // size should be big enough to hold the whole one-line msg + size_t maxMsgLen = sizeof(msg); msg[0] = 0; char *curMsg = msg; bool logSampling = fe->isLogSamplingSet() || TrcEnabled_Trc_JIT_Sampling_Detail; @@ -252,7 +253,18 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) fe->printTruncatedSignature(sig, SIG_SZ, (TR_OpaqueMethodBlock*)j9method); if (logSampling) - curMsg += sprintf(curMsg, "(%d)\tInterpreted %s\t", totalSampleCount, sig); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, "(%d)\tInterpreted %s\t", totalSampleCount, sig); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } if (TrcEnabled_Trc_JIT_Sampling && ((totalSampleCount % 4) == 0)) Trc_JIT_Sampling(getJ9VMThreadFromTR_VM(fe), "Interpreted", sig, 0); } @@ -294,20 +306,30 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) // Reduce the invocation count. // int32_t newCount = count / divisor; + size_t msgLen = 0; // Don't decrement more than the number of active threads if (newCount < activeThreadsThreshold) newCount = activeThreadsThreshold; if (TR::CompilationInfo::setInvocationCount(j9method, count, newCount)) { if (logSampling) - curMsg += sprintf(curMsg, " reducing count %d --> %d", count, newCount); + msgLen = snprintf(curMsg, maxMsgLen, " reducing count %d --> %d", count, newCount); if (cmdLineOptions->getOption(TR_UseSamplingJProfilingForInterpSampledMethods)) compInfo->getInterpSamplTrackingInfo()->addOrUpdate(j9method, count - newCount); } else { if (logSampling) - curMsg += sprintf(curMsg, " count = %d, already changed", count); + msgLen = snprintf(curMsg, maxMsgLen, " count = %d, already changed", count); + } + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; } // If the method is ready to be compiled and we are using a separate @@ -323,6 +345,7 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) } else if (returnIprofilerState() == IPROFILING_STATE_OFF) { + size_t msgLen = 0; int32_t newCount = 0; if (cmdLineOptions->getOption(TR_SubtractMethodCountsWhenIprofilerIsOff)) newCount = count - TR::Options::_IprofilerOffSubtractionFactor; @@ -335,18 +358,28 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) if (TR::CompilationInfo::setInvocationCount(j9method, count, newCount)) { if (logSampling) - curMsg += sprintf(curMsg, " reducing count %d --> %d", count, newCount); + msgLen = snprintf(curMsg, maxMsgLen, " reducing count %d --> %d", count, newCount); if (cmdLineOptions->getOption(TR_UseSamplingJProfilingForInterpSampledMethods)) compInfo->getInterpSamplTrackingInfo()->addOrUpdate(j9method, count - newCount); } else { if (logSampling) - curMsg += sprintf(curMsg, " count = %d, already changed", count); + msgLen = snprintf(curMsg, maxMsgLen, " count = %d, already changed", count); + } + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; } } else if (loopy && count > activeThreadsThreshold) { + size_t msgLen = 0; int32_t newCount = 0; if (cmdLineOptions->getOption(TR_SubtractLoopyMethodCounts)) newCount = count - TR::Options::_LoopyMethodSubtractionFactor; @@ -360,20 +393,40 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) if (TR::CompilationInfo::setInvocationCount(j9method, count, newCount)) { if (logSampling) - curMsg += sprintf(curMsg, " reducing count %d --> %d", count, newCount); + msgLen = snprintf(curMsg, maxMsgLen, " reducing count %d --> %d", count, newCount); if (cmdLineOptions->getOption(TR_UseSamplingJProfilingForInterpSampledMethods)) compInfo->getInterpSamplTrackingInfo()->addOrUpdate(j9method, count - newCount); } else { if (logSampling) - curMsg += sprintf(curMsg, " count = %d, already changed", count); + msgLen = snprintf(curMsg, maxMsgLen, " count = %d, already changed", count); + } + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; } } else { if (logSampling) - curMsg += sprintf(curMsg, " count = %d / %d", count, threshold); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, " count = %d / %d", count, threshold); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } } } else if (count == 0) @@ -384,7 +437,18 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) // The method receives a sample while still being interpreted. We should probably // schedule a compilation if (logSampling) - curMsg += sprintf(curMsg, " count = 0 (long running?)"); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, " count = 0 (long running?)"); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } if (fe->isAsyncCompilation()) { if (TR::Options::_compilationDelayTime <= 0 || @@ -397,7 +461,18 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) if (TR::CompilationInfo::getJ9MethodVMExtra(j9method) == J9_JIT_QUEUED_FOR_COMPILATION) { if (logSampling) - curMsg += sprintf(curMsg, " already queued"); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, " already queued"); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } if (compInfo && (compInfo->compBudgetSupport() || compInfo->dynamicThreadPriority())) { @@ -406,29 +481,60 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) fe->releaseCompilationLock(); if (logSampling) { + size_t msgLen = 0; if (n > 0) - curMsg += sprintf(curMsg, " promoted from %d", n); + msgLen = snprintf(curMsg, maxMsgLen, " promoted from %d", n); else if (n == 0) - curMsg += sprintf(curMsg, " comp in progress"); + msgLen = snprintf(curMsg, maxMsgLen, " comp in progress"); + else + msgLen = snprintf(curMsg, maxMsgLen, " already in the right place %d", n); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } else - curMsg += sprintf(curMsg, " already in the right place %d", n); + { + maxMsgLen = 0; + } } } } else { if (logSampling) - curMsg += sprintf(curMsg, " cannot be compiled, extra field is %" OMR_PRIdPTR, TR::CompilationInfo::getJ9MethodExtra(j9method)); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, " cannot be compiled, extra field is %" OMR_PRIdPTR, TR::CompilationInfo::getJ9MethodExtra(j9method)); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } } } TR::Recompilation::globalSampleCount++; } else if (logSampling) { + size_t msgLen = 0; if (count >= 0) - curMsg += sprintf(curMsg, " %d invocations before compiling", count); + msgLen = snprintf(curMsg, maxMsgLen, " %d invocations before compiling", count); else - curMsg += sprintf(curMsg, " cannot be compiled"); + msgLen = snprintf(curMsg, maxMsgLen, " cannot be compiled"); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } } } else // sampling interpreted body, but method was compiled @@ -444,7 +550,18 @@ J9::CompilationStrategy::processInterpreterSample(TR_MethodEvent *event) bodyInfo->_longRunningInterpreted = true; if (logSampling) - curMsg += sprintf(curMsg, " counter = XX (long running?)"); + { + size_t msgLen = snprintf(curMsg, maxMsgLen, " counter = XX (long running?)"); + if (msgLen <= maxMsgLen) + { + curMsg += msgLen; + maxMsgLen -= msgLen; + } + else + { + maxMsgLen = 0; + } + } // Note that we do not increment globalSampleCount here } if (fe->isLogSamplingSet()) @@ -529,11 +646,13 @@ J9::CompilationStrategy::ProcessJittedSample::initializeRecompRelatedFields() if (_logSampling) { - _curMsg += sprintf(_curMsg, " cnt=%d ncl=%d glblSmplCnt=%d startCnt=%d[-%u,+%u] samples=[%d %d] windows=[%d %u] crtSmplIntrvlCnt=%u", + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " cnt=%d ncl=%d glblSmplCnt=%d startCnt=%d[-%u,+%u] samples=[%d %d] windows=[%d %u] crtSmplIntrvlCnt=%u", _count, _methodInfo->getNextCompileLevel(), _totalSampleCount, _startSampleCount, _bodyInfo->getOldStartCountDelta(), _bodyInfo->getHotStartCountDelta(), _globalSamples, _globalSamplesInHotWindow, _scorchingSampleInterval, _hotSampleInterval, _crtSampleIntervalCount); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; } } @@ -547,7 +666,11 @@ J9::CompilationStrategy::ProcessJittedSample::logSampleInfoToBuffer() _fe->printTruncatedSignature(sig, SIG_SZ, (TR_OpaqueMethodBlock*)_j9method); int32_t pcOffset = (uint8_t *)(_event->_samplePC) - (uint8_t *)_startPC; if (_logSampling) - _curMsg += sprintf(_curMsg, "(%d)\tCompiled %s\tPC=" POINTER_PRINTF_FORMAT "\t%+d\t", _totalSampleCount, sig, _startPC, pcOffset); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, "(%d)\tCompiled %s\tPC=" POINTER_PRINTF_FORMAT "\t%+d\t", _totalSampleCount, sig, _startPC, pcOffset); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } if (TrcEnabled_Trc_JIT_Sampling && ((_totalSampleCount % 4) == 0)) Trc_JIT_Sampling(getJ9VMThreadFromTR_VM(_fe), "Compiled", sig, 0); // TODO put good pcOffset #undef SIG_SZ @@ -596,35 +719,42 @@ void J9::CompilationStrategy::ProcessJittedSample::findAndSetBodyAndMethodInfo() { J9::PrivateLinkage::LinkageInfo *linkageInfo = J9::PrivateLinkage::LinkageInfo::get(_startPC); + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = 0; if (linkageInfo->hasFailedRecompilation()) { _compInfo->_stats._compiledMethodSamplesIgnored++; if (_logSampling) - _curMsg += sprintf(_curMsg, " has already failed a recompilation attempt"); + msgLen = snprintf(_curMsg, maxMsgLen, " has already failed a recompilation attempt"); } else if (!linkageInfo->isSamplingMethodBody()) { _compInfo->_stats._compiledMethodSamplesIgnored++; if (_logSampling) - _curMsg += sprintf(_curMsg, " does not use sampling"); + msgLen = snprintf(_curMsg, maxMsgLen, " does not use sampling"); } else if (debug("disableSamplingRecompilation")) { _compInfo->_stats._compiledMethodSamplesIgnored++; if (_logSampling) - _curMsg += sprintf(_curMsg, " sampling disabled"); + msgLen = snprintf(_curMsg, maxMsgLen, " sampling disabled"); } else { _bodyInfo = TR::Recompilation::getJittedBodyInfoFromPC(_startPC); } + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; if (_bodyInfo && _bodyInfo->getDisableSampling()) { _compInfo->_stats._compiledMethodSamplesIgnored++; if (_logSampling) - _curMsg += sprintf(_curMsg, " uses sampling but sampling disabled (last comp. with prex)"); + { + maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + msgLen = snprintf(_curMsg, maxMsgLen, " uses sampling but sampling disabled (last comp. with prex)"); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } _bodyInfo = NULL; } @@ -662,7 +792,11 @@ J9::CompilationStrategy::ProcessJittedSample::shouldProcessSample() !_isAlreadyBeingCompiled) { if (_logSampling) - _curMsg += sprintf(_curMsg, " uses sampling but a recomp decision has already been taken"); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " uses sampling but a recomp decision has already been taken"); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } shouldProcess = false; } } @@ -706,7 +840,11 @@ J9::CompilationStrategy::ProcessJittedSample::determineWhetherToRecompileIfCount _methodInfo->setDisableMiscSamplingCounterDecrementation(); // write a message in the vlog to know the reason of recompilation if (_logSampling) - _curMsg += sprintf(_curMsg, " PICrecomp"); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " PICrecomp"); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } _methodInfo->setReasonForRecompilation(TR_PersistentMethodInfo::RecompDueToMegamorphicCallProfile); } else @@ -848,7 +986,9 @@ J9::CompilationStrategy::ProcessJittedSample::determineWhetherToRecompileBasedOn float scalingFactor = 0.01*((100 - TR::Options::_sampleThresholdVariationAllowance) + (avgCodeSize << 1)*TR::Options::_sampleThresholdVariationAllowance / (float)(avgCodeSize + codeSize)); - _curMsg += sprintf(_curMsg, " SizeScaling=%.1f", scalingFactor); + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " SizeScaling=%.1f", scalingFactor); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; _scaledHotThreshold = (int32_t)(_hotSampleThreshold * scalingFactor); // Do not use aggressive recompilations for big applications like websphere. @@ -911,7 +1051,11 @@ J9::CompilationStrategy::ProcessJittedSample::determineWhetherToRecompileBasedOn _compInfo->_stats._methodsSampleWindowReset++; _bodyInfo->setCounter(_count + _hotSampleInterval); if (_logSampling) - _curMsg += sprintf(_curMsg, " is cold, reset cnt to %d", _bodyInfo->getCounter()); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " is cold, reset cnt to %d", _bodyInfo->getCounter()); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } } // The hot sample interval is done. Prepare for next interval. @@ -953,7 +1097,11 @@ J9::CompilationStrategy::ProcessJittedSample::determineWhetherToRecompileBasedOn if (entry) { if (_logSampling) - _curMsg += sprintf(_curMsg, " adj opt lvl to %d", (int32_t)(entry->_optimizationPlan->getOptLevel())); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " adj opt lvl to %d", (int32_t)(entry->_optimizationPlan->getOptLevel())); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } int32_t measuredCpuUtil = _crtSampleIntervalCount == 0 ? // scorching interval done? _scorchingSampleInterval * 1000 / _globalSamples : _hotSampleInterval * 1000 / _globalSamplesInHotWindow; @@ -1078,29 +1226,40 @@ J9::CompilationStrategy::ProcessJittedSample::triggerRecompIfNeeded() if (_logSampling) { float cpu = measuredCpuUtil / 10.0; + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = 0; if (_useProfiling) - _curMsg += sprintf(_curMsg, " --> recompile at level %d, profiled CPU=%.1f%%", _nextOptLevel, cpu); + msgLen = snprintf(_curMsg, maxMsgLen, " --> recompile at level %d, profiled CPU=%.1f%%", _nextOptLevel, cpu); else - _curMsg += sprintf(_curMsg, " --> recompile at level %d CPU=%.1f%%", _nextOptLevel, cpu); + msgLen = snprintf(_curMsg, maxMsgLen, " --> recompile at level %d CPU=%.1f%%", _nextOptLevel, cpu); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; if (_methodInfo->getReasonForRecompilation() == TR_PersistentMethodInfo::RecompDueToThreshold) { - _curMsg += sprintf(_curMsg, " scaledThresholds=[%d %d]", _scaledScorchingThreshold, _scaledHotThreshold); + maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + msgLen = snprintf(_curMsg, maxMsgLen, " scaledThresholds=[%d %d]", _scaledScorchingThreshold, _scaledHotThreshold); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; } } } else // OOM { if (_logSampling) - _curMsg += sprintf(_curMsg, " --> not recompiled: OOM"); + { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = snprintf(_curMsg, maxMsgLen, " --> not recompiled: OOM"); + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; + } } } else if (_logSampling) { + size_t maxMsgLen = sizeof(_msg) - (_curMsg - _msg); + size_t msgLen = 0; if (_isAlreadyBeingCompiled) - _curMsg += sprintf(_curMsg, " - is already being recompiled"); + msgLen = snprintf(_curMsg, maxMsgLen, " - is already being recompiled"); else if (!_hotSamplingWindowComplete) - _curMsg += sprintf(_curMsg, " not recompiled, smpl interval not done"); + msgLen = snprintf(_curMsg, maxMsgLen, " not recompiled, smpl interval not done"); else { float measuredCpuUtil = 0.0; @@ -1114,10 +1273,11 @@ J9::CompilationStrategy::ProcessJittedSample::triggerRecompIfNeeded() if (_globalSamplesInHotWindow) measuredCpuUtil = _hotSampleInterval * 100.0 / _globalSamplesInHotWindow; } - _curMsg += sprintf(_curMsg, " not recompiled, CPU=%.1f%% %s scaledThresholds=[%d %d]", + msgLen = snprintf(_curMsg, maxMsgLen, " not recompiled, CPU=%.1f%% %s scaledThresholds=[%d %d]", measuredCpuUtil, _postponeDecision ? " postpone decision" : "", _scaledScorchingThreshold, _scaledHotThreshold); } + _curMsg += (msgLen <= maxMsgLen) ? msgLen : maxMsgLen; } return plan; diff --git a/runtime/compiler/control/MethodToBeCompiled.cpp b/runtime/compiler/control/MethodToBeCompiled.cpp index d85d3c83109..59915c336eb 100644 --- a/runtime/compiler/control/MethodToBeCompiled.cpp +++ b/runtime/compiler/control/MethodToBeCompiled.cpp @@ -42,7 +42,7 @@ TR_MethodToBeCompiled *TR_MethodToBeCompiled::allocate(J9JITConfig *jitConfig) return NULL; entry->_index = _globalIndex++; - sprintf(entry->_monitorName, "JIT-QueueSlotMonitor-%d", (int32_t)entry->_index); + snprintf(entry->_monitorName, sizeof(entry->_monitorName), "JIT-QueueSlotMonitor-%d", (int32_t)entry->_index); entry->_monitor = TR::Monitor::create(entry->_monitorName); if (!entry->_monitor) { diff --git a/runtime/compiler/control/OptionsPostRestore.cpp b/runtime/compiler/control/OptionsPostRestore.cpp index f4bdf93d89f..a640185b459 100644 --- a/runtime/compiler/control/OptionsPostRestore.cpp +++ b/runtime/compiler/control/OptionsPostRestore.cpp @@ -476,7 +476,7 @@ J9::OptionsPostRestore::shouldInvalidateCompiledMethod(J9Method *method, TR_J9VM if (methodSignature) { - sprintf(methodSignature, "%.*s.%.*s%.*s", + snprintf(methodSignature, len, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); diff --git a/runtime/compiler/env/VMJ9.cpp b/runtime/compiler/env/VMJ9.cpp index faa0f976d50..bfec77a0419 100644 --- a/runtime/compiler/env/VMJ9.cpp +++ b/runtime/compiler/env/VMJ9.cpp @@ -2628,7 +2628,7 @@ TR_J9VMBase::printTruncatedSignature(char *sigBuf, int32_t bufLen, J9UTF8 *class int32_t sigLen = J9UTF8_LENGTH(className) + J9UTF8_LENGTH(name) + J9UTF8_LENGTH(signature)+2; if (sigLen < bufLen) { - sigLen = sprintf(sigBuf, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), + sigLen = snprintf(sigBuf, (size_t)bufLen, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); } @@ -2636,7 +2636,7 @@ TR_J9VMBase::printTruncatedSignature(char *sigBuf, int32_t bufLen, J9UTF8 *class { if (sigLen - bufLen < J9UTF8_LENGTH(signature)) // classname and methodname can fit { - sigLen = sprintf(sigBuf, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), + sigLen = snprintf(sigBuf, (size_t)bufLen, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), (J9UTF8_LENGTH(signature) - (sigLen-bufLen)), utf8Data(signature)); } @@ -2644,9 +2644,9 @@ TR_J9VMBase::printTruncatedSignature(char *sigBuf, int32_t bufLen, J9UTF8 *class { int32_t nameLen = std::min(bufLen-3, J9UTF8_LENGTH(name)); if (nameLen == bufLen-3) // not even the method name can be printed entirely - sigLen = sprintf(sigBuf, "*.%.*s", nameLen, utf8Data(name)); + sigLen = snprintf(sigBuf, (size_t)bufLen, "*.%.*s", nameLen, utf8Data(name)); else - sigLen = sprintf(sigBuf, "%.*s.%.*s", std::min(bufLen-2 - nameLen, J9UTF8_LENGTH(className)), utf8Data(className), nameLen, utf8Data(name)); + sigLen = snprintf(sigBuf, (size_t)bufLen, "%.*s.%.*s", std::min(bufLen-2 - nameLen, J9UTF8_LENGTH(className)), utf8Data(className), nameLen, utf8Data(name)); } } return sigLen; @@ -3627,7 +3627,7 @@ TR_J9VMBase::compileMethods(TR::OptionSet *optionSet, void *config) } } - sprintf(fullMethodName, "%.*s.%.*s%.*s", + snprintf(fullMethodName, maxMethodNameLen, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), J9UTF8_DATA(className), J9UTF8_LENGTH(name), J9UTF8_DATA(name), J9UTF8_LENGTH(signature), J9UTF8_DATA(signature)); @@ -4239,9 +4239,10 @@ TR_J9VMBase::unknownByteCode(TR::Compilation * comp, U_8 opcode) char* TR_J9VMBase::printAdditionalInfoOnAssertionFailure(TR::Compilation *comp) { - char *c = (char *)comp->trMemory()->allocateHeapMemory(20); + size_t cSize = 20; + char *c = (char *)comp->trMemory()->allocateHeapMemory(cSize); - sprintf(c, "VMState: %#010" OMR_PRIxPTR, vmThread()->omrVMThread->vmState); + snprintf(c, cSize, "VMState: %#010" OMR_PRIxPTR, vmThread()->omrVMThread->vmState); return c; } @@ -4343,8 +4344,9 @@ getJ2IThunkSignature(char *invokeHandleSignature, uint32_t signatureLength, int argsToCopy = nextSignatureArgument(argsToCopy); uint32_t lengthToCopy = signatureLength - (argsToCopy - invokeHandleSignature); - char *resultBuf = (char*)comp->trMemory()->allocateMemory(2+lengthToCopy, stackAlloc); - sprintf(resultBuf, "(%.*s", lengthToCopy, argsToCopy); + size_t resultLen = 2 + lengthToCopy; + char *resultBuf = (char*)comp->trMemory()->allocateMemory(resultLen, stackAlloc); + snprintf(resultBuf, resultLen, "(%.*s", lengthToCopy, argsToCopy); if (comp->getOption(TR_TraceCG)) traceMsg(comp, "JSR292: j2i-thunk signature for %s of '%.*s' is '%s'\n", description, signatureLength, invokeHandleSignature, resultBuf); @@ -4581,6 +4583,7 @@ TR_J9VMBase::lookupMethodHandleThunkArchetype(uintptr_t methodHandle) char *archetypeSpecimenSignature = (char*)alloca(thunkableSignatureLength+20); strcpy(archetypeSpecimenSignature, thunkSignature); char *returnType = (1+strchr(archetypeSpecimenSignature, ')')); + size_t maxSize = (thunkableSignatureLength + 20) - (returnType - archetypeSpecimenSignature); switch (returnType[0]) { case '[': @@ -4588,11 +4591,11 @@ TR_J9VMBase::lookupMethodHandleThunkArchetype(uintptr_t methodHandle) // The thunkable signature might return some other class, but archetypes // returning a reference are always declared to return Object. // - sprintf(returnType, "Ljava/lang/Object;"); + snprintf(returnType, maxSize, "Ljava/lang/Object;"); break; } char methodName[50]; - sprintf(methodName, "invokeExact_thunkArchetype_%c", returnType[0]); + snprintf(methodName, sizeof(methodName), "invokeExact_thunkArchetype_%c", returnType[0]); TR_OpaqueMethodBlock *result = lookupArchetype(getObjectClass((uintptr_t)methodHandle), methodName, archetypeSpecimenSignature); if (!result) @@ -7051,7 +7054,7 @@ TR_J9VM::sampleSignature(TR_OpaqueMethodBlock * aMethod, char *buf, int32_t bufL int32_t len = J9UTF8_LENGTH(className)+J9UTF8_LENGTH(name)+J9UTF8_LENGTH(signature)+3; char * s = len <= bufLen ? buf : (memory ? (char*)memory->allocateHeapMemory(len) : NULL); if (s) - sprintf(s, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); + snprintf(s, (size_t)len, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); return s; } diff --git a/runtime/compiler/env/VMJ9Server.cpp b/runtime/compiler/env/VMJ9Server.cpp index 0bc52f25216..0b81d41b975 100644 --- a/runtime/compiler/env/VMJ9Server.cpp +++ b/runtime/compiler/env/VMJ9Server.cpp @@ -1044,7 +1044,7 @@ TR_J9ServerVM::sampleSignature(TR_OpaqueMethodBlock * aMethod, char *buf, int32_ int32_t len = J9UTF8_LENGTH(className) + J9UTF8_LENGTH(name) + J9UTF8_LENGTH(signature) + 3; char *s = len <= bufLen ? buf : (trMemory ? (char *)trMemory->allocateHeapMemory(len) : NULL); if (s) - sprintf(s, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); + snprintf(s, len, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); return s; } diff --git a/runtime/compiler/env/annotations/Annotations.cpp b/runtime/compiler/env/annotations/Annotations.cpp index 429f5c91cde..4e2884b720d 100644 --- a/runtime/compiler/env/annotations/Annotations.cpp +++ b/runtime/compiler/env/annotations/Annotations.cpp @@ -107,8 +107,8 @@ TR_Debug::printAnnotationInfoEntry(J9AnnotationInfo * annotationInfo, signatureName = ""; if ((flag & ~ANNOTATION_PARM_MASK) == ANNOTATION_TYPE_PARAMETER) { - sprintf(annNameBuffer,"parm(%d)",(flag & ANNOTATION_PARM_MASK) >> ANNOTATION_PARM_SHIFT); - TR_ASSERT( strlen(annNameBuffer) < ANNO_NAMEBUF_LEN, "buffer length somehow exceeded\n"); + size_t len = snprintf(annNameBuffer, sizeof(annNameBuffer), "parm(%d)",(flag & ANNOTATION_PARM_MASK) >> ANNOTATION_PARM_SHIFT); + TR_ASSERT(len < sizeof(annNameBuffer), "buffer length somehow exceeded\n"); annotationTypeName = annNameBuffer; filterOnName = true; break; diff --git a/runtime/compiler/env/j9method.cpp b/runtime/compiler/env/j9method.cpp index c2e3eef7804..96050dbd2f9 100644 --- a/runtime/compiler/env/j9method.cpp +++ b/runtime/compiler/env/j9method.cpp @@ -398,8 +398,9 @@ TR_J9MethodBase::signature(TR_Memory * trMemory, TR_AllocationKind allocKind) { if( !_fullSignature ) { - char * s = (char *)trMemory->allocateMemory(classNameLength() + nameLength() + signatureLength() + 3, allocKind); - sprintf(s, "%.*s.%.*s%.*s", classNameLength(), classNameChars(), nameLength(), nameChars(), signatureLength(), signatureChars()); + size_t len = classNameLength() + nameLength() + signatureLength() + 3; + char * s = (char *)trMemory->allocateMemory(len, allocKind); + snprintf(s, len, "%.*s.%.*s%.*s", classNameLength(), classNameChars(), nameLength(), nameChars(), signatureLength(), signatureChars()); if ( allocKind == heapAlloc) _fullSignature = s; @@ -690,7 +691,7 @@ TR_ResolvedJ9MethodBase::fieldOrStaticName(I_32 cpIndex, int32_t & len, TR_Memor len = J9UTF8_LENGTH(declName) + J9UTF8_LENGTH(J9ROMNAMEANDSIGNATURE_NAME(nameAndSignature)) + J9UTF8_LENGTH(J9ROMNAMEANDSIGNATURE_SIGNATURE(nameAndSignature)) +3; char * s = (char *)trMemory->allocateMemory(len, kind); - sprintf(s, "%.*s.%.*s %.*s", + snprintf(s, len, "%.*s.%.*s %.*s", J9UTF8_LENGTH(declName), utf8Data(declName), J9UTF8_LENGTH(J9ROMNAMEANDSIGNATURE_NAME(nameAndSignature)), utf8Data(J9ROMNAMEANDSIGNATURE_NAME(nameAndSignature)), J9UTF8_LENGTH(J9ROMNAMEANDSIGNATURE_SIGNATURE(nameAndSignature)), utf8Data(J9ROMNAMEANDSIGNATURE_SIGNATURE(nameAndSignature))); @@ -5280,10 +5281,7 @@ bool TR_ResolvedJ9Method::isSubjectToPhaseChange(TR::Compilation *comp) if (J9UTF8_LENGTH(name) == 13) { - char s[15]; - sprintf(s, "%.*s", - J9UTF8_LENGTH(name), J9UTF8_DATA(name)); - if (strncmp(s, "specInstance$", 13) == 0) + if (0 == strncmp((const char *)J9UTF8_DATA(name), "specInstance$", 13)) return true; } } @@ -6504,8 +6502,9 @@ TR_ResolvedJ9Method::newInstancePrototypeSignature(TR_Memory * m, TR_AllocationK TR_ASSERT(_j9classForNewInstance, "Must have the class for newInstance"); J9Class * clazz = _j9classForNewInstance; //((J9Class*)((uintptr_t)(ramMethod()->extra) & ~J9_STARTPC_NOT_TRANSLATED); char * className = fej9()->getClassNameChars(_fe->convertClassPtrToClassOffset(clazz), clen); - char * s = (char *)m->allocateMemory(clen+nameLength()+signatureLength()+3, allocKind); - sprintf(s, "%.*s.%.*s%.*s", clen, className, nameLength(), nameChars(), signatureLength(), signatureChars()); + size_t len = clen + nameLength() + signatureLength() + 3; + char * s = (char *)m->allocateMemory(len, allocKind); + snprintf(s, len, "%.*s.%.*s%.*s", clen, className, nameLength(), nameChars(), signatureLength(), signatureChars()); return s; } @@ -8076,7 +8075,7 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) sourceType = "Ljava/lang/Object;"; break; default: - sprintf(sourceBuf, "%c", sourceSig[0]); + snprintf(sourceBuf, sizeof(sourceBuf), "%c", sourceSig[0]); break; } switch (targetSig[0]) @@ -8087,7 +8086,7 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) targetType = "Ljava/lang/Object;"; break; default: - sprintf(targetBuf, "%c", targetSig[0]); + snprintf(targetBuf, sizeof(targetBuf), "%c", targetSig[0]); break; } @@ -8097,10 +8096,10 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) { char methodName[30], methodSignature[50]; if ((sourceType[0] == 'L') && isExplicit) - sprintf(methodName, "explicitObject2%s", targetName); + snprintf(methodName, sizeof(methodName), "explicitObject2%s", targetName); else - sprintf(methodName, "%s2%s", sourceName, targetName); - sprintf(methodSignature, "(%s)%s", sourceType, targetType); + snprintf(methodName, sizeof(methodName), "%s2%s", sourceName, targetName); + snprintf(methodSignature, sizeof(methodSignature), "(%s)%s", sourceType, targetType); TR::SymbolReference *methodSymRef = comp()->getSymRefTab()->methodSymRefFromName(_methodSymbol, "java/lang/invoke/ConvertHandle$FilterHelpers", methodName, @@ -8421,11 +8420,11 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) { case 'L': case '[': - sprintf(extraName, "extra_L"); + snprintf(extraName, sizeof(extraName), "extra_L"); extraSignature = artificialSignature(stackAlloc, "(L" JSR292_ArgumentMoverHandle ";I)Ljava/lang/Object;"); break; default: - sprintf(extraName, "extra_%c", argType[0]); + snprintf(extraName, sizeof(extraName), "extra_%c", argType[0]); extraSignature = artificialSignature(stackAlloc, "(L" JSR292_ArgumentMoverHandle ";I).@", nextHandleSignature, i); break; } @@ -8504,11 +8503,11 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) { case 'L': case '[': - sprintf(extraName, "extra_L"); + snprintf(extraName, sizeof(extraName), "extra_L"); extraSignature = artificialSignature(stackAlloc, "(L" JSR292_ArgumentMoverHandle ";I)Ljava/lang/Object;"); break; default: - sprintf(extraName, "extra_%c", argType[0]); + snprintf(extraName, sizeof(extraName), "extra_%c", argType[0]); extraSignature = artificialSignature(stackAlloc, "(L" JSR292_ArgumentMoverHandle ";I).@", nextHandleSignature, i); break; } @@ -8844,11 +8843,11 @@ TR_J9ByteCodeIlGenerator::runFEMacro(TR::SymbolReference *symRef) int32_t arrayRomClassNameLength; char *arrayRomClassNameChars = fej9->getClassNameChars((TR_OpaqueClassBlock*)arrayJ9Class, arrayRomClassNameLength); TR_ASSERT(arrayRomClassNameLength == 2, "Every array romclass '%.*s' should be of the form [X where X is a single character", arrayRomClassNameLength, arrayRomClassNameChars); - sprintf(arrayClassSignature+arity-1, "%.*s", arrayRomClassNameLength, arrayRomClassNameChars); + snprintf(arrayClassSignature+arity-1, leafClassNameLength + 4, "%.*s", arrayRomClassNameLength, arrayRomClassNameChars); } else { - sprintf(arrayClassSignature+arity, "L%.*s;", leafClassNameLength, leafClassNameChars); + snprintf(arrayClassSignature+arity, leafClassNameLength + 3, "L%.*s;", leafClassNameLength, leafClassNameChars); } if (comp()->getOption(TR_TraceILGen)) diff --git a/runtime/compiler/ilgen/Walker.cpp b/runtime/compiler/ilgen/Walker.cpp index 2ac370b97cf..76df57f3460 100644 --- a/runtime/compiler/ilgen/Walker.cpp +++ b/runtime/compiler/ilgen/Walker.cpp @@ -126,7 +126,7 @@ static void printStack(TR::Compilation *comp, TR_Stack *stack, const { TR::Node *node = stack->element(i); traceMsg(comp, "\n"); - sprintf(buf, " @%-2d", i); + snprintf(buf, sizeof(buf), " @%-2d", i); comp->getDebug()->printWithFixedPrefix(comp->getOutFile(), node, 1, false, true, buf); if (!nodesAlreadyPrinted.isSet(node->getGlobalIndex())) { @@ -781,7 +781,7 @@ TR_J9ByteCodeIlGenerator::symRefWithArtificialSignature(TR::SymbolReference *ori return result; } -static int32_t processArtificialSignature(char *result, const char *format, va_list args) +static int32_t processArtificialSignature(char *result, size_t maxResult, const char *format, va_list args) { int32_t resultLength = 0; char *cur = result; @@ -869,10 +869,19 @@ static int32_t processArtificialSignature(char *result, const char *format, va_l TR_ASSERT(length >= 0, "assertion failure"); TR_ASSERT(startChar != NULL, "assertion failure"); - resultLength += length; if (result) - cur += sprintf(cur, "%.*s", length, startChar); - + { + size_t len = snprintf(cur, maxResult - resultLength, "%.*s", length, startChar); + if (len <= (maxResult - resultLength)) + { + cur += len; + resultLength += len; + } + } + else + { + resultLength += length; + } } return resultLength; @@ -893,13 +902,13 @@ char *TR_J9ByteCodeIlGenerator::vartificialSignature(TR_AllocationKind allocKind // va_list argsCopy; va_copy(argsCopy, args); - int32_t resultLength = processArtificialSignature(NULL, format, argsCopy); + int32_t resultLength = processArtificialSignature(NULL, 0, format, argsCopy); va_copy_end(argsCopy); // Produce formatted signature // char *result = (char*)trMemory()->allocateMemory(resultLength+1, allocKind); - processArtificialSignature(result, format, args); + processArtificialSignature(result, resultLength + 1, format, args); return result; } @@ -3187,7 +3196,7 @@ static char *suffixedName(char *baseName, char typeSuffix, char *buf, int32_t bu int32_t methodNameLength = strlen(baseName) + 2; if (methodNameLength >= bufSize) methodName = (char*)comp->trMemory()->allocateStackMemory(methodNameLength+1, TR_MemoryBase::IlGenerator); - sprintf(methodName, "%s%c", baseName, typeSuffix); + snprintf(methodName, methodNameLength + 1, "%s%c", baseName, typeSuffix); return methodName; } @@ -5059,7 +5068,8 @@ TR_J9ByteCodeIlGenerator::runMacro(TR::SymbolReference * symRef) char *secondArgType = nextSignatureArgument(arrayElementType); int arrayElementTypeLength = secondArgType - arrayElementType; - char *expandedArgsSignature = (char*)comp()->trMemory()->allocateStackMemory(numElements * arrayElementTypeLength + 1); + size_t argsLen = (numElements * arrayElementTypeLength) + 1; + char *expandedArgsSignature = (char*)comp()->trMemory()->allocateStackMemory(argsLen); TR::DataType arrayElementDataType = TR::NoType; TR::ILOpCodes convertOp = TR::BadILOp; @@ -5109,7 +5119,16 @@ TR_J9ByteCodeIlGenerator::runMacro(TR::SymbolReference * symRef) loadArrayElement(arrayElementDataType); if (convertOp != TR::BadILOp) genUnary(convertOp); - cursor += sprintf(cursor, "%.*s", arrayElementTypeLength, arrayElementType); + size_t len = snprintf(cursor, argsLen, "%.*s", arrayElementTypeLength, arrayElementType); + if (len <= argsLen) + { + cursor += len; + argsLen -= len; + } + else + { + argsLen = 0; + } } // Create placeholder with signature that reflects the expansion of arguments. diff --git a/runtime/compiler/optimizer/IdiomRecognition.cpp b/runtime/compiler/optimizer/IdiomRecognition.cpp index 88887ac2bfc..e394cbed8e3 100644 --- a/runtime/compiler/optimizer/IdiomRecognition.cpp +++ b/runtime/compiler/optimizer/IdiomRecognition.cpp @@ -240,11 +240,11 @@ TR_CISCNode::dump(TR::FILE *pOutFile, TR::Compilation * comp) const char *name = getName((TR_CISCOps)_opcode, comp); if (isValidOtherInfo()) { - sprintf(buf, "%s %d", name, _otherInfo); + snprintf(buf, sizeof(buf), "%s %d", name, _otherInfo); } else { - sprintf(buf, "%s", name); + snprintf(buf, sizeof(buf), "%s", name); } traceMsg(comp, "[%p] %3d %2d%c %-11s", this, _id, _dagId, isOutsideOfLoop() ? ' ' : 'L', buf); traceMsg(comp, " ["); @@ -345,11 +345,11 @@ TR_CISCNode::printStdout() char buf[256]; if (isValidOtherInfo()) { - sprintf(buf, "%d %d", _opcode, _otherInfo); + snprintf(buf, sizeof(buf), "%d %d", _opcode, _otherInfo); } else { - sprintf(buf, "%d", _opcode); + snprintf(buf, sizeof(buf), "%d", _opcode); } printf("[%p] %3d %2d%c %-11s", this, _id, _dagId, isOutsideOfLoop() ? ' ' : 'L', buf); printf(" ["); @@ -7677,7 +7677,7 @@ TR_CISCTransformer::computeTopologicalEmbedding(TR_CISCGraph *P, TR_CISCGraph *T bool inlined = getBCIndexMinMax(_candidateRegion, &minIndex, &maxIndex, &minLN, &maxLN, true); if (minIndex <= maxIndex) { - sprintf(tmpbuf, ", bcindex %" OMR_PRIu32 " - %" OMR_PRIu32 " linenumber %" OMR_PRIu32 " - %" OMR_PRIu32 "%s.", minIndex, maxIndex, minLN, maxLN, inlined ? " (inlined)" : ""); + snprintf(tmpbuf, sizeof(tmpbuf), ", bcindex %" OMR_PRIu32 " - %" OMR_PRIu32 " linenumber %" OMR_PRIu32 " - %" OMR_PRIu32 "%s.", minIndex, maxIndex, minLN, maxLN, inlined ? " (inlined)" : ""); bcinfo = tmpbuf; } #endif diff --git a/runtime/compiler/optimizer/IdiomTransformations.cpp b/runtime/compiler/optimizer/IdiomTransformations.cpp index 64fbcc770f3..06c9317de85 100644 --- a/runtime/compiler/optimizer/IdiomTransformations.cpp +++ b/runtime/compiler/optimizer/IdiomTransformations.cpp @@ -3435,9 +3435,10 @@ TR_PCISCGraph * makeCopyingTROxGraph(TR::Compilation *c, int32_t ctrl, int pattern) { TR_ASSERT(pattern == 0 || pattern == 1, "not implemented"); - char *name = (char *)TR_MemoryBase::jitPersistentAlloc(16); - sprintf(name, "CopyingTROx(%d)",pattern); - TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, 16); + size_t nameSize = 16; + char *name = (char *)TR_MemoryBase::jitPersistentAlloc(nameSize); + snprintf(name, nameSize, "CopyingTROx(%d)",pattern); + TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, nameSize); /**************************************************************************** opc id dagId #cfg #child other/pred/children */ TR_PCISCNode *byteArray = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_arraybase, TR::NoType, tgt->incNumNodes(),16, 0, 0, 0); tgt->addNode(byteArray); // src array base @@ -3542,9 +3543,10 @@ TR_PCISCGraph * makeCopyingTROTInduction1Graph(TR::Compilation *c, int32_t ctrl, int32_t pattern) { TR_ASSERT(pattern == 0 || pattern == 1, "not implemented"); - char *name = (char *)TR_MemoryBase::jitPersistentAlloc(26); - sprintf(name, "CopyingTROTInduction1(%d)",pattern); - TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, 16); + size_t nameSize = 26; + char *name = (char *)TR_MemoryBase::jitPersistentAlloc(nameSize); + snprintf(name, nameSize, "CopyingTROTInduction1(%d)",pattern); + TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, nameSize); /********************************************************************* opc id dagId #cfg #child other/pred/children */ TR_PCISCNode *v0 = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_arraybase, TR::NoType, tgt->incNumNodes(), 13, 0, 0, 0); tgt->addNode(v0); // src array base TR_PCISCNode *v1 = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_variable, TR::NoType, tgt->incNumNodes(), 12, 0, 0, 0); tgt->addNode(v1); // src array index @@ -4612,9 +4614,10 @@ TR_PCISCGraph * makeCopyingTRTxGraph(TR::Compilation *c, int32_t ctrl, int pattern) { TR_ASSERT(pattern == 0 || pattern == 1 || pattern == 2, "not implemented"); - char *name = (char *)TR_MemoryBase::jitPersistentAlloc(16); - sprintf(name, "CopyingTRTx(%d)",pattern); - TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, 16); + size_t nameSize = 16; + char *name = (char *)TR_MemoryBase::jitPersistentAlloc(nameSize); + snprintf(name, nameSize, "CopyingTRTx(%d)",pattern); + TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, nameSize); /*************************************************************************** opc id dagId #cfg #child other/pred/children */ TR_PCISCNode *charArray = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_arraybase, TR::NoType, tgt->incNumNodes(), 15, 0, 0, 0); tgt->addNode(charArray); // src array base @@ -4856,9 +4859,10 @@ TR_PCISCGraph * makeCopyingTRTOInduction1Graph(TR::Compilation *c, int32_t ctrl, int32_t pattern) { TR_ASSERT(pattern == 0 || pattern == 1 || pattern == 2, "not implemented"); - char *name = (char *)TR_MemoryBase::jitPersistentAlloc(26); - sprintf(name, "CopyingTRTOInduction1(%d)",pattern); - TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, 16); + size_t nameSize = 26; + char *name = (char *)TR_MemoryBase::jitPersistentAlloc(nameSize); + snprintf(name, nameSize, "CopyingTRTOInduction1(%d)",pattern); + TR_PCISCGraph *tgt = new (PERSISTENT_NEW) TR_PCISCGraph(c->trMemory(), name, 0, nameSize); /********************************************************************* opc id dagId #cfg #child other/pred/children */ TR_PCISCNode *v0 = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_arraybase, TR::NoType, tgt->incNumNodes(), 13, 0, 0, 0); tgt->addNode(v0); // src array base TR_PCISCNode *v1 = new (PERSISTENT_NEW) TR_PCISCNode(c->trMemory(), TR_variable, TR::NoType, tgt->incNumNodes(), 12, 0, 0, 0); tgt->addNode(v1); // src array index diff --git a/runtime/compiler/ras/kca_offsets_generator.cpp b/runtime/compiler/ras/kca_offsets_generator.cpp index 99f73150f8c..70a0851dcde 100644 --- a/runtime/compiler/ras/kca_offsets_generator.cpp +++ b/runtime/compiler/ras/kca_offsets_generator.cpp @@ -63,7 +63,7 @@ J9::Options::kcaOffsets(const char *option, void *, TR::OptionTable *entry) szRT[0]='\0'; // The generated file looks like this: kca_offsets_gen_R#_#[_CMPRSS][_RT].h - sprintf( szFileName, "kca_offsets_gen_R%d_%d%s%s.h", EsVersionMajor, EsVersionMinor, szCMPRSS, szRT ); + snprintf( szFileName, sizeof(szFileName), "kca_offsets_gen_R%d_%d%s%s.h", EsVersionMajor, EsVersionMinor, szCMPRSS, szRT ); TR_ASSERT( strlen(szFileName)<40, "szFileName array needs to be increased" ); auto file = fopen( szFileName, "wt" ); diff --git a/runtime/compiler/runtime/GPUHelpers.cpp b/runtime/compiler/runtime/GPUHelpers.cpp index 054fc2c22e0..387e0f8921a 100644 --- a/runtime/compiler/runtime/GPUHelpers.cpp +++ b/runtime/compiler/runtime/GPUHelpers.cpp @@ -1113,7 +1113,7 @@ static bool loadKernel(CudaInfo *cudaInfo, GpuMetaData* gpuMetaData, int kernelI static bool disableModuleCaching = feGetEnv("TR_disableCUmoduleCaching") ? true : false; char functionName[16]; // 16 is max length of decimal string of ptxSourceID - sprintf(functionName, "test%d", kernelId); + snprintf(functionName, sizeof(functionName), "test%d", kernelId); int numPtxKernels = gpuMetaData->numPtxKernels; int maxNumCachedDevices = gpuMetaData->maxNumCachedDevices; @@ -1349,8 +1349,9 @@ generatePTX(int tracing, const char *programSource, int deviceId, TR::Persistent if (detailsTrace) TR_VerboseLog::writeLine(TR_Vlog_GPU, "\tAdded NVVM module size=%d", strlen(programSource)); #define OPTIONLENGTH 6 +#define OPTIONMAXSIZE 24 - char optionStr[OPTIONLENGTH][24] = {"-opt=0", "-ftz=1", "-prec-sqrt=1", "-prec-div=1", "-fma=0", "-arch=compute_MMMMmmmm"}; + char optionStr[OPTIONLENGTH][OPTIONMAXSIZE] = {"-opt=0", "-ftz=1", "-prec-sqrt=1", "-prec-div=1", "-fma=0", "-arch=compute_MMMMmmmm"}; char *options[OPTIONLENGTH]; int optionLength = (computeMajor == 256 && computeMinor == 256) ? OPTIONLENGTH - 1 : OPTIONLENGTH; @@ -1359,7 +1360,7 @@ generatePTX(int tracing, const char *programSource, int deviceId, TR::Persistent options[i] = (char *)optionStr[i]; } - sprintf(options[OPTIONLENGTH-1], "-arch=compute_%d%d", computeMajor, computeMinor); + snprintf(options[OPTIONLENGTH-1], OPTIONMAXSIZE, "-arch=compute_%d%d", computeMajor, computeMinor); //nvvm version 1.0 works with -opt=3 //nvvm version 1.1 is untested. -opt=0 is used since it might have the same problem as version 1.2 @@ -1369,7 +1370,7 @@ generatePTX(int tracing, const char *programSource, int deviceId, TR::Persistent checkNVVMError(jitNvvmVersion(&nvvmVersionMajor, &nvvmVersionMinor), tracing); if (detailsTrace) TR_VerboseLog::writeLine(TR_Vlog_GPU, "\tNVVM Version: %d.%d", nvvmVersionMajor, nvvmVersionMinor); if ( (nvvmVersionMajor == 1) && (nvvmVersionMinor == 0) ) - sprintf(options[0], "-opt=3"); + snprintf(options[0], OPTIONMAXSIZE, "-opt=3"); if (enableMath) { diff --git a/runtime/compiler/runtime/IProfiler.cpp b/runtime/compiler/runtime/IProfiler.cpp index 1d7ee8699f8..8f8df59acdc 100644 --- a/runtime/compiler/runtime/IProfiler.cpp +++ b/runtime/compiler/runtime/IProfiler.cpp @@ -4774,7 +4774,7 @@ void TR_AggregationHT::sortByNameAndPrint(TR_J9VMBase *fe) fprintf(stderr, "Cannot allocate memory. Incomplete data will be printed.\n"); break; } - sprintf(wholeName, "%.*s.%.*s%.*s", + snprintf(wholeName, len, "%.*s.%.*s%.*s", J9UTF8_LENGTH(className), utf8Data(className), J9UTF8_LENGTH(name), utf8Data(name), J9UTF8_LENGTH(signature), utf8Data(signature)); diff --git a/runtime/compiler/runtime/JITServerROMClassHash.cpp b/runtime/compiler/runtime/JITServerROMClassHash.cpp index 637e923fce4..593d4202f4b 100644 --- a/runtime/compiler/runtime/JITServerROMClassHash.cpp +++ b/runtime/compiler/runtime/JITServerROMClassHash.cpp @@ -84,8 +84,20 @@ JITServerROMClassHash::toString(char *buffer, size_t size) const TR_ASSERT(size > sizeof(_data) * 2, "Buffer too small"); char *s = buffer; + size_t len = size; for (size_t i = 0; i < sizeof(_data); ++i) - s += sprintf(s, "%02x", ((uint8_t *)_data)[i]); + { + size_t amt = snprintf(s, len, "%02x", ((uint8_t *)_data)[i]); + if (amt <= len) + { + s += amt; + len -= amt; + } + else + { + len = 0; + } + } return buffer; } diff --git a/runtime/compiler/runtime/JitRuntime.cpp b/runtime/compiler/runtime/JitRuntime.cpp index 0287e7ff97c..89ca92d9546 100644 --- a/runtime/compiler/runtime/JitRuntime.cpp +++ b/runtime/compiler/runtime/JitRuntime.cpp @@ -927,7 +927,7 @@ void dumpAllClasses(J9VMThread *vmThread) char fileName[256]; J9Class * clazz = NULL; - sprintf(fileName, "tracer-classdump-%p.txt", vmThread); + snprintf(fileName, sizeof(fileName), "tracer-classdump-%p.txt", vmThread); if (!(fp = fopen(fileName, "at"))) { @@ -935,7 +935,7 @@ void dumpAllClasses(J9VMThread *vmThread) return; } - sprintf(fileName, "tracer-methoddump-%p.txt", vmThread); + snprintf(fileName, sizeof(fileName), "tracer-methoddump-%p.txt", vmThread); if (!(methodFP = fopen(fileName, "at"))) { @@ -943,7 +943,7 @@ void dumpAllClasses(J9VMThread *vmThread) return; } - sprintf(fileName, "tracer-fielddump-%p.txt", vmThread); + snprintf(fileName, sizeof(fileName), "tracer-fielddump-%p.txt", vmThread); if (!(fieldFP = fopen(fileName, "at"))) { @@ -951,7 +951,7 @@ void dumpAllClasses(J9VMThread *vmThread) return; } - sprintf(fileName, "tracer-staticsdump-%p.txt", vmThread); + snprintf(fileName, sizeof(fileName), "tracer-staticsdump-%p.txt", vmThread); if (!(staticsFP = fopen(fileName, "at"))) { diff --git a/runtime/compiler/runtime/MetaDataDebug.cpp b/runtime/compiler/runtime/MetaDataDebug.cpp index ccb2065ac7b..4922577d097 100644 --- a/runtime/compiler/runtime/MetaDataDebug.cpp +++ b/runtime/compiler/runtime/MetaDataDebug.cpp @@ -538,7 +538,7 @@ extern "C" void jitBytecodePrintFunction(void *userData, char *format, ...) char outputBuffer[512]; va_start(args, format); - vsprintf(outputBuffer, format, args); + vsnprintf(outputBuffer, sizeof(outputBuffer), format, args); va_end(args); TR_Debug *dbg = (TR_Debug*)userData; diff --git a/runtime/exelib/common/libhlp.c b/runtime/exelib/common/libhlp.c index 53ac3873ec2..f14cf5ef579 100644 --- a/runtime/exelib/common/libhlp.c +++ b/runtime/exelib/common/libhlp.c @@ -461,15 +461,14 @@ int main_runJavaMain(JNIEnv * env, char *mainClassName, int nameIsUTF, int java_ char * main_vmVersionString(void) { - U_32 minorVersion; - char *native = ""; + U_32 minorVersion = EsVersionMinor; char *versionStringPtr = GLOBAL_DATA(versionString); - minorVersion = EsVersionMinor; - if ((minorVersion % 10) == 0) + if (0 == (minorVersion % 10)) { minorVersion /= 10; - sprintf (versionStringPtr, "%d.%d%s,%s %s", - EsVersionMajor, minorVersion, EsExtraVersionString, native, EsBuildVersionString); + } + snprintf(versionStringPtr, sizeof(versionString), "%d.%d%s, %s", + EsVersionMajor, minorVersion, EsExtraVersionString, EsBuildVersionString); return versionStringPtr; } diff --git a/runtime/vm/JFRChunkWriter.hpp b/runtime/vm/JFRChunkWriter.hpp index e5e73b19af4..66953e25d73 100644 --- a/runtime/vm/JFRChunkWriter.hpp +++ b/runtime/vm/JFRChunkWriter.hpp @@ -222,10 +222,11 @@ class VM_JFRChunkWriter { writeIntermediateJFRChunkToFile() { UDATA written = 0; - char fileName[sizeof(intermediateChunkFileName) + 16 + sizeof(".jfr")]; - sprintf(fileName, "%s%lX.jfr", intermediateChunkFileName, _vm->jfrState.jfrChunkCount); + const size_t fileNameLen = sizeof(intermediateChunkFileName) + 16 + sizeof(".jfr"); + char fileName[fileNameLen]; + snprintf(fileName, fileNameLen, "%s%lX.jfr", intermediateChunkFileName, _vm->jfrState.jfrChunkCount); UDATA len = _bufferWriter->getSize(); - IDATA fd = j9file_open(fileName, EsOpenWrite | EsOpenCreate | EsOpenTruncate , 0666); + IDATA fd = j9file_open(fileName, EsOpenWrite | EsOpenCreate | EsOpenTruncate, 0666); if (-1 == fd) { _buildResult = FileIOError; diff --git a/runtime/vm/linearswalk.c b/runtime/vm/linearswalk.c index bfb4c69f3ce..a5444364377 100644 --- a/runtime/vm/linearswalk.c +++ b/runtime/vm/linearswalk.c @@ -32,7 +32,7 @@ -static const char * getFrameName(J9SWFrame * frame, char * name); +static const char * getFrameName(J9SWFrame * frame, char * name, size_t nameSize); static const char * getFrameTypeName(UDATA frameType); static const char * getResolveFrameType(UDATA resolveFrameType); static char * lswStrDup(J9SlotWalker * slotWalker, char * str); @@ -396,23 +396,27 @@ lswRecordSlot(J9StackWalkState * walkState, const void * slotAddress, UDATA slot static char * -lswDescribeObject(J9VMThread * vmThread, char * dataPtr, J9Class ** class, J9Object * object) +lswDescribeObject(J9VMThread * vmThread, char * dataPtr, size_t dataSize, J9Class ** class, J9Object * object) { J9JavaVM *vm = vmThread->javaVM; + size_t len = 0; if (J9VMJAVALANGCLASS_OR_NULL(vm) == *class) { /* Heap class, get the class */ *class = J9VM_J9CLASS_FROM_HEAPCLASS(vmThread, object); - dataPtr += sprintf(dataPtr, "jlC: "); + len = snprintf(dataPtr, dataSize, "jlC: "); } else { - dataPtr += sprintf(dataPtr, "obj: "); - } + len = snprintf(dataPtr, dataSize, "obj: "); + } + if (len < dataSize) { + dataPtr += len; + } return dataPtr; } static void -lswDescribeSlot(J9VMThread * vmThread, J9StackWalkState * walkState, J9SWSlot * slot, char * data, UDATA dataSize) +lswDescribeSlot(J9VMThread * vmThread, J9StackWalkState * walkState, J9SWSlot * slot, char * data, size_t dataSize) { J9Class * class; J9Object * object; @@ -427,10 +431,17 @@ lswDescribeSlot(J9VMThread * vmThread, J9StackWalkState * walkState, J9SWSlot * case LSW_TYPE_INDIRECT_O_SLOT: case LSW_TYPE_O_SLOT: if (slot->data) { - + char *newPtr = NULL; if (slot->type == LSW_TYPE_INDIRECT_O_SLOT) { + size_t len = 0; object = (J9Object *) *((UDATA *) (slot->data & ~1)); - dataPtr += sprintf(dataPtr, "%p -> ", object); + len = snprintf(dataPtr, dataSize, "%p -> ", object); + if (len <= dataSize) { + dataPtr += len; + dataSize -= len; + } else { + dataSize = 0; + } } else { object = (J9Object *) slot->data; } @@ -438,10 +449,12 @@ lswDescribeSlot(J9VMThread * vmThread, J9StackWalkState * walkState, J9SWSlot * object = (J9Object *) object; class = J9OBJECT_CLAZZ(vmThread, object); - dataPtr = lswDescribeObject(vmThread, dataPtr, &class, object); + newPtr = lswDescribeObject(vmThread, dataPtr, dataSize, &class, object); + dataSize -= newPtr - dataPtr; + dataPtr = newPtr; className = J9ROMCLASS_CLASSNAME(class->romClass); - copySize = (J9UTF8_LENGTH(className) <= dataSize) ? J9UTF8_LENGTH(className) : LSW_STRING_MAX - 1; + copySize = (J9UTF8_LENGTH(className) < dataSize) ? J9UTF8_LENGTH(className) : (dataSize > 0 ? (dataSize - 1) : 0); memcpy(dataPtr, J9UTF8_DATA(className), copySize); dataPtr[copySize] = 0; } @@ -531,13 +544,13 @@ lswPrintFrames(J9VMThread * vmThread, J9StackWalkState * walkState) J9UTF8 * className = J9ROMCLASS_CLASSNAME(UNTAGGED_METHOD_CP(method)->ramClass->romClass); lswPrintf(privatePortLibrary, "[%s%-20s%s] j9method 0x%x %s%.*s.%.*s%.*s%s\n", - CYAN, getFrameName(frame, frameName), COL_RESET, + CYAN, getFrameName(frame, frameName, sizeof(frameName)), COL_RESET, frame->method, CYAN, (U_32) J9UTF8_LENGTH(className), J9UTF8_DATA(className), (U_32) J9UTF8_LENGTH(name), J9UTF8_DATA(name), (U_32) J9UTF8_LENGTH(sig), J9UTF8_DATA(sig), COL_RESET); } else { - lswPrintf(privatePortLibrary, "[%s%-20s%s]\n", CYAN, getFrameName(frame, frameName), COL_RESET); + lswPrintf(privatePortLibrary, "[%s%-20s%s]\n", CYAN, getFrameName(frame, frameName, sizeof(frameName)), COL_RESET); } switch (frame->type) { @@ -602,12 +615,12 @@ lswSanityCheck(J9JavaVM * vm, J9StackWalkState * walkState) static const char * -getFrameName(J9SWFrame * frame, char * name) +getFrameName(J9SWFrame * frame, char * name, size_t nameSize) { if (frame->type != LSW_FRAME_TYPE_JIT_RESOLVE) { return frame->name ? frame->name : (char *) getFrameTypeName(frame->type); } else { - sprintf(name, "JIT Resolve (%s)", getResolveFrameType(frame->ftd.resolve.type)); + snprintf(name, nameSize, "JIT Resolve (%s)", getResolveFrameType(frame->ftd.resolve.type)); } return name;