cmMakefile.cxx 159 KB

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