cmMakefile.cxx 143 KB

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