cmake.cxx 86 KB

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