cmake.cxx 119 KB

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