cmCTest.cxx 90 KB

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