cmake.cxx 149 KB

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