cmake.cxx 96 KB

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