cmake.cxx 94 KB

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