cmMakefile.cxx 143 KB

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