Moved -static-libgcc to linker flags.
3 * =============================================================================
5 * Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
33 #include "HandleSys.h"
35 #include "sourcemod.h"
36 #include "sm_stringutil.h"
38 #include "ExtensionSys.h"
40 #include <IThreader.h>
42 #define DBPARSE_LEVEL_NONE 0
43 #define DBPARSE_LEVEL_MAIN 1
44 #define DBPARSE_LEVEL_DATABASE 2
47 static bool s_OneTimeThreaderErrorMsg = false;
49 DBManager::DBManager()
50 : m_ParseLevel(0), m_ParseState(0), m_pDefault(NULL)
54 void DBManager::OnSourceModAllInitialized()
58 g_HandleSys.InitAccessDefaults(NULL, &sec);
59 sec.access[HandleAccess_Delete] |= HANDLE_RESTRICT_IDENTITY;
60 sec.access[HandleAccess_Clone] |= HANDLE_RESTRICT_IDENTITY;
62 m_DriverType = g_HandleSys.CreateType("IDriver", this, 0, NULL, &sec, g_pCoreIdent, NULL);
63 m_DatabaseType = g_HandleSys.CreateType("IDatabase", this, 0, NULL, NULL, g_pCoreIdent, NULL);
65 g_ShareSys.AddInterface(NULL, this);
67 g_SourceMod.BuildPath(Path_SM, m_Filename, sizeof(m_Filename), "configs/databases.cfg");
69 m_pConfigLock = g_pThreader->MakeMutex();
70 m_pThinkLock = g_pThreader->MakeMutex();
71 m_pQueueLock = g_pThreader->MakeMutex();
73 g_PluginSys.AddPluginsListener(this);
76 void DBManager::OnSourceModLevelChange(const char *mapName)
79 SMCStates states = {0, 0};
81 /* We lock and don't give up the lock until we're done.
82 * This way the thread's search won't be searching through a
83 * potentially empty/corrupt list, which would be very bad.
85 m_pConfigLock->Lock();
86 if ((err = textparsers->ParseFile_SMC(m_Filename, this, &states)) != SMCError_Okay)
88 g_Logger.LogError("[SM] Detected parse error(s) in file \"%s\"", m_Filename);
89 if (err != SMCError_Custom)
91 const char *txt = textparsers->GetSMCErrorString(err);
92 g_Logger.LogError("[SM] Line %d: %s", states.line, txt);
95 m_pConfigLock->Unlock();
98 void DBManager::OnSourceModShutdown()
101 g_PluginSys.RemovePluginsListener(this);
102 m_pConfigLock->DestroyThis();
103 m_pThinkLock->DestroyThis();
104 m_pQueueLock->DestroyThis();
105 g_HandleSys.RemoveType(m_DatabaseType, g_pCoreIdent);
106 g_HandleSys.RemoveType(m_DriverType, g_pCoreIdent);
110 unsigned int DBManager::GetInterfaceVersion()
112 return SMINTERFACE_DBI_VERSION;
115 const char *DBManager::GetInterfaceName()
117 return SMINTERFACE_DBI_NAME;
120 void DBManager::OnHandleDestroy(HandleType_t type, void *object)
122 if (type == m_DriverType)
128 if (g_HandleSys.TypeCheck(type, m_DatabaseType))
130 IDatabase *pdb = (IDatabase *)object;
135 void DBManager::ReadSMC_ParseStart()
139 m_ParseState = DBPARSE_LEVEL_NONE;
143 void DBManager::ClearConfigs()
145 List<ConfDbInfo *>::iterator iter;
146 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
151 ConfDbInfo s_CurInfo;
152 SMCResult DBManager::ReadSMC_NewSection(const SMCStates *states, const char *name)
157 return SMCResult_Continue;
160 if (m_ParseState == DBPARSE_LEVEL_NONE)
162 if (strcmp(name, "Databases") == 0)
164 m_ParseState = DBPARSE_LEVEL_MAIN;
168 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
169 s_CurInfo = ConfDbInfo();
170 s_CurInfo.name = name;
171 m_ParseState = DBPARSE_LEVEL_DATABASE;
172 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
176 return SMCResult_Continue;
179 SMCResult DBManager::ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
183 return SMCResult_Continue;
186 if (m_ParseState == DBPARSE_LEVEL_MAIN)
188 if (strcmp(key, "driver_default") == 0)
190 m_DefDriver.assign(value);
192 } else if (m_ParseState == DBPARSE_LEVEL_DATABASE) {
193 if (strcmp(key, "driver") == 0)
195 if (strcmp(value, "default") != 0)
197 s_CurInfo.driver = value;
199 } else if (strcmp(key, "database") == 0) {
200 s_CurInfo.database = value;
201 } else if (strcmp(key, "host") == 0) {
202 s_CurInfo.host = value;
203 } else if (strcmp(key, "user") == 0) {
204 s_CurInfo.user = value;
205 } else if (strcmp(key, "pass") == 0) {
206 s_CurInfo.pass = value;
207 } else if (strcmp(key, "timeout") == 0) {
208 s_CurInfo.info.maxTimeout = atoi(value);
209 } else if (strcmp(key, "port") == 0) {
210 s_CurInfo.info.port = atoi(value);
214 return SMCResult_Continue;
217 SMCResult DBManager::ReadSMC_LeavingSection(const SMCStates *states)
222 return SMCResult_Continue;
225 if (m_ParseState == DBPARSE_LEVEL_DATABASE)
227 ConfDbInfo *cdb = new ConfDbInfo();
229 cdb->name = s_CurInfo.name;
230 cdb->driver = s_CurInfo.driver;
231 cdb->host = s_CurInfo.host;
232 cdb->user = s_CurInfo.user;
233 cdb->pass = s_CurInfo.pass;
234 cdb->database = s_CurInfo.database;
235 cdb->realDriver = s_CurInfo.realDriver;
236 cdb->info.maxTimeout = s_CurInfo.info.maxTimeout;
237 cdb->info.port = s_CurInfo.info.port;
239 cdb->info.driver = cdb->driver.c_str();
240 cdb->info.database = cdb->database.c_str();
241 cdb->info.host = cdb->host.c_str();
242 cdb->info.user = cdb->user.c_str();
243 cdb->info.pass = cdb->pass.c_str();
246 m_confs.push_back(cdb);
248 /* Go up one level */
249 m_ParseState = DBPARSE_LEVEL_MAIN;
250 } else if (m_ParseState == DBPARSE_LEVEL_MAIN) {
251 m_ParseState = DBPARSE_LEVEL_NONE;
252 return SMCResult_Halt;
255 return SMCResult_Continue;
258 void DBManager::ReadSMC_ParseEnd(bool halted, bool failed)
262 bool DBManager::Connect(const char *name, IDBDriver **pdr, IDatabase **pdb, bool persistent, char *error, size_t maxlength)
264 ConfDbInfo *pInfo = GetDatabaseConf(name);
273 UTIL_Format(error, maxlength, "Configuration \"%s\" not found", name);
277 const char *dname = pInfo->info.driver;
278 if (!pInfo->realDriver)
280 /* Try to assign a real driver pointer */
281 if (pInfo->info.driver[0] == '\0')
283 if (!m_pDefault && m_DefDriver.size() > 0)
285 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
287 dname = m_DefDriver.size() ? m_DefDriver.c_str() : "default";
288 pInfo->realDriver = m_pDefault;
290 pInfo->realDriver = FindOrLoadDriver(pInfo->info.driver);
294 if (pInfo->realDriver)
298 *pdr = pInfo->realDriver;
300 *pdb = pInfo->realDriver->Connect(&pInfo->info, persistent, error, maxlength);
301 return (*pdb != NULL);
310 UTIL_Format(error, maxlength, "Driver \"%s\" not found", dname);
315 void DBManager::AddDriver(IDBDriver *pDriver)
317 /* Let's kill the worker. Join the thread and let the queries flush.
318 * This is kind of stupid but we just want to unload safely.
319 * Rather than recreate the worker, we'll wait until someone throws
320 * another query through.
324 m_drivers.push_back(pDriver);
327 void DBManager::RemoveDriver(IDBDriver *pDriver)
329 /* Again, we're forced to kill the worker. How rude!
330 * Doing this flushes the queue, and thus we don't need to
331 * clean anything else.
335 for (size_t i=0; i<m_drivers.size(); i++)
337 if (m_drivers[i] == pDriver)
339 m_drivers.erase(m_drivers.iterAt(i));
344 /* Make sure NOTHING references this! */
345 List<ConfDbInfo *>::iterator iter;
346 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
348 ConfDbInfo &db = *(*iter);
349 if (db.realDriver == pDriver)
351 db.realDriver = NULL;
355 /* Now that the driver is gone, we have to test the think queue.
356 * Whatever happens therein is up to the db op!
358 Queue<IDBThreadOperation *>::iterator qiter = m_ThinkQueue.begin();
359 Queue<IDBThreadOperation *> templist;
360 while (qiter != m_ThinkQueue.end())
362 IDBThreadOperation *op = (*qiter);
363 if (op->GetDriver() == pDriver)
366 qiter = m_ThinkQueue.erase(qiter);
372 for (qiter = templist.begin();
373 qiter != templist.end();
376 IDBThreadOperation *op = (*qiter);
377 op->CancelThinkPart();
382 IDBDriver *DBManager::GetDefaultDriver()
384 if (!m_pDefault && m_DefDriver.size() > 0)
386 m_pDefault = FindOrLoadDriver(m_DefDriver.c_str());
392 Handle_t DBManager::CreateHandle(DBHandleType dtype, void *ptr, IdentityToken_t *pToken)
394 HandleType_t type = 0;
396 if (dtype == DBHandle_Driver)
399 } else if (dtype == DBHandle_Database) {
400 type = m_DatabaseType;
405 return g_HandleSys.CreateHandle(type, ptr, pToken, g_pCoreIdent, NULL);
408 HandleError DBManager::ReadHandle(Handle_t hndl, DBHandleType dtype, void **ptr)
410 HandleType_t type = 0;
412 if (dtype == DBHandle_Driver)
415 } else if (dtype == DBHandle_Database) {
416 type = m_DatabaseType;
418 return HandleError_Type;
421 HandleSecurity sec(NULL, g_pCoreIdent);
423 return g_HandleSys.ReadHandle(hndl, type, &sec, ptr);
426 HandleError DBManager::ReleaseHandle(Handle_t hndl, DBHandleType type, IdentityToken_t *token)
428 HandleSecurity sec(token, g_pCoreIdent);
429 return g_HandleSys.FreeHandle(hndl, &sec);
432 unsigned int DBManager::GetDriverCount()
434 return (unsigned int)m_drivers.size();
437 IDBDriver *DBManager::GetDriver(unsigned int index)
439 if (index >= m_drivers.size())
444 return m_drivers[index];
447 const DatabaseInfo *DBManager::FindDatabaseConf(const char *name)
449 ConfDbInfo *info = GetDatabaseConf(name);
458 ConfDbInfo *DBManager::GetDatabaseConf(const char *name)
460 List<ConfDbInfo *>::iterator iter;
462 for (iter=m_confs.begin(); iter!=m_confs.end(); iter++)
464 ConfDbInfo &conf = *(*iter);
465 if (conf.name == name)
474 IDBDriver *DBManager::FindOrLoadDriver(const char *name)
476 size_t last_size = m_drivers.size();
477 for (size_t i=0; i<last_size; i++)
479 if (strcmp(m_drivers[i]->GetIdentifier(), name) == 0)
485 char filename[PLATFORM_MAX_PATH];
486 UTIL_Format(filename, sizeof(filename), "dbi.%s.ext", name);
488 IExtension *pExt = g_Extensions.LoadAutoExtension(filename);
489 if (!pExt || !pExt->IsLoaded() || m_drivers.size() <= last_size)
494 /* last_size is now gauranteed to be a valid index.
495 * The identifier must match the name.
497 if (strcmp(m_drivers[last_size]->GetIdentifier(), name) == 0)
499 return m_drivers[last_size];
505 void DBManager::KillWorkerThread()
509 m_pWorker->Stop(false);
510 g_pThreader->DestroyWorker(m_pWorker);
512 s_OneTimeThreaderErrorMsg = false;
516 static IdentityToken_t *s_pAddBlock = NULL;
518 bool DBManager::AddToThreadQueue(IDBThreadOperation *op, PrioQueueLevel prio)
520 if (s_pAddBlock && op->GetOwner() == s_pAddBlock)
527 m_pWorker = g_pThreader->MakeWorker(this, true);
530 if (!s_OneTimeThreaderErrorMsg)
532 g_Logger.LogError("[SM] Unable to create db threader (error unknown)");
533 s_OneTimeThreaderErrorMsg = true;
537 if (!m_pWorker->Start())
539 if (!s_OneTimeThreaderErrorMsg)
541 g_Logger.LogError("[SM] Unable to start db threader (error unknown)");
542 s_OneTimeThreaderErrorMsg = true;
544 g_pThreader->DestroyWorker(m_pWorker);
550 /* Add to the queue */
552 m_pQueueLock->Lock();
553 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetQueue(prio);
555 m_pQueueLock->Unlock();
558 /* Make the thread */
559 m_pWorker->MakeThread(this);
564 void DBManager::OnWorkerStart(IThreadWorker *pWorker)
567 for (size_t i=0; i<m_drivers.size(); i++)
569 if (m_drivers[i]->IsThreadSafe())
571 m_drSafety.push_back(m_drivers[i]->InitializeThreadSafety());
573 m_drSafety.push_back(false);
578 void DBManager::OnWorkerStop(IThreadWorker *pWorker)
580 for (size_t i=0; i<m_drivers.size(); i++)
584 m_drivers[i]->ShutdownThreadSafety();
590 void DBManager::RunThread(IThreadHandle *pThread)
592 IDBThreadOperation *op = NULL;
594 /* Get something from the queue */
596 m_pQueueLock->Lock();
597 Queue<IDBThreadOperation *> &queue = m_OpQueue.GetLikelyQueue();
603 m_pQueueLock->Unlock();
606 /* whoa. hi. did we get something? we should have. */
615 m_pThinkLock->Lock();
616 m_ThinkQueue.push(op);
617 m_pThinkLock->Unlock();
620 void DBManager::RunFrame()
622 /* Don't bother if we're empty */
623 if (!m_ThinkQueue.size())
628 /* Dump one thing per-frame so the server stays sane. */
629 m_pThinkLock->Lock();
630 IDBThreadOperation *op = m_ThinkQueue.first();
632 m_pThinkLock->Unlock();
637 void DBManager::OnTerminate(IThreadHandle *pThread, bool cancel)
642 void DBManager::OnSourceModIdentityDropped(IdentityToken_t *pToken)
644 s_pAddBlock = pToken;
646 /* Kill the thread so we can flush everything into the think queue... */
649 /* Run all of the think operations.
650 * Unlike the driver unloading example, we'll let these calls go through,
651 * since a plugin unloading is far more normal.
653 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
654 Queue<IDBThreadOperation *> templist;
655 while (iter != m_ThinkQueue.end())
657 IDBThreadOperation *op = (*iter);
658 if (op->GetOwner() == pToken)
661 iter = m_ThinkQueue.erase(iter);
667 for (iter = templist.begin();
668 iter != templist.end();
671 IDBThreadOperation *op = (*iter);
679 void DBManager::OnPluginUnloaded(IPlugin *plugin)
681 /* Kill the thread so we can flush everything into the think queue... */
684 /* Mark the plugin as being unloaded so future database calls will ignore threading... */
685 plugin->SetProperty("DisallowDBThreads", NULL);
687 /* Run all of the think operations.
688 * Unlike the driver unloading example, we'll let these calls go through,
689 * since a plugin unloading is far more normal.
691 Queue<IDBThreadOperation *>::iterator iter = m_ThinkQueue.begin();
692 Queue<IDBThreadOperation *> templist;
693 while (iter != m_ThinkQueue.end())
695 IDBThreadOperation *op = (*iter);
696 if (op->GetOwner() == plugin->GetIdentity())
699 iter = m_ThinkQueue.erase(iter);
705 for (iter = templist.begin();
706 iter != templist.end();
709 IDBThreadOperation *op = (*iter);
715 void DBManager::LockConfig()
717 m_pConfigLock->Lock();
720 void DBManager::UnlockConfig()
722 m_pConfigLock->Unlock();
725 const char *DBManager::GetDefaultDriverName()
727 return m_DefDriver.c_str();
730 void DBManager::AddDependency(IExtension *myself, IDBDriver *driver)
732 g_Extensions.AddRawDependency(myself, driver->GetIdentity(), driver);