cmake.cxx 118 KB

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