cmake.cxx 119 KB

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