cmMakefile.cxx 142 KB

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