cmakemain.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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 "cmAlgorithms.h"
  4. #include "cmDocumentationEntry.h" // IWYU pragma: keep
  5. #include "cmGlobalGenerator.h"
  6. #include "cmMakefile.h"
  7. #include "cmState.h"
  8. #include "cmStateTypes.h"
  9. #include "cmSystemTools.h"
  10. #include "cmake.h"
  11. #include "cmcmd.h"
  12. #ifdef CMAKE_BUILD_WITH_CMAKE
  13. # include "cmDocumentation.h"
  14. # include "cmDynamicLoader.h"
  15. #endif
  16. #include "cm_uv.h"
  17. #include "cmsys/Encoding.hxx"
  18. #if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
  19. # include "cmsys/ConsoleBuf.hxx"
  20. #endif
  21. #include <ctype.h>
  22. #include <iostream>
  23. #include <string.h>
  24. #include <string>
  25. #include <vector>
  26. #ifdef CMAKE_BUILD_WITH_CMAKE
  27. static const char* cmDocumentationName[][2] = {
  28. { nullptr, " cmake - Cross-Platform Makefile Generator." },
  29. { nullptr, nullptr }
  30. };
  31. static const char* cmDocumentationUsage[][2] = {
  32. { nullptr,
  33. " cmake [options] <path-to-source>\n"
  34. " cmake [options] <path-to-existing-build>\n"
  35. " cmake [options] -S <path-to-source> -B <path-to-build>" },
  36. { nullptr,
  37. "Specify a source directory to (re-)generate a build system for "
  38. "it in the current working directory. Specify an existing build "
  39. "directory to re-generate its build system." },
  40. { nullptr, nullptr }
  41. };
  42. static const char* cmDocumentationUsageNote[][2] = {
  43. { nullptr, "Run 'cmake --help' for more information." },
  44. { nullptr, nullptr }
  45. };
  46. # define CMAKE_BUILD_OPTIONS \
  47. " <dir> = Project binary directory to be built.\n" \
  48. " -j [<jobs>] --parallel [<jobs>] = Build in parallel using\n" \
  49. " the given number of jobs. If <jobs> is omitted\n" \
  50. " the native build tool's default number is used.\n" \
  51. " The CMAKE_BUILD_PARALLEL_LEVEL environment " \
  52. "variable\n" \
  53. " specifies a default parallel level when this " \
  54. "option\n" \
  55. " is not given.\n" \
  56. " --target <tgt> = Build <tgt> instead of default targets.\n" \
  57. " May only be specified once.\n" \
  58. " --config <cfg> = For multi-configuration tools, choose <cfg>.\n" \
  59. " --clean-first = Build target 'clean' first, then build.\n" \
  60. " (To clean only, use --target 'clean'.)\n" \
  61. " --use-stderr = Ignored. Behavior is default in CMake >= 3.0.\n" \
  62. " -v --verbose = Enable verbose output - if supported - including\n" \
  63. " the build commands to be executed. \n" \
  64. " -- = Pass remaining options to the native tool.\n"
  65. static const char* cmDocumentationOptions[][2] = {
  66. CMAKE_STANDARD_OPTIONS_TABLE,
  67. { "-E", "CMake command mode." },
  68. { "-L[A][H]", "List non-advanced cached variables." },
  69. { "--build <dir>", "Build a CMake-generated project binary tree." },
  70. { "--open <dir>", "Open generated project in the associated application." },
  71. { "-N", "View mode only." },
  72. { "-P <file>", "Process script mode." },
  73. { "--find-package", "Run in pkg-config like mode." },
  74. { "--graphviz=[file]",
  75. "Generate graphviz of dependencies, see "
  76. "CMakeGraphVizOptions.cmake for more." },
  77. { "--system-information [file]", "Dump information about this system." },
  78. { "--debug-trycompile",
  79. "Do not delete the try_compile build tree. Only "
  80. "useful on one try_compile at a time." },
  81. { "--debug-output", "Put cmake in a debug mode." },
  82. { "--trace", "Put cmake in trace mode." },
  83. { "--trace-expand", "Put cmake in trace mode with variable expansion." },
  84. { "--trace-source=<file>",
  85. "Trace only this CMake file/module. Multiple options allowed." },
  86. { "--warn-uninitialized", "Warn about uninitialized values." },
  87. { "--warn-unused-vars", "Warn about unused variables." },
  88. { "--no-warn-unused-cli", "Don't warn about command line options." },
  89. { "--check-system-vars",
  90. "Find problems with variable usage in system "
  91. "files." },
  92. { nullptr, nullptr }
  93. };
  94. #endif
  95. static int do_command(int ac, char const* const* av)
  96. {
  97. std::vector<std::string> args;
  98. args.reserve(ac - 1);
  99. args.emplace_back(av[0]);
  100. args.insert(args.end(), av + 2, av + ac);
  101. return cmcmd::ExecuteCMakeCommand(args);
  102. }
  103. int do_cmake(int ac, char const* const* av);
  104. static int do_build(int ac, char const* const* av);
  105. static int do_open(int ac, char const* const* av);
  106. static cmMakefile* cmakemainGetMakefile(cmake* cm)
  107. {
  108. if (cm && cm->GetDebugOutput()) {
  109. cmGlobalGenerator* gg = cm->GetGlobalGenerator();
  110. if (gg) {
  111. return gg->GetCurrentMakefile();
  112. }
  113. }
  114. return nullptr;
  115. }
  116. static std::string cmakemainGetStack(cmake* cm)
  117. {
  118. std::string msg;
  119. cmMakefile* mf = cmakemainGetMakefile(cm);
  120. if (mf) {
  121. msg = mf->FormatListFileStack();
  122. if (!msg.empty()) {
  123. msg = "\n Called from: " + msg;
  124. }
  125. }
  126. return msg;
  127. }
  128. static void cmakemainMessageCallback(const char* m, const char* /*unused*/,
  129. cmake* cm)
  130. {
  131. std::cerr << m << cmakemainGetStack(cm) << std::endl << std::flush;
  132. }
  133. static void cmakemainProgressCallback(const char* m, float prog, cmake* cm)
  134. {
  135. cmMakefile* mf = cmakemainGetMakefile(cm);
  136. std::string dir;
  137. if ((mf) && (strstr(m, "Configuring") == m) && (prog < 0)) {
  138. dir = " ";
  139. dir += mf->GetCurrentSourceDirectory();
  140. } else if ((mf) && (strstr(m, "Generating") == m)) {
  141. dir = " ";
  142. dir += mf->GetCurrentBinaryDirectory();
  143. }
  144. if ((prog < 0) || (!dir.empty())) {
  145. std::cout << "-- " << m << dir << cmakemainGetStack(cm) << std::endl;
  146. }
  147. std::cout.flush();
  148. }
  149. int main(int ac, char const* const* av)
  150. {
  151. #if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
  152. // Replace streambuf so we can output Unicode to console
  153. cmsys::ConsoleBuf::Manager consoleOut(std::cout);
  154. consoleOut.SetUTF8Pipes();
  155. cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
  156. consoleErr.SetUTF8Pipes();
  157. #endif
  158. cmsys::Encoding::CommandLineArguments args =
  159. cmsys::Encoding::CommandLineArguments::Main(ac, av);
  160. ac = args.argc();
  161. av = args.argv();
  162. cmSystemTools::EnableMSVCDebugHook();
  163. cmSystemTools::InitializeLibUV();
  164. cmSystemTools::FindCMakeResources(av[0]);
  165. if (ac > 1) {
  166. if (strcmp(av[1], "--build") == 0) {
  167. return do_build(ac, av);
  168. }
  169. if (strcmp(av[1], "--open") == 0) {
  170. return do_open(ac, av);
  171. }
  172. if (strcmp(av[1], "-E") == 0) {
  173. return do_command(ac, av);
  174. }
  175. }
  176. int ret = do_cmake(ac, av);
  177. #ifdef CMAKE_BUILD_WITH_CMAKE
  178. cmDynamicLoader::FlushCache();
  179. #endif
  180. uv_loop_close(uv_default_loop());
  181. return ret;
  182. }
  183. int do_cmake(int ac, char const* const* av)
  184. {
  185. if (cmSystemTools::GetCurrentWorkingDirectory().empty()) {
  186. std::cerr << "Current working directory cannot be established."
  187. << std::endl;
  188. return 1;
  189. }
  190. #ifdef CMAKE_BUILD_WITH_CMAKE
  191. cmDocumentation doc;
  192. doc.addCMakeStandardDocSections();
  193. if (doc.CheckOptions(ac, av)) {
  194. // Construct and print requested documentation.
  195. cmake hcm(cmake::RoleInternal, cmState::Unknown);
  196. hcm.SetHomeDirectory("");
  197. hcm.SetHomeOutputDirectory("");
  198. hcm.AddCMakePaths();
  199. // the command line args are processed here so that you can do
  200. // -DCMAKE_MODULE_PATH=/some/path and have this value accessible here
  201. std::vector<std::string> args(av, av + ac);
  202. hcm.SetCacheArgs(args);
  203. auto generators = hcm.GetGeneratorsDocumentation();
  204. doc.SetName("cmake");
  205. doc.SetSection("Name", cmDocumentationName);
  206. doc.SetSection("Usage", cmDocumentationUsage);
  207. if (ac == 1) {
  208. doc.AppendSection("Usage", cmDocumentationUsageNote);
  209. }
  210. doc.AppendSection("Generators", generators);
  211. doc.PrependSection("Options", cmDocumentationOptions);
  212. return doc.PrintRequestedDocumentation(std::cout) ? 0 : 1;
  213. }
  214. #else
  215. if (ac == 1) {
  216. std::cout
  217. << "Bootstrap CMake should not be used outside CMake build process."
  218. << std::endl;
  219. return 0;
  220. }
  221. #endif
  222. bool sysinfo = false;
  223. bool list_cached = false;
  224. bool list_all_cached = false;
  225. bool list_help = false;
  226. bool view_only = false;
  227. cmake::WorkingMode workingMode = cmake::NORMAL_MODE;
  228. std::vector<std::string> args;
  229. for (int i = 0; i < ac; ++i) {
  230. if (strcmp(av[i], "-i") == 0) {
  231. /* clang-format off */
  232. std::cerr <<
  233. "The \"cmake -i\" wizard mode is no longer supported.\n"
  234. "Use the -D option to set cache values on the command line.\n"
  235. "Use cmake-gui or ccmake for an interactive dialog.\n";
  236. /* clang-format on */
  237. return 1;
  238. }
  239. if (strcmp(av[i], "--system-information") == 0) {
  240. sysinfo = true;
  241. } else if (strcmp(av[i], "-N") == 0) {
  242. view_only = true;
  243. } else if (strcmp(av[i], "-L") == 0) {
  244. list_cached = true;
  245. } else if (strcmp(av[i], "-LA") == 0) {
  246. list_all_cached = true;
  247. } else if (strcmp(av[i], "-LH") == 0) {
  248. list_cached = true;
  249. list_help = true;
  250. } else if (strcmp(av[i], "-LAH") == 0) {
  251. list_all_cached = true;
  252. list_help = true;
  253. } else if (cmHasLiteralPrefix(av[i], "-P")) {
  254. if (i == ac - 1) {
  255. cmSystemTools::Error("No script specified for argument -P");
  256. return 1;
  257. }
  258. workingMode = cmake::SCRIPT_MODE;
  259. args.emplace_back(av[i]);
  260. i++;
  261. args.emplace_back(av[i]);
  262. } else if (cmHasLiteralPrefix(av[i], "--find-package")) {
  263. workingMode = cmake::FIND_PACKAGE_MODE;
  264. args.emplace_back(av[i]);
  265. } else {
  266. args.emplace_back(av[i]);
  267. }
  268. }
  269. if (sysinfo) {
  270. cmake cm(cmake::RoleProject, cmState::Project);
  271. cm.SetHomeDirectory("");
  272. cm.SetHomeOutputDirectory("");
  273. int ret = cm.GetSystemInformation(args);
  274. return ret;
  275. }
  276. cmake::Role const role =
  277. workingMode == cmake::SCRIPT_MODE ? cmake::RoleScript : cmake::RoleProject;
  278. cmState::Mode mode = cmState::Unknown;
  279. switch (workingMode) {
  280. case cmake::NORMAL_MODE:
  281. mode = cmState::Project;
  282. break;
  283. case cmake::SCRIPT_MODE:
  284. mode = cmState::Script;
  285. break;
  286. case cmake::FIND_PACKAGE_MODE:
  287. mode = cmState::FindPackage;
  288. break;
  289. }
  290. cmake cm(role, mode);
  291. cm.SetHomeDirectory("");
  292. cm.SetHomeOutputDirectory("");
  293. cmSystemTools::SetMessageCallback([&cm](const char* msg, const char* title) {
  294. cmakemainMessageCallback(msg, title, &cm);
  295. });
  296. cm.SetProgressCallback([&cm](const char* msg, float prog) {
  297. cmakemainProgressCallback(msg, prog, &cm);
  298. });
  299. cm.SetWorkingMode(workingMode);
  300. int res = cm.Run(args, view_only);
  301. if (list_cached || list_all_cached) {
  302. std::cout << "-- Cache values" << std::endl;
  303. std::vector<std::string> keys = cm.GetState()->GetCacheEntryKeys();
  304. for (std::string const& k : keys) {
  305. cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(k);
  306. if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC &&
  307. t != cmStateEnums::UNINITIALIZED) {
  308. const char* advancedProp =
  309. cm.GetState()->GetCacheEntryProperty(k, "ADVANCED");
  310. if (list_all_cached || !advancedProp) {
  311. if (list_help) {
  312. std::cout << "// "
  313. << cm.GetState()->GetCacheEntryProperty(k, "HELPSTRING")
  314. << std::endl;
  315. }
  316. std::cout << k << ":" << cmState::CacheEntryTypeToString(t) << "="
  317. << cm.GetState()->GetCacheEntryValue(k) << std::endl;
  318. if (list_help) {
  319. std::cout << std::endl;
  320. }
  321. }
  322. }
  323. }
  324. }
  325. // Always return a non-negative value. Windows tools do not always
  326. // interpret negative return values as errors.
  327. if (res != 0) {
  328. return 1;
  329. }
  330. return 0;
  331. }
  332. namespace {
  333. int extract_job_number(int& index, char const* current, char const* next,
  334. int len_of_flag)
  335. {
  336. std::string command(current);
  337. std::string jobString = command.substr(len_of_flag);
  338. if (jobString.empty() && next && isdigit(next[0])) {
  339. ++index; // skip parsing the job number
  340. jobString = std::string(next);
  341. }
  342. int jobs = -1;
  343. unsigned long numJobs = 0;
  344. if (jobString.empty()) {
  345. jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL;
  346. } else if (cmSystemTools::StringToULong(jobString.c_str(), &numJobs)) {
  347. jobs = int(numJobs);
  348. } else {
  349. std::cerr << "'" << command.substr(0, len_of_flag) << "' invalid number '"
  350. << jobString << "' given.\n\n";
  351. }
  352. return jobs;
  353. }
  354. }
  355. static int do_build(int ac, char const* const* av)
  356. {
  357. #ifndef CMAKE_BUILD_WITH_CMAKE
  358. std::cerr << "This cmake does not support --build\n";
  359. return -1;
  360. #else
  361. int jobs = cmake::NO_BUILD_PARALLEL_LEVEL;
  362. std::string target;
  363. std::string config = "Debug";
  364. std::string dir;
  365. std::vector<std::string> nativeOptions;
  366. bool clean = false;
  367. bool verbose = cmSystemTools::HasEnv("VERBOSE");
  368. bool hasTarget = false;
  369. enum Doing
  370. {
  371. DoingNone,
  372. DoingDir,
  373. DoingTarget,
  374. DoingConfig,
  375. DoingNative
  376. };
  377. Doing doing = DoingDir;
  378. for (int i = 2; i < ac; ++i) {
  379. if (doing == DoingNative) {
  380. nativeOptions.emplace_back(av[i]);
  381. } else if (cmHasLiteralPrefix(av[i], "-j")) {
  382. const char* nextArg = ((i + 1 < ac) ? av[i + 1] : nullptr);
  383. jobs = extract_job_number(i, av[i], nextArg, sizeof("-j") - 1);
  384. if (jobs < 0) {
  385. dir.clear();
  386. }
  387. } else if (cmHasLiteralPrefix(av[i], "--parallel")) {
  388. const char* nextArg = ((i + 1 < ac) ? av[i + 1] : nullptr);
  389. jobs = extract_job_number(i, av[i], nextArg, sizeof("--parallel") - 1);
  390. if (jobs < 0) {
  391. dir.clear();
  392. }
  393. } else if (strcmp(av[i], "--target") == 0) {
  394. if (!hasTarget) {
  395. doing = DoingTarget;
  396. hasTarget = true;
  397. } else {
  398. std::cerr << "'--target' may not be specified more than once.\n\n";
  399. dir.clear();
  400. break;
  401. }
  402. } else if (strcmp(av[i], "--config") == 0) {
  403. doing = DoingConfig;
  404. } else if (strcmp(av[i], "--clean-first") == 0) {
  405. clean = true;
  406. doing = DoingNone;
  407. } else if ((strcmp(av[i], "--verbose") == 0) ||
  408. (strcmp(av[i], "-v") == 0)) {
  409. verbose = true;
  410. doing = DoingNone;
  411. } else if (strcmp(av[i], "--use-stderr") == 0) {
  412. /* tolerate legacy option */
  413. } else if (strcmp(av[i], "--") == 0) {
  414. doing = DoingNative;
  415. } else {
  416. switch (doing) {
  417. case DoingDir:
  418. dir = cmSystemTools::CollapseFullPath(av[i]);
  419. doing = DoingNone;
  420. break;
  421. case DoingTarget:
  422. target = av[i];
  423. doing = DoingNone;
  424. break;
  425. case DoingConfig:
  426. config = av[i];
  427. doing = DoingNone;
  428. break;
  429. default:
  430. std::cerr << "Unknown argument " << av[i] << std::endl;
  431. dir.clear();
  432. break;
  433. }
  434. }
  435. }
  436. if (jobs == cmake::NO_BUILD_PARALLEL_LEVEL) {
  437. std::string parallel;
  438. if (cmSystemTools::GetEnv("CMAKE_BUILD_PARALLEL_LEVEL", parallel)) {
  439. if (parallel.empty()) {
  440. jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL;
  441. } else {
  442. unsigned long numJobs = 0;
  443. if (cmSystemTools::StringToULong(parallel.c_str(), &numJobs)) {
  444. jobs = int(numJobs);
  445. } else {
  446. std::cerr << "'CMAKE_BUILD_PARALLEL_LEVEL' environment variable\n"
  447. << "invalid number '" << parallel << "' given.\n\n";
  448. dir.clear();
  449. }
  450. }
  451. }
  452. }
  453. if (dir.empty()) {
  454. /* clang-format off */
  455. std::cerr <<
  456. "Usage: cmake --build <dir> [options] [-- [native-options]]\n"
  457. "Options:\n"
  458. CMAKE_BUILD_OPTIONS
  459. ;
  460. /* clang-format on */
  461. return 1;
  462. }
  463. cmake cm(cmake::RoleInternal, cmState::Unknown);
  464. cmSystemTools::SetMessageCallback([&cm](const char* msg, const char* title) {
  465. cmakemainMessageCallback(msg, title, &cm);
  466. });
  467. cm.SetProgressCallback([&cm](const char* msg, float prog) {
  468. cmakemainProgressCallback(msg, prog, &cm);
  469. });
  470. return cm.Build(jobs, dir, target, config, nativeOptions, clean, verbose);
  471. #endif
  472. }
  473. static int do_open(int ac, char const* const* av)
  474. {
  475. #ifndef CMAKE_BUILD_WITH_CMAKE
  476. std::cerr << "This cmake does not support --open\n";
  477. return -1;
  478. #else
  479. std::string dir;
  480. enum Doing
  481. {
  482. DoingNone,
  483. DoingDir,
  484. };
  485. Doing doing = DoingDir;
  486. for (int i = 2; i < ac; ++i) {
  487. switch (doing) {
  488. case DoingDir:
  489. dir = cmSystemTools::CollapseFullPath(av[i]);
  490. doing = DoingNone;
  491. break;
  492. default:
  493. std::cerr << "Unknown argument " << av[i] << std::endl;
  494. dir.clear();
  495. break;
  496. }
  497. }
  498. if (dir.empty()) {
  499. std::cerr << "Usage: cmake --open <dir>\n";
  500. return 1;
  501. }
  502. cmake cm(cmake::RoleInternal, cmState::Unknown);
  503. cmSystemTools::SetMessageCallback([&cm](const char* msg, const char* title) {
  504. cmakemainMessageCallback(msg, title, &cm);
  505. });
  506. cm.SetProgressCallback([&cm](const char* msg, float prog) {
  507. cmakemainProgressCallback(msg, prog, &cm);
  508. });
  509. return cm.Open(dir, false) ? 0 : 1;
  510. #endif
  511. }