cmake.cxx 82 KB

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