cmMakefile.cxx 158 KB

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