cmake.cxx 89 KB

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