cmakemain.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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"
  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);
  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. std::vector<cmDocumentationEntry> generators;
  205. hcm.GetGeneratorDocumentation(generators);
  206. doc.SetName("cmake");
  207. doc.SetSection("Name", cmDocumentationName);
  208. doc.SetSection("Usage", cmDocumentationUsage);
  209. if (ac == 1) {
  210. doc.AppendSection("Usage", cmDocumentationUsageNote);
  211. }
  212. doc.AppendSection("Generators", generators);
  213. doc.PrependSection("Options", cmDocumentationOptions);
  214. return doc.PrintRequestedDocumentation(std::cout) ? 0 : 1;
  215. }
  216. #else
  217. if (ac == 1) {
  218. std::cout
  219. << "Bootstrap CMake should not be used outside CMake build process."
  220. << std::endl;
  221. return 0;
  222. }
  223. #endif
  224. bool sysinfo = false;
  225. bool list_cached = false;
  226. bool list_all_cached = false;
  227. bool list_help = false;
  228. bool view_only = false;
  229. cmake::WorkingMode workingMode = cmake::NORMAL_MODE;
  230. std::vector<std::string> args;
  231. for (int i = 0; i < ac; ++i) {
  232. if (strcmp(av[i], "-i") == 0) {
  233. /* clang-format off */
  234. std::cerr <<
  235. "The \"cmake -i\" wizard mode is no longer supported.\n"
  236. "Use the -D option to set cache values on the command line.\n"
  237. "Use cmake-gui or ccmake for an interactive dialog.\n";
  238. /* clang-format on */
  239. return 1;
  240. }
  241. if (strcmp(av[i], "--system-information") == 0) {
  242. sysinfo = true;
  243. } else if (strcmp(av[i], "-N") == 0) {
  244. view_only = true;
  245. } else if (strcmp(av[i], "-L") == 0) {
  246. list_cached = true;
  247. } else if (strcmp(av[i], "-LA") == 0) {
  248. list_all_cached = true;
  249. } else if (strcmp(av[i], "-LH") == 0) {
  250. list_cached = true;
  251. list_help = true;
  252. } else if (strcmp(av[i], "-LAH") == 0) {
  253. list_all_cached = true;
  254. list_help = true;
  255. } else if (cmHasLiteralPrefix(av[i], "-P")) {
  256. if (i == ac - 1) {
  257. cmSystemTools::Error("No script specified for argument -P");
  258. } else {
  259. workingMode = cmake::SCRIPT_MODE;
  260. args.push_back(av[i]);
  261. i++;
  262. args.push_back(av[i]);
  263. }
  264. } else if (cmHasLiteralPrefix(av[i], "--find-package")) {
  265. workingMode = cmake::FIND_PACKAGE_MODE;
  266. args.push_back(av[i]);
  267. } else {
  268. args.push_back(av[i]);
  269. }
  270. }
  271. if (sysinfo) {
  272. cmake cm(cmake::RoleProject);
  273. cm.SetHomeDirectory("");
  274. cm.SetHomeOutputDirectory("");
  275. int ret = cm.GetSystemInformation(args);
  276. return ret;
  277. }
  278. cmake::Role const role =
  279. workingMode == cmake::SCRIPT_MODE ? cmake::RoleScript : cmake::RoleProject;
  280. cmake cm(role);
  281. cm.SetHomeDirectory("");
  282. cm.SetHomeOutputDirectory("");
  283. cmSystemTools::SetMessageCallback(cmakemainMessageCallback, &cm);
  284. cm.SetProgressCallback(cmakemainProgressCallback, &cm);
  285. cm.SetWorkingMode(workingMode);
  286. int res = cm.Run(args, view_only);
  287. if (list_cached || list_all_cached) {
  288. std::cout << "-- Cache values" << std::endl;
  289. std::vector<std::string> keys = cm.GetState()->GetCacheEntryKeys();
  290. for (std::string const& k : keys) {
  291. cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(k);
  292. if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC &&
  293. t != cmStateEnums::UNINITIALIZED) {
  294. const char* advancedProp =
  295. cm.GetState()->GetCacheEntryProperty(k, "ADVANCED");
  296. if (list_all_cached || !advancedProp) {
  297. if (list_help) {
  298. std::cout << "// "
  299. << cm.GetState()->GetCacheEntryProperty(k, "HELPSTRING")
  300. << std::endl;
  301. }
  302. std::cout << k << ":" << cmState::CacheEntryTypeToString(t) << "="
  303. << cm.GetState()->GetCacheEntryValue(k) << std::endl;
  304. if (list_help) {
  305. std::cout << std::endl;
  306. }
  307. }
  308. }
  309. }
  310. }
  311. // Always return a non-negative value. Windows tools do not always
  312. // interpret negative return values as errors.
  313. if (res != 0) {
  314. return 1;
  315. }
  316. return 0;
  317. }
  318. static int do_build(int ac, char const* const* av)
  319. {
  320. #ifndef CMAKE_BUILD_WITH_CMAKE
  321. std::cerr << "This cmake does not support --build\n";
  322. return -1;
  323. #else
  324. int jobs = cmake::NO_BUILD_PARALLEL_LEVEL;
  325. std::string target;
  326. std::string config = "Debug";
  327. std::string dir;
  328. std::vector<std::string> nativeOptions;
  329. bool clean = false;
  330. bool hasTarget = false;
  331. enum Doing
  332. {
  333. DoingNone,
  334. DoingJobs,
  335. DoingDir,
  336. DoingTarget,
  337. DoingConfig,
  338. DoingNative
  339. };
  340. Doing doing = DoingDir;
  341. for (int i = 2; i < ac; ++i) {
  342. if (doing == DoingNative) {
  343. nativeOptions.push_back(av[i]);
  344. } else if ((strcmp(av[i], "-j") == 0) ||
  345. (strcmp(av[i], "--parallel") == 0)) {
  346. jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL;
  347. /* does the next argument start with a number? */
  348. if ((i + 1 < ac) && (isdigit(*av[i + 1]))) {
  349. doing = DoingJobs;
  350. }
  351. } else if (strcmp(av[i], "--target") == 0) {
  352. if (!hasTarget) {
  353. doing = DoingTarget;
  354. hasTarget = true;
  355. } else {
  356. std::cerr << "'--target' may not be specified more than once.\n\n";
  357. dir.clear();
  358. break;
  359. }
  360. } else if (strcmp(av[i], "--config") == 0) {
  361. doing = DoingConfig;
  362. } else if (strcmp(av[i], "--clean-first") == 0) {
  363. clean = true;
  364. doing = DoingNone;
  365. } else if (strcmp(av[i], "--use-stderr") == 0) {
  366. /* tolerate legacy option */
  367. } else if (strcmp(av[i], "--") == 0) {
  368. doing = DoingNative;
  369. } else {
  370. switch (doing) {
  371. case DoingJobs: {
  372. unsigned long numJobs = 0;
  373. if (cmSystemTools::StringToULong(av[i], &numJobs)) {
  374. jobs = int(numJobs);
  375. doing = DoingNone;
  376. } else {
  377. std::cerr << "'" << av[i - 1] << "' invalid number '" << av[i]
  378. << "' given.\n\n";
  379. dir.clear();
  380. break;
  381. }
  382. } break;
  383. case DoingDir:
  384. dir = cmSystemTools::CollapseFullPath(av[i]);
  385. doing = DoingNone;
  386. break;
  387. case DoingTarget:
  388. target = av[i];
  389. doing = DoingNone;
  390. break;
  391. case DoingConfig:
  392. config = av[i];
  393. doing = DoingNone;
  394. break;
  395. default:
  396. std::cerr << "Unknown argument " << av[i] << std::endl;
  397. dir.clear();
  398. break;
  399. }
  400. }
  401. }
  402. if (jobs == cmake::NO_BUILD_PARALLEL_LEVEL) {
  403. std::string parallel;
  404. if (cmSystemTools::GetEnv("CMAKE_BUILD_PARALLEL_LEVEL", parallel)) {
  405. if (parallel.empty()) {
  406. jobs = cmake::DEFAULT_BUILD_PARALLEL_LEVEL;
  407. } else {
  408. unsigned long numJobs = 0;
  409. if (cmSystemTools::StringToULong(parallel.c_str(), &numJobs)) {
  410. jobs = int(numJobs);
  411. } else {
  412. std::cerr << "'CMAKE_BUILD_PARALLEL_LEVEL' environment variable\n"
  413. << "invalid number '" << parallel << "' given.\n\n";
  414. dir.clear();
  415. }
  416. }
  417. }
  418. }
  419. if (dir.empty()) {
  420. /* clang-format off */
  421. std::cerr <<
  422. "Usage: cmake --build <dir> [options] [-- [native-options]]\n"
  423. "Options:\n"
  424. CMAKE_BUILD_OPTIONS
  425. ;
  426. /* clang-format on */
  427. return 1;
  428. }
  429. cmake cm(cmake::RoleInternal);
  430. cmSystemTools::SetMessageCallback(cmakemainMessageCallback, &cm);
  431. cm.SetProgressCallback(cmakemainProgressCallback, &cm);
  432. return cm.Build(jobs, dir, target, config, nativeOptions, clean);
  433. #endif
  434. }
  435. static int do_open(int ac, char const* const* av)
  436. {
  437. #ifndef CMAKE_BUILD_WITH_CMAKE
  438. std::cerr << "This cmake does not support --open\n";
  439. return -1;
  440. #else
  441. std::string dir;
  442. enum Doing
  443. {
  444. DoingNone,
  445. DoingDir,
  446. };
  447. Doing doing = DoingDir;
  448. for (int i = 2; i < ac; ++i) {
  449. switch (doing) {
  450. case DoingDir:
  451. dir = cmSystemTools::CollapseFullPath(av[i]);
  452. doing = DoingNone;
  453. break;
  454. default:
  455. std::cerr << "Unknown argument " << av[i] << std::endl;
  456. dir.clear();
  457. break;
  458. }
  459. }
  460. if (dir.empty()) {
  461. std::cerr << "Usage: cmake --open <dir>\n";
  462. return 1;
  463. }
  464. cmake cm(cmake::RoleInternal);
  465. cmSystemTools::SetMessageCallback(cmakemainMessageCallback, &cm);
  466. cm.SetProgressCallback(cmakemainProgressCallback, &cm);
  467. return cm.Open(dir, false) ? 0 : 1;
  468. #endif
  469. }