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 "cmExternalMakefileProjectGenerator.h"
  10. #include "cmFileTimeComparison.h"
  11. #include "cmGeneratorTarget.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmGlobalGeneratorFactory.h"
  14. #include "cmLinkLineComputer.h"
  15. #include "cmLocalGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmMessenger.h"
  18. #include "cmState.h"
  19. #include "cmStateDirectory.h"
  20. #include "cmSystemTools.h"
  21. #include "cmTarget.h"
  22. #include "cmTargetLinkLibraryType.h"
  23. #include "cmUtils.hxx"
  24. #include "cmVersionConfig.h"
  25. #include "cmWorkingDirectory.h"
  26. #include "cm_sys_stat.h"
  27. #if defined(CMAKE_BUILD_WITH_CMAKE)
  28. #include "cm_jsoncpp_writer.h"
  29. #include "cmGraphVizWriter.h"
  30. #include "cmVariableWatch.h"
  31. #include <unordered_map>
  32. #endif
  33. #if defined(CMAKE_BUILD_WITH_CMAKE)
  34. #define CMAKE_USE_ECLIPSE
  35. #endif
  36. #if defined(__MINGW32__) && !defined(CMAKE_BUILD_WITH_CMAKE)
  37. #define CMAKE_BOOT_MINGW
  38. #endif
  39. // include the generator
  40. #if defined(_WIN32) && !defined(__CYGWIN__)
  41. #if !defined(CMAKE_BOOT_MINGW)
  42. #include "cmGlobalBorlandMakefileGenerator.h"
  43. #include "cmGlobalGhsMultiGenerator.h"
  44. #include "cmGlobalJOMMakefileGenerator.h"
  45. #include "cmGlobalNMakeMakefileGenerator.h"
  46. #include "cmGlobalVisualStudio10Generator.h"
  47. #include "cmGlobalVisualStudio11Generator.h"
  48. #include "cmGlobalVisualStudio12Generator.h"
  49. #include "cmGlobalVisualStudio14Generator.h"
  50. #include "cmGlobalVisualStudio15Generator.h"
  51. #include "cmGlobalVisualStudio8Generator.h"
  52. #include "cmGlobalVisualStudio9Generator.h"
  53. #include "cmVSSetupHelper.h"
  54. #define CMAKE_HAVE_VS_GENERATORS
  55. #endif
  56. #include "cmGlobalMSYSMakefileGenerator.h"
  57. #include "cmGlobalMinGWMakefileGenerator.h"
  58. #else
  59. #endif
  60. #if defined(CMAKE_USE_WMAKE)
  61. #include "cmGlobalWatcomWMakeGenerator.h"
  62. #endif
  63. #include "cmGlobalUnixMakefileGenerator3.h"
  64. #if defined(CMAKE_BUILD_WITH_CMAKE)
  65. #include "cmGlobalNinjaGenerator.h"
  66. #endif
  67. #include "cmExtraCodeLiteGenerator.h"
  68. #if !defined(CMAKE_BOOT_MINGW)
  69. #include "cmExtraCodeBlocksGenerator.h"
  70. #endif
  71. #include "cmExtraKateGenerator.h"
  72. #include "cmExtraSublimeTextGenerator.h"
  73. #ifdef CMAKE_USE_ECLIPSE
  74. #include "cmExtraEclipseCDT4Generator.h"
  75. #endif
  76. #if defined(__APPLE__)
  77. #if defined(CMAKE_BUILD_WITH_CMAKE)
  78. #include "cmGlobalXCodeGenerator.h"
  79. #define CMAKE_USE_XCODE 1
  80. #endif
  81. #include <sys/resource.h>
  82. #include <sys/time.h>
  83. #endif
  84. #include "cmsys/FStream.hxx"
  85. #include "cmsys/Glob.hxx"
  86. #include "cmsys/RegularExpression.hxx"
  87. #include <algorithm>
  88. #include <iostream>
  89. #include <iterator>
  90. #include <memory> // IWYU pragma: keep
  91. #include <sstream>
  92. #include <stdio.h>
  93. #include <stdlib.h>
  94. #include <string.h>
  95. #include <utility>
  96. namespace {
  97. #if defined(CMAKE_BUILD_WITH_CMAKE)
  98. typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
  99. #endif
  100. } // namespace
  101. static bool cmakeCheckStampFile(const char* stampName, bool verbose = true);
  102. static bool cmakeCheckStampList(const char* stampList, bool verbose = true);
  103. void cmWarnUnusedCliWarning(const std::string& variable, int /*unused*/,
  104. void* ctx, const char* /*unused*/,
  105. const cmMakefile* /*unused*/)
  106. {
  107. cmake* cm = reinterpret_cast<cmake*>(ctx);
  108. cm->MarkCliAsUsed(variable);
  109. }
  110. cmake::cmake(Role role)
  111. {
  112. this->Trace = false;
  113. this->TraceExpand = false;
  114. this->WarnUninitialized = false;
  115. this->WarnUnused = false;
  116. this->WarnUnusedCli = true;
  117. this->CheckSystemVars = false;
  118. this->DebugOutput = false;
  119. this->DebugTryCompile = false;
  120. this->ClearBuildSystem = false;
  121. this->FileComparison = new cmFileTimeComparison;
  122. this->State = new cmState;
  123. this->CurrentSnapshot = this->State->CreateBaseSnapshot();
  124. this->Messenger = new cmMessenger(this->State);
  125. #ifdef __APPLE__
  126. struct rlimit rlp;
  127. if (!getrlimit(RLIMIT_STACK, &rlp)) {
  128. if (rlp.rlim_cur != rlp.rlim_max) {
  129. rlp.rlim_cur = rlp.rlim_max;
  130. setrlimit(RLIMIT_STACK, &rlp);
  131. }
  132. }
  133. #endif
  134. this->GlobalGenerator = nullptr;
  135. this->ProgressCallback = nullptr;
  136. this->ProgressCallbackClientData = nullptr;
  137. this->CurrentWorkingMode = NORMAL_MODE;
  138. #ifdef CMAKE_BUILD_WITH_CMAKE
  139. this->VariableWatch = new cmVariableWatch;
  140. #endif
  141. this->AddDefaultGenerators();
  142. this->AddDefaultExtraGenerators();
  143. if (role == RoleScript || role == RoleProject) {
  144. this->AddScriptingCommands();
  145. }
  146. if (role == RoleProject) {
  147. this->AddProjectCommands();
  148. }
  149. // Make sure we can capture the build tool output.
  150. cmSystemTools::EnableVSConsoleOutput();
  151. // Set up a list of source and header extensions
  152. // these are used to find files when the extension
  153. // is not given
  154. // The "c" extension MUST precede the "C" extension.
  155. this->SourceFileExtensions.push_back("c");
  156. this->SourceFileExtensions.push_back("C");
  157. this->SourceFileExtensions.push_back("c++");
  158. this->SourceFileExtensions.push_back("cc");
  159. this->SourceFileExtensions.push_back("cpp");
  160. this->SourceFileExtensions.push_back("cxx");
  161. this->SourceFileExtensions.push_back("cu");
  162. this->SourceFileExtensions.push_back("m");
  163. this->SourceFileExtensions.push_back("M");
  164. this->SourceFileExtensions.push_back("mm");
  165. std::copy(this->SourceFileExtensions.begin(),
  166. this->SourceFileExtensions.end(),
  167. std::inserter(this->SourceFileExtensionsSet,
  168. this->SourceFileExtensionsSet.end()));
  169. this->HeaderFileExtensions.push_back("h");
  170. this->HeaderFileExtensions.push_back("hh");
  171. this->HeaderFileExtensions.push_back("h++");
  172. this->HeaderFileExtensions.push_back("hm");
  173. this->HeaderFileExtensions.push_back("hpp");
  174. this->HeaderFileExtensions.push_back("hxx");
  175. this->HeaderFileExtensions.push_back("in");
  176. this->HeaderFileExtensions.push_back("txx");
  177. std::copy(this->HeaderFileExtensions.begin(),
  178. this->HeaderFileExtensions.end(),
  179. std::inserter(this->HeaderFileExtensionsSet,
  180. this->HeaderFileExtensionsSet.end()));
  181. }
  182. cmake::~cmake()
  183. {
  184. delete this->State;
  185. delete this->Messenger;
  186. if (this->GlobalGenerator) {
  187. delete this->GlobalGenerator;
  188. this->GlobalGenerator = nullptr;
  189. }
  190. cmDeleteAll(this->Generators);
  191. #ifdef CMAKE_BUILD_WITH_CMAKE
  192. delete this->VariableWatch;
  193. #endif
  194. delete this->FileComparison;
  195. }
  196. #if defined(CMAKE_BUILD_WITH_CMAKE)
  197. Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
  198. {
  199. Json::Value obj = Json::objectValue;
  200. // Version information:
  201. Json::Value version = Json::objectValue;
  202. version["string"] = CMake_VERSION;
  203. version["major"] = CMake_VERSION_MAJOR;
  204. version["minor"] = CMake_VERSION_MINOR;
  205. version["suffix"] = CMake_VERSION_SUFFIX;
  206. version["isDirty"] = (CMake_VERSION_IS_DIRTY == 1);
  207. version["patch"] = CMake_VERSION_PATCH;
  208. obj["version"] = version;
  209. // Generators:
  210. std::vector<cmake::GeneratorInfo> generatorInfoList;
  211. this->GetRegisteredGenerators(generatorInfoList);
  212. JsonValueMapType generatorMap;
  213. for (cmake::GeneratorInfo const& gi : generatorInfoList) {
  214. if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
  215. // only
  216. continue;
  217. }
  218. if (gi.extraName.empty()) {
  219. Json::Value gen = Json::objectValue;
  220. gen["name"] = gi.name;
  221. gen["toolsetSupport"] = gi.supportsToolset;
  222. gen["platformSupport"] = gi.supportsPlatform;
  223. gen["extraGenerators"] = Json::arrayValue;
  224. generatorMap[gi.name] = gen;
  225. } else {
  226. Json::Value& gen = generatorMap[gi.baseName];
  227. gen["extraGenerators"].append(gi.extraName);
  228. }
  229. }
  230. Json::Value generators = Json::arrayValue;
  231. for (auto const& i : generatorMap) {
  232. generators.append(i.second);
  233. }
  234. obj["generators"] = generators;
  235. obj["serverMode"] = haveServerMode;
  236. return obj;
  237. }
  238. #endif
  239. std::string cmake::ReportCapabilities(bool haveServerMode) const
  240. {
  241. std::string result;
  242. #if defined(CMAKE_BUILD_WITH_CMAKE)
  243. Json::FastWriter writer;
  244. result = writer.write(this->ReportCapabilitiesJson(haveServerMode));
  245. #else
  246. result = "Not supported";
  247. #endif
  248. return result;
  249. }
  250. void cmake::CleanupCommandsAndMacros()
  251. {
  252. this->CurrentSnapshot = this->State->Reset();
  253. this->State->RemoveUserDefinedCommands();
  254. this->CurrentSnapshot.SetDefaultDefinitions();
  255. }
  256. // Parse the args
  257. bool cmake::SetCacheArgs(const std::vector<std::string>& args)
  258. {
  259. bool findPackageMode = false;
  260. for (unsigned int i = 1; i < args.size(); ++i) {
  261. std::string const& arg = args[i];
  262. if (arg.find("-D", 0) == 0) {
  263. std::string entry = arg.substr(2);
  264. if (entry.empty()) {
  265. ++i;
  266. if (i < args.size()) {
  267. entry = args[i];
  268. } else {
  269. cmSystemTools::Error("-D must be followed with VAR=VALUE.");
  270. return false;
  271. }
  272. }
  273. std::string var, value;
  274. cmStateEnums::CacheEntryType type = cmStateEnums::UNINITIALIZED;
  275. if (cmState::ParseCacheEntry(entry, var, value, type)) {
  276. // The value is transformed if it is a filepath for example, so
  277. // we can't compare whether the value is already in the cache until
  278. // after we call AddCacheEntry.
  279. bool haveValue = false;
  280. std::string cachedValue;
  281. if (this->WarnUnusedCli) {
  282. if (const char* v = this->State->GetInitializedCacheValue(var)) {
  283. haveValue = true;
  284. cachedValue = v;
  285. }
  286. }
  287. this->AddCacheEntry(var, value.c_str(),
  288. "No help, variable specified on the command line.",
  289. type);
  290. if (this->WarnUnusedCli) {
  291. if (!haveValue ||
  292. cachedValue != this->State->GetInitializedCacheValue(var)) {
  293. this->WatchUnusedCli(var);
  294. }
  295. }
  296. } else {
  297. std::cerr << "Parse error in command line argument: " << arg << "\n"
  298. << "Should be: VAR:type=value\n";
  299. cmSystemTools::Error("No cmake script provided.");
  300. return false;
  301. }
  302. } else if (cmHasLiteralPrefix(arg, "-W")) {
  303. std::string entry = arg.substr(2);
  304. if (entry.empty()) {
  305. ++i;
  306. if (i < args.size()) {
  307. entry = args[i];
  308. } else {
  309. cmSystemTools::Error("-W must be followed with [no-]<name>.");
  310. return false;
  311. }
  312. }
  313. std::string name;
  314. bool foundNo = false;
  315. bool foundError = false;
  316. unsigned int nameStartPosition = 0;
  317. if (entry.find("no-", nameStartPosition) == 0) {
  318. foundNo = true;
  319. nameStartPosition += 3;
  320. }
  321. if (entry.find("error=", nameStartPosition) == 0) {
  322. foundError = true;
  323. nameStartPosition += 6;
  324. }
  325. name = entry.substr(nameStartPosition);
  326. if (name.empty()) {
  327. cmSystemTools::Error("No warning name provided.");
  328. return false;
  329. }
  330. if (!foundNo && !foundError) {
  331. // -W<name>
  332. this->DiagLevels[name] = std::max(this->DiagLevels[name], DIAG_WARN);
  333. } else if (foundNo && !foundError) {
  334. // -Wno<name>
  335. this->DiagLevels[name] = DIAG_IGNORE;
  336. } else if (!foundNo && foundError) {
  337. // -Werror=<name>
  338. this->DiagLevels[name] = DIAG_ERROR;
  339. } else {
  340. // -Wno-error=<name>
  341. this->DiagLevels[name] = std::min(this->DiagLevels[name], DIAG_WARN);
  342. }
  343. } else if (arg.find("-U", 0) == 0) {
  344. std::string entryPattern = arg.substr(2);
  345. if (entryPattern.empty()) {
  346. ++i;
  347. if (i < args.size()) {
  348. entryPattern = args[i];
  349. } else {
  350. cmSystemTools::Error("-U must be followed with VAR.");
  351. return false;
  352. }
  353. }
  354. cmsys::RegularExpression regex(
  355. cmsys::Glob::PatternToRegex(entryPattern, true, true).c_str());
  356. // go through all cache entries and collect the vars which will be
  357. // removed
  358. std::vector<std::string> entriesToDelete;
  359. std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
  360. for (std::string const& ck : cacheKeys) {
  361. cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck);
  362. if (t != cmStateEnums::STATIC) {
  363. if (regex.find(ck.c_str())) {
  364. entriesToDelete.push_back(ck);
  365. }
  366. }
  367. }
  368. // now remove them from the cache
  369. for (std::string const& currentEntry : entriesToDelete) {
  370. this->State->RemoveCacheEntry(currentEntry);
  371. }
  372. } else if (arg.find("-C", 0) == 0) {
  373. std::string path = arg.substr(2);
  374. if (path.empty()) {
  375. ++i;
  376. if (i < args.size()) {
  377. path = args[i];
  378. } else {
  379. cmSystemTools::Error("-C must be followed by a file name.");
  380. return false;
  381. }
  382. }
  383. std::cout << "loading initial cache file " << path << "\n";
  384. this->ReadListFile(args, path.c_str());
  385. } else if (arg.find("-P", 0) == 0) {
  386. i++;
  387. if (i >= args.size()) {
  388. cmSystemTools::Error("-P must be followed by a file name.");
  389. return false;
  390. }
  391. std::string path = args[i];
  392. if (path.empty()) {
  393. cmSystemTools::Error("No cmake script provided.");
  394. return false;
  395. }
  396. // Register fake project commands that hint misuse in script mode.
  397. GetProjectCommandsInScriptMode(this->State);
  398. this->ReadListFile(args, path.c_str());
  399. } else if (arg.find("--find-package", 0) == 0) {
  400. findPackageMode = true;
  401. }
  402. }
  403. if (findPackageMode) {
  404. return this->FindPackage(args);
  405. }
  406. return true;
  407. }
  408. void cmake::ReadListFile(const std::vector<std::string>& args,
  409. const char* path)
  410. {
  411. // if a generator was not yet created, temporarily create one
  412. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  413. bool created = false;
  414. // if a generator was not specified use a generic one
  415. if (!gg) {
  416. gg = new cmGlobalGenerator(this);
  417. created = true;
  418. }
  419. // read in the list file to fill the cache
  420. if (path) {
  421. this->CurrentSnapshot = this->State->Reset();
  422. std::string homeDir = this->GetHomeDirectory();
  423. std::string homeOutputDir = this->GetHomeOutputDirectory();
  424. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  425. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  426. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  427. snapshot.GetDirectory().SetCurrentBinary(
  428. cmSystemTools::GetCurrentWorkingDirectory());
  429. snapshot.GetDirectory().SetCurrentSource(
  430. cmSystemTools::GetCurrentWorkingDirectory());
  431. snapshot.SetDefaultDefinitions();
  432. cmMakefile mf(gg, snapshot);
  433. if (this->GetWorkingMode() != NORMAL_MODE) {
  434. std::string file(cmSystemTools::CollapseFullPath(path));
  435. cmSystemTools::ConvertToUnixSlashes(file);
  436. mf.SetScriptModeFile(file.c_str());
  437. mf.SetArgcArgv(args);
  438. }
  439. if (!mf.ReadListFile(path)) {
  440. cmSystemTools::Error("Error processing file: ", path);
  441. }
  442. this->SetHomeDirectory(homeDir);
  443. this->SetHomeOutputDirectory(homeOutputDir);
  444. }
  445. // free generic one if generated
  446. if (created) {
  447. delete gg;
  448. }
  449. }
  450. bool cmake::FindPackage(const std::vector<std::string>& args)
  451. {
  452. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  453. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  454. // if a generator was not yet created, temporarily create one
  455. cmGlobalGenerator* gg = new cmGlobalGenerator(this);
  456. this->SetGlobalGenerator(gg);
  457. cmStateSnapshot snapshot = this->GetCurrentSnapshot();
  458. snapshot.GetDirectory().SetCurrentBinary(
  459. cmSystemTools::GetCurrentWorkingDirectory());
  460. snapshot.GetDirectory().SetCurrentSource(
  461. cmSystemTools::GetCurrentWorkingDirectory());
  462. // read in the list file to fill the cache
  463. snapshot.SetDefaultDefinitions();
  464. cmMakefile* mf = new cmMakefile(gg, snapshot);
  465. gg->AddMakefile(mf);
  466. mf->SetArgcArgv(args);
  467. std::string systemFile = mf->GetModulesFile("CMakeFindPackageMode.cmake");
  468. mf->ReadListFile(systemFile.c_str());
  469. std::string language = mf->GetSafeDefinition("LANGUAGE");
  470. std::string mode = mf->GetSafeDefinition("MODE");
  471. std::string packageName = mf->GetSafeDefinition("NAME");
  472. bool packageFound = mf->IsOn("PACKAGE_FOUND");
  473. bool quiet = mf->IsOn("PACKAGE_QUIET");
  474. if (!packageFound) {
  475. if (!quiet) {
  476. printf("%s not found.\n", packageName.c_str());
  477. }
  478. } else if (mode == "EXIST") {
  479. if (!quiet) {
  480. printf("%s found.\n", packageName.c_str());
  481. }
  482. } else if (mode == "COMPILE") {
  483. std::string includes = mf->GetSafeDefinition("PACKAGE_INCLUDE_DIRS");
  484. std::vector<std::string> includeDirs;
  485. cmSystemTools::ExpandListArgument(includes, includeDirs);
  486. gg->CreateGenerationObjects();
  487. cmLocalGenerator* lg = gg->LocalGenerators[0];
  488. std::string includeFlags =
  489. lg->GetIncludeFlags(includeDirs, nullptr, language);
  490. std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
  491. printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
  492. } else if (mode == "LINK") {
  493. const char* targetName = "dummy";
  494. std::vector<std::string> srcs;
  495. cmTarget* tgt = mf->AddExecutable(targetName, srcs, true);
  496. tgt->SetProperty("LINKER_LANGUAGE", language.c_str());
  497. std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
  498. std::vector<std::string> libList;
  499. cmSystemTools::ExpandListArgument(libs, libList);
  500. for (std::string const& lib : libList) {
  501. tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
  502. }
  503. std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
  504. buildType = cmSystemTools::UpperCase(buildType);
  505. std::string linkLibs;
  506. std::string frameworkPath;
  507. std::string linkPath;
  508. std::string flags;
  509. std::string linkFlags;
  510. gg->CreateGenerationObjects();
  511. cmGeneratorTarget* gtgt = gg->FindGeneratorTarget(tgt->GetName());
  512. cmLocalGenerator* lg = gtgt->GetLocalGenerator();
  513. cmLinkLineComputer linkLineComputer(lg,
  514. lg->GetStateSnapshot().GetDirectory());
  515. lg->GetTargetFlags(&linkLineComputer, buildType, linkLibs, flags,
  516. linkFlags, frameworkPath, linkPath, gtgt);
  517. linkLibs = frameworkPath + linkPath + linkLibs;
  518. printf("%s\n", linkLibs.c_str());
  519. /* if ( use_win32 )
  520. {
  521. tgt->SetProperty("WIN32_EXECUTABLE", "ON");
  522. }
  523. if ( use_macbundle)
  524. {
  525. tgt->SetProperty("MACOSX_BUNDLE", "ON");
  526. }*/
  527. }
  528. // free generic one if generated
  529. // this->SetGlobalGenerator(0); // setting 0-pointer is not possible
  530. // delete gg; // this crashes inside the cmake instance
  531. return packageFound;
  532. }
  533. // Parse the args
  534. void cmake::SetArgs(const std::vector<std::string>& args,
  535. bool directoriesSetBefore)
  536. {
  537. bool directoriesSet = directoriesSetBefore;
  538. bool haveToolset = false;
  539. bool havePlatform = false;
  540. for (unsigned int i = 1; i < args.size(); ++i) {
  541. std::string const& arg = args[i];
  542. if (arg.find("-H", 0) == 0) {
  543. directoriesSet = true;
  544. std::string path = arg.substr(2);
  545. path = cmSystemTools::CollapseFullPath(path);
  546. cmSystemTools::ConvertToUnixSlashes(path);
  547. this->SetHomeDirectory(path);
  548. } else if (arg.find("-S", 0) == 0) {
  549. // There is no local generate anymore. Ignore -S option.
  550. } else if (arg.find("-O", 0) == 0) {
  551. // There is no local generate anymore. Ignore -O option.
  552. } else if (arg.find("-B", 0) == 0) {
  553. directoriesSet = true;
  554. std::string path = arg.substr(2);
  555. path = cmSystemTools::CollapseFullPath(path);
  556. cmSystemTools::ConvertToUnixSlashes(path);
  557. this->SetHomeOutputDirectory(path);
  558. } else if ((i < args.size() - 2) &&
  559. (arg.find("--check-build-system", 0) == 0)) {
  560. this->CheckBuildSystemArgument = args[++i];
  561. this->ClearBuildSystem = (atoi(args[++i].c_str()) > 0);
  562. } else if ((i < args.size() - 1) &&
  563. (arg.find("--check-stamp-file", 0) == 0)) {
  564. this->CheckStampFile = args[++i];
  565. } else if ((i < args.size() - 1) &&
  566. (arg.find("--check-stamp-list", 0) == 0)) {
  567. this->CheckStampList = args[++i];
  568. }
  569. #if defined(CMAKE_HAVE_VS_GENERATORS)
  570. else if ((i < args.size() - 1) &&
  571. (arg.find("--vs-solution-file", 0) == 0)) {
  572. this->VSSolutionFile = args[++i];
  573. }
  574. #endif
  575. else if (arg.find("-D", 0) == 0) {
  576. // skip for now
  577. } else if (arg.find("-U", 0) == 0) {
  578. // skip for now
  579. } else if (arg.find("-C", 0) == 0) {
  580. // skip for now
  581. } else if (arg.find("-P", 0) == 0) {
  582. // skip for now
  583. i++;
  584. } else if (arg.find("--find-package", 0) == 0) {
  585. // skip for now
  586. i++;
  587. } else if (arg.find("-W", 0) == 0) {
  588. // skip for now
  589. } else if (arg.find("--graphviz=", 0) == 0) {
  590. std::string path = arg.substr(strlen("--graphviz="));
  591. path = cmSystemTools::CollapseFullPath(path);
  592. cmSystemTools::ConvertToUnixSlashes(path);
  593. this->GraphVizFile = path;
  594. if (this->GraphVizFile.empty()) {
  595. cmSystemTools::Error("No file specified for --graphviz");
  596. }
  597. } else if (arg.find("--debug-trycompile", 0) == 0) {
  598. std::cout << "debug trycompile on\n";
  599. this->DebugTryCompileOn();
  600. } else if (arg.find("--debug-output", 0) == 0) {
  601. std::cout << "Running with debug output on.\n";
  602. this->SetDebugOutputOn(true);
  603. } else if (arg.find("--trace-expand", 0) == 0) {
  604. std::cout << "Running with expanded trace output on.\n";
  605. this->SetTrace(true);
  606. this->SetTraceExpand(true);
  607. } else if (arg.find("--trace-source=", 0) == 0) {
  608. std::string file = arg.substr(strlen("--trace-source="));
  609. cmSystemTools::ConvertToUnixSlashes(file);
  610. this->AddTraceSource(file);
  611. this->SetTrace(true);
  612. } else if (arg.find("--trace", 0) == 0) {
  613. std::cout << "Running with trace output on.\n";
  614. this->SetTrace(true);
  615. this->SetTraceExpand(false);
  616. } else if (arg.find("--warn-uninitialized", 0) == 0) {
  617. std::cout << "Warn about uninitialized values.\n";
  618. this->SetWarnUninitialized(true);
  619. } else if (arg.find("--warn-unused-vars", 0) == 0) {
  620. std::cout << "Finding unused variables.\n";
  621. this->SetWarnUnused(true);
  622. } else if (arg.find("--no-warn-unused-cli", 0) == 0) {
  623. std::cout << "Not searching for unused variables given on the "
  624. << "command line.\n";
  625. this->SetWarnUnusedCli(false);
  626. } else if (arg.find("--check-system-vars", 0) == 0) {
  627. std::cout << "Also check system files when warning about unused and "
  628. << "uninitialized variables.\n";
  629. this->SetCheckSystemVars(true);
  630. } else if (arg.find("-A", 0) == 0) {
  631. std::string value = arg.substr(2);
  632. if (value.empty()) {
  633. ++i;
  634. if (i >= args.size()) {
  635. cmSystemTools::Error("No platform specified for -A");
  636. return;
  637. }
  638. value = args[i];
  639. }
  640. if (havePlatform) {
  641. cmSystemTools::Error("Multiple -A options not allowed");
  642. return;
  643. }
  644. this->GeneratorPlatform = value;
  645. havePlatform = true;
  646. } else if (arg.find("-T", 0) == 0) {
  647. std::string value = arg.substr(2);
  648. if (value.empty()) {
  649. ++i;
  650. if (i >= args.size()) {
  651. cmSystemTools::Error("No toolset specified for -T");
  652. return;
  653. }
  654. value = args[i];
  655. }
  656. if (haveToolset) {
  657. cmSystemTools::Error("Multiple -T options not allowed");
  658. return;
  659. }
  660. this->GeneratorToolset = value;
  661. haveToolset = true;
  662. } else if (arg.find("-G", 0) == 0) {
  663. std::string value = arg.substr(2);
  664. if (value.empty()) {
  665. ++i;
  666. if (i >= args.size()) {
  667. cmSystemTools::Error("No generator specified for -G");
  668. this->PrintGeneratorList();
  669. return;
  670. }
  671. value = args[i];
  672. }
  673. cmGlobalGenerator* gen = this->CreateGlobalGenerator(value);
  674. if (!gen) {
  675. const char* kdevError = nullptr;
  676. if (value.find("KDevelop3", 0) != std::string::npos) {
  677. kdevError = "\nThe KDevelop3 generator is not supported anymore.";
  678. }
  679. cmSystemTools::Error("Could not create named generator ",
  680. value.c_str(), kdevError);
  681. this->PrintGeneratorList();
  682. } else {
  683. this->SetGlobalGenerator(gen);
  684. }
  685. }
  686. // no option assume it is the path to the source
  687. else {
  688. directoriesSet = true;
  689. this->SetDirectoriesFromFile(arg.c_str());
  690. }
  691. }
  692. if (!directoriesSet) {
  693. this->SetHomeOutputDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  694. this->SetHomeDirectory(cmSystemTools::GetCurrentWorkingDirectory());
  695. }
  696. }
  697. void cmake::SetDirectoriesFromFile(const char* arg)
  698. {
  699. // Check if the argument refers to a CMakeCache.txt or
  700. // CMakeLists.txt file.
  701. std::string listPath;
  702. std::string cachePath;
  703. bool argIsFile = false;
  704. if (cmSystemTools::FileIsDirectory(arg)) {
  705. std::string path = cmSystemTools::CollapseFullPath(arg);
  706. cmSystemTools::ConvertToUnixSlashes(path);
  707. std::string cacheFile = path;
  708. cacheFile += "/CMakeCache.txt";
  709. std::string listFile = path;
  710. listFile += "/CMakeLists.txt";
  711. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  712. cachePath = path;
  713. }
  714. if (cmSystemTools::FileExists(listFile.c_str())) {
  715. listPath = path;
  716. }
  717. } else if (cmSystemTools::FileExists(arg)) {
  718. argIsFile = true;
  719. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  720. std::string name = cmSystemTools::GetFilenameName(fullPath);
  721. name = cmSystemTools::LowerCase(name);
  722. if (name == "cmakecache.txt") {
  723. cachePath = cmSystemTools::GetFilenamePath(fullPath);
  724. } else if (name == "cmakelists.txt") {
  725. listPath = cmSystemTools::GetFilenamePath(fullPath);
  726. }
  727. } else {
  728. // Specified file or directory does not exist. Try to set things
  729. // up to produce a meaningful error message.
  730. std::string fullPath = cmSystemTools::CollapseFullPath(arg);
  731. std::string name = cmSystemTools::GetFilenameName(fullPath);
  732. name = cmSystemTools::LowerCase(name);
  733. if (name == "cmakecache.txt" || name == "cmakelists.txt") {
  734. argIsFile = true;
  735. listPath = cmSystemTools::GetFilenamePath(fullPath);
  736. } else {
  737. listPath = fullPath;
  738. }
  739. }
  740. // If there is a CMakeCache.txt file, use its settings.
  741. if (!cachePath.empty()) {
  742. if (this->LoadCache(cachePath)) {
  743. const char* existingValue =
  744. this->State->GetCacheEntryValue("CMAKE_HOME_DIRECTORY");
  745. if (existingValue) {
  746. this->SetHomeOutputDirectory(cachePath);
  747. this->SetHomeDirectory(existingValue);
  748. return;
  749. }
  750. }
  751. }
  752. // If there is a CMakeLists.txt file, use it as the source tree.
  753. if (!listPath.empty()) {
  754. this->SetHomeDirectory(listPath);
  755. if (argIsFile) {
  756. // Source CMakeLists.txt file given. It was probably dropped
  757. // onto the executable in a GUI. Default to an in-source build.
  758. this->SetHomeOutputDirectory(listPath);
  759. } else {
  760. // Source directory given on command line. Use current working
  761. // directory as build tree.
  762. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  763. this->SetHomeOutputDirectory(cwd);
  764. }
  765. return;
  766. }
  767. // We didn't find a CMakeLists.txt or CMakeCache.txt file from the
  768. // argument. Assume it is the path to the source tree, and use the
  769. // current working directory as the build tree.
  770. std::string full = cmSystemTools::CollapseFullPath(arg);
  771. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  772. this->SetHomeDirectory(full);
  773. this->SetHomeOutputDirectory(cwd);
  774. }
  775. // at the end of this CMAKE_ROOT and CMAKE_COMMAND should be added to the
  776. // cache
  777. int cmake::AddCMakePaths()
  778. {
  779. // Save the value in the cache
  780. this->AddCacheEntry("CMAKE_COMMAND",
  781. cmSystemTools::GetCMakeCommand().c_str(),
  782. "Path to CMake executable.", cmStateEnums::INTERNAL);
  783. #ifdef CMAKE_BUILD_WITH_CMAKE
  784. this->AddCacheEntry(
  785. "CMAKE_CTEST_COMMAND", cmSystemTools::GetCTestCommand().c_str(),
  786. "Path to ctest program executable.", cmStateEnums::INTERNAL);
  787. this->AddCacheEntry(
  788. "CMAKE_CPACK_COMMAND", cmSystemTools::GetCPackCommand().c_str(),
  789. "Path to cpack program executable.", cmStateEnums::INTERNAL);
  790. #endif
  791. if (!cmSystemTools::FileExists(
  792. (cmSystemTools::GetCMakeRoot() + "/Modules/CMake.cmake").c_str())) {
  793. // couldn't find modules
  794. cmSystemTools::Error(
  795. "Could not find CMAKE_ROOT !!!\n"
  796. "CMake has most likely not been installed correctly.\n"
  797. "Modules directory not found in\n",
  798. cmSystemTools::GetCMakeRoot().c_str());
  799. return 0;
  800. }
  801. this->AddCacheEntry("CMAKE_ROOT", cmSystemTools::GetCMakeRoot().c_str(),
  802. "Path to CMake installation.", cmStateEnums::INTERNAL);
  803. return 1;
  804. }
  805. void cmake::AddDefaultExtraGenerators()
  806. {
  807. #if defined(CMAKE_BUILD_WITH_CMAKE)
  808. this->ExtraGenerators.push_back(cmExtraCodeBlocksGenerator::GetFactory());
  809. this->ExtraGenerators.push_back(cmExtraCodeLiteGenerator::GetFactory());
  810. this->ExtraGenerators.push_back(cmExtraSublimeTextGenerator::GetFactory());
  811. this->ExtraGenerators.push_back(cmExtraKateGenerator::GetFactory());
  812. #ifdef CMAKE_USE_ECLIPSE
  813. this->ExtraGenerators.push_back(cmExtraEclipseCDT4Generator::GetFactory());
  814. #endif
  815. #endif
  816. }
  817. void cmake::GetRegisteredGenerators(
  818. std::vector<GeneratorInfo>& generators) const
  819. {
  820. for (cmGlobalGeneratorFactory* gen : this->Generators) {
  821. std::vector<std::string> names;
  822. gen->GetGenerators(names);
  823. for (std::string const& name : names) {
  824. GeneratorInfo info;
  825. info.supportsToolset = gen->SupportsToolset();
  826. info.supportsPlatform = gen->SupportsPlatform();
  827. info.name = name;
  828. info.baseName = name;
  829. info.isAlias = false;
  830. generators.push_back(std::move(info));
  831. }
  832. }
  833. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  834. const std::vector<std::string> genList =
  835. eg->GetSupportedGlobalGenerators();
  836. for (std::string const& gen : genList) {
  837. GeneratorInfo info;
  838. info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  839. gen, eg->GetName());
  840. info.baseName = gen;
  841. info.extraName = eg->GetName();
  842. info.supportsPlatform = false;
  843. info.supportsToolset = false;
  844. info.isAlias = false;
  845. generators.push_back(std::move(info));
  846. }
  847. for (std::string const& a : eg->Aliases) {
  848. GeneratorInfo info;
  849. info.name = a;
  850. if (!genList.empty()) {
  851. info.baseName = genList.at(0);
  852. }
  853. info.extraName = eg->GetName();
  854. info.supportsPlatform = false;
  855. info.supportsToolset = false;
  856. info.isAlias = true;
  857. generators.push_back(std::move(info));
  858. }
  859. }
  860. }
  861. static std::pair<cmExternalMakefileProjectGenerator*, std::string>
  862. createExtraGenerator(
  863. const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
  864. const std::string& name)
  865. {
  866. for (cmExternalMakefileProjectGeneratorFactory* i : in) {
  867. const std::vector<std::string> generators =
  868. i->GetSupportedGlobalGenerators();
  869. if (i->GetName() == name) { // Match aliases
  870. return std::make_pair(i->CreateExternalMakefileProjectGenerator(),
  871. generators.at(0));
  872. }
  873. for (std::string const& g : generators) {
  874. const std::string fullName =
  875. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  876. g, i->GetName());
  877. if (fullName == name) {
  878. return std::make_pair(i->CreateExternalMakefileProjectGenerator(), g);
  879. }
  880. }
  881. }
  882. return std::make_pair(
  883. static_cast<cmExternalMakefileProjectGenerator*>(nullptr), name);
  884. }
  885. cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
  886. {
  887. std::pair<cmExternalMakefileProjectGenerator*, std::string> extra =
  888. createExtraGenerator(this->ExtraGenerators, gname);
  889. cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
  890. const std::string name = extra.second;
  891. cmGlobalGenerator* generator = nullptr;
  892. for (cmGlobalGeneratorFactory* g : this->Generators) {
  893. generator = g->CreateGlobalGenerator(name, this);
  894. if (generator) {
  895. break;
  896. }
  897. }
  898. if (generator) {
  899. generator->SetExternalMakefileProjectGenerator(extraGenerator);
  900. } else {
  901. delete extraGenerator;
  902. }
  903. return generator;
  904. }
  905. void cmake::SetHomeDirectory(const std::string& dir)
  906. {
  907. this->State->SetSourceDirectory(dir);
  908. if (this->CurrentSnapshot.IsValid()) {
  909. this->CurrentSnapshot.SetDefinition("CMAKE_SOURCE_DIR", dir);
  910. }
  911. }
  912. const char* cmake::GetHomeDirectory() const
  913. {
  914. return this->State->GetSourceDirectory();
  915. }
  916. void cmake::SetHomeOutputDirectory(const std::string& dir)
  917. {
  918. this->State->SetBinaryDirectory(dir);
  919. if (this->CurrentSnapshot.IsValid()) {
  920. this->CurrentSnapshot.SetDefinition("CMAKE_BINARY_DIR", dir);
  921. }
  922. }
  923. const char* cmake::GetHomeOutputDirectory() const
  924. {
  925. return this->State->GetBinaryDirectory();
  926. }
  927. std::string cmake::FindCacheFile(const std::string& binaryDir)
  928. {
  929. std::string cachePath = binaryDir;
  930. cmSystemTools::ConvertToUnixSlashes(cachePath);
  931. std::string cacheFile = cachePath;
  932. cacheFile += "/CMakeCache.txt";
  933. if (!cmSystemTools::FileExists(cacheFile.c_str())) {
  934. // search in parent directories for cache
  935. std::string cmakeFiles = cachePath;
  936. cmakeFiles += "/CMakeFiles";
  937. if (cmSystemTools::FileExists(cmakeFiles.c_str())) {
  938. std::string cachePathFound =
  939. cmSystemTools::FileExistsInParentDirectories("CMakeCache.txt",
  940. cachePath.c_str(), "/");
  941. if (!cachePathFound.empty()) {
  942. cachePath = cmSystemTools::GetFilenamePath(cachePathFound);
  943. }
  944. }
  945. }
  946. return cachePath;
  947. }
  948. void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
  949. {
  950. if (!gg) {
  951. cmSystemTools::Error("Error SetGlobalGenerator called with null");
  952. return;
  953. }
  954. // delete the old generator
  955. if (this->GlobalGenerator) {
  956. delete this->GlobalGenerator;
  957. // restore the original environment variables CXX and CC
  958. // Restore CC
  959. std::string env = "CC=";
  960. if (!this->CCEnvironment.empty()) {
  961. env += this->CCEnvironment;
  962. }
  963. cmSystemTools::PutEnv(env);
  964. env = "CXX=";
  965. if (!this->CXXEnvironment.empty()) {
  966. env += this->CXXEnvironment;
  967. }
  968. cmSystemTools::PutEnv(env);
  969. }
  970. // set the new
  971. this->GlobalGenerator = gg;
  972. // set the global flag for unix style paths on cmSystemTools as soon as
  973. // the generator is set. This allows gmake to be used on windows.
  974. cmSystemTools::SetForceUnixPaths(this->GlobalGenerator->GetForceUnixPaths());
  975. // Save the environment variables CXX and CC
  976. if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
  977. this->CXXEnvironment.clear();
  978. }
  979. if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
  980. this->CCEnvironment.clear();
  981. }
  982. }
  983. int cmake::DoPreConfigureChecks()
  984. {
  985. // Make sure the Source directory contains a CMakeLists.txt file.
  986. std::string srcList = this->GetHomeDirectory();
  987. srcList += "/CMakeLists.txt";
  988. if (!cmSystemTools::FileExists(srcList.c_str())) {
  989. std::ostringstream err;
  990. if (cmSystemTools::FileIsDirectory(this->GetHomeDirectory())) {
  991. err << "The source directory \"" << this->GetHomeDirectory()
  992. << "\" does not appear to contain CMakeLists.txt.\n";
  993. } else if (cmSystemTools::FileExists(this->GetHomeDirectory())) {
  994. err << "The source directory \"" << this->GetHomeDirectory()
  995. << "\" is a file, not a directory.\n";
  996. } else {
  997. err << "The source directory \"" << this->GetHomeDirectory()
  998. << "\" does not exist.\n";
  999. }
  1000. err << "Specify --help for usage, or press the help button on the CMake "
  1001. "GUI.";
  1002. cmSystemTools::Error(err.str().c_str());
  1003. return -2;
  1004. }
  1005. // do a sanity check on some values
  1006. if (this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY")) {
  1007. std::string cacheStart =
  1008. this->State->GetInitializedCacheValue("CMAKE_HOME_DIRECTORY");
  1009. cacheStart += "/CMakeLists.txt";
  1010. std::string currentStart = this->GetHomeDirectory();
  1011. currentStart += "/CMakeLists.txt";
  1012. if (!cmSystemTools::SameFile(cacheStart, currentStart)) {
  1013. std::string message = "The source \"";
  1014. message += currentStart;
  1015. message += "\" does not match the source \"";
  1016. message += cacheStart;
  1017. message += "\" used to generate cache. ";
  1018. message += "Re-run cmake with a different source directory.";
  1019. cmSystemTools::Error(message.c_str());
  1020. return -2;
  1021. }
  1022. } else {
  1023. return 0;
  1024. }
  1025. return 1;
  1026. }
  1027. struct SaveCacheEntry
  1028. {
  1029. std::string key;
  1030. std::string value;
  1031. std::string help;
  1032. cmStateEnums::CacheEntryType type;
  1033. };
  1034. int cmake::HandleDeleteCacheVariables(const std::string& var)
  1035. {
  1036. std::vector<std::string> argsSplit;
  1037. cmSystemTools::ExpandListArgument(std::string(var), argsSplit, true);
  1038. // erase the property to avoid infinite recursion
  1039. this->State->SetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_", "");
  1040. if (this->State->GetIsInTryCompile()) {
  1041. return 0;
  1042. }
  1043. std::vector<SaveCacheEntry> saved;
  1044. std::ostringstream warning;
  1045. /* clang-format off */
  1046. warning
  1047. << "You have changed variables that require your cache to be deleted.\n"
  1048. << "Configure will be re-run and you may have to reset some variables.\n"
  1049. << "The following variables have changed:\n";
  1050. /* clang-format on */
  1051. for (std::vector<std::string>::iterator i = argsSplit.begin();
  1052. i != argsSplit.end(); ++i) {
  1053. SaveCacheEntry save;
  1054. save.key = *i;
  1055. warning << *i << "= ";
  1056. i++;
  1057. save.value = *i;
  1058. warning << *i << "\n";
  1059. const char* existingValue = this->State->GetCacheEntryValue(save.key);
  1060. if (existingValue) {
  1061. save.type = this->State->GetCacheEntryType(save.key);
  1062. if (const char* help =
  1063. this->State->GetCacheEntryProperty(save.key, "HELPSTRING")) {
  1064. save.help = help;
  1065. }
  1066. }
  1067. saved.push_back(std::move(save));
  1068. }
  1069. // remove the cache
  1070. this->DeleteCache(this->GetHomeOutputDirectory());
  1071. // load the empty cache
  1072. this->LoadCache();
  1073. // restore the changed compilers
  1074. for (SaveCacheEntry const& i : saved) {
  1075. this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
  1076. }
  1077. cmSystemTools::Message(warning.str().c_str());
  1078. // avoid reconfigure if there were errors
  1079. if (!cmSystemTools::GetErrorOccuredFlag()) {
  1080. // re-run configure
  1081. return this->Configure();
  1082. }
  1083. return 0;
  1084. }
  1085. int cmake::Configure()
  1086. {
  1087. DiagLevel diagLevel;
  1088. if (this->DiagLevels.count("deprecated") == 1) {
  1089. diagLevel = this->DiagLevels["deprecated"];
  1090. if (diagLevel == DIAG_IGNORE) {
  1091. this->SetSuppressDeprecatedWarnings(true);
  1092. this->SetDeprecatedWarningsAsErrors(false);
  1093. } else if (diagLevel == DIAG_WARN) {
  1094. this->SetSuppressDeprecatedWarnings(false);
  1095. this->SetDeprecatedWarningsAsErrors(false);
  1096. } else if (diagLevel == DIAG_ERROR) {
  1097. this->SetSuppressDeprecatedWarnings(false);
  1098. this->SetDeprecatedWarningsAsErrors(true);
  1099. }
  1100. }
  1101. if (this->DiagLevels.count("dev") == 1) {
  1102. bool setDeprecatedVariables = false;
  1103. const char* cachedWarnDeprecated =
  1104. this->State->GetCacheEntryValue("CMAKE_WARN_DEPRECATED");
  1105. const char* cachedErrorDeprecated =
  1106. this->State->GetCacheEntryValue("CMAKE_ERROR_DEPRECATED");
  1107. // don't overwrite deprecated warning setting from a previous invocation
  1108. if (!cachedWarnDeprecated && !cachedErrorDeprecated) {
  1109. setDeprecatedVariables = true;
  1110. }
  1111. diagLevel = this->DiagLevels["dev"];
  1112. if (diagLevel == DIAG_IGNORE) {
  1113. this->SetSuppressDevWarnings(true);
  1114. this->SetDevWarningsAsErrors(false);
  1115. if (setDeprecatedVariables) {
  1116. this->SetSuppressDeprecatedWarnings(true);
  1117. this->SetDeprecatedWarningsAsErrors(false);
  1118. }
  1119. } else if (diagLevel == DIAG_WARN) {
  1120. this->SetSuppressDevWarnings(false);
  1121. this->SetDevWarningsAsErrors(false);
  1122. if (setDeprecatedVariables) {
  1123. this->SetSuppressDeprecatedWarnings(false);
  1124. this->SetDeprecatedWarningsAsErrors(false);
  1125. }
  1126. } else if (diagLevel == DIAG_ERROR) {
  1127. this->SetSuppressDevWarnings(false);
  1128. this->SetDevWarningsAsErrors(true);
  1129. if (setDeprecatedVariables) {
  1130. this->SetSuppressDeprecatedWarnings(false);
  1131. this->SetDeprecatedWarningsAsErrors(true);
  1132. }
  1133. }
  1134. }
  1135. int ret = this->ActualConfigure();
  1136. const char* delCacheVars =
  1137. this->State->GetGlobalProperty("__CMAKE_DELETE_CACHE_CHANGE_VARS_");
  1138. if (delCacheVars && delCacheVars[0] != 0) {
  1139. return this->HandleDeleteCacheVariables(delCacheVars);
  1140. }
  1141. return ret;
  1142. }
  1143. int cmake::ActualConfigure()
  1144. {
  1145. // Construct right now our path conversion table before it's too late:
  1146. this->UpdateConversionPathTable();
  1147. this->CleanupCommandsAndMacros();
  1148. int res = 0;
  1149. if (this->GetWorkingMode() == NORMAL_MODE) {
  1150. res = this->DoPreConfigureChecks();
  1151. }
  1152. if (res < 0) {
  1153. return -2;
  1154. }
  1155. if (!res) {
  1156. this->AddCacheEntry(
  1157. "CMAKE_HOME_DIRECTORY", this->GetHomeDirectory(),
  1158. "Source directory with the top level CMakeLists.txt file for this "
  1159. "project",
  1160. cmStateEnums::INTERNAL);
  1161. }
  1162. // no generator specified on the command line
  1163. if (!this->GlobalGenerator) {
  1164. const char* genName =
  1165. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1166. const char* extraGenName =
  1167. this->State->GetInitializedCacheValue("CMAKE_EXTRA_GENERATOR");
  1168. if (genName) {
  1169. std::string fullName =
  1170. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
  1171. genName, extraGenName ? extraGenName : "");
  1172. this->GlobalGenerator = this->CreateGlobalGenerator(fullName);
  1173. }
  1174. if (this->GlobalGenerator) {
  1175. // set the global flag for unix style paths on cmSystemTools as
  1176. // soon as the generator is set. This allows gmake to be used
  1177. // on windows.
  1178. cmSystemTools::SetForceUnixPaths(
  1179. this->GlobalGenerator->GetForceUnixPaths());
  1180. } else {
  1181. this->CreateDefaultGlobalGenerator();
  1182. }
  1183. if (!this->GlobalGenerator) {
  1184. cmSystemTools::Error("Could not create generator");
  1185. return -1;
  1186. }
  1187. }
  1188. const char* genName =
  1189. this->State->GetInitializedCacheValue("CMAKE_GENERATOR");
  1190. if (genName) {
  1191. if (!this->GlobalGenerator->MatchesGeneratorName(genName)) {
  1192. std::string message = "Error: generator : ";
  1193. message += this->GlobalGenerator->GetName();
  1194. message += "\nDoes not match the generator used previously: ";
  1195. message += genName;
  1196. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1197. "directory or choose a different binary directory.";
  1198. cmSystemTools::Error(message.c_str());
  1199. return -2;
  1200. }
  1201. }
  1202. if (!this->State->GetInitializedCacheValue("CMAKE_GENERATOR")) {
  1203. this->AddCacheEntry("CMAKE_GENERATOR",
  1204. this->GlobalGenerator->GetName().c_str(),
  1205. "Name of generator.", cmStateEnums::INTERNAL);
  1206. this->AddCacheEntry("CMAKE_EXTRA_GENERATOR",
  1207. this->GlobalGenerator->GetExtraGeneratorName().c_str(),
  1208. "Name of external makefile project generator.",
  1209. cmStateEnums::INTERNAL);
  1210. }
  1211. if (const char* instance =
  1212. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_INSTANCE")) {
  1213. if (!this->GeneratorInstance.empty() &&
  1214. this->GeneratorInstance != instance) {
  1215. std::string message = "Error: generator instance: ";
  1216. message += this->GeneratorInstance;
  1217. message += "\nDoes not match the instance used previously: ";
  1218. message += instance;
  1219. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1220. "directory or choose a different binary directory.";
  1221. cmSystemTools::Error(message.c_str());
  1222. return -2;
  1223. }
  1224. } else {
  1225. this->AddCacheEntry(
  1226. "CMAKE_GENERATOR_INSTANCE", this->GeneratorInstance.c_str(),
  1227. "Generator instance identifier.", cmStateEnums::INTERNAL);
  1228. }
  1229. if (const char* platformName =
  1230. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
  1231. if (!this->GeneratorPlatform.empty() &&
  1232. this->GeneratorPlatform != platformName) {
  1233. std::string message = "Error: generator platform: ";
  1234. message += this->GeneratorPlatform;
  1235. message += "\nDoes not match the platform used previously: ";
  1236. message += platformName;
  1237. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1238. "directory or choose a different binary directory.";
  1239. cmSystemTools::Error(message.c_str());
  1240. return -2;
  1241. }
  1242. } else {
  1243. this->AddCacheEntry("CMAKE_GENERATOR_PLATFORM",
  1244. this->GeneratorPlatform.c_str(),
  1245. "Name of generator platform.", cmStateEnums::INTERNAL);
  1246. }
  1247. if (const char* tsName =
  1248. this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
  1249. if (!this->GeneratorToolset.empty() && this->GeneratorToolset != tsName) {
  1250. std::string message = "Error: generator toolset: ";
  1251. message += this->GeneratorToolset;
  1252. message += "\nDoes not match the toolset used previously: ";
  1253. message += tsName;
  1254. message += "\nEither remove the CMakeCache.txt file and CMakeFiles "
  1255. "directory or choose a different binary directory.";
  1256. cmSystemTools::Error(message.c_str());
  1257. return -2;
  1258. }
  1259. } else {
  1260. this->AddCacheEntry("CMAKE_GENERATOR_TOOLSET",
  1261. this->GeneratorToolset.c_str(),
  1262. "Name of generator toolset.", cmStateEnums::INTERNAL);
  1263. }
  1264. // reset any system configuration information, except for when we are
  1265. // InTryCompile. With TryCompile the system info is taken from the parent's
  1266. // info to save time
  1267. if (!this->State->GetIsInTryCompile()) {
  1268. this->GlobalGenerator->ClearEnabledLanguages();
  1269. this->TruncateOutputLog("CMakeOutput.log");
  1270. this->TruncateOutputLog("CMakeError.log");
  1271. }
  1272. // actually do the configure
  1273. this->GlobalGenerator->Configure();
  1274. // Before saving the cache
  1275. // if the project did not define one of the entries below, add them now
  1276. // so users can edit the values in the cache:
  1277. // We used to always present LIBRARY_OUTPUT_PATH and
  1278. // EXECUTABLE_OUTPUT_PATH. They are now documented as old-style and
  1279. // should no longer be used. Therefore we present them only if the
  1280. // project requires compatibility with CMake 2.4. We detect this
  1281. // here by looking for the old CMAKE_BACKWARDS_COMPATIBILITY
  1282. // variable created when CMP0001 is not set to NEW.
  1283. if (this->State->GetInitializedCacheValue("CMAKE_BACKWARDS_COMPATIBILITY")) {
  1284. if (!this->State->GetInitializedCacheValue("LIBRARY_OUTPUT_PATH")) {
  1285. this->AddCacheEntry(
  1286. "LIBRARY_OUTPUT_PATH", "",
  1287. "Single output directory for building all libraries.",
  1288. cmStateEnums::PATH);
  1289. }
  1290. if (!this->State->GetInitializedCacheValue("EXECUTABLE_OUTPUT_PATH")) {
  1291. this->AddCacheEntry(
  1292. "EXECUTABLE_OUTPUT_PATH", "",
  1293. "Single output directory for building all executables.",
  1294. cmStateEnums::PATH);
  1295. }
  1296. }
  1297. cmMakefile* mf = this->GlobalGenerator->GetMakefiles()[0];
  1298. if (mf->IsOn("CTEST_USE_LAUNCHERS") &&
  1299. !this->State->GetGlobalProperty("RULE_LAUNCH_COMPILE")) {
  1300. cmSystemTools::Error(
  1301. "CTEST_USE_LAUNCHERS is enabled, but the "
  1302. "RULE_LAUNCH_COMPILE global property is not defined.\n"
  1303. "Did you forget to include(CTest) in the toplevel "
  1304. "CMakeLists.txt ?");
  1305. }
  1306. // only save the cache if there were no fatal errors
  1307. if (this->GetWorkingMode() == NORMAL_MODE) {
  1308. this->SaveCache(this->GetHomeOutputDirectory());
  1309. }
  1310. if (cmSystemTools::GetErrorOccuredFlag()) {
  1311. return -1;
  1312. }
  1313. return 0;
  1314. }
  1315. void cmake::CreateDefaultGlobalGenerator()
  1316. {
  1317. #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(CMAKE_BOOT_MINGW)
  1318. std::string found;
  1319. // Try to find the newest VS installed on the computer and
  1320. // use that as a default if -G is not specified
  1321. const std::string vsregBase = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\";
  1322. static const char* const vsVariants[] = {
  1323. /* clang-format needs this comment to break after the opening brace */
  1324. "VisualStudio\\", "VCExpress\\", "WDExpress\\"
  1325. };
  1326. struct VSVersionedGenerator
  1327. {
  1328. const char* MSVersion;
  1329. const char* GeneratorName;
  1330. };
  1331. static VSVersionedGenerator const vsGenerators[] = {
  1332. { "15.0", "Visual Studio 15 2017" }, //
  1333. { "14.0", "Visual Studio 14 2015" }, //
  1334. { "12.0", "Visual Studio 12 2013" }, //
  1335. { "11.0", "Visual Studio 11 2012" }, //
  1336. { "10.0", "Visual Studio 10 2010" }, //
  1337. { "9.0", "Visual Studio 9 2008" }, //
  1338. { "8.0", "Visual Studio 8 2005" }
  1339. };
  1340. static const char* const vsEntries[] = {
  1341. "\\Setup\\VC;ProductDir", //
  1342. ";InstallDir" //
  1343. };
  1344. cmVSSetupAPIHelper vsSetupAPIHelper;
  1345. if (vsSetupAPIHelper.IsVS2017Installed()) {
  1346. found = "Visual Studio 15 2017";
  1347. } else {
  1348. for (VSVersionedGenerator const* g = cm::cbegin(vsGenerators);
  1349. found.empty() && g != cm::cend(vsGenerators); ++g) {
  1350. for (const char* const* v = cm::cbegin(vsVariants);
  1351. found.empty() && v != cm::cend(vsVariants); ++v) {
  1352. for (const char* const* e = cm::cbegin(vsEntries);
  1353. found.empty() && e != cm::cend(vsEntries); ++e) {
  1354. std::string const reg = vsregBase + *v + g->MSVersion + *e;
  1355. std::string dir;
  1356. if (cmSystemTools::ReadRegistryValue(reg, dir,
  1357. cmSystemTools::KeyWOW64_32) &&
  1358. cmSystemTools::PathExists(dir)) {
  1359. found = g->GeneratorName;
  1360. }
  1361. }
  1362. }
  1363. }
  1364. }
  1365. cmGlobalGenerator* gen = this->CreateGlobalGenerator(found);
  1366. if (!gen) {
  1367. gen = new cmGlobalNMakeMakefileGenerator(this);
  1368. }
  1369. this->SetGlobalGenerator(gen);
  1370. std::cout << "-- Building for: " << gen->GetName() << "\n";
  1371. #else
  1372. this->SetGlobalGenerator(new cmGlobalUnixMakefileGenerator3(this));
  1373. #endif
  1374. }
  1375. void cmake::PreLoadCMakeFiles()
  1376. {
  1377. std::vector<std::string> args;
  1378. std::string pre_load = this->GetHomeDirectory();
  1379. if (!pre_load.empty()) {
  1380. pre_load += "/PreLoad.cmake";
  1381. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1382. this->ReadListFile(args, pre_load.c_str());
  1383. }
  1384. }
  1385. pre_load = this->GetHomeOutputDirectory();
  1386. if (!pre_load.empty()) {
  1387. pre_load += "/PreLoad.cmake";
  1388. if (cmSystemTools::FileExists(pre_load.c_str())) {
  1389. this->ReadListFile(args, pre_load.c_str());
  1390. }
  1391. }
  1392. }
  1393. // handle a command line invocation
  1394. int cmake::Run(const std::vector<std::string>& args, bool noconfigure)
  1395. {
  1396. // Process the arguments
  1397. this->SetArgs(args);
  1398. if (cmSystemTools::GetErrorOccuredFlag()) {
  1399. return -1;
  1400. }
  1401. // If we are given a stamp list file check if it is really out of date.
  1402. if (!this->CheckStampList.empty() &&
  1403. cmakeCheckStampList(this->CheckStampList.c_str())) {
  1404. return 0;
  1405. }
  1406. // If we are given a stamp file check if it is really out of date.
  1407. if (!this->CheckStampFile.empty() &&
  1408. cmakeCheckStampFile(this->CheckStampFile.c_str())) {
  1409. return 0;
  1410. }
  1411. if (this->GetWorkingMode() == NORMAL_MODE) {
  1412. // load the cache
  1413. if (this->LoadCache() < 0) {
  1414. cmSystemTools::Error("Error executing cmake::LoadCache(). Aborting.\n");
  1415. return -1;
  1416. }
  1417. } else {
  1418. this->AddCMakePaths();
  1419. }
  1420. // Add any cache args
  1421. if (!this->SetCacheArgs(args)) {
  1422. cmSystemTools::Error("Problem processing arguments. Aborting.\n");
  1423. return -1;
  1424. }
  1425. // In script mode we terminate after running the script.
  1426. if (this->GetWorkingMode() != NORMAL_MODE) {
  1427. if (cmSystemTools::GetErrorOccuredFlag()) {
  1428. return -1;
  1429. }
  1430. return 0;
  1431. }
  1432. // If MAKEFLAGS are given in the environment, remove the environment
  1433. // variable. This will prevent try-compile from succeeding when it
  1434. // should fail (if "-i" is an option). We cannot simply test
  1435. // whether "-i" is given and remove it because some make programs
  1436. // encode the MAKEFLAGS variable in a strange way.
  1437. if (cmSystemTools::HasEnv("MAKEFLAGS")) {
  1438. cmSystemTools::PutEnv("MAKEFLAGS=");
  1439. }
  1440. this->PreLoadCMakeFiles();
  1441. if (noconfigure) {
  1442. return 0;
  1443. }
  1444. // now run the global generate
  1445. // Check the state of the build system to see if we need to regenerate.
  1446. if (!this->CheckBuildSystem()) {
  1447. return 0;
  1448. }
  1449. int ret = this->Configure();
  1450. if (ret || this->GetWorkingMode() != NORMAL_MODE) {
  1451. #if defined(CMAKE_HAVE_VS_GENERATORS)
  1452. if (!this->VSSolutionFile.empty() && this->GlobalGenerator) {
  1453. // CMake is running to regenerate a Visual Studio build tree
  1454. // during a build from the VS IDE. The build files cannot be
  1455. // regenerated, so we should stop the build.
  1456. cmSystemTools::Message("CMake Configure step failed. "
  1457. "Build files cannot be regenerated correctly. "
  1458. "Attempting to stop IDE build.");
  1459. cmGlobalVisualStudioGenerator* gg =
  1460. static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator);
  1461. gg->CallVisualStudioMacro(cmGlobalVisualStudioGenerator::MacroStop,
  1462. this->VSSolutionFile.c_str());
  1463. }
  1464. #endif
  1465. return ret;
  1466. }
  1467. ret = this->Generate();
  1468. std::string message = "Build files have been written to: ";
  1469. message += this->GetHomeOutputDirectory();
  1470. this->UpdateProgress(message.c_str(), -1);
  1471. return ret;
  1472. }
  1473. int cmake::Generate()
  1474. {
  1475. if (!this->GlobalGenerator) {
  1476. return -1;
  1477. }
  1478. if (!this->GlobalGenerator->Compute()) {
  1479. return -1;
  1480. }
  1481. this->GlobalGenerator->Generate();
  1482. if (!this->GraphVizFile.empty()) {
  1483. std::cout << "Generate graphviz: " << this->GraphVizFile << std::endl;
  1484. this->GenerateGraphViz(this->GraphVizFile.c_str());
  1485. }
  1486. if (this->WarnUnusedCli) {
  1487. this->RunCheckForUnusedVariables();
  1488. }
  1489. if (cmSystemTools::GetErrorOccuredFlag()) {
  1490. return -1;
  1491. }
  1492. // Save the cache again after a successful Generate so that any internal
  1493. // variables created during Generate are saved. (Specifically target GUIDs
  1494. // for the Visual Studio and Xcode generators.)
  1495. if (this->GetWorkingMode() == NORMAL_MODE) {
  1496. this->SaveCache(this->GetHomeOutputDirectory());
  1497. }
  1498. return 0;
  1499. }
  1500. void cmake::AddCacheEntry(const std::string& key, const char* value,
  1501. const char* helpString, int type)
  1502. {
  1503. this->State->AddCacheEntry(key, value, helpString,
  1504. cmStateEnums::CacheEntryType(type));
  1505. this->UnwatchUnusedCli(key);
  1506. }
  1507. std::string cmake::StripExtension(const std::string& file) const
  1508. {
  1509. auto dotpos = file.rfind('.');
  1510. if (dotpos != std::string::npos) {
  1511. auto ext = file.substr(dotpos + 1);
  1512. #if defined(_WIN32) || defined(__APPLE__)
  1513. ext = cmSystemTools::LowerCase(ext);
  1514. #endif
  1515. if (this->IsSourceExtension(ext) || this->IsHeaderExtension(ext)) {
  1516. return file.substr(0, dotpos);
  1517. }
  1518. }
  1519. return file;
  1520. }
  1521. const char* cmake::GetCacheDefinition(const std::string& name) const
  1522. {
  1523. return this->State->GetInitializedCacheValue(name);
  1524. }
  1525. void cmake::AddScriptingCommands()
  1526. {
  1527. GetScriptingCommands(this->State);
  1528. }
  1529. void cmake::AddProjectCommands()
  1530. {
  1531. GetProjectCommands(this->State);
  1532. }
  1533. void cmake::AddDefaultGenerators()
  1534. {
  1535. #if defined(_WIN32) && !defined(__CYGWIN__)
  1536. #if !defined(CMAKE_BOOT_MINGW)
  1537. this->Generators.push_back(cmGlobalVisualStudio15Generator::NewFactory());
  1538. this->Generators.push_back(cmGlobalVisualStudio14Generator::NewFactory());
  1539. this->Generators.push_back(cmGlobalVisualStudio12Generator::NewFactory());
  1540. this->Generators.push_back(cmGlobalVisualStudio11Generator::NewFactory());
  1541. this->Generators.push_back(cmGlobalVisualStudio10Generator::NewFactory());
  1542. this->Generators.push_back(cmGlobalVisualStudio9Generator::NewFactory());
  1543. this->Generators.push_back(cmGlobalVisualStudio8Generator::NewFactory());
  1544. this->Generators.push_back(cmGlobalBorlandMakefileGenerator::NewFactory());
  1545. this->Generators.push_back(cmGlobalNMakeMakefileGenerator::NewFactory());
  1546. this->Generators.push_back(cmGlobalJOMMakefileGenerator::NewFactory());
  1547. this->Generators.push_back(cmGlobalGhsMultiGenerator::NewFactory());
  1548. #endif
  1549. this->Generators.push_back(cmGlobalMSYSMakefileGenerator::NewFactory());
  1550. this->Generators.push_back(cmGlobalMinGWMakefileGenerator::NewFactory());
  1551. #endif
  1552. this->Generators.push_back(cmGlobalUnixMakefileGenerator3::NewFactory());
  1553. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1554. this->Generators.push_back(cmGlobalNinjaGenerator::NewFactory());
  1555. #endif
  1556. #if defined(CMAKE_USE_WMAKE)
  1557. this->Generators.push_back(cmGlobalWatcomWMakeGenerator::NewFactory());
  1558. #endif
  1559. #ifdef CMAKE_USE_XCODE
  1560. this->Generators.push_back(cmGlobalXCodeGenerator::NewFactory());
  1561. #endif
  1562. }
  1563. bool cmake::ParseCacheEntry(const std::string& entry, std::string& var,
  1564. std::string& value,
  1565. cmStateEnums::CacheEntryType& type)
  1566. {
  1567. return cmState::ParseCacheEntry(entry, var, value, type);
  1568. }
  1569. int cmake::LoadCache()
  1570. {
  1571. // could we not read the cache
  1572. if (!this->LoadCache(this->GetHomeOutputDirectory())) {
  1573. // if it does exist, but isn't readable then warn the user
  1574. std::string cacheFile = this->GetHomeOutputDirectory();
  1575. cacheFile += "/CMakeCache.txt";
  1576. if (cmSystemTools::FileExists(cacheFile.c_str())) {
  1577. cmSystemTools::Error(
  1578. "There is a CMakeCache.txt file for the current binary tree but "
  1579. "cmake does not have permission to read it. Please check the "
  1580. "permissions of the directory you are trying to run CMake on.");
  1581. return -1;
  1582. }
  1583. }
  1584. // setup CMAKE_ROOT and CMAKE_COMMAND
  1585. if (!this->AddCMakePaths()) {
  1586. return -3;
  1587. }
  1588. return 0;
  1589. }
  1590. bool cmake::LoadCache(const std::string& path)
  1591. {
  1592. std::set<std::string> emptySet;
  1593. return this->LoadCache(path, true, emptySet, emptySet);
  1594. }
  1595. bool cmake::LoadCache(const std::string& path, bool internal,
  1596. std::set<std::string>& excludes,
  1597. std::set<std::string>& includes)
  1598. {
  1599. bool result = this->State->LoadCache(path, internal, excludes, includes);
  1600. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1601. "CMAKE_CACHE_MINOR_VERSION" };
  1602. for (const char* const* nameIt = cm::cbegin(entries);
  1603. nameIt != cm::cend(entries); ++nameIt) {
  1604. this->UnwatchUnusedCli(*nameIt);
  1605. }
  1606. return result;
  1607. }
  1608. bool cmake::SaveCache(const std::string& path)
  1609. {
  1610. bool result = this->State->SaveCache(path, this->GetMessenger());
  1611. static const char* entries[] = { "CMAKE_CACHE_MAJOR_VERSION",
  1612. "CMAKE_CACHE_MINOR_VERSION",
  1613. "CMAKE_CACHE_PATCH_VERSION",
  1614. "CMAKE_CACHEFILE_DIR" };
  1615. for (const char* const* nameIt = cm::cbegin(entries);
  1616. nameIt != cm::cend(entries); ++nameIt) {
  1617. this->UnwatchUnusedCli(*nameIt);
  1618. }
  1619. return result;
  1620. }
  1621. bool cmake::DeleteCache(const std::string& path)
  1622. {
  1623. return this->State->DeleteCache(path);
  1624. }
  1625. void cmake::SetProgressCallback(ProgressCallbackType f, void* cd)
  1626. {
  1627. this->ProgressCallback = f;
  1628. this->ProgressCallbackClientData = cd;
  1629. }
  1630. void cmake::UpdateProgress(const char* msg, float prog)
  1631. {
  1632. if (this->ProgressCallback && !this->State->GetIsInTryCompile()) {
  1633. (*this->ProgressCallback)(msg, prog, this->ProgressCallbackClientData);
  1634. return;
  1635. }
  1636. }
  1637. bool cmake::GetIsInTryCompile() const
  1638. {
  1639. return this->State->GetIsInTryCompile();
  1640. }
  1641. void cmake::SetIsInTryCompile(bool b)
  1642. {
  1643. this->State->SetIsInTryCompile(b);
  1644. }
  1645. void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
  1646. {
  1647. for (cmGlobalGeneratorFactory* g : this->Generators) {
  1648. cmDocumentationEntry e;
  1649. g->GetDocumentation(e);
  1650. v.push_back(std::move(e));
  1651. }
  1652. for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
  1653. const std::string doc = eg->GetDocumentation();
  1654. const std::string name = eg->GetName();
  1655. // Aliases:
  1656. for (std::string const& a : eg->Aliases) {
  1657. cmDocumentationEntry e;
  1658. e.Name = a;
  1659. e.Brief = doc;
  1660. v.push_back(std::move(e));
  1661. }
  1662. // Full names:
  1663. const std::vector<std::string> generators =
  1664. eg->GetSupportedGlobalGenerators();
  1665. for (std::string const& g : generators) {
  1666. cmDocumentationEntry e;
  1667. e.Name =
  1668. cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
  1669. e.Brief = doc;
  1670. v.push_back(std::move(e));
  1671. }
  1672. }
  1673. }
  1674. void cmake::PrintGeneratorList()
  1675. {
  1676. #ifdef CMAKE_BUILD_WITH_CMAKE
  1677. cmDocumentation doc;
  1678. std::vector<cmDocumentationEntry> generators;
  1679. this->GetGeneratorDocumentation(generators);
  1680. doc.AppendSection("Generators", generators);
  1681. std::cerr << "\n";
  1682. doc.PrintDocumentation(cmDocumentation::ListGenerators, std::cerr);
  1683. #endif
  1684. }
  1685. void cmake::UpdateConversionPathTable()
  1686. {
  1687. // Update the path conversion table with any specified file:
  1688. const char* tablepath =
  1689. this->State->GetInitializedCacheValue("CMAKE_PATH_TRANSLATION_FILE");
  1690. if (tablepath) {
  1691. cmsys::ifstream table(tablepath);
  1692. if (!table) {
  1693. cmSystemTools::Error("CMAKE_PATH_TRANSLATION_FILE set to ", tablepath,
  1694. ". CMake can not open file.");
  1695. cmSystemTools::ReportLastSystemError("CMake can not open file.");
  1696. } else {
  1697. std::string a, b;
  1698. while (!table.eof()) {
  1699. // two entries per line
  1700. table >> a;
  1701. table >> b;
  1702. cmSystemTools::AddTranslationPath(a, b);
  1703. }
  1704. }
  1705. }
  1706. }
  1707. int cmake::CheckBuildSystem()
  1708. {
  1709. // We do not need to rerun CMake. Check dependency integrity.
  1710. const bool verbose = isCMakeVerbose();
  1711. // This method will check the integrity of the build system if the
  1712. // option was given on the command line. It reads the given file to
  1713. // determine whether CMake should rerun.
  1714. // If no file is provided for the check, we have to rerun.
  1715. if (this->CheckBuildSystemArgument.empty()) {
  1716. if (verbose) {
  1717. std::ostringstream msg;
  1718. msg << "Re-run cmake no build system arguments\n";
  1719. cmSystemTools::Stdout(msg.str().c_str());
  1720. }
  1721. return 1;
  1722. }
  1723. // If the file provided does not exist, we have to rerun.
  1724. if (!cmSystemTools::FileExists(this->CheckBuildSystemArgument.c_str())) {
  1725. if (verbose) {
  1726. std::ostringstream msg;
  1727. msg << "Re-run cmake missing file: " << this->CheckBuildSystemArgument
  1728. << "\n";
  1729. cmSystemTools::Stdout(msg.str().c_str());
  1730. }
  1731. return 1;
  1732. }
  1733. // Read the rerun check file and use it to decide whether to do the
  1734. // global generate.
  1735. cmake cm(RoleScript); // Actually, all we need is the `set` command.
  1736. cm.SetHomeDirectory("");
  1737. cm.SetHomeOutputDirectory("");
  1738. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1739. cmGlobalGenerator gg(&cm);
  1740. cmMakefile mf(&gg, cm.GetCurrentSnapshot());
  1741. if (!mf.ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
  1742. cmSystemTools::GetErrorOccuredFlag()) {
  1743. if (verbose) {
  1744. std::ostringstream msg;
  1745. msg << "Re-run cmake error reading : " << this->CheckBuildSystemArgument
  1746. << "\n";
  1747. cmSystemTools::Stdout(msg.str().c_str());
  1748. }
  1749. // There was an error reading the file. Just rerun.
  1750. return 1;
  1751. }
  1752. if (this->ClearBuildSystem) {
  1753. // Get the generator used for this build system.
  1754. const char* genName = mf.GetDefinition("CMAKE_DEPENDS_GENERATOR");
  1755. if (!genName || genName[0] == '\0') {
  1756. genName = "Unix Makefiles";
  1757. }
  1758. // Create the generator and use it to clear the dependencies.
  1759. std::unique_ptr<cmGlobalGenerator> ggd(
  1760. this->CreateGlobalGenerator(genName));
  1761. if (ggd) {
  1762. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1763. cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
  1764. std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mfd));
  1765. lgd->ClearDependencies(&mfd, verbose);
  1766. }
  1767. }
  1768. // If any byproduct of makefile generation is missing we must re-run.
  1769. std::vector<std::string> products;
  1770. if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
  1771. cmSystemTools::ExpandListArgument(productStr, products);
  1772. }
  1773. for (std::string const& p : products) {
  1774. if (!(cmSystemTools::FileExists(p.c_str()) ||
  1775. 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.c_str())) {
  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.c_str())) {
  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.c_str()) &&
  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, 0, cmSystemTools::OUTPUT_PASSTHROUGH,
  2246. 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. }