cmake.cxx 96 KB

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