cmake.cxx 80 KB

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