cmake.cxx 151 KB

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