Bug 1307085-a - C-C TB: Tigher checking of InitWithFile and friends. A few checks thrown in other files as well. draft
authorISHIKAWA, Chiaki <ishikawa@yk.rim.or.jp>
Wed, 01 Jul 2020 13:26:15 +0900
changeset 89803 cdbab14b904cda22db64a2732be3fd579aed6975
parent 89802 ae79e4ab8b2948ee65d92396c4b214e8a36199af
child 89804 9d1858b545bdf345df600f25e5e3e26926e74163
push id11337
push userishikawa@yk.rim.or.jp
push dateWed, 01 Jul 2020 04:26:34 +0000
treeherdertry-comm-central@5b0c8a7b2471 [default view] [failures only]
bugs1307085
Bug 1307085-a - C-C TB: Tigher checking of InitWithFile and friends. A few checks thrown in other files as well. * * * mailnews/mapi/mapihook/src/msgMapiHook.cpp * * * nsMsgUtils
mailnews/base/search/src/nsMsgBodyHandler.cpp
mailnews/base/search/src/nsMsgSearchTerm.cpp
mailnews/base/src/nsMessenger.cpp
mailnews/base/src/nsMsgFolderCompactor.cpp
mailnews/base/util/nsMsgDBFolder.cpp
mailnews/base/util/nsMsgUtils.cpp
mailnews/base/util/nsMsgUtils.h
mailnews/db/msgdb/src/nsMsgDatabase.cpp
mailnews/imap/src/nsImapMailFolder.cpp
mailnews/local/src/nsMovemailService.cpp
mailnews/local/src/nsMsgMaildirStore.cpp
mailnews/mapi/mapihook/src/msgMapiHook.cpp
mailnews/mime/src/mimeebod.cpp
--- a/mailnews/base/search/src/nsMsgBodyHandler.cpp
+++ b/mailnews/base/search/src/nsMsgBodyHandler.cpp
@@ -126,20 +126,34 @@ int32_t nsMsgBodyHandler::GetNextLine(ns
     StripHtml(buf);
     outLength = buf.Length();
   }
 
   charset = m_partCharset;
   return outLength;
 }
 
+// xxx
+// Even if the low-level routine returns early with I/O error indication,
+// the current framework does not pay heed to such error value very explicitly
+// sometimes :-(
+//
 void nsMsgBodyHandler::OpenLocalFolder() {
   nsCOMPtr<nsIInputStream> inputStream;
   nsresult rv = m_scope->GetInputStream(m_msgHdr, getter_AddRefs(inputStream));
   // Warn and return if GetInputStream fails
+  if (NS_FAILED(rv)) {
+    // I think we need to set an initial value in error case.
+    m_fileLineStream = nullptr;
+#ifdef DEBUG
+    fprintf(stderr,
+            "(debug) nsMsgBodyHandler::OpenLocalFolder: "
+            "returning early since m_scope->GetInputStream failed.\n");
+#endif
+  }
   NS_ENSURE_SUCCESS_VOID(rv);
   m_fileLineStream = do_QueryInterface(inputStream);
 }
 
 int32_t nsMsgBodyHandler::GetNextFilterLine(nsCString& buf) {
   // m_nextHdr always points to the next header in the list....the list is NULL
   // terminated...
   uint32_t numBytesCopied = 0;
--- a/mailnews/base/search/src/nsMsgSearchTerm.cpp
+++ b/mailnews/base/search/src/nsMsgSearchTerm.cpp
@@ -1668,16 +1668,26 @@ NS_IMETHODIMP
 nsMsgSearchScopeTerm::GetInputStream(nsIMsgDBHdr* aMsgHdr,
                                      nsIInputStream** aInputStream) {
   NS_ENSURE_ARG_POINTER(aInputStream);
   NS_ENSURE_ARG_POINTER(aMsgHdr);
   NS_ENSURE_TRUE(m_folder, NS_ERROR_NULL_POINTER);
   bool reusable;
   nsresult rv = m_folder->GetMsgInputStream(aMsgHdr, &reusable,
                                             getter_AddRefs(m_inputStream));
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    fprintf(stderr,
+            "(debug) "
+            "nsMsgSearchScopeTerm::GetInputStream():m_folder->"
+            "GetMsgInputStream failed "
+            "returning rv=0x%" PRIx32 "\n",
+            static_cast<uint32_t>(rv));
+  }
+#endif
   NS_ENSURE_SUCCESS(rv, rv);
   NS_IF_ADDREF(*aInputStream = m_inputStream);
   return rv;
 }
 
 NS_IMETHODIMP nsMsgSearchScopeTerm::CloseInputStream() {
   if (m_inputStream) {
     m_inputStream->Close();
--- a/mailnews/base/src/nsMessenger.cpp
+++ b/mailnews/base/src/nsMessenger.cpp
@@ -345,16 +345,23 @@ nsresult nsMessenger::PromptIfFileExists
 
   // if we don't re-init the path for redisplay the picker will
   // show the full path, not just the file name
   nsCOMPtr<nsIFile> currentFile =
       do_CreateInstance("@mozilla.org/file/local;1");
   if (!currentFile) return NS_ERROR_FAILURE;
 
   rv = currentFile->InitWithPath(path);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    nsAutoCString cpath = NS_ConvertUTF16toUTF8(path);
+    DUMP_INITWITHPATH_PATH("nsMessenger::PromptIfFileExists", currentFile,
+                           cpath, rv);
+  }
+#endif
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoString leafName;
   currentFile->GetLeafName(leafName);
   if (!leafName.IsEmpty())
     path.Assign(leafName);  // path should be a copy of leafName
 
   nsCOMPtr<nsIFilePicker> filePicker =
@@ -951,17 +958,23 @@ nsMessenger::SaveAs(const nsACString& aU
     if (!aBypassFilePicker) {
       rv = GetSaveAsFile(aMsgFilename, &saveAsFileType,
                          getter_AddRefs(saveAsFile));
       // A null saveAsFile means that the user canceled the save as
       if (NS_FAILED(rv) || !saveAsFile) goto done;
     } else {
       saveAsFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
       rv = saveAsFile->InitWithPath(aMsgFilename);
-      if (NS_FAILED(rv)) goto done;
+      if (NS_FAILED(rv)) {
+#ifdef DEBUG
+        nsAutoCString cpath = NS_ConvertUTF16toUTF8(aMsgFilename);
+        DUMP_INITWITHPATH_PATH("nsMessenger::SaveAs", saveAsFile, cpath, rv);
+#endif
+        goto done;
+      }
       if (StringEndsWith(aMsgFilename, NS_LITERAL_STRING(TEXT_FILE_EXTENSION),
                          nsCaseInsensitiveStringComparator))
         saveAsFileType = TEXT_FILE_TYPE;
       else if ((StringEndsWith(aMsgFilename,
                                NS_LITERAL_STRING(HTML_FILE_EXTENSION),
                                nsCaseInsensitiveStringComparator)) ||
                (StringEndsWith(aMsgFilename,
                                NS_LITERAL_STRING(HTML_FILE_EXTENSION2),
@@ -1700,16 +1713,23 @@ nsSaveMsgListener::OnStopRequest(nsIRequ
                           m_saveAllAttachmentsState->m_count) {
       nsSaveAllAttachmentsState* state = m_saveAllAttachmentsState;
       uint32_t i = state->m_curIndex;
       nsString unescapedName;
       RefPtr<nsLocalFile> localFile =
           new nsLocalFile(nsTDependentString<PathChar>(state->m_directoryName));
       if (localFile->NativePath().IsEmpty()) {
         rv = NS_ERROR_FAILURE;
+#ifdef DEBUG
+        // nsDependentCString(state->m_directoryName) does not work in Aug.,
+        // 2019
+        DUMP_INITWITHNATIVEPATH_PATH(
+            "", localFile, nsTDependentString<PathChar>(state->m_directoryName),
+            rv);
+#endif
         goto done;
       }
 
       ConvertAndSanitizeFileName(state->m_displayNameArray[i], unescapedName);
       rv = localFile->Append(unescapedName);
       if (NS_FAILED(rv)) goto done;
 
       // When we are running with no warnings (typically filters and other
--- a/mailnews/base/src/nsMsgFolderCompactor.cpp
+++ b/mailnews/base/src/nsMsgFolderCompactor.cpp
@@ -32,16 +32,21 @@
 #include "nsMsgBaseCID.h"
 #include "nsIMsgFolderNotificationService.h"
 #include "nsIMsgPluggableStore.h"
 #include "nsMsgFolderCompactor.h"
 #include "nsIOutputStream.h"
 #include "nsIInputStream.h"
 #include "nsPrintfCString.h"
 
+#ifdef DEBUG
+// To include DUMP_INITWITHFILE_PATH macro
+#  include "nsMsgUtils.h"
+#endif
+
 //////////////////////////////////////////////////////////////////////////////
 // nsFolderCompactState
 //////////////////////////////////////////////////////////////////////////////
 
 NS_IMPL_ISUPPORTS(nsFolderCompactState, nsIMsgFolderCompactor,
                   nsIRequestObserver, nsIStreamListener,
                   nsICopyMessageStreamListener, nsIUrlListener)
 
@@ -322,17 +327,24 @@ nsresult nsFolderCompactState::Init(nsIM
                                     const char* baseMsgUri, nsIMsgDatabase* db,
                                     nsIFile* path, nsIMsgWindow* aMsgWindow) {
   nsresult rv;
 
   m_folder = folder;
   m_baseMessageUri = baseMsgUri;
   m_file = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  m_file->InitWithFile(path);
+
+  rv = m_file->InitWithFile(path);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    DUMP_INITWITHFILE_PATH("nsFolderCompactState::Init", m_file, path, rv);
+  }
+#endif
+  NS_ENSURE_SUCCESS(rv, rv);
 
   m_file->SetNativeLeafName(NS_LITERAL_CSTRING("nstmp"));
   // Make sure we are not crunching existing nstmp file.
   rv = m_file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600);
   NS_ENSURE_SUCCESS(rv, rv);
 
   m_window = aMsgWindow;
   m_keyArray = new nsMsgKeyArray;
@@ -437,16 +449,22 @@ nsresult nsFolderCompactState::FinishCom
   nsCOMPtr<nsIDBFolderInfo> folderInfo;
 
   // get leaf name and database name of the folder
   nsresult rv = m_folder->GetFilePath(getter_AddRefs(path));
   nsCOMPtr<nsIFile> folderPath =
       do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
   rv = folderPath->InitWithFile(path);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    DUMP_INITWITHFILE_PATH("nsFolderCompactState::FinishCompact()", folderPath,
+                           path, rv);
+  }
+#endif
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIFile> oldSummaryFile;
   rv = GetSummaryFileLocation(folderPath, getter_AddRefs(oldSummaryFile));
   NS_ENSURE_SUCCESS(rv, rv);
   nsAutoCString dbName;
   oldSummaryFile->GetNativeLeafName(dbName);
   nsAutoCString folderName;
--- a/mailnews/base/util/nsMsgDBFolder.cpp
+++ b/mailnews/base/util/nsMsgDBFolder.cpp
@@ -918,17 +918,23 @@ nsresult nsMsgDBFolder::CreateFileForDB(
   // create is unique.  now that we've got the "safe" proposedDBName,
   // we append ".msf" to see if the file exists.  if so, we make the name
   // unique and then string off the ".msf" so that we pass the right thing
   // into Open().  this isn't ideal, since this is not atomic
   // but it will make do.
   nsresult rv;
   nsCOMPtr<nsIFile> dbPath = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  dbPath->InitWithFile(path);
+  rv = dbPath->InitWithFile(path);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    DUMP_INITWITHFILE_PATH("nsMsgDBFolder::CreateFileForDB", dbPath, path, rv);
+  }
+#endif
+  NS_ENSURE_SUCCESS(rv, rv);
   proposedDBName.AppendLiteral(SUMMARY_SUFFIX);
   dbPath->Append(proposedDBName);
   bool exists;
   dbPath->Exists(&exists);
   if (exists) {
     rv = dbPath->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600);
     NS_ENSURE_SUCCESS(rv, rv);
     dbPath->GetLeafName(proposedDBName);
@@ -1278,45 +1284,89 @@ NS_IMETHODIMP nsMsgDBFolder::ReadFromFol
 #endif
   mInitializedFromCache = true;
   return rv;
 }
 
 nsresult nsMsgDBFolder::GetFolderCacheKey(
     nsIFile** aFile, bool createDBIfMissing /* = false */) {
   nsresult rv;
+  nsresult rv2;
   nsCOMPtr<nsIFile> path;
   rv = GetFilePath(getter_AddRefs(path));
 
   // now we put a new file  in aFile, because we're going to change it.
   nsCOMPtr<nsIFile> dbPath = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (dbPath) {
-    dbPath->InitWithFile(path);
+    rv = dbPath->InitWithFile(path);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsMsgDBFolder::GetFolderCacheKey", dbPath, path,
+                             rv);
+    }
+#endif
+
     // if not a server, we need to convert to a db Path with .msf on the end
     bool isServer = false;
-    GetIsServer(&isServer);
+    rv2 = GetIsServer(&isServer);
+
+#ifdef DEBUG
+    if (NS_FAILED(rv2)) {
+      fprintf(stderr, "(debug) GetIsServer failed. rv = 0x%" PRIx32 "\n",
+              static_cast<uint32_t>(rv2));
+    }
+#endif
 
     // if it's a server, we don't need the .msf appended to the name
-    if (!isServer) {
+    if (NS_SUCCEEDED(rv2) && !isServer) {
       nsCOMPtr<nsIFile> summaryName;
       rv = GetSummaryFileLocation(dbPath, getter_AddRefs(summaryName));
-      dbPath->InitWithFile(summaryName);
-
-      // create the .msf file
+
+      // The error code handling here looks like  a mess.
+
+      // Note that when we don't have an existing DB,
+      // some operations will fail, and then if the DB file
+      // is not found in the end, then we need to create a file.
+
+      // However, note that rv from the above line is returned at the
+      // end of this function body.  But what about the errors of
+      // InitWithFile() or the failure of dbPath->Create() (the
+      // latter was NOT checked AT ALL. Sigh ....)
+
+      // We probably do not want to run InitWithFile when GetSummaryFileLocation
+      // above fails to avoid passing null/empty summaryName.
+
+      if (NS_SUCCEEDED(rv)) {
+        nsresult rv4 = dbPath->InitWithFile(summaryName);
+        if (NS_FAILED(rv4)) {
+#ifdef DEBUG
+          DUMP_INITWITHFILE_PATH("nsMsgDBFolder::GetFolderCacheKey", dbPath,
+                                 summaryName, rv4);
+#endif
+        }
+      }
+      // create the .msf file if it does not exist yet after the above
+      // processing.
+
       // see bug #244217 for details
       bool exists;
       if (createDBIfMissing && NS_SUCCEEDED(dbPath->Exists(&exists)) &&
           !exists) {
         rv = dbPath->Create(nsIFile::NORMAL_FILE_TYPE, 0644);
         NS_ENSURE_SUCCESS(rv, rv);
       }
     }
+  } else {
+    // XXX should we return before dbPath.forget(aFile)?
+    // Actually, here dbPath is nullptr. So we SHOULD return here.
+    return NS_ERROR_UNEXPECTED;
   }
+
   dbPath.forget(aFile);
   return rv;
 }
 
 nsresult nsMsgDBFolder::FlushToFolderCache() {
   nsresult rv;
   nsCOMPtr<nsIMsgAccountManager> accountManager =
       do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv);
@@ -3016,16 +3066,24 @@ nsresult nsMsgDBFolder::parseURI(bool ne
         if (NS_FAILED(rv)) {
           mPath = nullptr;
           return rv;
         }
       }
       mPath = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
       NS_ENSURE_SUCCESS(rv, rv);
       mPath->InitWithFile(serverPath);
+      rv = mPath->InitWithFile(serverPath);
+#ifdef DEBUG
+      if (NS_FAILED(rv)) {
+        DUMP_INITWITHFILE_PATH("nsMsgDBFolder::parseURI", mPath, serverPath,
+                               rv);
+      }
+#endif
+      NS_ENSURE_SUCCESS(rv, rv);
     }
     // URI is completely parsed when we've attempted to get the server
     mHaveParsedURI = true;
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -4333,35 +4391,66 @@ nsMsgDBFolder::SetFilePath(nsIFile* aFil
 NS_IMETHODIMP
 nsMsgDBFolder::GetFilePath(nsIFile** aFile) {
   NS_ENSURE_ARG_POINTER(aFile);
   nsresult rv;
   // make a new nsIFile object in case the caller
   // alters the underlying file object.
   nsCOMPtr<nsIFile> file = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  if (!mPath) parseURI(true);
+
+  if (!mPath) {
+    rv = parseURI(true);
+    if (NS_FAILED(rv)) {
+#ifdef DEBUG
+      fprintf(stderr,
+              "(debug) nsMsgDBFolder::GetFilePath: parseURI(true) failed. "
+              "rv=0x%" PRIx32 "\n",
+              static_cast<uint32_t>(rv));
+#endif
+      // We ought to retun here to avoid passing empty mPath to InitWithFile
+      // below.
+      return rv;
+    }
+  }
+
   rv = file->InitWithFile(mPath);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    DUMP_INITWITHFILE_PATH("nsMsgDBFolder::GetFilePath", file, mPath, rv);
+  }
+#endif
+  // XXX: should we perform error return before file.forget(aFile) below???
+  NS_ENSURE_SUCCESS(rv, rv);
+
   file.forget(aFile);
   return NS_OK;
 }
 
 NS_IMETHODIMP nsMsgDBFolder::GetSummaryFile(nsIFile** aSummaryFile) {
   NS_ENSURE_ARG_POINTER(aSummaryFile);
 
   nsresult rv;
   nsCOMPtr<nsIFile> newSummaryLocation =
       do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIFile> pathFile;
   rv = GetFilePath(getter_AddRefs(pathFile));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  newSummaryLocation->InitWithFile(pathFile);
+  rv = newSummaryLocation->InitWithFile(pathFile);
+  if (NS_FAILED(rv)) {
+#ifdef DEBUG
+    DUMP_INITWITHFILE_PATH("nsMsgDBFolder::GetSummaryFile", newSummaryLocation,
+                           pathFile, rv);
+#endif
+    return rv;
+  }
+
 
   nsString fileName;
   rv = newSummaryLocation->GetLeafName(fileName);
   NS_ENSURE_SUCCESS(rv, rv);
 
   fileName.AppendLiteral(SUMMARY_SUFFIX);
   rv = newSummaryLocation->SetLeafName(fileName);
   NS_ENSURE_SUCCESS(rv, rv);
--- a/mailnews/base/util/nsMsgUtils.cpp
+++ b/mailnews/base/util/nsMsgUtils.cpp
@@ -1363,17 +1363,24 @@ void Seconds2PRTime(uint32_t seconds, PR
 
 nsresult GetSummaryFileLocation(nsIFile* fileLocation,
                                 nsIFile** summaryLocation) {
   nsresult rv;
   nsCOMPtr<nsIFile> newSummaryLocation =
       do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  newSummaryLocation->InitWithFile(fileLocation);
+  rv = newSummaryLocation->InitWithFile(fileLocation);
+  if (NS_FAILED(rv)) {
+#ifdef DEBUG
+    DUMP_INITWITHFILE_PATH("GetSummaryFileLocation", newSummaryLocation,
+                           fileLocation, rv);
+#endif
+    return rv;
+  }
   nsString fileName;
 
   rv = newSummaryLocation->GetLeafName(fileName);
   if (NS_FAILED(rv)) return rv;
 
   fileName.AppendLiteral(SUMMARY_SUFFIX);
   rv = newSummaryLocation->SetLeafName(fileName);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -1429,27 +1436,39 @@ nsresult MsgCleanupTempFiles(const char*
   } while (exists && ++index < 10000);
   return NS_OK;
 }
 
 nsresult MsgGetFileStream(nsIFile* file, nsIOutputStream** fileStream) {
   nsMsgFileStream* newFileStream = new nsMsgFileStream;
   NS_ENSURE_TRUE(newFileStream, NS_ERROR_OUT_OF_MEMORY);
   nsresult rv = newFileStream->InitWithFile(file);
+  if (NS_FAILED(rv)) {
+#ifdef DEBUG
+    DUMP_INITWITHFILE_PATH("MsgGetFileStream", newFileStream, file, rv);
+#endif
+  }
   if (NS_SUCCEEDED(rv))
     rv = newFileStream->QueryInterface(NS_GET_IID(nsIOutputStream),
                                        (void**)fileStream);
   return rv;
 }
 
 nsresult MsgReopenFileStream(nsIFile* file, nsIInputStream* fileStream) {
   nsMsgFileStream* msgFileStream = static_cast<nsMsgFileStream*>(fileStream);
-  if (msgFileStream)
-    return msgFileStream->InitWithFile(file);
-  else
+  if (msgFileStream) {
+    nsresult rv;
+    rv = msgFileStream->InitWithFile(file);
+    if (NS_FAILED(rv)) {
+#ifdef DEBUG
+      DUMP_INITWITHFILE_PATH("MsgReopenFileStream", msgFileStream, file, rv);
+#endif
+    }
+    return rv;
+  } else
     return NS_ERROR_FAILURE;
 }
 
 nsresult MsgNewBufferedFileOutputStream(nsIOutputStream** aResult,
                                         nsIFile* aFile, int32_t aIOFlags,
                                         int32_t aPerm) {
   nsCOMPtr<nsIOutputStream> stream;
   nsresult rv = NS_NewLocalFileOutputStream(getter_AddRefs(stream), aFile,
--- a/mailnews/base/util/nsMsgUtils.h
+++ b/mailnews/base/util/nsMsgUtils.h
@@ -407,16 +407,74 @@ void MsgRemoveQueryPart(nsCString& aSpec
     return NS_OK;                                 \
   }                                               \
   NS_IMETHODIMP clazz::Set##attr(type aValue) {   \
     member = aValue;                              \
     return NS_OK;                                 \
   }
 
 /**
+ * Helper macro for printing debug output for failure associated with
+ * InitWithFile()
+ *
+ * Useful tracing strange file-related errors in the log produced on tryserver.
+ *
+ * Usage:
+ *    nsresult functionA () {
+ *    ....
+ *    rv = ptr->InitWithFile(filePath);
+ *    if (NS_FAILED(rv)) {
+ *    #ifdef DEBUG
+ *       DUMP_INITIWITHFILE_PATH("functionA", ptr, filePath, rv) ;
+ *    #endif
+ *    }
+ *
+ */
+
+#define DUMP_INITWITHFILE_PATH(func, p1, p2, result)                           \
+  {                                                                            \
+    nsAutoCString nativePath;                                                  \
+    fprintf(stderr, "(debug) %s: %s->InitWithFile(%s) failed: rv = 0x%08x\n",  \
+            func, #p1, #p2, (unsigned int)(result));                           \
+    if (p2) {                                                                  \
+      nsresult rv2 = p2->GetNativeTarget(nativePath);                          \
+      if (NS_FAILED(rv2))                                                      \
+        fprintf(stderr, "(debug) %s: %s->GetNativeTarget failed.rv2=0x%08x\n", \
+                func, #p2, (unsigned int)(rv2));                               \
+      else                                                                     \
+        fprintf(stderr, "(debug) %s: %s->nativePath=<<%s>>\n", func, #p2,      \
+                nativePath.Data());                                            \
+    } else                                                                     \
+      fprintf(stderr, "(debug) %s: %s was NULL\n", func, #p2);                 \
+  }
+
+/* cast on p2.Data() is tricky. MSVC's handling is done by class char16ptr_t
+ * that permits casting to a few data types. (char*) is NOT one of them. This is
+ * also true under OSX. I could have used %S explicitly if there were no files
+ * that passed (char *) like data. Unfortunately, nsMessanger.cpp did, and thus
+ * used (void *) cast.
+ */
+#define DUMP_INITWITHPATH_PATH(func, p1, p2, result)                          \
+  {                                                                           \
+    fprintf(stderr, "(debug) %s: %s->InitWithPath(%s) failed: rv = 0x%08x\n", \
+            func, #p1, #p2, (unsigned int)(result));                          \
+    fprintf(stderr, "(debug) %s: %s=<<%s>>\n", func, #p2,                     \
+            (char *)((void *)p2.Data()));                                     \
+  }
+
+#define DUMP_INITWITHNATIVEPATH_PATH(func, p1, p2, result)                  \
+  {                                                                         \
+    fprintf(stderr,                                                         \
+            "(debug) %s: %s->InitWithNativePath(%s) failed: rv = 0x%08x\n", \
+            func, #p1, #p2, (unsigned int)(result));                        \
+    fprintf(stderr, "(debug) %s: %s=<<%s>>\n", func, #p2,                   \
+            (char *)((void *)p2.Data()));                                   \
+  }
+
+/**
  * Macro and helper function for reporting an error, warning or
  * informational message to the Error Console
  *
  * This will require the inclusion of the following files in the source file
  * #include "nsIScriptError.h"
  * #include "nsIConsoleService.h"
  *
  */
--- a/mailnews/db/msgdb/src/nsMsgDatabase.cpp
+++ b/mailnews/db/msgdb/src/nsMsgDatabase.cpp
@@ -505,20 +505,32 @@ NS_IMETHODIMP nsMsgDatabase::SetLastUseT
 
 NS_IMETHODIMP nsMsgDatabase::GetDatabaseSize(int64_t* _retval) {
   NS_ENSURE_ARG_POINTER(_retval);
 
   nsresult rv;
   bool exists;
   NS_ENSURE_TRUE(m_dbFile, NS_ERROR_NULL_POINTER);
   rv = m_dbFile->Exists(&exists);
+
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    fprintf(stderr, "{debug}: m_dbFile->Exists(&exists) failed.\n");
+  }
+#endif
+
   if (NS_SUCCEEDED(rv)) {
-    if (exists)
+    if (exists) {
       rv = m_dbFile->GetFileSize(_retval);
-    else
+#ifdef DEBUG
+      if (NS_FAILED(rv)) {
+        fprintf(stderr, "{debug}: m_dbFile->GetFileSize(_retval) failed.\n");
+      }
+#endif
+    } else
       *_retval = 0;
   }
 
   return rv;
 }
 
 NS_IMETHODIMP nsMsgDatabase::ClearCachedHdrs() {
   ClearCachedObjects(false);
--- a/mailnews/imap/src/nsImapMailFolder.cpp
+++ b/mailnews/imap/src/nsImapMailFolder.cpp
@@ -450,20 +450,40 @@ nsresult nsImapMailFolder::CreateSubFold
 
     // OK, here we need to get the online name from the folder cache if we can.
     // If we can, use that to create the sub-folder
     nsCOMPtr<nsIFile> curFolder =
         do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     nsCOMPtr<nsIFile> dbFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
-    dbFile->InitWithFile(currentFolderPath);
-    curFolder->InitWithFile(currentFolderPath);
+
+
+    rv = dbFile->InitWithFile(currentFolderPath);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsImapMailFolder::CreateSubFolders", dbFile,
+                             currentFolderPath, rv);
+    }
+#endif
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    rv = curFolder->InitWithFile(currentFolderPath);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsImapMailFolder::CreateSubFolders", curFolder,
+                             currentFolderPath, rv);
+    }
+#endif
+    NS_ENSURE_SUCCESS(rv, rv);
+
     // don't strip off the .msf in currentFolderPath.
-    currentFolderPath->SetLeafName(currentFolderNameStr);
+    rv = currentFolderPath->SetLeafName(currentFolderNameStr);
+    NS_ENSURE_SUCCESS(rv, rv);
+
     currentFolderDBNameStr = currentFolderNameStr;
     nsAutoString utf7LeafName = currentFolderNameStr;
 
     if (curFolder) {
       nsCOMPtr<nsIMsgFolderCacheElement> cacheElement;
       rv = GetFolderCacheElemFromFile(dbFile, getter_AddRefs(cacheElement));
       if (NS_SUCCEEDED(rv) && cacheElement) {
         nsCString onlineFullUtf7Name;
@@ -494,17 +514,26 @@ nsresult nsImapMailFolder::CreateSubFold
           if (leafPos > 0) utf7LeafName.Cut(0, leafPos + 1);
         }
       }
     }
     // make the imap folder remember the file spec it was created with.
     nsCOMPtr<nsIFile> msfFilePath =
         do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
-    msfFilePath->InitWithFile(currentFolderPath);
+    rv = msfFilePath->InitWithFile(currentFolderPath);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsImapMailFolder::CreateSubFolders", msfFilePath,
+                             currentFolderPath, rv);
+    }
+#endif
+    // It is best to bail out if error.
+    NS_ENSURE_SUCCESS(rv, rv);
+
     if (NS_SUCCEEDED(rv) && msfFilePath) {
       // leaf name is the db name w/o .msf (nsShouldIgnoreFile strips it off)
       // so this trims the .msf off the file spec.
       msfFilePath->SetLeafName(currentFolderDBNameStr);
     }
     // use the utf7 name as the uri for the folder.
     nsCOMPtr<nsIMsgFolder> child;
     AddSubfolderWithPath(utf7LeafName, msfFilePath, getter_AddRefs(child));
@@ -8420,16 +8449,25 @@ NS_IMETHODIMP nsImapMailFolder::RenameSu
     oldPathFile->GetNativeLeafName(oldLeafName);
     newParentPathFile->AppendNative(oldLeafName);
 
     nsCOMPtr<nsIFile> newPathFile =
         do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     newPathFile->InitWithFile(newParentPathFile);
 
+    rv = newPathFile->InitWithFile(newParentPathFile);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsImapMailFolder::RenameSubFolders", newPathFile,
+                             newParentPathFile, rv);
+    }
+#endif
+    NS_ENSURE_SUCCESS(rv, rv);
+
     nsCOMPtr<nsIFile> dbFilePath = newPathFile;
 
     nsCOMPtr<nsIMsgFolder> child;
 
     nsString folderName;
     rv = msgFolder->GetName(folderName);
     if (folderName.IsEmpty() || NS_FAILED(rv)) return rv;
 
--- a/mailnews/local/src/nsMovemailService.cpp
+++ b/mailnews/local/src/nsMovemailService.cpp
@@ -328,28 +328,39 @@ static nsresult LocateSpoolFile(nsACStri
   NS_ENSURE_SUCCESS(rv, rv);
 
   char* mailEnv = PR_GetEnv("MAIL");
   char* userEnv = PR_GetEnv("USER");
   if (!userEnv) userEnv = PR_GetEnv("USERNAME");
 
   if (mailEnv) {
     rv = spoolFile->InitWithNativePath(nsDependentCString(mailEnv));
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHNATIVEPATH_PATH("LocateSpoolFile", spoolFile,
+                                   nsDependentCString(mailEnv), rv);
+    }
+#endif
     NS_ENSURE_SUCCESS(rv, rv);
     rv = spoolFile->IsFile(&isFile);
     if (NS_SUCCEEDED(rv) && isFile) spoolPath = mailEnv;
   } else if (userEnv) {
     // Try to build the mailbox path from the username and a number
     // of guessed spool directory paths.
     nsAutoCString tmpPath;
     uint32_t i;
     for (i = 0; i < NUM_DEFAULT_SPOOL_PATHS; i++) {
       tmpPath = gDefaultSpoolPaths[i];
       tmpPath += userEnv;
       rv = spoolFile->InitWithNativePath(tmpPath);
+#ifdef DEBUG
+      if (NS_FAILED(rv)) {
+        DUMP_INITWITHNATIVEPATH_PATH("LocateSpoolFile", spoolFile, tmpPath, rv);
+      }
+#endif
       NS_ENSURE_SUCCESS(rv, rv);
       rv = spoolFile->IsFile(&isFile);
       if (NS_SUCCEEDED(rv) && isFile) {
         spoolPath = tmpPath;
         break;
       }
     }
   }
--- a/mailnews/local/src/nsMsgMaildirStore.cpp
+++ b/mailnews/local/src/nsMsgMaildirStore.cpp
@@ -163,17 +163,23 @@ nsresult nsMsgMaildirStore::CreateMaildi
     NS_WARNING("Could not create root directory for message folder");
     return rv;
   }
 
   // Create tmp, cur leaves
   nsCOMPtr<nsIFile> leaf(do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  leaf->InitWithFile(path);
+  rv = leaf->InitWithFile(path);
+#ifdef DEBUG
+  if (NS_FAILED(rv)) {
+    DUMP_INITWITHFILE_PATH("nsMsgMaildirStore::CreateMaildir", leaf, path, rv);
+  }
+#endif
+  NS_ENSURE_SUCCESS(rv, rv);
 
   leaf->AppendNative(NS_LITERAL_CSTRING("tmp"));
   rv = leaf->Create(nsIFile::DIRECTORY_TYPE, 0700);
   if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS) {
     NS_WARNING("Could not create tmp directory for message folder");
     return rv;
   }
 
@@ -359,16 +365,22 @@ NS_IMETHODIMP nsMsgMaildirStore::RenameF
   // old sbd directory
   nsCOMPtr<nsIFile> sbdPathFile;
   uint32_t numChildren;
   aFolder->GetNumSubFolders(&numChildren);
   if (numChildren > 0) {
     sbdPathFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = sbdPathFile->InitWithFile(oldPathFile);
+#ifdef DEBUG
+    if (NS_FAILED(rv)) {
+      DUMP_INITWITHFILE_PATH("nsMsgMaildirStore::RenameFolder", sbdPathFile,
+                             oldPathFile, rv);
+    }
+#endif
     NS_ENSURE_SUCCESS(rv, rv);
     GetDirectoryForFolder(sbdPathFile);
   }
 
   // old summary
   nsCOMPtr<nsIFile> oldSummaryFile;
   rv = aFolder->GetSummaryFile(getter_AddRefs(oldSummaryFile));
   NS_ENSURE_SUCCESS(rv, rv);
--- a/mailnews/mapi/mapihook/src/msgMapiHook.cpp
+++ b/mailnews/mapi/mapihook/src/msgMapiHook.cpp
@@ -1,8 +1,9 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #define MAPI_STARTUP_ARG "/MAPIStartUp"
 
 #include <mapidefs.h>
 #include <mapi.h>
@@ -360,22 +361,40 @@ nsresult nsMapiHook::HandleAttachments(n
   nsCOMPtr<nsIFile> pFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   if (NS_FAILED(rv) || (!pFile)) return rv;
   nsCOMPtr<nsIFile> pTempDir = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
   if (NS_FAILED(rv) || (!pTempDir)) return rv;
 
   for (int i = 0; i < aFileCount; i++) {
     if (aFiles[i].lpszPathName) {
       // check if attachment exists
-      if (!aIsUTF8)
-        pFile->InitWithNativePath(nsDependentCString(aFiles[i].lpszPathName));
-      else
-        pFile->InitWithPath(NS_ConvertUTF8toUTF16(aFiles[i].lpszPathName));
+      if (!aIsUTF8) {
+        rv = pFile->InitWithNativePath(
+            nsDependentCString(aFiles[i].lpszPathName));
+        if (NS_FAILED(rv)) {
+#ifdef DEBUG
+          DUMP_INITWITHNATIVEPATH_PATH(
+            "nsMapiHook::HandleAttachments", pFile,
+            nsDependentCString((const char *)aFiles[i].lpszPathName), rv);
+#endif
+          return rv;
+        }
+      } else {
+        rv = pFile->InitWithPath(NS_ConvertUTF8toUTF16(aFiles[i].lpszPathName));
+        if (NS_FAILED(rv)) {
+#ifdef DEBUG
+          DUMP_INITWITHNATIVEPATH_PATH(
+              "nsMapiHook::HandleAttachments", pFile,
+              nsDependentCString((const char *)aFiles[i].lpszPathName), rv);
+#endif
+          return rv;
+        }
+      }
 
-      bool bExist;
+      bool bExist = false;
       rv = pFile->Exists(&bExist);
       MOZ_LOG(
           MAPI, mozilla::LogLevel::Debug,
           ("nsMapiHook::HandleAttachments: filename: %s path: %s exists = %s\n",
            (const char*)aFiles[i].lpszFileName,
            (const char*)aFiles[i].lpszPathName, bExist ? "true" : "false"));
       if (NS_FAILED(rv) || (!bExist))
         return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
@@ -432,16 +451,24 @@ nsresult nsMapiHook::HandleAttachments(n
         NS_ENSURE_SUCCESS(rv, rv);
         pTempFile->Remove(false);  // remove so we can copy over it.
         pTempFile->GetLeafName(leafName);
       }
       // copy the file to its new location and file name
       pFile->CopyTo(pTempDir, leafName);
       // point pFile to the new location of the attachment
       pFile->InitWithFile(pTempDir);
+      rv = pFile->InitWithFile(pTempDir);
+#ifdef DEBUG
+      if (NS_FAILED(rv)) {
+        DUMP_INITWITHFILE_PATH("nsMapiHook::HandleAttachments", pFile, pTempDir,
+                               rv);
+      }
+#endif
+      NS_ENSURE_SUCCESS(rv, rv);
       pFile->Append(leafName);
 
       // create MsgCompose attachment object
       attachment->SetTemporary(
           true);  // this one is a temp file so set the flag for MsgCompose
 
       // now set the attachment object
       nsAutoCString pURL;
@@ -834,17 +861,25 @@ nsresult nsMapiHook::PopulateCompFieldsF
         if (_getdcwd(_getdrive(), cwd, MAX_PATH)) {
           nsAutoCString cwdStr;
           cwdStr.Assign(cwd);
           cwdStr.Append('\\');
           RemainingPaths.Insert(cwdStr, 0);
         }
       }
 
-      pFile->InitWithNativePath(RemainingPaths);
+      rv = pFile->InitWithNativePath(RemainingPaths);
+      if (NS_FAILED(rv)) {
+#ifdef DEBUG
+        DUMP_INITWITHNATIVEPATH_PATH(
+            "nsMapiHook::PopulateCompFieldsForSendDocs", pFile,
+            RemainingPaths, rv);
+#endif
+        return rv;
+      }
 
       rv = pFile->Exists(&bExist);
       if (NS_FAILED(rv) || (!bExist))
         return NS_ERROR_FILE_TARGET_DOES_NOT_EXIST;
 
       // filename of the file attachment
       nsAutoString leafName;
       pFile->GetLeafName(leafName);
--- a/mailnews/mime/src/mimeebod.cpp
+++ b/mailnews/mime/src/mimeebod.cpp
@@ -150,18 +150,32 @@ char* MimeExternalBody_make_url(const ch
     if (!name) return 0;
 
 #ifdef XP_UNIX
     if (!PL_strcasecmp(at, "afs")) /* only if there is a /afs/ directory */
     {
       nsCOMPtr<nsIFile> fs = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
       bool exists = false;
       if (fs) {
-        fs->InitWithNativePath(NS_LITERAL_CSTRING("/afs/."));
-        fs->Exists(&exists);
+        nsresult rv = fs->InitWithNativePath(NS_LITERAL_CSTRING("/afs/."));
+        if (NS_FAILED(rv)) {
+#  ifdef DEBUG
+          DUMP_INITWITHNATIVEPATH_PATH("MimeExternalBody_make_url", fs,
+                                       NS_LITERAL_CSTRING("/afs/."), rv);
+#  endif
+          return 0; /* xxx: we may want to show a large error dialog? */
+        }
+        rv = fs->Exists(&exists);
+        if (NS_FAILED(rv)) {
+#  ifdef DEBUG
+          fprintf(stderr,
+                  "(debug) MimeExternalBody_make_url: fs->Exists failed\n");
+#  endif
+          return 0;
+        }
       }
       if (!exists) return 0;
     }
 #else  /* !XP_UNIX */
     return 0; /* never, if not Unix. */
 #endif /* !XP_UNIX */
 
     slen = (strlen(name) * 3 + 20);