cmake.cxx 123 KB

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