cmMakefile.cxx 141 KB

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