cmake.cxx 142 KB

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