cmake.cxx 143 KB

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