cmake.cxx 126 KB

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