From fffbd86a1014ad169ed2d68ea58cdddf346faa14 Mon Sep 17 00:00:00 2001
From: Andrei Karas <akaras@inbox.ru>
Date: Tue, 21 Jul 2015 00:47:44 +0300
Subject: Add missing checks and non null attributes.

---
 src/actions/actions.cpp                |  2 ++
 src/being/being.cpp                    |  7 +++++--
 src/client.cpp                         |  3 +--
 src/game.cpp                           | 10 +++-------
 src/graphicsmanager.h                  |  3 ++-
 src/gui/windows/charcreatedialog.cpp   | 24 ++++++++++++++++--------
 src/gui/windows/maileditwindow.cpp     | 11 +++++++----
 src/gui/windows/updaterwindow.cpp      | 11 ++++++++++-
 src/logger.h                           |  6 +++---
 src/net/eathena/beinghandler.cpp       |  7 ++++---
 src/net/eathena/buyingstorehandler.cpp |  2 ++
 src/net/eathena/inventoryhandler.cpp   |  4 ++++
 src/resources/db/emotedb.cpp           |  2 ++
 src/resources/db/horsedb.cpp           |  2 ++
 src/resources/image.cpp                |  2 ++
 src/utils/chatutils.cpp                |  4 +++-
 src/utils/copynpaste.cpp               |  6 +-----
 src/utils/stringutils.h                |  2 +-
 src/utils/xml.cpp                      |  3 +++
 19 files changed, 73 insertions(+), 38 deletions(-)

(limited to 'src')

diff --git a/src/actions/actions.cpp b/src/actions/actions.cpp
index d6a8ec53d..a8d21367e 100644
--- a/src/actions/actions.cpp
+++ b/src/actions/actions.cpp
@@ -1531,6 +1531,8 @@ impHandler(invToStorage)
     Item *item = nullptr;
     const int amount = getAmountFromEvent(event, item,
         InventoryType::INVENTORY);
+    if (!item)
+        return true;
     if (amount)
     {
         inventoryHandler->moveItem2(InventoryType::INVENTORY,
diff --git a/src/being/being.cpp b/src/being/being.cpp
index bf05eb7eb..746cc729b 100644
--- a/src/being/being.cpp
+++ b/src/being/being.cpp
@@ -3611,7 +3611,7 @@ void Being::addItemParticles(const int id, const SpriteDisplay &display)
         pi = (*it).second;
     }
 
-    if (!pi->particles.empty())
+    if (!pi || !pi->particles.empty())
         return;
 
     // setup particle effects
@@ -3735,7 +3735,10 @@ void Being::setRiding(const bool b)
     if (b)
     {
         mHorseInfo = HorseDB::get(1);
-        mHorseSprite = mHorseInfo->sprite;
+        if (mHorseInfo)
+            mHorseSprite = mHorseInfo->sprite;
+        else
+            mHorseSprite = nullptr;
     }
     else
     {
diff --git a/src/client.cpp b/src/client.cpp
index f75ba53b9..adf2ffdb2 100644
--- a/src/client.cpp
+++ b/src/client.cpp
@@ -426,8 +426,7 @@ void Client::gameInit()
             branding.getValue("defaultServerType", "tmwathena"));
     }
 
-    if (chatLogger)
-        chatLogger->setServerName(mCurrentServer.hostname);
+    chatLogger->setServerName(mCurrentServer.hostname);
 
     if (loginData.username.empty() && loginData.remember)
         loginData.username = serverConfig.getValue("username", "");
diff --git a/src/game.cpp b/src/game.cpp
index df2b99e64..b5e492ee5 100644
--- a/src/game.cpp
+++ b/src/game.cpp
@@ -275,13 +275,9 @@ static void createGuiWindows()
         battleChatTab = nullptr;
     }
 
-    if (chatWindow)
-    {
-        chatWindow->showGMTab();
-
-        if (!isSafeMode)
-            chatWindow->loadState();
-    }
+    chatWindow->showGMTab();
+    if (!isSafeMode)
+        chatWindow->loadState();
 
     if (setupWindow)
         setupWindow->externalUpdate();
diff --git a/src/graphicsmanager.h b/src/graphicsmanager.h
index 0063be275..f2c0e6507 100644
--- a/src/graphicsmanager.h
+++ b/src/graphicsmanager.h
@@ -134,7 +134,8 @@ class GraphicsManager final
 
         static std::string getGLString(const int num) A_WARN_UNUSED;
 
-        static void logString(const char *const format, const int num);
+        static void logString(const char *const format,
+                              const int num) A_NONNULL(1);
 
         void detectVideoSettings();
 
diff --git a/src/gui/windows/charcreatedialog.cpp b/src/gui/windows/charcreatedialog.cpp
index eba1dd96e..2168ad0a1 100644
--- a/src/gui/windows/charcreatedialog.cpp
+++ b/src/gui/windows/charcreatedialog.cpp
@@ -268,20 +268,28 @@ CharCreateDialog::CharCreateDialog(CharSelectDialog *const parent,
     if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
     {
         y += 24;
-        mPrevLookButton->setPosition(leftX, y);
-        mNextLookButton->setPosition(rightX, y);
+        if (mPrevLookButton)
+            mPrevLookButton->setPosition(leftX, y);
+        if (mNextLookButton)
+            mNextLookButton->setPosition(rightX, y);
         y += 5;
-        mLookLabel->setPosition(labelX, y);
-        mLookNameLabel->setPosition(nameX, y);  // 93
+        if (mLookLabel)
+            mLookLabel->setPosition(labelX, y);
+        if (mLookNameLabel)
+            mLookNameLabel->setPosition(nameX, y);  // 93
     }
     if (serverFeatures->haveRaceSelection())
     {
         y += 24;
-        mPrevRaceButton->setPosition(leftX, y);
-        mNextRaceButton->setPosition(rightX, y);
+        if (mPrevRaceButton)
+            mPrevRaceButton->setPosition(leftX, y);
+        if (mNextRaceButton)
+            mNextRaceButton->setPosition(rightX, y);
         y += 5;
-        mRaceLabel->setPosition(labelX, y);
-        mRaceNameLabel->setPosition(nameX, y);
+        if (mRaceLabel)
+            mRaceLabel->setPosition(labelX, y);
+        if (mRaceNameLabel)
+            mRaceNameLabel->setPosition(nameX, y);
     }
 
     updateSliders();
diff --git a/src/gui/windows/maileditwindow.cpp b/src/gui/windows/maileditwindow.cpp
index 12ab097c0..1699b979c 100644
--- a/src/gui/windows/maileditwindow.cpp
+++ b/src/gui/windows/maileditwindow.cpp
@@ -136,11 +136,14 @@ void MailEditWindow::action(const ActionEvent &event)
         if (tempItem)
         {
             const Inventory *const inv = PlayerInfo::getInventory();
-            const Item *const item = inv->findItem(tempItem->getId(), 1);
-            if (item)
+            if (inv)
             {
-                mailHandler->setAttach(item->getInvIndex(),
-                    tempItem->getQuantity());
+                const Item *const item = inv->findItem(tempItem->getId(), 1);
+                if (item)
+                {
+                    mailHandler->setAttach(item->getInvIndex(),
+                        tempItem->getQuantity());
+                }
             }
         }
 
diff --git a/src/gui/windows/updaterwindow.cpp b/src/gui/windows/updaterwindow.cpp
index e221b73b9..9330539ab 100644
--- a/src/gui/windows/updaterwindow.cpp
+++ b/src/gui/windows/updaterwindow.cpp
@@ -362,7 +362,11 @@ void UpdaterWindow::loadNews()
     // Reallocate and include terminating 0 character
     mMemoryBuffer = static_cast<char*>(realloc(
         mMemoryBuffer, mDownloadedBytes + 1));
-
+    if (!mMemoryBuffer)
+    {
+        logger->log1("Couldn't load news");
+        return;
+    }
     mMemoryBuffer[mDownloadedBytes] = '\0';
     mBrowserBox->clearRows();
 
@@ -425,6 +429,11 @@ void UpdaterWindow::loadPatch()
     // Reallocate and include terminating 0 character
     mMemoryBuffer = static_cast<char*>(
         realloc(mMemoryBuffer, mDownloadedBytes + 1));
+    if (!mMemoryBuffer)
+    {
+        logger->log1("Couldn't load patch");
+        return;
+    }
     mMemoryBuffer[mDownloadedBytes] = '\0';
 
     std::string version;
diff --git a/src/logger.h b/src/logger.h
index da910fd57..e05ab3e67 100644
--- a/src/logger.h
+++ b/src/logger.h
@@ -81,7 +81,7 @@ class Logger final
         /**
          * Enters a message in the log. The message will be timestamped.
          */
-        void log(const char *const log_text, ...)
+        void log(const char *const log_text, ...) A_NONNULL(2)
 #ifdef __GNUC__
 #ifdef __OpenBSD__
 
@@ -102,7 +102,7 @@ class Logger final
         /**
          * Enters a message in the log (thread safe).
          */
-        void log_r(const char *const log_text, ...)
+        void log_r(const char *const log_text, ...) A_NONNULL(2)
 #ifdef __GNUC__
 #ifdef __OpenBSD__
             __attribute__((__format__(printf, 2, 3)))
@@ -122,7 +122,7 @@ class Logger final
         /**
          * Enters a message in the log. The message will be timestamped.
          */
-        void log1(const char *const log_text);
+        void log1(const char *const log_text) A_NONNULL(2);
 
         /**
          * Enters a message in the log. The message will be timestamped.
diff --git a/src/net/eathena/beinghandler.cpp b/src/net/eathena/beinghandler.cpp
index 79fddcf18..d12941fcd 100644
--- a/src/net/eathena/beinghandler.cpp
+++ b/src/net/eathena/beinghandler.cpp
@@ -663,7 +663,6 @@ void BeingHandler::processBeingVisible(Net::MessageIn &msg)
             return;
 
         dstBeing = createBeing2(msg, id, job, type);
-
         if (!dstBeing)
             return;
     }
@@ -831,7 +830,6 @@ void BeingHandler::processBeingMove(Net::MessageIn &msg)
             return;
 
         dstBeing = createBeing2(msg, id, job, type);
-
         if (!dstBeing)
             return;
     }
@@ -1001,7 +999,6 @@ void BeingHandler::processBeingSpawn(Net::MessageIn &msg)
             return;
 
         dstBeing = createBeing2(msg, id, job, type);
-
         if (!dstBeing)
             return;
     }
@@ -1120,6 +1117,8 @@ void BeingHandler::processMapTypeProperty(Net::MessageIn &msg)
         MapTypeProperty2 props;
         props.data = static_cast<uint32_t>(flags);
         Game *const game = Game::instance();
+        if (!game)
+            return;
         Map *const map = game->getCurrentMap();
         if (!map)
             return;
@@ -1679,6 +1678,8 @@ void BeingHandler::processBeingFakeName(Net::MessageIn &msg)
     msg.skip(4, "unsued");
 
     Being *const dstBeing = createBeing2(msg, id, job, type);
+    if (!dstBeing)
+        return;
     dstBeing->setSubtype(fromInt(job, BeingTypeId), 0);
     dstBeing->setTileCoords(x, y);
     dstBeing->setDirection(dir);
diff --git a/src/net/eathena/buyingstorehandler.cpp b/src/net/eathena/buyingstorehandler.cpp
index f2017bd53..d42d66b07 100644
--- a/src/net/eathena/buyingstorehandler.cpp
+++ b/src/net/eathena/buyingstorehandler.cpp
@@ -208,6 +208,8 @@ void BuyingStoreHandler::processBuyingStoreItemsList(Net::MessageIn &msg)
         const int itemType = msg.readUInt8("item type");
         const int itemId = msg.readInt16("item id");
 
+        if (!inv)
+            continue;
         const Item *const item = inv->findItem(itemId, 1);
         if (!item)
             continue;
diff --git a/src/net/eathena/inventoryhandler.cpp b/src/net/eathena/inventoryhandler.cpp
index 015ff3c2c..86faea2e7 100644
--- a/src/net/eathena/inventoryhandler.cpp
+++ b/src/net/eathena/inventoryhandler.cpp
@@ -803,6 +803,8 @@ void InventoryHandler::processPlayerUseCard(Net::MessageIn &msg)
     for (int f = 0; f < count; f ++)
     {
         const int itemIndex = msg.readInt16("item index") - INVENTORY_OFFSET;
+        if (!inv)
+            continue;
         const Item *const item = inv->getItem(itemIndex);
         if (!item)
             continue;
@@ -822,6 +824,8 @@ void InventoryHandler::processPlayerInsertCard(Net::MessageIn &msg)
     {
         NotifyManager::notify(NotifyTypes::CARD_INSERT_SUCCESS);
         Inventory *const inv = PlayerInfo::getInventory();
+        if (!inv)
+            return;
         Item *const card = inv->getItem(cardIndex);
         int cardId = 0;
         if (card)
diff --git a/src/resources/db/emotedb.cpp b/src/resources/db/emotedb.cpp
index accea5ae9..eb5eef418 100644
--- a/src/resources/db/emotedb.cpp
+++ b/src/resources/db/emotedb.cpp
@@ -108,6 +108,8 @@ void EmoteDB::loadXmlFile(const std::string &fileName)
             currentInfo = mEmoteInfos[id];
         else
             currentInfo = new EmoteInfo;
+        if (!currentInfo)
+            continue;
         currentInfo->time = XML::getProperty(emoteNode, "time", 500);
         currentInfo->effectId = XML::getProperty(emoteNode, "effect", -1);
 
diff --git a/src/resources/db/horsedb.cpp b/src/resources/db/horsedb.cpp
index 11fd57d36..a3daf76cc 100644
--- a/src/resources/db/horsedb.cpp
+++ b/src/resources/db/horsedb.cpp
@@ -97,6 +97,8 @@ void HorseDB::loadXmlFile(const std::string &fileName)
         else
             currentInfo = new HorseInfo;
 
+        if (!currentInfo)
+            continue;
         currentInfo->offsetX = XML::getProperty(horseNode, "offsetX", 0);
         currentInfo->offsetY = XML::getProperty(horseNode, "offsetY", 0);
 
diff --git a/src/resources/image.cpp b/src/resources/image.cpp
index cd615c030..fc1c5fa4f 100644
--- a/src/resources/image.cpp
+++ b/src/resources/image.cpp
@@ -305,6 +305,8 @@ void Image::setAlpha(const float alpha)
             else
             {
                 mSDLSurface = SDLImageHelper::SDLDuplicateSurface(mSDLSurface);
+                if (!mSDLSurface)
+                    return;
             }
         }
 
diff --git a/src/utils/chatutils.cpp b/src/utils/chatutils.cpp
index c5b7e25ad..17ee9e11a 100644
--- a/src/utils/chatutils.cpp
+++ b/src/utils/chatutils.cpp
@@ -158,7 +158,9 @@ void replaceVars(std::string &str)
         StringVect names;
         std::string newStr;
         const Party *party = nullptr;
-        if (localPlayer->isInParty() && (party = localPlayer->getParty()))
+        if (localPlayer->isInParty() &&
+            (party = localPlayer->getParty()) &&
+            party)
         {
             party->getNames(names);
             FOR_EACH (StringVectCIter, it, names)
diff --git a/src/utils/copynpaste.cpp b/src/utils/copynpaste.cpp
index ce16bbab0..1f88d8abf 100644
--- a/src/utils/copynpaste.cpp
+++ b/src/utils/copynpaste.cpp
@@ -373,13 +373,9 @@ bool retrieveBuffer(std::string& text, size_t& pos)
     {
         Display *const dpy = info.info.x11.display;
         Window us = info.info.x11.window;
-        char *data = nullptr;
 
         requestAtom = XInternAtom(dpy, "UTF8_STRING", true);
-
-        if (!data)
-            data = getSelection(dpy, us, XA_PRIMARY);
-
+        char *data = getSelection(dpy, us, XA_PRIMARY);
         if (!data)
             data = getSelection(dpy, us, XA_SECONDARY);
         if (!data)
diff --git a/src/utils/stringutils.h b/src/utils/stringutils.h
index 3307d6e73..67144ea65 100644
--- a/src/utils/stringutils.h
+++ b/src/utils/stringutils.h
@@ -99,7 +99,7 @@ const char *ipToString(const uint32_t address) A_WARN_UNUSED;
 /**
  * A safe version of sprintf that returns a std::string of the result.
  */
-std::string strprintf(const char *const format, ...) A_WARN_UNUSED
+std::string strprintf(const char *const format, ...) A_NONNULL(1) A_WARN_UNUSED
 #ifdef __GNUC__
     /* This attribute is nice: it even works through gettext invokation. For
        example, gcc will complain that strprintf(_("%s"), 42) is ill-formed. */
diff --git a/src/utils/xml.cpp b/src/utils/xml.cpp
index 8642140c9..e9b2260bf 100644
--- a/src/utils/xml.cpp
+++ b/src/utils/xml.cpp
@@ -54,6 +54,9 @@ static void xmlErrorLogger(void *ctx A_UNUSED, const char *msg, ...)
     if (msgSize * 3 > size)
         size = msgSize * 3;
 
+    if (!msg)
+        return;
+
     char* buf = new char[size + 1];
     va_list ap;
 
-- 
cgit v1.2.3-70-g09d2