cmake.cxx 105 KB

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