cmMakefile.cxx 155 KB

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