cmMakefile.cxx 155 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886
  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 "cmMakefile.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmsys/RegularExpression.hxx"
  6. #include <algorithm>
  7. #include <assert.h>
  8. #include <cstring>
  9. #include <ctype.h>
  10. #include <iterator>
  11. #include <memory>
  12. #include <sstream>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <utility>
  16. #include "cmAlgorithms.h"
  17. #include "cmCommandArgumentParserHelper.h"
  18. #include "cmCustomCommand.h"
  19. #include "cmCustomCommandLines.h"
  20. #include "cmExecutionStatus.h"
  21. #include "cmExpandedCommandArgument.h" // IWYU pragma: keep
  22. #include "cmFileLockPool.h"
  23. #include "cmFunctionBlocker.h"
  24. #include "cmGeneratorExpression.h"
  25. #include "cmGeneratorExpressionEvaluationFile.h"
  26. #include "cmGlobalGenerator.h"
  27. #include "cmInstallGenerator.h" // IWYU pragma: keep
  28. #include "cmInstallSubdirectoryGenerator.h"
  29. #include "cmListFileCache.h"
  30. #include "cmMessageType.h"
  31. #include "cmRange.h"
  32. #include "cmSourceFile.h"
  33. #include "cmSourceFileLocation.h"
  34. #include "cmState.h"
  35. #include "cmStateDirectory.h"
  36. #include "cmStateTypes.h"
  37. #include "cmSystemTools.h"
  38. #include "cmTargetLinkLibraryType.h"
  39. #include "cmTest.h"
  40. #include "cmTestGenerator.h" // IWYU pragma: keep
  41. #include "cmVersion.h"
  42. #include "cmWorkingDirectory.h"
  43. #include "cm_sys_stat.h"
  44. #include "cmake.h"
  45. #include "cmConfigure.h" // IWYU pragma: keep
  46. #ifndef CMAKE_BOOTSTRAP
  47. # include "cmVariableWatch.h"
  48. #endif
  49. class cmMessenger;
  50. cmDirectoryId::cmDirectoryId(std::string s)
  51. : String(std::move(s))
  52. {
  53. }
  54. // default is not to be building executables
  55. cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
  56. cmStateSnapshot const& snapshot)
  57. : GlobalGenerator(globalGenerator)
  58. , StateSnapshot(snapshot)
  59. , Backtrace(snapshot)
  60. {
  61. this->IsSourceFileTryCompile = false;
  62. this->WarnUnused = this->GetCMakeInstance()->GetWarnUnused();
  63. this->CheckSystemVars = this->GetCMakeInstance()->GetCheckSystemVars();
  64. this->SuppressSideEffects = false;
  65. // Setup the default include complaint regular expression (match nothing).
  66. this->ComplainFileRegularExpression = "^$";
  67. this->DefineFlags = " ";
  68. this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
  69. this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
  70. this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
  71. this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
  72. this->StateSnapshot =
  73. this->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  74. this->StateSnapshot);
  75. this->RecursionDepth = 0;
  76. // Enter a policy level for this directory.
  77. this->PushPolicy();
  78. // push empty loop block
  79. this->PushLoopBlockBarrier();
  80. // By default the check is not done. It is enabled by
  81. // cmListFileCache in the top level if necessary.
  82. this->CheckCMP0000 = false;
  83. #if !defined(CMAKE_BOOTSTRAP)
  84. this->AddSourceGroup("", "^.*$");
  85. this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
  86. this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
  87. this->AddSourceGroup("CMake Rules", "\\.rule$");
  88. this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
  89. this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
  90. this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
  91. this->SourceGroups.emplace_back("Object Libraries", "^MATCH_NO_SOURCES$");
  92. #endif
  93. }
  94. cmMakefile::~cmMakefile()
  95. {
  96. cmDeleteAll(this->InstallGenerators);
  97. cmDeleteAll(this->TestGenerators);
  98. cmDeleteAll(this->SourceFiles);
  99. cmDeleteAll(this->Tests);
  100. cmDeleteAll(this->ImportedTargetsOwned);
  101. cmDeleteAll(this->EvaluationFiles);
  102. }
  103. cmDirectoryId cmMakefile::GetDirectoryId() const
  104. {
  105. // Use the instance pointer value to uniquely identify this directory.
  106. // If we ever need to expose this to CMake language code we should
  107. // add a read-only property in cmMakefile::GetProperty.
  108. char buf[32];
  109. sprintf(buf, "<%p>",
  110. static_cast<void const*>(this)); // cast avoids format warning
  111. return std::string(buf);
  112. }
  113. void cmMakefile::IssueMessage(MessageType t, std::string const& text) const
  114. {
  115. if (!this->ExecutionStatusStack.empty()) {
  116. if ((t == MessageType::FATAL_ERROR) ||
  117. (t == MessageType::INTERNAL_ERROR)) {
  118. this->ExecutionStatusStack.back()->SetNestedError();
  119. }
  120. }
  121. this->GetCMakeInstance()->IssueMessage(t, text, this->GetBacktrace());
  122. }
  123. bool cmMakefile::CheckCMP0037(std::string const& targetName,
  124. cmStateEnums::TargetType targetType) const
  125. {
  126. MessageType messageType = MessageType::AUTHOR_WARNING;
  127. std::ostringstream e;
  128. bool issueMessage = false;
  129. switch (this->GetPolicyStatus(cmPolicies::CMP0037)) {
  130. case cmPolicies::WARN:
  131. if (targetType != cmStateEnums::INTERFACE_LIBRARY) {
  132. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0037) << "\n";
  133. issueMessage = true;
  134. }
  135. CM_FALLTHROUGH;
  136. case cmPolicies::OLD:
  137. break;
  138. case cmPolicies::NEW:
  139. case cmPolicies::REQUIRED_IF_USED:
  140. case cmPolicies::REQUIRED_ALWAYS:
  141. issueMessage = true;
  142. messageType = MessageType::FATAL_ERROR;
  143. break;
  144. }
  145. if (issueMessage) {
  146. e << "The target name \"" << targetName
  147. << "\" is reserved or not valid for certain "
  148. "CMake features, such as generator expressions, and may result "
  149. "in undefined behavior.";
  150. this->IssueMessage(messageType, e.str());
  151. if (messageType == MessageType::FATAL_ERROR) {
  152. return false;
  153. }
  154. }
  155. return true;
  156. }
  157. void cmMakefile::MaybeWarnCMP0074(std::string const& pkg)
  158. {
  159. // Warn if a <pkg>_ROOT variable we may use is set.
  160. std::string const varName = pkg + "_ROOT";
  161. const char* var = this->GetDefinition(varName);
  162. std::string env;
  163. cmSystemTools::GetEnv(varName, env);
  164. bool const haveVar = var && *var;
  165. bool const haveEnv = !env.empty();
  166. if ((haveVar || haveEnv) && this->WarnedCMP0074.insert(varName).second) {
  167. std::ostringstream w;
  168. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0074) << "\n";
  169. if (haveVar) {
  170. w << "CMake variable " << varName << " is set to:\n"
  171. << " " << var << "\n";
  172. }
  173. if (haveEnv) {
  174. w << "Environment variable " << varName << " is set to:\n"
  175. << " " << env << "\n";
  176. }
  177. w << "For compatibility, CMake is ignoring the variable.";
  178. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  179. }
  180. }
  181. cmStringRange cmMakefile::GetIncludeDirectoriesEntries() const
  182. {
  183. return this->StateSnapshot.GetDirectory().GetIncludeDirectoriesEntries();
  184. }
  185. cmBacktraceRange cmMakefile::GetIncludeDirectoriesBacktraces() const
  186. {
  187. return this->StateSnapshot.GetDirectory()
  188. .GetIncludeDirectoriesEntryBacktraces();
  189. }
  190. cmStringRange cmMakefile::GetCompileOptionsEntries() const
  191. {
  192. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntries();
  193. }
  194. cmBacktraceRange cmMakefile::GetCompileOptionsBacktraces() const
  195. {
  196. return this->StateSnapshot.GetDirectory().GetCompileOptionsEntryBacktraces();
  197. }
  198. cmStringRange cmMakefile::GetCompileDefinitionsEntries() const
  199. {
  200. return this->StateSnapshot.GetDirectory().GetCompileDefinitionsEntries();
  201. }
  202. cmBacktraceRange cmMakefile::GetCompileDefinitionsBacktraces() const
  203. {
  204. return this->StateSnapshot.GetDirectory()
  205. .GetCompileDefinitionsEntryBacktraces();
  206. }
  207. cmStringRange cmMakefile::GetLinkOptionsEntries() const
  208. {
  209. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntries();
  210. }
  211. cmBacktraceRange cmMakefile::GetLinkOptionsBacktraces() const
  212. {
  213. return this->StateSnapshot.GetDirectory().GetLinkOptionsEntryBacktraces();
  214. }
  215. cmStringRange cmMakefile::GetLinkDirectoriesEntries() const
  216. {
  217. return this->StateSnapshot.GetDirectory().GetLinkDirectoriesEntries();
  218. }
  219. cmBacktraceRange cmMakefile::GetLinkDirectoriesBacktraces() const
  220. {
  221. return this->StateSnapshot.GetDirectory()
  222. .GetLinkDirectoriesEntryBacktraces();
  223. }
  224. cmListFileBacktrace cmMakefile::GetBacktrace() const
  225. {
  226. return this->Backtrace;
  227. }
  228. cmListFileBacktrace cmMakefile::GetBacktrace(cmCommandContext const& cc) const
  229. {
  230. cmListFileContext lfc;
  231. lfc.Name = cc.Name.Original;
  232. lfc.Line = cc.Line;
  233. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  234. return this->Backtrace.Push(lfc);
  235. }
  236. cmListFileContext cmMakefile::GetExecutionContext() const
  237. {
  238. cmListFileContext const& cur = this->Backtrace.Top();
  239. cmListFileContext lfc;
  240. lfc.Name = cur.Name;
  241. lfc.Line = cur.Line;
  242. lfc.FilePath = this->StateSnapshot.GetExecutionListFile();
  243. return lfc;
  244. }
  245. void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
  246. {
  247. // Check if current file in the list of requested to trace...
  248. std::vector<std::string> const& trace_only_this_files =
  249. this->GetCMakeInstance()->GetTraceSources();
  250. std::string const& full_path = this->GetExecutionFilePath();
  251. std::string const& only_filename = cmSystemTools::GetFilenameName(full_path);
  252. bool trace = trace_only_this_files.empty();
  253. if (!trace) {
  254. for (std::string const& file : trace_only_this_files) {
  255. std::string::size_type const pos = full_path.rfind(file);
  256. trace = (pos != std::string::npos) &&
  257. ((pos + file.size()) == full_path.size()) &&
  258. (only_filename == cmSystemTools::GetFilenameName(file));
  259. if (trace) {
  260. break;
  261. }
  262. }
  263. // Do nothing if current file wasn't requested for trace...
  264. if (!trace) {
  265. return;
  266. }
  267. }
  268. std::ostringstream msg;
  269. msg << full_path << "(" << lff.Line << "): ";
  270. msg << lff.Name.Original << "(";
  271. bool expand = this->GetCMakeInstance()->GetTraceExpand();
  272. std::string temp;
  273. for (cmListFileArgument const& arg : lff.Arguments) {
  274. if (expand) {
  275. temp = arg.Value;
  276. this->ExpandVariablesInString(temp);
  277. msg << temp;
  278. } else {
  279. msg << arg.Value;
  280. }
  281. msg << " ";
  282. }
  283. msg << ")";
  284. cmSystemTools::Message(msg.str());
  285. }
  286. // Helper class to make sure the call stack is valid.
  287. class cmMakefileCall
  288. {
  289. public:
  290. cmMakefileCall(cmMakefile* mf, cmCommandContext const& cc,
  291. cmExecutionStatus& status)
  292. : Makefile(mf)
  293. {
  294. cmListFileContext const& lfc = cmListFileContext::FromCommandContext(
  295. cc, this->Makefile->StateSnapshot.GetExecutionListFile());
  296. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(lfc);
  297. ++this->Makefile->RecursionDepth;
  298. this->Makefile->ExecutionStatusStack.push_back(&status);
  299. }
  300. ~cmMakefileCall()
  301. {
  302. this->Makefile->ExecutionStatusStack.pop_back();
  303. --this->Makefile->RecursionDepth;
  304. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  305. }
  306. cmMakefileCall(const cmMakefileCall&) = delete;
  307. cmMakefileCall& operator=(const cmMakefileCall&) = delete;
  308. private:
  309. cmMakefile* Makefile;
  310. };
  311. void cmMakefile::OnExecuteCommand(std::function<void()> callback)
  312. {
  313. this->ExecuteCommandCallback = std::move(callback);
  314. }
  315. bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
  316. cmExecutionStatus& status)
  317. {
  318. bool result = true;
  319. // quick return if blocked
  320. if (this->IsFunctionBlocked(lff, status)) {
  321. // No error.
  322. return result;
  323. }
  324. if (this->ExecuteCommandCallback) {
  325. this->ExecuteCommandCallback();
  326. }
  327. // Place this call on the call stack.
  328. cmMakefileCall stack_manager(this, lff, status);
  329. static_cast<void>(stack_manager);
  330. // Check for maximum recursion depth.
  331. int depth = CMake_DEFAULT_RECURSION_LIMIT;
  332. const char* depthStr = this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  333. if (depthStr) {
  334. std::istringstream s(depthStr);
  335. int d;
  336. if (s >> d) {
  337. depth = d;
  338. }
  339. }
  340. if (this->RecursionDepth > depth) {
  341. std::ostringstream e;
  342. e << "Maximum recursion depth of " << depth << " exceeded";
  343. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  344. cmSystemTools::SetFatalErrorOccured();
  345. return false;
  346. }
  347. // Lookup the command prototype.
  348. if (cmState::Command command =
  349. this->GetState()->GetCommandByExactName(lff.Name.Lower)) {
  350. // Decide whether to invoke the command.
  351. if (!cmSystemTools::GetFatalErrorOccured()) {
  352. // if trace is enabled, print out invoke information
  353. if (this->GetCMakeInstance()->GetTrace()) {
  354. this->PrintCommandTrace(lff);
  355. }
  356. // Try invoking the command.
  357. bool invokeSucceeded = command(lff.Arguments, status);
  358. bool hadNestedError = status.GetNestedError();
  359. if (!invokeSucceeded || hadNestedError) {
  360. if (!hadNestedError) {
  361. // The command invocation requested that we report an error.
  362. std::string const error =
  363. std::string(lff.Name.Original) + " " + status.GetError();
  364. this->IssueMessage(MessageType::FATAL_ERROR, error);
  365. }
  366. result = false;
  367. if (this->GetCMakeInstance()->GetWorkingMode() != cmake::NORMAL_MODE) {
  368. cmSystemTools::SetFatalErrorOccured();
  369. }
  370. }
  371. }
  372. } else {
  373. if (!cmSystemTools::GetFatalErrorOccured()) {
  374. std::string error = "Unknown CMake command \"";
  375. error += lff.Name.Original;
  376. error += "\".";
  377. this->IssueMessage(MessageType::FATAL_ERROR, error);
  378. result = false;
  379. cmSystemTools::SetFatalErrorOccured();
  380. }
  381. }
  382. return result;
  383. }
  384. class cmMakefile::IncludeScope
  385. {
  386. public:
  387. IncludeScope(cmMakefile* mf, std::string const& filenametoread,
  388. bool noPolicyScope);
  389. ~IncludeScope();
  390. void Quiet() { this->ReportError = false; }
  391. IncludeScope(const IncludeScope&) = delete;
  392. IncludeScope& operator=(const IncludeScope&) = delete;
  393. private:
  394. cmMakefile* Makefile;
  395. bool NoPolicyScope;
  396. bool CheckCMP0011;
  397. bool ReportError;
  398. void EnforceCMP0011();
  399. };
  400. cmMakefile::IncludeScope::IncludeScope(cmMakefile* mf,
  401. std::string const& filenametoread,
  402. bool noPolicyScope)
  403. : Makefile(mf)
  404. , NoPolicyScope(noPolicyScope)
  405. , CheckCMP0011(false)
  406. , ReportError(true)
  407. {
  408. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  409. this->Makefile->PushFunctionBlockerBarrier();
  410. this->Makefile->StateSnapshot =
  411. this->Makefile->GetState()->CreateIncludeFileSnapshot(
  412. this->Makefile->StateSnapshot, filenametoread);
  413. if (!this->NoPolicyScope) {
  414. // Check CMP0011 to determine the policy scope type.
  415. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  416. case cmPolicies::WARN:
  417. // We need to push a scope to detect whether the script sets
  418. // any policies that would affect the includer and therefore
  419. // requires a warning. We use a weak scope to simulate OLD
  420. // behavior by allowing policy changes to affect the includer.
  421. this->Makefile->PushPolicy(true);
  422. this->CheckCMP0011 = true;
  423. break;
  424. case cmPolicies::OLD:
  425. // OLD behavior is to not push a scope at all.
  426. this->NoPolicyScope = true;
  427. break;
  428. case cmPolicies::REQUIRED_IF_USED:
  429. case cmPolicies::REQUIRED_ALWAYS:
  430. // We should never make this policy required, but we handle it
  431. // here just in case.
  432. this->CheckCMP0011 = true;
  433. CM_FALLTHROUGH;
  434. case cmPolicies::NEW:
  435. // NEW behavior is to push a (strong) scope.
  436. this->Makefile->PushPolicy();
  437. break;
  438. }
  439. }
  440. }
  441. cmMakefile::IncludeScope::~IncludeScope()
  442. {
  443. if (!this->NoPolicyScope) {
  444. // If we need to enforce policy CMP0011 then the top entry is the
  445. // one we pushed above. If the entry is empty, then the included
  446. // script did not set any policies that might affect the includer so
  447. // we do not need to enforce the policy.
  448. if (this->CheckCMP0011 &&
  449. !this->Makefile->StateSnapshot.HasDefinedPolicyCMP0011()) {
  450. this->CheckCMP0011 = false;
  451. }
  452. // Pop the scope we pushed for the script.
  453. this->Makefile->PopPolicy();
  454. // We enforce the policy after the script's policy stack entry has
  455. // been removed.
  456. if (this->CheckCMP0011) {
  457. this->EnforceCMP0011();
  458. }
  459. }
  460. this->Makefile->PopSnapshot(this->ReportError);
  461. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  462. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  463. }
  464. void cmMakefile::IncludeScope::EnforceCMP0011()
  465. {
  466. // We check the setting of this policy again because the included
  467. // script might actually set this policy for its includer.
  468. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0011)) {
  469. case cmPolicies::WARN:
  470. // Warn because the user did not set this policy.
  471. {
  472. std::ostringstream w;
  473. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0011) << "\n"
  474. << "The included script\n "
  475. << this->Makefile->GetExecutionFilePath() << "\n"
  476. << "affects policy settings. "
  477. << "CMake is implying the NO_POLICY_SCOPE option for compatibility, "
  478. << "so the effects are applied to the including context.";
  479. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  480. }
  481. break;
  482. case cmPolicies::REQUIRED_IF_USED:
  483. case cmPolicies::REQUIRED_ALWAYS: {
  484. std::ostringstream e;
  485. /* clang-format off */
  486. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0011) << "\n"
  487. << "The included script\n "
  488. << this->Makefile->GetExecutionFilePath() << "\n"
  489. << "affects policy settings, so it requires this policy to be set.";
  490. /* clang-format on */
  491. this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
  492. } break;
  493. case cmPolicies::OLD:
  494. case cmPolicies::NEW:
  495. // The script set this policy. We assume the purpose of the
  496. // script is to initialize policies for its includer, and since
  497. // the policy is now set for later scripts, we do not warn.
  498. break;
  499. }
  500. }
  501. bool cmMakefile::ReadDependentFile(const std::string& filename,
  502. bool noPolicyScope)
  503. {
  504. if (const char* def = this->GetDefinition("CMAKE_CURRENT_LIST_FILE")) {
  505. this->AddDefinition("CMAKE_PARENT_LIST_FILE", def);
  506. }
  507. std::string filenametoread = cmSystemTools::CollapseFullPath(
  508. filename, this->GetCurrentSourceDirectory());
  509. IncludeScope incScope(this, filenametoread, noPolicyScope);
  510. cmListFile listFile;
  511. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  512. this->Backtrace)) {
  513. return false;
  514. }
  515. this->ReadListFile(listFile, filenametoread);
  516. if (cmSystemTools::GetFatalErrorOccured()) {
  517. incScope.Quiet();
  518. }
  519. return true;
  520. }
  521. class cmMakefile::ListFileScope
  522. {
  523. public:
  524. ListFileScope(cmMakefile* mf, std::string const& filenametoread)
  525. : Makefile(mf)
  526. , ReportError(true)
  527. {
  528. this->Makefile->Backtrace = this->Makefile->Backtrace.Push(filenametoread);
  529. this->Makefile->StateSnapshot =
  530. this->Makefile->GetState()->CreateInlineListFileSnapshot(
  531. this->Makefile->StateSnapshot, filenametoread);
  532. assert(this->Makefile->StateSnapshot.IsValid());
  533. this->Makefile->PushFunctionBlockerBarrier();
  534. }
  535. ~ListFileScope()
  536. {
  537. this->Makefile->PopSnapshot(this->ReportError);
  538. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  539. this->Makefile->Backtrace = this->Makefile->Backtrace.Pop();
  540. }
  541. void Quiet() { this->ReportError = false; }
  542. ListFileScope(const ListFileScope&) = delete;
  543. ListFileScope& operator=(const ListFileScope&) = delete;
  544. private:
  545. cmMakefile* Makefile;
  546. bool ReportError;
  547. };
  548. bool cmMakefile::ReadListFile(const std::string& filename)
  549. {
  550. std::string filenametoread = cmSystemTools::CollapseFullPath(
  551. filename, this->GetCurrentSourceDirectory());
  552. ListFileScope scope(this, filenametoread);
  553. cmListFile listFile;
  554. if (!listFile.ParseFile(filenametoread.c_str(), this->GetMessenger(),
  555. this->Backtrace)) {
  556. return false;
  557. }
  558. this->ReadListFile(listFile, filenametoread);
  559. if (cmSystemTools::GetFatalErrorOccured()) {
  560. scope.Quiet();
  561. }
  562. return true;
  563. }
  564. void cmMakefile::ReadListFile(cmListFile const& listFile,
  565. std::string const& filenametoread)
  566. {
  567. // add this list file to the list of dependencies
  568. this->ListFiles.push_back(filenametoread);
  569. std::string currentParentFile =
  570. this->GetSafeDefinition("CMAKE_PARENT_LIST_FILE");
  571. std::string currentFile = this->GetSafeDefinition("CMAKE_CURRENT_LIST_FILE");
  572. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", filenametoread);
  573. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  574. cmSystemTools::GetFilenamePath(filenametoread));
  575. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  576. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  577. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  578. // Run the parsed commands.
  579. const size_t numberFunctions = listFile.Functions.size();
  580. for (size_t i = 0; i < numberFunctions; ++i) {
  581. cmExecutionStatus status(*this);
  582. this->ExecuteCommand(listFile.Functions[i], status);
  583. if (cmSystemTools::GetFatalErrorOccured()) {
  584. break;
  585. }
  586. if (status.GetReturnInvoked()) {
  587. // Exit early due to return command.
  588. break;
  589. }
  590. }
  591. this->CheckForUnusedVariables();
  592. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentParentFile);
  593. this->AddDefinition("CMAKE_CURRENT_LIST_FILE", currentFile);
  594. this->AddDefinition("CMAKE_CURRENT_LIST_DIR",
  595. cmSystemTools::GetFilenamePath(currentFile));
  596. this->MarkVariableAsUsed("CMAKE_PARENT_LIST_FILE");
  597. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_FILE");
  598. this->MarkVariableAsUsed("CMAKE_CURRENT_LIST_DIR");
  599. }
  600. void cmMakefile::EnforceDirectoryLevelRules() const
  601. {
  602. // Diagnose a violation of CMP0000 if necessary.
  603. if (this->CheckCMP0000) {
  604. std::ostringstream msg;
  605. msg << "No cmake_minimum_required command is present. "
  606. << "A line of code such as\n"
  607. << " cmake_minimum_required(VERSION " << cmVersion::GetMajorVersion()
  608. << "." << cmVersion::GetMinorVersion() << ")\n"
  609. << "should be added at the top of the file. "
  610. << "The version specified may be lower if you wish to "
  611. << "support older CMake versions for this project. "
  612. << "For more information run "
  613. << "\"cmake --help-policy CMP0000\".";
  614. switch (this->GetPolicyStatus(cmPolicies::CMP0000)) {
  615. case cmPolicies::WARN:
  616. // Warn because the user did not provide a minimum required
  617. // version.
  618. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  619. msg.str(), this->Backtrace);
  620. case cmPolicies::OLD:
  621. // OLD behavior is to use policy version 2.4 set in
  622. // cmListFileCache.
  623. break;
  624. case cmPolicies::REQUIRED_IF_USED:
  625. case cmPolicies::REQUIRED_ALWAYS:
  626. case cmPolicies::NEW:
  627. // NEW behavior is to issue an error.
  628. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  629. msg.str(), this->Backtrace);
  630. cmSystemTools::SetFatalErrorOccured();
  631. return;
  632. }
  633. }
  634. }
  635. void cmMakefile::AddEvaluationFile(
  636. const std::string& inputFile,
  637. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  638. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  639. bool inputIsContent)
  640. {
  641. this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile(
  642. inputFile, std::move(outputName), std::move(condition), inputIsContent,
  643. this->GetPolicyStatus(cmPolicies::CMP0070)));
  644. }
  645. std::vector<cmGeneratorExpressionEvaluationFile*>
  646. cmMakefile::GetEvaluationFiles() const
  647. {
  648. return this->EvaluationFiles;
  649. }
  650. std::vector<cmExportBuildFileGenerator*>
  651. cmMakefile::GetExportBuildFileGenerators() const
  652. {
  653. return this->ExportBuildFileGenerators;
  654. }
  655. void cmMakefile::RemoveExportBuildFileGeneratorCMP0024(
  656. cmExportBuildFileGenerator* gen)
  657. {
  658. std::vector<cmExportBuildFileGenerator*>::iterator it =
  659. std::find(this->ExportBuildFileGenerators.begin(),
  660. this->ExportBuildFileGenerators.end(), gen);
  661. if (it != this->ExportBuildFileGenerators.end()) {
  662. this->ExportBuildFileGenerators.erase(it);
  663. }
  664. }
  665. void cmMakefile::AddExportBuildFileGenerator(cmExportBuildFileGenerator* gen)
  666. {
  667. this->ExportBuildFileGenerators.push_back(gen);
  668. }
  669. namespace {
  670. struct file_not_persistent
  671. {
  672. bool operator()(const std::string& path) const
  673. {
  674. return !(path.find("CMakeTmp") == std::string::npos &&
  675. cmSystemTools::FileExists(path));
  676. }
  677. };
  678. }
  679. void cmMakefile::AddFinalAction(FinalAction action)
  680. {
  681. this->FinalActions.push_back(std::move(action));
  682. }
  683. void cmMakefile::FinalPass()
  684. {
  685. // do all the variable expansions here
  686. this->ExpandVariablesCMP0019();
  687. // give all the commands a chance to do something
  688. // after the file has been parsed before generation
  689. for (FinalAction& action : this->FinalActions) {
  690. action(*this);
  691. }
  692. // go through all configured files and see which ones still exist.
  693. // we don't want cmake to re-run if a configured file is created and deleted
  694. // during processing as that would make it a transient file that can't
  695. // influence the build process
  696. cmEraseIf(this->OutputFiles, file_not_persistent());
  697. // if a configured file is used as input for another configured file,
  698. // and then deleted it will show up in the input list files so we
  699. // need to scan those too
  700. cmEraseIf(this->ListFiles, file_not_persistent());
  701. }
  702. // Generate the output file
  703. void cmMakefile::ConfigureFinalPass()
  704. {
  705. this->FinalPass();
  706. const char* oldValue = this->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY");
  707. if (oldValue &&
  708. cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, oldValue, "2.4")) {
  709. this->GetCMakeInstance()->IssueMessage(
  710. MessageType::FATAL_ERROR,
  711. "You have set CMAKE_BACKWARDS_COMPATIBILITY to a CMake version less "
  712. "than 2.4. This version of CMake only supports backwards compatibility "
  713. "with CMake 2.4 or later. For compatibility with older versions please "
  714. "use any CMake 2.8.x release or lower.",
  715. this->Backtrace);
  716. }
  717. }
  718. void cmMakefile::AddCustomCommandToTarget(
  719. const std::string& target, const std::vector<std::string>& byproducts,
  720. const std::vector<std::string>& depends,
  721. const cmCustomCommandLines& commandLines, cmTarget::CustomCommandType type,
  722. const char* comment, const char* workingDir, bool escapeOldStyle,
  723. bool uses_terminal, const std::string& depfile, const std::string& job_pool,
  724. bool command_expand_lists, ObjectLibraryCommands objLibraryCommands)
  725. {
  726. // Find the target to which to add the custom command.
  727. cmTargetMap::iterator ti = this->Targets.find(target);
  728. if (ti == this->Targets.end()) {
  729. MessageType messageType = MessageType::AUTHOR_WARNING;
  730. bool issueMessage = false;
  731. std::ostringstream e;
  732. switch (this->GetPolicyStatus(cmPolicies::CMP0040)) {
  733. case cmPolicies::WARN:
  734. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0040) << "\n";
  735. issueMessage = true;
  736. case cmPolicies::OLD:
  737. break;
  738. case cmPolicies::NEW:
  739. case cmPolicies::REQUIRED_IF_USED:
  740. case cmPolicies::REQUIRED_ALWAYS:
  741. issueMessage = true;
  742. messageType = MessageType::FATAL_ERROR;
  743. }
  744. if (issueMessage) {
  745. if (cmTarget const* t = this->FindTargetToUse(target)) {
  746. if (t->IsImported()) {
  747. e << "TARGET '" << target
  748. << "' is IMPORTED and does not build here.";
  749. } else {
  750. e << "TARGET '" << target << "' was not created in this directory.";
  751. }
  752. } else {
  753. e << "No TARGET '" << target
  754. << "' has been created in this directory.";
  755. }
  756. IssueMessage(messageType, e.str());
  757. }
  758. return;
  759. }
  760. cmTarget& t = ti->second;
  761. if (objLibraryCommands == RejectObjectLibraryCommands &&
  762. t.GetType() == cmStateEnums::OBJECT_LIBRARY) {
  763. std::ostringstream e;
  764. e << "Target \"" << target
  765. << "\" is an OBJECT library "
  766. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  767. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  768. return;
  769. }
  770. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  771. std::ostringstream e;
  772. e << "Target \"" << target
  773. << "\" is an INTERFACE library "
  774. "that may not have PRE_BUILD, PRE_LINK, or POST_BUILD commands.";
  775. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  776. return;
  777. }
  778. // Always create the byproduct sources and mark them generated.
  779. for (std::string const& o : byproducts) {
  780. if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
  781. out->SetProperty("GENERATED", "1");
  782. }
  783. }
  784. // Add the command to the appropriate build step for the target.
  785. std::vector<std::string> no_output;
  786. cmCustomCommand cc(this, no_output, byproducts, depends, commandLines,
  787. comment, workingDir);
  788. cc.SetEscapeOldStyle(escapeOldStyle);
  789. cc.SetEscapeAllowMakeVars(true);
  790. cc.SetUsesTerminal(uses_terminal);
  791. cc.SetCommandExpandLists(command_expand_lists);
  792. cc.SetDepfile(depfile);
  793. cc.SetJobPool(job_pool);
  794. switch (type) {
  795. case cmTarget::PRE_BUILD:
  796. t.AddPreBuildCommand(cc);
  797. break;
  798. case cmTarget::PRE_LINK:
  799. t.AddPreLinkCommand(cc);
  800. break;
  801. case cmTarget::POST_BUILD:
  802. t.AddPostBuildCommand(cc);
  803. break;
  804. }
  805. }
  806. cmSourceFile* cmMakefile::AddCustomCommandToOutput(
  807. const std::vector<std::string>& outputs,
  808. const std::vector<std::string>& byproducts,
  809. const std::vector<std::string>& depends, const std::string& main_dependency,
  810. const cmCustomCommandLines& commandLines, const char* comment,
  811. const char* workingDir, bool replace, bool escapeOldStyle,
  812. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  813. const std::string& job_pool)
  814. {
  815. // Make sure there is at least one output.
  816. if (outputs.empty()) {
  817. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  818. return nullptr;
  819. }
  820. // Validate custom commands. TODO: More strict?
  821. for (cmCustomCommandLine const& cl : commandLines) {
  822. if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
  823. std::ostringstream e;
  824. e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
  825. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  826. return nullptr;
  827. }
  828. }
  829. // Choose a source file on which to store the custom command.
  830. cmSourceFile* file = nullptr;
  831. if (!commandLines.empty() && !main_dependency.empty()) {
  832. // The main dependency was specified. Use it unless a different
  833. // custom command already used it.
  834. file = this->GetSource(main_dependency);
  835. if (file && file->GetCustomCommand() && !replace) {
  836. // The main dependency already has a custom command.
  837. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  838. // The existing custom command is identical. Silently ignore
  839. // the duplicate.
  840. return file;
  841. }
  842. // The existing custom command is different. We need to
  843. // generate a rule file for this new command.
  844. file = nullptr;
  845. } else if (!file) {
  846. file = this->CreateSource(main_dependency);
  847. }
  848. }
  849. // Generate a rule file if the main dependency is not available.
  850. if (!file) {
  851. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  852. // Construct a rule file associated with the first output produced.
  853. std::string outName = gg->GenerateRuleFile(outputs[0]);
  854. // Check if the rule file already exists.
  855. file = this->GetSource(outName, cmSourceFileLocationKind::Known);
  856. if (file && file->GetCustomCommand() && !replace) {
  857. // The rule file already exists.
  858. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  859. cmSystemTools::Error("Attempt to add a custom rule to output \"" +
  860. outName + "\" which already has a custom rule.");
  861. }
  862. return file;
  863. }
  864. // Create a cmSourceFile for the rule file.
  865. if (!file) {
  866. file =
  867. this->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  868. }
  869. file->SetProperty("__CMAKE_RULE", "1");
  870. }
  871. // Always create the output sources and mark them generated.
  872. for (std::string const& o : outputs) {
  873. if (cmSourceFile* out =
  874. this->GetOrCreateSource(o, true, cmSourceFileLocationKind::Known)) {
  875. out->SetProperty("GENERATED", "1");
  876. }
  877. }
  878. for (std::string const& o : byproducts) {
  879. if (cmSourceFile* out =
  880. this->GetOrCreateSource(o, true, cmSourceFileLocationKind::Known)) {
  881. out->SetProperty("GENERATED", "1");
  882. }
  883. }
  884. // Attach the custom command to the file.
  885. if (file) {
  886. // Construct a complete list of dependencies.
  887. std::vector<std::string> depends2(depends);
  888. if (!main_dependency.empty()) {
  889. depends2.push_back(main_dependency);
  890. }
  891. cmCustomCommand* cc = new cmCustomCommand(
  892. this, outputs, byproducts, depends2, commandLines, comment, workingDir);
  893. cc->SetEscapeOldStyle(escapeOldStyle);
  894. cc->SetEscapeAllowMakeVars(true);
  895. cc->SetUsesTerminal(uses_terminal);
  896. cc->SetCommandExpandLists(command_expand_lists);
  897. cc->SetDepfile(depfile);
  898. cc->SetJobPool(job_pool);
  899. file->SetCustomCommand(cc);
  900. this->UpdateOutputToSourceMap(outputs, file);
  901. }
  902. return file;
  903. }
  904. void cmMakefile::UpdateOutputToSourceMap(
  905. std::vector<std::string> const& outputs, cmSourceFile* source)
  906. {
  907. for (std::string const& o : outputs) {
  908. this->UpdateOutputToSourceMap(o, source);
  909. }
  910. }
  911. void cmMakefile::UpdateOutputToSourceMap(std::string const& output,
  912. cmSourceFile* source)
  913. {
  914. OutputToSourceMap::iterator i = this->OutputToSource.find(output);
  915. if (i != this->OutputToSource.end()) {
  916. // Multiple custom commands produce the same output but may
  917. // be attached to a different source file (MAIN_DEPENDENCY).
  918. // LinearGetSourceFileWithOutput would return the first one,
  919. // so keep the mapping for the first one.
  920. //
  921. // TODO: Warn the user about this case. However, the VS 8 generator
  922. // triggers it for separate generate.stamp rules in ZERO_CHECK and
  923. // individual targets.
  924. return;
  925. }
  926. this->OutputToSource[output] = source;
  927. }
  928. cmSourceFile* cmMakefile::AddCustomCommandToOutput(
  929. const std::string& output, const std::vector<std::string>& depends,
  930. const std::string& main_dependency, const cmCustomCommandLines& commandLines,
  931. const char* comment, const char* workingDir, bool replace,
  932. bool escapeOldStyle, bool uses_terminal, bool command_expand_lists,
  933. const std::string& depfile, const std::string& job_pool)
  934. {
  935. std::vector<std::string> outputs;
  936. outputs.push_back(output);
  937. std::vector<std::string> no_byproducts;
  938. return this->AddCustomCommandToOutput(
  939. outputs, no_byproducts, depends, main_dependency, commandLines, comment,
  940. workingDir, replace, escapeOldStyle, uses_terminal, command_expand_lists,
  941. depfile, job_pool);
  942. }
  943. void cmMakefile::AddCustomCommandOldStyle(
  944. const std::string& target, const std::vector<std::string>& outputs,
  945. const std::vector<std::string>& depends, const std::string& source,
  946. const cmCustomCommandLines& commandLines, const char* comment)
  947. {
  948. // Translate the old-style signature to one of the new-style
  949. // signatures.
  950. if (source == target) {
  951. // In the old-style signature if the source and target were the
  952. // same then it added a post-build rule to the target. Preserve
  953. // this behavior.
  954. std::vector<std::string> no_byproducts;
  955. this->AddCustomCommandToTarget(target, no_byproducts, depends,
  956. commandLines, cmTarget::POST_BUILD, comment,
  957. nullptr);
  958. return;
  959. }
  960. // Each output must get its own copy of this rule.
  961. cmsys::RegularExpression sourceFiles("\\.(C|M|c|c\\+\\+|cc|cpp|cxx|cu|m|mm|"
  962. "rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
  963. "hm|hpp|hxx|in|txx|inl)$");
  964. for (std::string const& oi : outputs) {
  965. // Get the name of this output.
  966. const char* output = oi.c_str();
  967. cmSourceFile* sf;
  968. // Choose whether to use a main dependency.
  969. if (sourceFiles.find(source)) {
  970. // The source looks like a real file. Use it as the main dependency.
  971. sf = this->AddCustomCommandToOutput(output, depends, source,
  972. commandLines, comment, nullptr);
  973. } else {
  974. // The source may not be a real file. Do not use a main dependency.
  975. std::string no_main_dependency;
  976. std::vector<std::string> depends2 = depends;
  977. depends2.push_back(source);
  978. sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
  979. commandLines, comment, nullptr);
  980. }
  981. // If the rule was added to the source (and not a .rule file),
  982. // then add the source to the target to make sure the rule is
  983. // included.
  984. if (sf && !sf->GetPropertyAsBool("__CMAKE_RULE")) {
  985. cmTargetMap::iterator ti = this->Targets.find(target);
  986. if (ti != this->Targets.end()) {
  987. ti->second.AddSource(sf->GetFullPath());
  988. } else {
  989. cmSystemTools::Error("Attempt to add a custom rule to a target "
  990. "that does not exist yet for target " +
  991. target);
  992. return;
  993. }
  994. }
  995. }
  996. }
  997. cmTarget* cmMakefile::AddUtilityCommand(
  998. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  999. const std::vector<std::string>& depends, const char* workingDirectory,
  1000. const char* command, const char* arg1, const char* arg2, const char* arg3,
  1001. const char* arg4)
  1002. {
  1003. // Construct the command line for the custom command.
  1004. cmCustomCommandLine commandLine;
  1005. commandLine.push_back(command);
  1006. if (arg1) {
  1007. commandLine.push_back(arg1);
  1008. }
  1009. if (arg2) {
  1010. commandLine.push_back(arg2);
  1011. }
  1012. if (arg3) {
  1013. commandLine.push_back(arg3);
  1014. }
  1015. if (arg4) {
  1016. commandLine.push_back(arg4);
  1017. }
  1018. cmCustomCommandLines commandLines;
  1019. commandLines.push_back(std::move(commandLine));
  1020. // Call the real signature of this method.
  1021. return this->AddUtilityCommand(utilityName, origin, excludeFromAll,
  1022. workingDirectory, depends, commandLines);
  1023. }
  1024. cmTarget* cmMakefile::AddUtilityCommand(
  1025. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  1026. const char* workingDirectory, const std::vector<std::string>& depends,
  1027. const cmCustomCommandLines& commandLines, bool escapeOldStyle,
  1028. const char* comment, bool uses_terminal, bool command_expand_lists,
  1029. const std::string& job_pool)
  1030. {
  1031. std::vector<std::string> no_byproducts;
  1032. return this->AddUtilityCommand(
  1033. utilityName, origin, excludeFromAll, workingDirectory, no_byproducts,
  1034. depends, commandLines, escapeOldStyle, comment, uses_terminal,
  1035. command_expand_lists, job_pool);
  1036. }
  1037. cmTarget* cmMakefile::AddUtilityCommand(
  1038. const std::string& utilityName, TargetOrigin origin, bool excludeFromAll,
  1039. const char* workingDirectory, const std::vector<std::string>& byproducts,
  1040. const std::vector<std::string>& depends,
  1041. const cmCustomCommandLines& commandLines, bool escapeOldStyle,
  1042. const char* comment, bool uses_terminal, bool command_expand_lists,
  1043. const std::string& job_pool)
  1044. {
  1045. // Create a target instance for this utility.
  1046. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1047. target->SetIsGeneratorProvided(origin == TargetOrigin::Generator);
  1048. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1049. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1050. }
  1051. if (!comment) {
  1052. // Use an empty comment to avoid generation of default comment.
  1053. comment = "";
  1054. }
  1055. // Store the custom command in the target.
  1056. if (!commandLines.empty() || !depends.empty()) {
  1057. std::string force = this->GetCurrentBinaryDirectory();
  1058. force += "/CMakeFiles";
  1059. force += "/";
  1060. force += utilityName;
  1061. std::vector<std::string> forced;
  1062. forced.push_back(force);
  1063. std::string no_main_dependency;
  1064. bool no_replace = false;
  1065. this->AddCustomCommandToOutput(
  1066. forced, byproducts, depends, no_main_dependency, commandLines, comment,
  1067. workingDirectory, no_replace, escapeOldStyle, uses_terminal,
  1068. command_expand_lists, /*depfile=*/"", job_pool);
  1069. cmSourceFile* sf = target->AddSourceCMP0049(force);
  1070. // The output is not actually created so mark it symbolic.
  1071. if (sf) {
  1072. sf->SetProperty("SYMBOLIC", "1");
  1073. } else {
  1074. cmSystemTools::Error("Could not get source file entry for " + force);
  1075. }
  1076. // Always create the byproduct sources and mark them generated.
  1077. for (std::string const& byproduct : byproducts) {
  1078. if (cmSourceFile* out = this->GetOrCreateSource(
  1079. byproduct, true, cmSourceFileLocationKind::Known)) {
  1080. out->SetProperty("GENERATED", "1");
  1081. }
  1082. }
  1083. }
  1084. return target;
  1085. }
  1086. static void s_AddDefineFlag(std::string const& flag, std::string& dflags)
  1087. {
  1088. // remove any \n\r
  1089. std::string::size_type initSize = dflags.size();
  1090. dflags += ' ';
  1091. dflags += flag;
  1092. std::string::iterator flagStart = dflags.begin() + initSize + 1;
  1093. std::replace(flagStart, dflags.end(), '\n', ' ');
  1094. std::replace(flagStart, dflags.end(), '\r', ' ');
  1095. }
  1096. void cmMakefile::AddDefineFlag(std::string const& flag)
  1097. {
  1098. if (flag.empty()) {
  1099. return;
  1100. }
  1101. // Update the string used for the old DEFINITIONS property.
  1102. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1103. // If this is really a definition, update COMPILE_DEFINITIONS.
  1104. if (this->ParseDefineFlag(flag, false)) {
  1105. return;
  1106. }
  1107. // Add this flag that does not look like a definition.
  1108. s_AddDefineFlag(flag, this->DefineFlags);
  1109. }
  1110. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1111. {
  1112. std::string::size_type const len = flag.length();
  1113. // Remove all instances of the flag that are surrounded by
  1114. // whitespace or the beginning/end of the string.
  1115. for (std::string::size_type lpos = dflags.find(flag, 0);
  1116. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1117. std::string::size_type rpos = lpos + len;
  1118. if ((lpos <= 0 || isspace(dflags[lpos - 1])) &&
  1119. (rpos >= dflags.size() || isspace(dflags[rpos]))) {
  1120. dflags.erase(lpos, len);
  1121. } else {
  1122. ++lpos;
  1123. }
  1124. }
  1125. }
  1126. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1127. {
  1128. // Check the length of the flag to remove.
  1129. if (flag.empty()) {
  1130. return;
  1131. }
  1132. // Update the string used for the old DEFINITIONS property.
  1133. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1134. // If this is really a definition, update COMPILE_DEFINITIONS.
  1135. if (this->ParseDefineFlag(flag, true)) {
  1136. return;
  1137. }
  1138. // Remove this flag that does not look like a definition.
  1139. s_RemoveDefineFlag(flag, this->DefineFlags);
  1140. }
  1141. void cmMakefile::AddCompileDefinition(std::string const& option)
  1142. {
  1143. this->AppendProperty("COMPILE_DEFINITIONS", option.c_str());
  1144. }
  1145. void cmMakefile::AddCompileOption(std::string const& option)
  1146. {
  1147. this->AppendProperty("COMPILE_OPTIONS", option.c_str());
  1148. }
  1149. void cmMakefile::AddLinkOption(std::string const& option)
  1150. {
  1151. this->AppendProperty("LINK_OPTIONS", option.c_str());
  1152. }
  1153. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1154. {
  1155. cmListFileBacktrace lfbt = this->GetBacktrace();
  1156. if (before) {
  1157. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(directory,
  1158. lfbt);
  1159. } else {
  1160. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(directory,
  1161. lfbt);
  1162. }
  1163. }
  1164. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1165. {
  1166. // Create a regular expression to match valid definitions.
  1167. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1168. // Make sure the definition matches.
  1169. if (!valid.find(def)) {
  1170. return false;
  1171. }
  1172. // Definitions with non-trivial values require a policy check.
  1173. static cmsys::RegularExpression trivial(
  1174. "^[-/]D[A-Za-z_][A-Za-z0-9_]*(=[A-Za-z0-9_.]+)?$");
  1175. if (!trivial.find(def)) {
  1176. // This definition has a non-trivial value.
  1177. switch (this->GetPolicyStatus(cmPolicies::CMP0005)) {
  1178. case cmPolicies::WARN:
  1179. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1180. cmPolicies::GetPolicyWarning(cmPolicies::CMP0005));
  1181. CM_FALLTHROUGH;
  1182. case cmPolicies::OLD:
  1183. // OLD behavior is to not escape the value. We should not
  1184. // convert the definition to use the property.
  1185. return false;
  1186. case cmPolicies::REQUIRED_IF_USED:
  1187. case cmPolicies::REQUIRED_ALWAYS:
  1188. this->IssueMessage(
  1189. MessageType::FATAL_ERROR,
  1190. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0005));
  1191. return false;
  1192. case cmPolicies::NEW:
  1193. // NEW behavior is to escape the value. Proceed to convert it
  1194. // to an entry in the property.
  1195. break;
  1196. }
  1197. }
  1198. // Get the definition part after the flag.
  1199. const char* define = def.c_str() + 2;
  1200. if (remove) {
  1201. if (const char* cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1202. // Expand the list.
  1203. std::vector<std::string> defs;
  1204. cmExpandList(cdefs, defs);
  1205. // Recompose the list without the definition.
  1206. std::vector<std::string>::const_iterator defEnd =
  1207. std::remove(defs.begin(), defs.end(), define);
  1208. std::vector<std::string>::const_iterator defBegin = defs.begin();
  1209. std::string ndefs = cmJoin(cmMakeRange(defBegin, defEnd), ";");
  1210. // Store the new list.
  1211. this->SetProperty("COMPILE_DEFINITIONS", ndefs.c_str());
  1212. }
  1213. } else {
  1214. // Append the definition to the directory property.
  1215. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1216. }
  1217. return true;
  1218. }
  1219. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1220. {
  1221. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1222. // define flags
  1223. this->DefineFlags = parent->DefineFlags;
  1224. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1225. // Include transform property. There is no per-config version.
  1226. {
  1227. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1228. this->SetProperty(prop, parent->GetProperty(prop));
  1229. }
  1230. // compile definitions property and per-config versions
  1231. cmPolicies::PolicyStatus polSt = this->GetPolicyStatus(cmPolicies::CMP0043);
  1232. if (polSt == cmPolicies::WARN || polSt == cmPolicies::OLD) {
  1233. this->SetProperty("COMPILE_DEFINITIONS",
  1234. parent->GetProperty("COMPILE_DEFINITIONS"));
  1235. std::vector<std::string> configs;
  1236. this->GetConfigurations(configs);
  1237. for (std::string const& config : configs) {
  1238. std::string defPropName = "COMPILE_DEFINITIONS_";
  1239. defPropName += cmSystemTools::UpperCase(config);
  1240. const char* prop = parent->GetProperty(defPropName);
  1241. this->SetProperty(defPropName, prop);
  1242. }
  1243. }
  1244. // labels
  1245. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1246. // link libraries
  1247. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1248. // the initial project name
  1249. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1250. // Copy include regular expressions.
  1251. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1252. // Imported targets.
  1253. this->ImportedTargets = parent->ImportedTargets;
  1254. // Recursion depth.
  1255. this->RecursionDepth = parent->RecursionDepth;
  1256. }
  1257. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1258. const cmPolicies::PolicyMap& pm)
  1259. {
  1260. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1261. this->StateSnapshot, fileName);
  1262. assert(this->StateSnapshot.IsValid());
  1263. this->PushLoopBlockBarrier();
  1264. #if !defined(CMAKE_BOOTSTRAP)
  1265. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1266. #endif
  1267. this->PushFunctionBlockerBarrier();
  1268. this->PushPolicy(true, pm);
  1269. }
  1270. void cmMakefile::PopFunctionScope(bool reportError)
  1271. {
  1272. this->PopPolicy();
  1273. this->PopSnapshot(reportError);
  1274. this->PopFunctionBlockerBarrier(reportError);
  1275. #if !defined(CMAKE_BOOTSTRAP)
  1276. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1277. #endif
  1278. this->PopLoopBlockBarrier();
  1279. this->CheckForUnusedVariables();
  1280. }
  1281. void cmMakefile::PushMacroScope(std::string const& fileName,
  1282. const cmPolicies::PolicyMap& pm)
  1283. {
  1284. this->StateSnapshot =
  1285. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1286. assert(this->StateSnapshot.IsValid());
  1287. this->PushFunctionBlockerBarrier();
  1288. this->PushPolicy(true, pm);
  1289. }
  1290. void cmMakefile::PopMacroScope(bool reportError)
  1291. {
  1292. this->PopPolicy();
  1293. this->PopSnapshot(reportError);
  1294. this->PopFunctionBlockerBarrier(reportError);
  1295. }
  1296. bool cmMakefile::IsRootMakefile() const
  1297. {
  1298. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1299. }
  1300. class cmMakefile::BuildsystemFileScope
  1301. {
  1302. public:
  1303. BuildsystemFileScope(cmMakefile* mf)
  1304. : Makefile(mf)
  1305. , ReportError(true)
  1306. {
  1307. std::string currentStart =
  1308. this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource();
  1309. currentStart += "/CMakeLists.txt";
  1310. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1311. this->Makefile->StateSnapshot =
  1312. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1313. this->Makefile->StateSnapshot);
  1314. this->Makefile->PushFunctionBlockerBarrier();
  1315. this->GG = mf->GetGlobalGenerator();
  1316. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1317. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1318. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1319. this->GG->SetCurrentMakefile(mf);
  1320. #if !defined(CMAKE_BOOTSTRAP)
  1321. this->GG->GetFileLockPool().PushFileScope();
  1322. #endif
  1323. }
  1324. ~BuildsystemFileScope()
  1325. {
  1326. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1327. this->Makefile->PopSnapshot(this->ReportError);
  1328. #if !defined(CMAKE_BOOTSTRAP)
  1329. this->GG->GetFileLockPool().PopFileScope();
  1330. #endif
  1331. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1332. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1333. }
  1334. void Quiet() { this->ReportError = false; }
  1335. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1336. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1337. private:
  1338. cmMakefile* Makefile;
  1339. cmGlobalGenerator* GG;
  1340. cmMakefile* CurrentMakefile;
  1341. cmStateSnapshot Snapshot;
  1342. bool ReportError;
  1343. };
  1344. void cmMakefile::Configure()
  1345. {
  1346. std::string currentStart =
  1347. this->StateSnapshot.GetDirectory().GetCurrentSource();
  1348. currentStart += "/CMakeLists.txt";
  1349. // Add the bottom of all backtraces within this directory.
  1350. // We will never pop this scope because it should be available
  1351. // for messages during the generate step too.
  1352. this->Backtrace = this->Backtrace.Push(currentStart);
  1353. BuildsystemFileScope scope(this);
  1354. // make sure the CMakeFiles dir is there
  1355. std::string filesDir = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1356. filesDir += "/CMakeFiles";
  1357. cmSystemTools::MakeDirectory(filesDir);
  1358. assert(cmSystemTools::FileExists(currentStart, true));
  1359. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart);
  1360. cmListFile listFile;
  1361. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1362. this->Backtrace)) {
  1363. return;
  1364. }
  1365. if (this->IsRootMakefile()) {
  1366. bool hasVersion = false;
  1367. // search for the right policy command
  1368. for (cmListFileFunction const& func : listFile.Functions) {
  1369. if (func.Name.Lower == "cmake_minimum_required") {
  1370. hasVersion = true;
  1371. break;
  1372. }
  1373. }
  1374. // if no policy command is found this is an error if they use any
  1375. // non advanced functions or a lot of functions
  1376. if (!hasVersion) {
  1377. bool isProblem = true;
  1378. if (listFile.Functions.size() < 30) {
  1379. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1380. // these commands must have backwards compatibility forever and
  1381. // and that is a lot longer than your tiny mind can comprehend mortal
  1382. std::set<std::string> allowedCommands;
  1383. allowedCommands.insert("project");
  1384. allowedCommands.insert("set");
  1385. allowedCommands.insert("if");
  1386. allowedCommands.insert("endif");
  1387. allowedCommands.insert("else");
  1388. allowedCommands.insert("elseif");
  1389. allowedCommands.insert("add_executable");
  1390. allowedCommands.insert("add_library");
  1391. allowedCommands.insert("target_link_libraries");
  1392. allowedCommands.insert("option");
  1393. allowedCommands.insert("message");
  1394. isProblem = false;
  1395. for (cmListFileFunction const& func : listFile.Functions) {
  1396. if (allowedCommands.find(func.Name.Lower) == allowedCommands.end()) {
  1397. isProblem = true;
  1398. break;
  1399. }
  1400. }
  1401. }
  1402. if (isProblem) {
  1403. // Tell the top level cmMakefile to diagnose
  1404. // this violation of CMP0000.
  1405. this->SetCheckCMP0000(true);
  1406. // Implicitly set the version for the user.
  1407. this->SetPolicyVersion("2.4", std::string());
  1408. }
  1409. }
  1410. bool hasProject = false;
  1411. // search for a project command
  1412. for (cmListFileFunction const& func : listFile.Functions) {
  1413. if (func.Name.Lower == "project") {
  1414. hasProject = true;
  1415. break;
  1416. }
  1417. }
  1418. // if no project command is found, add one
  1419. if (!hasProject) {
  1420. this->GetCMakeInstance()->IssueMessage(
  1421. MessageType::AUTHOR_WARNING,
  1422. "No project() command is present. The top-level CMakeLists.txt "
  1423. "file must contain a literal, direct call to the project() command. "
  1424. "Add a line of code such as\n"
  1425. " project(ProjectName)\n"
  1426. "near the top of the file, but after cmake_minimum_required().\n"
  1427. "CMake is pretending there is a \"project(Project)\" command on "
  1428. "the first line.",
  1429. this->Backtrace);
  1430. cmListFileFunction project;
  1431. project.Name.Lower = "project";
  1432. project.Arguments.emplace_back("Project", cmListFileArgument::Unquoted,
  1433. 0);
  1434. project.Arguments.emplace_back("__CMAKE_INJECTED_PROJECT_COMMAND__",
  1435. cmListFileArgument::Unquoted, 0);
  1436. listFile.Functions.insert(listFile.Functions.begin(), project);
  1437. }
  1438. }
  1439. this->ReadListFile(listFile, currentStart);
  1440. if (cmSystemTools::GetFatalErrorOccured()) {
  1441. scope.Quiet();
  1442. }
  1443. // at the end handle any old style subdirs
  1444. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1445. // for each subdir recurse
  1446. std::vector<cmMakefile*>::iterator sdi = subdirs.begin();
  1447. for (; sdi != subdirs.end(); ++sdi) {
  1448. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1449. this->ConfigureSubDirectory(*sdi);
  1450. }
  1451. this->AddCMakeDependFilesFromUser();
  1452. }
  1453. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1454. {
  1455. mf->InitializeFromParent(this);
  1456. std::string currentStart = mf->GetCurrentSourceDirectory();
  1457. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1458. std::string msg = " Entering ";
  1459. msg += currentStart;
  1460. cmSystemTools::Message(msg);
  1461. }
  1462. std::string const currentStartFile = currentStart + "/CMakeLists.txt";
  1463. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1464. // The file is missing. Check policy CMP0014.
  1465. std::ostringstream e;
  1466. /* clang-format off */
  1467. e << "The source directory\n"
  1468. << " " << currentStart << "\n"
  1469. << "does not contain a CMakeLists.txt file.";
  1470. /* clang-format on */
  1471. switch (this->GetPolicyStatus(cmPolicies::CMP0014)) {
  1472. case cmPolicies::WARN:
  1473. // Print the warning.
  1474. /* clang-format off */
  1475. e << "\n"
  1476. << "CMake does not support this case but it used "
  1477. << "to work accidentally and is being allowed for "
  1478. << "compatibility."
  1479. << "\n"
  1480. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0014);
  1481. /* clang-format on */
  1482. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  1483. case cmPolicies::OLD:
  1484. // OLD behavior does not warn.
  1485. break;
  1486. case cmPolicies::REQUIRED_IF_USED:
  1487. case cmPolicies::REQUIRED_ALWAYS:
  1488. e << "\n" << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0014);
  1489. CM_FALLTHROUGH;
  1490. case cmPolicies::NEW:
  1491. // NEW behavior prints the error.
  1492. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1493. }
  1494. return;
  1495. }
  1496. // finally configure the subdir
  1497. mf->Configure();
  1498. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1499. std::string msg = " Returning to ";
  1500. msg += this->GetCurrentSourceDirectory();
  1501. cmSystemTools::Message(msg);
  1502. }
  1503. }
  1504. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1505. const std::string& binPath,
  1506. bool excludeFromAll, bool immediate)
  1507. {
  1508. // Make sure the binary directory is unique.
  1509. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1510. return;
  1511. }
  1512. cmStateSnapshot newSnapshot =
  1513. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1514. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1515. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1516. cmSystemTools::MakeDirectory(binPath);
  1517. cmMakefile* subMf = new cmMakefile(this->GlobalGenerator, newSnapshot);
  1518. this->GetGlobalGenerator()->AddMakefile(subMf);
  1519. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1520. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1521. }
  1522. if (immediate) {
  1523. this->ConfigureSubDirectory(subMf);
  1524. } else {
  1525. this->UnConfiguredDirectories.push_back(subMf);
  1526. }
  1527. this->AddInstallGenerator(new cmInstallSubdirectoryGenerator(
  1528. subMf, binPath.c_str(), excludeFromAll));
  1529. }
  1530. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1531. {
  1532. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1533. }
  1534. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1535. {
  1536. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1537. }
  1538. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1539. {
  1540. std::vector<cmTarget*> tgts;
  1541. tgts.reserve(this->ImportedTargets.size());
  1542. for (auto const& impTarget : this->ImportedTargets) {
  1543. tgts.push_back(impTarget.second);
  1544. }
  1545. return tgts;
  1546. }
  1547. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1548. bool before)
  1549. {
  1550. if (incs.empty()) {
  1551. return;
  1552. }
  1553. cmListFileBacktrace lfbt = this->GetBacktrace();
  1554. std::string entryString = cmJoin(incs, ";");
  1555. if (before) {
  1556. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1557. entryString, lfbt);
  1558. } else {
  1559. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1560. entryString, lfbt);
  1561. }
  1562. // Property on each target:
  1563. for (auto& target : this->Targets) {
  1564. cmTarget& t = target.second;
  1565. t.InsertInclude(entryString, lfbt, before);
  1566. }
  1567. }
  1568. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1569. {
  1570. if (incs.empty()) {
  1571. return;
  1572. }
  1573. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1574. for (auto& target : this->Targets) {
  1575. cmTarget& t = target.second;
  1576. t.AddSystemIncludeDirectories(incs);
  1577. }
  1578. }
  1579. void cmMakefile::AddDefinition(const std::string& name, cm::string_view value)
  1580. {
  1581. if (this->VariableInitialized(name)) {
  1582. this->LogUnused("changing definition", name);
  1583. }
  1584. this->StateSnapshot.SetDefinition(name, value);
  1585. #ifndef CMAKE_BOOTSTRAP
  1586. cmVariableWatch* vv = this->GetVariableWatch();
  1587. if (vv) {
  1588. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1589. value.data(), this);
  1590. }
  1591. #endif
  1592. }
  1593. void cmMakefile::AddDefinitionBool(const std::string& name, bool value)
  1594. {
  1595. this->AddDefinition(name, value ? "ON" : "OFF");
  1596. }
  1597. void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
  1598. const char* doc,
  1599. cmStateEnums::CacheEntryType type,
  1600. bool force)
  1601. {
  1602. const std::string* existingValue =
  1603. this->GetState()->GetInitializedCacheValue(name);
  1604. // must be outside the following if() to keep it alive long enough
  1605. std::string nvalue;
  1606. if (existingValue &&
  1607. (this->GetState()->GetCacheEntryType(name) ==
  1608. cmStateEnums::UNINITIALIZED)) {
  1609. // if this is not a force, then use the value from the cache
  1610. // if it is a force, then use the value being passed in
  1611. if (!force) {
  1612. value = existingValue->c_str();
  1613. }
  1614. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1615. std::vector<std::string>::size_type cc;
  1616. std::vector<std::string> files;
  1617. nvalue = value ? value : "";
  1618. cmExpandList(nvalue, files);
  1619. nvalue.clear();
  1620. for (cc = 0; cc < files.size(); cc++) {
  1621. if (!cmIsOff(files[cc])) {
  1622. files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
  1623. }
  1624. if (cc > 0) {
  1625. nvalue += ";";
  1626. }
  1627. nvalue += files[cc];
  1628. }
  1629. this->GetCMakeInstance()->AddCacheEntry(name, nvalue.c_str(), doc, type);
  1630. nvalue = *this->GetState()->GetInitializedCacheValue(name);
  1631. value = nvalue.c_str();
  1632. }
  1633. }
  1634. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1635. // if there was a definition then remove it
  1636. this->StateSnapshot.RemoveDefinition(name);
  1637. }
  1638. void cmMakefile::CheckForUnusedVariables() const
  1639. {
  1640. if (!this->WarnUnused) {
  1641. return;
  1642. }
  1643. for (const std::string& key : this->StateSnapshot.UnusedKeys()) {
  1644. this->LogUnused("out of scope", key);
  1645. }
  1646. }
  1647. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1648. {
  1649. this->StateSnapshot.GetDefinition(var);
  1650. }
  1651. bool cmMakefile::VariableInitialized(const std::string& var) const
  1652. {
  1653. return this->StateSnapshot.IsInitialized(var);
  1654. }
  1655. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1656. const char* sourceFilename) const
  1657. {
  1658. // check to see if we need to print a warning
  1659. // if strict mode is on and the variable has
  1660. // not been "cleared"/initialized with a set(foo ) call
  1661. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1662. !this->VariableInitialized(variable)) {
  1663. if (this->CheckSystemVars ||
  1664. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1665. std::ostringstream msg;
  1666. msg << "uninitialized variable \'" << variable << "\'";
  1667. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1668. }
  1669. }
  1670. }
  1671. void cmMakefile::LogUnused(const char* reason, const std::string& name) const
  1672. {
  1673. if (this->WarnUnused) {
  1674. std::string path;
  1675. if (!this->ExecutionStatusStack.empty()) {
  1676. path = this->GetExecutionContext().FilePath;
  1677. } else {
  1678. path = this->GetCurrentSourceDirectory();
  1679. path += "/CMakeLists.txt";
  1680. }
  1681. if (this->CheckSystemVars || this->IsProjectFile(path.c_str())) {
  1682. std::ostringstream msg;
  1683. msg << "unused variable (" << reason << ") \'" << name << "\'";
  1684. this->IssueMessage(MessageType::AUTHOR_WARNING, msg.str());
  1685. }
  1686. }
  1687. }
  1688. void cmMakefile::RemoveDefinition(const std::string& name)
  1689. {
  1690. if (this->VariableInitialized(name)) {
  1691. this->LogUnused("unsetting", name);
  1692. }
  1693. this->StateSnapshot.RemoveDefinition(name);
  1694. #ifndef CMAKE_BOOTSTRAP
  1695. cmVariableWatch* vv = this->GetVariableWatch();
  1696. if (vv) {
  1697. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1698. nullptr, this);
  1699. }
  1700. #endif
  1701. }
  1702. void cmMakefile::RemoveCacheDefinition(const std::string& name)
  1703. {
  1704. this->GetState()->RemoveCacheEntry(name);
  1705. }
  1706. void cmMakefile::SetProjectName(std::string const& p)
  1707. {
  1708. this->StateSnapshot.SetProjectName(p);
  1709. }
  1710. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1711. {
  1712. // for these targets do not add anything
  1713. switch (target.GetType()) {
  1714. case cmStateEnums::UTILITY:
  1715. case cmStateEnums::GLOBAL_TARGET:
  1716. case cmStateEnums::INTERFACE_LIBRARY:
  1717. return;
  1718. default:;
  1719. }
  1720. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1721. std::vector<std::string> linkLibs;
  1722. cmExpandList(linkLibsProp, linkLibs);
  1723. for (std::vector<std::string>::iterator j = linkLibs.begin();
  1724. j != linkLibs.end(); ++j) {
  1725. std::string libraryName = *j;
  1726. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1727. if (libraryName == "optimized") {
  1728. libType = OPTIMIZED_LibraryType;
  1729. ++j;
  1730. libraryName = *j;
  1731. } else if (libraryName == "debug") {
  1732. libType = DEBUG_LibraryType;
  1733. ++j;
  1734. libraryName = *j;
  1735. }
  1736. // This is equivalent to the target_link_libraries plain signature.
  1737. target.AddLinkLibrary(*this, libraryName, libType);
  1738. target.AppendProperty(
  1739. "INTERFACE_LINK_LIBRARIES",
  1740. target.GetDebugGeneratorExpressions(libraryName, libType).c_str());
  1741. }
  1742. }
  1743. }
  1744. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName)
  1745. {
  1746. this->AliasTargets[lname] = tgtName;
  1747. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1748. }
  1749. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1750. cmStateEnums::TargetType type,
  1751. const std::vector<std::string>& srcs,
  1752. bool excludeFromAll)
  1753. {
  1754. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1755. type == cmStateEnums::SHARED_LIBRARY ||
  1756. type == cmStateEnums::MODULE_LIBRARY ||
  1757. type == cmStateEnums::OBJECT_LIBRARY ||
  1758. type == cmStateEnums::INTERFACE_LIBRARY);
  1759. cmTarget* target = this->AddNewTarget(type, lname);
  1760. // Clear its dependencies. Otherwise, dependencies might persist
  1761. // over changes in CMakeLists.txt, making the information stale and
  1762. // hence useless.
  1763. target->ClearDependencyInformation(*this);
  1764. if (excludeFromAll ||
  1765. (type != cmStateEnums::INTERFACE_LIBRARY &&
  1766. this->GetPropertyAsBool("EXCLUDE_FROM_ALL"))) {
  1767. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1768. }
  1769. target->AddSources(srcs);
  1770. this->AddGlobalLinkInformation(*target);
  1771. return target;
  1772. }
  1773. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1774. const std::vector<std::string>& srcs,
  1775. bool excludeFromAll)
  1776. {
  1777. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1778. if (excludeFromAll || this->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1779. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1780. }
  1781. target->AddSources(srcs);
  1782. this->AddGlobalLinkInformation(*target);
  1783. return target;
  1784. }
  1785. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1786. const std::string& name)
  1787. {
  1788. cmTargetMap::iterator it =
  1789. this->Targets
  1790. .emplace(name, cmTarget(name, type, cmTarget::VisibilityNormal, this))
  1791. .first;
  1792. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1793. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1794. return &it->second;
  1795. }
  1796. cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput(
  1797. const std::string& name) const
  1798. {
  1799. std::string out;
  1800. // look through all the source files that have custom commands
  1801. // and see if the custom command has the passed source file as an output
  1802. for (cmSourceFile* src : this->SourceFiles) {
  1803. // does this source file have a custom command?
  1804. if (src->GetCustomCommand()) {
  1805. // Does the output of the custom command match the source file name?
  1806. const std::vector<std::string>& outputs =
  1807. src->GetCustomCommand()->GetOutputs();
  1808. for (std::string const& output : outputs) {
  1809. out = output;
  1810. std::string::size_type pos = out.rfind(name);
  1811. // If the output matches exactly
  1812. if (pos != std::string::npos && pos == out.size() - name.size() &&
  1813. (pos == 0 || out[pos - 1] == '/')) {
  1814. return src;
  1815. }
  1816. }
  1817. }
  1818. }
  1819. // otherwise return NULL
  1820. return nullptr;
  1821. }
  1822. cmSourceFile* cmMakefile::GetSourceFileWithOutput(
  1823. const std::string& name) const
  1824. {
  1825. // If the queried path is not absolute we use the backward compatible
  1826. // linear-time search for an output with a matching suffix.
  1827. if (!cmSystemTools::FileIsFullPath(name)) {
  1828. return this->LinearGetSourceFileWithOutput(name);
  1829. }
  1830. // Otherwise we use an efficient lookup map.
  1831. OutputToSourceMap::const_iterator o = this->OutputToSource.find(name);
  1832. if (o != this->OutputToSource.end()) {
  1833. return (*o).second;
  1834. }
  1835. return nullptr;
  1836. }
  1837. #if !defined(CMAKE_BOOTSTRAP)
  1838. cmSourceGroup* cmMakefile::GetSourceGroup(
  1839. const std::vector<std::string>& name) const
  1840. {
  1841. cmSourceGroup* sg = nullptr;
  1842. // first look for source group starting with the same as the one we want
  1843. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1844. std::string const& sgName = srcGroup.GetName();
  1845. if (sgName == name[0]) {
  1846. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1847. break;
  1848. }
  1849. }
  1850. if (sg != nullptr) {
  1851. // iterate through its children to find match source group
  1852. for (unsigned int i = 1; i < name.size(); ++i) {
  1853. sg = sg->LookupChild(name[i]);
  1854. if (sg == nullptr) {
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. return sg;
  1860. }
  1861. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1862. {
  1863. std::vector<std::string> nameVector;
  1864. nameVector.push_back(name);
  1865. this->AddSourceGroup(nameVector, regex);
  1866. }
  1867. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  1868. const char* regex)
  1869. {
  1870. cmSourceGroup* sg = nullptr;
  1871. std::vector<std::string> currentName;
  1872. int i = 0;
  1873. const int lastElement = static_cast<int>(name.size() - 1);
  1874. for (i = lastElement; i >= 0; --i) {
  1875. currentName.assign(name.begin(), name.begin() + i + 1);
  1876. sg = this->GetSourceGroup(currentName);
  1877. if (sg != nullptr) {
  1878. break;
  1879. }
  1880. }
  1881. // i now contains the index of the last found component
  1882. if (i == lastElement) {
  1883. // group already exists, replace its regular expression
  1884. if (regex && sg) {
  1885. // We only want to set the regular expression. If there are already
  1886. // source files in the group, we don't want to remove them.
  1887. sg->SetGroupRegex(regex);
  1888. }
  1889. return;
  1890. }
  1891. if (i == -1) {
  1892. // group does not exist nor belong to any existing group
  1893. // add its first component
  1894. this->SourceGroups.emplace_back(name[0], regex);
  1895. sg = this->GetSourceGroup(currentName);
  1896. i = 0; // last component found
  1897. }
  1898. if (!sg) {
  1899. cmSystemTools::Error("Could not create source group ");
  1900. return;
  1901. }
  1902. // build the whole source group path
  1903. for (++i; i <= lastElement; ++i) {
  1904. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1905. sg = sg->LookupChild(name[i]);
  1906. }
  1907. sg->SetGroupRegex(regex);
  1908. }
  1909. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1910. const std::vector<std::string>& folders)
  1911. {
  1912. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1913. if (sg == nullptr) {
  1914. this->AddSourceGroup(folders);
  1915. sg = this->GetSourceGroup(folders);
  1916. }
  1917. return sg;
  1918. }
  1919. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  1920. {
  1921. const char* delimiter = this->GetDefinition("SOURCE_GROUP_DELIMITER");
  1922. if (delimiter == nullptr) {
  1923. delimiter = "\\";
  1924. }
  1925. return this->GetOrCreateSourceGroup(cmTokenize(name, delimiter));
  1926. }
  1927. /**
  1928. * Find a source group whose regular expression matches the filename
  1929. * part of the given source name. Search backward through the list of
  1930. * source groups, and take the first matching group found. This way
  1931. * non-inherited SOURCE_GROUP commands will have precedence over
  1932. * inherited ones.
  1933. */
  1934. cmSourceGroup* cmMakefile::FindSourceGroup(
  1935. const std::string& source, std::vector<cmSourceGroup>& groups) const
  1936. {
  1937. // First search for a group that lists the file explicitly.
  1938. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1939. sg != groups.rend(); ++sg) {
  1940. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  1941. if (result) {
  1942. return result;
  1943. }
  1944. }
  1945. // Now search for a group whose regex matches the file.
  1946. for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
  1947. sg != groups.rend(); ++sg) {
  1948. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  1949. if (result) {
  1950. return result;
  1951. }
  1952. }
  1953. // Shouldn't get here, but just in case, return the default group.
  1954. return groups.data();
  1955. }
  1956. #endif
  1957. static bool mightExpandVariablesCMP0019(const char* s)
  1958. {
  1959. return s && *s && strstr(s, "${") && strchr(s, '}');
  1960. }
  1961. void cmMakefile::ExpandVariablesCMP0019()
  1962. {
  1963. // Drop this ancient compatibility behavior with a policy.
  1964. cmPolicies::PolicyStatus pol = this->GetPolicyStatus(cmPolicies::CMP0019);
  1965. if (pol != cmPolicies::OLD && pol != cmPolicies::WARN) {
  1966. return;
  1967. }
  1968. std::ostringstream w;
  1969. const char* includeDirs = this->GetProperty("INCLUDE_DIRECTORIES");
  1970. if (mightExpandVariablesCMP0019(includeDirs)) {
  1971. std::string dirs = includeDirs;
  1972. this->ExpandVariablesInString(dirs, true, true);
  1973. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1974. /* clang-format off */
  1975. w << "Evaluated directory INCLUDE_DIRECTORIES\n"
  1976. << " " << includeDirs << "\n"
  1977. << "as\n"
  1978. << " " << dirs << "\n";
  1979. /* clang-format on */
  1980. }
  1981. this->SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  1982. }
  1983. // Also for each target's INCLUDE_DIRECTORIES property:
  1984. for (auto& target : this->Targets) {
  1985. cmTarget& t = target.second;
  1986. if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  1987. t.GetType() == cmStateEnums::GLOBAL_TARGET) {
  1988. continue;
  1989. }
  1990. includeDirs = t.GetProperty("INCLUDE_DIRECTORIES");
  1991. if (mightExpandVariablesCMP0019(includeDirs)) {
  1992. std::string dirs = includeDirs;
  1993. this->ExpandVariablesInString(dirs, true, true);
  1994. if (pol == cmPolicies::WARN && dirs != includeDirs) {
  1995. /* clang-format off */
  1996. w << "Evaluated target " << t.GetName() << " INCLUDE_DIRECTORIES\n"
  1997. << " " << includeDirs << "\n"
  1998. << "as\n"
  1999. << " " << dirs << "\n";
  2000. /* clang-format on */
  2001. }
  2002. t.SetProperty("INCLUDE_DIRECTORIES", dirs.c_str());
  2003. }
  2004. }
  2005. if (const char* linkDirsProp = this->GetProperty("LINK_DIRECTORIES")) {
  2006. if (mightExpandVariablesCMP0019(linkDirsProp)) {
  2007. std::string d = linkDirsProp;
  2008. std::string orig = linkDirsProp;
  2009. this->ExpandVariablesInString(d, true, true);
  2010. if (pol == cmPolicies::WARN && d != orig) {
  2011. /* clang-format off */
  2012. w << "Evaluated link directories\n"
  2013. << " " << orig << "\n"
  2014. << "as\n"
  2015. << " " << d << "\n";
  2016. /* clang-format on */
  2017. }
  2018. }
  2019. }
  2020. if (const char* linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  2021. std::vector<std::string> linkLibs;
  2022. cmExpandList(linkLibsProp, linkLibs);
  2023. for (std::vector<std::string>::iterator l = linkLibs.begin();
  2024. l != linkLibs.end(); ++l) {
  2025. std::string libName = *l;
  2026. if (libName == "optimized") {
  2027. ++l;
  2028. libName = *l;
  2029. } else if (libName == "debug") {
  2030. ++l;
  2031. libName = *l;
  2032. }
  2033. if (mightExpandVariablesCMP0019(libName.c_str())) {
  2034. std::string orig = libName;
  2035. this->ExpandVariablesInString(libName, true, true);
  2036. if (pol == cmPolicies::WARN && libName != orig) {
  2037. /* clang-format off */
  2038. w << "Evaluated link library\n"
  2039. << " " << orig << "\n"
  2040. << "as\n"
  2041. << " " << libName << "\n";
  2042. /* clang-format on */
  2043. }
  2044. }
  2045. }
  2046. }
  2047. if (!w.str().empty()) {
  2048. std::ostringstream m;
  2049. /* clang-format off */
  2050. m << cmPolicies::GetPolicyWarning(cmPolicies::CMP0019)
  2051. << "\n"
  2052. << "The following variable evaluations were encountered:\n"
  2053. << w.str();
  2054. /* clang-format on */
  2055. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  2056. m.str(), this->Backtrace);
  2057. }
  2058. }
  2059. bool cmMakefile::IsOn(const std::string& name) const
  2060. {
  2061. const char* value = this->GetDefinition(name);
  2062. return cmIsOn(value);
  2063. }
  2064. bool cmMakefile::IsSet(const std::string& name) const
  2065. {
  2066. const char* value = this->GetDefinition(name);
  2067. if (!value) {
  2068. return false;
  2069. }
  2070. if (!*value) {
  2071. return false;
  2072. }
  2073. if (cmIsNOTFOUND(value)) {
  2074. return false;
  2075. }
  2076. return true;
  2077. }
  2078. bool cmMakefile::PlatformIs32Bit() const
  2079. {
  2080. if (const char* plat_abi =
  2081. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2082. if (strcmp(plat_abi, "ELF X32") == 0) {
  2083. return false;
  2084. }
  2085. }
  2086. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2087. return atoi(sizeof_dptr) == 4;
  2088. }
  2089. return false;
  2090. }
  2091. bool cmMakefile::PlatformIs64Bit() const
  2092. {
  2093. if (const char* sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  2094. return atoi(sizeof_dptr) == 8;
  2095. }
  2096. return false;
  2097. }
  2098. bool cmMakefile::PlatformIsx32() const
  2099. {
  2100. if (const char* plat_abi =
  2101. this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  2102. if (strcmp(plat_abi, "ELF X32") == 0) {
  2103. return true;
  2104. }
  2105. }
  2106. return false;
  2107. }
  2108. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  2109. {
  2110. std::string sdkRoot;
  2111. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  2112. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  2113. struct
  2114. {
  2115. std::string name;
  2116. AppleSDK sdk;
  2117. } const sdkDatabase[]{
  2118. { "appletvos", AppleSDK::AppleTVOS },
  2119. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  2120. { "iphoneos", AppleSDK::IPhoneOS },
  2121. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  2122. { "watchos", AppleSDK::WatchOS },
  2123. { "watchsimulator", AppleSDK::WatchSimulator },
  2124. };
  2125. for (auto const& entry : sdkDatabase) {
  2126. if (sdkRoot.find(entry.name) == 0 ||
  2127. sdkRoot.find(std::string("/") + entry.name) != std::string::npos) {
  2128. return entry.sdk;
  2129. }
  2130. }
  2131. return AppleSDK::MacOS;
  2132. }
  2133. bool cmMakefile::PlatformIsAppleEmbedded() const
  2134. {
  2135. return GetAppleSDKType() != AppleSDK::MacOS;
  2136. }
  2137. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  2138. {
  2139. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  2140. if (!language.empty()) {
  2141. name += "_";
  2142. name += language;
  2143. }
  2144. name += "_FLAG";
  2145. return GetDefinition(name);
  2146. }
  2147. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  2148. {
  2149. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  2150. return true;
  2151. }
  2152. // If we are doing an in-source build, then the test will always fail
  2153. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  2154. this->GetHomeOutputDirectory())) {
  2155. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  2156. }
  2157. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  2158. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  2159. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  2160. }
  2161. const std::string& cmMakefile::GetRequiredDefinition(
  2162. const std::string& name) const
  2163. {
  2164. static std::string const empty;
  2165. const std::string* def = GetDef(name);
  2166. if (!def) {
  2167. cmSystemTools::Error("Error required internal CMake variable not "
  2168. "set, cmake may not be built correctly.\n"
  2169. "Missing variable is:\n" +
  2170. name);
  2171. return empty;
  2172. }
  2173. return *def;
  2174. }
  2175. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2176. {
  2177. const std::string* def = this->StateSnapshot.GetDefinition(name);
  2178. if (!def) {
  2179. def = this->GetState()->GetInitializedCacheValue(name);
  2180. }
  2181. #ifndef CMAKE_BOOTSTRAP
  2182. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2183. if (!def) {
  2184. vv->VariableAccessed(
  2185. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2186. }
  2187. }
  2188. #endif
  2189. return def != nullptr;
  2190. }
  2191. const std::string* cmMakefile::GetDef(const std::string& name) const
  2192. {
  2193. const std::string* def = this->StateSnapshot.GetDefinition(name);
  2194. if (!def) {
  2195. def = this->GetState()->GetInitializedCacheValue(name);
  2196. }
  2197. #ifndef CMAKE_BOOTSTRAP
  2198. cmVariableWatch* vv = this->GetVariableWatch();
  2199. if (vv && !this->SuppressSideEffects) {
  2200. bool const watch_function_executed =
  2201. vv->VariableAccessed(name,
  2202. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2203. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2204. (def ? def->c_str() : nullptr), this);
  2205. if (watch_function_executed) {
  2206. // A callback was executed and may have caused re-allocation of the
  2207. // variable storage. Look it up again for now.
  2208. // FIXME: Refactor variable storage to avoid this problem.
  2209. def = this->StateSnapshot.GetDefinition(name);
  2210. if (!def) {
  2211. def = this->GetState()->GetInitializedCacheValue(name);
  2212. }
  2213. }
  2214. }
  2215. #endif
  2216. return def;
  2217. }
  2218. const char* cmMakefile::GetDefinition(const std::string& name) const
  2219. {
  2220. const std::string* def = GetDef(name);
  2221. if (!def) {
  2222. return nullptr;
  2223. }
  2224. return def->c_str();
  2225. }
  2226. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2227. {
  2228. static std::string const empty;
  2229. const std::string* def = GetDef(name);
  2230. if (!def) {
  2231. return empty;
  2232. }
  2233. return *def;
  2234. }
  2235. std::vector<std::string> cmMakefile::GetDefinitions() const
  2236. {
  2237. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2238. cmAppend(res, this->GetState()->GetCacheEntryKeys());
  2239. std::sort(res.begin(), res.end());
  2240. return res;
  2241. }
  2242. const std::string& cmMakefile::ExpandVariablesInString(
  2243. std::string& source) const
  2244. {
  2245. return this->ExpandVariablesInString(source, false, false);
  2246. }
  2247. const std::string& cmMakefile::ExpandVariablesInString(
  2248. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2249. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2250. {
  2251. bool compareResults = false;
  2252. MessageType mtype = MessageType::LOG;
  2253. std::string errorstr;
  2254. std::string original;
  2255. // Sanity check the @ONLY mode.
  2256. if (atOnly && (!noEscapes || !removeEmpty)) {
  2257. // This case should never be called. At-only is for
  2258. // configure-file/string which always does no escapes.
  2259. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2260. "ExpandVariablesInString @ONLY called "
  2261. "on something with escapes.");
  2262. return source;
  2263. }
  2264. // Variables used in the WARN case.
  2265. std::string newResult;
  2266. std::string newErrorstr;
  2267. MessageType newError = MessageType::LOG;
  2268. switch (this->GetPolicyStatus(cmPolicies::CMP0053)) {
  2269. case cmPolicies::WARN: {
  2270. // Save the original string for the warning.
  2271. original = source;
  2272. newResult = source;
  2273. compareResults = true;
  2274. // Suppress variable watches to avoid calling hooks twice. Suppress new
  2275. // dereferences since the OLD behavior is still what is actually used.
  2276. this->SuppressSideEffects = true;
  2277. newError = ExpandVariablesInStringNew(newErrorstr, newResult,
  2278. escapeQuotes, noEscapes, atOnly,
  2279. filename, line, replaceAt);
  2280. this->SuppressSideEffects = false;
  2281. CM_FALLTHROUGH;
  2282. }
  2283. case cmPolicies::OLD:
  2284. mtype =
  2285. ExpandVariablesInStringOld(errorstr, source, escapeQuotes, noEscapes,
  2286. atOnly, filename, line, removeEmpty, true);
  2287. break;
  2288. case cmPolicies::REQUIRED_IF_USED:
  2289. case cmPolicies::REQUIRED_ALWAYS:
  2290. // Messaging here would be *very* verbose.
  2291. case cmPolicies::NEW:
  2292. mtype =
  2293. ExpandVariablesInStringNew(errorstr, source, escapeQuotes, noEscapes,
  2294. atOnly, filename, line, replaceAt);
  2295. break;
  2296. }
  2297. // If it's an error in either case, just report the error...
  2298. if (mtype != MessageType::LOG) {
  2299. if (mtype == MessageType::FATAL_ERROR) {
  2300. cmSystemTools::SetFatalErrorOccured();
  2301. }
  2302. this->IssueMessage(mtype, errorstr);
  2303. }
  2304. // ...otherwise, see if there's a difference that needs to be warned about.
  2305. else if (compareResults && (newResult != source || newError != mtype)) {
  2306. std::string msg = cmPolicies::GetPolicyWarning(cmPolicies::CMP0053);
  2307. msg += "\n";
  2308. std::string msg_input = original;
  2309. cmSystemTools::ReplaceString(msg_input, "\n", "\n ");
  2310. msg += "For input:\n '";
  2311. msg += msg_input;
  2312. msg += "'\n";
  2313. std::string msg_old = source;
  2314. cmSystemTools::ReplaceString(msg_old, "\n", "\n ");
  2315. msg += "the old evaluation rules produce:\n '";
  2316. msg += msg_old;
  2317. msg += "'\n";
  2318. if (newError == mtype) {
  2319. std::string msg_new = newResult;
  2320. cmSystemTools::ReplaceString(msg_new, "\n", "\n ");
  2321. msg += "but the new evaluation rules produce:\n '";
  2322. msg += msg_new;
  2323. msg += "'\n";
  2324. } else {
  2325. std::string msg_err = newErrorstr;
  2326. cmSystemTools::ReplaceString(msg_err, "\n", "\n ");
  2327. msg += "but the new evaluation rules produce an error:\n ";
  2328. msg += msg_err;
  2329. msg += "\n";
  2330. }
  2331. msg +=
  2332. "Using the old result for compatibility since the policy is not set.";
  2333. this->IssueMessage(MessageType::AUTHOR_WARNING, msg);
  2334. }
  2335. return source;
  2336. }
  2337. MessageType cmMakefile::ExpandVariablesInStringOld(
  2338. std::string& errorstr, std::string& source, bool escapeQuotes,
  2339. bool noEscapes, bool atOnly, const char* filename, long line,
  2340. bool removeEmpty, bool replaceAt) const
  2341. {
  2342. // Fast path strings without any special characters.
  2343. if (source.find_first_of("$@\\") == std::string::npos) {
  2344. return MessageType::LOG;
  2345. }
  2346. // Special-case the @ONLY mode.
  2347. if (atOnly) {
  2348. // Store an original copy of the input.
  2349. std::string input = source;
  2350. // Start with empty output.
  2351. source.clear();
  2352. // Look for one @VAR@ at a time.
  2353. const char* in = input.c_str();
  2354. while (this->cmAtVarRegex.find(in)) {
  2355. // Get the range of the string to replace.
  2356. const char* first = in + this->cmAtVarRegex.start();
  2357. const char* last = in + this->cmAtVarRegex.end();
  2358. // Store the unchanged part of the string now.
  2359. source.append(in, first - in);
  2360. // Lookup the definition of VAR.
  2361. std::string var(first + 1, last - first - 2);
  2362. if (const char* val = this->GetDefinition(var)) {
  2363. // Store the value in the output escaping as requested.
  2364. if (escapeQuotes) {
  2365. source.append(cmEscapeQuotes(val));
  2366. } else {
  2367. source.append(val);
  2368. }
  2369. }
  2370. // Continue looking for @VAR@ further along the string.
  2371. in = last;
  2372. }
  2373. // Append the rest of the unchanged part of the string.
  2374. source.append(in);
  2375. return MessageType::LOG;
  2376. }
  2377. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2378. // with GetDefinition(), if not found in the map, nothing is expanded.
  2379. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2380. // the current environment variables.
  2381. cmCommandArgumentParserHelper parser;
  2382. parser.SetMakefile(this);
  2383. parser.SetLineFile(line, filename);
  2384. parser.SetEscapeQuotes(escapeQuotes);
  2385. parser.SetNoEscapeMode(noEscapes);
  2386. parser.SetReplaceAtSyntax(replaceAt);
  2387. parser.SetRemoveEmpty(removeEmpty);
  2388. int res = parser.ParseString(source.c_str(), 0);
  2389. const char* emsg = parser.GetError();
  2390. MessageType mtype = MessageType::LOG;
  2391. if (res && !emsg[0]) {
  2392. source = parser.GetResult();
  2393. } else {
  2394. // Construct the main error message.
  2395. std::ostringstream error;
  2396. error << "Syntax error in cmake code ";
  2397. if (filename && line > 0) {
  2398. // This filename and line number may be more specific than the
  2399. // command context because one command invocation can have
  2400. // arguments on multiple lines.
  2401. error << "at\n"
  2402. << " " << filename << ":" << line << "\n";
  2403. }
  2404. error << "when parsing string\n"
  2405. << " " << source << "\n";
  2406. error << emsg;
  2407. // If the parser failed ("res" is false) then this is a real
  2408. // argument parsing error, so the policy applies. Otherwise the
  2409. // parser reported an error message without failing because the
  2410. // helper implementation is unhappy, which has always reported an
  2411. // error.
  2412. mtype = MessageType::FATAL_ERROR;
  2413. if (!res) {
  2414. // This is a real argument parsing error. Use policy CMP0010 to
  2415. // decide whether it is an error.
  2416. switch (this->GetPolicyStatus(cmPolicies::CMP0010)) {
  2417. case cmPolicies::WARN:
  2418. error << "\n" << cmPolicies::GetPolicyWarning(cmPolicies::CMP0010);
  2419. CM_FALLTHROUGH;
  2420. case cmPolicies::OLD:
  2421. // OLD behavior is to just warn and continue.
  2422. mtype = MessageType::AUTHOR_WARNING;
  2423. break;
  2424. case cmPolicies::REQUIRED_IF_USED:
  2425. case cmPolicies::REQUIRED_ALWAYS:
  2426. error << "\n"
  2427. << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0010);
  2428. case cmPolicies::NEW:
  2429. // NEW behavior is to report the error.
  2430. break;
  2431. }
  2432. }
  2433. errorstr = error.str();
  2434. }
  2435. return mtype;
  2436. }
  2437. typedef enum
  2438. {
  2439. NORMAL,
  2440. ENVIRONMENT,
  2441. CACHE
  2442. } t_domain;
  2443. struct t_lookup
  2444. {
  2445. t_domain domain = NORMAL;
  2446. size_t loc = 0;
  2447. };
  2448. bool cmMakefile::IsProjectFile(const char* filename) const
  2449. {
  2450. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2451. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2452. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2453. }
  2454. int cmMakefile::GetRecursionDepth() const
  2455. {
  2456. return this->RecursionDepth;
  2457. }
  2458. void cmMakefile::SetRecursionDepth(int recursionDepth)
  2459. {
  2460. this->RecursionDepth = recursionDepth;
  2461. }
  2462. MessageType cmMakefile::ExpandVariablesInStringNew(
  2463. std::string& errorstr, std::string& source, bool escapeQuotes,
  2464. bool noEscapes, bool atOnly, const char* filename, long line,
  2465. bool replaceAt) const
  2466. {
  2467. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2468. // with GetDefinition(), if not found in the map, nothing is expanded.
  2469. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2470. // the current environment variables.
  2471. const char* in = source.c_str();
  2472. const char* last = in;
  2473. std::string result;
  2474. result.reserve(source.size());
  2475. std::vector<t_lookup> openstack;
  2476. bool error = false;
  2477. bool done = false;
  2478. MessageType mtype = MessageType::LOG;
  2479. cmState* state = this->GetCMakeInstance()->GetState();
  2480. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2481. do {
  2482. char inc = *in;
  2483. switch (inc) {
  2484. case '}':
  2485. if (!openstack.empty()) {
  2486. t_lookup var = openstack.back();
  2487. openstack.pop_back();
  2488. result.append(last, in - last);
  2489. std::string const& lookup = result.substr(var.loc);
  2490. const char* value = nullptr;
  2491. std::string varresult;
  2492. std::string svalue;
  2493. switch (var.domain) {
  2494. case NORMAL:
  2495. if (filename && lookup == lineVar) {
  2496. std::ostringstream ostr;
  2497. ostr << line;
  2498. varresult = ostr.str();
  2499. } else {
  2500. value = this->GetDefinition(lookup);
  2501. }
  2502. break;
  2503. case ENVIRONMENT:
  2504. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2505. value = svalue.c_str();
  2506. }
  2507. break;
  2508. case CACHE:
  2509. value = state->GetCacheEntryValue(lookup);
  2510. break;
  2511. }
  2512. // Get the string we're meant to append to.
  2513. if (value) {
  2514. if (escapeQuotes) {
  2515. varresult = cmEscapeQuotes(value);
  2516. } else {
  2517. varresult = value;
  2518. }
  2519. } else if (!this->SuppressSideEffects) {
  2520. this->MaybeWarnUninitialized(lookup, filename);
  2521. }
  2522. result.replace(var.loc, result.size() - var.loc, varresult);
  2523. // Start looking from here on out.
  2524. last = in + 1;
  2525. }
  2526. break;
  2527. case '$':
  2528. if (!atOnly) {
  2529. t_lookup lookup;
  2530. const char* next = in + 1;
  2531. const char* start = nullptr;
  2532. char nextc = *next;
  2533. if (nextc == '{') {
  2534. // Looking for a variable.
  2535. start = in + 2;
  2536. lookup.domain = NORMAL;
  2537. } else if (nextc == '<') {
  2538. } else if (!nextc) {
  2539. result.append(last, next - last);
  2540. last = next;
  2541. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2542. // Looking for an environment variable.
  2543. start = in + 5;
  2544. lookup.domain = ENVIRONMENT;
  2545. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2546. // Looking for a cache variable.
  2547. start = in + 7;
  2548. lookup.domain = CACHE;
  2549. } else {
  2550. if (this->cmNamedCurly.find(next)) {
  2551. errorstr = "Syntax $" +
  2552. std::string(next, this->cmNamedCurly.end()) +
  2553. "{} is not supported. Only ${}, $ENV{}, "
  2554. "and $CACHE{} are allowed.";
  2555. mtype = MessageType::FATAL_ERROR;
  2556. error = true;
  2557. }
  2558. }
  2559. if (start) {
  2560. result.append(last, in - last);
  2561. last = start;
  2562. in = start - 1;
  2563. lookup.loc = result.size();
  2564. openstack.push_back(lookup);
  2565. }
  2566. break;
  2567. }
  2568. CM_FALLTHROUGH;
  2569. case '\\':
  2570. if (!noEscapes) {
  2571. const char* next = in + 1;
  2572. char nextc = *next;
  2573. if (nextc == 't') {
  2574. result.append(last, in - last);
  2575. result.append("\t");
  2576. last = next + 1;
  2577. } else if (nextc == 'n') {
  2578. result.append(last, in - last);
  2579. result.append("\n");
  2580. last = next + 1;
  2581. } else if (nextc == 'r') {
  2582. result.append(last, in - last);
  2583. result.append("\r");
  2584. last = next + 1;
  2585. } else if (nextc == ';' && openstack.empty()) {
  2586. // Handled in ExpandListArgument; pass the backslash literally.
  2587. } else if (isalnum(nextc) || nextc == '\0') {
  2588. errorstr += "Invalid character escape '\\";
  2589. if (nextc) {
  2590. errorstr += nextc;
  2591. errorstr += "'.";
  2592. } else {
  2593. errorstr += "' (at end of input).";
  2594. }
  2595. error = true;
  2596. } else {
  2597. // Take what we've found so far, skipping the escape character.
  2598. result.append(last, in - last);
  2599. // Start tracking from the next character.
  2600. last = in + 1;
  2601. }
  2602. // Skip the next character since it was escaped, but don't read past
  2603. // the end of the string.
  2604. if (*last) {
  2605. ++in;
  2606. }
  2607. }
  2608. break;
  2609. case '\n':
  2610. // Onto the next line.
  2611. ++line;
  2612. break;
  2613. case '\0':
  2614. done = true;
  2615. break;
  2616. case '@':
  2617. if (replaceAt) {
  2618. const char* nextAt = strchr(in + 1, '@');
  2619. if (nextAt && nextAt != in + 1 &&
  2620. nextAt ==
  2621. in + 1 +
  2622. strspn(in + 1,
  2623. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2624. "abcdefghijklmnopqrstuvwxyz"
  2625. "0123456789/_.+-")) {
  2626. std::string variable(in + 1, nextAt - in - 1);
  2627. std::string varresult;
  2628. if (filename && variable == lineVar) {
  2629. varresult = std::to_string(line);
  2630. } else {
  2631. const std::string* def = this->GetDef(variable);
  2632. if (def) {
  2633. varresult = *def;
  2634. } else if (!this->SuppressSideEffects) {
  2635. this->MaybeWarnUninitialized(variable, filename);
  2636. }
  2637. }
  2638. if (escapeQuotes) {
  2639. varresult = cmEscapeQuotes(varresult);
  2640. }
  2641. // Skip over the variable.
  2642. result.append(last, in - last);
  2643. result.append(varresult);
  2644. in = nextAt;
  2645. last = in + 1;
  2646. break;
  2647. }
  2648. }
  2649. // Failed to find a valid @ expansion; treat it as literal.
  2650. /* FALLTHROUGH */
  2651. default: {
  2652. if (!openstack.empty() &&
  2653. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2654. inc == '+' || inc == '-')) {
  2655. errorstr += "Invalid character (\'";
  2656. errorstr += inc;
  2657. result.append(last, in - last);
  2658. errorstr += "\') in a variable name: "
  2659. "'" +
  2660. result.substr(openstack.back().loc) + "'";
  2661. mtype = MessageType::FATAL_ERROR;
  2662. error = true;
  2663. }
  2664. break;
  2665. }
  2666. }
  2667. // Look at the next character.
  2668. } while (!error && !done && *++in);
  2669. // Check for open variable references yet.
  2670. if (!error && !openstack.empty()) {
  2671. // There's an open variable reference waiting. Policy CMP0010 flags
  2672. // whether this is an error or not. The new parser now enforces
  2673. // CMP0010 as well.
  2674. errorstr += "There is an unterminated variable reference.";
  2675. error = true;
  2676. }
  2677. if (error) {
  2678. std::ostringstream emsg;
  2679. emsg << "Syntax error in cmake code ";
  2680. if (filename) {
  2681. // This filename and line number may be more specific than the
  2682. // command context because one command invocation can have
  2683. // arguments on multiple lines.
  2684. emsg << "at\n"
  2685. << " " << filename << ":" << line << "\n";
  2686. }
  2687. emsg << "when parsing string\n"
  2688. << " " << source << "\n";
  2689. emsg << errorstr;
  2690. mtype = MessageType::FATAL_ERROR;
  2691. errorstr = emsg.str();
  2692. } else {
  2693. // Append the rest of the unchanged part of the string.
  2694. result.append(last);
  2695. source = result;
  2696. }
  2697. return mtype;
  2698. }
  2699. void cmMakefile::RemoveVariablesInString(std::string& source,
  2700. bool atOnly) const
  2701. {
  2702. if (!atOnly) {
  2703. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2704. while (var.find(source)) {
  2705. source.erase(var.start(), var.end() - var.start());
  2706. }
  2707. }
  2708. if (!atOnly) {
  2709. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2710. while (varb.find(source)) {
  2711. source.erase(varb.start(), varb.end() - varb.start());
  2712. }
  2713. }
  2714. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2715. while (var2.find(source)) {
  2716. source.erase(var2.start(), var2.end() - var2.start());
  2717. }
  2718. }
  2719. std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs,
  2720. bool singleConfig) const
  2721. {
  2722. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2723. if (const char* configTypes =
  2724. this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2725. cmExpandList(configTypes, configs);
  2726. }
  2727. return "";
  2728. }
  2729. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2730. if (singleConfig && !buildType.empty()) {
  2731. configs.push_back(buildType);
  2732. }
  2733. return buildType;
  2734. }
  2735. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2736. cmExecutionStatus& status)
  2737. {
  2738. // if there are no blockers get out of here
  2739. if (this->FunctionBlockers.empty()) {
  2740. return false;
  2741. }
  2742. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2743. }
  2744. void cmMakefile::PushFunctionBlockerBarrier()
  2745. {
  2746. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2747. }
  2748. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2749. {
  2750. // Remove any extra entries pushed on the barrier.
  2751. FunctionBlockersType::size_type barrier =
  2752. this->FunctionBlockerBarriers.back();
  2753. while (this->FunctionBlockers.size() > barrier) {
  2754. std::unique_ptr<cmFunctionBlocker> fb(
  2755. std::move(this->FunctionBlockers.top()));
  2756. this->FunctionBlockers.pop();
  2757. if (reportError) {
  2758. // Report the context in which the unclosed block was opened.
  2759. cmListFileContext const& lfc = fb->GetStartingContext();
  2760. std::ostringstream e;
  2761. /* clang-format off */
  2762. e << "A logical block opening on the line\n"
  2763. << " " << lfc << "\n"
  2764. << "is not closed.";
  2765. /* clang-format on */
  2766. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2767. reportError = false;
  2768. }
  2769. }
  2770. // Remove the barrier.
  2771. this->FunctionBlockerBarriers.pop_back();
  2772. }
  2773. void cmMakefile::PushLoopBlock()
  2774. {
  2775. assert(!this->LoopBlockCounter.empty());
  2776. this->LoopBlockCounter.top()++;
  2777. }
  2778. void cmMakefile::PopLoopBlock()
  2779. {
  2780. assert(!this->LoopBlockCounter.empty());
  2781. assert(this->LoopBlockCounter.top() > 0);
  2782. this->LoopBlockCounter.top()--;
  2783. }
  2784. void cmMakefile::PushLoopBlockBarrier()
  2785. {
  2786. this->LoopBlockCounter.push(0);
  2787. }
  2788. void cmMakefile::PopLoopBlockBarrier()
  2789. {
  2790. assert(!this->LoopBlockCounter.empty());
  2791. assert(this->LoopBlockCounter.top() == 0);
  2792. this->LoopBlockCounter.pop();
  2793. }
  2794. bool cmMakefile::IsLoopBlock() const
  2795. {
  2796. assert(!this->LoopBlockCounter.empty());
  2797. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  2798. }
  2799. std::string cmMakefile::GetExecutionFilePath() const
  2800. {
  2801. assert(this->StateSnapshot.IsValid());
  2802. return this->StateSnapshot.GetExecutionListFile();
  2803. }
  2804. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  2805. std::vector<std::string>& outArgs,
  2806. const char* filename) const
  2807. {
  2808. std::string efp = this->GetExecutionFilePath();
  2809. if (!filename) {
  2810. filename = efp.c_str();
  2811. }
  2812. std::string value;
  2813. outArgs.reserve(inArgs.size());
  2814. for (cmListFileArgument const& i : inArgs) {
  2815. // No expansion in a bracket argument.
  2816. if (i.Delim == cmListFileArgument::Bracket) {
  2817. outArgs.push_back(i.Value);
  2818. continue;
  2819. }
  2820. // Expand the variables in the argument.
  2821. value = i.Value;
  2822. this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
  2823. false, false);
  2824. // If the argument is quoted, it should be one argument.
  2825. // Otherwise, it may be a list of arguments.
  2826. if (i.Delim == cmListFileArgument::Quoted) {
  2827. outArgs.push_back(value);
  2828. } else {
  2829. cmExpandList(value, outArgs);
  2830. }
  2831. }
  2832. return !cmSystemTools::GetFatalErrorOccured();
  2833. }
  2834. bool cmMakefile::ExpandArguments(
  2835. std::vector<cmListFileArgument> const& inArgs,
  2836. std::vector<cmExpandedCommandArgument>& outArgs, const char* filename) const
  2837. {
  2838. std::string efp = this->GetExecutionFilePath();
  2839. if (!filename) {
  2840. filename = efp.c_str();
  2841. }
  2842. std::string value;
  2843. outArgs.reserve(inArgs.size());
  2844. for (cmListFileArgument const& i : inArgs) {
  2845. // No expansion in a bracket argument.
  2846. if (i.Delim == cmListFileArgument::Bracket) {
  2847. outArgs.emplace_back(i.Value, true);
  2848. continue;
  2849. }
  2850. // Expand the variables in the argument.
  2851. value = i.Value;
  2852. this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
  2853. false, false);
  2854. // If the argument is quoted, it should be one argument.
  2855. // Otherwise, it may be a list of arguments.
  2856. if (i.Delim == cmListFileArgument::Quoted) {
  2857. outArgs.emplace_back(value, true);
  2858. } else {
  2859. std::vector<std::string> stringArgs;
  2860. cmExpandList(value, stringArgs);
  2861. for (std::string const& stringArg : stringArgs) {
  2862. outArgs.emplace_back(stringArg, false);
  2863. }
  2864. }
  2865. }
  2866. return !cmSystemTools::GetFatalErrorOccured();
  2867. }
  2868. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  2869. {
  2870. if (!this->ExecutionStatusStack.empty()) {
  2871. // Record the context in which the blocker is created.
  2872. fb->SetStartingContext(this->GetExecutionContext());
  2873. }
  2874. this->FunctionBlockers.push(std::move(fb));
  2875. }
  2876. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  2877. {
  2878. assert(!this->FunctionBlockers.empty());
  2879. assert(this->FunctionBlockerBarriers.empty() ||
  2880. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  2881. auto b = std::move(this->FunctionBlockers.top());
  2882. this->FunctionBlockers.pop();
  2883. return b;
  2884. }
  2885. std::string const& cmMakefile::GetHomeDirectory() const
  2886. {
  2887. return this->GetCMakeInstance()->GetHomeDirectory();
  2888. }
  2889. std::string const& cmMakefile::GetHomeOutputDirectory() const
  2890. {
  2891. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2892. }
  2893. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  2894. {
  2895. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  2896. }
  2897. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  2898. {
  2899. std::ostringstream strStream;
  2900. strStream << args.size();
  2901. this->AddDefinition("CMAKE_ARGC", strStream.str());
  2902. // this->MarkVariableAsUsed("CMAKE_ARGC");
  2903. for (unsigned int t = 0; t < args.size(); ++t) {
  2904. std::ostringstream tmpStream;
  2905. tmpStream << "CMAKE_ARGV" << t;
  2906. this->AddDefinition(tmpStream.str(), args[t]);
  2907. // this->MarkVariableAsUsed(tmpStream.str().c_str());
  2908. }
  2909. }
  2910. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  2911. cmSourceFileLocationKind kind) const
  2912. {
  2913. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  2914. if (kind == cmSourceFileLocationKind::Known) {
  2915. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  2916. if (sfsi != this->KnownFileSearchIndex.end()) {
  2917. return sfsi->second;
  2918. }
  2919. }
  2920. cmSourceFileLocation sfl(this, sourceName, kind);
  2921. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  2922. #if defined(_WIN32) || defined(__APPLE__)
  2923. name = cmSystemTools::LowerCase(name);
  2924. #endif
  2925. auto sfsi = this->SourceFileSearchIndex.find(name);
  2926. if (sfsi != this->SourceFileSearchIndex.end()) {
  2927. for (auto sf : sfsi->second) {
  2928. if (sf->Matches(sfl)) {
  2929. return sf;
  2930. }
  2931. }
  2932. }
  2933. return nullptr;
  2934. }
  2935. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  2936. bool generated,
  2937. cmSourceFileLocationKind kind)
  2938. {
  2939. cmSourceFile* sf = new cmSourceFile(this, sourceName, kind);
  2940. if (generated) {
  2941. sf->SetProperty("GENERATED", "1");
  2942. }
  2943. this->SourceFiles.push_back(sf);
  2944. auto name =
  2945. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  2946. #if defined(_WIN32) || defined(__APPLE__)
  2947. name = cmSystemTools::LowerCase(name);
  2948. #endif
  2949. this->SourceFileSearchIndex[name].push_back(sf);
  2950. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  2951. if (kind == cmSourceFileLocationKind::Known) {
  2952. this->KnownFileSearchIndex[sourceName] = sf;
  2953. }
  2954. return sf;
  2955. }
  2956. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  2957. bool generated,
  2958. cmSourceFileLocationKind kind)
  2959. {
  2960. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  2961. return esf;
  2962. }
  2963. return this->CreateSource(sourceName, generated, kind);
  2964. }
  2965. void cmMakefile::AddTargetObject(std::string const& tgtName,
  2966. std::string const& objFile)
  2967. {
  2968. cmSourceFile* sf = this->GetOrCreateSource(objFile, true);
  2969. sf->SetObjectLibrary(tgtName);
  2970. sf->SetProperty("EXTERNAL_OBJECT", "1");
  2971. #if !defined(CMAKE_BOOTSTRAP)
  2972. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  2973. sf->GetFullPath());
  2974. #endif
  2975. }
  2976. void cmMakefile::EnableLanguage(std::vector<std::string> const& lang,
  2977. bool optional)
  2978. {
  2979. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  2980. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  2981. }
  2982. // If RC is explicitly listed we need to do it after other languages.
  2983. // On some platforms we enable RC implicitly while enabling others.
  2984. // Do not let that look like recursive enable_language(RC).
  2985. std::vector<std::string> langs;
  2986. std::vector<std::string> langsRC;
  2987. langs.reserve(lang.size());
  2988. for (std::string const& i : lang) {
  2989. if (i == "RC") {
  2990. langsRC.push_back(i);
  2991. } else {
  2992. langs.push_back(i);
  2993. }
  2994. }
  2995. if (!langs.empty()) {
  2996. this->GetGlobalGenerator()->EnableLanguage(langs, this, optional);
  2997. }
  2998. if (!langsRC.empty()) {
  2999. this->GetGlobalGenerator()->EnableLanguage(langsRC, this, optional);
  3000. }
  3001. }
  3002. int cmMakefile::TryCompile(const std::string& srcdir,
  3003. const std::string& bindir,
  3004. const std::string& projectName,
  3005. const std::string& targetName, bool fast, int jobs,
  3006. const std::vector<std::string>* cmakeArgs,
  3007. std::string& output)
  3008. {
  3009. this->IsSourceFileTryCompile = fast;
  3010. // does the binary directory exist ? If not create it...
  3011. if (!cmSystemTools::FileIsDirectory(bindir)) {
  3012. cmSystemTools::MakeDirectory(bindir);
  3013. }
  3014. // change to the tests directory and run cmake
  3015. // use the cmake object instead of calling cmake
  3016. cmWorkingDirectory workdir(bindir);
  3017. if (workdir.Failed()) {
  3018. this->IssueMessage(MessageType::FATAL_ERROR,
  3019. "Failed to set working directory to " + bindir + " : " +
  3020. std::strerror(workdir.GetLastResult()));
  3021. cmSystemTools::SetFatalErrorOccured();
  3022. this->IsSourceFileTryCompile = false;
  3023. return 1;
  3024. }
  3025. // make sure the same generator is used
  3026. // use this program as the cmake to be run, it should not
  3027. // be run that way but the cmake object requires a vailid path
  3028. cmake cm(cmake::RoleProject, cmState::Project);
  3029. cm.SetIsInTryCompile(true);
  3030. cmGlobalGenerator* gg =
  3031. cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  3032. if (!gg) {
  3033. this->IssueMessage(MessageType::INTERNAL_ERROR,
  3034. "Global generator '" +
  3035. this->GetGlobalGenerator()->GetName() +
  3036. "' could not be created.");
  3037. cmSystemTools::SetFatalErrorOccured();
  3038. this->IsSourceFileTryCompile = false;
  3039. return 1;
  3040. }
  3041. gg->RecursionDepth = this->RecursionDepth;
  3042. cm.SetGlobalGenerator(gg);
  3043. // do a configure
  3044. cm.SetHomeDirectory(srcdir);
  3045. cm.SetHomeOutputDirectory(bindir);
  3046. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  3047. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  3048. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  3049. cm.LoadCache();
  3050. if (!gg->IsMultiConfig()) {
  3051. if (const char* config =
  3052. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  3053. // Tell the single-configuration generator which one to use.
  3054. // Add this before the user-provided CMake arguments in case
  3055. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  3056. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  3057. cmStateEnums::STRING);
  3058. }
  3059. }
  3060. const char* recursionDepth =
  3061. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  3062. if (recursionDepth) {
  3063. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  3064. "Maximum recursion depth", cmStateEnums::STRING);
  3065. }
  3066. // if cmake args were provided then pass them in
  3067. if (cmakeArgs) {
  3068. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  3069. //
  3070. // Ideally we should use SetArgs to honor options like --warn-unused-vars.
  3071. // However, there is a subtle problem when certain arguments are passed to
  3072. // a macro wrapping around try_compile or try_run that does not escape
  3073. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  3074. // this case a list argument like "-DVAR=a;b" gets split into multiple
  3075. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  3076. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  3077. // the try_compile or try_run does not get the proper value of VAR. If we
  3078. // call SetArgs here then it would treat "b" as the source directory and
  3079. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  3080. // does not exist", thus breaking the try_compile or try_run completely.
  3081. //
  3082. // Strictly speaking the bug is in the wrapper macro because the CMake
  3083. // language has always flattened nested lists and the macro should escape
  3084. // the semicolons in its arguments before forwarding them. However, this
  3085. // bug is so subtle that projects typically work anyway, usually because
  3086. // the value VAR=a is sufficient for the try_compile or try_run to get the
  3087. // correct result. Calling SetArgs here would break such projects that
  3088. // previously built. Instead we work around the issue by never reporting
  3089. // unused arguments and ignoring options such as --warn-unused-vars.
  3090. cm.SetWarnUnusedCli(false);
  3091. // cm.SetArgs(*cmakeArgs, true);
  3092. cm.SetCacheArgs(*cmakeArgs);
  3093. }
  3094. // to save time we pass the EnableLanguage info directly
  3095. gg->EnableLanguagesFromGenerator(this->GetGlobalGenerator(), this);
  3096. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  3097. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  3098. cmStateEnums::INTERNAL);
  3099. } else {
  3100. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  3101. cmStateEnums::INTERNAL);
  3102. }
  3103. if (cm.Configure() != 0) {
  3104. this->IssueMessage(MessageType::FATAL_ERROR,
  3105. "Failed to configure test project build system.");
  3106. cmSystemTools::SetFatalErrorOccured();
  3107. this->IsSourceFileTryCompile = false;
  3108. return 1;
  3109. }
  3110. if (cm.Generate() != 0) {
  3111. this->IssueMessage(MessageType::FATAL_ERROR,
  3112. "Failed to generate test project build system.");
  3113. cmSystemTools::SetFatalErrorOccured();
  3114. this->IsSourceFileTryCompile = false;
  3115. return 1;
  3116. }
  3117. // finally call the generator to actually build the resulting project
  3118. int ret = this->GetGlobalGenerator()->TryCompile(
  3119. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  3120. this->IsSourceFileTryCompile = false;
  3121. return ret;
  3122. }
  3123. bool cmMakefile::GetIsSourceFileTryCompile() const
  3124. {
  3125. return this->IsSourceFileTryCompile;
  3126. }
  3127. cmake* cmMakefile::GetCMakeInstance() const
  3128. {
  3129. return this->GlobalGenerator->GetCMakeInstance();
  3130. }
  3131. cmMessenger* cmMakefile::GetMessenger() const
  3132. {
  3133. return this->GetCMakeInstance()->GetMessenger();
  3134. }
  3135. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  3136. {
  3137. return this->GlobalGenerator;
  3138. }
  3139. #ifndef CMAKE_BOOTSTRAP
  3140. cmVariableWatch* cmMakefile::GetVariableWatch() const
  3141. {
  3142. if (this->GetCMakeInstance() &&
  3143. this->GetCMakeInstance()->GetVariableWatch()) {
  3144. return this->GetCMakeInstance()->GetVariableWatch();
  3145. }
  3146. return nullptr;
  3147. }
  3148. #endif
  3149. cmState* cmMakefile::GetState() const
  3150. {
  3151. return this->GetCMakeInstance()->GetState();
  3152. }
  3153. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  3154. {
  3155. cmake* cm = this->GetCMakeInstance();
  3156. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  3157. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  3158. // directly be fed to the compiler, which will be confused.
  3159. return;
  3160. }
  3161. cm->UpdateProgress(message, s);
  3162. }
  3163. std::string cmMakefile::GetModulesFile(const std::string& filename,
  3164. bool& system) const
  3165. {
  3166. std::string result;
  3167. // We search the module always in CMAKE_ROOT and in CMAKE_MODULE_PATH,
  3168. // and then decide based on the policy setting which one to return.
  3169. // See CMP0017 for more details.
  3170. // The specific problem was that KDE 4.5.0 installs a
  3171. // FindPackageHandleStandardArgs.cmake which doesn't have the new features
  3172. // of FPHSA.cmake introduced in CMake 2.8.3 yet, and by setting
  3173. // CMAKE_MODULE_PATH also e.g. FindZLIB.cmake from cmake included
  3174. // FPHSA.cmake from kdelibs and not from CMake, and tried to use the
  3175. // new features, which were not there in the version from kdelibs, and so
  3176. // failed ("
  3177. std::string moduleInCMakeRoot;
  3178. std::string moduleInCMakeModulePath;
  3179. // Always search in CMAKE_MODULE_PATH:
  3180. const char* cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  3181. if (cmakeModulePath) {
  3182. std::vector<std::string> modulePath;
  3183. cmExpandList(cmakeModulePath, modulePath);
  3184. // Look through the possible module directories.
  3185. for (std::string itempl : modulePath) {
  3186. cmSystemTools::ConvertToUnixSlashes(itempl);
  3187. itempl += "/";
  3188. itempl += filename;
  3189. if (cmSystemTools::FileExists(itempl)) {
  3190. moduleInCMakeModulePath = itempl;
  3191. break;
  3192. }
  3193. }
  3194. }
  3195. // Always search in the standard modules location.
  3196. moduleInCMakeRoot = cmSystemTools::GetCMakeRoot();
  3197. moduleInCMakeRoot += "/Modules/";
  3198. moduleInCMakeRoot += filename;
  3199. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  3200. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  3201. moduleInCMakeRoot.clear();
  3202. }
  3203. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  3204. // from which we are being called is located itself in CMAKE_ROOT, then
  3205. // prefer results from CMAKE_ROOT depending on the policy setting.
  3206. system = false;
  3207. result = moduleInCMakeModulePath;
  3208. if (result.empty()) {
  3209. system = true;
  3210. result = moduleInCMakeRoot;
  3211. }
  3212. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  3213. const char* currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  3214. std::string mods = cmSystemTools::GetCMakeRoot() + "/Modules/";
  3215. if (currentFile && cmSystemTools::IsSubDirectory(currentFile, mods)) {
  3216. switch (this->GetPolicyStatus(cmPolicies::CMP0017)) {
  3217. case cmPolicies::WARN: {
  3218. std::ostringstream e;
  3219. /* clang-format off */
  3220. e << "File " << currentFile << " includes "
  3221. << moduleInCMakeModulePath
  3222. << " (found via CMAKE_MODULE_PATH) which shadows "
  3223. << moduleInCMakeRoot << ". This may cause errors later on .\n"
  3224. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0017);
  3225. /* clang-format on */
  3226. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3227. CM_FALLTHROUGH;
  3228. }
  3229. case cmPolicies::OLD:
  3230. system = false;
  3231. result = moduleInCMakeModulePath;
  3232. break;
  3233. case cmPolicies::REQUIRED_IF_USED:
  3234. case cmPolicies::REQUIRED_ALWAYS:
  3235. case cmPolicies::NEW:
  3236. system = true;
  3237. result = moduleInCMakeRoot;
  3238. break;
  3239. }
  3240. }
  3241. }
  3242. return result;
  3243. }
  3244. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3245. bool atOnly, bool escapeQuotes) const
  3246. {
  3247. // Split input to handle one line at a time.
  3248. std::string::const_iterator lineStart = input.begin();
  3249. while (lineStart != input.end()) {
  3250. // Find the end of this line.
  3251. std::string::const_iterator lineEnd = lineStart;
  3252. while (lineEnd != input.end() && *lineEnd != '\n') {
  3253. ++lineEnd;
  3254. }
  3255. // Copy the line.
  3256. std::string line(lineStart, lineEnd);
  3257. // Skip the newline character.
  3258. bool haveNewline = (lineEnd != input.end());
  3259. if (haveNewline) {
  3260. ++lineEnd;
  3261. }
  3262. // Replace #cmakedefine instances.
  3263. if (this->cmDefineRegex.find(line)) {
  3264. const char* def = this->GetDefinition(this->cmDefineRegex.match(2));
  3265. if (!cmIsOff(def)) {
  3266. const std::string indentation = this->cmDefineRegex.match(1);
  3267. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine",
  3268. "#" + indentation + "define");
  3269. output += line;
  3270. } else {
  3271. output += "/* #undef ";
  3272. output += this->cmDefineRegex.match(2);
  3273. output += " */";
  3274. }
  3275. } else if (this->cmDefine01Regex.find(line)) {
  3276. const std::string indentation = this->cmDefine01Regex.match(1);
  3277. const char* def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3278. cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine01",
  3279. "#" + indentation + "define");
  3280. output += line;
  3281. if (!cmIsOff(def)) {
  3282. output += " 1";
  3283. } else {
  3284. output += " 0";
  3285. }
  3286. } else {
  3287. output += line;
  3288. }
  3289. if (haveNewline) {
  3290. output += "\n";
  3291. }
  3292. // Move to the next line.
  3293. lineStart = lineEnd;
  3294. }
  3295. // Perform variable replacements.
  3296. const char* filename = nullptr;
  3297. long lineNumber = -1;
  3298. if (!this->Backtrace.Empty()) {
  3299. const auto& currentTrace = this->Backtrace.Top();
  3300. filename = currentTrace.FilePath.c_str();
  3301. lineNumber = currentTrace.Line;
  3302. }
  3303. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3304. lineNumber, true, true);
  3305. }
  3306. int cmMakefile::ConfigureFile(const std::string& infile,
  3307. const std::string& outfile, bool copyonly,
  3308. bool atOnly, bool escapeQuotes,
  3309. cmNewLineStyle newLine)
  3310. {
  3311. int res = 1;
  3312. if (!this->CanIWriteThisFile(outfile)) {
  3313. cmSystemTools::Error("Attempt to write file: " + outfile +
  3314. " into a source directory.");
  3315. return 0;
  3316. }
  3317. if (!cmSystemTools::FileExists(infile)) {
  3318. cmSystemTools::Error("File " + infile + " does not exist.");
  3319. return 0;
  3320. }
  3321. std::string soutfile = outfile;
  3322. const std::string& sinfile = infile;
  3323. this->AddCMakeDependFile(sinfile);
  3324. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3325. // Re-generate if non-temporary outputs are missing.
  3326. // when we finalize the configuration we will remove all
  3327. // output files that now don't exist.
  3328. this->AddCMakeOutputFile(soutfile);
  3329. mode_t perm = 0;
  3330. cmSystemTools::GetPermissions(sinfile, perm);
  3331. std::string::size_type pos = soutfile.rfind('/');
  3332. if (pos != std::string::npos) {
  3333. std::string path = soutfile.substr(0, pos);
  3334. cmSystemTools::MakeDirectory(path);
  3335. }
  3336. if (copyonly) {
  3337. if (!cmSystemTools::CopyFileIfDifferent(sinfile, soutfile)) {
  3338. return 0;
  3339. }
  3340. } else {
  3341. std::string newLineCharacters;
  3342. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3343. if (newLine.IsValid()) {
  3344. newLineCharacters = newLine.GetCharacters();
  3345. omode |= std::ios::binary;
  3346. } else {
  3347. newLineCharacters = "\n";
  3348. }
  3349. std::string tempOutputFile = soutfile;
  3350. tempOutputFile += ".tmp";
  3351. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3352. if (!fout) {
  3353. cmSystemTools::Error("Could not open file for write in copy operation " +
  3354. tempOutputFile);
  3355. cmSystemTools::ReportLastSystemError("");
  3356. return 0;
  3357. }
  3358. cmsys::ifstream fin(sinfile.c_str());
  3359. if (!fin) {
  3360. cmSystemTools::Error("Could not open file for read in copy operation " +
  3361. sinfile);
  3362. return 0;
  3363. }
  3364. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3365. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3366. std::ostringstream e;
  3367. e << "File starts with a Byte-Order-Mark that is not UTF-8:\n "
  3368. << sinfile;
  3369. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3370. return 0;
  3371. }
  3372. // rewind to copy BOM to output file
  3373. fin.seekg(0);
  3374. // now copy input to output and expand variables in the
  3375. // input file at the same time
  3376. std::string inLine;
  3377. std::string outLine;
  3378. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3379. outLine.clear();
  3380. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3381. fout << outLine << newLineCharacters;
  3382. }
  3383. // close the files before attempting to copy
  3384. fin.close();
  3385. fout.close();
  3386. if (!cmSystemTools::CopyFileIfDifferent(tempOutputFile, soutfile)) {
  3387. res = 0;
  3388. } else {
  3389. cmSystemTools::SetPermissions(soutfile, perm);
  3390. }
  3391. cmSystemTools::RemoveFile(tempOutputFile);
  3392. }
  3393. return res;
  3394. }
  3395. void cmMakefile::SetProperty(const std::string& prop, const char* value)
  3396. {
  3397. cmListFileBacktrace lfbt = this->GetBacktrace();
  3398. this->StateSnapshot.GetDirectory().SetProperty(prop, value, lfbt);
  3399. }
  3400. void cmMakefile::AppendProperty(const std::string& prop, const char* value,
  3401. bool asString)
  3402. {
  3403. cmListFileBacktrace lfbt = this->GetBacktrace();
  3404. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3405. lfbt);
  3406. }
  3407. const char* cmMakefile::GetProperty(const std::string& prop) const
  3408. {
  3409. // Check for computed properties.
  3410. static std::string output;
  3411. if (prop == "TESTS") {
  3412. std::vector<std::string> keys;
  3413. // get list of keys
  3414. std::transform(this->Tests.begin(), this->Tests.end(),
  3415. std::back_inserter(keys),
  3416. [](decltype(this->Tests)::value_type const& pair) {
  3417. return pair.first;
  3418. });
  3419. output = cmJoin(keys, ";");
  3420. return output.c_str();
  3421. }
  3422. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3423. }
  3424. const char* cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3425. {
  3426. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3427. }
  3428. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3429. {
  3430. return cmIsOn(this->GetProperty(prop));
  3431. }
  3432. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3433. {
  3434. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3435. }
  3436. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3437. {
  3438. cmTargetMap::iterator i = this->Targets.find(name);
  3439. if (i != this->Targets.end()) {
  3440. return &i->second;
  3441. }
  3442. return nullptr;
  3443. }
  3444. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3445. {
  3446. cmTest* test = this->GetTest(testName);
  3447. if (test) {
  3448. return test;
  3449. }
  3450. test = new cmTest(this);
  3451. test->SetName(testName);
  3452. this->Tests[testName] = test;
  3453. return test;
  3454. }
  3455. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3456. {
  3457. std::map<std::string, cmTest*>::const_iterator mi =
  3458. this->Tests.find(testName);
  3459. if (mi != this->Tests.end()) {
  3460. return mi->second;
  3461. }
  3462. return nullptr;
  3463. }
  3464. void cmMakefile::GetTests(const std::string& config,
  3465. std::vector<cmTest*>& tests)
  3466. {
  3467. for (auto generator : this->GetTestGenerators()) {
  3468. if (generator->TestsForConfig(config)) {
  3469. tests.push_back(generator->GetTest());
  3470. }
  3471. }
  3472. }
  3473. void cmMakefile::AddCMakeDependFilesFromUser()
  3474. {
  3475. std::vector<std::string> deps;
  3476. if (const char* deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3477. cmExpandList(deps_str, deps);
  3478. }
  3479. for (std::string const& dep : deps) {
  3480. if (cmSystemTools::FileIsFullPath(dep)) {
  3481. this->AddCMakeDependFile(dep);
  3482. } else {
  3483. std::string f = this->GetCurrentSourceDirectory();
  3484. f += "/";
  3485. f += dep;
  3486. this->AddCMakeDependFile(f);
  3487. }
  3488. }
  3489. }
  3490. std::string cmMakefile::FormatListFileStack() const
  3491. {
  3492. std::vector<std::string> listFiles;
  3493. cmStateSnapshot snp = this->StateSnapshot;
  3494. while (snp.IsValid()) {
  3495. listFiles.push_back(snp.GetExecutionListFile());
  3496. snp = snp.GetCallStackParent();
  3497. }
  3498. std::reverse(listFiles.begin(), listFiles.end());
  3499. std::ostringstream tmp;
  3500. size_t depth = listFiles.size();
  3501. if (depth > 0) {
  3502. std::vector<std::string>::const_iterator it = listFiles.end();
  3503. do {
  3504. if (depth != listFiles.size()) {
  3505. tmp << "\n ";
  3506. }
  3507. --it;
  3508. tmp << "[";
  3509. tmp << depth;
  3510. tmp << "]\t";
  3511. tmp << *it;
  3512. depth--;
  3513. } while (it != listFiles.begin());
  3514. }
  3515. return tmp.str();
  3516. }
  3517. void cmMakefile::PushScope()
  3518. {
  3519. this->StateSnapshot =
  3520. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3521. this->PushLoopBlockBarrier();
  3522. #if !defined(CMAKE_BOOTSTRAP)
  3523. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3524. #endif
  3525. }
  3526. void cmMakefile::PopScope()
  3527. {
  3528. #if !defined(CMAKE_BOOTSTRAP)
  3529. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3530. #endif
  3531. this->PopLoopBlockBarrier();
  3532. this->CheckForUnusedVariables();
  3533. this->PopSnapshot();
  3534. }
  3535. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3536. {
  3537. if (var.empty()) {
  3538. return;
  3539. }
  3540. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3541. std::ostringstream m;
  3542. m << "Cannot set \"" << var << "\": current scope has no parent.";
  3543. this->IssueMessage(MessageType::AUTHOR_WARNING, m.str());
  3544. return;
  3545. }
  3546. #ifndef CMAKE_BOOTSTRAP
  3547. cmVariableWatch* vv = this->GetVariableWatch();
  3548. if (vv) {
  3549. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3550. varDef, this);
  3551. }
  3552. #endif
  3553. }
  3554. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3555. cmStateEnums::TargetType type,
  3556. bool global)
  3557. {
  3558. // Create the target.
  3559. std::unique_ptr<cmTarget> target(
  3560. new cmTarget(name, type,
  3561. global ? cmTarget::VisibilityImportedGlobally
  3562. : cmTarget::VisibilityImported,
  3563. this));
  3564. // Add to the set of available imported targets.
  3565. this->ImportedTargets[name] = target.get();
  3566. this->GetGlobalGenerator()->IndexTarget(target.get());
  3567. // Transfer ownership to this cmMakefile object.
  3568. this->ImportedTargetsOwned.push_back(target.get());
  3569. return target.release();
  3570. }
  3571. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3572. bool excludeAliases) const
  3573. {
  3574. // Look for an imported target. These take priority because they
  3575. // are more local in scope and do not have to be globally unique.
  3576. TargetMap::const_iterator imported = this->ImportedTargets.find(name);
  3577. if (imported != this->ImportedTargets.end()) {
  3578. return imported->second;
  3579. }
  3580. // Look for a target built in this directory.
  3581. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3582. return t;
  3583. }
  3584. // Look for a target built in this project.
  3585. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3586. }
  3587. bool cmMakefile::IsAlias(const std::string& name) const
  3588. {
  3589. if (this->AliasTargets.find(name) != this->AliasTargets.end()) {
  3590. return true;
  3591. }
  3592. return this->GetGlobalGenerator()->IsAlias(name);
  3593. }
  3594. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3595. bool isCustom) const
  3596. {
  3597. if (this->IsAlias(name)) {
  3598. std::ostringstream e;
  3599. e << "cannot create target \"" << name
  3600. << "\" because an alias with the same name already exists.";
  3601. msg = e.str();
  3602. return false;
  3603. }
  3604. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3605. // The name given conflicts with an existing target. Produce an
  3606. // error in a compatible way.
  3607. if (existing->IsImported()) {
  3608. // Imported targets were not supported in previous versions.
  3609. // This is new code, so we can make it an error.
  3610. std::ostringstream e;
  3611. e << "cannot create target \"" << name
  3612. << "\" because an imported target with the same name already exists.";
  3613. msg = e.str();
  3614. return false;
  3615. }
  3616. // target names must be globally unique
  3617. switch (this->GetPolicyStatus(cmPolicies::CMP0002)) {
  3618. case cmPolicies::WARN:
  3619. this->IssueMessage(MessageType::AUTHOR_WARNING,
  3620. cmPolicies::GetPolicyWarning(cmPolicies::CMP0002));
  3621. CM_FALLTHROUGH;
  3622. case cmPolicies::OLD:
  3623. return true;
  3624. case cmPolicies::REQUIRED_IF_USED:
  3625. case cmPolicies::REQUIRED_ALWAYS:
  3626. this->IssueMessage(
  3627. MessageType::FATAL_ERROR,
  3628. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0002));
  3629. return true;
  3630. case cmPolicies::NEW:
  3631. break;
  3632. }
  3633. // The conflict is with a non-imported target.
  3634. // Allow this if the user has requested support.
  3635. cmake* cm = this->GetCMakeInstance();
  3636. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3637. this != existing->GetMakefile() &&
  3638. cm->GetState()->GetGlobalPropertyAsBool(
  3639. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3640. return true;
  3641. }
  3642. // Produce an error that tells the user how to work around the
  3643. // problem.
  3644. std::ostringstream e;
  3645. e << "cannot create target \"" << name
  3646. << "\" because another target with the same name already exists. "
  3647. << "The existing target is ";
  3648. switch (existing->GetType()) {
  3649. case cmStateEnums::EXECUTABLE:
  3650. e << "an executable ";
  3651. break;
  3652. case cmStateEnums::STATIC_LIBRARY:
  3653. e << "a static library ";
  3654. break;
  3655. case cmStateEnums::SHARED_LIBRARY:
  3656. e << "a shared library ";
  3657. break;
  3658. case cmStateEnums::MODULE_LIBRARY:
  3659. e << "a module library ";
  3660. break;
  3661. case cmStateEnums::UTILITY:
  3662. e << "a custom target ";
  3663. break;
  3664. case cmStateEnums::INTERFACE_LIBRARY:
  3665. e << "an interface library ";
  3666. break;
  3667. default:
  3668. break;
  3669. }
  3670. e << "created in source directory \""
  3671. << existing->GetMakefile()->GetCurrentSourceDirectory() << "\". "
  3672. << "See documentation for policy CMP0002 for more details.";
  3673. msg = e.str();
  3674. return false;
  3675. }
  3676. return true;
  3677. }
  3678. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  3679. const std::string& binPath) const
  3680. {
  3681. // Make sure the binary directory is unique.
  3682. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  3683. if (gg->BinaryDirectoryIsNew(binPath)) {
  3684. return true;
  3685. }
  3686. std::ostringstream e;
  3687. switch (this->GetPolicyStatus(cmPolicies::CMP0013)) {
  3688. case cmPolicies::WARN:
  3689. // Print the warning.
  3690. /* clang-format off */
  3691. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0013)
  3692. << "\n"
  3693. << "The binary directory\n"
  3694. << " " << binPath << "\n"
  3695. << "is already used to build a source directory. "
  3696. << "This command uses it to build source directory\n"
  3697. << " " << srcPath << "\n"
  3698. << "which can generate conflicting build files. "
  3699. << "CMake does not support this use case but it used "
  3700. << "to work accidentally and is being allowed for "
  3701. << "compatibility.";
  3702. /* clang-format on */
  3703. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  3704. CM_FALLTHROUGH;
  3705. case cmPolicies::OLD:
  3706. // OLD behavior does not warn.
  3707. return true;
  3708. case cmPolicies::REQUIRED_IF_USED:
  3709. case cmPolicies::REQUIRED_ALWAYS:
  3710. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0013) << "\n";
  3711. CM_FALLTHROUGH;
  3712. case cmPolicies::NEW:
  3713. // NEW behavior prints the error.
  3714. /* clang-format off */
  3715. e << "The binary directory\n"
  3716. << " " << binPath << "\n"
  3717. << "is already used to build a source directory. "
  3718. << "It cannot be used to build source directory\n"
  3719. << " " << srcPath << "\n"
  3720. << "Specify a unique binary directory name.";
  3721. /* clang-format on */
  3722. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3723. break;
  3724. }
  3725. return false;
  3726. }
  3727. static std::string const matchVariables[] = {
  3728. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  3729. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  3730. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  3731. };
  3732. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  3733. void cmMakefile::ClearMatches()
  3734. {
  3735. const char* nMatchesStr = this->GetDefinition(nMatchesVariable);
  3736. if (!nMatchesStr) {
  3737. return;
  3738. }
  3739. int nMatches = atoi(nMatchesStr);
  3740. for (int i = 0; i <= nMatches; i++) {
  3741. std::string const& var = matchVariables[i];
  3742. std::string const& s = this->GetSafeDefinition(var);
  3743. if (!s.empty()) {
  3744. this->AddDefinition(var, "");
  3745. this->MarkVariableAsUsed(var);
  3746. }
  3747. }
  3748. this->AddDefinition(nMatchesVariable, "0");
  3749. this->MarkVariableAsUsed(nMatchesVariable);
  3750. }
  3751. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  3752. {
  3753. char highest = 0;
  3754. for (int i = 0; i < 10; i++) {
  3755. std::string const& m = re.match(i);
  3756. if (!m.empty()) {
  3757. std::string const& var = matchVariables[i];
  3758. this->AddDefinition(var, m);
  3759. this->MarkVariableAsUsed(var);
  3760. highest = static_cast<char>('0' + i);
  3761. }
  3762. }
  3763. char nMatches[] = { highest, '\0' };
  3764. this->AddDefinition(nMatchesVariable, nMatches);
  3765. this->MarkVariableAsUsed(nMatchesVariable);
  3766. }
  3767. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  3768. {
  3769. return this->StateSnapshot;
  3770. }
  3771. const char* cmMakefile::GetDefineFlagsCMP0059() const
  3772. {
  3773. return this->DefineFlagsOrig.c_str();
  3774. }
  3775. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  3776. bool parent_scope) const
  3777. {
  3778. return this->StateSnapshot.GetPolicy(id, parent_scope);
  3779. }
  3780. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var)
  3781. {
  3782. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  3783. if (const char* val = this->GetDefinition(var)) {
  3784. return cmIsOn(val);
  3785. }
  3786. // Enable optional policy warnings with --debug-output, --trace,
  3787. // or --trace-expand.
  3788. cmake* cm = this->GetCMakeInstance();
  3789. return cm->GetDebugOutput() || cm->GetTrace();
  3790. }
  3791. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  3792. {
  3793. cmPolicies::PolicyID pid;
  3794. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  3795. std::ostringstream e;
  3796. e << "Policy \"" << id << "\" is not known to this version of CMake.";
  3797. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  3798. return false;
  3799. }
  3800. return this->SetPolicy(pid, status);
  3801. }
  3802. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  3803. cmPolicies::PolicyStatus status)
  3804. {
  3805. // A REQUIRED_ALWAYS policy may be set only to NEW.
  3806. if (status != cmPolicies::NEW &&
  3807. cmPolicies::GetPolicyStatus(id) == cmPolicies::REQUIRED_ALWAYS) {
  3808. std::string msg = cmPolicies::GetRequiredAlwaysPolicyError(id);
  3809. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  3810. return false;
  3811. }
  3812. // Deprecate old policies, especially those that require a lot
  3813. // of code to maintain the old behavior.
  3814. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0067 &&
  3815. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  3816. (
  3817. // Policies set by cmCoreTryCompile::TryCompileCode.
  3818. id == cmPolicies::CMP0065))) {
  3819. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  3820. cmPolicies::GetPolicyDeprecatedWarning(id));
  3821. }
  3822. this->StateSnapshot.SetPolicy(id, status);
  3823. return true;
  3824. }
  3825. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  3826. : Makefile(m)
  3827. {
  3828. this->Makefile->PushPolicy();
  3829. }
  3830. cmMakefile::PolicyPushPop::~PolicyPushPop()
  3831. {
  3832. this->Makefile->PopPolicy();
  3833. }
  3834. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  3835. {
  3836. this->StateSnapshot.PushPolicy(pm, weak);
  3837. }
  3838. void cmMakefile::PopPolicy()
  3839. {
  3840. if (!this->StateSnapshot.PopPolicy()) {
  3841. this->IssueMessage(MessageType::FATAL_ERROR,
  3842. "cmake_policy POP without matching PUSH");
  3843. }
  3844. }
  3845. void cmMakefile::PopSnapshot(bool reportError)
  3846. {
  3847. // cmStateSnapshot manages nested policy scopes within it.
  3848. // Since the scope corresponding to the snapshot is closing,
  3849. // reject any still-open nested policy scopes with an error.
  3850. while (!this->StateSnapshot.CanPopPolicyScope()) {
  3851. if (reportError) {
  3852. this->IssueMessage(MessageType::FATAL_ERROR,
  3853. "cmake_policy PUSH without matching POP");
  3854. reportError = false;
  3855. }
  3856. this->PopPolicy();
  3857. }
  3858. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  3859. assert(this->StateSnapshot.IsValid());
  3860. }
  3861. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  3862. std::string const& version_max)
  3863. {
  3864. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max);
  3865. }
  3866. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  3867. cmListFileContext const& context) const
  3868. {
  3869. return !this->CMP0054ReportedIds.insert(context).second;
  3870. }
  3871. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm)
  3872. {
  3873. /* Record the setting of every policy. */
  3874. typedef cmPolicies::PolicyID PolicyID;
  3875. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  3876. pid = PolicyID(pid + 1)) {
  3877. pm.Set(pid, this->GetPolicyStatus(pid));
  3878. }
  3879. }
  3880. bool cmMakefile::IgnoreErrorsCMP0061() const
  3881. {
  3882. bool ignoreErrors = true;
  3883. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  3884. case cmPolicies::WARN:
  3885. // No warning for this policy!
  3886. case cmPolicies::OLD:
  3887. break;
  3888. case cmPolicies::REQUIRED_IF_USED:
  3889. case cmPolicies::REQUIRED_ALWAYS:
  3890. case cmPolicies::NEW:
  3891. ignoreErrors = false;
  3892. break;
  3893. }
  3894. return ignoreErrors;
  3895. }
  3896. #define FEATURE_STRING(F) , #F
  3897. static const char* const C_FEATURES[] = { nullptr FOR_EACH_C_FEATURE(
  3898. FEATURE_STRING) };
  3899. static const char* const CXX_FEATURES[] = { nullptr FOR_EACH_CXX_FEATURE(
  3900. FEATURE_STRING) };
  3901. #undef FEATURE_STRING
  3902. static const char* const C_STANDARDS[] = { "90", "99", "11" };
  3903. static const char* const CXX_STANDARDS[] = { "98", "11", "14", "17", "20" };
  3904. bool cmMakefile::AddRequiredTargetFeature(cmTarget* target,
  3905. const std::string& feature,
  3906. std::string* error) const
  3907. {
  3908. if (cmGeneratorExpression::Find(feature) != std::string::npos) {
  3909. target->AppendProperty("COMPILE_FEATURES", feature.c_str());
  3910. return true;
  3911. }
  3912. std::string lang;
  3913. if (!this->CompileFeatureKnown(target, feature, lang, error)) {
  3914. return false;
  3915. }
  3916. const char* features = this->CompileFeaturesAvailable(lang, error);
  3917. if (!features) {
  3918. return false;
  3919. }
  3920. std::vector<std::string> availableFeatures;
  3921. cmExpandList(features, availableFeatures);
  3922. if (std::find(availableFeatures.begin(), availableFeatures.end(), feature) ==
  3923. availableFeatures.end()) {
  3924. std::ostringstream e;
  3925. e << "The compiler feature \"" << feature << "\" is not known to " << lang
  3926. << " compiler\n\""
  3927. << this->GetDefinition("CMAKE_" + lang + "_COMPILER_ID")
  3928. << "\"\nversion "
  3929. << this->GetDefinition("CMAKE_" + lang + "_COMPILER_VERSION") << ".";
  3930. if (error) {
  3931. *error = e.str();
  3932. } else {
  3933. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  3934. this->Backtrace);
  3935. }
  3936. return false;
  3937. }
  3938. target->AppendProperty("COMPILE_FEATURES", feature.c_str());
  3939. return lang == "C"
  3940. ? this->AddRequiredTargetCFeature(target, feature, error)
  3941. : this->AddRequiredTargetCxxFeature(target, feature, error);
  3942. }
  3943. bool cmMakefile::CompileFeatureKnown(cmTarget const* target,
  3944. const std::string& feature,
  3945. std::string& lang,
  3946. std::string* error) const
  3947. {
  3948. assert(cmGeneratorExpression::Find(feature) == std::string::npos);
  3949. bool isCFeature =
  3950. std::find_if(cm::cbegin(C_FEATURES) + 1, cm::cend(C_FEATURES),
  3951. cmStrCmp(feature)) != cm::cend(C_FEATURES);
  3952. if (isCFeature) {
  3953. lang = "C";
  3954. return true;
  3955. }
  3956. bool isCxxFeature =
  3957. std::find_if(cm::cbegin(CXX_FEATURES) + 1, cm::cend(CXX_FEATURES),
  3958. cmStrCmp(feature)) != cm::cend(CXX_FEATURES);
  3959. if (isCxxFeature) {
  3960. lang = "CXX";
  3961. return true;
  3962. }
  3963. std::ostringstream e;
  3964. if (error) {
  3965. e << "specified";
  3966. } else {
  3967. e << "Specified";
  3968. }
  3969. e << " unknown feature \"" << feature
  3970. << "\" for "
  3971. "target \""
  3972. << target->GetName() << "\".";
  3973. if (error) {
  3974. *error = e.str();
  3975. } else {
  3976. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  3977. this->Backtrace);
  3978. }
  3979. return false;
  3980. }
  3981. const char* cmMakefile::CompileFeaturesAvailable(const std::string& lang,
  3982. std::string* error) const
  3983. {
  3984. if (!this->GlobalGenerator->GetLanguageEnabled(lang)) {
  3985. std::ostringstream e;
  3986. if (error) {
  3987. e << "cannot";
  3988. } else {
  3989. e << "Cannot";
  3990. }
  3991. e << " use features from non-enabled language " << lang;
  3992. if (error) {
  3993. *error = e.str();
  3994. } else {
  3995. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  3996. this->Backtrace);
  3997. }
  3998. return nullptr;
  3999. }
  4000. const char* featuresKnown =
  4001. this->GetDefinition("CMAKE_" + lang + "_COMPILE_FEATURES");
  4002. if (!featuresKnown || !*featuresKnown) {
  4003. std::ostringstream e;
  4004. if (error) {
  4005. e << "no";
  4006. } else {
  4007. e << "No";
  4008. }
  4009. e << " known features for " << lang << " compiler\n\""
  4010. << this->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_ID")
  4011. << "\"\nversion "
  4012. << this->GetSafeDefinition("CMAKE_" + lang + "_COMPILER_VERSION") << ".";
  4013. if (error) {
  4014. *error = e.str();
  4015. } else {
  4016. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  4017. this->Backtrace);
  4018. }
  4019. return nullptr;
  4020. }
  4021. return featuresKnown;
  4022. }
  4023. bool cmMakefile::HaveStandardAvailable(cmTarget const* target,
  4024. std::string const& lang,
  4025. const std::string& feature) const
  4026. {
  4027. return lang == "C" ? this->HaveCStandardAvailable(target, feature)
  4028. : this->HaveCxxStandardAvailable(target, feature);
  4029. }
  4030. bool cmMakefile::HaveCStandardAvailable(cmTarget const* target,
  4031. const std::string& feature) const
  4032. {
  4033. const char* defaultCStandard =
  4034. this->GetDefinition("CMAKE_C_STANDARD_DEFAULT");
  4035. if (!defaultCStandard) {
  4036. std::ostringstream e;
  4037. e << "CMAKE_C_STANDARD_DEFAULT is not set. COMPILE_FEATURES support "
  4038. "not fully configured for this compiler.";
  4039. this->IssueMessage(MessageType::INTERNAL_ERROR, e.str());
  4040. // Return true so the caller does not try to lookup the default standard.
  4041. return true;
  4042. }
  4043. if (std::find_if(cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS),
  4044. cmStrCmp(defaultCStandard)) == cm::cend(C_STANDARDS)) {
  4045. std::ostringstream e;
  4046. e << "The CMAKE_C_STANDARD_DEFAULT variable contains an "
  4047. "invalid value: \""
  4048. << defaultCStandard << "\".";
  4049. this->IssueMessage(MessageType::INTERNAL_ERROR, e.str());
  4050. return false;
  4051. }
  4052. bool needC90 = false;
  4053. bool needC99 = false;
  4054. bool needC11 = false;
  4055. this->CheckNeededCLanguage(feature, needC90, needC99, needC11);
  4056. const char* existingCStandard = target->GetProperty("C_STANDARD");
  4057. if (!existingCStandard) {
  4058. existingCStandard = defaultCStandard;
  4059. }
  4060. if (std::find_if(cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS),
  4061. cmStrCmp(existingCStandard)) == cm::cend(C_STANDARDS)) {
  4062. std::ostringstream e;
  4063. e << "The C_STANDARD property on target \"" << target->GetName()
  4064. << "\" contained an invalid value: \"" << existingCStandard << "\".";
  4065. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4066. return false;
  4067. }
  4068. const char* const* existingCIt = existingCStandard
  4069. ? std::find_if(cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS),
  4070. cmStrCmp(existingCStandard))
  4071. : cm::cend(C_STANDARDS);
  4072. if (needC11 && existingCStandard &&
  4073. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4074. cm::cend(C_STANDARDS), cmStrCmp("11"))) {
  4075. return false;
  4076. }
  4077. if (needC99 && existingCStandard &&
  4078. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4079. cm::cend(C_STANDARDS), cmStrCmp("99"))) {
  4080. return false;
  4081. }
  4082. if (needC90 && existingCStandard &&
  4083. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4084. cm::cend(C_STANDARDS), cmStrCmp("90"))) {
  4085. return false;
  4086. }
  4087. return true;
  4088. }
  4089. bool cmMakefile::IsLaterStandard(std::string const& lang,
  4090. std::string const& lhs,
  4091. std::string const& rhs)
  4092. {
  4093. if (lang == "C") {
  4094. const char* const* rhsIt = std::find_if(
  4095. cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS), cmStrCmp(rhs));
  4096. return std::find_if(rhsIt, cm::cend(C_STANDARDS), cmStrCmp(lhs)) !=
  4097. cm::cend(C_STANDARDS);
  4098. }
  4099. const char* const* rhsIt = std::find_if(
  4100. cm::cbegin(CXX_STANDARDS), cm::cend(CXX_STANDARDS), cmStrCmp(rhs));
  4101. return std::find_if(rhsIt, cm::cend(CXX_STANDARDS), cmStrCmp(lhs)) !=
  4102. cm::cend(CXX_STANDARDS);
  4103. }
  4104. bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target,
  4105. const std::string& feature) const
  4106. {
  4107. const char* defaultCxxStandard =
  4108. this->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  4109. if (!defaultCxxStandard) {
  4110. std::ostringstream e;
  4111. e << "CMAKE_CXX_STANDARD_DEFAULT is not set. COMPILE_FEATURES support "
  4112. "not fully configured for this compiler.";
  4113. this->IssueMessage(MessageType::INTERNAL_ERROR, e.str());
  4114. // Return true so the caller does not try to lookup the default standard.
  4115. return true;
  4116. }
  4117. if (std::find_if(cm::cbegin(CXX_STANDARDS), cm::cend(CXX_STANDARDS),
  4118. cmStrCmp(defaultCxxStandard)) == cm::cend(CXX_STANDARDS)) {
  4119. std::ostringstream e;
  4120. e << "The CMAKE_CXX_STANDARD_DEFAULT variable contains an "
  4121. "invalid value: \""
  4122. << defaultCxxStandard << "\".";
  4123. this->IssueMessage(MessageType::INTERNAL_ERROR, e.str());
  4124. return false;
  4125. }
  4126. bool needCxx98 = false;
  4127. bool needCxx11 = false;
  4128. bool needCxx14 = false;
  4129. bool needCxx17 = false;
  4130. bool needCxx20 = false;
  4131. this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14,
  4132. needCxx17, needCxx20);
  4133. const char* existingCxxStandard = target->GetProperty("CXX_STANDARD");
  4134. if (!existingCxxStandard) {
  4135. existingCxxStandard = defaultCxxStandard;
  4136. }
  4137. const char* const* existingCxxLevel =
  4138. std::find_if(cm::cbegin(CXX_STANDARDS), cm::cend(CXX_STANDARDS),
  4139. cmStrCmp(existingCxxStandard));
  4140. if (existingCxxLevel == cm::cend(CXX_STANDARDS)) {
  4141. std::ostringstream e;
  4142. e << "The CXX_STANDARD property on target \"" << target->GetName()
  4143. << "\" contained an invalid value: \"" << existingCxxStandard << "\".";
  4144. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4145. return false;
  4146. }
  4147. /* clang-format off */
  4148. const char* const* needCxxLevel =
  4149. needCxx20 ? &CXX_STANDARDS[4]
  4150. : needCxx17 ? &CXX_STANDARDS[3]
  4151. : needCxx14 ? &CXX_STANDARDS[2]
  4152. : needCxx11 ? &CXX_STANDARDS[1]
  4153. : needCxx98 ? &CXX_STANDARDS[0]
  4154. : nullptr;
  4155. /* clang-format on */
  4156. return !needCxxLevel || needCxxLevel <= existingCxxLevel;
  4157. }
  4158. void cmMakefile::CheckNeededCxxLanguage(const std::string& feature,
  4159. bool& needCxx98, bool& needCxx11,
  4160. bool& needCxx14, bool& needCxx17,
  4161. bool& needCxx20) const
  4162. {
  4163. if (const char* propCxx98 =
  4164. this->GetDefinition("CMAKE_CXX98_COMPILE_FEATURES")) {
  4165. std::vector<std::string> props;
  4166. cmExpandList(propCxx98, props);
  4167. needCxx98 = std::find(props.begin(), props.end(), feature) != props.end();
  4168. }
  4169. if (const char* propCxx11 =
  4170. this->GetDefinition("CMAKE_CXX11_COMPILE_FEATURES")) {
  4171. std::vector<std::string> props;
  4172. cmExpandList(propCxx11, props);
  4173. needCxx11 = std::find(props.begin(), props.end(), feature) != props.end();
  4174. }
  4175. if (const char* propCxx14 =
  4176. this->GetDefinition("CMAKE_CXX14_COMPILE_FEATURES")) {
  4177. std::vector<std::string> props;
  4178. cmExpandList(propCxx14, props);
  4179. needCxx14 = std::find(props.begin(), props.end(), feature) != props.end();
  4180. }
  4181. if (const char* propCxx17 =
  4182. this->GetDefinition("CMAKE_CXX17_COMPILE_FEATURES")) {
  4183. std::vector<std::string> props;
  4184. cmExpandList(propCxx17, props);
  4185. needCxx17 = std::find(props.begin(), props.end(), feature) != props.end();
  4186. }
  4187. if (const char* propCxx20 =
  4188. this->GetDefinition("CMAKE_CXX20_COMPILE_FEATURES")) {
  4189. std::vector<std::string> props;
  4190. cmExpandList(propCxx20, props);
  4191. needCxx20 = std::find(props.begin(), props.end(), feature) != props.end();
  4192. }
  4193. }
  4194. bool cmMakefile::AddRequiredTargetCxxFeature(cmTarget* target,
  4195. const std::string& feature,
  4196. std::string* error) const
  4197. {
  4198. bool needCxx98 = false;
  4199. bool needCxx11 = false;
  4200. bool needCxx14 = false;
  4201. bool needCxx17 = false;
  4202. bool needCxx20 = false;
  4203. this->CheckNeededCxxLanguage(feature, needCxx98, needCxx11, needCxx14,
  4204. needCxx17, needCxx20);
  4205. const char* existingCxxStandard = target->GetProperty("CXX_STANDARD");
  4206. if (existingCxxStandard == nullptr) {
  4207. const char* defaultCxxStandard =
  4208. this->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  4209. if (defaultCxxStandard && *defaultCxxStandard) {
  4210. existingCxxStandard = defaultCxxStandard;
  4211. }
  4212. }
  4213. const char* const* existingCxxLevel = nullptr;
  4214. if (existingCxxStandard) {
  4215. existingCxxLevel =
  4216. std::find_if(cm::cbegin(CXX_STANDARDS), cm::cend(CXX_STANDARDS),
  4217. cmStrCmp(existingCxxStandard));
  4218. if (existingCxxLevel == cm::cend(CXX_STANDARDS)) {
  4219. std::ostringstream e;
  4220. e << "The CXX_STANDARD property on target \"" << target->GetName()
  4221. << "\" contained an invalid value: \"" << existingCxxStandard << "\".";
  4222. if (error) {
  4223. *error = e.str();
  4224. } else {
  4225. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  4226. e.str(), this->Backtrace);
  4227. }
  4228. return false;
  4229. }
  4230. }
  4231. const char* existingCudaStandard = target->GetProperty("CUDA_STANDARD");
  4232. const char* const* existingCudaLevel = nullptr;
  4233. if (existingCudaStandard) {
  4234. existingCudaLevel =
  4235. std::find_if(cm::cbegin(CXX_STANDARDS), cm::cend(CXX_STANDARDS),
  4236. cmStrCmp(existingCudaStandard));
  4237. if (existingCudaLevel == cm::cend(CXX_STANDARDS)) {
  4238. std::ostringstream e;
  4239. e << "The CUDA_STANDARD property on target \"" << target->GetName()
  4240. << "\" contained an invalid value: \"" << existingCudaStandard
  4241. << "\".";
  4242. if (error) {
  4243. *error = e.str();
  4244. } else {
  4245. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  4246. e.str(), this->Backtrace);
  4247. }
  4248. return false;
  4249. }
  4250. }
  4251. /* clang-format off */
  4252. const char* const* needCxxLevel =
  4253. needCxx20 ? &CXX_STANDARDS[4]
  4254. : needCxx17 ? &CXX_STANDARDS[3]
  4255. : needCxx14 ? &CXX_STANDARDS[2]
  4256. : needCxx11 ? &CXX_STANDARDS[1]
  4257. : needCxx98 ? &CXX_STANDARDS[0]
  4258. : nullptr;
  4259. /* clang-format on */
  4260. if (needCxxLevel) {
  4261. // Ensure the C++ language level is high enough to support
  4262. // the needed C++ features.
  4263. if (!existingCxxLevel || existingCxxLevel < needCxxLevel) {
  4264. target->SetProperty("CXX_STANDARD", *needCxxLevel);
  4265. }
  4266. // Ensure the CUDA language level is high enough to support
  4267. // the needed C++ features.
  4268. if (!existingCudaLevel || existingCudaLevel < needCxxLevel) {
  4269. target->SetProperty("CUDA_STANDARD", *needCxxLevel);
  4270. }
  4271. }
  4272. return true;
  4273. }
  4274. void cmMakefile::CheckNeededCLanguage(const std::string& feature,
  4275. bool& needC90, bool& needC99,
  4276. bool& needC11) const
  4277. {
  4278. if (const char* propC90 =
  4279. this->GetDefinition("CMAKE_C90_COMPILE_FEATURES")) {
  4280. std::vector<std::string> props;
  4281. cmExpandList(propC90, props);
  4282. needC90 = std::find(props.begin(), props.end(), feature) != props.end();
  4283. }
  4284. if (const char* propC99 =
  4285. this->GetDefinition("CMAKE_C99_COMPILE_FEATURES")) {
  4286. std::vector<std::string> props;
  4287. cmExpandList(propC99, props);
  4288. needC99 = std::find(props.begin(), props.end(), feature) != props.end();
  4289. }
  4290. if (const char* propC11 =
  4291. this->GetDefinition("CMAKE_C11_COMPILE_FEATURES")) {
  4292. std::vector<std::string> props;
  4293. cmExpandList(propC11, props);
  4294. needC11 = std::find(props.begin(), props.end(), feature) != props.end();
  4295. }
  4296. }
  4297. bool cmMakefile::AddRequiredTargetCFeature(cmTarget* target,
  4298. const std::string& feature,
  4299. std::string* error) const
  4300. {
  4301. bool needC90 = false;
  4302. bool needC99 = false;
  4303. bool needC11 = false;
  4304. this->CheckNeededCLanguage(feature, needC90, needC99, needC11);
  4305. const char* existingCStandard = target->GetProperty("C_STANDARD");
  4306. if (existingCStandard == nullptr) {
  4307. const char* defaultCStandard =
  4308. this->GetDefinition("CMAKE_C_STANDARD_DEFAULT");
  4309. if (defaultCStandard && *defaultCStandard) {
  4310. existingCStandard = defaultCStandard;
  4311. }
  4312. }
  4313. if (existingCStandard) {
  4314. if (std::find_if(cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS),
  4315. cmStrCmp(existingCStandard)) == cm::cend(C_STANDARDS)) {
  4316. std::ostringstream e;
  4317. e << "The C_STANDARD property on target \"" << target->GetName()
  4318. << "\" contained an invalid value: \"" << existingCStandard << "\".";
  4319. if (error) {
  4320. *error = e.str();
  4321. } else {
  4322. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  4323. e.str(), this->Backtrace);
  4324. }
  4325. return false;
  4326. }
  4327. }
  4328. const char* const* existingCIt = existingCStandard
  4329. ? std::find_if(cm::cbegin(C_STANDARDS), cm::cend(C_STANDARDS),
  4330. cmStrCmp(existingCStandard))
  4331. : cm::cend(C_STANDARDS);
  4332. bool setC90 = needC90 && !existingCStandard;
  4333. bool setC99 = needC99 && !existingCStandard;
  4334. bool setC11 = needC11 && !existingCStandard;
  4335. if (needC11 && existingCStandard &&
  4336. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4337. cm::cend(C_STANDARDS), cmStrCmp("11"))) {
  4338. setC11 = true;
  4339. } else if (needC99 && existingCStandard &&
  4340. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4341. cm::cend(C_STANDARDS),
  4342. cmStrCmp("99"))) {
  4343. setC99 = true;
  4344. } else if (needC90 && existingCStandard &&
  4345. existingCIt < std::find_if(cm::cbegin(C_STANDARDS),
  4346. cm::cend(C_STANDARDS),
  4347. cmStrCmp("90"))) {
  4348. setC90 = true;
  4349. }
  4350. if (setC11) {
  4351. target->SetProperty("C_STANDARD", "11");
  4352. } else if (setC99) {
  4353. target->SetProperty("C_STANDARD", "99");
  4354. } else if (setC90) {
  4355. target->SetProperty("C_STANDARD", "90");
  4356. }
  4357. return true;
  4358. }
  4359. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  4360. const std::string& fileName,
  4361. cmPolicies::PolicyMap const& pm)
  4362. : Makefile(mf)
  4363. , ReportError(true)
  4364. {
  4365. this->Makefile->PushFunctionScope(fileName, pm);
  4366. }
  4367. cmMakefile::FunctionPushPop::~FunctionPushPop()
  4368. {
  4369. this->Makefile->PopFunctionScope(this->ReportError);
  4370. }
  4371. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  4372. const std::string& fileName,
  4373. const cmPolicies::PolicyMap& pm)
  4374. : Makefile(mf)
  4375. , ReportError(true)
  4376. {
  4377. this->Makefile->PushMacroScope(fileName, pm);
  4378. }
  4379. cmMakefile::MacroPushPop::~MacroPushPop()
  4380. {
  4381. this->Makefile->PopMacroScope(this->ReportError);
  4382. }