Bug 1060419 - make AppendPrintf and nsPrintfCString use Printf.h draft
authorTom Tromey <tom@tromey.com>
Wed, 14 Dec 2016 09:32:21 -0700
changeset 450653 711ae2e164b9b20bf23265786171dc419a851bc7
parent 450652 101ed2022ab153f0933362b5d86f322d1cc5df83
child 450654 591160ed629e29837e5b3a124a4e893bb34ca791
push id38931
push userbmo:ttromey@mozilla.com
push dateSat, 17 Dec 2016 20:55:15 +0000
bugs1060419
milestone53.0a1
Bug 1060419 - make AppendPrintf and nsPrintfCString use Printf.h MozReview-Commit-ID: 2E8FoiNxU8L
dom/base/DOMException.cpp
dom/base/nsWindowMemoryReporter.cpp
dom/file/File.cpp
dom/indexedDB/ActorsParent.cpp
dom/indexedDB/ProfilerHelpers.h
dom/indexedDB/ReportInternalError.cpp
dom/ipc/ContentParent.cpp
dom/ipc/ProcessPriorityManager.cpp
dom/media/DecoderDoctorDiagnostics.cpp
dom/media/MediaDecoderReader.cpp
dom/media/MediaDecoderStateMachine.cpp
dom/media/MediaFormatReader.cpp
dom/media/MediaResult.h
dom/media/eme/DetailedPromise.cpp
dom/media/fmp4/MP4Demuxer.cpp
dom/media/mediasink/DecodedStream.cpp
dom/media/mediasink/VideoSink.cpp
dom/media/mediasource/MediaSourceDemuxer.cpp
dom/plugins/base/nsPluginStreamListenerPeer.cpp
dom/quota/ActorsParent.cpp
dom/workers/ScriptLoader.cpp
dom/xslt/xpath/txMozillaXPathTreeWalker.cpp
gfx/gl/GLLibraryEGL.cpp
gfx/layers/Layers.cpp
gfx/layers/LayersLogging.cpp
js/ipc/JavaScriptLogging.h
js/xpconnect/src/XPCJSContext.cpp
layout/base/PositionedEventTargeting.cpp
layout/generic/nsFrameState.cpp
layout/style/nsLayoutStylesheetCache.cpp
netwerk/cache/nsDiskCacheDeviceSQL.cpp
netwerk/protocol/http/ConnectionDiagnostics.cpp
netwerk/protocol/http/nsHttpChannel.cpp
netwerk/protocol/http/nsHttpResponseHead.cpp
toolkit/components/filepicker/nsFileView.cpp
toolkit/components/places/nsNavBookmarks.cpp
toolkit/components/places/nsNavHistory.cpp
toolkit/components/telemetry/WebrtcTelemetry.cpp
toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp
toolkit/xre/ProfileReset.cpp
tools/profiler/tasktracer/GeckoTaskTracer.h
xpcom/base/SystemMemoryReporter.cpp
xpcom/build/LateWriteChecks.cpp
xpcom/string/nsPrintfCString.h
xpcom/string/nsTSubstring.cpp
xpcom/string/nsTSubstring.h
xpcom/string/string-template-def-char.h
xpcom/string/string-template-def-unichar.h
xpcom/string/string-template-undef.h
--- a/dom/base/DOMException.cpp
+++ b/dom/base/DOMException.cpp
@@ -356,17 +356,17 @@ Exception::GetData(nsISupports** aData)
 NS_IMETHODIMP
 Exception::ToString(JSContext* aCx, nsACString& _retval)
 {
   NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED);
 
   static const char defaultMsg[] = "<no message>";
   static const char defaultLocation[] = "<unknown>";
   static const char format[] =
-"[Exception... \"%s\"  nsresult: \"0x%x (%s)\"  location: \"%s\"  data: %s]";
+"[Exception... \"%s\"  nsresult: \"0x%" PRIx32 " (%s)\"  location: \"%s\"  data: %s]";
 
   nsCString location;
 
   if (mLocation) {
     // we need to free this if it does not fail
     nsresult rv = mLocation->ToString(aCx, location);
     NS_ENSURE_SUCCESS(rv, rv);
   }
@@ -384,17 +384,17 @@ Exception::ToString(JSContext* aCx, nsAC
     if (!msg) {
       msg = defaultMsg;
     }
     resultName = "<unknown>";
   }
   const char* data = mData ? "yes" : "no";
 
   _retval.Truncate();
-  _retval.AppendPrintf(format, msg, mResult, resultName,
+  _retval.AppendPrintf(format, msg, static_cast<uint32_t>(mResult), resultName,
                        location.get(), data);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 Exception::Initialize(const nsACString& aMessage, nsresult aResult,
                       const nsACString& aName, nsIStackFrame *aLocation,
                       nsISupports *aData)
@@ -548,28 +548,28 @@ NS_IMETHODIMP
 DOMException::ToString(JSContext* aCx, nsACString& aReturn)
 {
   aReturn.Truncate();
 
   static const char defaultMsg[] = "<no message>";
   static const char defaultLocation[] = "<unknown>";
   static const char defaultName[] = "<unknown>";
   static const char format[] =
-    "[Exception... \"%s\"  code: \"%d\" nsresult: \"0x%x (%s)\"  location: \"%s\"]";
+    "[Exception... \"%s\"  code: \"%d\" nsresult: \"0x%" PRIu32 " (%s)\"  location: \"%s\"]";
 
   nsAutoCString location;
 
   if (location.IsEmpty()) {
     location = defaultLocation;
   }
 
   const char* msg = !mMessage.IsEmpty() ? mMessage.get() : defaultMsg;
   const char* resultName = !mName.IsEmpty() ? mName.get() : defaultName;
 
-  aReturn.AppendPrintf(format, msg, mCode, mResult, resultName,
+  aReturn.AppendPrintf(format, msg, mCode, static_cast<uint32_t>(mResult), resultName,
                        location.get());
 
   return NS_OK;
 }
 
 void
 DOMException::GetName(nsString& retval)
 {
--- a/dom/base/nsWindowMemoryReporter.cpp
+++ b/dom/base/nsWindowMemoryReporter.cpp
@@ -163,17 +163,17 @@ GetWindowURI(nsGlobalWindow* aWindow)
 
 static void
 AppendWindowURI(nsGlobalWindow *aWindow, nsACString& aStr, bool aAnonymize)
 {
   nsCOMPtr<nsIURI> uri = GetWindowURI(aWindow);
 
   if (uri) {
     if (aAnonymize && !aWindow->IsChromeWindow()) {
-      aStr.AppendPrintf("<anonymized-%llu>", aWindow->WindowID());
+      aStr.AppendPrintf("<anonymized-%" PRIu64 ">", aWindow->WindowID());
     } else {
       nsCString spec = uri->GetSpecOrDefault();
 
       // A hack: replace forward slashes with '\\' so they aren't
       // treated as path separators.  Users of the reporters
       // (such as about:memory) have to undo this change.
       spec.ReplaceChar('/', '\\');
 
@@ -271,17 +271,17 @@ CollectWindowReports(nsGlobalWindow *aWi
     }
   }
 
   windowPath += NS_LITERAL_CSTRING("window-objects/");
 
   if (top) {
     windowPath += NS_LITERAL_CSTRING("top(");
     AppendWindowURI(top, windowPath, aAnonymize);
-    windowPath.AppendPrintf(", id=%llu)", top->WindowID());
+    windowPath.AppendPrintf(", id=%" PRIu64 ")", top->WindowID());
 
     aTopWindowPaths->Put(aWindow->WindowID(), windowPath);
 
     windowPath += aWindow->IsFrozen() ? NS_LITERAL_CSTRING("/cached/")
                                       : NS_LITERAL_CSTRING("/active/");
   } else {
     if (aGhostWindowIDs->Contains(aWindow->WindowID())) {
       windowPath += NS_LITERAL_CSTRING("top(none)/ghost/");
--- a/dom/file/File.cpp
+++ b/dom/file/File.cpp
@@ -1164,21 +1164,21 @@ public:
         nsAutoCString digestString;
         for (size_t i = 0; i < sizeof(digest); i++) {
           digestString.AppendPrintf("%02x", digest[i]);
         }
 
         aHandleReport->Callback(
           /* process */ NS_LITERAL_CSTRING(""),
           nsPrintfCString(
-            "explicit/dom/memory-file-data/large/file(length=%llu, sha1=%s)",
+            "explicit/dom/memory-file-data/large/file(length=%" PRIu64 ", sha1=%s)",
             owner->mLength, aAnonymize ? "<anonymized>" : digestString.get()),
           KIND_HEAP, UNITS_BYTES, size,
           nsPrintfCString(
-            "Memory used to back a memory file of length %llu bytes.  The file "
+            "Memory used to back a memory file of length %" PRIu64 " bytes.  The file "
             "has a sha1 of %s.\n\n"
             "Note that the allocator may round up a memory file's length -- "
             "that is, an N-byte memory file may take up more than N bytes of "
             "memory.",
             owner->mLength, digestString.get()),
           aData);
       }
     }
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -574,19 +574,19 @@ ClampResultCode(nsresult aResultCode)
 
   switch (aResultCode) {
     case NS_ERROR_FILE_NO_DEVICE_SPACE:
       return NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR;
     case NS_ERROR_STORAGE_CONSTRAINT:
       return NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR;
     default:
 #ifdef DEBUG
-      nsPrintfCString message("Converting non-IndexedDB error code (0x%X) to "
+      nsPrintfCString message("Converting non-IndexedDB error code (0x%" PRIX32 ") to "
                               "NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR",
-                              aResultCode);
+                              static_cast<uint32_t>(aResultCode));
       NS_WARNING(message.get());
 #else
       ;
 #endif
   }
 
   IDB_REPORT_INTERNAL_ERR();
   return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
@@ -4548,17 +4548,17 @@ CreateStorageConnection(nsIFile* aDBFile
 
   if (schemaVersion != kSQLiteSchemaVersion) {
     const bool newDatabase = !schemaVersion;
 
     if (newDatabase) {
       // Set the page size first.
       if (kSQLitePageSizeOverride) {
         rv = connection->ExecuteSimpleSQL(
-          nsPrintfCString("PRAGMA page_size = %lu;", kSQLitePageSizeOverride)
+          nsPrintfCString("PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride)
         );
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
       }
 
       // We have to set the auto_vacuum mode before opening a transaction.
       rv = connection->ExecuteSimpleSQL(
@@ -4784,17 +4784,17 @@ CreateStorageConnection(nsIFile* aDBFile
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
 
         if (journalMode.EqualsLiteral("delete")) {
           // Successfully set to rollback journal mode so changing the page size
           // is possible with a VACUUM.
           rv = connection->ExecuteSimpleSQL(
-            nsPrintfCString("PRAGMA page_size = %lu;", kSQLitePageSizeOverride)
+            nsPrintfCString("PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride)
           );
           if (NS_WARN_IF(NS_FAILED(rv))) {
             return rv;
           }
 
           // We will need to VACUUM in order to change the page size.
           vacuumNeeded = true;
         } else {
@@ -13125,17 +13125,17 @@ ThreadRunnable::Run()
     return NS_OK;
   }
 
   mFirstRun = false;
 
   {
     // Scope for the thread name. Both PR_SetCurrentThreadName() and
     // profiler_register_thread() copy the string so we don't need to keep it.
-    const nsPrintfCString threadName("IndexedDB #%lu", mSerialNumber);
+    const nsPrintfCString threadName("IndexedDB #%" PRIu32, mSerialNumber);
 
     PR_SetCurrentThreadName(threadName.get());
 
 #ifdef MOZ_ENABLE_PROFILER_SPS
     profiler_register_thread(threadName.get(), &stackTopGuess);
 #endif // MOZ_ENABLE_PROFILER_SPS
   }
 
--- a/dom/indexedDB/ProfilerHelpers.h
+++ b/dom/indexedDB/ProfilerHelpers.h
@@ -272,17 +272,17 @@ public:
       eventType = nsDependentString(aDefault);
     }
 
     AppendUTF16toUTF8(eventType, *this);
     Append(kQuote);
   }
 };
 
-inline void
+inline void MOZ_FORMAT_PRINTF(2, 3)
 LoggingHelper(bool aUseProfiler, const char* aFmt, ...)
 {
   MOZ_ASSERT(IndexedDatabaseManager::GetLoggingMode() !=
                IndexedDatabaseManager::Logging_Disabled);
   MOZ_ASSERT(aFmt);
 
   mozilla::LogModule* logModule = IndexedDatabaseManager::GetLoggingModule();
   MOZ_ASSERT(logModule);
--- a/dom/indexedDB/ReportInternalError.cpp
+++ b/dom/indexedDB/ReportInternalError.cpp
@@ -22,15 +22,15 @@ ReportInternalError(const char* aFile, u
   for (const char* p = aFile; *p; ++p) {
     if (*p == '/' && *(p + 1)) {
       aFile = p + 1;
     }
   }
 
   nsContentUtils::LogSimpleConsoleError(
     NS_ConvertUTF8toUTF16(nsPrintfCString(
-                          "IndexedDB %s: %s:%lu", aStr, aFile, aLine)),
+                          "IndexedDB %s: %s:%" PRIu32, aStr, aFile, aLine)),
     "indexedDB");
 }
 
 } // namespace indexedDB
 } // namespace dom
 } // namespace mozilla
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -474,17 +474,17 @@ ContentParentsMemoryReporter::CollectRep
         channelStr = "closed channel";
       } else {
         channelStr = "open channel";
       }
       numQueuedMessages = channel->Unsound_NumQueuedMessages();
     }
 
     nsPrintfCString path("queued-ipc-messages/content-parent"
-                         "(%s, pid=%d, %s, 0x%p, refcnt=%d)",
+                         "(%s, pid=%d, %s, 0x%p, refcnt=%lu)",
                          NS_ConvertUTF16toUTF8(friendlyName).get(),
                          cp->Pid(), channelStr,
                          static_cast<nsIContentParent*>(cp), refcnt);
 
     NS_NAMED_LITERAL_CSTRING(desc,
       "The number of unset IPC messages held in this ContentParent's "
       "channel.  A large value here might indicate that we're leaking "
       "messages.  Similarly, a ContentParent object for a process that's no "
--- a/dom/ipc/ProcessPriorityManager.cpp
+++ b/dom/ipc/ProcessPriorityManager.cpp
@@ -529,17 +529,17 @@ ProcessPriorityManagerImpl::GetParticula
   uint64_t cpId = aContentParent->ChildID();
   mParticularManagers.Get(cpId, &pppm);
   if (!pppm) {
     pppm = new ParticularProcessPriorityManager(aContentParent, sFrozen);
     pppm->Init();
     mParticularManagers.Put(cpId, pppm);
 
     FireTestOnlyObserverNotification("process-created",
-      nsPrintfCString("%lld", cpId));
+      nsPrintfCString("%" PRIu64, cpId));
   }
 
   return pppm.forget();
 }
 
 void
 ProcessPriorityManagerImpl::SetProcessPriority(ContentParent* aContentParent,
                                                ProcessPriority aPriority,
@@ -1192,17 +1192,17 @@ void
 ParticularProcessPriorityManager::FireTestOnlyObserverNotification(
   const char* aTopic,
   const nsACString& aData /* = EmptyCString() */)
 {
   if (!ProcessPriorityManagerImpl::TestMode()) {
     return;
   }
 
-  nsAutoCString data(nsPrintfCString("%lld", ChildID()));
+  nsAutoCString data(nsPrintfCString("%" PRIu64, ChildID()));
   if (!aData.IsEmpty()) {
     data.Append(':');
     data.Append(aData);
   }
 
   // ProcessPriorityManagerImpl::GetSingleton() is guaranteed not to return
   // null, since ProcessPriorityManagerImpl is the only class which creates
   // ParticularProcessPriorityManagers.
--- a/dom/media/DecoderDoctorDiagnostics.cpp
+++ b/dom/media/DecoderDoctorDiagnostics.cpp
@@ -831,18 +831,18 @@ DecoderDoctorDiagnostics::GetDescription
         case eUnset:
           break;
         case eWidevineWithNoWMF:
           s += ", Widevine with no WMF";
           break;
       }
       break;
     case eEvent:
-      s = nsPrintfCString("event domain %s result=%u",
-                          EventDomainString(mEvent.mDomain), mEvent.mResult);
+      s = nsPrintfCString("event domain %s result=%" PRIu32,
+                          EventDomainString(mEvent.mDomain), static_cast<uint32_t>(mEvent.mResult));
       break;
     default:
       MOZ_ASSERT_UNREACHABLE("Unexpected DiagnosticsType");
       s = "?";
       break;
   }
   return s;
 }
--- a/dom/media/MediaDecoderReader.cpp
+++ b/dom/media/MediaDecoderReader.cpp
@@ -220,17 +220,18 @@ MediaDecoderReader::AsyncReadMetadata()
   metadata->mInfo.AssertValid();
 
   // Update the buffer ranges before resolving the metadata promise. Bug 1320258.
   UpdateBuffered();
 
   // We're not waiting for anything. If we didn't get the metadata, that's an
   // error.
   if (NS_FAILED(rv) || !metadata->mInfo.HasValidMedia()) {
-    DECODER_WARN("ReadMetadata failed, rv=%x HasValidMedia=%d", rv, metadata->mInfo.HasValidMedia());
+    DECODER_WARN("ReadMetadata failed, rv=%" PRIx32 " HasValidMedia=%d",
+                 static_cast<uint32_t>(rv), metadata->mInfo.HasValidMedia());
     return MetadataPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_METADATA_ERR, __func__);
   }
 
   // Success!
   return MetadataPromise::CreateAndResolve(metadata, __func__);
 }
 
 class ReRequestVideoWithSkipTask : public Runnable
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -3141,20 +3141,20 @@ MediaDecoderStateMachine::DumpDebugInfo(
   MOZ_ASSERT(NS_IsMainThread());
 
   // It is fine to capture a raw pointer here because MediaDecoder only call
   // this function before shutdown begins.
   nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([this] () {
     mMediaSink->DumpDebugInfo();
     mStateObj->DumpDebugInfo();
     DUMP_LOG(
-      "GetMediaTime=%lld GetClock=%lld mMediaSink=%p "
+      "GetMediaTime=%" PRId64 " GetClock=%" PRId64 " mMediaSink=%p "
       "mState=%s mPlayState=%d mSentFirstFrameLoadedEvent=%d IsPlaying=%d "
-      "mAudioStatus=%s mVideoStatus=%s mDecodedAudioEndTime=%lld mDecodedVideoEndTime=%lld "
-      "mAudioCompleted=%d mVideoCompleted=%d",
+      "mAudioStatus=%s mVideoStatus=%s mDecodedAudioEndTime=%" PRId64
+      " mDecodedVideoEndTime=%" PRId64 " mAudioCompleted=%d mVideoCompleted=%d",
       GetMediaTime(), mMediaSink->IsStarted() ? GetClock() : -1, mMediaSink.get(),
       ToStateStr(), mPlayState.Ref(), mSentFirstFrameLoadedEvent, IsPlaying(),
       AudioRequestStatus(), VideoRequestStatus(), mDecodedAudioEndTime, mDecodedVideoEndTime,
       mAudioCompleted, mVideoCompleted);
   });
 
   // Since the task is run asynchronously, it is possible other tasks get first
   // and change the object states before we print them. Therefore we want to
--- a/dom/media/MediaFormatReader.cpp
+++ b/dom/media/MediaFormatReader.cpp
@@ -2301,20 +2301,20 @@ MediaFormatReader::GetMozDebugReaderData
     audioName = mAudio.mDescription;
   }
   if (HasVideo()) {
     MonitorAutoLock mon(mVideo.mMonitor);
     videoName = mVideo.mDescription;
   }
 
   result += nsPrintfCString("audio decoder: %s\n", audioName);
-  result += nsPrintfCString("audio frames decoded: %lld\n",
+  result += nsPrintfCString("audio frames decoded: %" PRIu64 "\n",
                             mAudio.mNumSamplesOutputTotal);
   if (HasAudio()) {
-    result += nsPrintfCString("audio state: ni=%d no=%d ie=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%llu out:%llu qs=%u pending:%u waiting:%d wfk:%d sid:%u\n",
+    result += nsPrintfCString("audio state: ni=%d no=%d ie=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%" PRIu64 " out:%" PRIu64 " qs=%u pending:%u waiting:%d wfk:%d sid:%u\n",
                               NeedInput(mAudio), mAudio.HasPromise(),
                               mAudio.mDecodePending,
                               mAudio.mDemuxRequest.Exists(),
                               int(mAudio.mQueuedSamples.Length()),
                               mAudio.mTimeThreshold
                               ? mAudio.mTimeThreshold.ref().Time().ToSeconds()
                               : -1.0,
                               mAudio.mTimeThreshold
@@ -2324,21 +2324,21 @@ MediaFormatReader::GetMozDebugReaderData
                               unsigned(size_t(mAudio.mSizeOfQueue)),
                               unsigned(mAudio.mOutput.Length()),
                               mAudio.mWaitingForData, mAudio.mWaitingForKey,
                               mAudio.mLastStreamSourceID);
   }
   result += nsPrintfCString("video decoder: %s\n", videoName);
   result += nsPrintfCString("hardware video decoding: %s\n",
                             VideoIsHardwareAccelerated() ? "enabled" : "disabled");
-  result += nsPrintfCString("video frames decoded: %lld (skipped:%lld)\n",
+  result += nsPrintfCString("video frames decoded: %" PRIu64 " (skipped:%" PRIu64 ")\n",
                             mVideo.mNumSamplesOutputTotal,
                             mVideo.mNumSamplesSkippedTotal);
   if (HasVideo()) {
-    result += nsPrintfCString("video state: ni=%d no=%d ie=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%llu out:%llu qs=%u pending:%u waiting:%d wfk:%d, sid:%u\n",
+    result += nsPrintfCString("video state: ni=%d no=%d ie=%d demuxr:%d demuxq:%d tt:%f tths:%d in:%" PRIu64 " out:%" PRIu64 " qs=%u pending:%u waiting:%d wfk:%d, sid:%u\n",
                               NeedInput(mVideo), mVideo.HasPromise(),
                               mVideo.mDecodePending,
                               mVideo.mDemuxRequest.Exists(),
                               int(mVideo.mQueuedSamples.Length()),
                               mVideo.mTimeThreshold
                               ? mVideo.mTimeThreshold.ref().Time().ToSeconds()
                               : -1.0,
                               mVideo.mTimeThreshold
--- a/dom/media/MediaResult.h
+++ b/dom/media/MediaResult.h
@@ -46,20 +46,20 @@ public:
   bool operator!=(nsresult aResult) const { return aResult != mCode; }
   operator nsresult () const { return mCode; }
 
   nsCString Description() const
   {
     if (NS_SUCCEEDED(mCode)) {
       return nsCString();
     }
-    return nsPrintfCString("0x%08x: %s", mCode, mMessage.get());
+    return nsPrintfCString("0x%08" PRIx32 ": %s", static_cast<uint32_t>(mCode), mMessage.get());
   }
 
 private:
   nsresult mCode;
   nsCString mMessage;
 };
 
 #define RESULT_DETAIL(arg, ...) nsPrintfCString("%s: " arg, __func__, ##__VA_ARGS__)
 
 } // namespace mozilla
-#endif // MediaResult_h_
\ No newline at end of file
+#endif // MediaResult_h_
--- a/dom/media/eme/DetailedPromise.cpp
+++ b/dom/media/eme/DetailedPromise.cpp
@@ -37,18 +37,18 @@ DetailedPromise::~DetailedPromise()
   // unlinked, so don't have a reference to our actual JS Promise object
   // anymore.
   MaybeReportTelemetry(Failed);
 }
 
 void
 DetailedPromise::MaybeReject(nsresult aArg, const nsACString& aReason)
 {
-  nsPrintfCString msg("%s promise rejected 0x%x '%s'", mName.get(), aArg,
-                      PromiseFlatCString(aReason).get());
+  nsPrintfCString msg("%s promise rejected 0x%" PRIx32 " '%s'", mName.get(),
+                      static_cast<uint32_t>(aArg), PromiseFlatCString(aReason).get());
   EME_LOG(msg.get());
 
   MaybeReportTelemetry(Failed);
 
   LogToBrowserConsole(NS_ConvertUTF8toUTF16(msg));
 
   ErrorResult rv;
   rv.ThrowDOMException(aArg, aReason);
--- a/dom/media/fmp4/MP4Demuxer.cpp
+++ b/dom/media/fmp4/MP4Demuxer.cpp
@@ -329,27 +329,27 @@ MP4TrackDemuxer::GetNextSample()
       mp4_demuxer::H264::FrameType type =
         mp4_demuxer::H264::GetFrameType(sample);
       switch (type) {
         case mp4_demuxer::H264::FrameType::I_FRAME: MOZ_FALLTHROUGH;
         case mp4_demuxer::H264::FrameType::OTHER:
         {
           bool keyframe = type == mp4_demuxer::H264::FrameType::I_FRAME;
           if (sample->mKeyframe != keyframe) {
-            NS_WARNING(nsPrintfCString("Frame incorrectly marked as %skeyframe @ pts:%lld dur:%u dts:%lld",
+            NS_WARNING(nsPrintfCString("Frame incorrectly marked as %skeyframe @ pts:%" PRId64 " dur:%" PRId64 " dts:%" PRId64,
                                        keyframe ? "" : "non-",
                                        sample->mTime,
                                        sample->mDuration,
                                        sample->mTimecode).get());
             sample->mKeyframe = keyframe;
           }
           break;
         }
         case mp4_demuxer::H264::FrameType::INVALID:
-          NS_WARNING(nsPrintfCString("Invalid H264 frame @ pts:%lld dur:%u dts:%lld",
+          NS_WARNING(nsPrintfCString("Invalid H264 frame @ pts:%" PRId64 " dur:%" PRId64 " dts:%" PRId64,
                                      sample->mTime,
                                      sample->mDuration,
                                      sample->mTimecode).get());
           // We could reject the sample now, however demuxer errors are fatal.
           // So we keep the invalid frame, relying on the H264 decoder to
           // handle the error later.
           // TODO: make demuxer errors non-fatal.
           break;
--- a/dom/media/mediasink/DecodedStream.cpp
+++ b/dom/media/mediasink/DecodedStream.cpp
@@ -219,18 +219,18 @@ DecodedStreamData::Forget()
 {
   mListener->Forget();
 }
 
 void
 DecodedStreamData::DumpDebugInfo()
 {
   DUMP_LOG(
-    "DecodedStreamData=%p mPlaying=%d mAudioFramesWritten=%lld"
-    "mNextAudioTime=%lld mNextVideoTime=%lld mHaveSentFinish=%d"
+    "DecodedStreamData=%p mPlaying=%d mAudioFramesWritten=%" PRId64
+    "mNextAudioTime=%" PRId64 " mNextVideoTime=%" PRId64 " mHaveSentFinish=%d"
     "mHaveSentFinishAudio=%d mHaveSentFinishVideo=%d",
     this, mPlaying, mAudioFramesWritten, mNextAudioTime, mNextVideoTime,
     mHaveSentFinish, mHaveSentFinishAudio, mHaveSentFinishVideo);
 }
 
 DecodedStream::DecodedStream(AbstractThread* aOwnerThread,
                              MediaQueue<MediaData>& aAudioQueue,
                              MediaQueue<MediaData>& aVideoQueue,
--- a/dom/media/mediasink/VideoSink.cpp
+++ b/dom/media/mediasink/VideoSink.cpp
@@ -474,18 +474,18 @@ VideoSink::MaybeResolveEndPromise()
   }
 }
 
 void
 VideoSink::DumpDebugInfo()
 {
   AssertOwnerThread();
   DUMP_LOG(
-    "IsStarted=%d IsPlaying=%d, VideoQueue: finished=%d size=%d, "
-    "mVideoFrameEndTime=%lld mHasVideo=%d mVideoSinkEndRequest.Exists()=%d "
+    "IsStarted=%d IsPlaying=%d, VideoQueue: finished=%d size=%" PRIuSIZE
+    ", mVideoFrameEndTime=%" PRId64 " mHasVideo=%d mVideoSinkEndRequest.Exists()=%d "
     "mEndPromiseHolder.IsEmpty()=%d",
     IsStarted(), IsPlaying(), VideoQueue().IsFinished(), VideoQueue().GetSize(),
     mVideoFrameEndTime, mHasVideo, mVideoSinkEndRequest.Exists(), mEndPromiseHolder.IsEmpty());
   mAudioSink->DumpDebugInfo();
 }
 
 } // namespace media
 } // namespace mozilla
--- a/dom/media/mediasource/MediaSourceDemuxer.cpp
+++ b/dom/media/mediasource/MediaSourceDemuxer.cpp
@@ -248,31 +248,31 @@ MediaSourceDemuxer::~MediaSourceDemuxer(
 void
 MediaSourceDemuxer::GetMozDebugReaderData(nsAString& aString)
 {
   MonitorAutoLock mon(mMonitor);
   nsAutoCString result;
   result += nsPrintfCString("Dumping data for demuxer %p:\n", this);
   if (mAudioTrack) {
     result += nsPrintfCString("\tDumping Audio Track Buffer(%s): - mLastAudioTime: %f\n"
-                              "\t\tNumSamples:%u Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
+                              "\t\tNumSamples:%" PRId64 " Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
                               mAudioTrack->mAudioTracks.mInfo->mMimeType.get(),
                               mAudioTrack->mAudioTracks.mNextSampleTime.ToSeconds(),
                               mAudioTrack->mAudioTracks.mBuffers[0].Length(),
                               mAudioTrack->mAudioTracks.mSizeBuffer,
                               mAudioTrack->Evictable(TrackInfo::kAudioTrack),
                               mAudioTrack->mAudioTracks.mNextGetSampleIndex.valueOr(-1),
                               mAudioTrack->mAudioTracks.mNextInsertionIndex.valueOr(-1));
 
     result += nsPrintfCString("\t\tBuffered: ranges=%s\n",
                               DumpTimeRanges(mAudioTrack->SafeBuffered(TrackInfo::kAudioTrack)).get());
   }
   if (mVideoTrack) {
     result += nsPrintfCString("\tDumping Video Track Buffer(%s) - mLastVideoTime: %f\n"
-                              "\t\tNumSamples:%u Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
+                              "\t\tNumSamples:%" PRId64 " Size:%u Evictable:%u NextGetSampleIndex:%u NextInsertionIndex:%d\n",
                               mVideoTrack->mVideoTracks.mInfo->mMimeType.get(),
                               mVideoTrack->mVideoTracks.mNextSampleTime.ToSeconds(),
                               mVideoTrack->mVideoTracks.mBuffers[0].Length(),
                               mVideoTrack->mVideoTracks.mSizeBuffer,
                               mVideoTrack->Evictable(TrackInfo::kVideoTrack),
                               mVideoTrack->mVideoTracks.mNextGetSampleIndex.valueOr(-1),
                               mVideoTrack->mVideoTracks.mNextInsertionIndex.valueOr(-1));
 
--- a/dom/plugins/base/nsPluginStreamListenerPeer.cpp
+++ b/dom/plugins/base/nsPluginStreamListenerPeer.cpp
@@ -1152,28 +1152,28 @@ nsresult nsPluginStreamListenerPeer::Set
       // HTTP version: provide if available.  Defaults to empty string.
       nsCString ver;
       nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
       do_QueryInterface(channel);
       if (httpChannelInternal) {
         uint32_t major, minor;
         if (NS_SUCCEEDED(httpChannelInternal->GetResponseVersion(&major,
                                                                  &minor))) {
-          ver = nsPrintfCString("/%lu.%lu", major, minor);
+          ver = nsPrintfCString("/%" PRIu32 ".%" PRIu32, major, minor);
         }
       }
 
       // Status text: provide if available.  Defaults to "OK".
       nsCString statusText;
       if (NS_FAILED(httpChannel->GetResponseStatusText(statusText))) {
         statusText = "OK";
       }
 
       // Assemble everything and pass to listener.
-      nsPrintfCString status("HTTP%s %lu %s", ver.get(), statusNum,
+      nsPrintfCString status("HTTP%s %" PRIu32 " %s", ver.get(), statusNum,
                              statusText.get());
       static_cast<nsIHTTPHeaderListener*>(mPStreamListener)->StatusLine(status.get());
     }
 
     // Also provide all HTTP response headers to our listener.
     httpChannel->VisitResponseHeaders(this);
 
     mSeekable = false;
--- a/dom/quota/ActorsParent.cpp
+++ b/dom/quota/ActorsParent.cpp
@@ -1249,17 +1249,17 @@ ReportInternalError(const char* aFile, u
   for (const char* p = aFile; *p; ++p) {
     if (*p == '/' && *(p + 1)) {
       aFile = p + 1;
     }
   }
 
   nsContentUtils::LogSimpleConsoleError(
     NS_ConvertUTF8toUTF16(nsPrintfCString(
-                          "Quota %s: %s:%lu", aStr, aFile, aLine)),
+                          "Quota %s: %s:%" PRIu32, aStr, aFile, aLine)),
     "quota");
 }
 
 namespace {
 
 StaticRefPtr<QuotaManager> gInstance;
 bool gCreateFailed = false;
 StaticRefPtr<QuotaManager::CreateRunnable> gCreateRunnable;
@@ -4232,17 +4232,17 @@ QuotaManager::EnsureStorageIsInitialized
 
   if (storageVersion < kStorageVersion) {
     const bool newDatabase = !storageVersion;
 
     if (newDatabase) {
       // Set the page size first.
       if (kSQLitePageSizeOverride) {
         rv = connection->ExecuteSimpleSQL(
-          nsPrintfCString("PRAGMA page_size = %lu;", kSQLitePageSizeOverride)
+          nsPrintfCString("PRAGMA page_size = %" PRIu32 ";", kSQLitePageSizeOverride)
         );
         if (NS_WARN_IF(NS_FAILED(rv))) {
           return rv;
         }
       }
     }
 
     mozStorageTransaction transaction(connection, false,
--- a/dom/workers/ScriptLoader.cpp
+++ b/dom/workers/ScriptLoader.cpp
@@ -2221,19 +2221,19 @@ void ReportLoadError(ErrorResult& aRv, n
       aLoadResult = NS_ERROR_DOM_SECURITY_ERR;
       break;
 
     default:
       // For lack of anything better, go ahead and throw a NetworkError here.
       // We don't want to throw a JS exception, because for toplevel script
       // loads that would get squelched.
       aRv.ThrowDOMException(NS_ERROR_DOM_NETWORK_ERR,
-        nsPrintfCString("Failed to load worker script at %s (nsresult = 0x%x)",
+        nsPrintfCString("Failed to load worker script at %s (nsresult = 0x%" PRIx32 ")",
                         NS_ConvertUTF16toUTF8(aScriptURL).get(),
-                        aLoadResult));
+                        static_cast<uint32_t>(aLoadResult)));
       return;
   }
 
   aRv.ThrowDOMException(aLoadResult,
                         NS_LITERAL_CSTRING("Failed to load worker script at \"") +
                         NS_ConvertUTF16toUTF8(aScriptURL) +
                         NS_LITERAL_CSTRING("\""));
 }
--- a/dom/xslt/xpath/txMozillaXPathTreeWalker.cpp
+++ b/dom/xslt/xpath/txMozillaXPathTreeWalker.cpp
@@ -534,18 +534,18 @@ txXPathNodeUtils::isWhitespace(const txX
 
 /* static */
 txXPathNode*
 txXPathNodeUtils::getOwnerDocument(const txXPathNode& aNode)
 {
     return new txXPathNode(aNode.mNode->OwnerDoc());
 }
 
-const char gPrintfFmt[] = "id0x%p";
-const char gPrintfFmtAttr[] = "id0x%p-%010i";
+const char gPrintfFmt[] = "id0x%" PRIxPTR;
+const char gPrintfFmtAttr[] = "id0x%" PRIxPTR "-%010i";
 
 /* static */
 nsresult
 txXPathNodeUtils::getXSLTId(const txXPathNode& aNode,
                             const txXPathNode& aBase,
                             nsAString& aResult)
 {
     uintptr_t nodeid = ((uintptr_t)aNode.mNode) - ((uintptr_t)aBase.mNode);
--- a/gfx/gl/GLLibraryEGL.cpp
+++ b/gfx/gl/GLLibraryEGL.cpp
@@ -209,17 +209,17 @@ public:
             tokenizer.CheckChar(':') &&
             tokenizer.CheckChar(':') &&
             tokenizer.CheckWord("initialize") &&
             tokenizer.CheckWhite() &&
             tokenizer.CheckWord("error") &&
             tokenizer.CheckWhite() &&
             tokenizer.Check(Tokenizer::TOKEN_INTEGER, intToken)) {
             *mFailureId = "FAILURE_ID_ANGLE_ID_";
-            mFailureId->AppendPrintf("%i", intToken.AsInteger());
+            mFailureId->AppendPrintf("%" PRIu64, intToken.AsInteger());
         } else {
             *mFailureId = "FAILURE_ID_ANGLE_UNKNOWN";
         }
     }
 private:
     nsACString* mFailureId;
 };
 
--- a/gfx/layers/Layers.cpp
+++ b/gfx/layers/Layers.cpp
@@ -1951,30 +1951,30 @@ Layer::PrintInfo(std::stringstream& aStr
   }
   if (Is3DContextLeaf()) {
     aStream << " [is3DContextLeaf]";
   }
   if (IsScrollbarContainer()) {
     aStream << " [scrollbar]";
   }
   if (GetScrollbarDirection() == VERTICAL) {
-    aStream << nsPrintfCString(" [vscrollbar=%lld]", GetScrollbarTargetContainerId()).get();
+    aStream << nsPrintfCString(" [vscrollbar=%lu]", GetScrollbarTargetContainerId()).get();
   }
   if (GetScrollbarDirection() == HORIZONTAL) {
-    aStream << nsPrintfCString(" [hscrollbar=%lld]", GetScrollbarTargetContainerId()).get();
+    aStream << nsPrintfCString(" [hscrollbar=%lu]", GetScrollbarTargetContainerId()).get();
   }
   if (GetIsFixedPosition()) {
     LayerPoint anchor = GetFixedPositionAnchor();
-    aStream << nsPrintfCString(" [isFixedPosition scrollId=%lld sides=0x%x anchor=%s]",
+    aStream << nsPrintfCString(" [isFixedPosition scrollId=%lu sides=0x%x anchor=%s]",
                      GetFixedPositionScrollContainerId(),
                      GetFixedPositionSides(),
                      ToString(anchor).c_str()).get();
   }
   if (GetIsStickyPosition()) {
-    aStream << nsPrintfCString(" [isStickyPosition scrollId=%d outer=(%.3f,%.3f)-(%.3f,%.3f) "
+    aStream << nsPrintfCString(" [isStickyPosition scrollId=%lu outer=(%.3f,%.3f)-(%.3f,%.3f) "
                      "inner=(%.3f,%.3f)-(%.3f,%.3f)]", mStickyPositionData->mScrollId,
                      mStickyPositionData->mOuter.x, mStickyPositionData->mOuter.y,
                      mStickyPositionData->mOuter.XMost(), mStickyPositionData->mOuter.YMost(),
                      mStickyPositionData->mInner.x, mStickyPositionData->mInner.y,
                      mStickyPositionData->mInner.XMost(), mStickyPositionData->mInner.YMost()).get();
   }
   if (mMaskLayer) {
     aStream << nsPrintfCString(" [mMaskLayer=%p]", mMaskLayer.get()).get();
--- a/gfx/layers/LayersLogging.cpp
+++ b/gfx/layers/LayersLogging.cpp
@@ -185,20 +185,20 @@ AppendToString(std::stringstream& aStrea
     AppendToString(aStream, m.GetRootCompositionSize(), "] [rcs=");
     AppendToString(aStream, m.GetViewport(), "] [v=");
     aStream << nsPrintfCString("] [z=(ld=%.3f r=%.3f",
             m.GetDevPixelsPerCSSPixel().scale,
             m.GetPresShellResolution()).get();
     AppendToString(aStream, m.GetCumulativeResolution(), " cr=");
     AppendToString(aStream, m.GetZoom(), " z=");
     AppendToString(aStream, m.GetExtraResolution(), " er=");
-    aStream << nsPrintfCString(")] [u=(%d %d %lu)",
+    aStream << nsPrintfCString(")] [u=(%d %d %" PRIu32 ")",
             m.GetScrollUpdateType(), m.GetDoSmoothScroll(),
             m.GetScrollGeneration()).get();
-    aStream << nsPrintfCString("] [i=(%ld %lld %d)] }",
+    aStream << nsPrintfCString("] [i=(%" PRIu32 " %lu %d)] }",
             m.GetPresShellId(), m.GetScrollId(), m.IsRootContent()).get();
   }
   aStream << sfx;
 }
 
 void
 AppendToString(std::stringstream& aStream, const ScrollableLayerGuid& s,
                const char* pfx, const char* sfx)
--- a/js/ipc/JavaScriptLogging.h
+++ b/js/ipc/JavaScriptLogging.h
@@ -115,17 +115,17 @@ class Logging
             side = shared->isParent() ? "parent" : "child";
             ptr = js::UncheckedUnwrap(obj, true);
         } else {
             objDesc = "<cpow>";
             side = shared->isParent() ? "child" : "parent";
             ptr = nullptr;
         }
 
-        out = nsPrintfCString("<%s %s:%d:%p>", side, objDesc, id.serialNumber(), ptr);
+        out = nsPrintfCString("<%s %s:%" PRIu64 ":%p>", side, objDesc, id.serialNumber(), ptr);
     }
 
     void format(const ReceiverObj& obj, nsCString& out) {
         formatObject(true, true, obj.id, out);
     }
 
     void format(const nsTArray<JSParam>& values, nsCString& out) {
         nsAutoCString tmp;
--- a/js/xpconnect/src/XPCJSContext.cpp
+++ b/js/xpconnect/src/XPCJSContext.cpp
@@ -1920,17 +1920,17 @@ ReportZoneStats(const JS::ZoneStats& zSt
         // path, because we don't want any forward slashes in the string to
         // count as path separators.
         nsCString escapedString(notableString);
         escapedString.ReplaceSubstring("/", "\\");
 
         bool truncated = notableString.Length() < info.length;
 
         nsCString path = pathPrefix +
-            nsPrintfCString("strings/" STRING_LENGTH "%d, copies=%d, \"%s\"%s)/",
+            nsPrintfCString("strings/" STRING_LENGTH "%" PRIuSIZE ", copies=%d, \"%s\"%s)/",
                             info.length, info.numCopies, escapedString.get(),
                             truncated ? " (truncated)" : "");
 
         if (info.gcHeapLatin1 > 0) {
             REPORT_GC_BYTES(path + NS_LITERAL_CSTRING("gc-heap/latin1"),
                 info.gcHeapLatin1,
                 "Latin1 strings. " MAYBE_INLINE);
         }
--- a/layout/base/PositionedEventTargeting.cpp
+++ b/layout/base/PositionedEventTargeting.cpp
@@ -122,27 +122,23 @@ GetPrefsFor(EventClassID aEventClassID)
           "ui.mouse.radius.inputSource.touchOnly", true);
     } else {
       prefs->mTouchOnly = false;
     }
 
     nsPrintfCString repositionPref("ui.%s.radius.reposition", prefBranch);
     Preferences::AddBoolVarCache(&prefs->mRepositionEventCoords, repositionPref.get(), false);
 
-    nsPrintfCString touchClusterPref("ui.zoomedview.enabled", prefBranch);
-    Preferences::AddBoolVarCache(&prefs->mTouchClusterDetectionEnabled, touchClusterPref.get(), false);
+    Preferences::AddBoolVarCache(&prefs->mTouchClusterDetectionEnabled, "ui.zoomedview.enabled", false);
 
-    nsPrintfCString simplifiedClusterDetectionPref("ui.zoomedview.simplified", prefBranch);
-    Preferences::AddBoolVarCache(&prefs->mSimplifiedClusterDetection, simplifiedClusterDetectionPref.get(), false);
+    Preferences::AddBoolVarCache(&prefs->mSimplifiedClusterDetection, "ui.zoomedview.simplified", false);
 
-    nsPrintfCString limitReadableSizePref("ui.zoomedview.limitReadableSize", prefBranch);
-    Preferences::AddUintVarCache(&prefs->mLimitReadableSize, limitReadableSizePref.get(), 8);
+    Preferences::AddUintVarCache(&prefs->mLimitReadableSize, "ui.zoomedview.limitReadableSize", 8);
 
-    nsPrintfCString keepLimitSize("ui.zoomedview.keepLimitSize", prefBranch);
-    Preferences::AddUintVarCache(&prefs->mKeepLimitSizeForCluster, keepLimitSize.get(), 16);
+    Preferences::AddUintVarCache(&prefs->mKeepLimitSizeForCluster, "ui.zoomedview.keepLimitSize", 16);
   }
 
   return prefs;
 }
 
 static bool
 HasMouseListener(nsIContent* aContent)
 {
--- a/layout/generic/nsFrameState.cpp
+++ b/layout/generic/nsFrameState.cpp
@@ -57,17 +57,17 @@ GetFrameState(nsIFrame* aFrame)
     result.Insert(#name_, 0);                                                 \
     state = state & ~NS_FRAME_STATE_BIT(value_);                              \
   }
 #include "nsFrameStateBits.h"
 #undef FRAME_STATE_GROUP
 #undef FRAME_STATE_BIT
 
   if (state) {
-    result.AppendPrintf(" | 0x%0llx", state);
+    result.AppendPrintf(" | 0x%0lx", state);
   }
 
   return result;
 }
 
 void
 PrintFrameState(nsIFrame* aFrame)
 {
--- a/layout/style/nsLayoutStylesheetCache.cpp
+++ b/layout/style/nsLayoutStylesheetCache.cpp
@@ -776,17 +776,17 @@ nsLayoutStylesheetCache::LoadSheet(nsIUR
   }
 
 #ifdef MOZ_CRASHREPORTER
   nsZipArchive::sFileCorruptedReason = nullptr;
 #endif
   nsresult rv = loader->LoadSheetSync(aURI, aParsingMode, true, aSheet);
   if (NS_FAILED(rv)) {
     ErrorLoadingSheet(aURI,
-      nsPrintfCString("LoadSheetSync failed with error %x", rv).get(),
+      nsPrintfCString("LoadSheetSync failed with error %" PRIx32, static_cast<uint32_t>(rv)).get(),
       aFailureAction);
   }
 }
 
 /* static */ void
 nsLayoutStylesheetCache::InvalidateSheet(RefPtr<StyleSheet>* aGeckoSheet,
                                          RefPtr<StyleSheet>* aServoSheet)
 {
--- a/netwerk/cache/nsDiskCacheDeviceSQL.cpp
+++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp
@@ -2322,17 +2322,17 @@ nsOfflineCacheDevice::CreateApplicationC
   if (!NS_Escape(nsCString(group), clientID, url_Path)) {
     return NS_ERROR_OUT_OF_MEMORY;
   }
 
   PRTime now = PR_Now();
 
   // Include the timestamp to guarantee uniqueness across runs, and
   // the gNextTemporaryClientID for uniqueness within a second.
-  clientID.Append(nsPrintfCString("|%016lld|%d",
+  clientID.Append(nsPrintfCString("|%016ld|%d",
                                   now / PR_USEC_PER_SEC,
                                   gNextTemporaryClientID++));
 
   nsCOMPtr<nsIApplicationCache> cache = new nsApplicationCache(this,
                                                                group,
                                                                clientID);
   if (!cache)
     return NS_ERROR_OUT_OF_MEMORY;
--- a/netwerk/protocol/http/ConnectionDiagnostics.cpp
+++ b/netwerk/protocol/http/ConnectionDiagnostics.cpp
@@ -45,25 +45,25 @@ nsHttpConnectionMgr::OnMsgPrintDiagnosti
     nsAutoPtr<nsConnectionEntry>& ent = iter.Data();
 
     mLogData.AppendPrintf(" ent host = %s hashkey = %s\n",
                           ent->mConnInfo->Origin(), ent->mConnInfo->HashKey().get());
     mLogData.AppendPrintf("   AtActiveConnectionLimit = %d\n",
                           AtActiveConnectionLimit(ent, NS_HTTP_ALLOW_KEEPALIVE));
     mLogData.AppendPrintf("   RestrictConnections = %d\n",
                           RestrictConnections(ent));
-    mLogData.AppendPrintf("   Pending Q Length = %u\n",
+    mLogData.AppendPrintf("   Pending Q Length = %" PRIuSIZE "\n",
                           ent->mPendingQ.Length());
-    mLogData.AppendPrintf("   Active Conns Length = %u\n",
+    mLogData.AppendPrintf("   Active Conns Length = %" PRIuSIZE "\n",
                           ent->mActiveConns.Length());
-    mLogData.AppendPrintf("   Idle Conns Length = %u\n",
+    mLogData.AppendPrintf("   Idle Conns Length = %" PRIuSIZE "\n",
                           ent->mIdleConns.Length());
-    mLogData.AppendPrintf("   Half Opens Length = %u\n",
+    mLogData.AppendPrintf("   Half Opens Length = %" PRIuSIZE "\n",
                           ent->mHalfOpens.Length());
-    mLogData.AppendPrintf("   Coalescing Keys Length = %u\n",
+    mLogData.AppendPrintf("   Coalescing Keys Length = %" PRIuSIZE "\n",
                           ent->mCoalescingKeys.Length());
     mLogData.AppendPrintf("   Spdy using = %d, preferred = %d\n",
                           ent->mUsingSpdy, ent->mInPreferredHash);
     mLogData.AppendPrintf("   pipelinestate = %d penalty = %d\n",
                           ent->mPipelineState, ent->mPipeliningPenalty);
 
     uint32_t i;
     for (i = 0; i < nsAHttpTransaction::CLASS_MAX; ++i) {
@@ -136,17 +136,17 @@ nsHttpConnection::PrintDiagnostics(nsCSt
 
   log.AppendPrintf("    mTransaction = %d mSpdySession = %d\n",
                    !!mTransaction.get(), !!mSpdySession.get());
 
   PRIntervalTime now = PR_IntervalNow();
   log.AppendPrintf("    time since last read = %ums\n",
                    PR_IntervalToMilliseconds(now - mLastReadTime));
 
-  log.AppendPrintf("    max-read/read/written %lld/%lld/%lld\n",
+  log.AppendPrintf("    max-read/read/written %" PRId64 "/%" PRId64 "/%" PRId64 "\n",
                    mMaxBytesRead, mTotalBytesRead, mTotalBytesWritten);
 
   log.AppendPrintf("    rtt = %ums\n", PR_IntervalToMilliseconds(mRtt));
 
   log.AppendPrintf("    idlemonitoring = %d transactionCount=%d\n",
                    mIdleMonitoring, mHttp1xTransactionCount);
 
   log.AppendPrintf("    supports pipeline = %d classification = 0x%x\n",
@@ -168,17 +168,17 @@ Http2Session::PrintDiagnostics(nsCString
 
   log.AppendPrintf("     roomformorestreams = %d roomformoreconcurrent = %d\n",
                    RoomForMoreStreams(), RoomForMoreConcurrent());
 
   log.AppendPrintf("     transactionHashCount = %d streamIDHashCount = %d\n",
                    mStreamTransactionHash.Count(),
                    mStreamIDHash.Count());
 
-  log.AppendPrintf("     Queued Stream Size = %d\n", mQueuedStreams.GetSize());
+  log.AppendPrintf("     Queued Stream Size = %" PRIuSIZE "\n", mQueuedStreams.GetSize());
 
   PRIntervalTime now = PR_IntervalNow();
   log.AppendPrintf("     Ping Threshold = %ums\n",
                    PR_IntervalToMilliseconds(mPingThreshold));
   log.AppendPrintf("     Ping Timeout = %ums\n",
                    PR_IntervalToMilliseconds(gHttpHandler->SpdyPingTimeout()));
   log.AppendPrintf("     Idle for Any Activity (ping) = %ums\n",
                    PR_IntervalToMilliseconds(now - mLastReadEpoch));
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -3544,17 +3544,17 @@ nsHttpChannel::OpenCacheEntry(bool isHtt
         cacheEntryOpenFlags |= nsICacheStorage::OPEN_PRIORITY;
 
     // Only for backward compatibility with the old cache back end.
     // When removed, remove the flags and related code snippets.
     if (mLoadFlags & LOAD_BYPASS_LOCAL_CACHE_IF_BUSY)
         cacheEntryOpenFlags |= nsICacheStorage::OPEN_BYPASS_IF_BUSY;
 
     if (PossiblyIntercepted()) {
-        extension.Append(nsPrintfCString("u%lld", mInterceptionID));
+        extension.Append(nsPrintfCString("u%" PRIu64, mInterceptionID));
     } else if (mPostID) {
         extension.Append(nsPrintfCString("%d", mPostID));
     }
 
     // If this channel should be intercepted, we do not open a cache entry for this channel
     // until the interception process is complete and the consumer decides what to do with it.
     if (mInterceptCache == MAYBE_INTERCEPT) {
         DebugOnly<bool> exists;
--- a/netwerk/protocol/http/nsHttpResponseHead.cpp
+++ b/netwerk/protocol/http/nsHttpResponseHead.cpp
@@ -224,17 +224,17 @@ nsHttpResponseHead::SetContentLength(int
 {
     ReentrantMonitorAutoEnter monitor(mReentrantMonitor);
 
     mContentLength = len;
     if (len < 0)
         mHeaders.ClearHeader(nsHttp::Content_Length);
     else
         mHeaders.SetHeader(nsHttp::Content_Length,
-                           nsPrintfCString("%lld", len),
+                           nsPrintfCString("%" PRId64, len),
                            false,
                            nsHttpHeaderArray::eVarietyResponse);
 }
 
 void
 nsHttpResponseHead::Flatten(nsACString &buf, bool pruneTransients)
 {
     ReentrantMonitorAutoEnter monitor(mReentrantMonitor);
--- a/toolkit/components/filepicker/nsFileView.cpp
+++ b/toolkit/components/filepicker/nsFileView.cpp
@@ -735,17 +735,17 @@ nsFileView::GetCellText(int32_t aRow, ns
     aCellText = temp;
   } else {
     // file size
     if (isDirectory)
       aCellText.SetCapacity(0);
     else {
       int64_t fileSize;
       curFile->GetFileSize(&fileSize);
-      CopyUTF8toUTF16(nsPrintfCString("%lld", fileSize), aCellText);
+      CopyUTF8toUTF16(nsPrintfCString("%" PRId64, fileSize), aCellText);
     }
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsFileView::SetTree(nsITreeBoxObject* aTree)
--- a/toolkit/components/places/nsNavBookmarks.cpp
+++ b/toolkit/components/places/nsNavBookmarks.cpp
@@ -1608,17 +1608,17 @@ nsNavBookmarks::SetItemDateAdded(int64_t
   }
 
   // Note: mDBSetItemDateAdded also sets lastModified to aDateAdded.
   NOTIFY_OBSERVERS(mCanNotify, mCacheObservers, mObservers,
                    nsINavBookmarkObserver,
                    OnItemChanged(bookmark.id,
                                  NS_LITERAL_CSTRING("dateAdded"),
                                  false,
-                                 nsPrintfCString("%lld", bookmark.dateAdded),
+                                 nsPrintfCString("%ld", bookmark.dateAdded),
                                  bookmark.dateAdded,
                                  bookmark.type,
                                  bookmark.parentId,
                                  bookmark.guid,
                                  bookmark.parentGuid,
                                  EmptyCString(),
                                  aSource));
   return NS_OK;
@@ -1678,17 +1678,17 @@ nsNavBookmarks::SetItemLastModified(int6
   }
 
   // Note: mDBSetItemDateAdded also sets lastModified to aDateAdded.
   NOTIFY_OBSERVERS(mCanNotify, mCacheObservers, mObservers,
                    nsINavBookmarkObserver,
                    OnItemChanged(bookmark.id,
                                  NS_LITERAL_CSTRING("lastModified"),
                                  false,
-                                 nsPrintfCString("%lld", bookmark.lastModified),
+                                 nsPrintfCString("%ld", bookmark.lastModified),
                                  bookmark.lastModified,
                                  bookmark.type,
                                  bookmark.parentId,
                                  bookmark.guid,
                                  bookmark.parentGuid,
                                  EmptyCString(),
                                  aSource));
   return NS_OK;
--- a/toolkit/components/places/nsNavHistory.cpp
+++ b/toolkit/components/places/nsNavHistory.cpp
@@ -199,17 +199,17 @@ void GetTagsSqlFragment(int64_t aTagsFol
   else {
     // This subquery DOES NOT order tags for performance reasons.
     _sqlFragment.Assign(NS_LITERAL_CSTRING(
          "(SELECT GROUP_CONCAT(t_t.title, ',') "
            "FROM moz_bookmarks b_t "
            "JOIN moz_bookmarks t_t ON t_t.id = +b_t.parent  "
            "WHERE b_t.fk = ") + aRelation + NS_LITERAL_CSTRING(" "
            "AND t_t.parent = ") +
-           nsPrintfCString("%lld", aTagsFolder) + NS_LITERAL_CSTRING(" "
+           nsPrintfCString("%" PRId64, aTagsFolder) + NS_LITERAL_CSTRING(" "
          ")"));
   }
 
   _sqlFragment.AppendLiteral(" AS tags ");
 }
 
 /**
  * This class sets begin/end of batch updates to correspond to C++ scopes so
@@ -1537,17 +1537,17 @@ PlacesSQLQueryBuilder::SelectAsURI()
                 "FROM moz_bookmarks b "
                 // ADDITIONAL_CONDITIONS will filter on parent.
                 "WHERE b.type = 1 {ADDITIONAL_CONDITIONS} "
                 ") AS seed ON b2.fk = seed.fk "
           "JOIN moz_places h ON h.id = b2.fk "
           "LEFT OUTER JOIN moz_favicons f ON h.favicon_id = f.id "
           "WHERE NOT EXISTS ( "
             "SELECT id FROM moz_bookmarks WHERE id = b2.parent AND parent = ") +
-                nsPrintfCString("%lld", history->GetTagsFolder()) +
+                nsPrintfCString("%" PRId64, history->GetTagsFolder()) +
           NS_LITERAL_CSTRING(") "
           "ORDER BY b2.fk DESC, b2.lastModified DESC");
       }
       else {
         GetTagsSqlFragment(history->GetTagsFolder(),
                            NS_LITERAL_CSTRING("b.fk"),
                            mHasSearchTerms,
                            tagsSqlFragment);
@@ -1558,17 +1558,17 @@ PlacesSQLQueryBuilder::SelectAsURI()
             tagsSqlFragment + NS_LITERAL_CSTRING(", h.frecency, h.hidden, h.guid,"
             "null, null, null, b.guid, b.position, b.type, b.fk "
           "FROM moz_bookmarks b "
           "JOIN moz_places h ON b.fk = h.id "
           "LEFT OUTER JOIN moz_favicons f ON h.favicon_id = f.id "
           "WHERE NOT EXISTS "
               "(SELECT id FROM moz_bookmarks "
                 "WHERE id = b.parent AND parent = ") +
-                  nsPrintfCString("%lld", history->GetTagsFolder()) +
+                  nsPrintfCString("%" PRId64, history->GetTagsFolder()) +
               NS_LITERAL_CSTRING(") "
             "{ADDITIONAL_CONDITIONS}");
       }
       break;
 
     default:
       return NS_ERROR_NOT_IMPLEMENTED;
   }
@@ -1618,17 +1618,17 @@ PlacesSQLQueryBuilder::SelectAsDay()
       (uint16_t)nsINavHistoryQueryOptions::RESULTS_AS_URI :
       (uint16_t)nsINavHistoryQueryOptions::RESULTS_AS_SITE_QUERY;
 
   // beginTime will become the node's time property, we don't use endTime
   // because it could overlap, and we use time to sort containers and find
   // insert position in a result.
   mQueryString = nsPrintfCString(
      "SELECT null, "
-       "'place:type=%ld&sort=%ld&beginTime='||beginTime||'&endTime='||endTime, "
+       "'place:type=%d&sort=%d&beginTime='||beginTime||'&endTime='||endTime, "
       "dayTitle, null, null, beginTime, null, null, null, null, null, null, "
       "null, null, null "
      "FROM (", // TOUTER BEGIN
      resultType,
      sortingMode);
 
   nsNavHistory *history = nsNavHistory::GetHistoryService();
   NS_ENSURE_STATE(history);
@@ -1822,32 +1822,32 @@ PlacesSQLQueryBuilder::SelectAsSite()
     additionalConditions.AssignLiteral("{QUERY_OPTIONS_VISITS} "
                                        "{QUERY_OPTIONS_PLACES} "
                                        "{ADDITIONAL_CONDITIONS} ");
     timeConstraints.AssignLiteral("||'&beginTime='||:begin_time||"
                                     "'&endTime='||:end_time");
   }
 
   mQueryString = nsPrintfCString(
-    "SELECT null, 'place:type=%ld&sort=%ld&domain=&domainIsHost=true'%s, "
+    "SELECT null, 'place:type=%d&sort=%d&domain=&domainIsHost=true'%s, "
            ":localhost, :localhost, null, null, null, null, null, null, null, "
            "null, null, null "
     "WHERE EXISTS ( "
       "SELECT h.id FROM moz_places h "
       "%s "
       "WHERE h.hidden = 0 "
         "AND h.visit_count > 0 "
         "AND h.url_hash BETWEEN hash('file', 'prefix_lo') AND "
                                "hash('file', 'prefix_hi') "
       "%s "
       "LIMIT 1 "
     ") "
     "UNION ALL "
     "SELECT null, "
-           "'place:type=%ld&sort=%ld&domain='||host||'&domainIsHost=true'%s, "
+           "'place:type=%d&sort=%d&domain='||host||'&domainIsHost=true'%s, "
            "host, host, null, null, null, null, null, null, null, "
            "null, null, null "
     "FROM ( "
       "SELECT get_unreversed_host(h.rev_host) AS host "
       "FROM moz_places h "
       "%s "
       "WHERE h.hidden = 0 "
         "AND h.rev_host <> '.' "
@@ -1877,21 +1877,21 @@ PlacesSQLQueryBuilder::SelectAsTag()
   nsNavHistory *history = nsNavHistory::GetHistoryService();
   NS_ENSURE_STATE(history);
 
   // This allows sorting by date fields what is not possible with
   // other history queries.
   mHasDateColumns = true;
 
   mQueryString = nsPrintfCString(
-    "SELECT null, 'place:folder=' || id || '&queryType=%d&type=%ld', "
+    "SELECT null, 'place:folder=' || id || '&queryType=%d&type=%d', "
            "title, null, null, null, null, null, dateAdded, "
            "lastModified, null, null, null, null, null, null "
     "FROM moz_bookmarks "
-    "WHERE parent = %lld",
+    "WHERE parent = %" PRId64,
     nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS,
     nsINavHistoryQueryOptions::RESULTS_AS_TAG_CONTENTS,
     history->GetTagsFolder()
   );
 
   return NS_OK;
 }
 
@@ -3334,17 +3334,17 @@ nsNavHistory::QueryToSelectClause(nsNavH
       nsTArray<int64_t> subFolders;
       if (NS_FAILED(bookmarks->GetDescendantFolders(folders[i], subFolders)))
         continue;
       includeFolders.AppendElements(subFolders);
     }
 
     clause.Condition("b.parent IN(");
     for (nsTArray<int64_t>::size_type i = 0; i < includeFolders.Length(); ++i) {
-      clause.Str(nsPrintfCString("%lld", includeFolders[i]).get());
+      clause.Str(nsPrintfCString("%" PRIuSIZE, includeFolders[i]).get());
       if (i < includeFolders.Length() - 1) {
         clause.Str(",");
       }
     }
     clause.Str(")");
   }
 
   if (excludeQueries) {
--- a/toolkit/components/telemetry/WebrtcTelemetry.cpp
+++ b/toolkit/components/telemetry/WebrtcTelemetry.cpp
@@ -41,17 +41,17 @@ ReflectIceEntry(const WebrtcTelemetry::W
     return true;
 
   const uint32_t &bitmask = entry->GetKey();
 
   JS::Rooted<JSObject*> statsObj(cx, JS_NewPlainObject(cx));
   if (!statsObj)
     return false;
   if (!JS_DefineProperty(cx, obj,
-                         nsPrintfCString("%lu", bitmask).BeginReading(),
+                         nsPrintfCString("%" PRIu32, bitmask).BeginReading(),
                          statsObj, JSPROP_ENUMERATE)) {
     return false;
   }
   if (stat->successCount && !JS_DefineProperty(cx, statsObj, "successCount",
                                                stat->successCount,
                                                JSPROP_ENUMERATE)) {
     return false;
   }
--- a/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp
+++ b/toolkit/components/url-classifier/nsUrlClassifierStreamUpdater.cpp
@@ -34,17 +34,17 @@ const uint32_t MAX_FILE_SIZE = (32 * 102
 #undef LOG
 
 // MOZ_LOG=UrlClassifierStreamUpdater:5
 static mozilla::LazyLogModule gUrlClassifierStreamUpdaterLog("UrlClassifierStreamUpdater");
 #define LOG(args) TrimAndLog args
 
 // Calls nsIURLFormatter::TrimSensitiveURLs to remove sensitive
 // info from the logging message.
-static void TrimAndLog(const char* aFmt, ...)
+static MOZ_FORMAT_PRINTF(1, 2) void TrimAndLog(const char* aFmt, ...)
 {
   nsString raw;
 
   va_list ap;
   va_start(ap, aFmt);
   raw.AppendPrintf(aFmt, ap);
   va_end(ap);
 
@@ -394,17 +394,18 @@ nsUrlClassifierStreamUpdater::FetchNextR
 
 NS_IMETHODIMP
 nsUrlClassifierStreamUpdater::StreamFinished(nsresult status,
                                              uint32_t requestedDelay)
 {
   // We are a service and may not be reset with Init between calls, so reset
   // mBeganStream manually.
   mBeganStream = false;
-  LOG(("nsUrlClassifierStreamUpdater::StreamFinished [%x, %d]", status, requestedDelay));
+  LOG(("nsUrlClassifierStreamUpdater::StreamFinished [%" PRIx32 ", %d]",
+       static_cast<uint32_t>(status), requestedDelay));
   if (NS_FAILED(status) || mPendingUpdates.Length() == 0) {
     // We're done.
     LOG(("nsUrlClassifierStreamUpdater::Done [this=%p]", this));
     mDBService->FinishUpdate();
     return NS_OK;
   }
 
   // This timer is for fetching indirect updates ("forwards") from any "u:" lines
@@ -700,17 +701,17 @@ nsUrlClassifierStreamUpdater::OnDataAvai
                                               uint32_t aLength)
 {
   if (!mDBService)
     return NS_ERROR_NOT_INITIALIZED;
 
   LOG(("OnDataAvailable (%d bytes)", aLength));
 
   if (aSourceOffset > MAX_FILE_SIZE) {
-    LOG(("OnDataAvailable::Abort because exceeded the maximum file size(%lld)", aSourceOffset));
+    LOG(("OnDataAvailable::Abort because exceeded the maximum file size(%" PRIu64 ")", aSourceOffset));
     return NS_ERROR_FILE_TOO_BIG;
   }
 
   nsresult rv;
 
   // Copy the data into a nsCString
   nsCString chunk;
   rv = NS_ConsumeStream(aIStream, aLength, chunk);
@@ -725,18 +726,18 @@ nsUrlClassifierStreamUpdater::OnDataAvai
 
 NS_IMETHODIMP
 nsUrlClassifierStreamUpdater::OnStopRequest(nsIRequest *request, nsISupports* context,
                                             nsresult aStatus)
 {
   if (!mDBService)
     return NS_ERROR_NOT_INITIALIZED;
 
-  LOG(("OnStopRequest (status %x, beganStream %s, this=%p)", aStatus,
-       mBeganStream ? "true" : "false", this));
+  LOG(("OnStopRequest (status %" PRIx32 ", beganStream %s, this=%p)",
+       static_cast<uint32_t>(aStatus), mBeganStream ? "true" : "false", this));
 
   nsresult rv;
 
   if (NS_SUCCEEDED(aStatus)) {
     // Success, finish this stream and move on to the next.
     rv = mDBService->FinishStream();
   } else if (mBeganStream) {
     LOG(("OnStopRequest::Canceling update [this=%p]", this));
--- a/toolkit/xre/ProfileReset.cpp
+++ b/toolkit/xre/ProfileReset.cpp
@@ -33,17 +33,17 @@ static const char kProfileProperties[] =
 nsresult
 CreateResetProfile(nsIToolkitProfileService* aProfileSvc, nsIToolkitProfile* *aNewProfile)
 {
   MOZ_ASSERT(aProfileSvc, "NULL profile service");
 
   nsCOMPtr<nsIToolkitProfile> newProfile;
   // Make the new profile "default-" + the time in seconds since epoch for uniqueness.
   nsAutoCString newProfileName("default-");
-  newProfileName.Append(nsPrintfCString("%lld", PR_Now() / 1000));
+  newProfileName.Append(nsPrintfCString("%ld", PR_Now() / 1000));
   nsresult rv = aProfileSvc->CreateProfile(nullptr, // choose a default dir for us
                                            newProfileName,
                                            getter_AddRefs(newProfile));
   if (NS_FAILED(rv)) return rv;
 
   rv = aProfileSvc->Flush();
   if (NS_FAILED(rv)) return rv;
 
--- a/tools/profiler/tasktracer/GeckoTaskTracer.h
+++ b/tools/profiler/tasktracer/GeckoTaskTracer.h
@@ -61,17 +61,17 @@ public:
   ~AutoSourceEvent();
 };
 
 void InitTaskTracer(uint32_t aFlags = 0);
 void ShutdownTaskTracer();
 
 // Add a label to the currently running task, aFormat is the message to log,
 // followed by corresponding parameters.
-void AddLabel(const char* aFormat, ...);
+void AddLabel(const char* aFormat, ...) MOZ_FORMAT_PRINTF(1, 2);
 
 void StartLogging();
 void StopLogging();
 UniquePtr<nsTArray<nsCString>> GetLoggedData(TimeStamp aStartTime);
 
 // Returns the timestamp when Task Tracer is enabled in this process.
 PRTime GetStartTime();
 
--- a/xpcom/base/SystemMemoryReporter.cpp
+++ b/xpcom/base/SystemMemoryReporter.cpp
@@ -456,17 +456,17 @@ private:
       aName.AppendLiteral("/name(");
       aName.Append(escapedThreadName);
       aName.Append(')');
       aTag = aName;
       aName.AppendPrintf("/thread(%d)", tid);
 
       aDesc.AppendPrintf("The stack size of a non-main thread named '%s' with "
                          "thread ID %d.  This corresponds to '[stack:%d]' "
-                         "in /proc/%d/smaps.", threadName.get(), tid, tid);
+                         "in /proc/%d/smaps.", threadName.get(), tid, tid, tid);
     } else if (absPath.EqualsLiteral("[vdso]")) {
       aName.AppendLiteral("vdso");
       aDesc.AppendLiteral(
         "The virtual dynamically-linked shared object, also known as the "
         "'vsyscall page'. This is a memory region mapped by the operating "
         "system for the purpose of allowing processes to perform some "
         "privileged actions without the overhead of a syscall.");
       aTag = aName;
--- a/xpcom/build/LateWriteChecks.cpp
+++ b/xpcom/build/LateWriteChecks.cpp
@@ -49,17 +49,17 @@ class SHA1Stream
 {
 public:
   explicit SHA1Stream(FILE* aStream)
     : mFile(aStream)
   {
     MozillaRegisterDebugFILE(mFile);
   }
 
-  void Printf(const char* aFormat, ...)
+  void Printf(const char* aFormat, ...) MOZ_FORMAT_PRINTF(2, 3)
   {
     MOZ_ASSERT(mFile);
     va_list list;
     va_start(list, aFormat);
     nsAutoCString str;
     str.AppendPrintf(aFormat, list);
     va_end(list);
     mSHA1.update(str.get(), str.Length());
--- a/xpcom/string/nsPrintfCString.h
+++ b/xpcom/string/nsPrintfCString.h
@@ -20,17 +20,17 @@
  *
  * See also nsCString::AppendPrintf().
  */
 class nsPrintfCString : public nsFixedCString
 {
   typedef nsCString string_type;
 
 public:
-  explicit nsPrintfCString(const char_type* aFormat, ...)
+  explicit nsPrintfCString(const char_type* aFormat, ...) MOZ_FORMAT_PRINTF(2, 3)
     : nsFixedCString(mLocalBuffer, kLocalBufferSize, 0)
   {
     va_list ap;
     va_start(ap, aFormat);
     AppendPrintf(aFormat, ap);
     va_end(ap);
   }
 
--- a/xpcom/string/nsTSubstring.cpp
+++ b/xpcom/string/nsTSubstring.cpp
@@ -891,49 +891,62 @@ nsTSubstring_CharT::StripChars(const cha
       // Not stripped, copy this char.
       *to++ = theChar;
     }
   }
   *to = char_type(0); // add the null
   mLength = to - mData;
 }
 
-int
-nsTSubstring_CharT::AppendFunc(void* aArg, const char* aStr, uint32_t aLen)
+struct PrintfAppend_CharT : public mozilla::PrintfTarget
 {
-  self_type* self = static_cast<self_type*>(aArg);
-
-  // NSPR sends us the final null terminator even though we don't want it
-  if (aLen && aStr[aLen - 1] == '\0') {
-    --aLen;
+  PrintfAppend_CharT(nsTSubstring_CharT* aString)
+    : mString(aString)
+  {
   }
 
-  self->AppendASCII(aStr, aLen);
+  bool append(const char* aStr, size_t aLen) {
+    if (aLen == 0) {
+      return true;
+    }
 
-  return aLen;
-}
+    // Printf sends us the final null terminator even though we don't want it
+    if (aLen && aStr[aLen - 1] == '\0') {
+      --aLen;
+    }
+
+    mString->AppendASCII(aStr, aLen);
+    return true;
+  }
+
+private:
+
+  nsTSubstring_CharT* mString;
+};
 
 void
 nsTSubstring_CharT::AppendPrintf(const char* aFormat, ...)
 {
+  PrintfAppend_CharT appender(this);
   va_list ap;
   va_start(ap, aFormat);
-  uint32_t r = PR_vsxprintf(AppendFunc, this, aFormat, ap);
-  if (r == (uint32_t)-1) {
-    MOZ_CRASH("Allocation or other failure in PR_vsxprintf");
+  bool r = appender.vprint(aFormat, ap);
+  if (!r) {
+    MOZ_CRASH("Allocation or other failure in PrintfTarget::print");
   }
   va_end(ap);
 }
 
 void
 nsTSubstring_CharT::AppendPrintf(const char* aFormat, va_list aAp)
 {
-  uint32_t r = PR_vsxprintf(AppendFunc, this, aFormat, aAp);
-  if (r == (uint32_t)-1) {
-    MOZ_CRASH("Allocation or other failure in PR_vsxprintf");
+  PrintfAppend_CharT appender(this);
+  bool r = appender.vprint(aFormat, aAp);
+  if (!r) {
+    MOZ_CRASH("Allocation or other failure in PrintfTarget::print");
   }
 }
 
 /* hack to make sure we define FormatWithoutTrailingZeros only once */
 #ifdef CharT_is_PRUnichar
 // Returns the length of the formatted aDouble in aBuf.
 static int
 FormatWithoutTrailingZeros(char (&aBuf)[40], double aDouble,
--- a/xpcom/string/nsTSubstring.h
+++ b/xpcom/string/nsTSubstring.h
@@ -569,53 +569,53 @@ public:
   {
     return ReplaceASCII(mLength, 0, aData, aLength, aFallible);
   }
 
   /**
    * Append a formatted string to the current string. Uses the format
    * codes documented in prprf.h
    */
-  void AppendPrintf(const char* aFormat, ...);
+  void AppendPrintf(const char* aFormat, ...) MOZ_FORMAT_PRINTF(2, 3);
   void AppendPrintf(const char* aFormat, va_list aAp);
   void AppendInt(int32_t aInteger)
   {
-    AppendPrintf("%d", aInteger);
+    AppendPrintf("%" PRId32, aInteger);
   }
   void AppendInt(int32_t aInteger, int aRadix)
   {
-    const char* fmt = aRadix == 10 ? "%d" : aRadix == 8 ? "%o" : "%x";
-    AppendPrintf(fmt, aInteger);
+    AppendPrintf(aRadix == 10 ? "%" PRIu32 : aRadix == 8 ? "%" PRIo32 : "%" PRIx32,
+                 static_cast<uint32_t>(aInteger));
   }
   void AppendInt(uint32_t aInteger)
   {
-    AppendPrintf("%u", aInteger);
+    AppendPrintf("%" PRIu32, aInteger);
   }
   void AppendInt(uint32_t aInteger, int aRadix)
   {
-    const char* fmt = aRadix == 10 ? "%u" : aRadix == 8 ? "%o" : "%x";
-    AppendPrintf(fmt, aInteger);
+    AppendPrintf(aRadix == 10 ? "%" PRIu32 : aRadix == 8 ? "%" PRIo32 : "%" PRIx32,
+                 aInteger);
   }
   void AppendInt(int64_t aInteger)
   {
-    AppendPrintf("%lld", aInteger);
+    AppendPrintf("%" PRId64, aInteger);
   }
   void AppendInt(int64_t aInteger, int aRadix)
   {
-    const char* fmt = aRadix == 10 ? "%lld" : aRadix == 8 ? "%llo" : "%llx";
-    AppendPrintf(fmt, aInteger);
+    AppendPrintf(aRadix == 10 ? "%" PRIu64 : aRadix == 8 ? "%" PRIo64 : "%" PRIx64,
+                 static_cast<uint64_t>(aInteger));
   }
   void AppendInt(uint64_t aInteger)
   {
-    AppendPrintf("%llu", aInteger);
+    AppendPrintf("%" PRIu64, aInteger);
   }
   void AppendInt(uint64_t aInteger, int aRadix)
   {
-    const char* fmt = aRadix == 10 ? "%llu" : aRadix == 8 ? "%llo" : "%llx";
-    AppendPrintf(fmt, aInteger);
+    AppendPrintf(aRadix == 10 ? "%" PRIu64 : aRadix == 8 ? "%" PRIo64 : "%" PRIx64,
+                 aInteger);
   }
 
   /**
    * Append the given float to this string
    */
   void NS_FASTCALL AppendFloat(float aFloat);
   void NS_FASTCALL AppendFloat(double aFloat);
 public:
@@ -1036,18 +1036,16 @@ protected:
   {
     NS_ASSERTION((aDataFlags & 0xFFFF0000) == 0, "bad flags");
     mFlags = aDataFlags | (mFlags & 0xFFFF0000);
   }
 
   void NS_FASTCALL ReplaceLiteral(index_type aCutStart, size_type aCutLength,
                                   const char_type* aData, size_type aLength);
 
-  static int AppendFunc(void* aArg, const char* aStr, uint32_t aLen);
-
 public:
 
   // NOTE: this method is declared public _only_ for convenience for
   // callers who don't have access to the original nsLiteralString_CharT.
   void NS_FASTCALL AssignLiteral(const char_type* aData, size_type aLength);
 
   // mFlags is a bitwise combination of the following flags.  the meaning
   // and interpretation of these flags is an implementation detail.
--- a/xpcom/string/string-template-def-char.h
+++ b/xpcom/string/string-template-def-char.h
@@ -7,16 +7,17 @@
 
 #define CharT                               char
 #define CharT_is_char                       1
 #define nsTAString_IncompatibleCharT        nsAString
 #define nsTString_CharT                     nsCString
 #define nsTFixedString_CharT                nsFixedCString
 #define nsTAutoString_CharT                 nsAutoCString
 #define nsTSubstring_CharT                  nsACString
+#define PrintfAppend_CharT                  PrintfAppend_nsACString
 #define nsTSubstringTuple_CharT             nsCSubstringTuple
 #define nsTStringComparator_CharT           nsCStringComparator
 #define nsTDefaultStringComparator_CharT    nsDefaultCStringComparator
 #define nsTDependentString_CharT            nsDependentCString
 #define nsTDependentSubstring_CharT         nsDependentCSubstring
 #define nsTLiteralString_CharT              nsLiteralCString
 #define nsTXPIDLString_CharT                nsXPIDLCString
 #define nsTGetterCopies_CharT               nsCGetterCopies
--- a/xpcom/string/string-template-def-unichar.h
+++ b/xpcom/string/string-template-def-unichar.h
@@ -7,16 +7,17 @@
 
 #define CharT                               char16_t
 #define CharT_is_PRUnichar                  1
 #define nsTAString_IncompatibleCharT        nsACString
 #define nsTString_CharT                     nsString
 #define nsTFixedString_CharT                nsFixedString
 #define nsTAutoString_CharT                 nsAutoString
 #define nsTSubstring_CharT                  nsAString
+#define PrintfAppend_CharT                  PrintfAppend_nsAString
 #define nsTSubstringTuple_CharT             nsSubstringTuple
 #define nsTStringComparator_CharT           nsStringComparator
 #define nsTDefaultStringComparator_CharT    nsDefaultStringComparator
 #define nsTDependentString_CharT            nsDependentString
 #define nsTDependentSubstring_CharT         nsDependentSubstring
 #define nsTLiteralString_CharT              nsLiteralString
 #define nsTXPIDLString_CharT                nsXPIDLString
 #define nsTGetterCopies_CharT               nsGetterCopies
--- a/xpcom/string/string-template-undef.h
+++ b/xpcom/string/string-template-undef.h
@@ -8,16 +8,17 @@
 #undef CharT
 #undef CharT_is_PRUnichar
 #undef CharT_is_char
 #undef nsTAString_IncompatibleCharT
 #undef nsTString_CharT
 #undef nsTFixedString_CharT
 #undef nsTAutoString_CharT
 #undef nsTSubstring_CharT
+#undef PrintfAppend_CharT
 #undef nsTSubstringTuple_CharT
 #undef nsTStringComparator_CharT
 #undef nsTDefaultStringComparator_CharT
 #undef nsTDependentString_CharT
 #undef nsTDependentSubstring_CharT
 #undef nsTLiteralString_CharT
 #undef nsTXPIDLString_CharT
 #undef nsTGetterCopies_CharT