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