cmake.cxx 89 KB

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