cmake.cxx 90 KB

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