cmMakefile.cxx 149 KB

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