1
0

cmake.cxx 93 KB

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