cmake.cxx 86 KB

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