cmake.cxx 85 KB

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