For usages of assert() that are meant to persist in Release builds (when NDEBUG is...
authorCraig Robbins <kde.psych@gmail.com>
Fri, 6 Mar 2015 10:21:51 +0000 (20:21 +1000)
committerCraig Robbins <kde.psych@gmail.com>
Sat, 7 Mar 2015 12:41:47 +0000 (22:41 +1000)
62 files changed:
src/chat.cpp
src/client.cpp
src/client/clientlauncher.cpp
src/client/tile.cpp
src/clientiface.h
src/clientmap.cpp
src/clientmedia.cpp
src/collision.cpp
src/content_cao.cpp
src/content_mapblock.cpp
src/content_sao.cpp
src/database-sqlite3.cpp
src/debug.cpp
src/debug.h
src/environment.cpp
src/fontengine.cpp
src/game.cpp
src/guiEngine.cpp
src/guiFormSpecMenu.cpp
src/guiKeyChangeMenu.cpp
src/httpfetch.cpp
src/inventory.cpp
src/inventory.h
src/inventorymanager.cpp
src/itemdef.cpp
src/keycode.cpp
src/localplayer.cpp
src/localplayer.h
src/main.cpp
src/map.cpp
src/map.h
src/mapblock.cpp
src/mapblock.h
src/mapgen_singlenode.cpp
src/mapgen_v5.cpp
src/mapgen_v6.cpp
src/mapgen_v7.cpp
src/mapnode.cpp
src/mapsector.cpp
src/mg_schematic.cpp
src/network/connection.cpp
src/network/connection.h
src/network/packethandlers/client.cpp
src/nodedef.cpp
src/noise.h
src/player.h
src/porting.cpp
src/script/common/c_internal.cpp
src/script/cpp_api/s_async.cpp
src/script/cpp_api/s_base.cpp
src/script/lua_api/l_env.cpp
src/script/lua_api/l_mainmenu.cpp
src/server.cpp
src/settings.cpp
src/shader.cpp
src/sound_openal.cpp
src/staticobject.h
src/test.cpp
src/util/serialize.cpp
src/util/string.cpp
src/voxel.h
src/wieldmesh.cpp

index 1fb872b8527badb4d5fa4ae1696601b84c7d5970..2d29d39da77fe1b87381607b392ee920a7732e45 100644 (file)
@@ -83,7 +83,7 @@ u32 ChatBuffer::getScrollback() const
 
 const ChatLine& ChatBuffer::getLine(u32 index) const
 {
-       assert(index < getLineCount());
+       assert(index < getLineCount()); // pre-condition
        return m_unformatted[index];
 }
 
@@ -107,7 +107,8 @@ void ChatBuffer::deleteOldest(u32 count)
                // keep m_formatted in sync
                if (del_formatted < m_formatted.size())
                {
-                       assert(m_formatted[del_formatted].first);
+
+                       sanity_check(m_formatted[del_formatted].first);
                        ++del_formatted;
                        while (del_formatted < m_formatted.size() &&
                                        !m_formatted[del_formatted].first)
index 00b79e92ef181093dc0c52b383d478c31f703e9d..edf24445298971f56cc124e631fe5338fdab0a70 100644 (file)
@@ -97,7 +97,7 @@ void MeshUpdateQueue::addBlock(v3s16 p, MeshMakeData *data, bool ack_block_to_se
 {
        DSTACK(__FUNCTION_NAME);
 
-       assert(data);
+       assert(data);   // pre-condition
 
        JMutexAutoLock lock(m_mutex);
 
@@ -388,8 +388,9 @@ void Client::step(float dtime)
                if(counter <= 0.0) {
                        counter = 2.0;
 
-                       Player *myplayer = m_env.getLocalPlayer();
-                       assert(myplayer != NULL);
+                       Player *myplayer = m_env.getLocalPlayer();              
+                       FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
+
                        // Send TOSERVER_INIT
                        // [0] u16 TOSERVER_INIT
                        // [2] u8 SER_FMT_VER_HIGHEST_READ
@@ -707,7 +708,9 @@ bool Client::loadMedia(const std::string &data, const std::string &filename)
                // Create an irrlicht memory file
                io::IReadFile *rfile = irrfs->createMemoryReadFile(
                                *data_rw, data_rw.getSize(), "_tempreadfile");
-               assert(rfile);
+
+               FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
+
                // Read image
                video::IImage *img = vdrv->createImageFromFile(rfile);
                if(!img){
@@ -785,7 +788,8 @@ void Client::request_media(const std::vector<std::string> &file_requests)
        std::ostringstream os(std::ios_base::binary);
        writeU16(os, TOSERVER_REQUEST_MEDIA);
        size_t file_requests_size = file_requests.size();
-       assert(file_requests_size <= 0xFFFF);
+
+       FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
 
        // Packet dynamicly resized
        NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
@@ -986,7 +990,8 @@ void Client::sendNodemetaFields(v3s16 p, const std::string &formname,
                const std::map<std::string, std::string> &fields)
 {
        size_t fields_size = fields.size();
-       assert(fields_size <= 0xFFFF);
+
+       FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
 
        NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
 
@@ -1007,7 +1012,7 @@ void Client::sendInventoryFields(const std::string &formname,
                const std::map<std::string, std::string> &fields)
 {
        size_t fields_size = fields.size();
-       assert(fields_size <= 0xFFFF);
+       FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
 
        NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
        *pkt << formname << (u16) (fields_size & 0xFFFF);
@@ -1141,7 +1146,7 @@ void Client::sendPlayerPos()
        // Set peer id if not set already
        if(myplayer->peer_id == PEER_ID_INEXISTENT)
                myplayer->peer_id = our_peer_id;
-       // Check that an existing peer_id is the same as the connection's
+
        assert(myplayer->peer_id == our_peer_id);
 
        v3f pf         = myplayer->getPosition();
@@ -1179,8 +1184,6 @@ void Client::sendPlayerItem(u16 item)
        // Set peer id if not set already
        if(myplayer->peer_id == PEER_ID_INEXISTENT)
                myplayer->peer_id = our_peer_id;
-
-       // Check that an existing peer_id is the same as the connection's
        assert(myplayer->peer_id == our_peer_id);
 
        NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
@@ -1295,7 +1298,7 @@ Inventory* Client::getInventory(const InventoryLocation &loc)
        }
        break;
        default:
-               assert(0);
+               FATAL_ERROR("Invalid inventory location type.");
        }
        return NULL;
 }
@@ -1555,9 +1558,9 @@ float Client::mediaReceiveProgress()
 void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
 {
        infostream<<"Client::afterContentReceived() started"<<std::endl;
-       assert(m_itemdef_received);
-       assert(m_nodedef_received);
-       assert(mediaReceived());
+       assert(m_itemdef_received); // pre-condition
+       assert(m_nodedef_received); // pre-condition
+       assert(mediaReceived()); // pre-condition
 
        const wchar_t* text = wgettext("Loading textures...");
 
@@ -1697,9 +1700,10 @@ scene::ISceneManager* Client::getSceneManager()
 }
 u16 Client::allocateUnknownNodeId(const std::string &name)
 {
-       errorstream<<"Client::allocateUnknownNodeId(): "
-                       <<"Client cannot allocate node IDs"<<std::endl;
-       assert(0);
+       errorstream << "Client::allocateUnknownNodeId(): "
+                       << "Client cannot allocate node IDs" << std::endl;
+       FATAL_ERROR("Client allocated unknown node");
+
        return CONTENT_IGNORE;
 }
 ISoundManager* Client::getSoundManager()
@@ -1734,7 +1738,7 @@ scene::IAnimatedMesh* Client::getMesh(const std::string &filename)
        io::IFileSystem *irrfs = m_device->getFileSystem();
        io::IReadFile *rfile   = irrfs->createMemoryReadFile(
                        *data_rw, data_rw.getSize(), filename.c_str());
-       assert(rfile);
+       FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
 
        scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
        rfile->drop();
index 0f60dcd635aead274b0c21e825aa69055d9b6206..7bf849624dc48584cfe439154aef3c9bf7717141 100644 (file)
@@ -128,7 +128,7 @@ bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
        skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
 
        g_fontengine = new FontEngine(g_settings, guienv);
-       assert(g_fontengine != NULL);
+       FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
 
 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
        // Irrlicht 1.8 input colours
index e5d02de7c9f26784be1bbed3e978407d5d983758..541247fa8691faf863922b1353375ce2bbba845d 100644 (file)
@@ -199,7 +199,7 @@ public:
        void insert(const std::string &name, video::IImage *img,
                        bool prefer_local, video::IVideoDriver *driver)
        {
-               assert(img);
+               assert(img); // Pre-condition
                // Remove old image
                std::map<std::string, video::IImage*>::iterator n;
                n = m_images.find(name);
@@ -423,7 +423,7 @@ IWritableTextureSource* createTextureSource(IrrlichtDevice *device)
 TextureSource::TextureSource(IrrlichtDevice *device):
                m_device(device)
 {
-       assert(m_device);
+       assert(m_device); // Pre-condition
 
        m_main_thread = get_current_thread_id();
 
@@ -597,7 +597,7 @@ u32 TextureSource::generateTexture(const std::string &name)
        }
 
        video::IVideoDriver *driver = m_device->getVideoDriver();
-       assert(driver);
+       sanity_check(driver);
 
        video::IImage *img = generateImage(name);
 
@@ -684,7 +684,7 @@ void TextureSource::insertSourceImage(const std::string &name, video::IImage *im
 {
        //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
 
-       assert(get_current_thread_id() == m_main_thread);
+       sanity_check(get_current_thread_id() == m_main_thread);
 
        m_sourcecache.insert(name, img, true, m_device->getVideoDriver());
        m_source_image_existence.set(name, true);
@@ -695,7 +695,7 @@ void TextureSource::rebuildImagesAndTextures()
        JMutexAutoLock lock(m_textureinfo_cache_mutex);
 
        video::IVideoDriver* driver = m_device->getVideoDriver();
-       assert(driver != 0);
+       sanity_check(driver);
 
        // Recreate textures
        for (u32 i=0; i<m_textureinfo_cache.size(); i++){
@@ -703,8 +703,8 @@ void TextureSource::rebuildImagesAndTextures()
                video::IImage *img = generateImage(ti->name);
 #ifdef __ANDROID__
                img = Align2Npot2(img, driver);
-               assert(img->getDimension().Height == npot2(img->getDimension().Height));
-               assert(img->getDimension().Width == npot2(img->getDimension().Width));
+               sanity_check(img->getDimension().Height == npot2(img->getDimension().Height));
+               sanity_check(img->getDimension().Width == npot2(img->getDimension().Width));
 #endif
                // Create texture from resulting image
                video::ITexture *t = NULL;
@@ -725,7 +725,7 @@ video::ITexture* TextureSource::generateTextureFromMesh(
                const TextureFromMeshParams &params)
 {
        video::IVideoDriver *driver = m_device->getVideoDriver();
-       assert(driver);
+       sanity_check(driver);
 
 #ifdef __ANDROID__
        const GLubyte* renderstr = glGetString(GL_RENDERER);
@@ -741,9 +741,9 @@ video::ITexture* TextureSource::generateTextureFromMesh(
                ) {
                // Get a scene manager
                scene::ISceneManager *smgr_main = m_device->getSceneManager();
-               assert(smgr_main);
+               sanity_check(smgr_main);
                scene::ISceneManager *smgr = smgr_main->createNewSceneManager();
-               assert(smgr);
+               sanity_check(smgr);
 
                const float scaling = 0.2;
 
@@ -978,7 +978,7 @@ video::IImage* TextureSource::generateImage(const std::string &name)
 
 
        video::IVideoDriver* driver = m_device->getVideoDriver();
-       assert(driver);
+       sanity_check(driver);
 
        /*
                Parse out the last part of the name of the image and act
@@ -1078,7 +1078,7 @@ bool TextureSource::generateImagePart(std::string part_of_name,
                video::IImage *& baseimg)
 {
        video::IVideoDriver* driver = m_device->getVideoDriver();
-       assert(driver);
+       sanity_check(driver);
 
        // Stuff starting with [ are special commands
        if (part_of_name.size() == 0 || part_of_name[0] != '[')
@@ -1106,7 +1106,7 @@ bool TextureSource::generateImagePart(std::string part_of_name,
                        //core::dimension2d<u32> dim(2,2);
                        core::dimension2d<u32> dim(1,1);
                        image = driver->createImage(video::ECF_A8R8G8B8, dim);
-                       assert(image);
+                       sanity_check(image != NULL);
                        /*image->setPixel(0,0, video::SColor(255,255,0,0));
                        image->setPixel(1,0, video::SColor(255,0,255,0));
                        image->setPixel(0,1, video::SColor(255,0,0,255));
@@ -1362,7 +1362,7 @@ bool TextureSource::generateImagePart(std::string part_of_name,
                                        transform, baseimg->getDimension());
                        video::IImage *image = driver->createImage(
                                        baseimg->getColorFormat(), dim);
-                       assert(image);
+                       sanity_check(image != NULL);
                        imageTransform(transform, baseimg, image);
                        baseimg->drop();
                        baseimg = image;
@@ -1422,7 +1422,7 @@ bool TextureSource::generateImagePart(std::string part_of_name,
                                        (imagename_left + "__temp__").c_str(), img_left);
                        video::ITexture *texture_right = driver->addTexture(
                                        (imagename_right + "__temp__").c_str(), img_right);
-                       assert(texture_top && texture_left && texture_right);
+                       FATAL_ERROR_IF(!(texture_top && texture_left && texture_right), "");
 
                        // Drop images
                        img_top->drop();
@@ -1476,7 +1476,7 @@ bool TextureSource::generateImagePart(std::string part_of_name,
 
                        // Create image of render target
                        video::IImage *image = driver->createImage(rtt, v2s32(0, 0), params.dim);
-                       assert(image);
+                       FATAL_ERROR_IF(!image, "Could not create image of render target");
 
                        // Cleanup texture
                        driver->removeTexture(rtt);
@@ -1892,10 +1892,10 @@ void imageTransform(u32 transform, video::IImage *src, video::IImage *dst)
        if (src == NULL || dst == NULL)
                return;
 
-       core::dimension2d<u32> srcdim = src->getDimension();
        core::dimension2d<u32> dstdim = dst->getDimension();
 
-       assert(dstdim == imageTransformDimension(transform, srcdim));
+       // Pre-conditions
+       assert(dstdim == imageTransformDimension(transform, src->getDimension()));
        assert(transform <= 7);
 
        /*
index 2f265b128f6010158a023b391a65c585d5325ddd..cc303734afe1998584c6f16f4639d98651c8d97e 100644 (file)
@@ -426,9 +426,12 @@ public:
        /* event to update client state */
        void event(u16 peer_id, ClientStateEvent event);
 
-       /* set environment */
-       void setEnv(ServerEnvironment* env)
-       { assert(m_env == 0); m_env = env; }
+       /* Set environment. Do not call this function if environment is already set */
+       void setEnv(ServerEnvironment *env)
+       {
+               assert(m_env == NULL); // pre-condition
+               m_env = env;
+       }
 
        static std::string state2Name(ClientState state);
 
index 1c420b5f9adbe348f7ae2054371a83f526659ba0..907df7128a15a6629a60914b8b9804334d4595cc 100644 (file)
@@ -102,34 +102,6 @@ MapSector * ClientMap::emergeSector(v2s16 p2d)
        return sector;
 }
 
-#if 0
-void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
-{
-       DSTACK(__FUNCTION_NAME);
-       ClientMapSector *sector = NULL;
-
-       //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
-
-       core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
-
-       if(n != NULL)
-       {
-               sector = (ClientMapSector*)n->getValue();
-               assert(sector->getId() == MAPSECTOR_CLIENT);
-       }
-       else
-       {
-               sector = new ClientMapSector(this, p2d);
-               {
-                       //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
-                       m_sectors.insert(p2d, sector);
-               }
-       }
-
-       sector->deSerialize(is);
-}
-#endif
-
 void ClientMap::OnRegisterSceneNode()
 {
        if(IsVisible)
index 1d825c14316b7069852969b82b39435747842b01..0918e8a3797002d2d262445d7dfe3ffec32b7ce4 100644 (file)
@@ -72,7 +72,7 @@ ClientMediaDownloader::~ClientMediaDownloader()
 
 void ClientMediaDownloader::addFile(std::string name, std::string sha1)
 {
-       assert(!m_initial_step_done);
+       assert(!m_initial_step_done); // pre-condition
 
        // if name was already announced, ignore the new announcement
        if (m_files.count(name) != 0) {
@@ -107,7 +107,7 @@ void ClientMediaDownloader::addFile(std::string name, std::string sha1)
 
 void ClientMediaDownloader::addRemoteServer(std::string baseurl)
 {
-       assert(!m_initial_step_done);
+       assert(!m_initial_step_done);   // pre-condition
 
        #ifdef USE_CURL
 
@@ -356,11 +356,11 @@ void ClientMediaDownloader::remoteMediaReceived(
                m_remote_file_transfers.erase(it);
        }
 
-       assert(m_files.count(name) != 0);
+       sanity_check(m_files.count(name) != 0);
 
        FileStatus *filestatus = m_files[name];
-       assert(!filestatus->received);
-       assert(filestatus->current_remote >= 0);
+       sanity_check(!filestatus->received);
+       sanity_check(filestatus->current_remote >= 0);
 
        RemoteServerStatus *remote = m_remotes[filestatus->current_remote];
 
@@ -382,6 +382,7 @@ void ClientMediaDownloader::remoteMediaReceived(
 
 s32 ClientMediaDownloader::selectRemoteServer(FileStatus *filestatus)
 {
+       // Pre-conditions
        assert(filestatus != NULL);
        assert(!filestatus->received);
        assert(filestatus->current_remote < 0);
@@ -483,7 +484,7 @@ void ClientMediaDownloader::startRemoteMediaTransfers()
 
 void ClientMediaDownloader::startConventionalTransfers(Client *client)
 {
-       assert(m_httpfetch_active == 0);
+       assert(m_httpfetch_active == 0);        // pre-condition
 
        if (m_uncached_received_count != m_uncached_count) {
                // Some media files have not been received yet, use the
@@ -616,7 +617,7 @@ std::string ClientMediaDownloader::serializeRequiredHashSet()
                        it = m_files.begin();
                        it != m_files.end(); ++it) {
                if (!it->second->received) {
-                       assert(it->second->sha1.size() == 20);
+                       FATAL_ERROR_IF(it->second->sha1.size() != 20, "Invalid SHA1 size");
                        os << it->second->sha1;
                }
        }
index b1b1e23bd40a2fab3ef6bbfbac682faac1e8d7cf..12eabff090dd6dd433e4ae30748be786720bf1f8 100644 (file)
@@ -173,7 +173,7 @@ bool wouldCollideWithCeiling(
 {
        //TimeTaker tt("wouldCollideWithCeiling");
 
-       assert(y_increase >= 0);
+       assert(y_increase >= 0);        // pre-condition
 
        for(std::vector<aabb3f>::const_iterator
                        i = staticboxes.begin();
@@ -348,11 +348,11 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
                }
        } //tt3
 
-       assert(cboxes.size() == is_unloaded.size());
-       assert(cboxes.size() == is_step_up.size());
-       assert(cboxes.size() == bouncy_values.size());
-       assert(cboxes.size() == node_positions.size());
-       assert(cboxes.size() == is_object.size());
+       assert(cboxes.size() == is_unloaded.size());    // post-condition
+       assert(cboxes.size() == is_step_up.size());     // post-condition
+       assert(cboxes.size() == bouncy_values.size());  // post-condition
+       assert(cboxes.size() == node_positions.size()); // post-condition
+       assert(cboxes.size() == is_object.size());      // post-condition
 
        /*
                Collision detection
@@ -367,7 +367,7 @@ collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
        //f32 d = 0.15*BS;
 
        // This should always apply, otherwise there are glitches
-       assert(d > pos_max_d);
+       assert(d > pos_max_d);  // invariant
 
        int loopcount = 0;
 
index 5c3c7b54cb984a32cd1486eee1060afc442d9863..4c8962edbbf55ceea073a67474907fb9dc282083 100644 (file)
@@ -1718,10 +1718,12 @@ void GenericCAO::processMessage(const std::string &data)
        }
 }
        
+/* \pre punchitem != NULL
+ */
 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
                float time_from_last_punch)
 {
-       assert(punchitem);
+       assert(punchitem);      // pre-condition
        const ToolCapabilities *toolcap =
                        &punchitem->getToolCapabilities(m_gamedef->idef());
        PunchDamageResult result = getPunchDamage(
index 3428f85f98bb5814eaecaac13a8b55b2caafc188..2f1368765fd3c2f2c29053a6a51b32a5485bf450 100644 (file)
@@ -47,7 +47,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 void makeCuboid(MeshCollector *collector, const aabb3f &box,
        TileSpec *tiles, int tilecount, video::SColor &c, const f32* txc)
 {
-       assert(tilecount >= 1 && tilecount <= 6);
+       assert(tilecount >= 1 && tilecount <= 6); // pre-condition
 
        v3f min = box.MinEdge;
        v3f max = box.MaxEdge;
@@ -206,8 +206,8 @@ void mapblock_mesh_generate_special(MeshMakeData *data,
 
                switch(f.drawtype){
                default:
-                       infostream<<"Got "<<f.drawtype<<std::endl;
-                       assert(0);
+                       infostream << "Got " << f.drawtype << std::endl;
+                       FATAL_ERROR("Unknown drawtype");
                        break;
                case NDT_AIRLIKE:
                        break;
@@ -754,7 +754,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data,
                break;}
                case NDT_GLASSLIKE_FRAMED_OPTIONAL:
                        // This is always pre-converted to something else
-                       assert(0);
+                       FATAL_ERROR("NDT_GLASSLIKE_FRAMED_OPTIONAL not pre-converted as expected");
                        break;
                case NDT_GLASSLIKE_FRAMED:
                {
@@ -1006,7 +1006,7 @@ void mapblock_mesh_generate_special(MeshMakeData *data,
                break;}
                case NDT_ALLFACES_OPTIONAL:
                        // This is always pre-converted to something else
-                       assert(0);
+                       FATAL_ERROR("NDT_ALLFACES_OPTIONAL not pre-converted");
                        break;
                case NDT_TORCHLIKE:
                {
index 9b2e41677bf58c8e5d7435a37ec427ce9de4ac39..e58aa4b6e6ea909a350de0fbde11dd3fc9c87c13 100644 (file)
@@ -724,8 +724,8 @@ PlayerSAO::PlayerSAO(ServerEnvironment *env_, Player *player_, u16 peer_id_,
        m_physics_override_sneak_glitch(true),
        m_physics_override_sent(false)
 {
-       assert(m_player);
-       assert(m_peer_id != 0);
+       assert(m_player);       // pre-condition
+       assert(m_peer_id != 0); // pre-condition
        setBasePosition(m_player->getPosition());
        m_inventory = &m_player->inventory;
        m_armor_groups["fleshy"] = 100;
@@ -833,7 +833,7 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version)
 
 std::string PlayerSAO::getStaticData()
 {
-       assert(0);
+       FATAL_ERROR("Deprecated function (?)");
        return "";
 }
 
index 3480894c941790f0ab48723c7495eab200fffd6c..c937cae3128bfafac52e7fd6d8634b5bacf142cb 100644 (file)
@@ -210,14 +210,13 @@ std::string Database_SQLite3::loadBlock(const v3s16 &pos)
 
 void Database_SQLite3::createDatabase()
 {
-       assert(m_database);
+       assert(m_database); // Pre-condition
        SQLOK(sqlite3_exec(m_database,
                "CREATE TABLE IF NOT EXISTS `blocks` (\n"
                "       `pos` INT PRIMARY KEY,\n"
                "       `data` BLOB\n"
                ");\n",
                NULL, NULL, NULL));
-
 }
 
 void Database_SQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst)
index bd970a8e4b953de49265dad7d5f7e99b75a51497..521891bbd42d47905b24932654e2fc80a177ef10 100644 (file)
@@ -133,11 +133,11 @@ Nullstream dummyout;
        Assert
 */
 
-void assert_fail(const char *assertion, const char *file,
+void sanity_check_fn(const char *assertion, const char *file,
                unsigned int line, const char *function)
 {
        DEBUGPRINT("\nIn thread %lx:\n"
-                       "%s:%u: %s: Assertion '%s' failed.\n",
+                       "%s:%u: %s: An engine assumption '%s' failed.\n",
                        (unsigned long)get_current_thread_id(),
                        file, line, function, assertion);
 
@@ -149,6 +149,22 @@ void assert_fail(const char *assertion, const char *file,
        abort();
 }
 
+void fatal_error_fn(const char *msg, const char *file,
+               unsigned int line, const char *function)
+{
+       DEBUGPRINT("\nIn thread %lx:\n"
+                       "%s:%u: %s: A fatal error occurred: %s\n",
+                       (unsigned long)get_current_thread_id(),
+                       file, line, function, msg);
+
+       debug_stacks_print();
+
+       if(g_debugstreams[1])
+               fclose(g_debugstreams[1]);
+
+       abort();
+}
+
 /*
        DebugStack
 */
index 1027fde695b89703b84ef6a6e167874e0d69f465..9684aa2dff50e2d44f31ca9126e140b5eb7500d0 100644 (file)
@@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 
 #include <iostream>
 #include <exception>
+#include <assert.h>
 #include "gettime.h"
 
 #if (defined(WIN32) || defined(_WIN32_WCE))
@@ -72,28 +73,38 @@ extern std::ostream dstream;
 extern std::ostream dstream_no_stderr;
 extern Nullstream dummyout;
 
-/*
-       Include assert.h and immediately undef assert so that it can't override
-       our assert later on. leveldb/slice.h is a notable offender.
-*/
 
-#include <assert.h>
-#undef assert
+/* Abort program execution immediately
+ */
+__NORETURN extern void fatal_error_fn(
+               const char *msg, const char *file,
+               unsigned int line, const char *function);
+
+#define FATAL_ERROR(msg) \
+       fatal_error_fn((msg), __FILE__, __LINE__, __FUNCTION_NAME)
+
+#define FATAL_ERROR_IF(expr, msg) \
+       ((expr) \
+       ? fatal_error_fn((msg), __FILE__, __LINE__, __FUNCTION_NAME) \
+       : (void)(0))
 
 /*
-       Assert
+       sanity_check()
+       Equivalent to assert() but persists in Release builds (i.e. when NDEBUG is
+       defined)
 */
 
-__NORETURN extern void assert_fail(
+__NORETURN extern void sanity_check_fn(
                const char *assertion, const char *file,
                unsigned int line, const char *function);
 
-#define ASSERT(expr)\
-       ((expr)\
-       ? (void)(0)\
-       : assert_fail(#expr, __FILE__, __LINE__, __FUNCTION_NAME))
+#define SANITY_CHECK(expr) \
+       ((expr) \
+       ? (void)(0) \
+       : sanity_check_fn(#expr, __FILE__, __LINE__, __FUNCTION_NAME))
+
+#define sanity_check(expr) SANITY_CHECK(expr)
 
-#define assert(expr) ASSERT(expr)
 
 void debug_set_exception_handler();
 
index 60a26e65fe10e2a08fa4eb7f7173a1df014eaea5..f75e7a0b78fe2606909312876a1eb60377f18d57 100644 (file)
@@ -77,9 +77,9 @@ void Environment::addPlayer(Player *player)
        */
        // If peer id is non-zero, it has to be unique.
        if(player->peer_id != 0)
-               assert(getPlayer(player->peer_id) == NULL);
+               FATAL_ERROR_IF(getPlayer(player->peer_id) != NULL, "Peer id not unique");
        // Name has to be unique.
-       assert(getPlayer(player->getName()) == NULL);
+       FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique");
        // Add.
        m_players.push_back(player);
 }
@@ -926,7 +926,7 @@ void ServerEnvironment::clearAllObjects()
                        i != loaded_blocks.end(); ++i) {
                v3s16 p = *i;
                MapBlock *block = m_map->getBlockNoCreateNoEx(p);
-               assert(block);
+               assert(block != NULL);
                block->refGrab();
        }
 
@@ -1295,7 +1295,7 @@ u16 getFreeServerActiveObjectId(
 
 u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
 {
-       assert(object);
+       assert(object); // Pre-condition
        m_added_objects++;
        u16 id = addActiveObjectRaw(object, true, 0);
        return id;
@@ -1473,7 +1473,7 @@ ActiveObjectMessage ServerEnvironment::getActiveObjectMessage()
 u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object,
                bool set_changed, u32 dtime_s)
 {
-       assert(object);
+       assert(object); // Pre-condition
        if(object->getId() == 0){
                u16 new_id = getFreeServerActiveObjectId(m_active_objects);
                if(new_id == 0)
@@ -2051,7 +2051,8 @@ void ClientEnvironment::addPlayer(Player *player)
                It is a failure if player is local and there already is a local
                player
        */
-       assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
+       FATAL_ERROR_IF(player->isLocal() == true && getLocalPlayer() != NULL,
+               "Player is local but there is already a local player");
 
        Environment::addPlayer(player);
 }
@@ -2439,7 +2440,7 @@ u16 getFreeClientActiveObjectId(
 
 u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
 {
-       assert(object);
+       assert(object); // Pre-condition
        if(object->getId() == 0)
        {
                u16 new_id = getFreeClientActiveObjectId(m_active_objects);
index 3b82a3c470ff82cec67702f4940eb40f9ff95b54..fa30b403813795a15ce3662d9117e835e63f046a 100644 (file)
@@ -55,9 +55,9 @@ FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) :
                m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED;
        }
 
-       assert(m_settings != NULL);
-       assert(m_env != NULL);
-       assert(m_env->getSkin() != NULL);
+       assert(m_settings != NULL); // pre-condition
+       assert(m_env != NULL); // pre-condition
+       assert(m_env->getSkin() != NULL); // pre-condition
 
        m_currentMode = FM_Simple;
 
@@ -172,7 +172,7 @@ unsigned int FontEngine::getTextHeight(unsigned int font_size, FontMode mode)
        if (font == NULL) {
                font = m_env->getSkin()->getFont();
        }
-       assert(font != NULL);
+       FATAL_ERROR_IF(font == NULL, "Could not get skin font");
 
        return font->getDimension(L"Some unimportant example String").Height;
 }
@@ -187,7 +187,7 @@ unsigned int FontEngine::getTextWidth(const std::wstring& text,
        if (font == NULL) {
                font = m_env->getSkin()->getFont();
        }
-       assert(font != NULL);
+       FATAL_ERROR_IF(font == NULL, "Could not get font");
 
        return font->getDimension(text.c_str()).Width;
 }
@@ -202,7 +202,7 @@ unsigned int FontEngine::getLineHeight(unsigned int font_size, FontMode mode)
        if (font == NULL) {
                font = m_env->getSkin()->getFont();
        }
-       assert(font != NULL);
+       FATAL_ERROR_IF(font == NULL, "Could not get font");
 
        return font->getDimension(L"Some unimportant example String").Height
                        + font->getKerningHeight();
@@ -255,7 +255,7 @@ void FontEngine::updateSkin()
 
        // If we did fail to create a font our own make irrlicht find a default one
        font = m_env->getSkin()->getFont();
-       assert(font);
+       FATAL_ERROR_IF(font == NULL, "Could not create/get font");
 
        u32 text_height = font->getDimension(L"Hello, world!").Height;
        infostream << "text_height=" << text_height << std::endl;
@@ -355,7 +355,7 @@ void FontEngine::initFont(unsigned int basesize, FontMode mode)
 /** initialize a font without freetype */
 void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode)
 {
-       assert((mode == FM_Simple) || (mode == FM_SimpleMono));
+       assert(mode == FM_Simple || mode == FM_SimpleMono); // pre-condition
 
        std::string font_path = "";
        if (mode == FM_Simple) {
index be8d4e6795a5e5b89356990428446f9ebf78bc16..7b6d2a3c19d6f0305f1dce3a7adaad7cbc14d5dc 100644 (file)
@@ -3112,7 +3112,7 @@ void Game::processClientEvents(CameraOrientation *cam, float *damage_flash)
 
                        u32 new_id = player->addHud(e);
                        //if this isn't true our huds aren't consistent
-                       assert(new_id == id);
+                       sanity_check(new_id == id);
 
                        delete event.hudadd.pos;
                        delete event.hudadd.name;
index b45011c2c4237638766e6dd7dd9e953e426bae39..dbb6fdf92396bdb0c5ba2927d5acc205012ba94a 100644 (file)
@@ -304,7 +304,7 @@ void GUIEngine::run()
 GUIEngine::~GUIEngine()
 {
        video::IVideoDriver* driver = m_device->getVideoDriver();
-       assert(driver != 0);
+       FATAL_ERROR_IF(driver == 0, "Could not get video driver");
 
        if(m_sound_manager != &dummySoundManager){
                delete m_sound_manager;
@@ -514,7 +514,7 @@ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath,
                bool tile_image, unsigned int minsize)
 {
        video::IVideoDriver* driver = m_device->getVideoDriver();
-       assert(driver != 0);
+       FATAL_ERROR_IF(driver == 0, "Could not get video driver");
 
        if (m_textures[layer].texture != NULL)
        {
index 581da894b4cb412e2c3e7328be4fb26115c849d5..300eaf80cb7a7626bf0c4250a5aa6244416de921 100644 (file)
@@ -1973,7 +1973,7 @@ void GUIFormSpecMenu::regenerateGui(v2u32 screensize)
        m_tooltip_element->setOverrideFont(m_font);
 
        gui::IGUISkin* skin = Environment->getSkin();
-       assert(skin != NULL);
+       sanity_check(skin != NULL);
        gui::IGUIFont *old_font = skin->getFont();
        skin->setFont(m_font);
 
@@ -2217,9 +2217,9 @@ void GUIFormSpecMenu::drawSelectedItem()
        video::IVideoDriver* driver = Environment->getVideoDriver();
 
        Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
-       assert(inv);
+       sanity_check(inv);
        InventoryList *list = inv->getList(m_selected_item->listname);
-       assert(list);
+       sanity_check(list);
        ItemStack stack = list->getItem(m_selected_item->i);
        stack.count = m_selected_amount;
 
@@ -2239,7 +2239,7 @@ void GUIFormSpecMenu::drawMenu()
        }
 
        gui::IGUISkin* skin = Environment->getSkin();
-       assert(skin != NULL);
+       sanity_check(skin != NULL);
        gui::IGUIFont *old_font = skin->getFont();
        skin->setFont(m_font);
 
@@ -2725,7 +2725,7 @@ bool GUIFormSpecMenu::preprocessEvent(const SEvent& event)
                if (hovered && isMyChild(hovered) &&
                                hovered->getType() == gui::EGUIET_TAB_CONTROL) {
                        gui::IGUISkin* skin = Environment->getSkin();
-                       assert(skin != NULL);
+                       sanity_check(skin != NULL);
                        gui::IGUIFont *old_font = skin->getFont();
                        skin->setFont(m_font);
                        bool retval = hovered->OnEvent(event);
@@ -3013,7 +3013,7 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
                                break;
                                default:
                                        //can't happen at all!
-                                       assert("reached a source line that can't ever been reached" == 0);
+                                       FATAL_ERROR("Reached a source line that can't ever been reached");
                                        break;
                        }
                        if (current_keys_pending.key_enter && m_allowclose) {
@@ -3047,8 +3047,8 @@ bool GUIFormSpecMenu::OnEvent(const SEvent& event)
 
                if(m_selected_item) {
                        inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
-                       assert(inv_selected);
-                       assert(inv_selected->getList(m_selected_item->listname) != NULL);
+                       sanity_check(inv_selected);
+                       sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
                }
 
                u32 s_count = 0;
index 9b5a31d267368dd2ca7e16ac41664ca7cdd11eb0..3ddb3f5d9e21a99bf6ee5a1899b2c8738498b201 100644 (file)
@@ -303,7 +303,7 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
 
                // But go on
                {
-                       key_setting *k=NULL;
+                       key_setting *k = NULL;
                        for(size_t i = 0; i < key_settings.size(); i++)
                        {
                                if(key_settings.at(i)->id == activeKey)
@@ -312,7 +312,7 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
                                        break;
                                }
                        }
-                       assert(k);
+                       FATAL_ERROR_IF(k == NULL, "Key setting not found");
                        k->key = kp;
                        const wchar_t *text = wgettext(k->key.name());
                        k->button->setText(text);
@@ -364,7 +364,7 @@ bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
                                                        break;
                                                }
                                        }
-                                       assert(k);
+                                       FATAL_ERROR_IF(k == NULL, "Key setting not found");
 
                                        resetMenu();
                                        shift_down = false;
index e6886f6524f32baa85e2dbff1375cee60863098a..40ad92da3dad98f3b3c7fb5f1ccd9f6b078cf0e9 100644 (file)
@@ -81,7 +81,7 @@ unsigned long httpfetch_caller_alloc()
                }
        }
 
-       assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
+       FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
        return discard;
 }
 
@@ -633,7 +633,7 @@ protected:
                        return NULL;
                }
 
-               assert(m_all_ongoing.empty());
+               FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
 
                while (!StopRequested()) {
                        BEGIN_DEBUG_EXCEPTION_HANDLER
@@ -714,7 +714,7 @@ void httpfetch_init(int parallel_limit)
                        <<std::endl;
 
        CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
-       assert(res == CURLE_OK);
+       FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
 
        g_httpfetch_thread = new CurlFetchThread(parallel_limit);
 }
index 3fa31965c5bf65ae28c51b8eb4bc76da4cf61002..7941b3a2a7d3fbee314fbd2f4e12f2992d4f4fb1 100644 (file)
@@ -620,13 +620,13 @@ u32 InventoryList::getFreeSlots() const
 
 const ItemStack& InventoryList::getItem(u32 i) const
 {
-       assert(i < m_size);
+       assert(i < m_size); // Pre-condition
        return m_items[i];
 }
 
 ItemStack& InventoryList::getItem(u32 i)
 {
-       assert(i < m_size);
+       assert(i < m_size); // Pre-condition
        return m_items[i];
 }
 
@@ -643,7 +643,7 @@ ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
 
 void InventoryList::deleteItem(u32 i)
 {
-       assert(i < m_items.size());
+       assert(i < m_items.size()); // Pre-condition
        m_items[i].clear();
 }
 
index e4a97e1d37353f79f98b7eb5481be60c93cd49ca..faaa5ef95a450469c138d3e2c1c18ea215d0413e 100644 (file)
@@ -71,7 +71,7 @@ struct ItemStack
 
        void remove(u16 n)
        {
-               assert(count >= n);
+               assert(count >= n); // Pre-condition
                count -= n;
                if(count == 0)
                        clear(); // reset name, wear and metadata too
index ed18126d0dc8538fcb9e0349f15229662ffd090d..26cabc25f078a95a8a2d461f07c0645d2f0b2a32 100644 (file)
@@ -62,7 +62,7 @@ void InventoryLocation::serialize(std::ostream &os) const
                os<<"detached:"<<name;
                break;
        default:
-               assert(0);
+               FATAL_ERROR("Unhandled inventory location type");
        }
 }
 
index 381773bb4b1e3c95a6a16d408556dd91238b7e2d..65ba356f4e1d8b33be9cbf49f2ca74f6e69a9e67 100644 (file)
@@ -321,7 +321,7 @@ public:
                                <<name<<"\""<<std::endl;
 
                // This is not thread-safe
-               assert(get_current_thread_id() == m_main_thread);
+               sanity_check(get_current_thread_id() == m_main_thread);
 
                // Skip if already in cache
                ClientCached *cc = NULL;
@@ -544,7 +544,7 @@ public:
                verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
                // Ensure that the "" item (the hand) always has ToolCapabilities
                if(def.name == "")
-                       assert(def.tool_capabilities != NULL);
+                       FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
 
                if(m_item_definitions.count(def.name) == 0)
                        m_item_definitions[def.name] = new ItemDefinition(def);
index 27d0b6d500eb3fefd419df387d0f07bc540db361..d9fc88934cfc4da3a7c2505f206827f132eb2762 100644 (file)
@@ -263,7 +263,8 @@ KeyPress::KeyPress(const char *name)
                        m_name = name;
                        if (strlen(name) > 8 && strncmp(name, "KEY_KEY_", 8) == 0) {
                                int chars_read = mbtowc(&Char, name + 8, 1);
-                               assert (chars_read == 1 && "unexpected multibyte character");
+
+                               FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character");
                        } else
                                Char = L'\0';
                        return;
@@ -275,7 +276,8 @@ KeyPress::KeyPress(const char *name)
                try {
                        Key = keyname_to_keycode(m_name.c_str());
                        int chars_read = mbtowc(&Char, name, 1);
-                       assert (chars_read == 1 && "unexpected multibyte character");
+
+                       FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character");
                        return;
                } catch (UnknownKeycode &e) {};
        }
@@ -285,7 +287,7 @@ KeyPress::KeyPress(const char *name)
        Key = irr::KEY_KEY_CODES_COUNT;
 
        int mbtowc_ret = mbtowc(&Char, name, 1);
-       assert (mbtowc_ret == 1 && "unexpected multibyte character");
+       FATAL_ERROR_IF(mbtowc_ret != 1, "Unexpected multibyte character");
        m_name = name[0];
 }
 
index cb183947a74d3108f74fddaace3396654768ec8b..55578422e8a2fea792e26b56dd2f537dd8124f68 100644 (file)
@@ -172,7 +172,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d,
        f32 d = 0.15*BS;
 
        // This should always apply, otherwise there are glitches
-       assert(d > pos_max_d);
+       sanity_check(d > pos_max_d);
 
        // Maximum distance over border for sneaking
        f32 sneak_max = BS*0.4;
index 2a4a9dfc74c2f95c26baadf0bd92e53b4e85487e..b60e156be30b05ed4a8b2952d994f1bcf3b8d7bf 100644 (file)
@@ -78,7 +78,7 @@ public:
        }
 
        void setCAO(GenericCAO* toset) {
-               assert( m_cao == NULL );
+               assert( m_cao == NULL ); // Pre-condition
                m_cao = toset;
        }
 
index a01ddec93f80e69079806cb60d55cc157177f827..d84a09f7616e3dd2edc18d6c14ef540c8a19b7a2 100644 (file)
@@ -273,7 +273,7 @@ int main(int argc, char *argv[])
        if (!game_configure(&game_params, cmd_args))
                return 1;
 
-       assert(game_params.world_path != "");
+       sanity_check(game_params.world_path != "");
 
        infostream << "Using commanded world path ["
                   << game_params.world_path << "]" << std::endl;
@@ -549,7 +549,7 @@ static void startup_message()
 static bool read_config_file(const Settings &cmd_args)
 {
        // Path of configuration file in use
-       assert(g_settings_path == "");  // Sanity check
+       sanity_check(g_settings_path == "");    // Sanity check
 
        if (cmd_args.exists("config")) {
                bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
@@ -748,7 +748,7 @@ static bool auto_select_world(GameParams *game_params)
                           << world_path << "]" << std::endl;
        }
 
-       assert(world_path != "");
+       assert(world_path != "");       // Post-condition
        game_params->world_path = world_path;
        return true;
 }
@@ -804,7 +804,7 @@ static bool determine_subgame(GameParams *game_params)
 {
        SubgameSpec gamespec;
 
-       assert(game_params->world_path != "");  // pre-condition
+       assert(game_params->world_path != "");  // Pre-condition
 
        verbosestream << _("Determining gameid/gamespec") << std::endl;
        // If world doesn't exist
index e80c8252276055cc0fa71d168874c476bb05bcbe..14a237c0a822688694206de7349db885a7c4ea06 100644 (file)
@@ -767,8 +767,7 @@ void Map::updateLighting(enum LightBank bank,
                        }
                        else
                        {
-                               // Invalid lighting bank
-                               assert(0);
+                               assert("Invalid lighting bank" == NULL);
                        }
 
                        /*infostream<<"Bottom for sunlight-propagated block ("
@@ -783,7 +782,7 @@ void Map::updateLighting(enum LightBank bank,
                        }
                        catch(InvalidPositionException &e)
                        {
-                               assert(0);
+                               FATAL_ERROR("Invalid position");
                        }
 
                }
@@ -1220,7 +1219,7 @@ void Map::removeNodeAndUpdate(v3s16 p,
                        n.setLight(LIGHTBANK_DAY, 0, ndef);
                        setNode(p, n);
                } else {
-                       assert(0);
+                       FATAL_ERROR("Invalid position");
                }
        }
 
@@ -2180,7 +2179,7 @@ bool ServerMap::initBlockMake(BlockMakeData *data, v3s16 blockpos)
                        v2s16 sectorpos(x, z);
                        // Sector metadata is loaded from disk if not already loaded.
                        ServerMapSector *sector = createSector(sectorpos);
-                       assert(sector);
+                       FATAL_ERROR_IF(sector == NULL, "createSector() failed");
                        (void) sector;
 
                        for(s16 y=blockpos_min.Y-extra_borders.Y;
@@ -2628,7 +2627,7 @@ MapBlock * ServerMap::createBlock(v3s16 p)
                      lighting on blocks for them.
        */
        ServerMapSector *sector;
-       try{
+       try {
                sector = (ServerMapSector*)createSector(p2d);
                assert(sector->getId() == MAPSECTOR_SERVER);
        }
@@ -2861,9 +2860,10 @@ v2s16 ServerMap::getSectorPos(std::string dirname)
        }
        else
        {
-               assert(false);
+               r = -1;
        }
-       assert(r == 2);
+
+       FATAL_ERROR_IF(r != 2, "getSectorPos()");
        v2s16 pos((s16)x, (s16)y);
        return pos;
 }
@@ -3368,7 +3368,7 @@ void ServerMap::loadBlock(std::string sectordir, std::string blockfile,
                                <<"what()="<<e.what()
                                <<std::endl;
                                // Ignoring. A new one will be generated.
-               assert(0);
+               abort();
 
                // TODO: Backup file; name is in fullpath.
        }
@@ -3438,7 +3438,6 @@ void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool
                                        <<"(ignore_world_load_errors)"<<std::endl;
                } else {
                        throw SerializationError("Invalid block data in database");
-                       //assert(0);
                }
        }
 }
index a4fd8406b1d52420305899c5dc7a71170a8c25d9..325a02e6044af5d1463e063f1b6a493573ecfe78 100644 (file)
--- a/src/map.h
+++ b/src/map.h
@@ -263,15 +263,15 @@ public:
        //bool updateChangedVisibleArea();
 
        // Call these before and after saving of many blocks
-       virtual void beginSave() {return;};
-       virtual void endSave() {return;};
+       virtual void beginSave() { return; }
+       virtual void endSave() { return; }
 
-       virtual void save(ModifiedState save_level){assert(0);};
+       virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
 
        // Server implements these.
        // Client leaves them as no-op.
-       virtual bool saveBlock(MapBlock *block) { return false; };
-       virtual bool deleteBlock(v3s16 blockpos) { return false; };
+       virtual bool saveBlock(MapBlock *block) { return false; }
+       virtual bool deleteBlock(v3s16 blockpos) { return false; }
 
        /*
                Updates usage timers and unloads unused blocks and sectors.
index a05b7a4da4d7a51616372f305e15e624d11edc51..ca80c39d71cae6d55d9f2a49cccbdccdc2ebeb18 100644 (file)
@@ -521,7 +521,7 @@ void MapBlock::serialize(std::ostream &os, u8 version, bool disk)
                throw SerializationError("ERROR: Not writing dummy block.");
        }
 
-       assert(version >= SER_FMT_CLIENT_VER_LOWEST);
+       FATAL_ERROR_IF(version < SER_FMT_CLIENT_VER_LOWEST, "Serialize version error");
 
        // First byte
        u8 flags = 0;
index 76ba94c3437baa9653f5b77428f0db0009ff2749..3c0ae9cd769e4b2e867f74bf144ceb5933cf8fc3 100644 (file)
@@ -140,7 +140,7 @@ public:
        }
        void unDummify()
        {
-               assert(isDummy());
+               assert(isDummy()); // Pre-condition
                reallocate();
        }
        
index 5f81aba98d39b7c8d6bedc7ed757fd9839de4274..acf811dea4e332ef4a605e5283a6de443156670e 100644 (file)
@@ -62,6 +62,7 @@ MapgenSinglenode::~MapgenSinglenode()
 
 void MapgenSinglenode::makeChunk(BlockMakeData *data)
 {
+       // Pre-conditions
        assert(data->vmanip);
        assert(data->nodedef);
        assert(data->blockpos_requested.X >= data->blockpos_min.X &&
index 34484c7e5e0229bab179cc8a8851b6aa0c7ee11e..ffd16477440009db3da0af70f5e54c746835afdb 100644 (file)
@@ -201,6 +201,7 @@ int MapgenV5::getGroundLevelAtPoint(v2s16 p)
 
 void MapgenV5::makeChunk(BlockMakeData *data)
 {
+       // Pre-conditions
        assert(data->vmanip);
        assert(data->nodedef);
        assert(data->blockpos_requested.X >= data->blockpos_min.X &&
index 8ea4cd21dea0e861c766d7b5dceab84210395c8f..b7bfaef0c04158b02da9327bdce5b5f6c763b09b 100644 (file)
@@ -430,6 +430,7 @@ u32 MapgenV6::get_blockseed(u64 seed, v3s16 p)
 
 void MapgenV6::makeChunk(BlockMakeData *data)
 {
+       // Pre-conditions
        assert(data->vmanip);
        assert(data->nodedef);
        assert(data->blockpos_requested.X >= data->blockpos_min.X &&
index 21ee967c69080d2ecd7fccbf5b8260d825c60731..923f85a0fa96e3e4e57fc5026226798b2166d238 100644 (file)
@@ -212,6 +212,7 @@ int MapgenV7::getGroundLevelAtPoint(v2s16 p)
 
 void MapgenV7::makeChunk(BlockMakeData *data)
 {
+       // Pre-conditions
        assert(data->vmanip);
        assert(data->nodedef);
        assert(data->blockpos_requested.X >= data->blockpos_min.X &&
index 44525b6443a687a97be728f85bb8eb12196639a9..0335755e99a5345c1c97d3562d300b7d4b758334 100644 (file)
@@ -71,7 +71,7 @@ void MapNode::setLight(enum LightBank bank, u8 a_light, INodeDefManager *nodemgr
                param1 |= (a_light & 0x0f)<<4;
        }
        else
-               assert(0);
+               assert("Invalid light bank" == NULL);
 }
 
 bool MapNode::isLightDayNightEq(INodeDefManager *nodemgr) const
@@ -516,8 +516,8 @@ void MapNode::serializeBulk(std::ostream &os, int version,
        if(!ser_ver_supported(version))
                throw VersionMismatchException("ERROR: MapNode format not supported");
 
-       assert(content_width == 2);
-       assert(params_width == 2);
+       sanity_check(content_width == 2);
+       sanity_check(params_width == 2);
 
        // Can't do this anymore; we have 16-bit dynamically allocated node IDs
        // in memory; conversion just won't work in this direction.
@@ -563,9 +563,10 @@ void MapNode::deSerializeBulk(std::istream &is, int version,
        if(!ser_ver_supported(version))
                throw VersionMismatchException("ERROR: MapNode format not supported");
 
-       assert(version >= 22);
-       assert(content_width == 1 || content_width == 2);
-       assert(params_width == 2);
+       if (version < 22
+                       || (content_width != 1 && content_width != 2)
+                       || params_width != 2)
+               FATAL_ERROR("Deserialize bulk node data error");
 
        // Uncompress or read data
        u32 len = nodecount * (content_width + params_width);
index 7bc4bd3a36216886ff436d497e96becd5f679e29..3fe81dc902e13c943b9af7e990ff5e082d4cd75f 100644 (file)
@@ -85,7 +85,7 @@ MapBlock * MapSector::getBlockNoCreateNoEx(s16 y)
 
 MapBlock * MapSector::createBlankBlockNoInsert(s16 y)
 {
-       assert(getBlockBuffered(y) == NULL);
+       assert(getBlockBuffered(y) == NULL);    // Pre-condition
 
        v3s16 blockpos_map(m_pos.X, y, m_pos.Y);
        
index a3404e2dc3ee23422c3d3911dc8b6f1a4a9f0312..a05e372e51c43e6e3908cc3ddf4bc80b5d2e5333 100644 (file)
@@ -159,7 +159,7 @@ void Schematic::blitToVManip(v3s16 p, MMVManip *vm, Rotation rot,
 void Schematic::placeStructure(Map *map, v3s16 p, u32 flags, Rotation rot,
        bool force_placement, INodeDefManager *ndef)
 {
-       assert(schemdata != NULL);
+       assert(schemdata != NULL); // Pre-condition
        MMVManip *vm = new MMVManip(map);
 
        if (rot == ROTATE_RAND)
index b73981ccca7a72f1419120665a6eb800fb8fbc8e..fb31a07f0d85d3362a1c898bf2796ac542a5d2c4 100644 (file)
@@ -312,16 +312,16 @@ BufferedPacket ReliablePacketBuffer::popSeqnum(u16 seqnum)
 void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
 {
        JMutexAutoLock listlock(m_list_mutex);
-       assert(p.data.getSize() >= BASE_HEADER_SIZE+3);
+       FATAL_ERROR_IF(p.data.getSize() < BASE_HEADER_SIZE+3, "Invalid data size");
        u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
-       assert(type == TYPE_RELIABLE);
+       sanity_check(type == TYPE_RELIABLE);
        u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
 
-       assert(seqnum_in_window(seqnum,next_expected,MAX_RELIABLE_WINDOW_SIZE));
-       assert(seqnum != next_expected);
+       sanity_check(seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE));
+       sanity_check(seqnum != next_expected);
 
        ++m_list_size;
-       assert(m_list_size <= SEQNUM_MAX+1);
+       sanity_check(m_list_size <= SEQNUM_MAX+1);      // FIXME: Handle the error?
 
        // Find the right place for the packet and insert it there
        // If list is empty, just add it
@@ -377,9 +377,9 @@ void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
                        throw IncomingDataCorruption("duplicated packet isn't same as original one");
                }
 
-               assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
-               assert(i->data.getSize() == p.data.getSize());
-               assert(i->address == p.address);
+               sanity_check(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
+               sanity_check(i->data.getSize() == p.data.getSize());
+               sanity_check(i->address == p.address);
 
                /* nothing to do this seems to be a resent packet */
                /* for paranoia reason data should be compared */
@@ -449,9 +449,9 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
 {
        JMutexAutoLock listlock(m_map_mutex);
        u32 headersize = BASE_HEADER_SIZE + 7;
-       assert(p.data.getSize() >= headersize);
+       FATAL_ERROR_IF(p.data.getSize() < headersize, "Invalid data size");
        u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
-       assert(type == TYPE_SPLIT);
+       sanity_check(type == TYPE_SPLIT);
        u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
        u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
        u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
@@ -898,7 +898,7 @@ void Peer::DecUseCount()
 {
        {
                JMutexAutoLock lock(m_exclusive_access_mutex);
-               assert(m_usage > 0);
+               sanity_check(m_usage > 0);
                m_usage--;
 
                if (!((m_pending_deletion) && (m_usage == 0)))
@@ -1085,7 +1085,7 @@ bool UDPPeer::processReliableSendCommand(
                                                        - BASE_HEADER_SIZE
                                                        - RELIABLE_HEADER_SIZE;
 
-       assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
+       sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
 
        std::list<SharedBuffer<u8> > originals;
        u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
@@ -1142,7 +1142,7 @@ bool UDPPeer::processReliableSendCommand(
                        channels[c.channelnum].queued_reliables.push(p);
                        pcount++;
                }
-               assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
+               sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
                return true;
        }
        else {
@@ -1160,7 +1160,7 @@ bool UDPPeer::processReliableSendCommand(
                                = channels[c.channelnum].putBackSequenceNumber(
                                        (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
 
-                       assert(successfully_put_back_sequence_number);
+                       FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
                }
                LOG(dout_con<<m_connection->getDesc()
                                << " Windowsize exceeded on reliable sending "
@@ -1212,13 +1212,13 @@ void UDPPeer::RunCommandQueues(
 
 u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
 {
-       assert(channel < CHANNEL_COUNT);
+       assert(channel < CHANNEL_COUNT); // Pre-condition
        return channels[channel].readNextIncomingSeqNum();
 }
 
 void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
 {
-       assert(channel < CHANNEL_COUNT);
+       assert(channel < CHANNEL_COUNT); // Pre-condition
        channels[channel].setNextSplitSeqNum(seqnum);
 }
 
@@ -1226,7 +1226,7 @@ SharedBuffer<u8> UDPPeer::addSpiltPacket(u8 channel,
                                                                                        BufferedPacket toadd,
                                                                                        bool reliable)
 {
-       assert(channel < CHANNEL_COUNT);
+       assert(channel < CHANNEL_COUNT); // Pre-condition
        return channels[channel].incoming_splits.insert(toadd,reliable);
 }
 
@@ -1496,7 +1496,6 @@ void ConnectionSendThread::sendAsPacketReliable(BufferedPacket& p, Channel* chan
                LOG(derr_con<<m_connection->getDesc()
                                <<"WARNING: Going to send a reliable packet"
                                <<" in outgoing buffer" <<std::endl);
-               //assert(0);
        }
 
        // Send the packet
@@ -1511,7 +1510,7 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
                LOG(dout_con<<m_connection->getDesc()
                                <<" INFO: dropped packet for non existent peer_id: "
                                << peer_id << std::endl);
-               assert(reliable && "trying to send raw packet reliable but no peer found!");
+               FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
                return false;
        }
        Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
@@ -1582,7 +1581,7 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
 
 void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
 {
-       assert(c.reliable);
+       assert(c.reliable);  // Pre-condition
 
        switch(c.type) {
        case CONNCMD_NONE:
@@ -1626,7 +1625,7 @@ void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
        case CONNCMD_CONNECT:
        case CONNCMD_DISCONNECT:
        case CONCMD_ACK:
-               assert("Got command that shouldn't be reliable as reliable command" == 0);
+               FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
        default:
                LOG(dout_con<<m_connection->getDesc()
                                <<" Invalid reliable command type: " << c.type <<std::endl);
@@ -1636,7 +1635,7 @@ void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
 
 void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
 {
-       assert(!c.reliable);
+       assert(!c.reliable); // Pre-condition
 
        switch(c.type) {
        case CONNCMD_NONE:
@@ -1680,7 +1679,7 @@ void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
                sendAsPacket(c.peer_id,c.channelnum,c.data,true);
                return;
        case CONCMD_CREATE_PEER:
-               assert("Got command that should be reliable as unreliable command" == 0);
+               FATAL_ERROR("Got command that should be reliable as unreliable command");
        default:
                LOG(dout_con<<m_connection->getDesc()
                                <<" Invalid command type: " << c.type <<std::endl);
@@ -1778,7 +1777,7 @@ void ConnectionSendThread::disconnect_peer(u16 peer_id)
 void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
                SharedBuffer<u8> data)
 {
-       assert(channelnum < CHANNEL_COUNT);
+       assert(channelnum < CHANNEL_COUNT); // Pre-condition
 
        PeerHelper peer = m_connection->getPeerNoEx(peer_id);
        if (!peer)
@@ -2331,7 +2330,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
 
        if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
                errorstream << "Something is wrong with peer_id" << std::endl;
-               assert(0);
+               FATAL_ERROR("");
        }
 
        if (type == TYPE_CONTROL)
@@ -2343,7 +2342,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
 
                if (controltype == CONTROLTYPE_ACK)
                {
-                       assert(channel != 0);
+                       FATAL_ERROR_IF(channel == 0, "Invalid channel (0)");
                        if (packetdata.getSize() < 4)
                                throw InvalidIncomingDataException
                                                ("packetdata.getSize() < 4 (ACK header size)");
@@ -2511,7 +2510,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
        }
        else if (type == TYPE_RELIABLE)
        {
-               assert(channel != 0);
+               FATAL_ERROR_IF(channel == 0, "Invalid channel (0)");
                // Recursive reliable packets not allowed
                if (reliable)
                        throw InvalidIncomingDataException("Found nested reliable packets");
@@ -2635,10 +2634,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
        }
 
        // We should never get here.
-       // If you get here, add an exception or a return to some of the
-       // above conditionals.
-       assert(0);
-       throw BaseException("Error in Channel::ProcessPacket()");
+       FATAL_ERROR("Invalid execution point");
 }
 
 /*
@@ -2724,7 +2720,7 @@ Connection::~Connection()
 /* Internal stuff */
 void Connection::putEvent(ConnectionEvent &e)
 {
-       assert(e.type != CONNEVENT_NONE);
+       assert(e.type != CONNEVENT_NONE); // Pre-condition
        m_event_queue.push_back(e);
 }
 
@@ -2738,7 +2734,7 @@ PeerHelper Connection::getPeer(u16 peer_id)
        }
 
        // Error checking
-       assert(node->second->id == peer_id);
+       FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
 
        return PeerHelper(node->second);
 }
@@ -2753,7 +2749,7 @@ PeerHelper Connection::getPeerNoEx(u16 peer_id)
        }
 
        // Error checking
-       assert(node->second->id == peer_id);
+       FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
 
        return PeerHelper(node->second);
 }
@@ -2925,7 +2921,7 @@ u32 Connection::Receive(u16 &peer_id, SharedBuffer<u8> &data)
 void Connection::Send(u16 peer_id, u8 channelnum,
                NetworkPacket* pkt, bool reliable)
 {
-       assert(channelnum < CHANNEL_COUNT);
+       assert(channelnum < CHANNEL_COUNT); // Pre-condition
 
        ConnectionCommand c;
 
@@ -2955,9 +2951,7 @@ float Connection::getLocalStat(rate_stat_type type)
 {
        PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
 
-       if (!peer) {
-               assert("Connection::getLocalStat we couldn't get our own peer? are you serious???" == 0);
-       }
+       FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
 
        float retval = 0.0;
 
@@ -2982,7 +2976,7 @@ float Connection::getLocalStat(rate_stat_type type)
                                retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
                                break;
                default:
-                       assert("Connection::getLocalStat Invalid stat type" == 0);
+                       FATAL_ERROR("Connection::getLocalStat Invalid stat type");
                }
        }
        return retval;
@@ -3075,7 +3069,7 @@ void Connection::DisconnectPeer(u16 peer_id)
 
 void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
 {
-       assert(channelnum < CHANNEL_COUNT);
+       assert(channelnum < CHANNEL_COUNT); // Pre-condition
 
        LOG(dout_con<<getDesc()
                        <<" Queuing ACK command to peer_id: " << peer_id <<
index 77d7edac0d3711d0f15a61e0623b228631c25f32..33b7d0f7f8ef144c8dc75397dbff8832299a18af 100644 (file)
@@ -681,7 +681,7 @@ class Peer {
 
                virtual ~Peer() {
                        JMutexAutoLock usage_lock(m_exclusive_access_mutex);
-                       assert(m_usage == 0);
+                       FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
                };
 
                // Unique id of the peer
@@ -926,7 +926,7 @@ public:
        void Trigger();
 
        void setParent(Connection* parent) {
-               assert(parent != NULL);
+               assert(parent != NULL); // Pre-condition
                m_connection = parent;
        }
 
@@ -980,7 +980,7 @@ public:
        void * Thread       ();
 
        void setParent(Connection* parent) {
-               assert(parent != NULL);
+               assert(parent != NULL); // Pre-condition
                m_connection = parent;
        }
 
index 82f8b61b7244fb5f476bba443b0054c64c8c0cad..69f39d1f354f699968779542fedfef0edcd685e4 100644 (file)
@@ -476,7 +476,7 @@ void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt)
 
        // Mesh update thread must be stopped while
        // updating content definitions
-       assert(!m_mesh_update_thread.IsRunning());
+       sanity_check(!m_mesh_update_thread.IsRunning());
 
        for (u16 i = 0; i < num_files; i++) {
                std::string name, sha1_base64;
@@ -549,7 +549,7 @@ void Client::handleCommand_Media(NetworkPacket* pkt)
 
        // Mesh update thread must be stopped while
        // updating content definitions
-       assert(!m_mesh_update_thread.IsRunning());
+       sanity_check(!m_mesh_update_thread.IsRunning());
 
        for (u32 i=0; i < num_files; i++) {
                std::string name;
@@ -575,7 +575,7 @@ void Client::handleCommand_NodeDef(NetworkPacket* pkt)
 
        // Mesh update thread must be stopped while
        // updating content definitions
-       assert(!m_mesh_update_thread.IsRunning());
+       sanity_check(!m_mesh_update_thread.IsRunning());
 
        // Decompress node definitions
        std::string datastring(pkt->getString(0), pkt->getSize());
@@ -602,7 +602,7 @@ void Client::handleCommand_ItemDef(NetworkPacket* pkt)
 
        // Mesh update thread must be stopped while
        // updating content definitions
-       assert(!m_mesh_update_thread.IsRunning());
+       sanity_check(!m_mesh_update_thread.IsRunning());
 
        // Decompress item definitions
        std::string datastring(pkt->getString(0), pkt->getSize());
index 6cf456e4de241dafee70dea87144f0344b30c2b0..a0dcf6b71e21d734924721296abc756c4daec65f 100644 (file)
@@ -641,6 +641,7 @@ content_t CNodeDefManager::allocateId()
 // IWritableNodeDefManager
 content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
 {
+       // Pre-conditions
        assert(name != "");
        assert(name == def.name);
 
@@ -690,7 +691,7 @@ content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &d
 
 content_t CNodeDefManager::allocateDummy(const std::string &name)
 {
-       assert(name != "");
+       assert(name != "");     // Pre-condition
        ContentFeatures f;
        f.name = name;
        return set(name, f);
@@ -993,7 +994,9 @@ void CNodeDefManager::serialize(std::ostream &os, u16 protocol_version)
                f->serialize(wrapper_os, protocol_version);
                os2<<serializeString(wrapper_os.str());
 
-               assert(count + 1 > count); // must not overflow
+               // must not overflow
+               u16 next = count + 1;
+               FATAL_ERROR_IF(next < count, "Overflow");
                count++;
        }
        writeU16(os, count);
index 05c877b3237c6b0f66a90d0a0465792250094737..e59e73b233d14e99e70f02de2ea6e3d684e995df 100644 (file)
@@ -58,12 +58,12 @@ public:
                if (max-min > (PSEUDORANDOM_MAX + 1) / 10)
                {
                        //dstream<<"WARNING: PseudoRandom::range: max > 32767"<<std::endl;
-                       assert(0);
+                       assert("Something wrong with random number" == NULL);
                }
                if(min > max)
                {
-                       assert(0);
-                       return max;
+                       assert("Something wrong with random number" == NULL);
+                       //return max;
                }
                return (next()%(max-min+1))+min;
        }
index 435875233b45250368eae095f84292de4c56a0a2..4459b421a29477d2c1af770e8d040def196c6f34 100644 (file)
@@ -216,7 +216,7 @@ public:
        virtual PlayerSAO *getPlayerSAO()
        { return NULL; }
        virtual void setPlayerSAO(PlayerSAO *sao)
-       { assert(0); }
+       { FATAL_ERROR("FIXME"); }
 
        /*
                serialize() writes a bunch of text that can contain
index 8a685539b20d13cbaee599d3b01706a905ee3c85..6d0ab78c4ab2e547f961521950ac32b73fa567fb 100644 (file)
@@ -391,7 +391,7 @@ void initializePaths()
        //TODO: Test this code
        char buf[BUFSIZ];
        uint32_t len = sizeof(buf);
-       assert(_NSGetExecutablePath(buf, &len) != -1);
+       FATAL_ERROR_IF(_NSGetExecutablePath(buf, &len) == -1, "");
 
        pathRemoveFile(buf, '/');
 
@@ -411,7 +411,7 @@ void initializePaths()
        mib[1] = KERN_PROC;
        mib[2] = KERN_PROC_PATHNAME;
        mib[3] = -1;
-       assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
+       FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");
 
        pathRemoveFile(buf, '/');
 
@@ -446,13 +446,13 @@ void initializePaths()
        */
        #if defined(_WIN32)
 
-       const DWORD buflen = 1000;
+       const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
        char buf[buflen];
        DWORD len;
 
        // Find path of executable and set path_share relative to it
        len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
-       assert(len < buflen);
+       FATAL_ERROR_IF(len >= buflen, "Overlow");
        pathRemoveFile(buf, '\\');
 
        // Use ".\bin\.."
@@ -460,7 +460,7 @@ void initializePaths()
 
        // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
        len = GetEnvironmentVariable("APPDATA", buf, buflen);
-       assert(len < buflen);
+       FATAL_ERROR_IF(len >= buflen, "Overlow");
        path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
 
        /*
@@ -476,7 +476,7 @@ void initializePaths()
                if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
                        errorstream << "Unable to read bindir "<< std::endl;
 #ifndef __ANDROID__
-                       assert("Unable to read bindir" == 0);
+                       FATAL_ERROR("Unable to read bindir");
 #endif
                } else {
                        pathRemoveFile(buf, '/');
index f811dd5d31b545aaf73daed57d5be2ab5d0ec46a..61248534cf9594f3d48481f42be84297c5f77fca 100644 (file)
@@ -87,7 +87,7 @@ void script_error(lua_State *L)
 //     computed depending on mode
 void script_run_callbacks(lua_State *L, int nargs, RunCallbacksMode mode)
 {
-       assert(lua_gettop(L) >= nargs + 1);
+       FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
 
        // Insert error handler
        lua_pushcfunction(L, script_error_handler);
@@ -136,9 +136,7 @@ void log_deprecated(lua_State *L, std::string message)
                if (L != NULL) {
                        script_error(L);
                } else {
-                       /* As of april 2014 assert is not optimized to nop in release builds
-                        * therefore this is correct. */
-                       assert("Can't do a scripterror for this deprecated message, so exit completely!");
+                       FATAL_ERROR("Can't do a scripterror for this deprecated message, so exit completely!");
                }
        }
 
index de1ebc07b7faf22f52e148b1167da63c232e7714..eb1a2923af90b98b782ce4c5331d21435540aa68 100644 (file)
@@ -155,7 +155,7 @@ void AsyncEngine::step(lua_State *L, int errorhandler)
                lua_getfield(L, -1, "async_event_handler");
 
                if (lua_isnil(L, -1)) {
-                       assert("Async event handler does not exist!" == 0);
+                       FATAL_ERROR("Async event handler does not exist!");
                }
 
                luaL_checktype(L, -1, LUA_TFUNCTION);
@@ -237,7 +237,7 @@ AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
 /******************************************************************************/
 AsyncWorkerThread::~AsyncWorkerThread()
 {
-       assert(IsRunning() == false);
+       sanity_check(IsRunning() == false);
 }
 
 /******************************************************************************/
index 1f96373dc922e35bbbd47372a07c9a581b167442..71473d2154028259b2c2c43941def463c8ed645c 100644 (file)
@@ -72,7 +72,7 @@ ScriptApiBase::ScriptApiBase()
        #endif
 
        m_luastack = luaL_newstate();
-       assert(m_luastack);
+       FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
 
        luaL_openlibs(m_luastack);
 
index 1f1d8bffa04dfe25e3fa43e76158156836c1262c..840c3459506d416da0bac9c84702aed084cb1c5b 100644 (file)
@@ -49,7 +49,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
        scriptIface->realityCheck();
 
        lua_State *L = scriptIface->getStack();
-       assert(lua_checkstack(L, 20));
+       sanity_check(lua_checkstack(L, 20));
        StackUnroller stack_unroller(L);
 
        lua_pushcfunction(L, script_error_handler);
@@ -65,7 +65,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
        lua_pushnumber(L, m_id);
        lua_gettable(L, -2);
        if(lua_isnil(L, -1))
-               assert(0);
+               FATAL_ERROR("");
        lua_remove(L, -2); // Remove registered_abms
 
        // Call action
@@ -459,7 +459,7 @@ int ModApiEnvMod::l_set_timeofday(lua_State *L)
 
        // Do it
        float timeofday_f = luaL_checknumber(L, 1);
-       assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
+       sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
        int timeofday_mh = (int)(timeofday_f * 24000.0);
        // This should be set directly in the environment but currently
        // such changes aren't immediately sent to the clients, so call
index 2bed2a255f6f9383e2421035a03d334ec48afcc6..e6fcdcf8324471ea18fc0e8d466183d45f4abb2b 100644 (file)
@@ -90,7 +90,7 @@ int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid)
 int ModApiMainMenu::l_update_formspec(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        if (engine->m_startgame)
                return 0;
@@ -109,7 +109,7 @@ int ModApiMainMenu::l_update_formspec(lua_State *L)
 int ModApiMainMenu::l_start(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        //update c++ gamedata from lua table
 
@@ -134,7 +134,7 @@ int ModApiMainMenu::l_start(lua_State *L)
 int ModApiMainMenu::l_close(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        engine->m_kill = true;
        return 0;
@@ -144,7 +144,7 @@ int ModApiMainMenu::l_close(lua_State *L)
 int ModApiMainMenu::l_set_background(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        std::string backgroundlevel(luaL_checkstring(L, 1));
        std::string texturename(luaL_checkstring(L, 2));
@@ -189,7 +189,7 @@ int ModApiMainMenu::l_set_background(lua_State *L)
 int ModApiMainMenu::l_set_clouds(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        bool value = lua_toboolean(L,1);
 
@@ -209,7 +209,7 @@ int ModApiMainMenu::l_get_textlist_index(lua_State *L)
 int ModApiMainMenu::l_get_table_index(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        std::wstring tablename(narrow_to_wide(luaL_checkstring(L, 1)));
        GUITable *table = engine->m_menu->getTable(tablename);
@@ -617,7 +617,7 @@ int ModApiMainMenu::l_delete_favorite(lua_State *L)
 int ModApiMainMenu::l_show_keys_menu(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        GUIKeyChangeMenu *kmenu
                = new GUIKeyChangeMenu( engine->m_device->getGUIEnvironment(),
@@ -692,7 +692,7 @@ int ModApiMainMenu::l_delete_world(lua_State *L)
 int ModApiMainMenu::l_set_topleft_text(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        std::string text = "";
 
@@ -843,7 +843,7 @@ int ModApiMainMenu::l_copy_dir(lua_State *L)
 int ModApiMainMenu::l_extract_zip(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);(engine != 0);
 
        const char *zipfile     = luaL_checkstring(L, 1);
        const char *destination = luaL_checkstring(L, 2);
@@ -860,7 +860,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L)
                        return 1;
                }
 
-               assert(fs->getFileArchiveCount() > 0);
+               sanity_check(fs->getFileArchiveCount() > 0);
 
                /**********************************************************************/
                /* WARNING this is not threadsafe!!                                   */
@@ -931,7 +931,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L)
 int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        lua_pushstring(L,engine->getScriptDir().c_str());
        return 1;
@@ -963,7 +963,7 @@ bool ModApiMainMenu::isMinetestPath(std::string path)
 int ModApiMainMenu::l_show_file_open_dialog(lua_State *L)
 {
        GUIEngine* engine = getGuiEngine(L);
-       assert(engine != 0);
+       sanity_check(engine != NULL);
 
        const char *formname= luaL_checkstring(L, 1);
        const char *title       = luaL_checkstring(L, 2);
@@ -1118,8 +1118,8 @@ int ModApiMainMenu::l_do_async_callback(lua_State *L)
 
        const char* serialized_param_raw = luaL_checklstring(L, 2, &param_length);
 
-       assert(serialized_func_raw != NULL);
-       assert(serialized_param_raw != NULL);
+       sanity_check(serialized_func_raw != NULL);
+       sanity_check(serialized_param_raw != NULL);
 
        std::string serialized_func = std::string(serialized_func_raw, func_length);
        std::string serialized_param = std::string(serialized_param_raw, param_length);
index 09884f1bc0aa6ea7cb5c370545e5558606e53f2c..de23820dde3c6842bec58c9f5fe25ab63803bfc9 100644 (file)
@@ -1306,7 +1306,7 @@ Inventory* Server::getInventory(const InventoryLocation &loc)
        }
                break;
        default:
-               assert(0);
+               sanity_check(false); // abort
                break;
        }
        return NULL;
@@ -1345,7 +1345,7 @@ void Server::setInventoryModified(const InventoryLocation &loc)
        }
                break;
        default:
-               assert(0);
+               sanity_check(false); // abort
                break;
        }
 }
@@ -1454,7 +1454,7 @@ void Server::handlePeerChanges()
                        break;
 
                default:
-                       assert("Invalid peer change event received!" == 0);
+                       FATAL_ERROR("Invalid peer change event received!");
                        break;
                }
        }
@@ -2637,8 +2637,8 @@ void Server::UpdateCrafting(Player* player)
 
        // Put the new preview in
        InventoryList *plist = player->inventory.getList("craftpreview");
-       assert(plist);
-       assert(plist->getSize() >= 1);
+       sanity_check(plist);
+       sanity_check(plist->getSize() >= 1);
        plist->changeItem(0, preview);
 }
 
@@ -3026,7 +3026,7 @@ Inventory* Server::createDetachedInventory(const std::string &name)
                infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl;
        }
        Inventory *inv = new Inventory(m_itemdef);
-       assert(inv);
+       sanity_check(inv);
        m_detached_inventories[name] = inv;
        //TODO find a better way to do this
        sendDetachedInventory(name,PEER_ID_INEXISTENT);
index 7339af62baec80beb477950bb5dcd089924d3873..594b8944dadf76939f461e89540a0bac4adce765 100644 (file)
@@ -264,7 +264,7 @@ bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
                        it = m_settings.find(name);
                        if (it != m_settings.end() && it->second.is_group) {
                                os << line << "\n";
-                               assert(it->second.group != NULL);
+                               sanity_check(it->second.group != NULL);
                                was_modified |= it->second.group->updateConfigObject(is, os,
                                        "}", tab_depth + 1);
                        } else {
index 8c572ed49c4577e4a9c7ff2d188604151ab31e12..8a5fd417b658c7f683d48f1c5bf00c50faf3856e 100644 (file)
@@ -196,7 +196,7 @@ public:
        virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData)
        {
                video::IVideoDriver *driver = services->getVideoDriver();
-               assert(driver);
+               sanity_check(driver != NULL);
 
                bool is_highlevel = userData;
 
@@ -219,7 +219,7 @@ public:
                        bool is_highlevel)
        {
                video::IVideoDriver *driver = services->getVideoDriver();
-               assert(driver);
+               sanity_check(driver);
 
                // set inverted world matrix
                core::matrix4 invWorld = driver->getTransform(video::ETS_WORLD);
@@ -364,7 +364,7 @@ void load_shaders(std::string name, SourceShaderCache *sourcecache,
 ShaderSource::ShaderSource(IrrlichtDevice *device):
                m_device(device)
 {
-       assert(m_device);
+       assert(m_device); // Pre-condition
 
        m_shader_callback = new ShaderCallback(this, "default");
 
@@ -505,7 +505,7 @@ void ShaderSource::insertSourceShader(const std::string &name_of_shader,
                        "name_of_shader=\""<<name_of_shader<<"\", "
                        "filename=\""<<filename<<"\""<<std::endl;*/
 
-       assert(get_current_thread_id() == m_main_thread);
+       sanity_check(get_current_thread_id() == m_main_thread);
 
        m_sourcecache.insert(name_of_shader, filename, program, true);
 }
@@ -578,7 +578,7 @@ ShaderInfo generate_shader(std::string name, u8 material_type, u8 drawtype,
                return shaderinfo;
 
        video::IVideoDriver* driver = device->getVideoDriver();
-       assert(driver);
+       sanity_check(driver);
 
        video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
        if(!gpu){
index b2b424a19301f6c1b1c34f116bb0da3e0e939d61..cb4c7b5818dde9e90746f7843b622240ef1189dd 100644 (file)
@@ -37,10 +37,10 @@ with this program; ifnot, write to the Free Software Foundation, Inc.,
        #include <AL/alext.h>
 #endif
 #include <vorbis/vorbisfile.h>
+#include <assert.h>
 #include "log.h"
 #include "filesys.h"
 #include "util/numeric.h" // myrand()
-#include "debug.h" // assert()
 #include "porting.h"
 #include <map>
 #include <vector>
index 4918a14663eb127c5227bb824e911332755aad64..95a1b945ee040bc8c90741e879ba314a2c24d285 100644 (file)
@@ -68,8 +68,7 @@ public:
                        {
                                dstream<<"ERROR: StaticObjectList::insert(): "
                                                <<"id already exists"<<std::endl;
-                               assert(0);
-                               return;
+                               FATAL_ERROR("StaticObjectList::insert()");
                        }
                        m_active[id] = obj;
                }
@@ -77,7 +76,7 @@ public:
 
        void remove(u16 id)
        {
-               assert(id != 0);
+               assert(id != 0); // Pre-condition
                if(m_active.find(id) == m_active.end())
                {
                        dstream<<"WARNING: StaticObjectList::remove(): id="<<id
index 350cab127910f8cc6f607d761bedd1453f1ea9ee..7b82a2c318840e00b8dfa6fb29df02d3293c4021 100644 (file)
@@ -2115,8 +2115,6 @@ struct TestConnection: public TestBase
                UASSERT(hand_client.last_id == 1);
                UASSERT(hand_server.count == 1);
                UASSERT(hand_server.last_id == 2);
-
-               //assert(0);
        }
 };
 
index 8a108a0ff24b45f88e462af1a44c66abcbe780b3..659e816b0c86a084d1ec29ddc037742020c823ea 100644 (file)
@@ -31,7 +31,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 // Creates a string with the length as the first two bytes
 std::string serializeString(const std::string &plain)
 {
-       //assert(plain.size() <= 65535);
        if(plain.size() > 65535)
                throw SerializationError("String too long for serializeString");
        char buf[2];
@@ -45,7 +44,6 @@ std::string serializeString(const std::string &plain)
 // Creates a string with the length as the first two bytes from wide string
 std::string serializeWideString(const std::wstring &plain)
 {
-       //assert(plain.size() <= 65535);
        if(plain.size() > 65535)
                throw SerializationError("String too long for serializeString");
        char buf[2];
index 651293bfef0e34c0e4a03d6347dd71cc7ee08610..02a0586e796031ad166d3707401f2f13f81457cb 100644 (file)
@@ -320,7 +320,7 @@ char *mystrtok_r(char *s, const char *sep, char **lasts)
                }
                t++;
        }
-       
+
        *lasts = t;
        return s;
 }
@@ -329,15 +329,15 @@ u64 read_seed(const char *str)
 {
        char *endptr;
        u64 num;
-       
+
        if (str[0] == '0' && str[1] == 'x')
                num = strtoull(str, &endptr, 16);
        else
                num = strtoull(str, &endptr, 10);
-               
+
        if (*endptr)
                num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);
-               
+
        return num;
 }
 
@@ -614,4 +614,3 @@ void str_replace(std::string &str, char from, char to)
 {
        std::replace(str.begin(), str.end(), from, to);
 }
-
index 0546448893cf9374f308dda2b70a3978f258ebf5..58ad39be4a890d7f1fe6fe4ab1db6519dd4a024f 100644 (file)
@@ -213,7 +213,7 @@ public:
                        return;
                }
 
-               assert(contains(a));
+               assert(contains(a));    // pre-condition
 
                // Take back area, XY inclusive
                {
index a2be55544f945c720ec192a18076928709d04cbb..c1a898c1bd10282e43eb1f92000464bbe28a2ae6 100644 (file)
@@ -170,7 +170,7 @@ public:
                if (it == m_extrusion_meshes.end()) {
                        // no viable resolution found; use largest one
                        it = m_extrusion_meshes.find(MAX_EXTRUSION_MESH_RESOLUTION);
-                       assert(it != m_extrusion_meshes.end());
+                       sanity_check(it != m_extrusion_meshes.end());
                }
 
                scene::IMesh *mesh = it->second;
@@ -231,7 +231,7 @@ WieldMeshSceneNode::WieldMeshSceneNode(
 
 WieldMeshSceneNode::~WieldMeshSceneNode()
 {
-       assert(g_extrusion_mesh_cache);
+       sanity_check(g_extrusion_mesh_cache);
        if (g_extrusion_mesh_cache->drop())
                g_extrusion_mesh_cache = NULL;
 }