cmMakefile.cxx 128 KB

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