cmake.cxx 147 KB

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