cmake.cxx 120 KB

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