cmMakefile.cxx 143 KB

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