cmake.cxx 87 KB

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