Some Makefile improvements.
[LameXP.git] / src / Thread_Initialization.cpp
blob76fa08f65233cb6d5acb3b5f734c4219fdc55829
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2017 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Thread_Initialization.h"
25 //Internal
26 #define LAMEXP_INC_TOOLS 1
27 #include "Tools.h"
28 #include "LockedFile.h"
29 #include "FileHash.h"
30 #include "Tool_Abstract.h"
32 //MUtils
33 #include <MUtils/Global.h>
34 #include <MUtils/OSSupport.h>
35 #include <MUtils/Translation.h>
36 #include <MUtils/Exception.h>
38 //Qt
39 #include <QFileInfo>
40 #include <QCoreApplication>
41 #include <QProcess>
42 #include <QMap>
43 #include <QDir>
44 #include <QResource>
45 #include <QTextStream>
46 #include <QRunnable>
47 #include <QThreadPool>
48 #include <QMutex>
49 #include <QQueue>
50 #include <QElapsedTimer>
51 #include <QVector>
53 /* enable custom tools? */
54 static const bool ENABLE_CUSTOM_TOOLS = true;
56 /* helper macros */
57 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
58 #define MAKE_REGEXP(STR) (((STR) && ((STR)[0])) ? QRegExp((STR)) : QRegExp())
60 /* constants */
61 static const double g_allowedExtractDelay = 12.0;
62 static const size_t BUFF_SIZE = 512;
64 /* number of CPU cores -> number of threads */
65 static unsigned int cores2threads(const unsigned int cores)
67 static const size_t LUT_LEN = 4;
69 static const struct
71 const unsigned int upperBound;
72 const double coeffs[4];
74 LUT[LUT_LEN] =
76 { 4, { -0.052695810565, 0.158087431694, 4.982841530055, -1.088233151184 } },
77 { 8, { 0.042431693989, -0.983442622951, 9.548961748634, -7.176393442623 } },
78 { 12, { -0.006277322404, 0.185573770492, 0.196830601093, 17.762622950820 } },
79 { 32, { 0.000673497268, -0.064655737705, 3.199584699454, 5.751606557377 } }
82 size_t index = 0;
83 while((cores > LUT[index].upperBound) && (index < (LUT_LEN-1))) index++;
85 const double x = qBound(1.0, double(cores), double(LUT[LUT_LEN-1].upperBound));
86 const double y = (LUT[index].coeffs[0] * pow(x, 3.0)) + (LUT[index].coeffs[1] * pow(x, 2.0)) + (LUT[index].coeffs[2] * x) + LUT[index].coeffs[3];
88 return qRound(abs(y));
91 ////////////////////////////////////////////////////////////
92 // BaseTask class
93 ////////////////////////////////////////////////////////////
95 class BaseTask : public QRunnable
97 public:
98 BaseTask(void)
102 ~BaseTask(void)
106 static void clearFlags(void)
108 s_exception.fetchAndStoreOrdered(0);
109 s_errMsg[0] = char(0);
112 static bool getExcept(void)
114 return MUTILS_BOOLIFY(s_exception);
117 static bool getErrMsg(char *buffer, const size_t buffSize)
119 if(s_errMsg[0])
121 strncpy_s(buffer, BUFF_SIZE, s_errMsg, _TRUNCATE);
122 return true;
124 return false;
127 protected:
128 virtual void taskMain(void) = 0;
130 void run(void)
134 if(!getExcept()) taskMain();
136 catch(const std::exception &e)
138 if(!s_exception.fetchAndAddOrdered(1))
140 strncpy_s(s_errMsg, BUFF_SIZE, e.what(), _TRUNCATE);
142 qWarning("OptionalInitTask exception error:\n%s\n\n", e.what());
144 catch(...)
146 if (!s_exception.fetchAndAddOrdered(1))
148 strncpy_s(s_errMsg, BUFF_SIZE, "Unknown exception error!", _TRUNCATE);
150 qWarning("OptionalInitTask encountered an unknown exception!");
154 static QAtomicInt s_exception;
155 static char s_errMsg[BUFF_SIZE];
158 char BaseTask::s_errMsg[BUFF_SIZE] = {'\0'};
159 QAtomicInt BaseTask::s_exception(0);
161 ////////////////////////////////////////////////////////////
162 // ExtractorTask class
163 ////////////////////////////////////////////////////////////
165 class ExtractorTask : public BaseTask
167 public:
168 ExtractorTask(QResource *const toolResource, const QDir &appDir, const QString &toolName, const QByteArray &toolHash, const unsigned int toolVersion, const QString &toolTag)
170 m_appDir(appDir),
171 m_tempPath(MUtils::temp_folder()),
172 m_toolName(toolName),
173 m_toolHash(toolHash),
174 m_toolVersion(toolVersion),
175 m_toolTag(toolTag),
176 m_toolResource(toolResource)
178 /* Nothing to do */
181 ~ExtractorTask(void)
185 static bool getCustom(void)
187 return MUTILS_BOOLIFY(s_custom);
190 static void clearFlags(void)
192 BaseTask::clearFlags();
193 s_custom.fetchAndStoreOrdered(0);
196 protected:
197 void taskMain(void)
199 QScopedPointer<LockedFile> lockedFile;
200 unsigned int version = m_toolVersion;
202 const QFileInfo toolFileInfo(m_toolName);
203 const QString toolShrtName = QString("%1.%2").arg(toolFileInfo.baseName().toLower(), toolFileInfo.suffix().toLower());
205 //Try to load a "custom" tool first
206 if(ENABLE_CUSTOM_TOOLS)
208 const QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShrtName));
209 if(customTool.exists() && customTool.isFile())
211 qDebug("Setting up file: %s <- %s", toolShrtName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
214 lockedFile.reset(new LockedFile(customTool.canonicalFilePath()));
215 version = UINT_MAX; s_custom.ref();
217 catch(std::runtime_error&)
219 lockedFile.reset();
224 //Try to load the tool from the "cache" next
225 if(lockedFile.isNull())
227 const QFileInfo chachedTool(QString("%1/cache/%2").arg(m_appDir.canonicalPath(), toolFileInfo.fileName()));
228 if(chachedTool.exists() && chachedTool.isFile())
230 qDebug("Validating file: %s <- %s", toolShrtName.toLatin1().constData(), m_appDir.relativeFilePath(chachedTool.canonicalFilePath()).toLatin1().constData());
233 lockedFile.reset(new LockedFile(chachedTool.canonicalFilePath(), m_toolHash));
235 catch(std::runtime_error&)
237 lockedFile.reset();
242 //If still not initialized, extract tool now!
243 if(lockedFile.isNull())
245 qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShrtName.toLatin1().constData());
246 lockedFile.reset(new LockedFile(m_toolResource.data(), QString("%1/lxp_%2").arg(m_tempPath, toolShrtName), m_toolHash));
249 //Register tool
250 lamexp_tools_register(toolShrtName, lockedFile.take(), version, m_toolTag);
253 private:
254 static QAtomicInt s_custom;
255 QScopedPointer<QResource> m_toolResource;
256 const QDir m_appDir;
257 const QString m_tempPath;
258 const QString m_toolName;
259 const QByteArray m_toolHash;
260 const unsigned int m_toolVersion;
261 const QString m_toolTag;
264 QAtomicInt ExtractorTask::s_custom = false;
266 ////////////////////////////////////////////////////////////
267 // InitAacEncTask class
268 ////////////////////////////////////////////////////////////
270 class InitAacEncTask : public BaseTask
272 public:
273 InitAacEncTask(const aac_encoder_t *const encoder_info)
275 m_encoder_info(encoder_info)
279 ~InitAacEncTask(void)
283 protected:
284 void taskMain(void)
286 initAacEncImpl(m_encoder_info->toolName, m_encoder_info->fileNames, m_encoder_info->checkArgs ? (QStringList() << QString::fromLatin1(m_encoder_info->checkArgs)) : QStringList(), m_encoder_info->toolMinVersion, m_encoder_info->verDigits, m_encoder_info->verShift, m_encoder_info->verStr, MAKE_REGEXP(m_encoder_info->regExpVer), MAKE_REGEXP(m_encoder_info->regExpSig));
289 static void initAacEncImpl(const char *const toolName, const char *const fileNames[], const QStringList &checkArgs, const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp &regExpVer, QRegExp &regExpSig = QRegExp());
291 private:
292 const aac_encoder_t *const m_encoder_info;
295 ////////////////////////////////////////////////////////////
296 // Constructor
297 ////////////////////////////////////////////////////////////
299 InitializationThread::InitializationThread(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures)
301 m_bSuccess(false),
302 m_slowIndicator(false)
305 memcpy(&m_cpuFeatures, &cpuFeatures, sizeof(MUtils::CPUFetaures::cpu_info_t));
308 ////////////////////////////////////////////////////////////
309 // Thread Main
310 ////////////////////////////////////////////////////////////
312 void InitializationThread::run(void)
316 doInit();
318 catch(const std::exception &error)
320 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
321 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
323 catch(...)
325 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
326 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
330 double InitializationThread::doInit(const size_t threadCount)
332 m_bSuccess = false;
333 delay();
335 //CPU type selection
336 unsigned int cpuSupport = 0;
337 const bool haveSSE2 = (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE) && (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2);
338 if(haveSSE2 && (m_cpuFeatures.vendor & MUtils::CPUFetaures::VENDOR_INTEL))
340 if (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_AVX)
342 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_AVX : CPU_TYPE_X86_AVX;
344 else
346 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
349 else
351 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
354 //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
355 if(cpuSupport & CPU_TYPE_X64_ALL)
357 if(MUtils::OS::running_on_wine())
359 qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
360 cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
364 //Print selected CPU type
365 switch(cpuSupport)
367 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
368 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
369 PRINT_CPU_TYPE(CPU_TYPE_X86_AVX); break;
370 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
371 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
372 PRINT_CPU_TYPE(CPU_TYPE_X64_AVX); break;
373 default: MUTILS_THROW("CPU support undefined!");
376 //Allocate queues
377 QQueue<QString> queueToolName;
378 QQueue<QString> queueChecksum;
379 QQueue<QString> queueVersInfo;
380 QQueue<unsigned int> queueVersions;
381 QQueue<unsigned int> queueCpuTypes;
383 //Init properties
384 for(int i = 0; true; i++)
386 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
388 break;
390 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
392 queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
393 queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
394 queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
395 queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
396 queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
398 else
400 qFatal("Inconsistent checksum data detected. Take care!");
404 QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
406 QScopedPointer<QThreadPool> pool(new QThreadPool());
407 pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), 16U));
408 ExtractorTask::clearFlags();
410 //Start the timer
411 QElapsedTimer timeExtractStart;
412 timeExtractStart.start();
414 //Extract all files
415 while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
417 const QString toolName = queueToolName.dequeue();
418 const QString checksum = queueChecksum.dequeue();
419 const QString versInfo = queueVersInfo.dequeue();
420 const unsigned int cpuType = queueCpuTypes.dequeue();
421 const unsigned int version = queueVersions.dequeue();
423 const QByteArray toolHash(checksum.toLatin1());
424 if(toolHash.size() != 96)
426 qFatal("The checksum for \"%s\" has an invalid size!", MUTILS_UTF8(toolName));
427 return -1.0;
430 QScopedPointer<QResource> resource(new QResource(QString(":/tools/%1").arg(toolName)));
431 if(!(resource->isValid() && resource->data()))
433 qFatal("The resource for \"%s\" could not be found!", MUTILS_UTF8(toolName));
434 return -1.0;
437 if(cpuType & cpuSupport)
439 pool->start(new ExtractorTask(resource.take(), appDir, toolName, toolHash, version, versInfo));
440 continue;
444 //Sanity Check
445 if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
447 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
450 //Wait for extrator threads to finish
451 pool->waitForDone();
453 //Performance measure
454 const double delayExtract = double(timeExtractStart.elapsed()) / 1000.0;
455 timeExtractStart.invalidate();
457 //Make sure all files were extracted correctly
458 if(ExtractorTask::getExcept())
460 char errorMsg[BUFF_SIZE];
461 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
463 qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
464 return -1.0;
466 qFatal("At least one of the required tools could not be initialized!");
467 return -1.0;
470 qDebug("All extracted.\n");
472 //Using any custom tools?
473 if(ExtractorTask::getCustom())
475 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
478 //Check delay
479 if(delayExtract > g_allowedExtractDelay)
481 m_slowIndicator = true;
482 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
483 qWarning("Please report performance problems to your anti-virus developer !!!\n");
485 else
487 qDebug("Extracting the tools took %.3f seconds (OK).\n", delayExtract);
490 //Register all translations
491 initTranslations();
493 //Look for AAC encoders
494 InitAacEncTask::clearFlags();
495 for(size_t i = 0; g_lamexp_aacenc[i].toolName; i++)
497 pool->start(new InitAacEncTask(&(g_lamexp_aacenc[i])));
499 pool->waitForDone();
501 //Make sure initialization finished correctly
502 if(InitAacEncTask::getExcept())
504 char errorMsg[BUFF_SIZE];
505 if(InitAacEncTask::getErrMsg(errorMsg, BUFF_SIZE))
507 qFatal("At least one optional component failed to initialize:\n%s", errorMsg);
508 return -1.0;
510 qFatal("At least one optional component failed to initialize!");
511 return -1.0;
514 m_bSuccess = true;
515 delay();
517 return delayExtract;
520 ////////////////////////////////////////////////////////////
521 // INTERNAL FUNCTIONS
522 ////////////////////////////////////////////////////////////
524 void InitializationThread::delay(void)
526 MUtils::OS::sleep_ms(333);
529 ////////////////////////////////////////////////////////////
530 // Translation Support
531 ////////////////////////////////////////////////////////////
533 void InitializationThread::initTranslations(void)
535 //Search for language files
536 const QDir qmDirectory(":/localization");
537 const QStringList qmFiles = qmDirectory.entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
539 //Make sure we found at least one translation
540 if(qmFiles.count() < 1)
542 qFatal("Could not find any translation files!");
543 return;
546 //Initialize variables
547 const QString langResTemplate(":/localization/%1.txt");
548 QRegExp langIdExp("^LameXP_(\\w\\w)\\.qm$", Qt::CaseInsensitive);
550 //Add all available translations
551 for(QStringList::ConstIterator iter = qmFiles.constBegin(); iter != qmFiles.constEnd(); iter++)
553 const QString langFile = qmDirectory.absoluteFilePath(*iter);
554 QString langId, langName;
555 unsigned int systemId = 0, country = 0;
557 if(QFileInfo(langFile).isFile() && (langIdExp.indexIn(*iter) >= 0))
559 langId = langIdExp.cap(1).toLower();
560 QScopedPointer<QResource> langRes(new QResource(langResTemplate.arg(*iter)));
561 if(langRes->isValid() && langRes->size() > 0)
563 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes->data()), langRes->size());
564 QTextStream stream(&data, QIODevice::ReadOnly);
565 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
567 while(!(stream.atEnd() || (stream.status() != QTextStream::Ok)))
569 QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
570 if(langInfo.count() >= 3)
572 systemId = langInfo.at(0).trimmed().toUInt();
573 country = langInfo.at(1).trimmed().toUInt();
574 langName = langInfo.at(2).trimmed();
575 break;
581 if(!(langId.isEmpty() || langName.isEmpty() || (systemId == 0)))
583 if(MUtils::Translation::insert(langId, langFile, langName, systemId, country))
585 qDebug("Registering translation: %s = %s (%u) [%u]", MUTILS_UTF8(*iter), MUTILS_UTF8(langName), systemId, country);
587 else
589 qWarning("Failed to register: %s", langFile.toLatin1().constData());
594 qDebug("All registered.\n");
597 ////////////////////////////////////////////////////////////
598 // AAC Encoder Detection
599 ////////////////////////////////////////////////////////////
601 void InitAacEncTask::initAacEncImpl(const char *const toolName, const char *const fileNames[], const QStringList &checkArgs, const quint32 &toolMinVersion, const quint32 &verDigits, const quint32 &verShift, const char *const verStr, QRegExp &regExpVer, QRegExp &regExpSig)
603 static const size_t MAX_FILES = 8;
604 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
606 QFileInfoList fileInfo;
607 for(size_t i = 0; fileNames[i] && (fileInfo.count() < MAX_FILES); i++)
609 fileInfo.append(QFileInfo(QString("%1/%2").arg(appPath, QString::fromLatin1(fileNames[i]))));
612 for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
614 if(!(iter->exists() && iter->isFile()))
616 qDebug("%s encoder binaries not found -> Encoding support will be disabled!\n", toolName);
617 return;
619 if((iter->suffix().compare("exe", Qt::CaseInsensitive) == 0) && (!MUtils::OS::is_executable_file(iter->canonicalFilePath())))
621 qDebug("%s executable is invalid -> %s support will be disabled!\n", MUTILS_UTF8(iter->fileName()), toolName);
622 return;
626 qDebug("Found %s encoder binary:\n%s\n", toolName, MUTILS_UTF8(fileInfo.first().canonicalFilePath()));
628 //Lock the encoder binaries
629 QScopedPointer<LockedFile> binaries[MAX_FILES];
632 size_t index = 0;
633 for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
635 binaries[index++].reset(new LockedFile(iter->canonicalFilePath()));
638 catch(...)
640 qWarning("Failed to get excluive lock to encoder binary -> %s support will be disabled!", toolName);
641 return;
644 QProcess process;
645 MUtils::init_process(process, fileInfo.first().absolutePath());
646 process.start(fileInfo.first().canonicalFilePath(), checkArgs);
648 if(!process.waitForStarted())
650 qWarning("%s process failed to create!", toolName);
651 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
652 process.kill();
653 process.waitForFinished(-1);
654 return;
657 quint32 toolVersion = 0;
658 bool sigFound = regExpSig.isEmpty() ? true : false;
660 while(process.state() != QProcess::NotRunning)
662 if(!process.waitForReadyRead())
664 if(process.state() == QProcess::Running)
666 qWarning("%s process time out -> killing!", toolName);
667 process.kill();
668 process.waitForFinished(-1);
669 return;
672 while(process.canReadLine())
674 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
675 if((!sigFound) && regExpSig.lastIndexIn(line) >= 0)
677 sigFound = true;
678 continue;
680 if(sigFound && (regExpVer.lastIndexIn(line) >= 0))
682 quint32 tmp[8];
683 if(MUtils::regexp_parse_uint32(regExpVer, tmp, qMin(verDigits, 8U)))
685 toolVersion = 0;
686 for(quint32 i = 0; i < verDigits; i++)
688 toolVersion = (verShift > 0) ? ((toolVersion * verShift) + qBound(0U, tmp[i], (verShift - 1))) : tmp[i];
695 if(toolVersion <= 0)
697 qWarning("%s version could not be determined -> Encoding support will be disabled!", toolName);
698 return;
700 else if(toolVersion < toolMinVersion)
702 qWarning("%s version is too much outdated (%s) -> Encoding support will be disabled!", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A")));
703 qWarning("Minimum required %s version currently is: %s\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolMinVersion, "N/A")));
704 return;
707 qDebug("Enabled %s encoder %s.\n", toolName, MUTILS_UTF8(lamexp_version2string(verStr, toolVersion, "N/A")));
709 size_t index = 0;
710 for(QFileInfoList::ConstIterator iter = fileInfo.constBegin(); iter != fileInfo.constEnd(); iter++)
712 lamexp_tools_register(iter->fileName(), binaries[index++].take(), toolVersion);
716 ////////////////////////////////////////////////////////////
717 // Self-Test Function
718 ////////////////////////////////////////////////////////////
720 void InitializationThread::selfTest(void)
722 const unsigned int cpu[7] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X86_AVX, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE, CPU_TYPE_X64_AVX, 0 };
724 unsigned int expectedCount = UINT_MAX;
725 for(size_t k = 0; cpu[k]; k++)
727 qDebug("[TEST]");
728 switch(cpu[k])
730 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
731 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
732 PRINT_CPU_TYPE(CPU_TYPE_X86_AVX); break;
733 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
734 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
735 PRINT_CPU_TYPE(CPU_TYPE_X64_AVX); break;
736 default:
737 MUTILS_THROW("CPU support undefined!");
739 unsigned int n = 0;
740 for(int i = 0; true; i++)
742 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
744 break;
746 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
748 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
749 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
750 if(g_lamexp_tools[i].uiCpuType & cpu[k])
752 qDebug("%02i -> %s", ++n, MUTILS_UTF8(toolName));
753 QFile resource(QString(":/tools/%1").arg(toolName));
754 if(!resource.open(QIODevice::ReadOnly))
756 qFatal("The resource for \"%s\" could not be opened!", MUTILS_UTF8(toolName));
757 break;
759 QByteArray hash = FileHash::computeHash(resource);
760 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
762 qFatal("Hash check for tool \"%s\" has failed!", MUTILS_UTF8(toolName));
763 break;
765 resource.close();
768 else
770 qFatal("Inconsistent checksum data detected. Take care!");
773 if (expectedCount != UINT_MAX)
775 if (n != expectedCount)
777 qFatal("Tool count mismatch for CPU type %u. Should be %u, but got %u !!!", cpu[k], expectedCount, n);
780 else
782 expectedCount = n; /*remember count*/
784 qDebug("Done.\n");
788 ////////////////////////////////////////////////////////////
789 // EVENTS
790 ////////////////////////////////////////////////////////////
792 /*NONE*/