cmMakefile.cxx 153 KB

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