cmake.cxx 89 KB

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