cmake.cxx 83 KB

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