cmCTestScriptHandler.cxx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmCTestScriptHandler.h"
  4. #include <chrono>
  5. #include <cstdlib>
  6. #include <map>
  7. #include <ratio>
  8. #include <sstream>
  9. #include <utility>
  10. #include <cm/memory>
  11. #include <cm3p/uv.h>
  12. #include "cmCTest.h"
  13. #include "cmCTestBuildCommand.h"
  14. #include "cmCTestConfigureCommand.h"
  15. #include "cmCTestCoverageCommand.h"
  16. #include "cmCTestEmptyBinaryDirectoryCommand.h"
  17. #include "cmCTestMemCheckCommand.h"
  18. #include "cmCTestReadCustomFilesCommand.h"
  19. #include "cmCTestRunScriptCommand.h"
  20. #include "cmCTestSleepCommand.h"
  21. #include "cmCTestStartCommand.h"
  22. #include "cmCTestSubmitCommand.h"
  23. #include "cmCTestTestCommand.h"
  24. #include "cmCTestUpdateCommand.h"
  25. #include "cmCTestUploadCommand.h"
  26. #include "cmDuration.h"
  27. #include "cmGlobalGenerator.h"
  28. #include "cmMakefile.h"
  29. #include "cmState.h"
  30. #include "cmStateDirectory.h"
  31. #include "cmStateSnapshot.h"
  32. #include "cmSystemTools.h"
  33. #include "cmUVHandlePtr.h"
  34. #include "cmUVProcessChain.h"
  35. #include "cmake.h"
  36. cmCTestScriptHandler::cmCTestScriptHandler(cmCTest* ctest)
  37. : CTest(ctest)
  38. {
  39. }
  40. cmCTestScriptHandler::~cmCTestScriptHandler() = default;
  41. // just adds an argument to the vector
  42. void cmCTestScriptHandler::AddConfigurationScript(std::string const& script,
  43. bool pscope)
  44. {
  45. this->ConfigurationScripts.emplace_back(script);
  46. this->ScriptProcessScope.push_back(pscope);
  47. }
  48. // the generic entry point for handling scripts, this routine will run all
  49. // the scripts provides a -S arguments
  50. int cmCTestScriptHandler::ProcessHandler()
  51. {
  52. int res = 0;
  53. for (size_t i = 0; i < this->ConfigurationScripts.size(); ++i) {
  54. // for each script run it
  55. res |= this->RunConfigurationScript(this->ConfigurationScripts[i],
  56. this->ScriptProcessScope[i]);
  57. }
  58. return res;
  59. }
  60. void cmCTestScriptHandler::UpdateElapsedTime()
  61. {
  62. if (this->Makefile) {
  63. // set the current elapsed time
  64. auto itime = cmDurationTo<unsigned int>(this->CTest->GetElapsedTime());
  65. auto timeString = std::to_string(itime);
  66. this->Makefile->AddDefinition("CTEST_ELAPSED_TIME", timeString);
  67. }
  68. }
  69. int cmCTestScriptHandler::ExecuteScript(std::string const& total_script_arg)
  70. {
  71. // execute the script passing in the arguments to the script as well as the
  72. // arguments from this invocation of cmake
  73. std::vector<std::string> argv;
  74. argv.push_back(cmSystemTools::GetCTestCommand());
  75. argv.push_back("-SR");
  76. argv.push_back(total_script_arg);
  77. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  78. "Executable for CTest is: " << cmSystemTools::GetCTestCommand()
  79. << "\n");
  80. // now pass through all the other arguments
  81. std::vector<std::string>& initArgs =
  82. this->CTest->GetInitialCommandLineArguments();
  83. //*** need to make sure this does not have the current script ***
  84. for (size_t i = 1; i < initArgs.size(); ++i) {
  85. // in a nested subprocess, skip the parent's `-SR <path>` arguments.
  86. if (initArgs[i] == "-SR") {
  87. i++; // <path>
  88. } else {
  89. argv.push_back(initArgs[i]);
  90. }
  91. }
  92. // Now create process object
  93. cmUVProcessChainBuilder builder;
  94. builder.AddCommand(argv)
  95. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  96. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  97. auto process = builder.Start();
  98. cm::uv_pipe_ptr outPipe;
  99. outPipe.init(process.GetLoop(), 0);
  100. uv_pipe_open(outPipe, process.OutputStream());
  101. cm::uv_pipe_ptr errPipe;
  102. errPipe.init(process.GetLoop(), 0);
  103. uv_pipe_open(errPipe, process.ErrorStream());
  104. std::vector<char> out;
  105. std::vector<char> err;
  106. std::string line;
  107. auto pipe =
  108. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  109. std::chrono::seconds(100), out, err);
  110. while (pipe != cmSystemTools::WaitForLineResult::None) {
  111. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  112. "Output: " << line << "\n");
  113. if (pipe == cmSystemTools::WaitForLineResult::STDERR) {
  114. cmCTestLog(this->CTest, ERROR_MESSAGE, line << "\n");
  115. } else if (pipe == cmSystemTools::WaitForLineResult::STDOUT) {
  116. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, line << "\n");
  117. }
  118. pipe =
  119. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  120. std::chrono::seconds(100), out, err);
  121. }
  122. // Properly handle output of the build command
  123. process.Wait();
  124. auto const& status = process.GetStatus(0);
  125. auto result = status.GetException();
  126. int retVal = 0;
  127. bool failed = false;
  128. switch (result.first) {
  129. case cmUVProcessChain::ExceptionCode::None:
  130. retVal = static_cast<int>(status.ExitStatus);
  131. break;
  132. case cmUVProcessChain::ExceptionCode::Spawn:
  133. cmCTestLog(this->CTest, ERROR_MESSAGE,
  134. "\tError executing ctest: " << result.second << std::endl);
  135. failed = true;
  136. break;
  137. default:
  138. retVal = status.TermSignal;
  139. cmCTestLog(this->CTest, ERROR_MESSAGE,
  140. "\tThere was an exception: " << result.second << " " << retVal
  141. << std::endl);
  142. failed = true;
  143. }
  144. if (failed) {
  145. std::ostringstream message;
  146. message << "Error running command: [";
  147. message << static_cast<int>(result.first) << "] ";
  148. for (std::string const& arg : argv) {
  149. message << arg << " ";
  150. }
  151. cmCTestLog(this->CTest, ERROR_MESSAGE, message.str() << std::endl);
  152. return -1;
  153. }
  154. return retVal;
  155. }
  156. void cmCTestScriptHandler::CreateCMake()
  157. {
  158. // create a cmake instance to read the configuration script
  159. this->CMake = cm::make_unique<cmake>(cmState::Role::CTest);
  160. this->CMake->GetCurrentSnapshot().SetDefaultDefinitions();
  161. this->CMake->AddCMakePaths();
  162. this->CMake->SetWorkingMode(cmake::SCRIPT_MODE);
  163. this->GlobalGenerator =
  164. cm::make_unique<cmGlobalGenerator>(this->CMake.get());
  165. cmStateSnapshot snapshot = this->CMake->GetCurrentSnapshot();
  166. std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
  167. snapshot.GetDirectory().SetCurrentSource(cwd);
  168. snapshot.GetDirectory().SetCurrentBinary(cwd);
  169. this->Makefile =
  170. cm::make_unique<cmMakefile>(this->GlobalGenerator.get(), snapshot);
  171. if (this->ParentMakefile) {
  172. this->Makefile->SetRecursionDepth(
  173. this->ParentMakefile->GetRecursionDepth());
  174. }
  175. this->CMake->SetProgressCallback(
  176. [this](std::string const& m, float /*unused*/) {
  177. if (!m.empty()) {
  178. cmCTestLog(this->CTest, HANDLER_OUTPUT, "-- " << m << std::endl);
  179. }
  180. });
  181. cmState* state = this->CMake->GetState();
  182. state->AddBuiltinCommand("ctest_build", cmCTestBuildCommand(this->CTest));
  183. state->AddBuiltinCommand("ctest_configure",
  184. cmCTestConfigureCommand(this->CTest));
  185. state->AddBuiltinCommand("ctest_coverage",
  186. cmCTestCoverageCommand(this->CTest));
  187. state->AddBuiltinCommand("ctest_empty_binary_directory",
  188. cmCTestEmptyBinaryDirectoryCommand);
  189. state->AddBuiltinCommand("ctest_memcheck",
  190. cmCTestMemCheckCommand(this->CTest));
  191. state->AddBuiltinCommand("ctest_read_custom_files",
  192. cmCTestReadCustomFilesCommand(this->CTest));
  193. state->AddBuiltinCommand("ctest_run_script",
  194. cmCTestRunScriptCommand(this->CTest));
  195. state->AddBuiltinCommand("ctest_sleep", cmCTestSleepCommand);
  196. state->AddBuiltinCommand("ctest_start", cmCTestStartCommand(this->CTest));
  197. state->AddBuiltinCommand("ctest_submit", cmCTestSubmitCommand(this->CTest));
  198. state->AddBuiltinCommand("ctest_test", cmCTestTestCommand(this->CTest));
  199. state->AddBuiltinCommand("ctest_update", cmCTestUpdateCommand(this->CTest));
  200. state->AddBuiltinCommand("ctest_upload", cmCTestUploadCommand(this->CTest));
  201. }
  202. // this sets up some variables for the script to use, creates the required
  203. // cmake instance and generators, and then reads in the script
  204. int cmCTestScriptHandler::ReadInScript(std::string const& total_script_arg)
  205. {
  206. // Reset the error flag so that the script is read in no matter what
  207. cmSystemTools::ResetErrorOccurredFlag();
  208. // if the argument has a , in it then it needs to be broken into the fist
  209. // argument (which is the script) and the second argument which will be
  210. // passed into the scripts as S_ARG
  211. std::string script;
  212. std::string script_arg;
  213. std::string::size_type const comma_pos = total_script_arg.find(',');
  214. if (comma_pos != std::string::npos) {
  215. script = total_script_arg.substr(0, comma_pos);
  216. script_arg = total_script_arg.substr(comma_pos + 1);
  217. } else {
  218. script = total_script_arg;
  219. }
  220. // make sure the file exists
  221. if (!cmSystemTools::FileExists(script)) {
  222. cmSystemTools::Error("Cannot find file: " + script);
  223. return 1;
  224. }
  225. // read in the list file to fill the cache
  226. // create a cmake instance to read the configuration script
  227. this->CreateCMake();
  228. // set a variable with the path to the current script
  229. this->Makefile->AddDefinition("CTEST_SCRIPT_DIRECTORY",
  230. cmSystemTools::GetFilenamePath(script));
  231. this->Makefile->AddDefinition("CTEST_SCRIPT_NAME",
  232. cmSystemTools::GetFilenameName(script));
  233. this->Makefile->AddDefinition("CTEST_EXECUTABLE_NAME",
  234. cmSystemTools::GetCTestCommand());
  235. this->Makefile->AddDefinition("CMAKE_EXECUTABLE_NAME",
  236. cmSystemTools::GetCMakeCommand());
  237. this->UpdateElapsedTime();
  238. // set the CTEST_CONFIGURATION_TYPE variable to the current value of the
  239. // the -C argument on the command line.
  240. if (!this->CTest->GetConfigType().empty()) {
  241. this->Makefile->AddDefinition("CTEST_CONFIGURATION_TYPE",
  242. this->CTest->GetConfigType());
  243. }
  244. // add the script arg if defined
  245. if (!script_arg.empty()) {
  246. this->Makefile->AddDefinition("CTEST_SCRIPT_ARG", script_arg);
  247. }
  248. // set a callback function to update the elapsed time
  249. this->Makefile->OnExecuteCommand([this] { this->UpdateElapsedTime(); });
  250. /* Execute CTestScriptMode.cmake, which loads CMakeDetermineSystem and
  251. CMakeSystemSpecificInformation, so
  252. that variables like CMAKE_SYSTEM and also the search paths for libraries,
  253. header and executables are set correctly and can be used. Makes new-style
  254. ctest scripting easier. */
  255. std::string systemFile =
  256. this->Makefile->GetModulesFile("CTestScriptMode.cmake");
  257. if (!this->Makefile->ReadListFile(systemFile) ||
  258. cmSystemTools::GetErrorOccurredFlag()) {
  259. cmCTestLog(this->CTest, ERROR_MESSAGE,
  260. "Error in read:" << systemFile << "\n");
  261. return -1;
  262. }
  263. // Add definitions of variables passed in on the command line:
  264. std::map<std::string, std::string> const& defs =
  265. this->CTest->GetDefinitions();
  266. for (auto const& d : defs) {
  267. this->Makefile->AddDefinition(d.first, d.second);
  268. }
  269. int res = 0;
  270. // finally read in the script
  271. if (!this->Makefile->ReadListFile(script) ||
  272. cmSystemTools::GetErrorOccurredFlag()) {
  273. // Reset the error flag so that it can run more than
  274. // one script with an error when you use ctest_run_script.
  275. cmSystemTools::ResetErrorOccurredFlag();
  276. res = -1;
  277. }
  278. return this->CMake->HasScriptModeExitCode()
  279. ? this->CMake->GetScriptModeExitCode()
  280. : res;
  281. }
  282. // run a specific script
  283. int cmCTestScriptHandler::RunConfigurationScript(
  284. std::string const& total_script_arg, bool pscope)
  285. {
  286. #ifndef CMAKE_BOOTSTRAP
  287. cmSystemTools::SaveRestoreEnvironment sre;
  288. #endif
  289. int result;
  290. // read in the script
  291. if (pscope) {
  292. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  293. "Reading Script: " << total_script_arg << std::endl);
  294. result = this->ReadInScript(total_script_arg);
  295. } else {
  296. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  297. "Executing Script: " << total_script_arg << std::endl);
  298. result = this->ExecuteScript(total_script_arg);
  299. }
  300. return result;
  301. }
  302. bool cmCTestScriptHandler::RunScript(cmCTest* ctest, cmMakefile* mf,
  303. std::string const& sname, bool InProcess,
  304. int* returnValue)
  305. {
  306. auto sh = cm::make_unique<cmCTestScriptHandler>(ctest);
  307. sh->ParentMakefile = mf;
  308. sh->AddConfigurationScript(sname, InProcess);
  309. int res = sh->ProcessHandler();
  310. if (returnValue) {
  311. *returnValue = res;
  312. }
  313. return true;
  314. }