cmake.cxx 141 KB

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