cmake.cxx 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809
  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 "cmake.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmCommands.h"
  6. #include "cmDocumentation.h"
  7. #include "cmDocumentationEntry.h"
  8. #include "cmDocumentationFormatter.h"
  9. #include "cmDuration.h"
  10. #include "cmExternalMakefileProjectGenerator.h"
  11. #include "cmFileTimeComparison.h"
  12. #include "cmGeneratorTarget.h"
  13. #include "cmGlobalGenerator.h"
  14. #include "cmGlobalGeneratorFactory.h"
  15. #include "cmLinkLineComputer.h"
  16. #include "cmLocalGenerator.h"
  17. #include "cmMakefile.h"
  18. #include "cmMessenger.h"
  19. #include "cmState.h"
  20. #include "cmStateDirectory.h"
  21. #include "cmSystemTools.h"
  22. #include "cmTarget.h"
  23. #include "cmTargetLinkLibraryType.h"
  24. #include "cmUtils.hxx"
  25. #include "cmVersionConfig.h"
  26. #include "cmWorkingDirectory.h"
  27. #include "cm_sys_stat.h"
  28. #if defined(CMAKE_BUILD_WITH_CMAKE)
  29. # include "cm_jsoncpp_writer.h"
  30. # include "cmFileAPI.h"
  31. # include "cmGraphVizWriter.h"
  32. # include "cmVariableWatch.h"
  33. # include <unordered_map>
  34. #endif
  35. #if defined(CMAKE_BUILD_WITH_CMAKE)
  36. # define CMAKE_USE_ECLIPSE
  37. #endif
  38. #if defined(__MINGW32__) && !defined(CMAKE_BUILD_WITH_CMAKE)
  39. # define CMAKE_BOOT_MINGW
  40. #endif
  41. // include the generator
  42. #if defined(_WIN32) && !defined(__CYGWIN__)
  43. # if !defined(CMAKE_BOOT_MINGW)
  44. # include "cmGlobalBorlandMakefileGenerator.h"
  45. # include "cmGlobalGhsMultiGenerator.h"
  46. # include "cmGlobalJOMMakefileGenerator.h"
  47. # include "cmGlobalNMakeMakefileGenerator.h"
  48. # include "cmGlobalVisualStudio10Generator.h"
  49. # include "cmGlobalVisualStudio11Generator.h"
  50. # include "cmGlobalVisualStudio12Generator.h"
  51. # include "cmGlobalVisualStudio14Generator.h"
  52. # include "cmGlobalVisualStudio9Generator.h"
  53. # include "cmGlobalVisualStudioVersionedGenerator.h"
  54. # include "cmVSSetupHelper.h"
  55. # define CMAKE_HAVE_VS_GENERATORS
  56. # endif
  57. # include "cmGlobalMSYSMakefileGenerator.h"
  58. # include "cmGlobalMinGWMakefileGenerator.h"
  59. #else
  60. #endif
  61. #if defined(CMAKE_USE_WMAKE)
  62. # include "cmGlobalWatcomWMakeGenerator.h"
  63. #endif
  64. #include "cmGlobalUnixMakefileGenerator3.h"
  65. #if defined(CMAKE_BUILD_WITH_CMAKE)
  66. # include "cmGlobalNinjaGenerator.h"
  67. #endif
  68. #include "cmExtraCodeLiteGenerator.h"
  69. #if !defined(CMAKE_BOOT_MINGW)
  70. # include "cmExtraCodeBlocksGenerator.h"
  71. #endif
  72. #include "cmExtraKateGenerator.h"
  73. #include "cmExtraSublimeTextGenerator.h"
  74. #ifdef CMAKE_USE_ECLIPSE
  75. # include "cmExtraEclipseCDT4Generator.h"
  76. #endif
  77. #if defined(__APPLE__)
  78. # if defined(CMAKE_BUILD_WITH_CMAKE)
  79. # include "cmGlobalXCodeGenerator.h"
  80. # define CMAKE_USE_XCODE 1
  81. # endif
  82. # include <sys/resource.h>
  83. # include <sys/time.h>
  84. #endif
  85. #include "cmsys/FStream.hxx"
  86. #include "cmsys/Glob.hxx"
  87. #include "cmsys/RegularExpression.hxx"
  88. #include <algorithm>
  89. #include <cstring>
  90. #include <iostream>
  91. #include <iterator>
  92. #include <memory> // IWYU pragma: keep
  93. #include <sstream>
  94. #include <stdio.h>
  95. #include <stdlib.h>
  96. #include <utility>
  97. namespace {
  98. #if defined(CMAKE_BUILD_WITH_CMAKE)
  99. typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
  100. #endif
  101. } // namespace
  102. static bool cmakeCheckStampFile(const char* stampName, bool verbose = true);
  103. static bool cmakeCheckStampList(const char* stampList, bool verbose = true);
  104. void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  105. void* ctx, const char* /*unused*/,
  106. const cmMakefile* /*unused*/)
  107. {
  108. cmake* cm = reinterpret_cast<cmake*>(ctx);
  109. cm->MarkCliAsUsed(variable);
  110. }
  111. cmake::cmake(Role role, cmState::Mode mode)
  112. {
  113. this->Trace = false;
  114. this->TraceExpand = false;
  115. this->WarnUninitialized = false;
  116. this->WarnUnused = false;
  117. this->WarnUnusedCli = true;
  118. this->CheckSystemVars = false;
  119. this->DebugOutput = false;
  120. this->DebugTryCompile = false;
  121. this->ClearBuildSystem = false;
  122. this->FileComparison = new cmFileTimeComparison;
  123. this->State = new cmState;
  124. this->State->SetMode(mode);
  125. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  126. this->Messenger = new cmMessenger;
  127. #ifdef __APPLE__
  128. struct rlimit rlp;
  129. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  130. if (rlp.rlim_cur != rlp.rlim_max) {
  131. rlp.rlim_cur = rlp.rlim_max;
  132. setrlimit(RLIMIT_STACK, &rlp);
  133. }
  134. }
  135. #endif
  136. this->GlobalGenerator = nullptr;
  137. this->ProgressCallback = nullptr;
  138. this->ProgressCallbackClientData = nullptr;
  139. this->CurrentWorkingMode = NORMAL_MODE;
  140. #ifdef CMAKE_BUILD_WITH_CMAKE
  141. this->VariableWatch = new cmVariableWatch;
  142. #endif
  143. this->AddDefaultGenerators();
  144. this->AddDefaultExtraGenerators();
  145. if (role == RoleScript || role == RoleProject) {
  146. this->AddScriptingCommands();
  147. }
  148. if (role == RoleProject) {
  149. this->AddProjectCommands();
  150. }
  151. // Make sure we can capture the build tool output.
  152. cmSystemTools::EnableVSConsoleOutput();
  153. // Set up a list of source and header extensions
  154. // these are used to find files when the extension
  155. // is not given
  156. // The "c" extension MUST precede the "C" extension.
  157. this->SourceFileExtensions.push_back("c");
  158. this->SourceFileExtensions.push_back("C");
  159. this->SourceFileExtensions.push_back("c++");
  160. this->SourceFileExtensions.push_back("cc");
  161. this->SourceFileExtensions.push_back("cpp");
  162. this->SourceFileExtensions.push_back("cxx");
  163. this->SourceFileExtensions.push_back("cu");
  164. this->SourceFileExtensions.push_back("m");
  165. this->SourceFileExtensions.push_back("M");
  166. this->SourceFileExtensions.push_back("mm");
  167. std::copy(this->SourceFileExtensions.begin(),
  168. this->SourceFileExtensions.end(),
  169. std::inserter(this->SourceFileExtensionsSet,
  170. this->SourceFileExtensionsSet.end()));
  171. this->HeaderFileExtensions.push_back("h");
  172. this->HeaderFileExtensions.push_back("hh");
  173. this->HeaderFileExtensions.push_back("h++");
  174. this->HeaderFileExtensions.push_back("hm");
  175. this->HeaderFileExtensions.push_back("hpp");
  176. this->HeaderFileExtensions.push_back("hxx");
  177. this->HeaderFileExtensions.push_back("in");
  178. this->HeaderFileExtensions.push_back("txx");
  179. std::copy(this->HeaderFileExtensions.begin(),
  180. this->HeaderFileExtensions.end(),
  181. std::inserter(this->HeaderFileExtensionsSet,
  182. this->HeaderFileExtensionsSet.end()));
  183. }
  184. cmake::~cmake()
  185. {
  186. delete this->State;
  187. delete this->Messenger;
  188. if (this->GlobalGenerator) {
  189. delete this->GlobalGenerator;
  190. this->GlobalGenerator = nullptr;
  191. }
  192. cmDeleteAll(this->Generators);
  193. #ifdef CMAKE_BUILD_WITH_CMAKE
  194. delete this->VariableWatch;
  195. #endif
  196. delete this->FileComparison;
  197. }
  198. #if defined(CMAKE_BUILD_WITH_CMAKE)
  199. Json::Value cmake::ReportVersionJson() const
  200. {
  201. Json::Value version = Json::objectValue;
  202. version["string"] = CMake_VERSION;
  203. version["major"] = CMake_VERSION_MAJOR;
  204. version["minor"] = CMake_VERSION_MINOR;
  205. version["suffix"] = CMake_VERSION_SUFFIX;
  206. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  207. version["patch"] = CMake_VERSION_PATCH;
  208. return version;
  209. }
  210. Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
  211. {
  212. Json::Value obj = Json::objectValue;
  213. // Version information:
  214. obj["version"] = this->ReportVersionJson();
  215. // Generators:
  216. std::vector<cmake::GeneratorInfo> generatorInfoList;
  217. this->GetRegisteredGenerators(generatorInfoList);
  218. JsonValueMapType generatorMap;
  219. for (cmake::GeneratorInfo const& gi : generatorInfoList) {
  220. if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
  221. // only
  222. continue;
  223. }
  224. if (gi.extraName.empty()) {
  225. Json::Value gen = Json::objectValue;
  226. gen["name"] = gi.name;
  227. gen["toolsetSupport"] = gi.supportsToolset;
  228. gen["platformSupport"] = gi.supportsPlatform;
  229. gen["extraGenerators"] = Json::arrayValue;
  230. generatorMap[gi.name] = gen;
  231. } else {
  232. Json::Value& gen = generatorMap[gi.baseName];
  233. gen["extraGenerators"].append(gi.extraName);
  234. }
  235. }
  236. Json::Value generators = Json::arrayValue;
  237. for (auto const& i : generatorMap) {
  238. generators.append(i.second);
  239. }
  240. obj["generators"] = generators;
  241. obj["serverMode"] = haveServerMode;
  242. return obj;
  243. }
  244. #endif
  245. std::string cmake::ReportCapabilities(bool haveServerMode) const
  246. {
  247. std::string result;
  248. #if defined(CMAKE_BUILD_WITH_CMAKE)
  249. Json::FastWriter writer;
  250. result = writer.write(this->ReportCapabilitiesJson(haveServerMode));
  251. #else
  252. result = "Not supported";
  253. #endif
  254. return result;
  255. }
  256. void cmake::CleanupCommandsAndMacros()
  257. {
  258. this->CurrentSnapshot = this->State->Reset();
  259. this->State->RemoveUserDefinedCommands();
  260. this->CurrentSnapshot.SetDefaultDefinitions();
  261. }
  262. // Parse the args
  263. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  264. {
  265. bool findPackageMode = false;
  266. for (unsigned int i = 1; i < args.size(); ++i) {
  267. std::string const& arg = args[i];
  268. if (arg.find("-D", 0) == 0) {
  269. std::string entry = arg.substr(2);
  270. if (entry.empty()) {
  271. ++i;
  272. if (i < args.size()) {
  273. entry = args[i];
  274. } else {
  275. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  276. return false;
  277. }
  278. }
  279. std::string var, value;
  280. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  281. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  282. // The value is transformed if it is a filepath for example, so
  283. // we can't compare whether the value is already in the cache until
  284. // after we call AddCacheEntry.
  285. bool haveValue = false;
  286. std::string cachedValue;
  287. if (this->WarnUnusedCli) {
  288. if (const std::string* v =
  289. this->State->GetInitializedCacheValue(var)) {
  290. haveValue = true;
  291. cachedValue = *v;
  292. }
  293. }
  294. this->AddCacheEntry(var, value.c_str(),
  295. "No help, variable specified on the command line.",
  296. type);
  297. if (this->WarnUnusedCli) {
  298. if (!haveValue ||
  299. cachedValue != *this->State->GetInitializedCacheValue(var)) {
  300. this->WatchUnusedCli(var);
  301. }
  302. }
  303. } else {
  304. std::cerr << "Parse error in command line argument: " << arg << "\n"
  305. << "Should be: VAR:type=value\n";
  306. cmSystemTools::Error("No cmake script provided.");
  307. return false;
  308. }
  309. } else if (cmHasLiteralPrefix(arg, "-W")) {
  310. std::string entry = arg.substr(2);
  311. if (entry.empty()) {
  312. ++i;
  313. if (i < args.size()) {
  314. entry = args[i];
  315. } else {
  316. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  317. return false;
  318. }
  319. }
  320. std::string name;
  321. bool foundNo = false;
  322. bool foundError = false;
  323. unsigned int nameStartPosition = 0;
  324. if (entry.find("no-", nameStartPosition) == 0) {
  325. foundNo = true;
  326. nameStartPosition += 3;
  327. }
  328. if (entry.find("error=", nameStartPosition) == 0) {
  329. foundError = true;
  330. nameStartPosition += 6;
  331. }
  332. name = entry.substr(nameStartPosition);
  333. if (name.empty()) {
  334. cmSystemTools::Error("No warning name provided.");
  335. return false;
  336. }
  337. if (!foundNo && !foundError) {
  338. // -W<name>
  339. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  340. } else if (foundNo && !foundError) {
  341. // -Wno<name>
  342. this->DiagLevels[name] = DIAG_IGNORE;
  343. } else if (!foundNo && foundError) {
  344. // -Werror=<name>
  345. this->DiagLevels[name] = DIAG_ERROR;
  346. } else {
  347. // -Wno-error=<name>
  348. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  349. }
  350. } else if (arg.find("-U", 0) == 0) {
  351. std::string entryPattern = arg.substr(2);
  352. if (entryPattern.empty()) {
  353. ++i;
  354. if (i < args.size()) {
  355. entryPattern = args[i];
  356. } else {
  357. cmSystemTools::Error("-U must be followed with VAR.");
  358. return false;
  359. }
  360. }
  361. cmsys::RegularExpression regex(
  362. cmsys::Glob::PatternToRegex(entryPattern, true, true).c_str());
  363. // go through all cache entries and collect the vars which will be
  364. // removed
  365. std::vector<std::string> entriesToDelete;
  366. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  367. for (std::string const& ck : cacheKeys) {
  368. cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck);
  369. if (t != cmStateEnums::STATIC) {
  370. if (regex.find(ck)) {
  371. entriesToDelete.push_back(ck);
  372. }
  373. }
  374. }
  375. // now remove them from the cache
  376. for (std::string const& currentEntry : entriesToDelete) {
  377. this->State->RemoveCacheEntry(currentEntry);
  378. }
  379. } else if (arg.find("-C", 0) == 0) {
  380. std::string path = arg.substr(2);
  381. if (path.empty()) {
  382. ++i;
  383. if (i < args.size()) {
  384. path = args[i];
  385. } else {
  386. cmSystemTools::Error("-C must be followed by a file name.");
  387. return false;
  388. }
  389. }
  390. std::cout << "loading initial cache file " << path << "\n";
  391. this->ReadListFile(args, path.c_str());
  392. } else if (arg.find("-P", 0) == 0) {
  393. i++;
  394. if (i >= args.size()) {
  395. cmSystemTools::Error("-P must be followed by a file name.");
  396. return false;
  397. }
  398. std::string path = args[i];
  399. if (path.empty()) {
  400. cmSystemTools::Error("No cmake script provided.");
  401. return false;
  402. }
  403. // Register fake project commands that hint misuse in script mode.
  404. GetProjectCommandsInScriptMode(this->State);
  405. this->ReadListFile(args, path.c_str());
  406. } else if (arg.find("--find-package", 0) == 0) {
  407. findPackageMode = true;
  408. }
  409. }
  410. if (findPackageMode) {
  411. return this->FindPackage(args);
  412. }
  413. return true;
  414. }
  415. void cmake::ReadListFile(const std::vector<std::string>& args,
  416. const char* path)
  417. {
  418. // if a generator was not yet created, temporarily create one
  419. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  420. bool created = false;
  421. // if a generator was not specified use a generic one
  422. if (!gg) {
  423. gg = new cmGlobalGenerator(this);
  424. created = true;
  425. }
  426. // read in the list file to fill the cache
  427. if (path) {
  428. this->CurrentSnapshot = this->State->Reset();
  429. std::string homeDir = this->GetHomeDirectory();
  430. std::string homeOutputDir = this->GetHomeOutputDirectory();
  431. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  432. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  433. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  434. snapshot.GetDirectory().SetCurrentBinary(
  435. cmSystemTools::GetCurrentWorkingDirectory());
  436. snapshot.GetDirectory().SetCurrentSource(
  437. cmSystemTools::GetCurrentWorkingDirectory());
  438. snapshot.SetDefaultDefinitions();
  439. cmMakefile mf(gg, snapshot);
  440. if (this->GetWorkingMode() != NORMAL_MODE) {
  441. std::string file(cmSystemTools::CollapseFullPath(path));
  442. cmSystemTools::ConvertToUnixSlashes(file);
  443. mf.SetScriptModeFile(file);
  444. mf.SetArgcArgv(args);
  445. }
  446. if (!mf.ReadListFile(path)) {
  447. cmSystemTools::Error("Error processing file: ", path);
  448. }
  449. this->SetHomeDirectory(homeDir);
  450. this->SetHomeOutputDirectory(homeOutputDir);
  451. }
  452. // free generic one if generated
  453. if (created) {
  454. delete gg;
  455. }
  456. }
  457. bool cmake::FindPackage(const std::vector<std::string>& args)
  458. {
  459. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  460. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  461. // if a generator was not yet created, temporarily create one
  462. cmGlobalGenerator* gg = new cmGlobalGenerator(this);
  463. this->SetGlobalGenerator(gg);
  464. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  465. snapshot.GetDirectory().SetCurrentBinary(
  466. cmSystemTools::GetCurrentWorkingDirectory());
  467. snapshot.GetDirectory().SetCurrentSource(
  468. cmSystemTools::GetCurrentWorkingDirectory());
  469. // read in the list file to fill the cache
  470. snapshot.SetDefaultDefinitions();
  471. cmMakefile* mf = new cmMakefile(gg, snapshot);
  472. gg->AddMakefile(mf);
  473. mf->SetArgcArgv(args);
  474. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  475. mf->ReadListFile(systemFile.c_str());
  476. std::string language = mf->GetSafeDefinition("LANGUAGE");
  477. std::string mode = mf->GetSafeDefinition("MODE");
  478. std::string packageName = mf->GetSafeDefinition("NAME");
  479. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  480. bool quiet = mf->IsOn("PACKAGE_QUIET");
  481. if (!packageFound) {
  482. if (!quiet) {
  483. printf("%s not found.\n", packageName.c_str());
  484. }
  485. } else if (mode == "EXIST") {
  486. if (!quiet) {
  487. printf("%s found.\n", packageName.c_str());
  488. }
  489. } else if (mode == "COMPILE") {
  490. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  491. std::vector<std::string> includeDirs;
  492. cmSystemTools::ExpandListArgument(includes, includeDirs);
  493. gg->CreateGenerationObjects();
  494. cmLocalGenerator* lg = gg->LocalGenerators[0];
  495. std::string includeFlags =
  496. lg->GetIncludeFlags(includeDirs, nullptr, language);
  497. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  498. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  499. } else if (mode == "LINK") {
  500. const char* targetName = "dummy";
  501. std::vector<std::string> srcs;
  502. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  503. tgt->SetProperty("LINKER_LANGUAGE", language.c_str());
  504. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  505. std::vector<std::string> libList;
  506. cmSystemTools::ExpandListArgument(libs, libList);
  507. for (std::string const& lib : libList) {
  508. tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
  509. }
  510. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  511. buildType = cmSystemTools::UpperCase(buildType);
  512. std::string linkLibs;
  513. std::string frameworkPath;
  514. std::string linkPath;
  515. std::string flags;
  516. std::string linkFlags;
  517. gg->CreateGenerationObjects();
  518. cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
  519. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  520. cmLinkLineComputer linkLineComputer(lg,
  521. lg->GetStateSnapshot().GetDirectory());
  522. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  523. linkFlags, frameworkPath, linkPath, gtgt);
  524. linkLibs = frameworkPath + linkPath + linkLibs;
  525. printf("%s\n", linkLibs.c_str());
  526. /* if ( use_win32 )
  527. {
  528. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  529. }
  530. if ( use_macbundle)
  531. {
  532. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  533. }*/
  534. }
  535. // free generic one if generated
  536. // this->SetGlobalGenerator(0); // setting 0-pointer is not possible
  537. // delete gg; // this crashes inside the cmake instance
  538. return packageFound;
  539. }
  540. // Parse the args
  541. void cmake::SetArgs(const std::vector<std::string>& args)
  542. {
  543. bool haveToolset = false;
  544. bool havePlatform = false;
  545. for (unsigned int i = 1; i < args.size(); ++i) {
  546. std::string const& arg = args[i];
  547. if (arg.find("-H", 0) == 0 || arg.find("-S", 0) == 0) {
  548. std::string path = arg.substr(2);
  549. if (path.empty()) {
  550. ++i;
  551. if (i >= args.size()) {
  552. cmSystemTools::Error("No source directory specified for -S");
  553. return;
  554. }
  555. path = args[i];
  556. if (path[0] == '-') {
  557. cmSystemTools::Error("No source directory specified for -S");
  558. return;
  559. }
  560. }
  561. path = cmSystemTools::CollapseFullPath(path);
  562. cmSystemTools::ConvertToUnixSlashes(path);
  563. this->SetHomeDirectory(path);
  564. } else if (arg.find("-O", 0) == 0) {
  565. // There is no local generate anymore. Ignore -O option.
  566. } else if (arg.find("-B", 0) == 0) {
  567. std::string path = arg.substr(2);
  568. if (path.empty()) {
  569. ++i;
  570. if (i >= args.size()) {
  571. cmSystemTools::Error("No build directory specified for -B");
  572. return;
  573. }
  574. path = args[i];
  575. if (path[0] == '-') {
  576. cmSystemTools::Error("No build directory specified for -B");
  577. return;
  578. }
  579. }
  580. path = cmSystemTools::CollapseFullPath(path);
  581. cmSystemTools::ConvertToUnixSlashes(path);
  582. this->SetHomeOutputDirectory(path);
  583. } else if ((i < args.size() - 2) &&
  584. (arg.find("--check-build-system", 0) == 0)) {
  585. this->CheckBuildSystemArgument = args[++i];
  586. this->ClearBuildSystem = (atoi(args[++i].c_str()) > 0);
  587. } else if ((i < args.size() - 1) &&
  588. (arg.find("--check-stamp-file", 0) == 0)) {
  589. this->CheckStampFile = args[++i];
  590. } else if ((i < args.size() - 1) &&
  591. (arg.find("--check-stamp-list", 0) == 0)) {
  592. this->CheckStampList = args[++i];
  593. }
  594. #if defined(CMAKE_HAVE_VS_GENERATORS)
  595. else if ((i < args.size() - 1) &&
  596. (arg.find("--vs-solution-file", 0) == 0)) {
  597. this->VSSolutionFile = args[++i];
  598. }
  599. #endif
  600. else if (arg.find("-D", 0) == 0) {
  601. // skip for now
  602. // in case '-D var=val' is given, also skip the next
  603. // in case '-Dvar=val' is given, don't skip the next
  604. if (arg.size() == 2) {
  605. ++i;
  606. }
  607. } else if (arg.find("-U", 0) == 0) {
  608. // skip for now
  609. // in case '-U var' is given, also skip the next
  610. // in case '-Uvar' is given, don't skip the next
  611. if (arg.size() == 2) {
  612. ++i;
  613. }
  614. } else if (arg.find("-C", 0) == 0) {
  615. // skip for now
  616. // in case '-C path' is given, also skip the next
  617. // in case '-Cpath' is given, don't skip the next
  618. if (arg.size() == 2) {
  619. ++i;
  620. }
  621. } else if (arg.find("-P", 0) == 0) {
  622. // skip for now
  623. i++;
  624. } else if (arg.find("--find-package", 0) == 0) {
  625. // skip for now
  626. i++;
  627. } else if (arg.find("-W", 0) == 0) {
  628. // skip for now
  629. } else if (arg.find("--graphviz=", 0) == 0) {
  630. std::string path = arg.substr(strlen("--graphviz="));
  631. path = cmSystemTools::CollapseFullPath(path);
  632. cmSystemTools::ConvertToUnixSlashes(path);
  633. this->GraphVizFile = path;
  634. if (this->GraphVizFile.empty()) {
  635. cmSystemTools::Error("No file specified for --graphviz");
  636. }
  637. } else if (arg.find("--debug-trycompile", 0) == 0) {
  638. std::cout << "debug trycompile on\n";
  639. this->DebugTryCompileOn();
  640. } else if (arg.find("--debug-output", 0) == 0) {
  641. std::cout << "Running with debug output on.\n";
  642. this->SetDebugOutputOn(true);
  643. } else if (arg.find("--trace-expand", 0) == 0) {
  644. std::cout << "Running with expanded trace output on.\n";
  645. this->SetTrace(true);
  646. this->SetTraceExpand(true);
  647. } else if (arg.find("--trace-source=", 0) == 0) {
  648. std::string file = arg.substr(strlen("--trace-source="));
  649. cmSystemTools::ConvertToUnixSlashes(file);
  650. this->AddTraceSource(file);
  651. this->SetTrace(true);
  652. } else if (arg.find("--trace", 0) == 0) {
  653. std::cout << "Running with trace output on.\n";
  654. this->SetTrace(true);
  655. this->SetTraceExpand(false);
  656. } else if (arg.find("--warn-uninitialized", 0) == 0) {
  657. std::cout << "Warn about uninitialized values.\n";
  658. this->SetWarnUninitialized(true);
  659. } else if (arg.find("--warn-unused-vars", 0) == 0) {
  660. std::cout << "Finding unused variables.\n";
  661. this->SetWarnUnused(true);
  662. } else if (arg.find("--no-warn-unused-cli", 0) == 0) {
  663. std::cout << "Not searching for unused variables given on the "
  664. << "command line.\n";
  665. this->SetWarnUnusedCli(false);
  666. } else if (arg.find("--check-system-vars", 0) == 0) {
  667. std::cout << "Also check system files when warning about unused and "
  668. << "uninitialized variables.\n";
  669. this->SetCheckSystemVars(true);
  670. } else if (arg.find("-A", 0) == 0) {
  671. std::string value = arg.substr(2);
  672. if (value.empty()) {
  673. ++i;
  674. if (i >= args.size()) {
  675. cmSystemTools::Error("No platform specified for -A");
  676. return;
  677. }
  678. value = args[i];
  679. }
  680. if (havePlatform) {
  681. cmSystemTools::Error("Multiple -A options not allowed");
  682. return;
  683. }
  684. this->GeneratorPlatform = value;
  685. havePlatform = true;
  686. } else if (arg.find("-T", 0) == 0) {
  687. std::string value = arg.substr(2);
  688. if (value.empty()) {
  689. ++i;
  690. if (i >= args.size()) {
  691. cmSystemTools::Error("No toolset specified for -T");
  692. return;
  693. }
  694. value = args[i];
  695. }
  696. if (haveToolset) {
  697. cmSystemTools::Error("Multiple -T options not allowed");
  698. return;
  699. }
  700. this->GeneratorToolset = value;
  701. haveToolset = true;
  702. } else if (arg.find("-G", 0) == 0) {
  703. std::string value = arg.substr(2);
  704. if (value.empty()) {
  705. ++i;
  706. if (i >= args.size()) {
  707. cmSystemTools::Error("No generator specified for -G");
  708. this->PrintGeneratorList();
  709. return;
  710. }
  711. value = args[i];
  712. }
  713. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  714. if (!gen) {
  715. const char* kdevError = nullptr;
  716. if (value.find("KDevelop3", 0) != std::string::npos) {
  717. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  718. }
  719. cmSystemTools::Error("Could not create named generator ",
  720. value.c_str(), kdevError);
  721. this->PrintGeneratorList();
  722. } else {
  723. this->SetGlobalGenerator(gen);
  724. }
  725. }
  726. // no option assume it is the path to the source or an existing build
  727. else {
  728. this->SetDirectoriesFromFile(arg.c_str());
  729. }
  730. }
  731. const bool haveSourceDir = !this->GetHomeDirectory().empty();
  732. const bool haveBinaryDir = !this->GetHomeOutputDirectory().empty();
  733. if (this->CurrentWorkingMode == cmake::NORMAL_MODE && !haveSourceDir &&
  734. !haveBinaryDir) {
  735. cmSystemTools::Error("No source or binary directory provided");
  736. return;
  737. }
  738. if (!haveSourceDir) {
  739. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  740. }
  741. if (!haveBinaryDir) {
  742. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  743. }
  744. }
  745. void cmake::SetDirectoriesFromFile(const char* arg)
  746. {
  747. // Check if the argument refers to a CMakeCache.txt or
  748. // CMakeLists.txt file.
  749. std::string listPath;
  750. std::string cachePath;
  751. bool argIsFile = false;
  752. if (cmSystemTools::FileIsDirectory(arg)) {
  753. std::string path = cmSystemTools::CollapseFullPath(arg);
  754. cmSystemTools::ConvertToUnixSlashes(path);
  755. std::string cacheFile = path;
  756. cacheFile += "/CMakeCache.txt";
  757. std::string listFile = path;
  758. listFile += "/CMakeLists.txt";
  759. if (cmSystemTools::FileExists(cacheFile)) {
  760. cachePath = path;
  761. }
  762. if (cmSystemTools::FileExists(listFile)) {
  763. listPath = path;
  764. }
  765. } else if (cmSystemTools::FileExists(arg)) {
  766. argIsFile = true;
  767. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  768. std::string name = cmSystemTools::GetFilenameName(fullPath);
  769. name = cmSystemTools::LowerCase(name);
  770. if (name == "cmakecache.txt") {
  771. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  772. } else if (name == "cmakelists.txt") {
  773. listPath = cmSystemTools::GetFilenamePath(fullPath);
  774. }
  775. } else {
  776. // Specified file or directory does not exist. Try to set things
  777. // up to produce a meaningful error message.
  778. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  779. std::string name = cmSystemTools::GetFilenameName(fullPath);
  780. name = cmSystemTools::LowerCase(name);
  781. if (name == "cmakecache.txt" || name == "cmakelists.txt") {
  782. argIsFile = true;
  783. listPath = cmSystemTools::GetFilenamePath(fullPath);
  784. } else {
  785. listPath = fullPath;
  786. }
  787. }
  788. // If there is a CMakeCache.txt file, use its settings.
  789. if (!cachePath.empty()) {
  790. if (this->LoadCache(cachePath)) {
  791. const char* existingValue =
  792. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  793. if (existingValue) {
  794. this->SetHomeOutputDirectory(cachePath);
  795. this->SetHomeDirectory(existingValue);
  796. return;
  797. }
  798. }
  799. }
  800. // If there is a CMakeLists.txt file, use it as the source tree.
  801. if (!listPath.empty()) {
  802. this->SetHomeDirectory(listPath);
  803. if (argIsFile) {
  804. // Source CMakeLists.txt file given. It was probably dropped
  805. // onto the executable in a GUI. Default to an in-source build.
  806. this->SetHomeOutputDirectory(listPath);
  807. } else {
  808. // Source directory given on command line. Use current working
  809. // directory as build tree if -B hasn't been given already
  810. if (this->GetHomeOutputDirectory().empty()) {
  811. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  812. this->SetHomeOutputDirectory(cwd);
  813. }
  814. }
  815. return;
  816. }
  817. if (this->GetHomeDirectory().empty()) {
  818. // We didn't find a CMakeLists.txt and it wasn't specified
  819. // with -S. Assume it is the path to the source tree
  820. std::string full = cmSystemTools::CollapseFullPath(arg);
  821. this->SetHomeDirectory(full);
  822. }
  823. if (this->GetHomeOutputDirectory().empty()) {
  824. // We didn't find a CMakeCache.txt and it wasn't specified
  825. // with -B. Assume the current working directory as the build tree.
  826. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  827. this->SetHomeOutputDirectory(cwd);
  828. }
  829. }
  830. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  831. // cache
  832. int cmake::AddCMakePaths()
  833. {
  834. // Save the value in the cache
  835. this->AddCacheEntry("CMAKE_COMMAND",
  836. cmSystemTools::GetCMakeCommand().c_str(),
  837. "Path to CMake executable.", cmStateEnums::INTERNAL);
  838. #ifdef CMAKE_BUILD_WITH_CMAKE
  839. this->AddCacheEntry(
  840. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  841. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  842. this->AddCacheEntry(
  843. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  844. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  845. #endif
  846. if (!cmSystemTools::FileExists(
  847. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake"))) {
  848. // couldn't find modules
  849. cmSystemTools::Error(
  850. "Could not find CMAKE_ROOT !!!\n"
  851. "CMake has most likely not been installed correctly.\n"
  852. "Modules directory not found in\n",
  853. cmSystemTools::GetCMakeRoot().c_str());
  854. return 0;
  855. }
  856. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  857. "Path to CMake installation.", cmStateEnums::INTERNAL);
  858. return 1;
  859. }
  860. void cmake::AddDefaultExtraGenerators()
  861. {
  862. #if defined(CMAKE_BUILD_WITH_CMAKE)
  863. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  864. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  865. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  866. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  867. # ifdef CMAKE_USE_ECLIPSE
  868. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  869. # endif
  870. #endif
  871. }
  872. void cmake::GetRegisteredGenerators(
  873. std::vector<GeneratorInfo>& generators) const
  874. {
  875. for (cmGlobalGeneratorFactory* gen : this->Generators) {
  876. std::vector<std::string> names;
  877. gen->GetGenerators(names);
  878. for (std::string const& name : names) {
  879. GeneratorInfo info;
  880. info.supportsToolset = gen->SupportsToolset();
  881. info.supportsPlatform = gen->SupportsPlatform();
  882. info.name = name;
  883. info.baseName = name;
  884. info.isAlias = false;
  885. generators.push_back(std::move(info));
  886. }
  887. }
  888. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  889. const std::vector<std::string> genList =
  890. eg->GetSupportedGlobalGenerators();
  891. for (std::string const& gen : genList) {
  892. GeneratorInfo info;
  893. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  894. gen, eg->GetName());
  895. info.baseName = gen;
  896. info.extraName = eg->GetName();
  897. info.supportsPlatform = false;
  898. info.supportsToolset = false;
  899. info.isAlias = false;
  900. generators.push_back(std::move(info));
  901. }
  902. for (std::string const& a : eg->Aliases) {
  903. GeneratorInfo info;
  904. info.name = a;
  905. if (!genList.empty()) {
  906. info.baseName = genList.at(0);
  907. }
  908. info.extraName = eg->GetName();
  909. info.supportsPlatform = false;
  910. info.supportsToolset = false;
  911. info.isAlias = true;
  912. generators.push_back(std::move(info));
  913. }
  914. }
  915. }
  916. static std::pair<cmExternalMakefileProjectGenerator*, std::string>
  917. createExtraGenerator(
  918. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  919. const std::string& name)
  920. {
  921. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  922. const std::vector<std::string> generators =
  923. i->GetSupportedGlobalGenerators();
  924. if (i->GetName() == name) { // Match aliases
  925. return std::make_pair(i->CreateExternalMakefileProjectGenerator(),
  926. generators.at(0));
  927. }
  928. for (std::string const& g : generators) {
  929. const std::string fullName =
  930. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  931. g, i->GetName());
  932. if (fullName == name) {
  933. return std::make_pair(i->CreateExternalMakefileProjectGenerator(), g);
  934. }
  935. }
  936. }
  937. return std::make_pair(
  938. static_cast<cmExternalMakefileProjectGenerator*>(nullptr), name);
  939. }
  940. cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
  941. {
  942. std::pair<cmExternalMakefileProjectGenerator*, std::string> extra =
  943. createExtraGenerator(this->ExtraGenerators, gname);
  944. cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
  945. const std::string name = extra.second;
  946. cmGlobalGenerator* generator = nullptr;
  947. for (cmGlobalGeneratorFactory* g : this->Generators) {
  948. generator = g->CreateGlobalGenerator(name, this);
  949. if (generator) {
  950. break;
  951. }
  952. }
  953. if (generator) {
  954. generator->SetExternalMakefileProjectGenerator(extraGenerator);
  955. } else {
  956. delete extraGenerator;
  957. }
  958. return generator;
  959. }
  960. void cmake::SetHomeDirectory(const std::string& dir)
  961. {
  962. this->State->SetSourceDirectory(dir);
  963. if (this->CurrentSnapshot.IsValid()) {
  964. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  965. }
  966. }
  967. std::string const& cmake::GetHomeDirectory() const
  968. {
  969. return this->State->GetSourceDirectory();
  970. }
  971. void cmake::SetHomeOutputDirectory(const std::string& dir)
  972. {
  973. this->State->SetBinaryDirectory(dir);
  974. if (this->CurrentSnapshot.IsValid()) {
  975. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  976. }
  977. }
  978. std::string const& cmake::GetHomeOutputDirectory() const
  979. {
  980. return this->State->GetBinaryDirectory();
  981. }
  982. std::string cmake::FindCacheFile(const std::string& binaryDir)
  983. {
  984. std::string cachePath = binaryDir;
  985. cmSystemTools::ConvertToUnixSlashes(cachePath);
  986. std::string cacheFile = cachePath;
  987. cacheFile += "/CMakeCache.txt";
  988. if (!cmSystemTools::FileExists(cacheFile)) {
  989. // search in parent directories for cache
  990. std::string cmakeFiles = cachePath;
  991. cmakeFiles += "/CMakeFiles";
  992. if (cmSystemTools::FileExists(cmakeFiles)) {
  993. std::string cachePathFound =
  994. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  995. cachePath.c_str(), "/");
  996. if (!cachePathFound.empty()) {
  997. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  998. }
  999. }
  1000. }
  1001. return cachePath;
  1002. }
  1003. void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
  1004. {
  1005. if (!gg) {
  1006. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  1007. return;
  1008. }
  1009. // delete the old generator
  1010. if (this->GlobalGenerator) {
  1011. delete this->GlobalGenerator;
  1012. // restore the original environment variables CXX and CC
  1013. // Restore CC
  1014. std::string env = "CC=";
  1015. if (!this->CCEnvironment.empty()) {
  1016. env += this->CCEnvironment;
  1017. }
  1018. cmSystemTools::PutEnv(env);
  1019. env = "CXX=";
  1020. if (!this->CXXEnvironment.empty()) {
  1021. env += this->CXXEnvironment;
  1022. }
  1023. cmSystemTools::PutEnv(env);
  1024. }
  1025. // set the new
  1026. this->GlobalGenerator = gg;
  1027. // set the global flag for unix style paths on cmSystemTools as soon as
  1028. // the generator is set. This allows gmake to be used on windows.
  1029. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  1030. // Save the environment variables CXX and CC
  1031. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  1032. this->CXXEnvironment.clear();
  1033. }
  1034. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  1035. this->CCEnvironment.clear();
  1036. }
  1037. }
  1038. int cmake::DoPreConfigureChecks()
  1039. {
  1040. // Make sure the Source directory contains a CMakeLists.txt file.
  1041. std::string srcList = this->GetHomeDirectory();
  1042. srcList += "/CMakeLists.txt";
  1043. if (!cmSystemTools::FileExists(srcList)) {
  1044. std::ostringstream err;
  1045. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  1046. err << "The source directory \"" << this->GetHomeDirectory()
  1047. << "\" does not appear to contain CMakeLists.txt.\n";
  1048. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  1049. err << "The source directory \"" << this->GetHomeDirectory()
  1050. << "\" is a file, not a directory.\n";
  1051. } else {
  1052. err << "The source directory \"" << this->GetHomeDirectory()
  1053. << "\" does not exist.\n";
  1054. }
  1055. err << "Specify --help for usage, or press the help button on the CMake "
  1056. "GUI.";
  1057. cmSystemTools::Error(err.str().c_str());
  1058. return -2;
  1059. }
  1060. // do a sanity check on some values
  1061. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1062. std::string cacheStart =
  1063. *this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  1064. cacheStart += "/CMakeLists.txt";
  1065. std::string currentStart = this->GetHomeDirectory();
  1066. currentStart += "/CMakeLists.txt";
  1067. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1068. std::string message = "The source \"";
  1069. message += currentStart;
  1070. message += "\" does not match the source \"";
  1071. message += cacheStart;
  1072. message += "\" used to generate cache. ";
  1073. message += "Re-run cmake with a different source directory.";
  1074. cmSystemTools::Error(message.c_str());
  1075. return -2;
  1076. }
  1077. } else {
  1078. return 0;
  1079. }
  1080. return 1;
  1081. }
  1082. struct SaveCacheEntry
  1083. {
  1084. std::string key;
  1085. std::string value;
  1086. std::string help;
  1087. cmStateEnums::CacheEntryType type;
  1088. };
  1089. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1090. {
  1091. std::vector<std::string> argsSplit;
  1092. cmSystemTools::ExpandListArgument(std::string(var), argsSplit, true);
  1093. // erase the property to avoid infinite recursion
  1094. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1095. if (this->State->GetIsInTryCompile()) {
  1096. return 0;
  1097. }
  1098. std::vector<SaveCacheEntry> saved;
  1099. std::ostringstream warning;
  1100. /* clang-format off */
  1101. warning
  1102. << "You have changed variables that require your cache to be deleted.\n"
  1103. << "Configure will be re-run and you may have to reset some variables.\n"
  1104. << "The following variables have changed:\n";
  1105. /* clang-format on */
  1106. for (std::vector<std::string>::iterator i = argsSplit.begin();
  1107. i != argsSplit.end(); ++i) {
  1108. SaveCacheEntry save;
  1109. save.key = *i;
  1110. warning << *i << "= ";
  1111. i++;
  1112. save.value = *i;
  1113. warning << *i << "\n";
  1114. const char* existingValue = this->State->GetCacheEntryValue(save.key);
  1115. if (existingValue) {
  1116. save.type = this->State->GetCacheEntryType(save.key);
  1117. if (const char* help =
  1118. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1119. save.help = help;
  1120. }
  1121. }
  1122. saved.push_back(std::move(save));
  1123. }
  1124. // remove the cache
  1125. this->DeleteCache(this->GetHomeOutputDirectory());
  1126. // load the empty cache
  1127. this->LoadCache();
  1128. // restore the changed compilers
  1129. for (SaveCacheEntry const& i : saved) {
  1130. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1131. }
  1132. cmSystemTools::Message(warning.str().c_str());
  1133. // avoid reconfigure if there were errors
  1134. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1135. // re-run configure
  1136. return this->Configure();
  1137. }
  1138. return 0;
  1139. }
  1140. int cmake::Configure()
  1141. {
  1142. DiagLevel diagLevel;
  1143. if (this->DiagLevels.count("deprecated") == 1) {
  1144. diagLevel = this->DiagLevels["deprecated"];
  1145. if (diagLevel == DIAG_IGNORE) {
  1146. this->SetSuppressDeprecatedWarnings(true);
  1147. this->SetDeprecatedWarningsAsErrors(false);
  1148. } else if (diagLevel == DIAG_WARN) {
  1149. this->SetSuppressDeprecatedWarnings(false);
  1150. this->SetDeprecatedWarningsAsErrors(false);
  1151. } else if (diagLevel == DIAG_ERROR) {
  1152. this->SetSuppressDeprecatedWarnings(false);
  1153. this->SetDeprecatedWarningsAsErrors(true);
  1154. }
  1155. }
  1156. if (this->DiagLevels.count("dev") == 1) {
  1157. bool setDeprecatedVariables = false;
  1158. const char* cachedWarnDeprecated =
  1159. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1160. const char* cachedErrorDeprecated =
  1161. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1162. // don't overwrite deprecated warning setting from a previous invocation
  1163. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1164. setDeprecatedVariables = true;
  1165. }
  1166. diagLevel = this->DiagLevels["dev"];
  1167. if (diagLevel == DIAG_IGNORE) {
  1168. this->SetSuppressDevWarnings(true);
  1169. this->SetDevWarningsAsErrors(false);
  1170. if (setDeprecatedVariables) {
  1171. this->SetSuppressDeprecatedWarnings(true);
  1172. this->SetDeprecatedWarningsAsErrors(false);
  1173. }
  1174. } else if (diagLevel == DIAG_WARN) {
  1175. this->SetSuppressDevWarnings(false);
  1176. this->SetDevWarningsAsErrors(false);
  1177. if (setDeprecatedVariables) {
  1178. this->SetSuppressDeprecatedWarnings(false);
  1179. this->SetDeprecatedWarningsAsErrors(false);
  1180. }
  1181. } else if (diagLevel == DIAG_ERROR) {
  1182. this->SetSuppressDevWarnings(false);
  1183. this->SetDevWarningsAsErrors(true);
  1184. if (setDeprecatedVariables) {
  1185. this->SetSuppressDeprecatedWarnings(false);
  1186. this->SetDeprecatedWarningsAsErrors(true);
  1187. }
  1188. }
  1189. }
  1190. // Cache variables may have already been set by a previous invocation,
  1191. // so we cannot rely on command line options alone. Always ensure our
  1192. // messenger is in sync with the cache.
  1193. const char* value = this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1194. this->Messenger->SetSuppressDeprecatedWarnings(value &&
  1195. cmSystemTools::IsOff(value));
  1196. value = this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1197. this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value));
  1198. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_WARNINGS");
  1199. this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value));
  1200. value = this->State->GetCacheEntryValue("CMAKE_SUPPRESS_DEVELOPER_ERRORS");
  1201. this->Messenger->SetDevWarningsAsErrors(value &&
  1202. cmSystemTools::IsOff(value));
  1203. int ret = this->ActualConfigure();
  1204. const char* delCacheVars =
  1205. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1206. if (delCacheVars && delCacheVars[0] != 0) {
  1207. return this->HandleDeleteCacheVariables(delCacheVars);
  1208. }
  1209. return ret;
  1210. }
  1211. int cmake::ActualConfigure()
  1212. {
  1213. // Construct right now our path conversion table before it's too late:
  1214. this->UpdateConversionPathTable();
  1215. this->CleanupCommandsAndMacros();
  1216. int res = this->DoPreConfigureChecks();
  1217. if (res < 0) {
  1218. return -2;
  1219. }
  1220. if (!res) {
  1221. this->AddCacheEntry(
  1222. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory().c_str(),
  1223. "Source directory with the top level CMakeLists.txt file for this "
  1224. "project",
  1225. cmStateEnums::INTERNAL);
  1226. }
  1227. // no generator specified on the command line
  1228. if (!this->GlobalGenerator) {
  1229. const std::string* genName =
  1230. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1231. const std::string* extraGenName =
  1232. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1233. if (genName) {
  1234. std::string fullName =
  1235. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1236. *genName, extraGenName ? *extraGenName : "");
  1237. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1238. }
  1239. if (this->GlobalGenerator) {
  1240. // set the global flag for unix style paths on cmSystemTools as
  1241. // soon as the generator is set. This allows gmake to be used
  1242. // on windows.
  1243. cmSystemTools::SetForceUnixPaths(
  1244. this->GlobalGenerator->GetForceUnixPaths());
  1245. } else {
  1246. this->CreateDefaultGlobalGenerator();
  1247. }
  1248. if (!this->GlobalGenerator) {
  1249. cmSystemTools::Error("Could not create generator");
  1250. return -1;
  1251. }
  1252. }
  1253. const std::string* genName =
  1254. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1255. if (genName) {
  1256. if (!this->GlobalGenerator->MatchesGeneratorName(*genName)) {
  1257. std::string message = "Error: generator : ";
  1258. message += this->GlobalGenerator->GetName();
  1259. message += "\nDoes not match the generator used previously: ";
  1260. message += *genName;
  1261. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1262. "directory or choose a different binary directory.";
  1263. cmSystemTools::Error(message.c_str());
  1264. return -2;
  1265. }
  1266. }
  1267. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1268. this->AddCacheEntry("CMAKE_GENERATOR",
  1269. this->GlobalGenerator->GetName().c_str(),
  1270. "Name of generator.", cmStateEnums::INTERNAL);
  1271. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1272. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1273. "Name of external makefile project generator.",
  1274. cmStateEnums::INTERNAL);
  1275. }
  1276. if (const std::string* instance =
  1277. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1278. if (!this->GeneratorInstance.empty() &&
  1279. this->GeneratorInstance != *instance) {
  1280. std::string message = "Error: generator instance: ";
  1281. message += this->GeneratorInstance;
  1282. message += "\nDoes not match the instance used previously: ";
  1283. message += *instance;
  1284. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1285. "directory or choose a different binary directory.";
  1286. cmSystemTools::Error(message.c_str());
  1287. return -2;
  1288. }
  1289. } else {
  1290. this->AddCacheEntry(
  1291. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1292. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1293. }
  1294. if (const std::string* platformName =
  1295. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1296. if (!this->GeneratorPlatform.empty() &&
  1297. this->GeneratorPlatform != *platformName) {
  1298. std::string message = "Error: generator platform: ";
  1299. message += this->GeneratorPlatform;
  1300. message += "\nDoes not match the platform used previously: ";
  1301. message += *platformName;
  1302. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1303. "directory or choose a different binary directory.";
  1304. cmSystemTools::Error(message.c_str());
  1305. return -2;
  1306. }
  1307. } else {
  1308. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1309. this->GeneratorPlatform.c_str(),
  1310. "Name of generator platform.", cmStateEnums::INTERNAL);
  1311. }
  1312. if (const std::string* tsName =
  1313. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1314. if (!this->GeneratorToolset.empty() && this->GeneratorToolset != *tsName) {
  1315. std::string message = "Error: generator toolset: ";
  1316. message += this->GeneratorToolset;
  1317. message += "\nDoes not match the toolset used previously: ";
  1318. message += *tsName;
  1319. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1320. "directory or choose a different binary directory.";
  1321. cmSystemTools::Error(message.c_str());
  1322. return -2;
  1323. }
  1324. } else {
  1325. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1326. this->GeneratorToolset.c_str(),
  1327. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1328. }
  1329. // reset any system configuration information, except for when we are
  1330. // InTryCompile. With TryCompile the system info is taken from the parent's
  1331. // info to save time
  1332. if (!this->State->GetIsInTryCompile()) {
  1333. this->GlobalGenerator->ClearEnabledLanguages();
  1334. this->TruncateOutputLog("CMakeOutput.log");
  1335. this->TruncateOutputLog("CMakeError.log");
  1336. }
  1337. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1338. this->FileAPI = cm::make_unique<cmFileAPI>(this);
  1339. this->FileAPI->ReadQueries();
  1340. #endif
  1341. // actually do the configure
  1342. this->GlobalGenerator->Configure();
  1343. // Before saving the cache
  1344. // if the project did not define one of the entries below, add them now
  1345. // so users can edit the values in the cache:
  1346. // We used to always present LIBRARY_OUTPUT_PATH and
  1347. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1348. // should no longer be used. Therefore we present them only if the
  1349. // project requires compatibility with CMake 2.4. We detect this
  1350. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1351. // variable created when CMP0001 is not set to NEW.
  1352. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1353. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1354. this->AddCacheEntry(
  1355. "LIBRARY_OUTPUT_PATH", "",
  1356. "Single output directory for building all libraries.",
  1357. cmStateEnums::PATH);
  1358. }
  1359. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1360. this->AddCacheEntry(
  1361. "EXECUTABLE_OUTPUT_PATH", "",
  1362. "Single output directory for building all executables.",
  1363. cmStateEnums::PATH);
  1364. }
  1365. }
  1366. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1367. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1368. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1369. cmSystemTools::Error(
  1370. "CTEST_USE_LAUNCHERS is enabled, but the "
  1371. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1372. "Did you forget to include(CTest) in the toplevel "
  1373. "CMakeLists.txt ?");
  1374. }
  1375. this->State->SaveVerificationScript(this->GetHomeOutputDirectory());
  1376. this->SaveCache(this->GetHomeOutputDirectory());
  1377. if (cmSystemTools::GetErrorOccuredFlag()) {
  1378. return -1;
  1379. }
  1380. return 0;
  1381. }
  1382. void cmake::CreateDefaultGlobalGenerator()
  1383. {
  1384. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1385. std::string found;
  1386. // Try to find the newest VS installed on the computer and
  1387. // use that as a default if -G is not specified
  1388. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1389. static const char* const vsVariants[] = {
  1390. /* clang-format needs this comment to break after the opening brace */
  1391. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1392. };
  1393. struct VSVersionedGenerator
  1394. {
  1395. const char* MSVersion;
  1396. const char* GeneratorName;
  1397. };
  1398. static VSVersionedGenerator const vsGenerators[] = {
  1399. { "14.0", "Visual Studio 14 2015" }, //
  1400. { "12.0", "Visual Studio 12 2013" }, //
  1401. { "11.0", "Visual Studio 11 2012" }, //
  1402. { "10.0", "Visual Studio 10 2010" }, //
  1403. { "9.0", "Visual Studio 9 2008" }
  1404. };
  1405. static const char* const vsEntries[] = {
  1406. "\\Setup\\VC;ProductDir", //
  1407. ";InstallDir" //
  1408. };
  1409. if (cmVSSetupAPIHelper(16).IsVSInstalled()) {
  1410. found = "Visual Studio 16 2019";
  1411. } else if (cmVSSetupAPIHelper(15).IsVSInstalled()) {
  1412. found = "Visual Studio 15 2017";
  1413. } else {
  1414. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1415. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1416. for (const char* const* v = cm::cbegin(vsVariants);
  1417. found.empty() && v != cm::cend(vsVariants); ++v) {
  1418. for (const char* const* e = cm::cbegin(vsEntries);
  1419. found.empty() && e != cm::cend(vsEntries); ++e) {
  1420. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1421. std::string dir;
  1422. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1423. cmSystemTools::KeyWOW64_32) &&
  1424. cmSystemTools::PathExists(dir)) {
  1425. found = g->GeneratorName;
  1426. }
  1427. }
  1428. }
  1429. }
  1430. }
  1431. cmGlobalGenerator* gen = this->CreateGlobalGenerator(found);
  1432. if (!gen) {
  1433. gen = new cmGlobalNMakeMakefileGenerator(this);
  1434. }
  1435. this->SetGlobalGenerator(gen);
  1436. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1437. #else
  1438. this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
  1439. #endif
  1440. }
  1441. void cmake::PreLoadCMakeFiles()
  1442. {
  1443. std::vector<std::string> args;
  1444. std::string pre_load = this->GetHomeDirectory();
  1445. if (!pre_load.empty()) {
  1446. pre_load += "/PreLoad.cmake";
  1447. if (cmSystemTools::FileExists(pre_load)) {
  1448. this->ReadListFile(args, pre_load.c_str());
  1449. }
  1450. }
  1451. pre_load = this->GetHomeOutputDirectory();
  1452. if (!pre_load.empty()) {
  1453. pre_load += "/PreLoad.cmake";
  1454. if (cmSystemTools::FileExists(pre_load)) {
  1455. this->ReadListFile(args, pre_load.c_str());
  1456. }
  1457. }
  1458. }
  1459. // handle a command line invocation
  1460. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1461. {
  1462. // Process the arguments
  1463. this->SetArgs(args);
  1464. if (cmSystemTools::GetErrorOccuredFlag()) {
  1465. return -1;
  1466. }
  1467. // If we are given a stamp list file check if it is really out of date.
  1468. if (!this->CheckStampList.empty() &&
  1469. cmakeCheckStampList(this->CheckStampList.c_str())) {
  1470. return 0;
  1471. }
  1472. // If we are given a stamp file check if it is really out of date.
  1473. if (!this->CheckStampFile.empty() &&
  1474. cmakeCheckStampFile(this->CheckStampFile.c_str())) {
  1475. return 0;
  1476. }
  1477. if (this->GetWorkingMode() == NORMAL_MODE) {
  1478. // load the cache
  1479. if (this->LoadCache() < 0) {
  1480. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1481. return -1;
  1482. }
  1483. } else {
  1484. this->AddCMakePaths();
  1485. }
  1486. // Add any cache args
  1487. if (!this->SetCacheArgs(args)) {
  1488. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1489. return -1;
  1490. }
  1491. // In script mode we terminate after running the script.
  1492. if (this->GetWorkingMode() != NORMAL_MODE) {
  1493. if (cmSystemTools::GetErrorOccuredFlag()) {
  1494. return -1;
  1495. }
  1496. return 0;
  1497. }
  1498. // If MAKEFLAGS are given in the environment, remove the environment
  1499. // variable. This will prevent try-compile from succeeding when it
  1500. // should fail (if "-i" is an option). We cannot simply test
  1501. // whether "-i" is given and remove it because some make programs
  1502. // encode the MAKEFLAGS variable in a strange way.
  1503. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1504. cmSystemTools::PutEnv("MAKEFLAGS=");
  1505. }
  1506. this->PreLoadCMakeFiles();
  1507. if (noconfigure) {
  1508. return 0;
  1509. }
  1510. // now run the global generate
  1511. // Check the state of the build system to see if we need to regenerate.
  1512. if (!this->CheckBuildSystem()) {
  1513. return 0;
  1514. }
  1515. int ret = this->Configure();
  1516. if (ret) {
  1517. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1518. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1519. // CMake is running to regenerate a Visual Studio build tree
  1520. // during a build from the VS IDE. The build files cannot be
  1521. // regenerated, so we should stop the build.
  1522. cmSystemTools::Message("CMake Configure step failed. "
  1523. "Build files cannot be regenerated correctly. "
  1524. "Attempting to stop IDE build.");
  1525. cmGlobalVisualStudioGenerator* gg =
  1526. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1527. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1528. this->VSSolutionFile.c_str());
  1529. }
  1530. #endif
  1531. return ret;
  1532. }
  1533. ret = this->Generate();
  1534. std::string message = "Build files have been written to: ";
  1535. message += this->GetHomeOutputDirectory();
  1536. this->UpdateProgress(message.c_str(), -1);
  1537. return ret;
  1538. }
  1539. int cmake::Generate()
  1540. {
  1541. if (!this->GlobalGenerator) {
  1542. return -1;
  1543. }
  1544. if (!this->GlobalGenerator->Compute()) {
  1545. return -1;
  1546. }
  1547. this->GlobalGenerator->Generate();
  1548. if (!this->GraphVizFile.empty()) {
  1549. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1550. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1551. }
  1552. if (this->WarnUnusedCli) {
  1553. this->RunCheckForUnusedVariables();
  1554. }
  1555. if (cmSystemTools::GetErrorOccuredFlag()) {
  1556. return -1;
  1557. }
  1558. // Save the cache again after a successful Generate so that any internal
  1559. // variables created during Generate are saved. (Specifically target GUIDs
  1560. // for the Visual Studio and Xcode generators.)
  1561. this->SaveCache(this->GetHomeOutputDirectory());
  1562. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1563. this->FileAPI->WriteReplies();
  1564. #endif
  1565. return 0;
  1566. }
  1567. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1568. const char* helpString, int type)
  1569. {
  1570. this->State->AddCacheEntry(key, value, helpString,
  1571. cmStateEnums::CacheEntryType(type));
  1572. this->UnwatchUnusedCli(key);
  1573. if (key == "CMAKE_WARN_DEPRECATED") {
  1574. this->Messenger->SetSuppressDeprecatedWarnings(
  1575. value && cmSystemTools::IsOff(value));
  1576. } else if (key == "CMAKE_ERROR_DEPRECATED") {
  1577. this->Messenger->SetDeprecatedWarningsAsErrors(cmSystemTools::IsOn(value));
  1578. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_WARNINGS") {
  1579. this->Messenger->SetSuppressDevWarnings(cmSystemTools::IsOn(value));
  1580. } else if (key == "CMAKE_SUPPRESS_DEVELOPER_ERRORS") {
  1581. this->Messenger->SetDevWarningsAsErrors(value &&
  1582. cmSystemTools::IsOff(value));
  1583. }
  1584. }
  1585. bool cmake::DoWriteGlobVerifyTarget() const
  1586. {
  1587. return this->State->DoWriteGlobVerifyTarget();
  1588. }
  1589. std::string const& cmake::GetGlobVerifyScript() const
  1590. {
  1591. return this->State->GetGlobVerifyScript();
  1592. }
  1593. std::string const& cmake::GetGlobVerifyStamp() const
  1594. {
  1595. return this->State->GetGlobVerifyStamp();
  1596. }
  1597. void cmake::AddGlobCacheEntry(bool recurse, bool listDirectories,
  1598. bool followSymlinks, const std::string& relative,
  1599. const std::string& expression,
  1600. const std::vector<std::string>& files,
  1601. const std::string& variable,
  1602. cmListFileBacktrace const& backtrace)
  1603. {
  1604. this->State->AddGlobCacheEntry(recurse, listDirectories, followSymlinks,
  1605. relative, expression, files, variable,
  1606. backtrace);
  1607. }
  1608. std::string cmake::StripExtension(const std::string& file) const
  1609. {
  1610. auto dotpos = file.rfind('.');
  1611. if (dotpos != std::string::npos) {
  1612. auto ext = file.substr(dotpos + 1);
  1613. #if defined(_WIN32) || defined(__APPLE__)
  1614. ext = cmSystemTools::LowerCase(ext);
  1615. #endif
  1616. if (this->IsSourceExtension(ext) || this->IsHeaderExtension(ext)) {
  1617. return file.substr(0, dotpos);
  1618. }
  1619. }
  1620. return file;
  1621. }
  1622. const char* cmake::GetCacheDefinition(const std::string& name) const
  1623. {
  1624. const std::string* p = this->State->GetInitializedCacheValue(name);
  1625. return p ? p->c_str() : nullptr;
  1626. }
  1627. void cmake::AddScriptingCommands()
  1628. {
  1629. GetScriptingCommands(this->State);
  1630. }
  1631. void cmake::AddProjectCommands()
  1632. {
  1633. GetProjectCommands(this->State);
  1634. }
  1635. void cmake::AddDefaultGenerators()
  1636. {
  1637. #if defined(_WIN32) && !defined(__CYGWIN__)
  1638. # if !defined(CMAKE_BOOT_MINGW)
  1639. this->Generators.push_back(
  1640. cmGlobalVisualStudioVersionedGenerator::NewFactory16());
  1641. this->Generators.push_back(
  1642. cmGlobalVisualStudioVersionedGenerator::NewFactory15());
  1643. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1644. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1645. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1646. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1647. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1648. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1649. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1650. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1651. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1652. # endif
  1653. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1654. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1655. #endif
  1656. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1657. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1658. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1659. #endif
  1660. #if defined(CMAKE_USE_WMAKE)
  1661. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1662. #endif
  1663. #ifdef CMAKE_USE_XCODE
  1664. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1665. #endif
  1666. }
  1667. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1668. std::string& value,
  1669. cmStateEnums::CacheEntryType& type)
  1670. {
  1671. return cmState::ParseCacheEntry(entry, var, value, type);
  1672. }
  1673. int cmake::LoadCache()
  1674. {
  1675. // could we not read the cache
  1676. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1677. // if it does exist, but isn't readable then warn the user
  1678. std::string cacheFile = this->GetHomeOutputDirectory();
  1679. cacheFile += "/CMakeCache.txt";
  1680. if (cmSystemTools::FileExists(cacheFile)) {
  1681. cmSystemTools::Error(
  1682. "There is a CMakeCache.txt file for the current binary tree but "
  1683. "cmake does not have permission to read it. Please check the "
  1684. "permissions of the directory you are trying to run CMake on.");
  1685. return -1;
  1686. }
  1687. }
  1688. // setup CMAKE_ROOT and CMAKE_COMMAND
  1689. if (!this->AddCMakePaths()) {
  1690. return -3;
  1691. }
  1692. return 0;
  1693. }
  1694. bool cmake::LoadCache(const std::string& path)
  1695. {
  1696. std::set<std::string> emptySet;
  1697. return this->LoadCache(path, true, emptySet, emptySet);
  1698. }
  1699. bool cmake::LoadCache(const std::string& path, bool internal,
  1700. std::set<std::string>& excludes,
  1701. std::set<std::string>& includes)
  1702. {
  1703. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1704. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1705. "CMAKE_CACHE_MINOR_VERSION" };
  1706. for (const char* const* nameIt = cm::cbegin(entries);
  1707. nameIt != cm::cend(entries); ++nameIt) {
  1708. this->UnwatchUnusedCli(*nameIt);
  1709. }
  1710. return result;
  1711. }
  1712. bool cmake::SaveCache(const std::string& path)
  1713. {
  1714. bool result = this->State->SaveCache(path, this->GetMessenger());
  1715. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1716. "CMAKE_CACHE_MINOR_VERSION",
  1717. "CMAKE_CACHE_PATCH_VERSION",
  1718. "CMAKE_CACHEFILE_DIR" };
  1719. for (const char* const* nameIt = cm::cbegin(entries);
  1720. nameIt != cm::cend(entries); ++nameIt) {
  1721. this->UnwatchUnusedCli(*nameIt);
  1722. }
  1723. return result;
  1724. }
  1725. bool cmake::DeleteCache(const std::string& path)
  1726. {
  1727. return this->State->DeleteCache(path);
  1728. }
  1729. void cmake::SetProgressCallback(ProgressCallbackType f, void* cd)
  1730. {
  1731. this->ProgressCallback = f;
  1732. this->ProgressCallbackClientData = cd;
  1733. }
  1734. void cmake::UpdateProgress(const char* msg, float prog)
  1735. {
  1736. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1737. (*this->ProgressCallback)(msg, prog, this->ProgressCallbackClientData);
  1738. return;
  1739. }
  1740. }
  1741. bool cmake::GetIsInTryCompile() const
  1742. {
  1743. return this->State->GetIsInTryCompile();
  1744. }
  1745. void cmake::SetIsInTryCompile(bool b)
  1746. {
  1747. this->State->SetIsInTryCompile(b);
  1748. }
  1749. void cmake::AppendGlobalGeneratorsDocumentation(
  1750. std::vector<cmDocumentationEntry>& v)
  1751. {
  1752. for (cmGlobalGeneratorFactory* g : this->Generators) {
  1753. cmDocumentationEntry e;
  1754. g->GetDocumentation(e);
  1755. v.push_back(std::move(e));
  1756. }
  1757. }
  1758. void cmake::AppendExtraGeneratorsDocumentation(
  1759. std::vector<cmDocumentationEntry>& v)
  1760. {
  1761. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1762. const std::string doc = eg->GetDocumentation();
  1763. const std::string name = eg->GetName();
  1764. // Aliases:
  1765. for (std::string const& a : eg->Aliases) {
  1766. cmDocumentationEntry e;
  1767. e.Name = a;
  1768. e.Brief = doc;
  1769. v.push_back(std::move(e));
  1770. }
  1771. // Full names:
  1772. const std::vector<std::string> generators =
  1773. eg->GetSupportedGlobalGenerators();
  1774. for (std::string const& g : generators) {
  1775. cmDocumentationEntry e;
  1776. e.Name =
  1777. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  1778. e.Brief = doc;
  1779. v.push_back(std::move(e));
  1780. }
  1781. }
  1782. }
  1783. std::vector<cmDocumentationEntry> cmake::GetGeneratorsDocumentation()
  1784. {
  1785. std::vector<cmDocumentationEntry> v;
  1786. this->AppendGlobalGeneratorsDocumentation(v);
  1787. this->AppendExtraGeneratorsDocumentation(v);
  1788. return v;
  1789. }
  1790. void cmake::PrintGeneratorList()
  1791. {
  1792. #ifdef CMAKE_BUILD_WITH_CMAKE
  1793. cmDocumentation doc;
  1794. auto generators = this->GetGeneratorsDocumentation();
  1795. doc.AppendSection("Generators", generators);
  1796. std::cerr << "\n";
  1797. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1798. #endif
  1799. }
  1800. void cmake::UpdateConversionPathTable()
  1801. {
  1802. // Update the path conversion table with any specified file:
  1803. const std::string* tablepath =
  1804. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1805. if (tablepath) {
  1806. cmsys::ifstream table(tablepath->c_str());
  1807. if (!table) {
  1808. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ",
  1809. tablepath->c_str(), ". CMake can not open file.");
  1810. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1811. } else {
  1812. std::string a, b;
  1813. while (!table.eof()) {
  1814. // two entries per line
  1815. table >> a;
  1816. table >> b;
  1817. cmSystemTools::AddTranslationPath(a, b);
  1818. }
  1819. }
  1820. }
  1821. }
  1822. int cmake::CheckBuildSystem()
  1823. {
  1824. // We do not need to rerun CMake. Check dependency integrity.
  1825. const bool verbose = isCMakeVerbose();
  1826. // This method will check the integrity of the build system if the
  1827. // option was given on the command line. It reads the given file to
  1828. // determine whether CMake should rerun.
  1829. // If no file is provided for the check, we have to rerun.
  1830. if (this->CheckBuildSystemArgument.empty()) {
  1831. if (verbose) {
  1832. std::ostringstream msg;
  1833. msg << "Re-run cmake no build system arguments\n";
  1834. cmSystemTools::Stdout(msg.str().c_str());
  1835. }
  1836. return 1;
  1837. }
  1838. // If the file provided does not exist, we have to rerun.
  1839. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument)) {
  1840. if (verbose) {
  1841. std::ostringstream msg;
  1842. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1843. << "\n";
  1844. cmSystemTools::Stdout(msg.str().c_str());
  1845. }
  1846. return 1;
  1847. }
  1848. // Read the rerun check file and use it to decide whether to do the
  1849. // global generate.
  1850. // Actually, all we need is the `set` command.
  1851. cmake cm(RoleScript, cmState::Unknown);
  1852. cm.SetHomeDirectory("");
  1853. cm.SetHomeOutputDirectory("");
  1854. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1855. cmGlobalGenerator gg(&cm);
  1856. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  1857. if (!mf.ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
  1858. cmSystemTools::GetErrorOccuredFlag()) {
  1859. if (verbose) {
  1860. std::ostringstream msg;
  1861. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1862. << "\n";
  1863. cmSystemTools::Stdout(msg.str().c_str());
  1864. }
  1865. // There was an error reading the file. Just rerun.
  1866. return 1;
  1867. }
  1868. if (this->ClearBuildSystem) {
  1869. // Get the generator used for this build system.
  1870. const char* genName = mf.GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1871. if (!genName || genName[0] == '\0') {
  1872. genName = "Unix Makefiles";
  1873. }
  1874. // Create the generator and use it to clear the dependencies.
  1875. std::unique_ptr<cmGlobalGenerator> ggd(
  1876. this->CreateGlobalGenerator(genName));
  1877. if (ggd) {
  1878. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1879. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  1880. std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mfd));
  1881. lgd->ClearDependencies(&mfd, verbose);
  1882. }
  1883. }
  1884. // If any byproduct of makefile generation is missing we must re-run.
  1885. std::vector<std::string> products;
  1886. if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1887. cmSystemTools::ExpandListArgument(productStr, products);
  1888. }
  1889. for (std::string const& p : products) {
  1890. if (!(cmSystemTools::FileExists(p) || cmSystemTools::FileIsSymlink(p))) {
  1891. if (verbose) {
  1892. std::ostringstream msg;
  1893. msg << "Re-run cmake, missing byproduct: " << p << "\n";
  1894. cmSystemTools::Stdout(msg.str().c_str());
  1895. }
  1896. return 1;
  1897. }
  1898. }
  1899. // Get the set of dependencies and outputs.
  1900. std::vector<std::string> depends;
  1901. std::vector<std::string> outputs;
  1902. const char* dependsStr = mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS");
  1903. const char* outputsStr = mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
  1904. if (dependsStr && outputsStr) {
  1905. cmSystemTools::ExpandListArgument(dependsStr, depends);
  1906. cmSystemTools::ExpandListArgument(outputsStr, outputs);
  1907. }
  1908. if (depends.empty() || outputs.empty()) {
  1909. // Not enough information was provided to do the test. Just rerun.
  1910. if (verbose) {
  1911. std::ostringstream msg;
  1912. msg << "Re-run cmake no CMAKE_MAKEFILE_DEPENDS "
  1913. "or CMAKE_MAKEFILE_OUTPUTS :\n";
  1914. cmSystemTools::Stdout(msg.str().c_str());
  1915. }
  1916. return 1;
  1917. }
  1918. // Find the newest dependency.
  1919. std::vector<std::string>::iterator dep = depends.begin();
  1920. std::string dep_newest = *dep++;
  1921. for (; dep != depends.end(); ++dep) {
  1922. int result = 0;
  1923. if (this->FileComparison->FileTimeCompare(dep_newest.c_str(), dep->c_str(),
  1924. &result)) {
  1925. if (result < 0) {
  1926. dep_newest = *dep;
  1927. }
  1928. } else {
  1929. if (verbose) {
  1930. std::ostringstream msg;
  1931. msg << "Re-run cmake: build system dependency is missing\n";
  1932. cmSystemTools::Stdout(msg.str().c_str());
  1933. }
  1934. return 1;
  1935. }
  1936. }
  1937. // Find the oldest output.
  1938. std::vector<std::string>::iterator out = outputs.begin();
  1939. std::string out_oldest = *out++;
  1940. for (; out != outputs.end(); ++out) {
  1941. int result = 0;
  1942. if (this->FileComparison->FileTimeCompare(out_oldest.c_str(), out->c_str(),
  1943. &result)) {
  1944. if (result > 0) {
  1945. out_oldest = *out;
  1946. }
  1947. } else {
  1948. if (verbose) {
  1949. std::ostringstream msg;
  1950. msg << "Re-run cmake: build system output is missing\n";
  1951. cmSystemTools::Stdout(msg.str().c_str());
  1952. }
  1953. return 1;
  1954. }
  1955. }
  1956. // If any output is older than any dependency then rerun.
  1957. {
  1958. int result = 0;
  1959. if (!this->FileComparison->FileTimeCompare(out_oldest.c_str(),
  1960. dep_newest.c_str(), &result) ||
  1961. result < 0) {
  1962. if (verbose) {
  1963. std::ostringstream msg;
  1964. msg << "Re-run cmake file: " << out_oldest
  1965. << " older than: " << dep_newest << "\n";
  1966. cmSystemTools::Stdout(msg.str().c_str());
  1967. }
  1968. return 1;
  1969. }
  1970. }
  1971. // No need to rerun.
  1972. return 0;
  1973. }
  1974. void cmake::TruncateOutputLog(const char* fname)
  1975. {
  1976. std::string fullPath = this->GetHomeOutputDirectory();
  1977. fullPath += "/";
  1978. fullPath += fname;
  1979. struct stat st;
  1980. if (::stat(fullPath.c_str(), &st)) {
  1981. return;
  1982. }
  1983. if (!this->State->GetInitializedCacheValue("CMAKE_CACHEFILE_DIR")) {
  1984. cmSystemTools::RemoveFile(fullPath);
  1985. return;
  1986. }
  1987. off_t fsize = st.st_size;
  1988. const off_t maxFileSize = 50 * 1024;
  1989. if (fsize < maxFileSize) {
  1990. // TODO: truncate file
  1991. return;
  1992. }
  1993. }
  1994. inline std::string removeQuotes(const std::string& s)
  1995. {
  1996. if (s.front() == '\"' && s.back() == '\"') {
  1997. return s.substr(1, s.size() - 2);
  1998. }
  1999. return s;
  2000. }
  2001. void cmake::MarkCliAsUsed(const std::string& variable)
  2002. {
  2003. this->UsedCliVariables[variable] = true;
  2004. }
  2005. void cmake::GenerateGraphViz(const char* fileName) const
  2006. {
  2007. #ifdef CMAKE_BUILD_WITH_CMAKE
  2008. cmGraphVizWriter gvWriter(this->GetGlobalGenerator());
  2009. std::string settingsFile = this->GetHomeOutputDirectory();
  2010. settingsFile += "/CMakeGraphVizOptions.cmake";
  2011. std::string fallbackSettingsFile = this->GetHomeDirectory();
  2012. fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
  2013. gvWriter.ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
  2014. gvWriter.WritePerTargetFiles(fileName);
  2015. gvWriter.WriteTargetDependersFiles(fileName);
  2016. gvWriter.WriteGlobalFile(fileName);
  2017. #endif
  2018. }
  2019. void cmake::SetProperty(const std::string& prop, const char* value)
  2020. {
  2021. this->State->SetGlobalProperty(prop, value);
  2022. }
  2023. void cmake::AppendProperty(const std::string& prop, const char* value,
  2024. bool asString)
  2025. {
  2026. this->State->AppendGlobalProperty(prop, value, asString);
  2027. }
  2028. const char* cmake::GetProperty(const std::string& prop)
  2029. {
  2030. return this->State->GetGlobalProperty(prop);
  2031. }
  2032. bool cmake::GetPropertyAsBool(const std::string& prop)
  2033. {
  2034. return this->State->GetGlobalPropertyAsBool(prop);
  2035. }
  2036. cmInstalledFile* cmake::GetOrCreateInstalledFile(cmMakefile* mf,
  2037. const std::string& name)
  2038. {
  2039. std::map<std::string, cmInstalledFile>::iterator i =
  2040. this->InstalledFiles.find(name);
  2041. if (i != this->InstalledFiles.end()) {
  2042. cmInstalledFile& file = i->second;
  2043. return &file;
  2044. }
  2045. cmInstalledFile& file = this->InstalledFiles[name];
  2046. file.SetName(mf, name);
  2047. return &file;
  2048. }
  2049. cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
  2050. {
  2051. std::map<std::string, cmInstalledFile>::const_iterator i =
  2052. this->InstalledFiles.find(name);
  2053. if (i != this->InstalledFiles.end()) {
  2054. cmInstalledFile const& file = i->second;
  2055. return &file;
  2056. }
  2057. return nullptr;
  2058. }
  2059. int cmake::GetSystemInformation(std::vector<std::string>& args)
  2060. {
  2061. // so create the directory
  2062. std::string resultFile;
  2063. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  2064. std::string destPath = cwd + "/__cmake_systeminformation";
  2065. cmSystemTools::RemoveADirectory(destPath);
  2066. if (!cmSystemTools::MakeDirectory(destPath)) {
  2067. std::cerr << "Error: --system-information must be run from a "
  2068. "writable directory!\n";
  2069. return 1;
  2070. }
  2071. // process the arguments
  2072. bool writeToStdout = true;
  2073. for (unsigned int i = 1; i < args.size(); ++i) {
  2074. std::string const& arg = args[i];
  2075. if (arg.find("-G", 0) == 0) {
  2076. std::string value = arg.substr(2);
  2077. if (value.empty()) {
  2078. ++i;
  2079. if (i >= args.size()) {
  2080. cmSystemTools::Error("No generator specified for -G");
  2081. this->PrintGeneratorList();
  2082. return -1;
  2083. }
  2084. value = args[i];
  2085. }
  2086. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  2087. if (!gen) {
  2088. cmSystemTools::Error("Could not create named generator ",
  2089. value.c_str());
  2090. this->PrintGeneratorList();
  2091. } else {
  2092. this->SetGlobalGenerator(gen);
  2093. }
  2094. }
  2095. // no option assume it is the output file
  2096. else {
  2097. if (!cmSystemTools::FileIsFullPath(arg)) {
  2098. resultFile = cwd;
  2099. resultFile += "/";
  2100. }
  2101. resultFile += arg;
  2102. writeToStdout = false;
  2103. }
  2104. }
  2105. // we have to find the module directory, so we can copy the files
  2106. this->AddCMakePaths();
  2107. std::string modulesPath = cmSystemTools::GetCMakeRoot();
  2108. modulesPath += "/Modules";
  2109. std::string inFile = modulesPath;
  2110. inFile += "/SystemInformation.cmake";
  2111. std::string outFile = destPath;
  2112. outFile += "/CMakeLists.txt";
  2113. // Copy file
  2114. if (!cmSystemTools::cmCopyFile(inFile.c_str(), outFile.c_str())) {
  2115. std::cerr << "Error copying file \"" << inFile << "\" to \"" << outFile
  2116. << "\".\n";
  2117. return 1;
  2118. }
  2119. // do we write to a file or to stdout?
  2120. if (resultFile.empty()) {
  2121. resultFile = cwd;
  2122. resultFile += "/__cmake_systeminformation/results.txt";
  2123. }
  2124. {
  2125. // now run cmake on the CMakeLists file
  2126. cmWorkingDirectory workdir(destPath);
  2127. if (workdir.Failed()) {
  2128. // We created the directory and we were able to copy the CMakeLists.txt
  2129. // file to it, so we wouldn't expect to get here unless the default
  2130. // permissions are questionable or some other process has deleted the
  2131. // directory
  2132. std::cerr << "Failed to change to directory " << destPath << " : "
  2133. << std::strerror(workdir.GetLastResult()) << std::endl;
  2134. return 1;
  2135. }
  2136. std::vector<std::string> args2;
  2137. args2.push_back(args[0]);
  2138. args2.push_back(destPath);
  2139. args2.push_back("-DRESULT_FILE=" + resultFile);
  2140. int res = this->Run(args2, false);
  2141. if (res != 0) {
  2142. std::cerr << "Error: --system-information failed on internal CMake!\n";
  2143. return res;
  2144. }
  2145. }
  2146. // echo results to stdout if needed
  2147. if (writeToStdout) {
  2148. FILE* fin = cmsys::SystemTools::Fopen(resultFile, "r");
  2149. if (fin) {
  2150. const int bufferSize = 4096;
  2151. char buffer[bufferSize];
  2152. size_t n;
  2153. while ((n = fread(buffer, 1, bufferSize, fin)) > 0) {
  2154. for (char* c = buffer; c < buffer + n; ++c) {
  2155. putc(*c, stdout);
  2156. }
  2157. fflush(stdout);
  2158. }
  2159. fclose(fin);
  2160. }
  2161. }
  2162. // clean up the directory
  2163. cmSystemTools::RemoveADirectory(destPath);
  2164. return 0;
  2165. }
  2166. static bool cmakeCheckStampFile(const char* stampName, bool verbose)
  2167. {
  2168. // The stamp file does not exist. Use the stamp dependencies to
  2169. // determine whether it is really out of date. This works in
  2170. // conjunction with cmLocalVisualStudio7Generator to avoid
  2171. // repeatedly re-running CMake when the user rebuilds the entire
  2172. // solution.
  2173. std::string stampDepends = stampName;
  2174. stampDepends += ".depend";
  2175. #if defined(_WIN32) || defined(__CYGWIN__)
  2176. cmsys::ifstream fin(stampDepends.c_str(), std::ios::in | std::ios::binary);
  2177. #else
  2178. cmsys::ifstream fin(stampDepends.c_str());
  2179. #endif
  2180. if (!fin) {
  2181. // The stamp dependencies file cannot be read. Just assume the
  2182. // build system is really out of date.
  2183. std::cout << "CMake is re-running because " << stampName
  2184. << " dependency file is missing.\n";
  2185. return false;
  2186. }
  2187. // Compare the stamp dependencies against the dependency file itself.
  2188. cmFileTimeComparison ftc;
  2189. std::string dep;
  2190. while (cmSystemTools::GetLineFromStream(fin, dep)) {
  2191. int result;
  2192. if (!dep.empty() && dep[0] != '#' &&
  2193. (!ftc.FileTimeCompare(stampDepends.c_str(), dep.c_str(), &result) ||
  2194. result < 0)) {
  2195. // The stamp depends file is older than this dependency. The
  2196. // build system is really out of date.
  2197. std::cout << "CMake is re-running because " << stampName
  2198. << " is out-of-date.\n";
  2199. std::cout << " the file '" << dep << "'\n";
  2200. std::cout << " is newer than '" << stampDepends << "'\n";
  2201. std::cout << " result='" << result << "'\n";
  2202. return false;
  2203. }
  2204. }
  2205. // The build system is up to date. The stamp file has been removed
  2206. // by the VS IDE due to a "rebuild" request. Restore it atomically.
  2207. std::ostringstream stampTempStream;
  2208. stampTempStream << stampName << ".tmp" << cmSystemTools::RandomSeed();
  2209. std::string stampTempString = stampTempStream.str();
  2210. const char* stampTemp = stampTempString.c_str();
  2211. {
  2212. // TODO: Teach cmGeneratedFileStream to use a random temp file (with
  2213. // multiple tries in unlikely case of conflict) and use that here.
  2214. cmsys::ofstream stamp(stampTemp);
  2215. stamp << "# CMake generation timestamp file for this directory.\n";
  2216. }
  2217. if (cmSystemTools::RenameFile(stampTemp, stampName)) {
  2218. if (verbose) {
  2219. // Notify the user why CMake is not re-running. It is safe to
  2220. // just print to stdout here because this code is only reachable
  2221. // through an undocumented flag used by the VS generator.
  2222. std::cout << "CMake does not need to re-run because " << stampName
  2223. << " is up-to-date.\n";
  2224. }
  2225. return true;
  2226. }
  2227. cmSystemTools::RemoveFile(stampTemp);
  2228. cmSystemTools::Error("Cannot restore timestamp ", stampName);
  2229. return false;
  2230. }
  2231. static bool cmakeCheckStampList(const char* stampList, bool verbose)
  2232. {
  2233. // If the stamp list does not exist CMake must rerun to generate it.
  2234. if (!cmSystemTools::FileExists(stampList)) {
  2235. std::cout << "CMake is re-running because generate.stamp.list "
  2236. << "is missing.\n";
  2237. return false;
  2238. }
  2239. cmsys::ifstream fin(stampList);
  2240. if (!fin) {
  2241. std::cout << "CMake is re-running because generate.stamp.list "
  2242. << "could not be read.\n";
  2243. return false;
  2244. }
  2245. // Check each stamp.
  2246. std::string stampName;
  2247. while (cmSystemTools::GetLineFromStream(fin, stampName)) {
  2248. if (!cmakeCheckStampFile(stampName.c_str(), verbose)) {
  2249. return false;
  2250. }
  2251. }
  2252. return true;
  2253. }
  2254. void cmake::IssueMessage(MessageType t, std::string const& text,
  2255. cmListFileBacktrace const& backtrace) const
  2256. {
  2257. this->Messenger->IssueMessage(t, text, backtrace);
  2258. }
  2259. std::vector<std::string> cmake::GetDebugConfigs()
  2260. {
  2261. std::vector<std::string> configs;
  2262. if (const char* config_list =
  2263. this->State->GetGlobalProperty("DEBUG_CONFIGURATIONS")) {
  2264. // Expand the specified list and convert to upper-case.
  2265. cmSystemTools::ExpandListArgument(config_list, configs);
  2266. std::transform(configs.begin(), configs.end(), configs.begin(),
  2267. cmSystemTools::UpperCase);
  2268. }
  2269. // If no configurations were specified, use a default list.
  2270. if (configs.empty()) {
  2271. configs.push_back("DEBUG");
  2272. }
  2273. return configs;
  2274. }
  2275. cmMessenger* cmake::GetMessenger() const
  2276. {
  2277. return this->Messenger;
  2278. }
  2279. int cmake::Build(int jobs, const std::string& dir, const std::string& target,
  2280. const std::string& config,
  2281. const std::vector<std::string>& nativeOptions, bool clean)
  2282. {
  2283. this->SetHomeDirectory("");
  2284. this->SetHomeOutputDirectory("");
  2285. if (!cmSystemTools::FileIsDirectory(dir)) {
  2286. std::cerr << "Error: " << dir << " is not a directory\n";
  2287. return 1;
  2288. }
  2289. std::string cachePath = FindCacheFile(dir);
  2290. if (!this->LoadCache(cachePath)) {
  2291. std::cerr << "Error: could not load cache\n";
  2292. return 1;
  2293. }
  2294. const char* cachedGenerator =
  2295. this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2296. if (!cachedGenerator) {
  2297. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2298. return 1;
  2299. }
  2300. cmGlobalGenerator* gen = this->CreateGlobalGenerator(cachedGenerator);
  2301. if (!gen) {
  2302. std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
  2303. << "\"\n";
  2304. return 1;
  2305. }
  2306. this->SetGlobalGenerator(gen);
  2307. const char* cachedGeneratorInstance =
  2308. this->State->GetCacheEntryValue("CMAKE_GENERATOR_INSTANCE");
  2309. if (cachedGeneratorInstance) {
  2310. cmMakefile mf(gen, this->GetCurrentSnapshot());
  2311. if (!gen->SetGeneratorInstance(cachedGeneratorInstance, &mf)) {
  2312. return 1;
  2313. }
  2314. }
  2315. const char* cachedGeneratorPlatform =
  2316. this->State->GetCacheEntryValue("CMAKE_GENERATOR_PLATFORM");
  2317. if (cachedGeneratorPlatform) {
  2318. cmMakefile mf(gen, this->GetCurrentSnapshot());
  2319. if (!gen->SetGeneratorPlatform(cachedGeneratorPlatform, &mf)) {
  2320. return 1;
  2321. }
  2322. }
  2323. std::string output;
  2324. std::string projName;
  2325. const char* cachedProjectName =
  2326. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2327. if (!cachedProjectName) {
  2328. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2329. return 1;
  2330. }
  2331. projName = cachedProjectName;
  2332. bool verbose = false;
  2333. const char* cachedVerbose =
  2334. this->State->GetCacheEntryValue("CMAKE_VERBOSE_MAKEFILE");
  2335. if (cachedVerbose) {
  2336. verbose = cmSystemTools::IsOn(cachedVerbose);
  2337. }
  2338. #ifdef CMAKE_HAVE_VS_GENERATORS
  2339. // For VS generators, explicitly check if regeneration is necessary before
  2340. // actually starting the build. If not done separately from the build
  2341. // itself, there is the risk of building an out-of-date solution file due
  2342. // to limitations of the underlying build system.
  2343. std::string const stampList = cachePath + "/" +
  2344. GetCMakeFilesDirectoryPostSlash() +
  2345. cmGlobalVisualStudio9Generator::GetGenerateStampList();
  2346. // Note that the stampList file only exists for VS generators.
  2347. if (cmSystemTools::FileExists(stampList)) {
  2348. // Check if running for Visual Studio 9 - we need to explicitly run
  2349. // the glob verification script before starting the build
  2350. this->AddScriptingCommands();
  2351. if (this->GlobalGenerator->MatchesGeneratorName("Visual Studio 9 2008")) {
  2352. std::string const globVerifyScript = cachePath + "/" +
  2353. GetCMakeFilesDirectoryPostSlash() + "VerifyGlobs.cmake";
  2354. if (cmSystemTools::FileExists(globVerifyScript)) {
  2355. std::vector<std::string> args;
  2356. this->ReadListFile(args, globVerifyScript.c_str());
  2357. }
  2358. }
  2359. if (!cmakeCheckStampList(stampList.c_str(), false)) {
  2360. // Correctly initialize the home (=source) and home output (=binary)
  2361. // directories, which is required for running the generation step.
  2362. std::string homeOrig = this->GetHomeDirectory();
  2363. std::string homeOutputOrig = this->GetHomeOutputDirectory();
  2364. this->SetDirectoriesFromFile(cachePath.c_str());
  2365. this->AddProjectCommands();
  2366. int ret = this->Configure();
  2367. if (ret) {
  2368. cmSystemTools::Message("CMake Configure step failed. "
  2369. "Build files cannot be regenerated correctly.");
  2370. return ret;
  2371. }
  2372. ret = this->Generate();
  2373. if (ret) {
  2374. cmSystemTools::Message("CMake Generate step failed. "
  2375. "Build files cannot be regenerated correctly.");
  2376. return ret;
  2377. }
  2378. std::string message = "Build files have been written to: ";
  2379. message += this->GetHomeOutputDirectory();
  2380. this->UpdateProgress(message.c_str(), -1);
  2381. // Restore the previously set directories to their original value.
  2382. this->SetHomeDirectory(homeOrig);
  2383. this->SetHomeOutputDirectory(homeOutputOrig);
  2384. }
  2385. }
  2386. #endif
  2387. gen->PrintBuildCommandAdvice(std::cerr, jobs);
  2388. return gen->Build(jobs, "", dir, projName, target, output, "", config, clean,
  2389. false, verbose, cmDuration::zero(),
  2390. cmSystemTools::OUTPUT_PASSTHROUGH, nativeOptions);
  2391. }
  2392. bool cmake::Open(const std::string& dir, bool dryRun)
  2393. {
  2394. this->SetHomeDirectory("");
  2395. this->SetHomeOutputDirectory("");
  2396. if (!cmSystemTools::FileIsDirectory(dir)) {
  2397. std::cerr << "Error: " << dir << " is not a directory\n";
  2398. return false;
  2399. }
  2400. std::string cachePath = FindCacheFile(dir);
  2401. if (!this->LoadCache(cachePath)) {
  2402. std::cerr << "Error: could not load cache\n";
  2403. return false;
  2404. }
  2405. const char* genName = this->State->GetCacheEntryValue("CMAKE_GENERATOR");
  2406. if (!genName) {
  2407. std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
  2408. return false;
  2409. }
  2410. const std::string* extraGenName =
  2411. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  2412. std::string fullName =
  2413. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  2414. genName, extraGenName ? *extraGenName : "");
  2415. std::unique_ptr<cmGlobalGenerator> gen(
  2416. this->CreateGlobalGenerator(fullName));
  2417. if (!gen) {
  2418. std::cerr << "Error: could create CMAKE_GENERATOR \"" << fullName
  2419. << "\"\n";
  2420. return false;
  2421. }
  2422. const char* cachedProjectName =
  2423. this->State->GetCacheEntryValue("CMAKE_PROJECT_NAME");
  2424. if (!cachedProjectName) {
  2425. std::cerr << "Error: could not find CMAKE_PROJECT_NAME in Cache\n";
  2426. return false;
  2427. }
  2428. return gen->Open(dir, cachedProjectName, dryRun);
  2429. }
  2430. void cmake::WatchUnusedCli(const std::string& var)
  2431. {
  2432. #ifdef CMAKE_BUILD_WITH_CMAKE
  2433. this->VariableWatch->AddWatch(var, cmWarnUnusedCliWarning, this);
  2434. if (this->UsedCliVariables.find(var) == this->UsedCliVariables.end()) {
  2435. this->UsedCliVariables[var] = false;
  2436. }
  2437. #endif
  2438. }
  2439. void cmake::UnwatchUnusedCli(const std::string& var)
  2440. {
  2441. #ifdef CMAKE_BUILD_WITH_CMAKE
  2442. this->VariableWatch->RemoveWatch(var, cmWarnUnusedCliWarning);
  2443. this->UsedCliVariables.erase(var);
  2444. #endif
  2445. }
  2446. void cmake::RunCheckForUnusedVariables()
  2447. {
  2448. #ifdef CMAKE_BUILD_WITH_CMAKE
  2449. bool haveUnused = false;
  2450. std::ostringstream msg;
  2451. msg << "Manually-specified variables were not used by the project:";
  2452. for (auto const& it : this->UsedCliVariables) {
  2453. if (!it.second) {
  2454. haveUnused = true;
  2455. msg << "\n " << it.first;
  2456. }
  2457. }
  2458. if (haveUnused) {
  2459. this->IssueMessage(MessageType::WARNING, msg.str());
  2460. }
  2461. #endif
  2462. }
  2463. bool cmake::GetSuppressDevWarnings() const
  2464. {
  2465. return this->Messenger->GetSuppressDevWarnings();
  2466. }
  2467. void cmake::SetSuppressDevWarnings(bool b)
  2468. {
  2469. std::string value;
  2470. // equivalent to -Wno-dev
  2471. if (b) {
  2472. value = "TRUE";
  2473. }
  2474. // equivalent to -Wdev
  2475. else {
  2476. value = "FALSE";
  2477. }
  2478. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", value.c_str(),
  2479. "Suppress Warnings that are meant for"
  2480. " the author of the CMakeLists.txt files.",
  2481. cmStateEnums::INTERNAL);
  2482. }
  2483. bool cmake::GetSuppressDeprecatedWarnings() const
  2484. {
  2485. return this->Messenger->GetSuppressDeprecatedWarnings();
  2486. }
  2487. void cmake::SetSuppressDeprecatedWarnings(bool b)
  2488. {
  2489. std::string value;
  2490. // equivalent to -Wno-deprecated
  2491. if (b) {
  2492. value = "FALSE";
  2493. }
  2494. // equivalent to -Wdeprecated
  2495. else {
  2496. value = "TRUE";
  2497. }
  2498. this->AddCacheEntry("CMAKE_WARN_DEPRECATED", value.c_str(),
  2499. "Whether to issue warnings for deprecated "
  2500. "functionality.",
  2501. cmStateEnums::INTERNAL);
  2502. }
  2503. bool cmake::GetDevWarningsAsErrors() const
  2504. {
  2505. return this->Messenger->GetDevWarningsAsErrors();
  2506. }
  2507. void cmake::SetDevWarningsAsErrors(bool b)
  2508. {
  2509. std::string value;
  2510. // equivalent to -Werror=dev
  2511. if (b) {
  2512. value = "FALSE";
  2513. }
  2514. // equivalent to -Wno-error=dev
  2515. else {
  2516. value = "TRUE";
  2517. }
  2518. this->AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_ERRORS", value.c_str(),
  2519. "Suppress errors that are meant for"
  2520. " the author of the CMakeLists.txt files.",
  2521. cmStateEnums::INTERNAL);
  2522. }
  2523. bool cmake::GetDeprecatedWarningsAsErrors() const
  2524. {
  2525. return this->Messenger->GetDeprecatedWarningsAsErrors();
  2526. }
  2527. void cmake::SetDeprecatedWarningsAsErrors(bool b)
  2528. {
  2529. std::string value;
  2530. // equivalent to -Werror=deprecated
  2531. if (b) {
  2532. value = "TRUE";
  2533. }
  2534. // equivalent to -Wno-error=deprecated
  2535. else {
  2536. value = "FALSE";
  2537. }
  2538. this->AddCacheEntry("CMAKE_ERROR_DEPRECATED", value.c_str(),
  2539. "Whether to issue deprecation errors for macros"
  2540. " and functions.",
  2541. cmStateEnums::INTERNAL);
  2542. }