cmCTest.cxx 96 KB

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