cmakemain.cxx 16 KB

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