cmMakefile.cxx 131 KB

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