cmake.cxx 146 KB

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