cmake.cxx 152 KB

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