cmake.cxx 89 KB

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