cmCTest.cxx 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTest.h"
  4. #include "cm_curl.h"
  5. #include "cm_zlib.h"
  6. #include "cmsys/Base64.h"
  7. #include "cmsys/Directory.hxx"
  8. #include "cmsys/FStream.hxx"
  9. #include "cmsys/Glob.hxx"
  10. #include "cmsys/Process.h"
  11. #include "cmsys/String.hxx"
  12. #include "cmsys/SystemInformation.hxx"
  13. #include <algorithm>
  14. #include <chrono>
  15. #include <ctype.h>
  16. #include <iostream>
  17. #include <map>
  18. #include <memory> // IWYU pragma: keep
  19. #include <sstream>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <string>
  24. #include <time.h>
  25. #include <utility>
  26. #include <vector>
  27. #include "cmAlgorithms.h"
  28. #include "cmCTestBuildAndTestHandler.h"
  29. #include "cmCTestBuildHandler.h"
  30. #include "cmCTestConfigureHandler.h"
  31. #include "cmCTestCoverageHandler.h"
  32. #include "cmCTestGenericHandler.h"
  33. #include "cmCTestMemCheckHandler.h"
  34. #include "cmCTestScriptHandler.h"
  35. #include "cmCTestStartCommand.h"
  36. #include "cmCTestSubmitHandler.h"
  37. #include "cmCTestTestHandler.h"
  38. #include "cmCTestUpdateHandler.h"
  39. #include "cmCTestUploadHandler.h"
  40. #include "cmCurl.h"
  41. #include "cmDynamicLoader.h"
  42. #include "cmGeneratedFileStream.h"
  43. #include "cmGlobalGenerator.h"
  44. #include "cmMakefile.h"
  45. #include "cmProcessOutput.h"
  46. #include "cmState.h"
  47. #include "cmStateSnapshot.h"
  48. #include "cmStateTypes.h"
  49. #include "cmSystemTools.h"
  50. #include "cmVersion.h"
  51. #include "cmVersionConfig.h"
  52. #include "cmXMLWriter.h"
  53. #include "cmake.h"
  54. #if defined(__BEOS__) || defined(__HAIKU__)
  55. #include <be/kernel/OS.h> /* disable_debugger() API. */
  56. #endif
  57. #define DEBUGOUT \
  58. std::cout << __LINE__ << " "; \
  59. std::cout
  60. #define DEBUGERR \
  61. std::cerr << __LINE__ << " "; \
  62. std::cerr
  63. struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
  64. {
  65. struct tm* lctime;
  66. time_t tctime = time(nullptr);
  67. lctime = gmtime(&tctime);
  68. char buf[1024];
  69. // add todays year day and month to the time in str because
  70. // curl_getdate no longer assumes the day is today
  71. sprintf(buf, "%d%02d%02d %s", lctime->tm_year + 1900, lctime->tm_mon + 1,
  72. lctime->tm_mday, str.c_str());
  73. cmCTestLog(this, OUTPUT, "Determine Nightly Start Time"
  74. << std::endl
  75. << " Specified time: " << str << std::endl);
  76. // Convert the nightly start time to seconds. Since we are
  77. // providing only a time and a timezone, the current date of
  78. // the local machine is assumed. Consequently, nightlySeconds
  79. // is the time at which the nightly dashboard was opened or
  80. // will be opened on the date of the current client machine.
  81. // As such, this time may be in the past or in the future.
  82. time_t ntime = curl_getdate(buf, &tctime);
  83. cmCTestLog(this, DEBUG, " Get curl time: " << ntime << std::endl);
  84. tctime = time(nullptr);
  85. cmCTestLog(this, DEBUG, " Get the current time: " << tctime << std::endl);
  86. const int dayLength = 24 * 60 * 60;
  87. cmCTestLog(this, DEBUG, "Seconds: " << tctime << std::endl);
  88. while (ntime > tctime) {
  89. // If nightlySeconds is in the past, this is the current
  90. // open dashboard, then return nightlySeconds. If
  91. // nightlySeconds is in the future, this is the next
  92. // dashboard to be opened, so subtract 24 hours to get the
  93. // time of the current open dashboard
  94. ntime -= dayLength;
  95. cmCTestLog(this, DEBUG, "Pick yesterday" << std::endl);
  96. cmCTestLog(this, DEBUG, " Future time, subtract day: " << ntime
  97. << std::endl);
  98. }
  99. while (tctime > (ntime + dayLength)) {
  100. ntime += dayLength;
  101. cmCTestLog(this, DEBUG, " Past time, add day: " << ntime << std::endl);
  102. }
  103. cmCTestLog(this, DEBUG, "nightlySeconds: " << ntime << std::endl);
  104. cmCTestLog(this, DEBUG, " Current time: " << tctime << " Nightly time: "
  105. << ntime << std::endl);
  106. if (tomorrowtag) {
  107. cmCTestLog(this, OUTPUT, " Use future tag, Add a day" << std::endl);
  108. ntime += dayLength;
  109. }
  110. lctime = gmtime(&ntime);
  111. return lctime;
  112. }
  113. std::string cmCTest::CleanString(const std::string& str)
  114. {
  115. std::string::size_type spos = str.find_first_not_of(" \n\t\r\f\v");
  116. std::string::size_type epos = str.find_last_not_of(" \n\t\r\f\v");
  117. if (spos == std::string::npos) {
  118. return std::string();
  119. }
  120. if (epos != std::string::npos) {
  121. epos = epos - spos + 1;
  122. }
  123. return str.substr(spos, epos);
  124. }
  125. std::string cmCTest::CurrentTime()
  126. {
  127. time_t currenttime = time(nullptr);
  128. struct tm* t = localtime(&currenttime);
  129. // return ::CleanString(ctime(&currenttime));
  130. char current_time[1024];
  131. if (this->ShortDateFormat) {
  132. strftime(current_time, 1000, "%b %d %H:%M %Z", t);
  133. } else {
  134. strftime(current_time, 1000, "%a %b %d %H:%M:%S %Z %Y", t);
  135. }
  136. cmCTestLog(this, DEBUG, " Current_Time: " << current_time << std::endl);
  137. return cmCTest::CleanString(current_time);
  138. }
  139. std::string cmCTest::GetCostDataFile()
  140. {
  141. std::string fname = this->GetCTestConfiguration("CostDataFile");
  142. if (fname.empty()) {
  143. fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt";
  144. }
  145. return fname;
  146. }
  147. #ifdef CMAKE_BUILD_WITH_CMAKE
  148. static size_t HTTPResponseCallback(void* ptr, size_t size, size_t nmemb,
  149. void* data)
  150. {
  151. int realsize = static_cast<int>(size * nmemb);
  152. std::string* response = static_cast<std::string*>(data);
  153. const char* chPtr = static_cast<char*>(ptr);
  154. *response += chPtr;
  155. return realsize;
  156. }
  157. int cmCTest::HTTPRequest(std::string url, HTTPMethod method,
  158. std::string& response, std::string const& fields,
  159. std::string const& putFile, int timeout)
  160. {
  161. CURL* curl;
  162. FILE* file;
  163. ::curl_global_init(CURL_GLOBAL_ALL);
  164. curl = ::curl_easy_init();
  165. cmCurlSetCAInfo(curl);
  166. // set request options based on method
  167. switch (method) {
  168. case cmCTest::HTTP_POST:
  169. ::curl_easy_setopt(curl, CURLOPT_POST, 1);
  170. ::curl_easy_setopt(curl, CURLOPT_POSTFIELDS, fields.c_str());
  171. break;
  172. case cmCTest::HTTP_PUT:
  173. if (!cmSystemTools::FileExists(putFile.c_str())) {
  174. response = "Error: File ";
  175. response += putFile + " does not exist.\n";
  176. return -1;
  177. }
  178. ::curl_easy_setopt(curl, CURLOPT_PUT, 1);
  179. file = cmsys::SystemTools::Fopen(putFile, "rb");
  180. ::curl_easy_setopt(curl, CURLOPT_INFILE, file);
  181. // fall through to append GET fields
  182. CM_FALLTHROUGH;
  183. case cmCTest::HTTP_GET:
  184. if (!fields.empty()) {
  185. url += "?" + fields;
  186. }
  187. break;
  188. }
  189. ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  190. ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  191. ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  192. // set response options
  193. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTTPResponseCallback);
  194. ::curl_easy_setopt(curl, CURLOPT_FILE, &response);
  195. ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  196. CURLcode res = ::curl_easy_perform(curl);
  197. ::curl_easy_cleanup(curl);
  198. ::curl_global_cleanup();
  199. return static_cast<int>(res);
  200. }
  201. #endif
  202. std::string cmCTest::MakeURLSafe(const std::string& str)
  203. {
  204. std::ostringstream ost;
  205. char buffer[10];
  206. for (unsigned char ch : str) {
  207. if ((ch > 126 || ch < 32 || ch == '&' || ch == '%' || ch == '+' ||
  208. ch == '=' || ch == '@') &&
  209. ch != 9) {
  210. sprintf(buffer, "%02x;", static_cast<unsigned int>(ch));
  211. ost << buffer;
  212. } else {
  213. ost << ch;
  214. }
  215. }
  216. return ost.str();
  217. }
  218. std::string cmCTest::DecodeURL(const std::string& in)
  219. {
  220. std::string out;
  221. for (const char* c = in.c_str(); *c; ++c) {
  222. if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
  223. char buf[3] = { *(c + 1), *(c + 2), 0 };
  224. out.append(1, char(strtoul(buf, nullptr, 16)));
  225. c += 2;
  226. } else {
  227. out.append(1, *c);
  228. }
  229. }
  230. return out;
  231. }
  232. cmCTest::cmCTest()
  233. {
  234. this->LabelSummary = true;
  235. this->SubprojectSummary = true;
  236. this->ParallelLevel = 1;
  237. this->ParallelLevelSetInCli = false;
  238. this->TestLoad = 0;
  239. this->SubmitIndex = 0;
  240. this->Failover = false;
  241. this->BatchJobs = false;
  242. this->ForceNewCTestProcess = false;
  243. this->TomorrowTag = false;
  244. this->Verbose = false;
  245. this->Debug = false;
  246. this->ShowLineNumbers = false;
  247. this->Quiet = false;
  248. this->ExtraVerbose = false;
  249. this->ProduceXML = false;
  250. this->ShowOnly = false;
  251. this->RunConfigurationScript = false;
  252. this->UseHTTP10 = false;
  253. this->PrintLabels = false;
  254. this->CompressTestOutput = true;
  255. this->TestModel = cmCTest::EXPERIMENTAL;
  256. this->MaxTestNameWidth = 30;
  257. this->InteractiveDebugMode = true;
  258. this->TimeOut = std::chrono::duration<double>::zero();
  259. this->GlobalTimeout = std::chrono::duration<double>::zero();
  260. this->LastStopTimeout = std::chrono::hours(24);
  261. this->CompressXMLFiles = false;
  262. this->ScheduleType.clear();
  263. this->StopTime.clear();
  264. this->NextDayStopTime = false;
  265. this->OutputLogFile = nullptr;
  266. this->OutputLogFileLastTag = -1;
  267. this->SuppressUpdatingCTestConfiguration = false;
  268. this->DartVersion = 1;
  269. this->DropSiteCDash = false;
  270. this->OutputTestOutputOnTestFailure = false;
  271. this->RepeatTests = 1; // default to run each test once
  272. this->RepeatUntilFail = false;
  273. std::string outOnFail;
  274. if (cmSystemTools::GetEnv("CTEST_OUTPUT_ON_FAILURE", outOnFail)) {
  275. this->OutputTestOutputOnTestFailure =
  276. !cmSystemTools::IsOff(outOnFail.c_str());
  277. }
  278. this->InitStreams();
  279. this->Parts[PartStart].SetName("Start");
  280. this->Parts[PartUpdate].SetName("Update");
  281. this->Parts[PartConfigure].SetName("Configure");
  282. this->Parts[PartBuild].SetName("Build");
  283. this->Parts[PartTest].SetName("Test");
  284. this->Parts[PartCoverage].SetName("Coverage");
  285. this->Parts[PartMemCheck].SetName("MemCheck");
  286. this->Parts[PartSubmit].SetName("Submit");
  287. this->Parts[PartNotes].SetName("Notes");
  288. this->Parts[PartExtraFiles].SetName("ExtraFiles");
  289. this->Parts[PartUpload].SetName("Upload");
  290. // Fill the part name-to-id map.
  291. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  292. this->PartMap[cmSystemTools::LowerCase(this->Parts[p].GetName())] = p;
  293. }
  294. this->ShortDateFormat = true;
  295. this->TestingHandlers["build"] = new cmCTestBuildHandler;
  296. this->TestingHandlers["buildtest"] = new cmCTestBuildAndTestHandler;
  297. this->TestingHandlers["coverage"] = new cmCTestCoverageHandler;
  298. this->TestingHandlers["script"] = new cmCTestScriptHandler;
  299. this->TestingHandlers["test"] = new cmCTestTestHandler;
  300. this->TestingHandlers["update"] = new cmCTestUpdateHandler;
  301. this->TestingHandlers["configure"] = new cmCTestConfigureHandler;
  302. this->TestingHandlers["memcheck"] = new cmCTestMemCheckHandler;
  303. this->TestingHandlers["submit"] = new cmCTestSubmitHandler;
  304. this->TestingHandlers["upload"] = new cmCTestUploadHandler;
  305. for (auto& handler : this->TestingHandlers) {
  306. handler.second->SetCTestInstance(this);
  307. }
  308. // Make sure we can capture the build tool output.
  309. cmSystemTools::EnableVSConsoleOutput();
  310. }
  311. cmCTest::~cmCTest()
  312. {
  313. cmDeleteAll(this->TestingHandlers);
  314. this->SetOutputLogFileName(nullptr);
  315. }
  316. void cmCTest::SetParallelLevel(int level)
  317. {
  318. this->ParallelLevel = level < 1 ? 1 : level;
  319. }
  320. void cmCTest::SetTestLoad(unsigned long load)
  321. {
  322. this->TestLoad = load;
  323. }
  324. bool cmCTest::ShouldCompressTestOutput()
  325. {
  326. return this->CompressTestOutput;
  327. }
  328. cmCTest::Part cmCTest::GetPartFromName(const char* name)
  329. {
  330. // Look up by lower-case to make names case-insensitive.
  331. std::string lower_name = cmSystemTools::LowerCase(name);
  332. PartMapType::const_iterator i = this->PartMap.find(lower_name);
  333. if (i != this->PartMap.end()) {
  334. return i->second;
  335. }
  336. // The string does not name a valid part.
  337. return PartCount;
  338. }
  339. int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
  340. {
  341. bool quiet = false;
  342. if (command && command->ShouldBeQuiet()) {
  343. quiet = true;
  344. }
  345. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  346. if (!this->InteractiveDebugMode) {
  347. this->BlockTestErrorDiagnostics();
  348. } else {
  349. cmSystemTools::PutEnv("CTEST_INTERACTIVE_DEBUG_MODE=1");
  350. }
  351. this->BinaryDir = binary_dir;
  352. cmSystemTools::ConvertToUnixSlashes(this->BinaryDir);
  353. this->UpdateCTestConfiguration();
  354. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  355. if (this->ProduceXML) {
  356. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl, quiet);
  357. cmCTestOptionalLog(
  358. this, OUTPUT, " Site: "
  359. << this->GetCTestConfiguration("Site") << std::endl
  360. << " Build name: "
  361. << cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"))
  362. << std::endl,
  363. quiet);
  364. cmCTestOptionalLog(this, DEBUG, "Produce XML is on" << std::endl, quiet);
  365. if (this->TestModel == cmCTest::NIGHTLY &&
  366. this->GetCTestConfiguration("NightlyStartTime").empty()) {
  367. cmCTestOptionalLog(
  368. this, WARNING,
  369. "WARNING: No nightly start time found please set in CTestConfig.cmake"
  370. " or DartConfig.cmake"
  371. << std::endl,
  372. quiet);
  373. cmCTestOptionalLog(this, DEBUG, "Here: " << __LINE__ << std::endl,
  374. quiet);
  375. return 0;
  376. }
  377. }
  378. cmake cm(cmake::RoleScript);
  379. cm.SetHomeDirectory("");
  380. cm.SetHomeOutputDirectory("");
  381. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  382. cmGlobalGenerator gg(&cm);
  383. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  384. if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), &mf)) {
  385. cmCTestOptionalLog(
  386. this, DEBUG, "Cannot find custom configuration file tree" << std::endl,
  387. quiet);
  388. return 0;
  389. }
  390. if (this->ProduceXML) {
  391. // Verify "Testing" directory exists:
  392. //
  393. std::string testingDir = this->BinaryDir + "/Testing";
  394. if (cmSystemTools::FileExists(testingDir.c_str())) {
  395. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  396. cmCTestLog(this, ERROR_MESSAGE, "File "
  397. << testingDir
  398. << " is in the place of the testing directory"
  399. << std::endl);
  400. return 0;
  401. }
  402. } else {
  403. if (!cmSystemTools::MakeDirectory(testingDir.c_str())) {
  404. cmCTestLog(this, ERROR_MESSAGE, "Cannot create directory "
  405. << testingDir << std::endl);
  406. return 0;
  407. }
  408. }
  409. // Create new "TAG" file or read existing one:
  410. //
  411. bool createNewTag = true;
  412. if (command) {
  413. createNewTag = command->ShouldCreateNewTag();
  414. }
  415. std::string tagfile = testingDir + "/TAG";
  416. cmsys::ifstream tfin(tagfile.c_str());
  417. std::string tag;
  418. if (createNewTag) {
  419. time_t tctime = time(nullptr);
  420. if (this->TomorrowTag) {
  421. tctime += (24 * 60 * 60);
  422. }
  423. struct tm* lctime = gmtime(&tctime);
  424. if (tfin && cmSystemTools::GetLineFromStream(tfin, tag)) {
  425. int year = 0;
  426. int mon = 0;
  427. int day = 0;
  428. int hour = 0;
  429. int min = 0;
  430. sscanf(tag.c_str(), "%04d%02d%02d-%02d%02d", &year, &mon, &day, &hour,
  431. &min);
  432. if (year != lctime->tm_year + 1900 || mon != lctime->tm_mon + 1 ||
  433. day != lctime->tm_mday) {
  434. tag.clear();
  435. }
  436. std::string tagmode;
  437. if (cmSystemTools::GetLineFromStream(tfin, tagmode)) {
  438. if (tagmode.size() > 4 && !this->Parts[PartStart]) {
  439. this->TestModel = cmCTest::GetTestModelFromString(tagmode.c_str());
  440. }
  441. }
  442. tfin.close();
  443. }
  444. if (tag.empty() || (nullptr != command) || this->Parts[PartStart]) {
  445. cmCTestOptionalLog(
  446. this, DEBUG,
  447. "TestModel: " << this->GetTestModelString() << std::endl, quiet);
  448. cmCTestOptionalLog(
  449. this, DEBUG, "TestModel: " << this->TestModel << std::endl, quiet);
  450. if (this->TestModel == cmCTest::NIGHTLY) {
  451. lctime = this->GetNightlyTime(
  452. this->GetCTestConfiguration("NightlyStartTime"),
  453. this->TomorrowTag);
  454. }
  455. char datestring[100];
  456. sprintf(datestring, "%04d%02d%02d-%02d%02d", lctime->tm_year + 1900,
  457. lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour,
  458. lctime->tm_min);
  459. tag = datestring;
  460. cmsys::ofstream ofs(tagfile.c_str());
  461. if (ofs) {
  462. ofs << tag << std::endl;
  463. ofs << this->GetTestModelString() << std::endl;
  464. }
  465. ofs.close();
  466. if (nullptr == command) {
  467. cmCTestOptionalLog(this, OUTPUT, "Create new tag: "
  468. << tag << " - " << this->GetTestModelString()
  469. << std::endl,
  470. quiet);
  471. }
  472. }
  473. } else {
  474. if (tfin) {
  475. cmSystemTools::GetLineFromStream(tfin, tag);
  476. tfin.close();
  477. }
  478. if (tag.empty()) {
  479. cmCTestLog(this, ERROR_MESSAGE, "Cannot read existing TAG file in "
  480. << testingDir << std::endl);
  481. return 0;
  482. }
  483. cmCTestOptionalLog(this, OUTPUT, " Use existing tag: "
  484. << tag << " - " << this->GetTestModelString()
  485. << std::endl,
  486. quiet);
  487. }
  488. this->CurrentTag = tag;
  489. }
  490. return 1;
  491. }
  492. bool cmCTest::InitializeFromCommand(cmCTestStartCommand* command)
  493. {
  494. std::string src_dir = this->GetCTestConfiguration("SourceDirectory");
  495. std::string bld_dir = this->GetCTestConfiguration("BuildDirectory");
  496. this->DartVersion = 1;
  497. this->DropSiteCDash = false;
  498. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  499. this->Parts[p].SubmitFiles.clear();
  500. }
  501. cmMakefile* mf = command->GetMakefile();
  502. std::string fname;
  503. std::string src_dir_fname = src_dir;
  504. src_dir_fname += "/CTestConfig.cmake";
  505. cmSystemTools::ConvertToUnixSlashes(src_dir_fname);
  506. std::string bld_dir_fname = bld_dir;
  507. bld_dir_fname += "/CTestConfig.cmake";
  508. cmSystemTools::ConvertToUnixSlashes(bld_dir_fname);
  509. if (cmSystemTools::FileExists(bld_dir_fname.c_str())) {
  510. fname = bld_dir_fname;
  511. } else if (cmSystemTools::FileExists(src_dir_fname.c_str())) {
  512. fname = src_dir_fname;
  513. }
  514. if (!fname.empty()) {
  515. cmCTestOptionalLog(this, OUTPUT, " Reading ctest configuration file: "
  516. << fname << std::endl,
  517. command->ShouldBeQuiet());
  518. bool readit = mf->ReadDependentFile(fname.c_str());
  519. if (!readit) {
  520. std::string m = "Could not find include file: ";
  521. m += fname;
  522. command->SetError(m);
  523. return false;
  524. }
  525. } else {
  526. cmCTestOptionalLog(this, WARNING,
  527. "Cannot locate CTest configuration: in BuildDirectory: "
  528. << bld_dir_fname << std::endl,
  529. command->ShouldBeQuiet());
  530. cmCTestOptionalLog(
  531. this, WARNING, "Cannot locate CTest configuration: in SourceDirectory: "
  532. << src_dir_fname << std::endl,
  533. command->ShouldBeQuiet());
  534. }
  535. this->SetCTestConfigurationFromCMakeVariable(mf, "NightlyStartTime",
  536. "CTEST_NIGHTLY_START_TIME",
  537. command->ShouldBeQuiet());
  538. this->SetCTestConfigurationFromCMakeVariable(mf, "Site", "CTEST_SITE",
  539. command->ShouldBeQuiet());
  540. this->SetCTestConfigurationFromCMakeVariable(
  541. mf, "BuildName", "CTEST_BUILD_NAME", command->ShouldBeQuiet());
  542. const char* dartVersion = mf->GetDefinition("CTEST_DART_SERVER_VERSION");
  543. if (dartVersion) {
  544. this->DartVersion = atoi(dartVersion);
  545. if (this->DartVersion < 0) {
  546. cmCTestLog(this, ERROR_MESSAGE, "Invalid Dart server version: "
  547. << dartVersion << ". Please specify the version number."
  548. << std::endl);
  549. return false;
  550. }
  551. }
  552. this->DropSiteCDash = mf->IsOn("CTEST_DROP_SITE_CDASH");
  553. if (!this->Initialize(bld_dir.c_str(), command)) {
  554. return false;
  555. }
  556. cmCTestOptionalLog(this, OUTPUT, " Use "
  557. << this->GetTestModelString()
  558. << " tag: " << this->GetCurrentTag() << std::endl,
  559. command->ShouldBeQuiet());
  560. return true;
  561. }
  562. bool cmCTest::UpdateCTestConfiguration()
  563. {
  564. if (this->SuppressUpdatingCTestConfiguration) {
  565. return true;
  566. }
  567. std::string fileName = this->BinaryDir + "/CTestConfiguration.ini";
  568. if (!cmSystemTools::FileExists(fileName.c_str())) {
  569. fileName = this->BinaryDir + "/DartConfiguration.tcl";
  570. }
  571. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  572. "UpdateCTestConfiguration from :" << fileName << "\n");
  573. if (!cmSystemTools::FileExists(fileName.c_str())) {
  574. // No need to exit if we are not producing XML
  575. if (this->ProduceXML) {
  576. cmCTestLog(this, ERROR_MESSAGE, "Cannot find file: " << fileName
  577. << std::endl);
  578. return false;
  579. }
  580. } else {
  581. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Parse Config file:" << fileName
  582. << "\n");
  583. // parse the dart test file
  584. cmsys::ifstream fin(fileName.c_str());
  585. if (!fin) {
  586. return false;
  587. }
  588. char buffer[1024];
  589. while (fin) {
  590. buffer[0] = 0;
  591. fin.getline(buffer, 1023);
  592. buffer[1023] = 0;
  593. std::string line = cmCTest::CleanString(buffer);
  594. if (line.empty()) {
  595. continue;
  596. }
  597. while (fin && (line[line.size() - 1] == '\\')) {
  598. line = line.substr(0, line.size() - 1);
  599. buffer[0] = 0;
  600. fin.getline(buffer, 1023);
  601. buffer[1023] = 0;
  602. line += cmCTest::CleanString(buffer);
  603. }
  604. if (line[0] == '#') {
  605. continue;
  606. }
  607. std::string::size_type cpos = line.find_first_of(':');
  608. if (cpos == std::string::npos) {
  609. continue;
  610. }
  611. std::string key = line.substr(0, cpos);
  612. std::string value = cmCTest::CleanString(line.substr(cpos + 1));
  613. this->CTestConfiguration[key] = value;
  614. }
  615. fin.close();
  616. }
  617. if (!this->GetCTestConfiguration("BuildDirectory").empty()) {
  618. this->BinaryDir = this->GetCTestConfiguration("BuildDirectory");
  619. cmSystemTools::ChangeDirectory(this->BinaryDir);
  620. }
  621. this->TimeOut =
  622. std::chrono::seconds(atoi(this->GetCTestConfiguration("TimeOut").c_str()));
  623. std::string const& testLoad = this->GetCTestConfiguration("TestLoad");
  624. if (!testLoad.empty()) {
  625. unsigned long load;
  626. if (cmSystemTools::StringToULong(testLoad.c_str(), &load)) {
  627. this->SetTestLoad(load);
  628. } else {
  629. cmCTestLog(this, WARNING,
  630. "Invalid value for 'Test Load' : " << testLoad << std::endl);
  631. }
  632. }
  633. if (this->ProduceXML) {
  634. this->CompressXMLFiles = cmSystemTools::IsOn(
  635. this->GetCTestConfiguration("CompressSubmission").c_str());
  636. }
  637. return true;
  638. }
  639. void cmCTest::BlockTestErrorDiagnostics()
  640. {
  641. cmSystemTools::PutEnv("DART_TEST_FROM_DART=1");
  642. cmSystemTools::PutEnv("DASHBOARD_TEST_FROM_CTEST=" CMake_VERSION);
  643. #if defined(_WIN32)
  644. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
  645. #elif defined(__BEOS__) || defined(__HAIKU__)
  646. disable_debugger(1);
  647. #endif
  648. }
  649. void cmCTest::SetTestModel(int mode)
  650. {
  651. this->InteractiveDebugMode = false;
  652. this->TestModel = mode;
  653. }
  654. bool cmCTest::SetTest(const char* ttype, bool report)
  655. {
  656. if (cmSystemTools::LowerCase(ttype) == "all") {
  657. for (Part p = PartStart; p != PartCount; p = Part(p + 1)) {
  658. this->Parts[p].Enable();
  659. }
  660. return true;
  661. }
  662. Part p = this->GetPartFromName(ttype);
  663. if (p != PartCount) {
  664. this->Parts[p].Enable();
  665. return true;
  666. }
  667. if (report) {
  668. cmCTestLog(this, ERROR_MESSAGE, "Don't know about test \""
  669. << ttype << "\" yet..." << std::endl);
  670. }
  671. return false;
  672. }
  673. void cmCTest::Finalize()
  674. {
  675. }
  676. bool cmCTest::OpenOutputFile(const std::string& path, const std::string& name,
  677. cmGeneratedFileStream& stream, bool compress)
  678. {
  679. std::string testingDir = this->BinaryDir + "/Testing";
  680. if (!path.empty()) {
  681. testingDir += "/" + path;
  682. }
  683. if (cmSystemTools::FileExists(testingDir.c_str())) {
  684. if (!cmSystemTools::FileIsDirectory(testingDir)) {
  685. cmCTestLog(this, ERROR_MESSAGE, "File "
  686. << testingDir << " is in the place of the testing directory"
  687. << std::endl);
  688. return false;
  689. }
  690. } else {
  691. if (!cmSystemTools::MakeDirectory(testingDir.c_str())) {
  692. cmCTestLog(this, ERROR_MESSAGE, "Cannot create directory " << testingDir
  693. << std::endl);
  694. return false;
  695. }
  696. }
  697. std::string filename = testingDir + "/" + name;
  698. stream.Open(filename.c_str());
  699. if (!stream) {
  700. cmCTestLog(this, ERROR_MESSAGE, "Problem opening file: " << filename
  701. << std::endl);
  702. return false;
  703. }
  704. if (compress) {
  705. if (this->CompressXMLFiles) {
  706. stream.SetCompression(true);
  707. }
  708. }
  709. return true;
  710. }
  711. bool cmCTest::AddIfExists(Part part, const char* file)
  712. {
  713. if (this->CTestFileExists(file)) {
  714. this->AddSubmitFile(part, file);
  715. } else {
  716. std::string name = file;
  717. name += ".gz";
  718. if (this->CTestFileExists(name)) {
  719. this->AddSubmitFile(part, file);
  720. } else {
  721. return false;
  722. }
  723. }
  724. return true;
  725. }
  726. bool cmCTest::CTestFileExists(const std::string& filename)
  727. {
  728. std::string testingDir =
  729. this->BinaryDir + "/Testing/" + this->CurrentTag + "/" + filename;
  730. return cmSystemTools::FileExists(testingDir.c_str());
  731. }
  732. cmCTestGenericHandler* cmCTest::GetInitializedHandler(const char* handler)
  733. {
  734. cmCTest::t_TestingHandlers::iterator it =
  735. this->TestingHandlers.find(handler);
  736. if (it == this->TestingHandlers.end()) {
  737. return nullptr;
  738. }
  739. it->second->Initialize();
  740. return it->second;
  741. }
  742. cmCTestGenericHandler* cmCTest::GetHandler(const char* handler)
  743. {
  744. cmCTest::t_TestingHandlers::iterator it =
  745. this->TestingHandlers.find(handler);
  746. if (it == this->TestingHandlers.end()) {
  747. return nullptr;
  748. }
  749. return it->second;
  750. }
  751. int cmCTest::ExecuteHandler(const char* shandler)
  752. {
  753. cmCTestGenericHandler* handler = this->GetHandler(shandler);
  754. if (!handler) {
  755. return -1;
  756. }
  757. handler->Initialize();
  758. return handler->ProcessHandler();
  759. }
  760. int cmCTest::ProcessSteps()
  761. {
  762. int res = 0;
  763. bool notest = true;
  764. int update_count = 0;
  765. for (Part p = PartStart; notest && p != PartCount; p = Part(p + 1)) {
  766. notest = !this->Parts[p];
  767. }
  768. if (this->Parts[PartUpdate] &&
  769. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  770. cmCTestGenericHandler* uphandler = this->GetHandler("update");
  771. uphandler->SetPersistentOption(
  772. "SourceDirectory",
  773. this->GetCTestConfiguration("SourceDirectory").c_str());
  774. update_count = uphandler->ProcessHandler();
  775. if (update_count < 0) {
  776. res |= cmCTest::UPDATE_ERRORS;
  777. }
  778. }
  779. if (this->TestModel == cmCTest::CONTINUOUS && !update_count) {
  780. return 0;
  781. }
  782. if (this->Parts[PartConfigure] &&
  783. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  784. if (this->GetHandler("configure")->ProcessHandler() < 0) {
  785. res |= cmCTest::CONFIGURE_ERRORS;
  786. }
  787. }
  788. if (this->Parts[PartBuild] &&
  789. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  790. this->UpdateCTestConfiguration();
  791. if (this->GetHandler("build")->ProcessHandler() < 0) {
  792. res |= cmCTest::BUILD_ERRORS;
  793. }
  794. }
  795. if ((this->Parts[PartTest] || notest) &&
  796. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  797. this->UpdateCTestConfiguration();
  798. if (this->GetHandler("test")->ProcessHandler() < 0) {
  799. res |= cmCTest::TEST_ERRORS;
  800. }
  801. }
  802. if (this->Parts[PartCoverage] &&
  803. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  804. this->UpdateCTestConfiguration();
  805. if (this->GetHandler("coverage")->ProcessHandler() < 0) {
  806. res |= cmCTest::COVERAGE_ERRORS;
  807. }
  808. }
  809. if (this->Parts[PartMemCheck] &&
  810. (this->GetRemainingTimeAllowed() > std::chrono::minutes(2))) {
  811. this->UpdateCTestConfiguration();
  812. if (this->GetHandler("memcheck")->ProcessHandler() < 0) {
  813. res |= cmCTest::MEMORY_ERRORS;
  814. }
  815. }
  816. if (!notest) {
  817. std::string notes_dir = this->BinaryDir + "/Testing/Notes";
  818. if (cmSystemTools::FileIsDirectory(notes_dir)) {
  819. cmsys::Directory d;
  820. d.Load(notes_dir);
  821. unsigned long kk;
  822. for (kk = 0; kk < d.GetNumberOfFiles(); kk++) {
  823. const char* file = d.GetFile(kk);
  824. std::string fullname = notes_dir + "/" + file;
  825. if (cmSystemTools::FileExists(fullname.c_str()) &&
  826. !cmSystemTools::FileIsDirectory(fullname)) {
  827. if (!this->NotesFiles.empty()) {
  828. this->NotesFiles += ";";
  829. }
  830. this->NotesFiles += fullname;
  831. this->Parts[PartNotes].Enable();
  832. }
  833. }
  834. }
  835. }
  836. if (this->Parts[PartNotes]) {
  837. this->UpdateCTestConfiguration();
  838. if (!this->NotesFiles.empty()) {
  839. this->GenerateNotesFile(this->NotesFiles.c_str());
  840. }
  841. }
  842. if (this->Parts[PartSubmit]) {
  843. this->UpdateCTestConfiguration();
  844. if (this->GetHandler("submit")->ProcessHandler() < 0) {
  845. res |= cmCTest::SUBMIT_ERRORS;
  846. }
  847. }
  848. if (res != 0) {
  849. cmCTestLog(this, ERROR_MESSAGE, "Errors while running CTest" << std::endl);
  850. }
  851. return res;
  852. }
  853. std::string cmCTest::GetTestModelString()
  854. {
  855. if (!this->SpecificTrack.empty()) {
  856. return this->SpecificTrack;
  857. }
  858. switch (this->TestModel) {
  859. case cmCTest::NIGHTLY:
  860. return "Nightly";
  861. case cmCTest::CONTINUOUS:
  862. return "Continuous";
  863. }
  864. return "Experimental";
  865. }
  866. int cmCTest::GetTestModelFromString(const char* str)
  867. {
  868. if (!str) {
  869. return cmCTest::EXPERIMENTAL;
  870. }
  871. std::string rstr = cmSystemTools::LowerCase(str);
  872. if (cmHasLiteralPrefix(rstr.c_str(), "cont")) {
  873. return cmCTest::CONTINUOUS;
  874. }
  875. if (cmHasLiteralPrefix(rstr.c_str(), "nigh")) {
  876. return cmCTest::NIGHTLY;
  877. }
  878. return cmCTest::EXPERIMENTAL;
  879. }
  880. //######################################################################
  881. //######################################################################
  882. //######################################################################
  883. //######################################################################
  884. int cmCTest::RunMakeCommand(const char* command, std::string& output,
  885. int* retVal, const char* dir,
  886. std::chrono::duration<double> timeout,
  887. std::ostream& ofs, Encoding encoding)
  888. {
  889. // First generate the command and arguments
  890. std::vector<std::string> args = cmSystemTools::ParseArguments(command);
  891. if (args.empty()) {
  892. return false;
  893. }
  894. std::vector<const char*> argv;
  895. argv.reserve(args.size() + 1);
  896. for (std::string const& a : args) {
  897. argv.push_back(a.c_str());
  898. }
  899. argv.push_back(nullptr);
  900. output.clear();
  901. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
  902. for (char const* arg : argv) {
  903. if (!arg) {
  904. break;
  905. }
  906. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
  907. }
  908. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
  909. // Now create process object
  910. cmsysProcess* cp = cmsysProcess_New();
  911. cmsysProcess_SetCommand(cp, &*argv.begin());
  912. cmsysProcess_SetWorkingDirectory(cp, dir);
  913. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  914. cmsysProcess_SetTimeout(cp, timeout.count());
  915. cmsysProcess_Execute(cp);
  916. // Initialize tick's
  917. std::string::size_type tick = 0;
  918. std::string::size_type tick_len = 1024;
  919. std::string::size_type tick_line_len = 50;
  920. char* data;
  921. int length;
  922. cmProcessOutput processOutput(encoding);
  923. std::string strdata;
  924. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Each . represents "
  925. << tick_len << " bytes of output" << std::endl
  926. << " " << std::flush);
  927. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  928. processOutput.DecodeText(data, length, strdata);
  929. for (char& cc : strdata) {
  930. if (cc == 0) {
  931. cc = '\n';
  932. }
  933. }
  934. output.append(strdata);
  935. while (output.size() > (tick * tick_len)) {
  936. tick++;
  937. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, "." << std::flush);
  938. if (tick % tick_line_len == 0 && tick > 0) {
  939. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT,
  940. " Size: " << int((double(output.size()) / 1024.0) + 1)
  941. << "K" << std::endl
  942. << " " << std::flush);
  943. }
  944. }
  945. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  946. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  947. if (ofs) {
  948. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  949. }
  950. }
  951. processOutput.DecodeText(std::string(), strdata);
  952. if (!strdata.empty()) {
  953. output.append(strdata);
  954. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  955. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  956. if (ofs) {
  957. ofs << cmCTestLogWrite(strdata.c_str(), strdata.size());
  958. }
  959. }
  960. cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Size of output: "
  961. << int(double(output.size()) / 1024.0) << "K" << std::endl);
  962. cmsysProcess_WaitForExit(cp, nullptr);
  963. int result = cmsysProcess_GetState(cp);
  964. if (result == cmsysProcess_State_Exited) {
  965. *retVal = cmsysProcess_GetExitValue(cp);
  966. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  967. "Command exited with the value: " << *retVal << std::endl);
  968. } else if (result == cmsysProcess_State_Exception) {
  969. *retVal = cmsysProcess_GetExitException(cp);
  970. cmCTestLog(this, WARNING, "There was an exception: " << *retVal
  971. << std::endl);
  972. } else if (result == cmsysProcess_State_Expired) {
  973. cmCTestLog(this, WARNING, "There was a timeout" << std::endl);
  974. } else if (result == cmsysProcess_State_Error) {
  975. output += "\n*** ERROR executing: ";
  976. output += cmsysProcess_GetErrorString(cp);
  977. output += "\n***The build process failed.";
  978. cmCTestLog(this, ERROR_MESSAGE, "There was an error: "
  979. << cmsysProcess_GetErrorString(cp) << std::endl);
  980. }
  981. cmsysProcess_Delete(cp);
  982. return result;
  983. }
  984. //######################################################################
  985. //######################################################################
  986. //######################################################################
  987. //######################################################################
  988. int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
  989. int* retVal, std::ostream* log,
  990. std::chrono::duration<double> testTimeOut,
  991. std::vector<std::string>* environment, Encoding encoding)
  992. {
  993. bool modifyEnv = (environment && !environment->empty());
  994. // determine how much time we have
  995. std::chrono::duration<double> timeout = this->GetRemainingTimeAllowed();
  996. if (timeout != cmCTest::MaxDuration()) {
  997. timeout -= std::chrono::minutes(2);
  998. }
  999. if (this->TimeOut > std::chrono::duration<double>::zero() &&
  1000. this->TimeOut < timeout) {
  1001. timeout = this->TimeOut;
  1002. }
  1003. if (testTimeOut > std::chrono::duration<double>::zero() &&
  1004. testTimeOut < this->GetRemainingTimeAllowed()) {
  1005. timeout = testTimeOut;
  1006. }
  1007. // always have at least 1 second if we got to here
  1008. if (timeout <= std::chrono::duration<double>::zero()) {
  1009. timeout = std::chrono::seconds(1);
  1010. }
  1011. cmCTestLog(
  1012. this, HANDLER_VERBOSE_OUTPUT, "Test timeout computed to be: "
  1013. << (timeout == cmCTest::MaxDuration()
  1014. ? std::string("infinite")
  1015. : std::to_string(
  1016. std::chrono::duration_cast<std::chrono::seconds>(timeout)
  1017. .count()))
  1018. << "\n");
  1019. if (cmSystemTools::SameFile(argv[0], cmSystemTools::GetCTestCommand()) &&
  1020. !this->ForceNewCTestProcess) {
  1021. cmCTest inst;
  1022. inst.ConfigType = this->ConfigType;
  1023. inst.TimeOut = timeout;
  1024. // Capture output of the child ctest.
  1025. std::ostringstream oss;
  1026. inst.SetStreams(&oss, &oss);
  1027. std::vector<std::string> args;
  1028. for (char const* i : argv) {
  1029. if (i) {
  1030. // make sure we pass the timeout in for any build and test
  1031. // invocations. Since --build-generator is required this is a
  1032. // good place to check for it, and to add the arguments in
  1033. if (strcmp(i, "--build-generator") == 0 &&
  1034. timeout != cmCTest::MaxDuration() &&
  1035. timeout > std::chrono::duration<double>::zero()) {
  1036. args.push_back("--test-timeout");
  1037. std::ostringstream msg;
  1038. msg << std::chrono::duration_cast<std::chrono::seconds>(timeout)
  1039. .count();
  1040. args.push_back(msg.str());
  1041. }
  1042. args.push_back(i);
  1043. }
  1044. }
  1045. if (log) {
  1046. *log << "* Run internal CTest" << std::endl;
  1047. }
  1048. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1049. if (modifyEnv) {
  1050. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1051. cmSystemTools::AppendEnv(*environment);
  1052. }
  1053. *retVal = inst.Run(args, output);
  1054. if (output) {
  1055. *output += oss.str();
  1056. }
  1057. if (log && output) {
  1058. *log << *output;
  1059. }
  1060. if (output) {
  1061. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1062. "Internal cmCTest object used to run test." << std::endl
  1063. << *output
  1064. << std::endl);
  1065. }
  1066. return cmsysProcess_State_Exited;
  1067. }
  1068. std::vector<char> tempOutput;
  1069. if (output) {
  1070. output->clear();
  1071. }
  1072. std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
  1073. if (modifyEnv) {
  1074. saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
  1075. cmSystemTools::AppendEnv(*environment);
  1076. }
  1077. cmsysProcess* cp = cmsysProcess_New();
  1078. cmsysProcess_SetCommand(cp, &*argv.begin());
  1079. cmCTestLog(this, DEBUG, "Command is: " << argv[0] << std::endl);
  1080. if (cmSystemTools::GetRunCommandHideConsole()) {
  1081. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  1082. }
  1083. cmsysProcess_SetTimeout(cp, timeout.count());
  1084. cmsysProcess_Execute(cp);
  1085. char* data;
  1086. int length;
  1087. cmProcessOutput processOutput(encoding);
  1088. std::string strdata;
  1089. while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
  1090. processOutput.DecodeText(data, length, strdata);
  1091. if (output) {
  1092. tempOutput.insert(tempOutput.end(), data, data + length);
  1093. }
  1094. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1095. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1096. if (log) {
  1097. log->write(strdata.c_str(), strdata.size());
  1098. }
  1099. }
  1100. processOutput.DecodeText(std::string(), strdata);
  1101. if (!strdata.empty()) {
  1102. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT,
  1103. cmCTestLogWrite(strdata.c_str(), strdata.size()));
  1104. if (log) {
  1105. log->write(strdata.c_str(), strdata.size());
  1106. }
  1107. }
  1108. cmsysProcess_WaitForExit(cp, nullptr);
  1109. processOutput.DecodeText(tempOutput, tempOutput);
  1110. if (output && tempOutput.begin() != tempOutput.end()) {
  1111. output->append(&*tempOutput.begin(), tempOutput.size());
  1112. }
  1113. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "-- Process completed"
  1114. << std::endl);
  1115. int result = cmsysProcess_GetState(cp);
  1116. if (result == cmsysProcess_State_Exited) {
  1117. *retVal = cmsysProcess_GetExitValue(cp);
  1118. if (*retVal != 0 && this->OutputTestOutputOnTestFailure) {
  1119. OutputTestErrors(tempOutput);
  1120. }
  1121. } else if (result == cmsysProcess_State_Exception) {
  1122. if (this->OutputTestOutputOnTestFailure) {
  1123. OutputTestErrors(tempOutput);
  1124. }
  1125. *retVal = cmsysProcess_GetExitException(cp);
  1126. std::string outerr = "\n*** Exception executing: ";
  1127. outerr += cmsysProcess_GetExceptionString(cp);
  1128. if (output) {
  1129. *output += outerr;
  1130. }
  1131. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr << std::endl
  1132. << std::flush);
  1133. } else if (result == cmsysProcess_State_Error) {
  1134. std::string outerr = "\n*** ERROR executing: ";
  1135. outerr += cmsysProcess_GetErrorString(cp);
  1136. if (output) {
  1137. *output += outerr;
  1138. }
  1139. cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, outerr << std::endl
  1140. << std::flush);
  1141. }
  1142. cmsysProcess_Delete(cp);
  1143. return result;
  1144. }
  1145. std::string cmCTest::SafeBuildIdField(const std::string& value)
  1146. {
  1147. std::string safevalue(value);
  1148. if (!safevalue.empty()) {
  1149. // Disallow non-filename and non-space whitespace characters.
  1150. // If they occur, replace them with ""
  1151. //
  1152. const char* disallowed = "\\:*?\"<>|\n\r\t\f\v";
  1153. if (safevalue.find_first_of(disallowed) != std::string::npos) {
  1154. std::string::size_type i = 0;
  1155. std::string::size_type n = strlen(disallowed);
  1156. char replace[2];
  1157. replace[1] = 0;
  1158. for (i = 0; i < n; ++i) {
  1159. replace[0] = disallowed[i];
  1160. cmSystemTools::ReplaceString(safevalue, replace, "");
  1161. }
  1162. }
  1163. }
  1164. if (safevalue.empty()) {
  1165. safevalue = "(empty)";
  1166. }
  1167. return safevalue;
  1168. }
  1169. void cmCTest::StartXML(cmXMLWriter& xml, bool append)
  1170. {
  1171. if (this->CurrentTag.empty()) {
  1172. cmCTestLog(this, ERROR_MESSAGE, "Current Tag empty, this may mean"
  1173. " NightlStartTime was not set correctly."
  1174. << std::endl);
  1175. cmSystemTools::SetFatalErrorOccured();
  1176. }
  1177. // find out about the system
  1178. cmsys::SystemInformation info;
  1179. info.RunCPUCheck();
  1180. info.RunOSCheck();
  1181. info.RunMemoryCheck();
  1182. std::string buildname =
  1183. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1184. std::string stamp = cmCTest::SafeBuildIdField(this->CurrentTag + "-" +
  1185. this->GetTestModelString());
  1186. std::string site =
  1187. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("Site"));
  1188. xml.StartDocument();
  1189. xml.StartElement("Site");
  1190. xml.Attribute("BuildName", buildname);
  1191. xml.BreakAttributes();
  1192. xml.Attribute("BuildStamp", stamp);
  1193. xml.Attribute("Name", site);
  1194. xml.Attribute("Generator",
  1195. std::string("ctest-") + cmVersion::GetCMakeVersion());
  1196. if (append) {
  1197. xml.Attribute("Append", "true");
  1198. }
  1199. xml.Attribute("CompilerName", this->GetCTestConfiguration("Compiler"));
  1200. xml.Attribute("CompilerVersion",
  1201. this->GetCTestConfiguration("CompilerVersion"));
  1202. xml.Attribute("OSName", info.GetOSName());
  1203. xml.Attribute("Hostname", info.GetHostname());
  1204. xml.Attribute("OSRelease", info.GetOSRelease());
  1205. xml.Attribute("OSVersion", info.GetOSVersion());
  1206. xml.Attribute("OSPlatform", info.GetOSPlatform());
  1207. xml.Attribute("Is64Bits", info.Is64Bits());
  1208. xml.Attribute("VendorString", info.GetVendorString());
  1209. xml.Attribute("VendorID", info.GetVendorID());
  1210. xml.Attribute("FamilyID", info.GetFamilyID());
  1211. xml.Attribute("ModelID", info.GetModelID());
  1212. xml.Attribute("ProcessorCacheSize", info.GetProcessorCacheSize());
  1213. xml.Attribute("NumberOfLogicalCPU", info.GetNumberOfLogicalCPU());
  1214. xml.Attribute("NumberOfPhysicalCPU", info.GetNumberOfPhysicalCPU());
  1215. xml.Attribute("TotalVirtualMemory", info.GetTotalVirtualMemory());
  1216. xml.Attribute("TotalPhysicalMemory", info.GetTotalPhysicalMemory());
  1217. xml.Attribute("LogicalProcessorsPerPhysical",
  1218. info.GetLogicalProcessorsPerPhysical());
  1219. xml.Attribute("ProcessorClockFrequency", info.GetProcessorClockFrequency());
  1220. std::string changeId = this->GetCTestConfiguration("ChangeId");
  1221. if (!changeId.empty()) {
  1222. xml.Attribute("ChangeId", changeId);
  1223. }
  1224. this->AddSiteProperties(xml);
  1225. }
  1226. void cmCTest::AddSiteProperties(cmXMLWriter& xml)
  1227. {
  1228. cmCTestScriptHandler* ch =
  1229. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1230. cmake* cm = ch->GetCMake();
  1231. // if no CMake then this is the old style script and props like
  1232. // this will not work anyway.
  1233. if (!cm) {
  1234. return;
  1235. }
  1236. // This code should go when cdash is changed to use labels only
  1237. const char* subproject = cm->GetState()->GetGlobalProperty("SubProject");
  1238. if (subproject) {
  1239. xml.StartElement("Subproject");
  1240. xml.Attribute("name", subproject);
  1241. const char* labels =
  1242. ch->GetCMake()->GetState()->GetGlobalProperty("SubProjectLabels");
  1243. if (labels) {
  1244. xml.StartElement("Labels");
  1245. std::string l = labels;
  1246. std::vector<std::string> args;
  1247. cmSystemTools::ExpandListArgument(l, args);
  1248. for (std::string const& i : args) {
  1249. xml.Element("Label", i);
  1250. }
  1251. xml.EndElement();
  1252. }
  1253. xml.EndElement();
  1254. }
  1255. // This code should stay when cdash only does label based sub-projects
  1256. const char* label = cm->GetState()->GetGlobalProperty("Label");
  1257. if (label) {
  1258. xml.StartElement("Labels");
  1259. xml.Element("Label", label);
  1260. xml.EndElement();
  1261. }
  1262. }
  1263. void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
  1264. {
  1265. for (std::string const& subproj : this->GetLabelsForSubprojects()) {
  1266. xml.StartElement("Subproject");
  1267. xml.Attribute("name", subproj);
  1268. xml.Element("Label", subproj);
  1269. xml.EndElement(); // Subproject
  1270. }
  1271. }
  1272. std::vector<std::string> cmCTest::GetLabelsForSubprojects()
  1273. {
  1274. std::string labelsForSubprojects =
  1275. this->GetCTestConfiguration("LabelsForSubprojects");
  1276. std::vector<std::string> subprojects;
  1277. cmSystemTools::ExpandListArgument(labelsForSubprojects, subprojects);
  1278. // sort the array
  1279. std::sort(subprojects.begin(), subprojects.end());
  1280. // remove duplicates
  1281. std::vector<std::string>::iterator new_end =
  1282. std::unique(subprojects.begin(), subprojects.end());
  1283. subprojects.erase(new_end, subprojects.end());
  1284. return subprojects;
  1285. }
  1286. void cmCTest::EndXML(cmXMLWriter& xml)
  1287. {
  1288. xml.EndElement(); // Site
  1289. xml.EndDocument();
  1290. }
  1291. int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
  1292. const cmCTest::VectorOfStrings& files)
  1293. {
  1294. std::string buildname =
  1295. cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
  1296. xml.StartDocument();
  1297. xml.ProcessingInstruction("xml-stylesheet",
  1298. "type=\"text/xsl\" "
  1299. "href=\"Dart/Source/Server/XSL/Build.xsl "
  1300. "<file:///Dart/Source/Server/XSL/Build.xsl> \"");
  1301. xml.StartElement("Site");
  1302. xml.Attribute("BuildName", buildname);
  1303. xml.Attribute("BuildStamp",
  1304. this->CurrentTag + "-" + this->GetTestModelString());
  1305. xml.Attribute("Name", this->GetCTestConfiguration("Site"));
  1306. xml.Attribute("Generator",
  1307. std::string("ctest") + cmVersion::GetCMakeVersion());
  1308. this->AddSiteProperties(xml);
  1309. xml.StartElement("Notes");
  1310. for (cmsys::String const& file : files) {
  1311. cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
  1312. std::string note_time = this->CurrentTime();
  1313. xml.StartElement("Note");
  1314. xml.Attribute("Name", file);
  1315. xml.Element("Time", std::chrono::system_clock::now());
  1316. xml.Element("DateTime", note_time);
  1317. xml.StartElement("Text");
  1318. cmsys::ifstream ifs(file.c_str());
  1319. if (ifs) {
  1320. std::string line;
  1321. while (cmSystemTools::GetLineFromStream(ifs, line)) {
  1322. xml.Content(line);
  1323. xml.Content("\n");
  1324. }
  1325. ifs.close();
  1326. } else {
  1327. xml.Content("Problem reading file: " + file + "\n");
  1328. cmCTestLog(this, ERROR_MESSAGE, "Problem reading file: "
  1329. << file << " while creating notes" << std::endl);
  1330. }
  1331. xml.EndElement(); // Text
  1332. xml.EndElement(); // Note
  1333. }
  1334. xml.EndElement(); // Notes
  1335. xml.EndElement(); // Site
  1336. xml.EndDocument();
  1337. return 1;
  1338. }
  1339. int cmCTest::GenerateNotesFile(const VectorOfStrings& files)
  1340. {
  1341. cmGeneratedFileStream ofs;
  1342. if (!this->OpenOutputFile(this->CurrentTag, "Notes.xml", ofs)) {
  1343. cmCTestLog(this, ERROR_MESSAGE, "Cannot open notes file" << std::endl);
  1344. return 1;
  1345. }
  1346. cmXMLWriter xml(ofs);
  1347. this->GenerateCTestNotesOutput(xml, files);
  1348. return 0;
  1349. }
  1350. int cmCTest::GenerateNotesFile(const char* cfiles)
  1351. {
  1352. if (!cfiles) {
  1353. return 1;
  1354. }
  1355. VectorOfStrings files;
  1356. cmCTestLog(this, OUTPUT, "Create notes file" << std::endl);
  1357. files = cmSystemTools::SplitString(cfiles, ';');
  1358. if (files.empty()) {
  1359. return 1;
  1360. }
  1361. return this->GenerateNotesFile(files);
  1362. }
  1363. std::string cmCTest::Base64GzipEncodeFile(std::string const& file)
  1364. {
  1365. std::string tarFile = file + "_temp.tar.gz";
  1366. std::vector<std::string> files;
  1367. files.push_back(file);
  1368. if (!cmSystemTools::CreateTar(tarFile.c_str(), files,
  1369. cmSystemTools::TarCompressGZip, false)) {
  1370. cmCTestLog(this, ERROR_MESSAGE, "Error creating tar while "
  1371. "encoding file: "
  1372. << file << std::endl);
  1373. return "";
  1374. }
  1375. std::string base64 = this->Base64EncodeFile(tarFile);
  1376. cmSystemTools::RemoveFile(tarFile);
  1377. return base64;
  1378. }
  1379. std::string cmCTest::Base64EncodeFile(std::string const& file)
  1380. {
  1381. size_t const len = cmSystemTools::FileLength(file);
  1382. cmsys::ifstream ifs(file.c_str(), std::ios::in
  1383. #ifdef _WIN32
  1384. | std::ios::binary
  1385. #endif
  1386. );
  1387. std::vector<char> file_buffer(len + 1);
  1388. ifs.read(&file_buffer[0], len);
  1389. ifs.close();
  1390. std::vector<char> encoded_buffer((len * 3) / 2 + 5);
  1391. size_t const rlen = cmsysBase64_Encode(
  1392. reinterpret_cast<unsigned char*>(&file_buffer[0]), len,
  1393. reinterpret_cast<unsigned char*>(&encoded_buffer[0]), 1);
  1394. return std::string(&encoded_buffer[0], rlen);
  1395. }
  1396. bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
  1397. {
  1398. for (cmsys::String const& file : files) {
  1399. if (!cmSystemTools::FileExists(file.c_str())) {
  1400. cmCTestLog(this, ERROR_MESSAGE, "Cannot find extra file: "
  1401. << file << " to submit." << std::endl;);
  1402. return false;
  1403. }
  1404. this->AddSubmitFile(PartExtraFiles, file.c_str());
  1405. }
  1406. return true;
  1407. }
  1408. bool cmCTest::SubmitExtraFiles(const char* cfiles)
  1409. {
  1410. if (!cfiles) {
  1411. return true;
  1412. }
  1413. VectorOfStrings files;
  1414. cmCTestLog(this, OUTPUT, "Submit extra files" << std::endl);
  1415. files = cmSystemTools::SplitString(cfiles, ';');
  1416. if (files.empty()) {
  1417. return true;
  1418. }
  1419. return this->SubmitExtraFiles(files);
  1420. }
  1421. // for a -D argument convert the next argument into
  1422. // the proper list of dashboard steps via SetTest
  1423. bool cmCTest::AddTestsForDashboardType(std::string& targ)
  1424. {
  1425. if (targ == "Experimental") {
  1426. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1427. this->SetTest("Start");
  1428. this->SetTest("Configure");
  1429. this->SetTest("Build");
  1430. this->SetTest("Test");
  1431. this->SetTest("Coverage");
  1432. this->SetTest("Submit");
  1433. } else if (targ == "ExperimentalStart") {
  1434. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1435. this->SetTest("Start");
  1436. } else if (targ == "ExperimentalUpdate") {
  1437. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1438. this->SetTest("Update");
  1439. } else if (targ == "ExperimentalConfigure") {
  1440. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1441. this->SetTest("Configure");
  1442. } else if (targ == "ExperimentalBuild") {
  1443. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1444. this->SetTest("Build");
  1445. } else if (targ == "ExperimentalTest") {
  1446. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1447. this->SetTest("Test");
  1448. } else if (targ == "ExperimentalMemCheck" || targ == "ExperimentalPurify") {
  1449. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1450. this->SetTest("MemCheck");
  1451. } else if (targ == "ExperimentalCoverage") {
  1452. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1453. this->SetTest("Coverage");
  1454. } else if (targ == "ExperimentalSubmit") {
  1455. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1456. this->SetTest("Submit");
  1457. } else if (targ == "Continuous") {
  1458. this->SetTestModel(cmCTest::CONTINUOUS);
  1459. this->SetTest("Start");
  1460. this->SetTest("Update");
  1461. this->SetTest("Configure");
  1462. this->SetTest("Build");
  1463. this->SetTest("Test");
  1464. this->SetTest("Coverage");
  1465. this->SetTest("Submit");
  1466. } else if (targ == "ContinuousStart") {
  1467. this->SetTestModel(cmCTest::CONTINUOUS);
  1468. this->SetTest("Start");
  1469. } else if (targ == "ContinuousUpdate") {
  1470. this->SetTestModel(cmCTest::CONTINUOUS);
  1471. this->SetTest("Update");
  1472. } else if (targ == "ContinuousConfigure") {
  1473. this->SetTestModel(cmCTest::CONTINUOUS);
  1474. this->SetTest("Configure");
  1475. } else if (targ == "ContinuousBuild") {
  1476. this->SetTestModel(cmCTest::CONTINUOUS);
  1477. this->SetTest("Build");
  1478. } else if (targ == "ContinuousTest") {
  1479. this->SetTestModel(cmCTest::CONTINUOUS);
  1480. this->SetTest("Test");
  1481. } else if (targ == "ContinuousMemCheck" || targ == "ContinuousPurify") {
  1482. this->SetTestModel(cmCTest::CONTINUOUS);
  1483. this->SetTest("MemCheck");
  1484. } else if (targ == "ContinuousCoverage") {
  1485. this->SetTestModel(cmCTest::CONTINUOUS);
  1486. this->SetTest("Coverage");
  1487. } else if (targ == "ContinuousSubmit") {
  1488. this->SetTestModel(cmCTest::CONTINUOUS);
  1489. this->SetTest("Submit");
  1490. } else if (targ == "Nightly") {
  1491. this->SetTestModel(cmCTest::NIGHTLY);
  1492. this->SetTest("Start");
  1493. this->SetTest("Update");
  1494. this->SetTest("Configure");
  1495. this->SetTest("Build");
  1496. this->SetTest("Test");
  1497. this->SetTest("Coverage");
  1498. this->SetTest("Submit");
  1499. } else if (targ == "NightlyStart") {
  1500. this->SetTestModel(cmCTest::NIGHTLY);
  1501. this->SetTest("Start");
  1502. } else if (targ == "NightlyUpdate") {
  1503. this->SetTestModel(cmCTest::NIGHTLY);
  1504. this->SetTest("Update");
  1505. } else if (targ == "NightlyConfigure") {
  1506. this->SetTestModel(cmCTest::NIGHTLY);
  1507. this->SetTest("Configure");
  1508. } else if (targ == "NightlyBuild") {
  1509. this->SetTestModel(cmCTest::NIGHTLY);
  1510. this->SetTest("Build");
  1511. } else if (targ == "NightlyTest") {
  1512. this->SetTestModel(cmCTest::NIGHTLY);
  1513. this->SetTest("Test");
  1514. } else if (targ == "NightlyMemCheck" || targ == "NightlyPurify") {
  1515. this->SetTestModel(cmCTest::NIGHTLY);
  1516. this->SetTest("MemCheck");
  1517. } else if (targ == "NightlyCoverage") {
  1518. this->SetTestModel(cmCTest::NIGHTLY);
  1519. this->SetTest("Coverage");
  1520. } else if (targ == "NightlySubmit") {
  1521. this->SetTestModel(cmCTest::NIGHTLY);
  1522. this->SetTest("Submit");
  1523. } else if (targ == "MemoryCheck") {
  1524. this->SetTestModel(cmCTest::EXPERIMENTAL);
  1525. this->SetTest("Start");
  1526. this->SetTest("Configure");
  1527. this->SetTest("Build");
  1528. this->SetTest("MemCheck");
  1529. this->SetTest("Coverage");
  1530. this->SetTest("Submit");
  1531. } else if (targ == "NightlyMemoryCheck") {
  1532. this->SetTestModel(cmCTest::NIGHTLY);
  1533. this->SetTest("Start");
  1534. this->SetTest("Update");
  1535. this->SetTest("Configure");
  1536. this->SetTest("Build");
  1537. this->SetTest("MemCheck");
  1538. this->SetTest("Coverage");
  1539. this->SetTest("Submit");
  1540. } else {
  1541. return false;
  1542. }
  1543. return true;
  1544. }
  1545. void cmCTest::ErrorMessageUnknownDashDValue(std::string& val)
  1546. {
  1547. cmCTestLog(this, ERROR_MESSAGE,
  1548. "CTest -D called with incorrect option: " << val << std::endl);
  1549. cmCTestLog(
  1550. this, ERROR_MESSAGE, "Available options are:"
  1551. << std::endl
  1552. << " ctest -D Continuous" << std::endl
  1553. << " ctest -D Continuous(Start|Update|Configure|Build)" << std::endl
  1554. << " ctest -D Continuous(Test|Coverage|MemCheck|Submit)" << std::endl
  1555. << " ctest -D Experimental" << std::endl
  1556. << " ctest -D Experimental(Start|Update|Configure|Build)" << std::endl
  1557. << " ctest -D Experimental(Test|Coverage|MemCheck|Submit)" << std::endl
  1558. << " ctest -D Nightly" << std::endl
  1559. << " ctest -D Nightly(Start|Update|Configure|Build)" << std::endl
  1560. << " ctest -D Nightly(Test|Coverage|MemCheck|Submit)" << std::endl
  1561. << " ctest -D NightlyMemoryCheck" << std::endl);
  1562. }
  1563. bool cmCTest::CheckArgument(const std::string& arg, const char* varg1,
  1564. const char* varg2)
  1565. {
  1566. return (varg1 && arg == varg1) || (varg2 && arg == varg2);
  1567. }
  1568. // Processes one command line argument (and its arguments if any)
  1569. // for many simple options and then returns
  1570. bool cmCTest::HandleCommandLineArguments(size_t& i,
  1571. std::vector<std::string>& args,
  1572. std::string& errormsg)
  1573. {
  1574. std::string arg = args[i];
  1575. if (this->CheckArgument(arg, "-F")) {
  1576. this->Failover = true;
  1577. }
  1578. if (this->CheckArgument(arg, "-j", "--parallel") && i < args.size() - 1) {
  1579. i++;
  1580. int plevel = atoi(args[i].c_str());
  1581. this->SetParallelLevel(plevel);
  1582. this->ParallelLevelSetInCli = true;
  1583. } else if (arg.find("-j") == 0) {
  1584. int plevel = atoi(arg.substr(2).c_str());
  1585. this->SetParallelLevel(plevel);
  1586. this->ParallelLevelSetInCli = true;
  1587. }
  1588. if (this->CheckArgument(arg, "--repeat-until-fail")) {
  1589. if (i >= args.size() - 1) {
  1590. errormsg = "'--repeat-until-fail' requires an argument";
  1591. return false;
  1592. }
  1593. i++;
  1594. long repeat = 1;
  1595. if (!cmSystemTools::StringToLong(args[i].c_str(), &repeat)) {
  1596. errormsg =
  1597. "'--repeat-until-fail' given non-integer value '" + args[i] + "'";
  1598. return false;
  1599. }
  1600. this->RepeatTests = static_cast<int>(repeat);
  1601. if (repeat > 1) {
  1602. this->RepeatUntilFail = true;
  1603. }
  1604. }
  1605. if (this->CheckArgument(arg, "--test-load") && i < args.size() - 1) {
  1606. i++;
  1607. unsigned long load;
  1608. if (cmSystemTools::StringToULong(args[i].c_str(), &load)) {
  1609. this->SetTestLoad(load);
  1610. } else {
  1611. cmCTestLog(this, WARNING,
  1612. "Invalid value for 'Test Load' : " << args[i] << std::endl);
  1613. }
  1614. }
  1615. if (this->CheckArgument(arg, "--no-compress-output")) {
  1616. this->CompressTestOutput = false;
  1617. }
  1618. if (this->CheckArgument(arg, "--print-labels")) {
  1619. this->PrintLabels = true;
  1620. }
  1621. if (this->CheckArgument(arg, "--http1.0")) {
  1622. this->UseHTTP10 = true;
  1623. }
  1624. if (this->CheckArgument(arg, "--timeout") && i < args.size() - 1) {
  1625. i++;
  1626. auto timeout = std::chrono::duration<double>(atof(args[i].c_str()));
  1627. this->GlobalTimeout = timeout;
  1628. }
  1629. if (this->CheckArgument(arg, "--stop-time") && i < args.size() - 1) {
  1630. i++;
  1631. this->SetStopTime(args[i]);
  1632. }
  1633. if (this->CheckArgument(arg, "-C", "--build-config") &&
  1634. i < args.size() - 1) {
  1635. i++;
  1636. this->SetConfigType(args[i].c_str());
  1637. }
  1638. if (this->CheckArgument(arg, "--debug")) {
  1639. this->Debug = true;
  1640. this->ShowLineNumbers = true;
  1641. }
  1642. if (this->CheckArgument(arg, "--track") && i < args.size() - 1) {
  1643. i++;
  1644. this->SpecificTrack = args[i];
  1645. }
  1646. if (this->CheckArgument(arg, "--show-line-numbers")) {
  1647. this->ShowLineNumbers = true;
  1648. }
  1649. if (this->CheckArgument(arg, "--no-label-summary")) {
  1650. this->LabelSummary = false;
  1651. }
  1652. if (this->CheckArgument(arg, "--no-subproject-summary")) {
  1653. this->SubprojectSummary = false;
  1654. }
  1655. if (this->CheckArgument(arg, "-Q", "--quiet")) {
  1656. this->Quiet = true;
  1657. }
  1658. if (this->CheckArgument(arg, "-V", "--verbose")) {
  1659. this->Verbose = true;
  1660. }
  1661. if (this->CheckArgument(arg, "-B")) {
  1662. this->BatchJobs = true;
  1663. }
  1664. if (this->CheckArgument(arg, "-VV", "--extra-verbose")) {
  1665. this->ExtraVerbose = true;
  1666. this->Verbose = true;
  1667. }
  1668. if (this->CheckArgument(arg, "--output-on-failure")) {
  1669. this->OutputTestOutputOnTestFailure = true;
  1670. }
  1671. if (this->CheckArgument(arg, "--test-output-size-passed") &&
  1672. i < args.size() - 1) {
  1673. i++;
  1674. long outputSize;
  1675. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1676. if (cmCTestTestHandler* pCTestTestHandler =
  1677. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1678. pCTestTestHandler->SetTestOutputSizePassed(int(outputSize));
  1679. }
  1680. } else {
  1681. cmCTestLog(this, WARNING,
  1682. "Invalid value for '--test-output-size-passed': " << args[i]
  1683. << "\n");
  1684. }
  1685. }
  1686. if (this->CheckArgument(arg, "--test-output-size-failed") &&
  1687. i < args.size() - 1) {
  1688. i++;
  1689. long outputSize;
  1690. if (cmSystemTools::StringToLong(args[i].c_str(), &outputSize)) {
  1691. if (cmCTestTestHandler* pCTestTestHandler =
  1692. static_cast<cmCTestTestHandler*>(this->TestingHandlers["test"])) {
  1693. pCTestTestHandler->SetTestOutputSizeFailed(int(outputSize));
  1694. }
  1695. } else {
  1696. cmCTestLog(this, WARNING,
  1697. "Invalid value for '--test-output-size-failed': " << args[i]
  1698. << "\n");
  1699. }
  1700. }
  1701. if (this->CheckArgument(arg, "-N", "--show-only")) {
  1702. this->ShowOnly = true;
  1703. }
  1704. if (this->CheckArgument(arg, "-O", "--output-log") && i < args.size() - 1) {
  1705. i++;
  1706. this->SetOutputLogFileName(args[i].c_str());
  1707. }
  1708. if (this->CheckArgument(arg, "--tomorrow-tag")) {
  1709. this->TomorrowTag = true;
  1710. }
  1711. if (this->CheckArgument(arg, "--force-new-ctest-process")) {
  1712. this->ForceNewCTestProcess = true;
  1713. }
  1714. if (this->CheckArgument(arg, "-W", "--max-width") && i < args.size() - 1) {
  1715. i++;
  1716. this->MaxTestNameWidth = atoi(args[i].c_str());
  1717. }
  1718. if (this->CheckArgument(arg, "--interactive-debug-mode") &&
  1719. i < args.size() - 1) {
  1720. i++;
  1721. this->InteractiveDebugMode = cmSystemTools::IsOn(args[i].c_str());
  1722. }
  1723. if (this->CheckArgument(arg, "--submit-index") && i < args.size() - 1) {
  1724. i++;
  1725. this->SubmitIndex = atoi(args[i].c_str());
  1726. if (this->SubmitIndex < 0) {
  1727. this->SubmitIndex = 0;
  1728. }
  1729. }
  1730. if (this->CheckArgument(arg, "--overwrite") && i < args.size() - 1) {
  1731. i++;
  1732. this->AddCTestConfigurationOverwrite(args[i]);
  1733. }
  1734. if (this->CheckArgument(arg, "-A", "--add-notes") && i < args.size() - 1) {
  1735. this->ProduceXML = true;
  1736. this->SetTest("Notes");
  1737. i++;
  1738. this->SetNotesFiles(args[i].c_str());
  1739. }
  1740. // options that control what tests are run
  1741. if (this->CheckArgument(arg, "-I", "--tests-information") &&
  1742. i < args.size() - 1) {
  1743. i++;
  1744. this->GetHandler("test")->SetPersistentOption("TestsToRunInformation",
  1745. args[i].c_str());
  1746. this->GetHandler("memcheck")
  1747. ->SetPersistentOption("TestsToRunInformation", args[i].c_str());
  1748. }
  1749. if (this->CheckArgument(arg, "-U", "--union")) {
  1750. this->GetHandler("test")->SetPersistentOption("UseUnion", "true");
  1751. this->GetHandler("memcheck")->SetPersistentOption("UseUnion", "true");
  1752. }
  1753. if (this->CheckArgument(arg, "-R", "--tests-regex") && i < args.size() - 1) {
  1754. i++;
  1755. this->GetHandler("test")->SetPersistentOption("IncludeRegularExpression",
  1756. args[i].c_str());
  1757. this->GetHandler("memcheck")
  1758. ->SetPersistentOption("IncludeRegularExpression", args[i].c_str());
  1759. }
  1760. if (this->CheckArgument(arg, "-L", "--label-regex") && i < args.size() - 1) {
  1761. i++;
  1762. this->GetHandler("test")->SetPersistentOption("LabelRegularExpression",
  1763. args[i].c_str());
  1764. this->GetHandler("memcheck")
  1765. ->SetPersistentOption("LabelRegularExpression", args[i].c_str());
  1766. }
  1767. if (this->CheckArgument(arg, "-LE", "--label-exclude") &&
  1768. i < args.size() - 1) {
  1769. i++;
  1770. this->GetHandler("test")->SetPersistentOption(
  1771. "ExcludeLabelRegularExpression", args[i].c_str());
  1772. this->GetHandler("memcheck")
  1773. ->SetPersistentOption("ExcludeLabelRegularExpression", args[i].c_str());
  1774. }
  1775. if (this->CheckArgument(arg, "-E", "--exclude-regex") &&
  1776. i < args.size() - 1) {
  1777. i++;
  1778. this->GetHandler("test")->SetPersistentOption("ExcludeRegularExpression",
  1779. args[i].c_str());
  1780. this->GetHandler("memcheck")
  1781. ->SetPersistentOption("ExcludeRegularExpression", args[i].c_str());
  1782. }
  1783. if (this->CheckArgument(arg, "-FA", "--fixture-exclude-any") &&
  1784. i < args.size() - 1) {
  1785. i++;
  1786. this->GetHandler("test")->SetPersistentOption(
  1787. "ExcludeFixtureRegularExpression", args[i].c_str());
  1788. this->GetHandler("memcheck")
  1789. ->SetPersistentOption("ExcludeFixtureRegularExpression",
  1790. args[i].c_str());
  1791. }
  1792. if (this->CheckArgument(arg, "-FS", "--fixture-exclude-setup") &&
  1793. i < args.size() - 1) {
  1794. i++;
  1795. this->GetHandler("test")->SetPersistentOption(
  1796. "ExcludeFixtureSetupRegularExpression", args[i].c_str());
  1797. this->GetHandler("memcheck")
  1798. ->SetPersistentOption("ExcludeFixtureSetupRegularExpression",
  1799. args[i].c_str());
  1800. }
  1801. if (this->CheckArgument(arg, "-FC", "--fixture-exclude-cleanup") &&
  1802. i < args.size() - 1) {
  1803. i++;
  1804. this->GetHandler("test")->SetPersistentOption(
  1805. "ExcludeFixtureCleanupRegularExpression", args[i].c_str());
  1806. this->GetHandler("memcheck")
  1807. ->SetPersistentOption("ExcludeFixtureCleanupRegularExpression",
  1808. args[i].c_str());
  1809. }
  1810. if (this->CheckArgument(arg, "--rerun-failed")) {
  1811. this->GetHandler("test")->SetPersistentOption("RerunFailed", "true");
  1812. this->GetHandler("memcheck")->SetPersistentOption("RerunFailed", "true");
  1813. }
  1814. return true;
  1815. }
  1816. // handle the -S -SR and -SP arguments
  1817. void cmCTest::HandleScriptArguments(size_t& i, std::vector<std::string>& args,
  1818. bool& SRArgumentSpecified)
  1819. {
  1820. std::string arg = args[i];
  1821. if (this->CheckArgument(arg, "-SP", "--script-new-process") &&
  1822. i < args.size() - 1) {
  1823. this->RunConfigurationScript = true;
  1824. i++;
  1825. cmCTestScriptHandler* ch =
  1826. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1827. // -SR is an internal argument, -SP should be ignored when it is passed
  1828. if (!SRArgumentSpecified) {
  1829. ch->AddConfigurationScript(args[i].c_str(), false);
  1830. }
  1831. }
  1832. if (this->CheckArgument(arg, "-SR", "--script-run") && i < args.size() - 1) {
  1833. SRArgumentSpecified = true;
  1834. this->RunConfigurationScript = true;
  1835. i++;
  1836. cmCTestScriptHandler* ch =
  1837. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1838. ch->AddConfigurationScript(args[i].c_str(), true);
  1839. }
  1840. if (this->CheckArgument(arg, "-S", "--script") && i < args.size() - 1) {
  1841. this->RunConfigurationScript = true;
  1842. i++;
  1843. cmCTestScriptHandler* ch =
  1844. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  1845. // -SR is an internal argument, -S should be ignored when it is passed
  1846. if (!SRArgumentSpecified) {
  1847. ch->AddConfigurationScript(args[i].c_str(), true);
  1848. }
  1849. }
  1850. }
  1851. bool cmCTest::AddVariableDefinition(const std::string& arg)
  1852. {
  1853. std::string name;
  1854. std::string value;
  1855. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  1856. if (cmake::ParseCacheEntry(arg, name, value, type)) {
  1857. this->Definitions[name] = value;
  1858. return true;
  1859. }
  1860. return false;
  1861. }
  1862. // the main entry point of ctest, called from main
  1863. int cmCTest::Run(std::vector<std::string>& args, std::string* output)
  1864. {
  1865. const char* ctestExec = "ctest";
  1866. bool cmakeAndTest = false;
  1867. bool executeTests = true;
  1868. bool SRArgumentSpecified = false;
  1869. // copy the command line
  1870. this->InitialCommandLineArguments.insert(
  1871. this->InitialCommandLineArguments.end(), args.begin(), args.end());
  1872. // process the command line arguments
  1873. for (size_t i = 1; i < args.size(); ++i) {
  1874. // handle the simple commandline arguments
  1875. std::string errormsg;
  1876. if (!this->HandleCommandLineArguments(i, args, errormsg)) {
  1877. cmSystemTools::Error(errormsg.c_str());
  1878. return 1;
  1879. }
  1880. // handle the script arguments -S -SR -SP
  1881. this->HandleScriptArguments(i, args, SRArgumentSpecified);
  1882. // --dashboard: handle a request for a dashboard
  1883. std::string arg = args[i];
  1884. if (this->CheckArgument(arg, "-D", "--dashboard") && i < args.size() - 1) {
  1885. this->ProduceXML = true;
  1886. i++;
  1887. std::string targ = args[i];
  1888. // AddTestsForDashboard parses the dashboard type and converts it
  1889. // into the separate stages
  1890. if (!this->AddTestsForDashboardType(targ)) {
  1891. if (!this->AddVariableDefinition(targ)) {
  1892. this->ErrorMessageUnknownDashDValue(targ);
  1893. executeTests = false;
  1894. }
  1895. }
  1896. }
  1897. // If it's not exactly -D, but it starts with -D, then try to parse out
  1898. // a variable definition from it, same as CMake does. Unsuccessful
  1899. // attempts are simply ignored since previous ctest versions ignore
  1900. // this too. (As well as many other unknown command line args.)
  1901. //
  1902. if (arg != "-D" && cmSystemTools::StringStartsWith(arg.c_str(), "-D")) {
  1903. std::string input = arg.substr(2);
  1904. this->AddVariableDefinition(input);
  1905. }
  1906. // --test-action: calls SetTest(<stage>, /*report=*/ false) to enable
  1907. // the corresponding stage
  1908. if (!this->HandleTestActionArgument(ctestExec, i, args)) {
  1909. executeTests = false;
  1910. }
  1911. // --test-model: what type of test model
  1912. if (!this->HandleTestModelArgument(ctestExec, i, args)) {
  1913. executeTests = false;
  1914. }
  1915. // --extra-submit
  1916. if (this->CheckArgument(arg, "--extra-submit") && i < args.size() - 1) {
  1917. this->ProduceXML = true;
  1918. this->SetTest("Submit");
  1919. i++;
  1920. if (!this->SubmitExtraFiles(args[i].c_str())) {
  1921. return 0;
  1922. }
  1923. }
  1924. // --build-and-test options
  1925. if (this->CheckArgument(arg, "--build-and-test") && i < args.size() - 1) {
  1926. cmakeAndTest = true;
  1927. }
  1928. // --schedule-random
  1929. if (this->CheckArgument(arg, "--schedule-random")) {
  1930. this->ScheduleType = "Random";
  1931. }
  1932. // pass the argument to all the handlers as well, but i may no longer be
  1933. // set to what it was originally so I'm not sure this is working as
  1934. // intended
  1935. for (auto& handler : this->TestingHandlers) {
  1936. if (!handler.second->ProcessCommandLineArguments(arg, i, args)) {
  1937. cmCTestLog(this, ERROR_MESSAGE,
  1938. "Problem parsing command line arguments within a handler");
  1939. return 0;
  1940. }
  1941. }
  1942. } // the close of the for argument loop
  1943. // handle CTEST_PARALLEL_LEVEL environment variable
  1944. if (!this->ParallelLevelSetInCli) {
  1945. std::string parallel;
  1946. if (cmSystemTools::GetEnv("CTEST_PARALLEL_LEVEL", parallel)) {
  1947. int plevel = atoi(parallel.c_str());
  1948. this->SetParallelLevel(plevel);
  1949. }
  1950. }
  1951. // now what should cmake do? if --build-and-test was specified then
  1952. // we run the build and test handler and return
  1953. if (cmakeAndTest) {
  1954. return this->RunCMakeAndTest(output);
  1955. }
  1956. if (executeTests) {
  1957. return this->ExecuteTests();
  1958. }
  1959. return 1;
  1960. }
  1961. bool cmCTest::HandleTestActionArgument(const char* ctestExec, size_t& i,
  1962. const std::vector<std::string>& args)
  1963. {
  1964. bool success = true;
  1965. std::string arg = args[i];
  1966. if (this->CheckArgument(arg, "-T", "--test-action") &&
  1967. (i < args.size() - 1)) {
  1968. this->ProduceXML = true;
  1969. i++;
  1970. if (!this->SetTest(args[i].c_str(), false)) {
  1971. success = false;
  1972. cmCTestLog(this, ERROR_MESSAGE, "CTest -T called with incorrect option: "
  1973. << args[i] << std::endl);
  1974. cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
  1975. << std::endl
  1976. << " " << ctestExec << " -T all" << std::endl
  1977. << " " << ctestExec << " -T start" << std::endl
  1978. << " " << ctestExec << " -T update" << std::endl
  1979. << " " << ctestExec << " -T configure" << std::endl
  1980. << " " << ctestExec << " -T build" << std::endl
  1981. << " " << ctestExec << " -T test" << std::endl
  1982. << " " << ctestExec << " -T coverage" << std::endl
  1983. << " " << ctestExec << " -T memcheck" << std::endl
  1984. << " " << ctestExec << " -T notes" << std::endl
  1985. << " " << ctestExec << " -T submit" << std::endl);
  1986. }
  1987. }
  1988. return success;
  1989. }
  1990. bool cmCTest::HandleTestModelArgument(const char* ctestExec, size_t& i,
  1991. const std::vector<std::string>& args)
  1992. {
  1993. bool success = true;
  1994. std::string arg = args[i];
  1995. if (this->CheckArgument(arg, "-M", "--test-model") &&
  1996. (i < args.size() - 1)) {
  1997. i++;
  1998. std::string const& str = args[i];
  1999. if (cmSystemTools::LowerCase(str) == "nightly") {
  2000. this->SetTestModel(cmCTest::NIGHTLY);
  2001. } else if (cmSystemTools::LowerCase(str) == "continuous") {
  2002. this->SetTestModel(cmCTest::CONTINUOUS);
  2003. } else if (cmSystemTools::LowerCase(str) == "experimental") {
  2004. this->SetTestModel(cmCTest::EXPERIMENTAL);
  2005. } else {
  2006. success = false;
  2007. cmCTestLog(this, ERROR_MESSAGE, "CTest -M called with incorrect option: "
  2008. << str << std::endl);
  2009. cmCTestLog(this, ERROR_MESSAGE, "Available options are:"
  2010. << std::endl
  2011. << " " << ctestExec << " -M Continuous" << std::endl
  2012. << " " << ctestExec << " -M Experimental" << std::endl
  2013. << " " << ctestExec << " -M Nightly" << std::endl);
  2014. }
  2015. }
  2016. return success;
  2017. }
  2018. int cmCTest::ExecuteTests()
  2019. {
  2020. int res;
  2021. // call process directory
  2022. if (this->RunConfigurationScript) {
  2023. if (this->ExtraVerbose) {
  2024. cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
  2025. }
  2026. for (auto& handler : this->TestingHandlers) {
  2027. handler.second->SetVerbose(this->ExtraVerbose);
  2028. handler.second->SetSubmitIndex(this->SubmitIndex);
  2029. }
  2030. this->GetHandler("script")->SetVerbose(this->Verbose);
  2031. res = this->GetHandler("script")->ProcessHandler();
  2032. if (res != 0) {
  2033. cmCTestLog(this, DEBUG,
  2034. "running script failing returning: " << res << std::endl);
  2035. }
  2036. } else {
  2037. // What is this? -V seems to be the same as -VV,
  2038. // and Verbose is always on in this case
  2039. this->ExtraVerbose = this->Verbose;
  2040. this->Verbose = true;
  2041. for (auto& handler : this->TestingHandlers) {
  2042. handler.second->SetVerbose(this->Verbose);
  2043. handler.second->SetSubmitIndex(this->SubmitIndex);
  2044. }
  2045. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2046. if (!this->Initialize(cwd.c_str(), nullptr)) {
  2047. res = 12;
  2048. cmCTestLog(this, ERROR_MESSAGE, "Problem initializing the dashboard."
  2049. << std::endl);
  2050. } else {
  2051. res = this->ProcessSteps();
  2052. }
  2053. this->Finalize();
  2054. }
  2055. if (res != 0) {
  2056. cmCTestLog(this, DEBUG,
  2057. "Running a test(s) failed returning : " << res << std::endl);
  2058. }
  2059. return res;
  2060. }
  2061. int cmCTest::RunCMakeAndTest(std::string* output)
  2062. {
  2063. this->Verbose = true;
  2064. cmCTestBuildAndTestHandler* handler =
  2065. static_cast<cmCTestBuildAndTestHandler*>(this->GetHandler("buildtest"));
  2066. int retv = handler->ProcessHandler();
  2067. *output = handler->GetOutput();
  2068. #ifdef CMAKE_BUILD_WITH_CMAKE
  2069. cmDynamicLoader::FlushCache();
  2070. #endif
  2071. if (retv != 0) {
  2072. cmCTestLog(this, DEBUG, "build and test failing returning: " << retv
  2073. << std::endl);
  2074. }
  2075. return retv;
  2076. }
  2077. void cmCTest::SetNotesFiles(const char* notes)
  2078. {
  2079. if (!notes) {
  2080. return;
  2081. }
  2082. this->NotesFiles = notes;
  2083. }
  2084. void cmCTest::SetStopTime(std::string const& time)
  2085. {
  2086. this->StopTime = time;
  2087. this->DetermineNextDayStop();
  2088. }
  2089. int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf)
  2090. {
  2091. bool found = false;
  2092. VectorOfStrings dirs;
  2093. VectorOfStrings ndirs;
  2094. cmCTestLog(this, DEBUG, "* Read custom CTest configuration directory: "
  2095. << dir << std::endl);
  2096. std::string fname = dir;
  2097. fname += "/CTestCustom.cmake";
  2098. cmCTestLog(this, DEBUG, "* Check for file: " << fname << std::endl);
  2099. if (cmSystemTools::FileExists(fname.c_str())) {
  2100. cmCTestLog(this, DEBUG, "* Read custom CTest configuration file: "
  2101. << fname << std::endl);
  2102. bool erroroc = cmSystemTools::GetErrorOccuredFlag();
  2103. cmSystemTools::ResetErrorOccuredFlag();
  2104. if (!mf->ReadListFile(fname.c_str()) ||
  2105. cmSystemTools::GetErrorOccuredFlag()) {
  2106. cmCTestLog(this, ERROR_MESSAGE, "Problem reading custom configuration: "
  2107. << fname << std::endl);
  2108. }
  2109. found = true;
  2110. if (erroroc) {
  2111. cmSystemTools::SetErrorOccured();
  2112. }
  2113. }
  2114. std::string rexpr = dir;
  2115. rexpr += "/CTestCustom.ctest";
  2116. cmCTestLog(this, DEBUG, "* Check for file: " << rexpr << std::endl);
  2117. if (!found && cmSystemTools::FileExists(rexpr.c_str())) {
  2118. cmsys::Glob gl;
  2119. gl.RecurseOn();
  2120. gl.FindFiles(rexpr);
  2121. std::vector<std::string>& files = gl.GetFiles();
  2122. std::vector<std::string>::iterator fileIt;
  2123. for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
  2124. cmCTestLog(this, DEBUG, "* Read custom CTest configuration file: "
  2125. << *fileIt << std::endl);
  2126. if (!mf->ReadListFile(fileIt->c_str()) ||
  2127. cmSystemTools::GetErrorOccuredFlag()) {
  2128. cmCTestLog(this, ERROR_MESSAGE,
  2129. "Problem reading custom configuration: " << *fileIt
  2130. << std::endl);
  2131. }
  2132. }
  2133. found = true;
  2134. }
  2135. if (found) {
  2136. for (auto& handler : this->TestingHandlers) {
  2137. cmCTestLog(
  2138. this, DEBUG, "* Read custom CTest configuration vectors for handler: "
  2139. << handler.first << " (" << handler.second << ")" << std::endl);
  2140. handler.second->PopulateCustomVectors(mf);
  2141. }
  2142. }
  2143. return 1;
  2144. }
  2145. void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def,
  2146. std::vector<std::string>& vec)
  2147. {
  2148. const char* dval = mf->GetDefinition(def);
  2149. if (!dval) {
  2150. return;
  2151. }
  2152. cmCTestLog(this, DEBUG, "PopulateCustomVector: " << def << std::endl);
  2153. vec.clear();
  2154. cmSystemTools::ExpandListArgument(dval, vec);
  2155. for (std::string const& it : vec) {
  2156. cmCTestLog(this, DEBUG, " -- " << it << std::endl);
  2157. }
  2158. }
  2159. void cmCTest::PopulateCustomInteger(cmMakefile* mf, const std::string& def,
  2160. int& val)
  2161. {
  2162. const char* dval = mf->GetDefinition(def);
  2163. if (!dval) {
  2164. return;
  2165. }
  2166. val = atoi(dval);
  2167. }
  2168. std::string cmCTest::GetShortPathToFile(const char* cfname)
  2169. {
  2170. const std::string& sourceDir = cmSystemTools::CollapseFullPath(
  2171. this->GetCTestConfiguration("SourceDirectory"));
  2172. const std::string& buildDir = cmSystemTools::CollapseFullPath(
  2173. this->GetCTestConfiguration("BuildDirectory"));
  2174. std::string fname = cmSystemTools::CollapseFullPath(cfname);
  2175. // Find relative paths to both directories
  2176. std::string srcRelpath =
  2177. cmSystemTools::RelativePath(sourceDir.c_str(), fname.c_str());
  2178. std::string bldRelpath =
  2179. cmSystemTools::RelativePath(buildDir.c_str(), fname.c_str());
  2180. // If any contains "." it is not parent directory
  2181. bool inSrc = srcRelpath.find("..") == std::string::npos;
  2182. bool inBld = bldRelpath.find("..") == std::string::npos;
  2183. // TODO: Handle files with .. in their name
  2184. std::string* res = nullptr;
  2185. if (inSrc && inBld) {
  2186. // If both have relative path with no dots, pick the shorter one
  2187. if (srcRelpath.size() < bldRelpath.size()) {
  2188. res = &srcRelpath;
  2189. } else {
  2190. res = &bldRelpath;
  2191. }
  2192. } else if (inSrc) {
  2193. res = &srcRelpath;
  2194. } else if (inBld) {
  2195. res = &bldRelpath;
  2196. }
  2197. std::string path;
  2198. if (!res) {
  2199. path = fname;
  2200. } else {
  2201. cmSystemTools::ConvertToUnixSlashes(*res);
  2202. path = "./" + *res;
  2203. if (path[path.size() - 1] == '/') {
  2204. path = path.substr(0, path.size() - 1);
  2205. }
  2206. }
  2207. cmsys::SystemTools::ReplaceString(path, ":", "_");
  2208. cmsys::SystemTools::ReplaceString(path, " ", "_");
  2209. return path;
  2210. }
  2211. std::string cmCTest::GetCTestConfiguration(const std::string& name)
  2212. {
  2213. if (this->CTestConfigurationOverwrites.find(name) !=
  2214. this->CTestConfigurationOverwrites.end()) {
  2215. return this->CTestConfigurationOverwrites[name];
  2216. }
  2217. return this->CTestConfiguration[name];
  2218. }
  2219. void cmCTest::EmptyCTestConfiguration()
  2220. {
  2221. this->CTestConfiguration.clear();
  2222. }
  2223. void cmCTest::DetermineNextDayStop()
  2224. {
  2225. struct tm* lctime;
  2226. time_t current_time = time(nullptr);
  2227. lctime = gmtime(&current_time);
  2228. int gm_hour = lctime->tm_hour;
  2229. time_t gm_time = mktime(lctime);
  2230. lctime = localtime(&current_time);
  2231. int local_hour = lctime->tm_hour;
  2232. int tzone_offset = local_hour - gm_hour;
  2233. if (gm_time > current_time && gm_hour < local_hour) {
  2234. // this means gm_time is on the next day
  2235. tzone_offset -= 24;
  2236. } else if (gm_time < current_time && gm_hour > local_hour) {
  2237. // this means gm_time is on the previous day
  2238. tzone_offset += 24;
  2239. }
  2240. tzone_offset *= 100;
  2241. char buf[1024];
  2242. sprintf(buf, "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
  2243. lctime->tm_mon + 1, lctime->tm_mday, this->StopTime.c_str(),
  2244. tzone_offset);
  2245. time_t stop_time = curl_getdate(buf, &current_time);
  2246. if (stop_time < current_time) {
  2247. this->NextDayStopTime = true;
  2248. }
  2249. }
  2250. void cmCTest::SetCTestConfiguration(const char* name, const char* value,
  2251. bool suppress)
  2252. {
  2253. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT, "SetCTestConfiguration:"
  2254. << name << ":" << (value ? value : "(null)") << "\n",
  2255. suppress);
  2256. if (!name) {
  2257. return;
  2258. }
  2259. if (!value) {
  2260. this->CTestConfiguration.erase(name);
  2261. return;
  2262. }
  2263. this->CTestConfiguration[name] = value;
  2264. }
  2265. std::string cmCTest::GetCurrentTag()
  2266. {
  2267. return this->CurrentTag;
  2268. }
  2269. std::string cmCTest::GetBinaryDir()
  2270. {
  2271. return this->BinaryDir;
  2272. }
  2273. std::string const& cmCTest::GetConfigType()
  2274. {
  2275. return this->ConfigType;
  2276. }
  2277. bool cmCTest::GetShowOnly()
  2278. {
  2279. return this->ShowOnly;
  2280. }
  2281. int cmCTest::GetMaxTestNameWidth() const
  2282. {
  2283. return this->MaxTestNameWidth;
  2284. }
  2285. void cmCTest::SetProduceXML(bool v)
  2286. {
  2287. this->ProduceXML = v;
  2288. }
  2289. bool cmCTest::GetProduceXML()
  2290. {
  2291. return this->ProduceXML;
  2292. }
  2293. const char* cmCTest::GetSpecificTrack()
  2294. {
  2295. if (this->SpecificTrack.empty()) {
  2296. return nullptr;
  2297. }
  2298. return this->SpecificTrack.c_str();
  2299. }
  2300. void cmCTest::SetSpecificTrack(const char* track)
  2301. {
  2302. if (!track) {
  2303. this->SpecificTrack.clear();
  2304. return;
  2305. }
  2306. this->SpecificTrack = track;
  2307. }
  2308. void cmCTest::AddSubmitFile(Part part, const char* name)
  2309. {
  2310. this->Parts[part].SubmitFiles.push_back(name);
  2311. }
  2312. void cmCTest::AddCTestConfigurationOverwrite(const std::string& overStr)
  2313. {
  2314. size_t epos = overStr.find('=');
  2315. if (epos == std::string::npos) {
  2316. cmCTestLog(this, ERROR_MESSAGE,
  2317. "CTest configuration overwrite specified in the wrong format."
  2318. << std::endl
  2319. << "Valid format is: --overwrite key=value" << std::endl
  2320. << "The specified was: --overwrite " << overStr << std::endl);
  2321. return;
  2322. }
  2323. std::string key = overStr.substr(0, epos);
  2324. std::string value = overStr.substr(epos + 1);
  2325. this->CTestConfigurationOverwrites[key] = value;
  2326. }
  2327. void cmCTest::SetConfigType(const char* ct)
  2328. {
  2329. this->ConfigType = ct ? ct : "";
  2330. cmSystemTools::ReplaceString(this->ConfigType, ".\\", "");
  2331. std::string confTypeEnv = "CMAKE_CONFIG_TYPE=" + this->ConfigType;
  2332. cmSystemTools::PutEnv(confTypeEnv);
  2333. }
  2334. bool cmCTest::SetCTestConfigurationFromCMakeVariable(
  2335. cmMakefile* mf, const char* dconfig, const std::string& cmake_var,
  2336. bool suppress)
  2337. {
  2338. const char* ctvar;
  2339. ctvar = mf->GetDefinition(cmake_var);
  2340. if (!ctvar) {
  2341. return false;
  2342. }
  2343. cmCTestOptionalLog(this, HANDLER_VERBOSE_OUTPUT,
  2344. "SetCTestConfigurationFromCMakeVariable:"
  2345. << dconfig << ":" << cmake_var << std::endl,
  2346. suppress);
  2347. this->SetCTestConfiguration(dconfig, ctvar, suppress);
  2348. return true;
  2349. }
  2350. bool cmCTest::RunCommand(std::vector<std::string> const& args,
  2351. std::string* stdOut, std::string* stdErr, int* retVal,
  2352. const char* dir,
  2353. std::chrono::duration<double> timeout,
  2354. Encoding encoding)
  2355. {
  2356. std::vector<const char*> argv;
  2357. argv.reserve(args.size() + 1);
  2358. for (std::string const& a : args) {
  2359. argv.push_back(a.c_str());
  2360. }
  2361. argv.push_back(nullptr);
  2362. stdOut->clear();
  2363. stdErr->clear();
  2364. cmsysProcess* cp = cmsysProcess_New();
  2365. cmsysProcess_SetCommand(cp, &*argv.begin());
  2366. cmsysProcess_SetWorkingDirectory(cp, dir);
  2367. if (cmSystemTools::GetRunCommandHideConsole()) {
  2368. cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
  2369. }
  2370. cmsysProcess_SetTimeout(cp, timeout.count());
  2371. cmsysProcess_Execute(cp);
  2372. std::vector<char> tempOutput;
  2373. std::vector<char> tempError;
  2374. char* data;
  2375. int length;
  2376. cmProcessOutput processOutput(encoding);
  2377. std::string strdata;
  2378. int res;
  2379. bool done = false;
  2380. while (!done) {
  2381. res = cmsysProcess_WaitForData(cp, &data, &length, nullptr);
  2382. switch (res) {
  2383. case cmsysProcess_Pipe_STDOUT:
  2384. tempOutput.insert(tempOutput.end(), data, data + length);
  2385. break;
  2386. case cmsysProcess_Pipe_STDERR:
  2387. tempError.insert(tempError.end(), data, data + length);
  2388. break;
  2389. default:
  2390. done = true;
  2391. }
  2392. if ((res == cmsysProcess_Pipe_STDOUT || res == cmsysProcess_Pipe_STDERR) &&
  2393. this->ExtraVerbose) {
  2394. processOutput.DecodeText(data, length, strdata);
  2395. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2396. }
  2397. }
  2398. if (this->ExtraVerbose) {
  2399. processOutput.DecodeText(std::string(), strdata);
  2400. if (!strdata.empty()) {
  2401. cmSystemTools::Stdout(strdata.c_str(), strdata.size());
  2402. }
  2403. }
  2404. cmsysProcess_WaitForExit(cp, nullptr);
  2405. if (!tempOutput.empty()) {
  2406. processOutput.DecodeText(tempOutput, tempOutput);
  2407. stdOut->append(&*tempOutput.begin(), tempOutput.size());
  2408. }
  2409. if (!tempError.empty()) {
  2410. processOutput.DecodeText(tempError, tempError);
  2411. stdErr->append(&*tempError.begin(), tempError.size());
  2412. }
  2413. bool result = true;
  2414. if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
  2415. if (retVal) {
  2416. *retVal = cmsysProcess_GetExitValue(cp);
  2417. } else {
  2418. if (cmsysProcess_GetExitValue(cp) != 0) {
  2419. result = false;
  2420. }
  2421. }
  2422. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exception) {
  2423. const char* exception_str = cmsysProcess_GetExceptionString(cp);
  2424. cmCTestLog(this, ERROR_MESSAGE, exception_str << std::endl);
  2425. stdErr->append(exception_str, strlen(exception_str));
  2426. result = false;
  2427. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
  2428. const char* error_str = cmsysProcess_GetErrorString(cp);
  2429. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2430. stdErr->append(error_str, strlen(error_str));
  2431. result = false;
  2432. } else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
  2433. const char* error_str = "Process terminated due to timeout\n";
  2434. cmCTestLog(this, ERROR_MESSAGE, error_str << std::endl);
  2435. stdErr->append(error_str, strlen(error_str));
  2436. result = false;
  2437. }
  2438. cmsysProcess_Delete(cp);
  2439. return result;
  2440. }
  2441. void cmCTest::SetOutputLogFileName(const char* name)
  2442. {
  2443. if (this->OutputLogFile) {
  2444. delete this->OutputLogFile;
  2445. this->OutputLogFile = nullptr;
  2446. }
  2447. if (name) {
  2448. this->OutputLogFile = new cmGeneratedFileStream(name);
  2449. }
  2450. }
  2451. static const char* cmCTestStringLogType[] = { "DEBUG",
  2452. "OUTPUT",
  2453. "HANDLER_OUTPUT",
  2454. "HANDLER_PROGRESS_OUTPUT",
  2455. "HANDLER_VERBOSE_OUTPUT",
  2456. "WARNING",
  2457. "ERROR_MESSAGE",
  2458. nullptr };
  2459. #define cmCTestLogOutputFileLine(stream) \
  2460. if (this->ShowLineNumbers) { \
  2461. (stream) << std::endl << file << ":" << line << " "; \
  2462. }
  2463. void cmCTest::InitStreams()
  2464. {
  2465. // By default we write output to the process output streams.
  2466. this->StreamOut = &std::cout;
  2467. this->StreamErr = &std::cerr;
  2468. }
  2469. void cmCTest::Log(int logType, const char* file, int line, const char* msg,
  2470. bool suppress)
  2471. {
  2472. if (!msg || !*msg) {
  2473. return;
  2474. }
  2475. if (suppress && logType != cmCTest::ERROR_MESSAGE) {
  2476. return;
  2477. }
  2478. if (logType == cmCTest::HANDLER_PROGRESS_OUTPUT &&
  2479. (this->Debug || this->ExtraVerbose)) {
  2480. return;
  2481. }
  2482. if (this->OutputLogFile) {
  2483. bool display = true;
  2484. if (logType == cmCTest::DEBUG && !this->Debug) {
  2485. display = false;
  2486. }
  2487. if (logType == cmCTest::HANDLER_VERBOSE_OUTPUT && !this->Debug &&
  2488. !this->ExtraVerbose) {
  2489. display = false;
  2490. }
  2491. if (display) {
  2492. cmCTestLogOutputFileLine(*this->OutputLogFile);
  2493. if (logType != this->OutputLogFileLastTag) {
  2494. *this->OutputLogFile << "[";
  2495. if (logType >= OTHER || logType < 0) {
  2496. *this->OutputLogFile << "OTHER";
  2497. } else {
  2498. *this->OutputLogFile << cmCTestStringLogType[logType];
  2499. }
  2500. *this->OutputLogFile << "] " << std::endl << std::flush;
  2501. }
  2502. *this->OutputLogFile << msg << std::flush;
  2503. if (logType != this->OutputLogFileLastTag) {
  2504. *this->OutputLogFile << std::endl << std::flush;
  2505. this->OutputLogFileLastTag = logType;
  2506. }
  2507. }
  2508. }
  2509. if (!this->Quiet) {
  2510. std::ostream& out = *this->StreamOut;
  2511. std::ostream& err = *this->StreamErr;
  2512. switch (logType) {
  2513. case DEBUG:
  2514. if (this->Debug) {
  2515. cmCTestLogOutputFileLine(out);
  2516. out << msg;
  2517. out.flush();
  2518. }
  2519. break;
  2520. case OUTPUT:
  2521. case HANDLER_OUTPUT:
  2522. if (this->Debug || this->Verbose) {
  2523. cmCTestLogOutputFileLine(out);
  2524. out << msg;
  2525. out.flush();
  2526. }
  2527. break;
  2528. case HANDLER_VERBOSE_OUTPUT:
  2529. if (this->Debug || this->ExtraVerbose) {
  2530. cmCTestLogOutputFileLine(out);
  2531. out << msg;
  2532. out.flush();
  2533. }
  2534. break;
  2535. case WARNING:
  2536. cmCTestLogOutputFileLine(err);
  2537. err << msg;
  2538. err.flush();
  2539. break;
  2540. case ERROR_MESSAGE:
  2541. cmCTestLogOutputFileLine(err);
  2542. err << msg;
  2543. err.flush();
  2544. cmSystemTools::SetErrorOccured();
  2545. break;
  2546. default:
  2547. cmCTestLogOutputFileLine(out);
  2548. out << msg;
  2549. out.flush();
  2550. }
  2551. }
  2552. }
  2553. std::chrono::duration<double> cmCTest::GetRemainingTimeAllowed()
  2554. {
  2555. if (!this->GetHandler("script")) {
  2556. return cmCTest::MaxDuration();
  2557. }
  2558. cmCTestScriptHandler* ch =
  2559. static_cast<cmCTestScriptHandler*>(this->GetHandler("script"));
  2560. return ch->GetRemainingTimeAllowed();
  2561. }
  2562. std::chrono::duration<double> cmCTest::MaxDuration()
  2563. {
  2564. return std::chrono::duration<double>(1.0e7);
  2565. }
  2566. void cmCTest::OutputTestErrors(std::vector<char> const& process_output)
  2567. {
  2568. std::string test_outputs("\n*** Test Failed:\n");
  2569. if (!process_output.empty()) {
  2570. test_outputs.append(&*process_output.begin(), process_output.size());
  2571. }
  2572. cmCTestLog(this, HANDLER_OUTPUT, test_outputs << std::endl << std::flush);
  2573. }
  2574. bool cmCTest::CompressString(std::string& str)
  2575. {
  2576. int ret;
  2577. z_stream strm;
  2578. strm.zalloc = Z_NULL;
  2579. strm.zfree = Z_NULL;
  2580. strm.opaque = Z_NULL;
  2581. ret = deflateInit(&strm, -1); // default compression level
  2582. if (ret != Z_OK) {
  2583. return false;
  2584. }
  2585. unsigned char* in =
  2586. reinterpret_cast<unsigned char*>(const_cast<char*>(str.c_str()));
  2587. // zlib makes the guarantee that this is the maximum output size
  2588. int outSize =
  2589. static_cast<int>(static_cast<double>(str.size()) * 1.001 + 13.0);
  2590. std::vector<unsigned char> out(outSize);
  2591. strm.avail_in = static_cast<uInt>(str.size());
  2592. strm.next_in = in;
  2593. strm.avail_out = outSize;
  2594. strm.next_out = &out[0];
  2595. ret = deflate(&strm, Z_FINISH);
  2596. if (ret != Z_STREAM_END) {
  2597. cmCTestLog(this, ERROR_MESSAGE, "Error during gzip compression."
  2598. << std::endl);
  2599. return false;
  2600. }
  2601. (void)deflateEnd(&strm);
  2602. // Now base64 encode the resulting binary string
  2603. std::vector<unsigned char> base64EncodedBuffer((outSize * 3) / 2);
  2604. size_t rlen =
  2605. cmsysBase64_Encode(&out[0], strm.total_out, &base64EncodedBuffer[0], 1);
  2606. str.assign(reinterpret_cast<char*>(&base64EncodedBuffer[0]), rlen);
  2607. return true;
  2608. }