cmake.cxx 84 KB

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