cmake.cxx 141 KB

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