cmMakefile.cxx 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211
  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. // Update the string used for the old DEFINITIONS property.
  1083. s_AddDefineFlag(flag, this->DefineFlagsOrig);
  1084. // If this is really a definition, update COMPILE_DEFINITIONS.
  1085. if (this->ParseDefineFlag(flag, false)) {
  1086. return;
  1087. }
  1088. // Add this flag that does not look like a definition.
  1089. s_AddDefineFlag(flag, this->DefineFlags);
  1090. }
  1091. static void s_RemoveDefineFlag(std::string const& flag, std::string& dflags)
  1092. {
  1093. std::string::size_type const len = flag.length();
  1094. // Remove all instances of the flag that are surrounded by
  1095. // whitespace or the beginning/end of the string.
  1096. for (std::string::size_type lpos = dflags.find(flag, 0);
  1097. lpos != std::string::npos; lpos = dflags.find(flag, lpos)) {
  1098. std::string::size_type rpos = lpos + len;
  1099. if ((lpos <= 0 || cmIsSpace(dflags[lpos - 1])) &&
  1100. (rpos >= dflags.size() || cmIsSpace(dflags[rpos]))) {
  1101. dflags.erase(lpos, len);
  1102. } else {
  1103. ++lpos;
  1104. }
  1105. }
  1106. }
  1107. void cmMakefile::RemoveDefineFlag(std::string const& flag)
  1108. {
  1109. // Check the length of the flag to remove.
  1110. if (flag.empty()) {
  1111. return;
  1112. }
  1113. // Update the string used for the old DEFINITIONS property.
  1114. s_RemoveDefineFlag(flag, this->DefineFlagsOrig);
  1115. // If this is really a definition, update COMPILE_DEFINITIONS.
  1116. if (this->ParseDefineFlag(flag, true)) {
  1117. return;
  1118. }
  1119. // Remove this flag that does not look like a definition.
  1120. s_RemoveDefineFlag(flag, this->DefineFlags);
  1121. }
  1122. void cmMakefile::AddCompileDefinition(std::string const& option)
  1123. {
  1124. this->AppendProperty("COMPILE_DEFINITIONS", option);
  1125. }
  1126. void cmMakefile::AddCompileOption(std::string const& option)
  1127. {
  1128. this->AppendProperty("COMPILE_OPTIONS", option);
  1129. }
  1130. void cmMakefile::AddLinkOption(std::string const& option)
  1131. {
  1132. this->AppendProperty("LINK_OPTIONS", option);
  1133. }
  1134. void cmMakefile::AddLinkDirectory(std::string const& directory, bool before)
  1135. {
  1136. if (before) {
  1137. this->StateSnapshot.GetDirectory().PrependLinkDirectoriesEntry(
  1138. BT<std::string>(directory, this->Backtrace));
  1139. } else {
  1140. this->StateSnapshot.GetDirectory().AppendLinkDirectoriesEntry(
  1141. BT<std::string>(directory, this->Backtrace));
  1142. }
  1143. }
  1144. bool cmMakefile::ParseDefineFlag(std::string const& def, bool remove)
  1145. {
  1146. // Create a regular expression to match valid definitions.
  1147. static cmsys::RegularExpression valid("^[-/]D[A-Za-z_][A-Za-z0-9_]*(=.*)?$");
  1148. // Make sure the definition matches.
  1149. if (!valid.find(def)) {
  1150. return false;
  1151. }
  1152. // Get the definition part after the flag.
  1153. const char* define = def.c_str() + 2;
  1154. if (remove) {
  1155. if (cmValue cdefs = this->GetProperty("COMPILE_DEFINITIONS")) {
  1156. // Expand the list.
  1157. cmList defs{ *cdefs };
  1158. // Recompose the list without the definition.
  1159. defs.remove_items({ define });
  1160. // Store the new list.
  1161. this->SetProperty("COMPILE_DEFINITIONS", defs.to_string());
  1162. }
  1163. } else {
  1164. // Append the definition to the directory property.
  1165. this->AppendProperty("COMPILE_DEFINITIONS", define);
  1166. }
  1167. return true;
  1168. }
  1169. void cmMakefile::InitializeFromParent(cmMakefile* parent)
  1170. {
  1171. this->SystemIncludeDirectories = parent->SystemIncludeDirectories;
  1172. // define flags
  1173. this->DefineFlags = parent->DefineFlags;
  1174. this->DefineFlagsOrig = parent->DefineFlagsOrig;
  1175. // Include transform property. There is no per-config version.
  1176. {
  1177. const char* prop = "IMPLICIT_DEPENDS_INCLUDE_TRANSFORM";
  1178. this->SetProperty(prop, parent->GetProperty(prop));
  1179. }
  1180. // labels
  1181. this->SetProperty("LABELS", parent->GetProperty("LABELS"));
  1182. // link libraries
  1183. this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
  1184. // the initial project name
  1185. this->StateSnapshot.SetProjectName(parent->StateSnapshot.GetProjectName());
  1186. // Copy include regular expressions.
  1187. this->ComplainFileRegularExpression = parent->ComplainFileRegularExpression;
  1188. // Imported targets.
  1189. this->ImportedTargets = parent->ImportedTargets;
  1190. // Non-global Alias targets.
  1191. this->AliasTargets = parent->AliasTargets;
  1192. // Recursion depth.
  1193. this->RecursionDepth = parent->RecursionDepth;
  1194. }
  1195. void cmMakefile::AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g)
  1196. {
  1197. if (g) {
  1198. this->InstallGenerators.push_back(std::move(g));
  1199. }
  1200. }
  1201. void cmMakefile::AddTestGenerator(std::unique_ptr<cmTestGenerator> g)
  1202. {
  1203. if (g) {
  1204. this->TestGenerators.push_back(std::move(g));
  1205. }
  1206. }
  1207. void cmMakefile::PushFunctionScope(std::string const& fileName,
  1208. const cmPolicies::PolicyMap& pm)
  1209. {
  1210. this->StateSnapshot = this->GetState()->CreateFunctionCallSnapshot(
  1211. this->StateSnapshot, fileName);
  1212. assert(this->StateSnapshot.IsValid());
  1213. this->PushLoopBlockBarrier();
  1214. #if !defined(CMAKE_BOOTSTRAP)
  1215. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  1216. #endif
  1217. this->PushFunctionBlockerBarrier();
  1218. this->PushPolicy(true, pm);
  1219. }
  1220. void cmMakefile::PopFunctionScope(bool reportError)
  1221. {
  1222. this->PopPolicy();
  1223. this->PopSnapshot(reportError);
  1224. this->PopFunctionBlockerBarrier(reportError);
  1225. #if !defined(CMAKE_BOOTSTRAP)
  1226. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  1227. #endif
  1228. this->PopLoopBlockBarrier();
  1229. }
  1230. void cmMakefile::PushMacroScope(std::string const& fileName,
  1231. const cmPolicies::PolicyMap& pm)
  1232. {
  1233. this->StateSnapshot =
  1234. this->GetState()->CreateMacroCallSnapshot(this->StateSnapshot, fileName);
  1235. assert(this->StateSnapshot.IsValid());
  1236. this->PushFunctionBlockerBarrier();
  1237. this->PushPolicy(true, pm);
  1238. }
  1239. void cmMakefile::PopMacroScope(bool reportError)
  1240. {
  1241. this->PopPolicy();
  1242. this->PopSnapshot(reportError);
  1243. this->PopFunctionBlockerBarrier(reportError);
  1244. }
  1245. bool cmMakefile::IsRootMakefile() const
  1246. {
  1247. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  1248. }
  1249. class cmMakefile::BuildsystemFileScope
  1250. {
  1251. public:
  1252. BuildsystemFileScope(cmMakefile* mf)
  1253. : Makefile(mf)
  1254. {
  1255. std::string currentStart =
  1256. this->Makefile->GetCMakeInstance()->GetCMakeListFile(
  1257. this->Makefile->StateSnapshot.GetDirectory().GetCurrentSource());
  1258. this->Makefile->StateSnapshot.SetListFile(currentStart);
  1259. this->Makefile->StateSnapshot =
  1260. this->Makefile->StateSnapshot.GetState()->CreatePolicyScopeSnapshot(
  1261. this->Makefile->StateSnapshot);
  1262. this->Makefile->PushFunctionBlockerBarrier();
  1263. this->GG = mf->GetGlobalGenerator();
  1264. this->CurrentMakefile = this->GG->GetCurrentMakefile();
  1265. this->Snapshot = this->GG->GetCMakeInstance()->GetCurrentSnapshot();
  1266. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1267. this->GG->SetCurrentMakefile(mf);
  1268. #if !defined(CMAKE_BOOTSTRAP)
  1269. this->GG->GetFileLockPool().PushFileScope();
  1270. #endif
  1271. }
  1272. ~BuildsystemFileScope()
  1273. {
  1274. this->Makefile->PopFunctionBlockerBarrier(this->ReportError);
  1275. this->Makefile->PopSnapshot(this->ReportError);
  1276. #if !defined(CMAKE_BOOTSTRAP)
  1277. this->GG->GetFileLockPool().PopFileScope();
  1278. #endif
  1279. this->GG->SetCurrentMakefile(this->CurrentMakefile);
  1280. this->GG->GetCMakeInstance()->SetCurrentSnapshot(this->Snapshot);
  1281. }
  1282. void Quiet() { this->ReportError = false; }
  1283. BuildsystemFileScope(const BuildsystemFileScope&) = delete;
  1284. BuildsystemFileScope& operator=(const BuildsystemFileScope&) = delete;
  1285. private:
  1286. cmMakefile* Makefile;
  1287. cmGlobalGenerator* GG;
  1288. cmMakefile* CurrentMakefile;
  1289. cmStateSnapshot Snapshot;
  1290. bool ReportError = true;
  1291. };
  1292. void cmMakefile::Configure()
  1293. {
  1294. std::string currentStart = this->GetCMakeInstance()->GetCMakeListFile(
  1295. this->StateSnapshot.GetDirectory().GetCurrentSource());
  1296. // Add the bottom of all backtraces within this directory.
  1297. // We will never pop this scope because it should be available
  1298. // for messages during the generate step too.
  1299. this->Backtrace =
  1300. this->Backtrace.Push(cmListFileContext::FromListFilePath(currentStart));
  1301. BuildsystemFileScope scope(this);
  1302. // make sure the CMakeFiles dir is there
  1303. std::string filesDir = cmStrCat(
  1304. this->StateSnapshot.GetDirectory().GetCurrentBinary(), "/CMakeFiles");
  1305. cmSystemTools::MakeDirectory(filesDir);
  1306. assert(cmSystemTools::FileExists(currentStart, true));
  1307. this->AddDefinition("CMAKE_PARENT_LIST_FILE", currentStart);
  1308. #ifdef CMake_ENABLE_DEBUGGER
  1309. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1310. this->GetCMakeInstance()->GetDebugAdapter()->OnBeginFileParse(
  1311. this, currentStart);
  1312. }
  1313. #endif
  1314. cmListFile listFile;
  1315. if (!listFile.ParseFile(currentStart.c_str(), this->GetMessenger(),
  1316. this->Backtrace)) {
  1317. #ifdef CMake_ENABLE_DEBUGGER
  1318. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1319. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1320. }
  1321. #endif
  1322. return;
  1323. }
  1324. #ifdef CMake_ENABLE_DEBUGGER
  1325. if (this->GetCMakeInstance()->GetDebugAdapter()) {
  1326. this->GetCMakeInstance()->GetDebugAdapter()->OnEndFileParse();
  1327. this->GetCMakeInstance()->GetDebugAdapter()->OnFileParsedSuccessfully(
  1328. currentStart, listFile.Functions);
  1329. }
  1330. #endif
  1331. if (this->IsRootMakefile()) {
  1332. bool hasVersion = false;
  1333. // search for the right policy command
  1334. for (cmListFileFunction const& func : listFile.Functions) {
  1335. if (func.LowerCaseName() == "cmake_minimum_required"_s) {
  1336. hasVersion = true;
  1337. break;
  1338. }
  1339. }
  1340. // if no policy command is found this is an error if they use any
  1341. // non advanced functions or a lot of functions
  1342. if (!hasVersion) {
  1343. bool isProblem = true;
  1344. if (listFile.Functions.size() < 30) {
  1345. // the list of simple commands DO NOT ADD TO THIS LIST!!!!!
  1346. // these commands must have backwards compatibility forever and
  1347. // and that is a lot longer than your tiny mind can comprehend mortal
  1348. std::set<std::string> allowedCommands;
  1349. allowedCommands.insert("project");
  1350. allowedCommands.insert("set");
  1351. allowedCommands.insert("if");
  1352. allowedCommands.insert("endif");
  1353. allowedCommands.insert("else");
  1354. allowedCommands.insert("elseif");
  1355. allowedCommands.insert("add_executable");
  1356. allowedCommands.insert("add_library");
  1357. allowedCommands.insert("target_link_libraries");
  1358. allowedCommands.insert("option");
  1359. allowedCommands.insert("message");
  1360. isProblem = false;
  1361. for (cmListFileFunction const& func : listFile.Functions) {
  1362. if (!cm::contains(allowedCommands, func.LowerCaseName())) {
  1363. isProblem = true;
  1364. break;
  1365. }
  1366. }
  1367. }
  1368. if (isProblem) {
  1369. // Tell the top level cmMakefile to diagnose
  1370. // this violation of CMP0000.
  1371. this->SetCheckCMP0000(true);
  1372. // Implicitly set the version for the user.
  1373. cmPolicies::ApplyPolicyVersion(this, 3, 0, 0,
  1374. cmPolicies::WarnCompat::Off);
  1375. }
  1376. }
  1377. bool hasProject = false;
  1378. // search for a project command
  1379. for (cmListFileFunction const& func : listFile.Functions) {
  1380. if (func.LowerCaseName() == "project"_s) {
  1381. hasProject = true;
  1382. break;
  1383. }
  1384. }
  1385. // if no project command is found, add one
  1386. if (!hasProject) {
  1387. this->GetCMakeInstance()->IssueMessage(
  1388. MessageType::AUTHOR_WARNING,
  1389. "No project() command is present. The top-level CMakeLists.txt "
  1390. "file must contain a literal, direct call to the project() command. "
  1391. "Add a line of code such as\n"
  1392. " project(ProjectName)\n"
  1393. "near the top of the file, but after cmake_minimum_required().\n"
  1394. "CMake is pretending there is a \"project(Project)\" command on "
  1395. "the first line.",
  1396. this->Backtrace);
  1397. cmListFileFunction project{
  1398. "project", 0, 0, { { "Project", cmListFileArgument::Unquoted, 0 } }
  1399. };
  1400. listFile.Functions.insert(listFile.Functions.begin(), project);
  1401. }
  1402. }
  1403. this->Defer = cm::make_unique<DeferCommands>();
  1404. this->RunListFile(listFile, currentStart, this->Defer.get());
  1405. this->Defer.reset();
  1406. if (cmSystemTools::GetFatalErrorOccurred()) {
  1407. scope.Quiet();
  1408. }
  1409. // at the end handle any old style subdirs
  1410. std::vector<cmMakefile*> subdirs = this->UnConfiguredDirectories;
  1411. // for each subdir recurse
  1412. auto sdi = subdirs.begin();
  1413. for (; sdi != subdirs.end(); ++sdi) {
  1414. (*sdi)->StateSnapshot.InitializeFromParent_ForSubdirsCommand();
  1415. this->ConfigureSubDirectory(*sdi);
  1416. }
  1417. this->AddCMakeDependFilesFromUser();
  1418. }
  1419. void cmMakefile::ConfigureSubDirectory(cmMakefile* mf)
  1420. {
  1421. mf->InitializeFromParent(this);
  1422. std::string currentStart = mf->GetCurrentSourceDirectory();
  1423. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1424. std::string msg = cmStrCat(" Entering ", currentStart);
  1425. cmSystemTools::Message(msg);
  1426. }
  1427. std::string currentStartFile =
  1428. this->GetCMakeInstance()->GetCMakeListFile(currentStart);
  1429. if (!cmSystemTools::FileExists(currentStartFile, true)) {
  1430. this->IssueMessage(MessageType::FATAL_ERROR,
  1431. cmStrCat("The source directory\n ", currentStart,
  1432. "\n"
  1433. "does not contain a CMakeLists.txt file."));
  1434. return;
  1435. }
  1436. // finally configure the subdir
  1437. mf->Configure();
  1438. if (this->GetCMakeInstance()->GetDebugOutput()) {
  1439. auto msg =
  1440. cmStrCat(" Returning to ", this->GetCurrentSourceDirectory());
  1441. cmSystemTools::Message(msg);
  1442. }
  1443. }
  1444. void cmMakefile::AddSubDirectory(const std::string& srcPath,
  1445. const std::string& binPath,
  1446. bool excludeFromAll, bool immediate,
  1447. bool system)
  1448. {
  1449. if (this->DeferRunning) {
  1450. this->IssueMessage(
  1451. MessageType::FATAL_ERROR,
  1452. "Subdirectories may not be created during deferred execution.");
  1453. return;
  1454. }
  1455. // Make sure the binary directory is unique.
  1456. if (!this->EnforceUniqueDir(srcPath, binPath)) {
  1457. return;
  1458. }
  1459. cmStateSnapshot newSnapshot =
  1460. this->GetState()->CreateBuildsystemDirectorySnapshot(this->StateSnapshot);
  1461. newSnapshot.GetDirectory().SetCurrentSource(srcPath);
  1462. newSnapshot.GetDirectory().SetCurrentBinary(binPath);
  1463. cmSystemTools::MakeDirectory(binPath);
  1464. auto subMfu =
  1465. cm::make_unique<cmMakefile>(this->GlobalGenerator, newSnapshot);
  1466. auto* subMf = subMfu.get();
  1467. this->GetGlobalGenerator()->AddMakefile(std::move(subMfu));
  1468. if (excludeFromAll) {
  1469. subMf->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1470. }
  1471. if (system) {
  1472. subMf->SetProperty("SYSTEM", "TRUE");
  1473. }
  1474. if (immediate) {
  1475. this->ConfigureSubDirectory(subMf);
  1476. } else {
  1477. this->UnConfiguredDirectories.push_back(subMf);
  1478. }
  1479. this->AddInstallGenerator(cm::make_unique<cmInstallSubdirectoryGenerator>(
  1480. subMf, binPath, this->GetBacktrace()));
  1481. }
  1482. const std::string& cmMakefile::GetCurrentSourceDirectory() const
  1483. {
  1484. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  1485. }
  1486. const std::string& cmMakefile::GetCurrentBinaryDirectory() const
  1487. {
  1488. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  1489. }
  1490. std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
  1491. {
  1492. std::vector<cmTarget*> tgts;
  1493. tgts.reserve(this->ImportedTargets.size());
  1494. for (auto const& impTarget : this->ImportedTargets) {
  1495. tgts.push_back(impTarget.second);
  1496. }
  1497. return tgts;
  1498. }
  1499. void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
  1500. bool before)
  1501. {
  1502. if (incs.empty()) {
  1503. return;
  1504. }
  1505. std::string entryString = cmList::to_string(incs);
  1506. if (before) {
  1507. this->StateSnapshot.GetDirectory().PrependIncludeDirectoriesEntry(
  1508. BT<std::string>(entryString, this->Backtrace));
  1509. } else {
  1510. this->StateSnapshot.GetDirectory().AppendIncludeDirectoriesEntry(
  1511. BT<std::string>(entryString, this->Backtrace));
  1512. }
  1513. // Property on each target:
  1514. for (auto& target : this->Targets) {
  1515. cmTarget& t = target.second;
  1516. t.InsertInclude(BT<std::string>(entryString, this->Backtrace), before);
  1517. }
  1518. }
  1519. void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
  1520. {
  1521. if (incs.empty()) {
  1522. return;
  1523. }
  1524. this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
  1525. for (auto& target : this->Targets) {
  1526. cmTarget& t = target.second;
  1527. t.AddSystemIncludeDirectories(incs);
  1528. }
  1529. }
  1530. void cmMakefile::AddDefinition(const std::string& name, cm::string_view value)
  1531. {
  1532. this->StateSnapshot.SetDefinition(name, value);
  1533. #ifndef CMAKE_BOOTSTRAP
  1534. cmVariableWatch* vv = this->GetVariableWatch();
  1535. if (vv) {
  1536. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  1537. value.data(), this);
  1538. }
  1539. #endif
  1540. }
  1541. void cmMakefile::AddDefinitionBool(const std::string& name, bool value)
  1542. {
  1543. this->AddDefinition(name, value ? "ON" : "OFF");
  1544. }
  1545. void cmMakefile::AddCacheDefinition(const std::string& name, cmValue value,
  1546. cmValue doc,
  1547. cmStateEnums::CacheEntryType type,
  1548. bool force)
  1549. {
  1550. cmValue existingValue = this->GetState()->GetInitializedCacheValue(name);
  1551. // must be outside the following if() to keep it alive long enough
  1552. std::string nvalue;
  1553. if (existingValue &&
  1554. (this->GetState()->GetCacheEntryType(name) ==
  1555. cmStateEnums::UNINITIALIZED)) {
  1556. // if this is not a force, then use the value from the cache
  1557. // if it is a force, then use the value being passed in
  1558. if (!force) {
  1559. value = existingValue;
  1560. }
  1561. if (type == cmStateEnums::PATH || type == cmStateEnums::FILEPATH) {
  1562. cmList files(value);
  1563. for (auto& file : files) {
  1564. if (!cmIsOff(file)) {
  1565. file = cmSystemTools::ToNormalizedPathOnDisk(file);
  1566. }
  1567. }
  1568. nvalue = files.to_string();
  1569. value = cmValue{ nvalue };
  1570. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1571. value = this->GetState()->GetInitializedCacheValue(name);
  1572. }
  1573. }
  1574. this->GetCMakeInstance()->AddCacheEntry(name, value, doc, type);
  1575. switch (this->GetPolicyStatus(cmPolicies::CMP0126)) {
  1576. case cmPolicies::WARN:
  1577. if (this->PolicyOptionalWarningEnabled("CMAKE_POLICY_WARNING_CMP0126") &&
  1578. this->IsNormalDefinitionSet(name)) {
  1579. this->IssueMessage(
  1580. MessageType::AUTHOR_WARNING,
  1581. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0126),
  1582. "\nFor compatibility with older versions of CMake, normal "
  1583. "variable \"",
  1584. name, "\" will be removed from the current scope."));
  1585. }
  1586. CM_FALLTHROUGH;
  1587. case cmPolicies::OLD:
  1588. // if there was a definition then remove it
  1589. this->StateSnapshot.RemoveDefinition(name);
  1590. break;
  1591. case cmPolicies::NEW:
  1592. break;
  1593. }
  1594. }
  1595. void cmMakefile::MarkVariableAsUsed(const std::string& var)
  1596. {
  1597. this->StateSnapshot.GetDefinition(var);
  1598. }
  1599. bool cmMakefile::VariableInitialized(const std::string& var) const
  1600. {
  1601. return this->StateSnapshot.IsInitialized(var);
  1602. }
  1603. void cmMakefile::MaybeWarnUninitialized(std::string const& variable,
  1604. const char* sourceFilename) const
  1605. {
  1606. // check to see if we need to print a warning
  1607. // if strict mode is on and the variable has
  1608. // not been "cleared"/initialized with a set(foo ) call
  1609. if (this->GetCMakeInstance()->GetWarnUninitialized() &&
  1610. !this->VariableInitialized(variable)) {
  1611. if (this->CheckSystemVars ||
  1612. (sourceFilename && this->IsProjectFile(sourceFilename))) {
  1613. this->IssueMessage(MessageType::AUTHOR_WARNING,
  1614. cmStrCat("uninitialized variable '", variable, '\''));
  1615. }
  1616. }
  1617. }
  1618. void cmMakefile::RemoveDefinition(const std::string& name)
  1619. {
  1620. this->StateSnapshot.RemoveDefinition(name);
  1621. #ifndef CMAKE_BOOTSTRAP
  1622. cmVariableWatch* vv = this->GetVariableWatch();
  1623. if (vv) {
  1624. vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
  1625. nullptr, this);
  1626. }
  1627. #endif
  1628. }
  1629. void cmMakefile::RemoveCacheDefinition(const std::string& name) const
  1630. {
  1631. this->GetState()->RemoveCacheEntry(name);
  1632. }
  1633. void cmMakefile::SetProjectName(std::string const& p)
  1634. {
  1635. this->StateSnapshot.SetProjectName(p);
  1636. }
  1637. void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
  1638. {
  1639. // for these targets do not add anything
  1640. switch (target.GetType()) {
  1641. case cmStateEnums::UTILITY:
  1642. case cmStateEnums::GLOBAL_TARGET:
  1643. case cmStateEnums::INTERFACE_LIBRARY:
  1644. return;
  1645. default:;
  1646. }
  1647. if (cmValue linkLibsProp = this->GetProperty("LINK_LIBRARIES")) {
  1648. cmList linkLibs{ *linkLibsProp };
  1649. for (auto j = linkLibs.begin(); j != linkLibs.end(); ++j) {
  1650. std::string libraryName = *j;
  1651. cmTargetLinkLibraryType libType = GENERAL_LibraryType;
  1652. if (libraryName == "optimized"_s) {
  1653. libType = OPTIMIZED_LibraryType;
  1654. ++j;
  1655. libraryName = *j;
  1656. } else if (libraryName == "debug"_s) {
  1657. libType = DEBUG_LibraryType;
  1658. ++j;
  1659. libraryName = *j;
  1660. }
  1661. // This is equivalent to the target_link_libraries plain signature.
  1662. target.AddLinkLibrary(*this, libraryName, libType);
  1663. target.AppendProperty(
  1664. "INTERFACE_LINK_LIBRARIES",
  1665. target.GetDebugGeneratorExpressions(libraryName, libType));
  1666. }
  1667. }
  1668. }
  1669. void cmMakefile::AddAlias(const std::string& lname, std::string const& tgtName,
  1670. bool globallyVisible)
  1671. {
  1672. this->AliasTargets[lname] = tgtName;
  1673. if (globallyVisible) {
  1674. this->GetGlobalGenerator()->AddAlias(lname, tgtName);
  1675. }
  1676. }
  1677. cmTarget* cmMakefile::AddLibrary(const std::string& lname,
  1678. cmStateEnums::TargetType type,
  1679. const std::vector<std::string>& srcs,
  1680. bool excludeFromAll)
  1681. {
  1682. assert(type == cmStateEnums::STATIC_LIBRARY ||
  1683. type == cmStateEnums::SHARED_LIBRARY ||
  1684. type == cmStateEnums::MODULE_LIBRARY ||
  1685. type == cmStateEnums::OBJECT_LIBRARY ||
  1686. type == cmStateEnums::INTERFACE_LIBRARY);
  1687. cmTarget* target = this->AddNewTarget(type, lname);
  1688. // Clear its dependencies. Otherwise, dependencies might persist
  1689. // over changes in CMakeLists.txt, making the information stale and
  1690. // hence useless.
  1691. target->ClearDependencyInformation(*this);
  1692. if (excludeFromAll) {
  1693. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1694. }
  1695. target->AddSources(srcs);
  1696. this->AddGlobalLinkInformation(*target);
  1697. return target;
  1698. }
  1699. cmTarget* cmMakefile::AddExecutable(const std::string& exeName,
  1700. const std::vector<std::string>& srcs,
  1701. bool excludeFromAll)
  1702. {
  1703. cmTarget* target = this->AddNewTarget(cmStateEnums::EXECUTABLE, exeName);
  1704. if (excludeFromAll) {
  1705. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1706. }
  1707. target->AddSources(srcs);
  1708. this->AddGlobalLinkInformation(*target);
  1709. return target;
  1710. }
  1711. cmTarget* cmMakefile::AddNewTarget(cmStateEnums::TargetType type,
  1712. const std::string& name)
  1713. {
  1714. return &this->CreateNewTarget(name, type).first;
  1715. }
  1716. cmTarget* cmMakefile::AddSynthesizedTarget(cmStateEnums::TargetType type,
  1717. const std::string& name)
  1718. {
  1719. return &this
  1720. ->CreateNewTarget(name, type, cmTarget::PerConfig::Yes,
  1721. cmTarget::Visibility::Generated)
  1722. .first;
  1723. }
  1724. std::pair<cmTarget&, bool> cmMakefile::CreateNewTarget(
  1725. const std::string& name, cmStateEnums::TargetType type,
  1726. cmTarget::PerConfig perConfig, cmTarget::Visibility vis)
  1727. {
  1728. auto ib =
  1729. this->Targets.emplace(name, cmTarget(name, type, vis, this, perConfig));
  1730. auto it = ib.first;
  1731. if (!ib.second) {
  1732. return std::make_pair(std::ref(it->second), false);
  1733. }
  1734. this->OrderedTargets.push_back(&it->second);
  1735. this->GetGlobalGenerator()->IndexTarget(&it->second);
  1736. this->GetStateSnapshot().GetDirectory().AddNormalTargetName(name);
  1737. return std::make_pair(std::ref(it->second), true);
  1738. }
  1739. cmTarget* cmMakefile::AddNewUtilityTarget(const std::string& utilityName,
  1740. bool excludeFromAll)
  1741. {
  1742. cmTarget* target = this->AddNewTarget(cmStateEnums::UTILITY, utilityName);
  1743. if (excludeFromAll) {
  1744. target->SetProperty("EXCLUDE_FROM_ALL", "TRUE");
  1745. }
  1746. return target;
  1747. }
  1748. namespace {
  1749. }
  1750. #if !defined(CMAKE_BOOTSTRAP)
  1751. cmSourceGroup* cmMakefile::GetSourceGroup(
  1752. const std::vector<std::string>& name) const
  1753. {
  1754. cmSourceGroup* sg = nullptr;
  1755. // first look for source group starting with the same as the one we want
  1756. for (cmSourceGroup const& srcGroup : this->SourceGroups) {
  1757. std::string const& sgName = srcGroup.GetName();
  1758. if (sgName == name[0]) {
  1759. sg = const_cast<cmSourceGroup*>(&srcGroup);
  1760. break;
  1761. }
  1762. }
  1763. if (sg) {
  1764. // iterate through its children to find match source group
  1765. for (unsigned int i = 1; i < name.size(); ++i) {
  1766. sg = sg->LookupChild(name[i]);
  1767. if (!sg) {
  1768. break;
  1769. }
  1770. }
  1771. }
  1772. return sg;
  1773. }
  1774. void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
  1775. {
  1776. std::vector<std::string> nameVector;
  1777. nameVector.push_back(name);
  1778. this->AddSourceGroup(nameVector, regex);
  1779. }
  1780. void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
  1781. const char* regex)
  1782. {
  1783. cmSourceGroup* sg = nullptr;
  1784. std::vector<std::string> currentName;
  1785. int i = 0;
  1786. const int lastElement = static_cast<int>(name.size() - 1);
  1787. for (i = lastElement; i >= 0; --i) {
  1788. currentName.assign(name.begin(), name.begin() + i + 1);
  1789. sg = this->GetSourceGroup(currentName);
  1790. if (sg) {
  1791. break;
  1792. }
  1793. }
  1794. // i now contains the index of the last found component
  1795. if (i == lastElement) {
  1796. // group already exists, replace its regular expression
  1797. if (regex && sg) {
  1798. // We only want to set the regular expression. If there are already
  1799. // source files in the group, we don't want to remove them.
  1800. sg->SetGroupRegex(regex);
  1801. }
  1802. return;
  1803. }
  1804. if (i == -1) {
  1805. // group does not exist nor belong to any existing group
  1806. // add its first component
  1807. this->SourceGroups.emplace_back(name[0], regex);
  1808. sg = this->GetSourceGroup(currentName);
  1809. i = 0; // last component found
  1810. }
  1811. if (!sg) {
  1812. cmSystemTools::Error("Could not create source group ");
  1813. return;
  1814. }
  1815. // build the whole source group path
  1816. for (++i; i <= lastElement; ++i) {
  1817. sg->AddChild(cmSourceGroup(name[i], nullptr, sg->GetFullName().c_str()));
  1818. sg = sg->LookupChild(name[i]);
  1819. }
  1820. sg->SetGroupRegex(regex);
  1821. }
  1822. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
  1823. const std::vector<std::string>& folders)
  1824. {
  1825. cmSourceGroup* sg = this->GetSourceGroup(folders);
  1826. if (!sg) {
  1827. this->AddSourceGroup(folders);
  1828. sg = this->GetSourceGroup(folders);
  1829. }
  1830. return sg;
  1831. }
  1832. cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
  1833. {
  1834. auto p = this->GetDefinition("SOURCE_GROUP_DELIMITER");
  1835. return this->GetOrCreateSourceGroup(
  1836. cmTokenize(name, p ? cm::string_view(*p) : R"(\/)"_s));
  1837. }
  1838. /**
  1839. * Find a source group whose regular expression matches the filename
  1840. * part of the given source name. Search backward through the list of
  1841. * source groups, and take the first matching group found. This way
  1842. * non-inherited SOURCE_GROUP commands will have precedence over
  1843. * inherited ones.
  1844. */
  1845. cmSourceGroup* cmMakefile::FindSourceGroup(
  1846. const std::string& source, std::vector<cmSourceGroup>& groups) const
  1847. {
  1848. // First search for a group that lists the file explicitly.
  1849. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  1850. cmSourceGroup* result = sg->MatchChildrenFiles(source);
  1851. if (result) {
  1852. return result;
  1853. }
  1854. }
  1855. // Now search for a group whose regex matches the file.
  1856. for (auto sg = groups.rbegin(); sg != groups.rend(); ++sg) {
  1857. cmSourceGroup* result = sg->MatchChildrenRegex(source);
  1858. if (result) {
  1859. return result;
  1860. }
  1861. }
  1862. // Shouldn't get here, but just in case, return the default group.
  1863. return groups.data();
  1864. }
  1865. #endif
  1866. bool cmMakefile::IsOn(const std::string& name) const
  1867. {
  1868. return this->GetDefinition(name).IsOn();
  1869. }
  1870. bool cmMakefile::IsSet(const std::string& name) const
  1871. {
  1872. cmValue value = this->GetDefinition(name);
  1873. if (!value) {
  1874. return false;
  1875. }
  1876. if (value->empty()) {
  1877. return false;
  1878. }
  1879. if (cmIsNOTFOUND(*value)) {
  1880. return false;
  1881. }
  1882. return true;
  1883. }
  1884. bool cmMakefile::PlatformIs32Bit() const
  1885. {
  1886. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  1887. if (*plat_abi == "ELF X32"_s) {
  1888. return false;
  1889. }
  1890. }
  1891. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  1892. return atoi(sizeof_dptr->c_str()) == 4;
  1893. }
  1894. return false;
  1895. }
  1896. bool cmMakefile::PlatformIs64Bit() const
  1897. {
  1898. if (cmValue sizeof_dptr = this->GetDefinition("CMAKE_SIZEOF_VOID_P")) {
  1899. return atoi(sizeof_dptr->c_str()) == 8;
  1900. }
  1901. return false;
  1902. }
  1903. bool cmMakefile::PlatformIsx32() const
  1904. {
  1905. if (cmValue plat_abi = this->GetDefinition("CMAKE_INTERNAL_PLATFORM_ABI")) {
  1906. if (*plat_abi == "ELF X32"_s) {
  1907. return true;
  1908. }
  1909. }
  1910. return false;
  1911. }
  1912. cmMakefile::AppleSDK cmMakefile::GetAppleSDKType() const
  1913. {
  1914. std::string sdkRoot;
  1915. sdkRoot = this->GetSafeDefinition("CMAKE_OSX_SYSROOT");
  1916. sdkRoot = cmSystemTools::LowerCase(sdkRoot);
  1917. struct
  1918. {
  1919. std::string name;
  1920. AppleSDK sdk;
  1921. } const sdkDatabase[]{
  1922. { "appletvos", AppleSDK::AppleTVOS },
  1923. { "appletvsimulator", AppleSDK::AppleTVSimulator },
  1924. { "iphoneos", AppleSDK::IPhoneOS },
  1925. { "iphonesimulator", AppleSDK::IPhoneSimulator },
  1926. { "watchos", AppleSDK::WatchOS },
  1927. { "watchsimulator", AppleSDK::WatchSimulator },
  1928. { "xros", AppleSDK::XROS },
  1929. { "xrsimulator", AppleSDK::XRSimulator },
  1930. };
  1931. for (auto const& entry : sdkDatabase) {
  1932. if (cmHasPrefix(sdkRoot, entry.name) ||
  1933. sdkRoot.find(cmStrCat('/', entry.name)) != std::string::npos) {
  1934. return entry.sdk;
  1935. }
  1936. }
  1937. return AppleSDK::MacOS;
  1938. }
  1939. bool cmMakefile::PlatformIsAppleEmbedded() const
  1940. {
  1941. return this->GetAppleSDKType() != AppleSDK::MacOS;
  1942. }
  1943. bool cmMakefile::PlatformIsAppleSimulator() const
  1944. {
  1945. return std::set<AppleSDK>{
  1946. AppleSDK::AppleTVSimulator,
  1947. AppleSDK::IPhoneSimulator,
  1948. AppleSDK::WatchSimulator,
  1949. AppleSDK::XRSimulator,
  1950. }
  1951. .count(this->GetAppleSDKType());
  1952. }
  1953. bool cmMakefile::PlatformIsAppleCatalyst() const
  1954. {
  1955. std::string systemName;
  1956. systemName = this->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  1957. systemName = cmSystemTools::LowerCase(systemName);
  1958. return systemName == "ios" && this->GetAppleSDKType() == AppleSDK::MacOS;
  1959. }
  1960. bool cmMakefile::PlatformSupportsAppleTextStubs() const
  1961. {
  1962. return this->IsOn("APPLE") && this->IsSet("CMAKE_TAPI");
  1963. }
  1964. const char* cmMakefile::GetSONameFlag(const std::string& language) const
  1965. {
  1966. std::string name = "CMAKE_SHARED_LIBRARY_SONAME";
  1967. if (!language.empty()) {
  1968. name += "_";
  1969. name += language;
  1970. }
  1971. name += "_FLAG";
  1972. return this->GetDefinition(name).GetCStr();
  1973. }
  1974. bool cmMakefile::CanIWriteThisFile(std::string const& fileName) const
  1975. {
  1976. if (!this->IsOn("CMAKE_DISABLE_SOURCE_CHANGES")) {
  1977. return true;
  1978. }
  1979. // If we are doing an in-source build, then the test will always fail
  1980. if (cmSystemTools::SameFile(this->GetHomeDirectory(),
  1981. this->GetHomeOutputDirectory())) {
  1982. return !this->IsOn("CMAKE_DISABLE_IN_SOURCE_BUILD");
  1983. }
  1984. return !cmSystemTools::IsSubDirectory(fileName, this->GetHomeDirectory()) ||
  1985. cmSystemTools::IsSubDirectory(fileName, this->GetHomeOutputDirectory()) ||
  1986. cmSystemTools::SameFile(fileName, this->GetHomeOutputDirectory());
  1987. }
  1988. const std::string& cmMakefile::GetRequiredDefinition(
  1989. const std::string& name) const
  1990. {
  1991. static std::string const empty;
  1992. cmValue def = this->GetDefinition(name);
  1993. if (!def) {
  1994. cmSystemTools::Error("Error required internal CMake variable not "
  1995. "set, cmake may not be built correctly.\n"
  1996. "Missing variable is:\n" +
  1997. name);
  1998. return empty;
  1999. }
  2000. return *def;
  2001. }
  2002. bool cmMakefile::IsDefinitionSet(const std::string& name) const
  2003. {
  2004. cmValue def = this->StateSnapshot.GetDefinition(name);
  2005. if (!def) {
  2006. def = this->GetState()->GetInitializedCacheValue(name);
  2007. }
  2008. #ifndef CMAKE_BOOTSTRAP
  2009. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2010. if (!def) {
  2011. vv->VariableAccessed(
  2012. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2013. }
  2014. }
  2015. #endif
  2016. return def != nullptr;
  2017. }
  2018. bool cmMakefile::IsNormalDefinitionSet(const std::string& name) const
  2019. {
  2020. cmValue def = this->StateSnapshot.GetDefinition(name);
  2021. #ifndef CMAKE_BOOTSTRAP
  2022. if (cmVariableWatch* vv = this->GetVariableWatch()) {
  2023. if (!def) {
  2024. vv->VariableAccessed(
  2025. name, cmVariableWatch::UNKNOWN_VARIABLE_DEFINED_ACCESS, nullptr, this);
  2026. }
  2027. }
  2028. #endif
  2029. return def != nullptr;
  2030. }
  2031. cmValue cmMakefile::GetDefinition(const std::string& name) const
  2032. {
  2033. cmValue def = this->StateSnapshot.GetDefinition(name);
  2034. if (!def) {
  2035. def = this->GetState()->GetInitializedCacheValue(name);
  2036. }
  2037. #ifndef CMAKE_BOOTSTRAP
  2038. cmVariableWatch* vv = this->GetVariableWatch();
  2039. if (vv) {
  2040. bool const watch_function_executed =
  2041. vv->VariableAccessed(name,
  2042. def ? cmVariableWatch::VARIABLE_READ_ACCESS
  2043. : cmVariableWatch::UNKNOWN_VARIABLE_READ_ACCESS,
  2044. def.GetCStr(), this);
  2045. if (watch_function_executed) {
  2046. // A callback was executed and may have caused re-allocation of the
  2047. // variable storage. Look it up again for now.
  2048. // FIXME: Refactor variable storage to avoid this problem.
  2049. def = this->StateSnapshot.GetDefinition(name);
  2050. if (!def) {
  2051. def = this->GetState()->GetInitializedCacheValue(name);
  2052. }
  2053. }
  2054. }
  2055. #endif
  2056. return def;
  2057. }
  2058. const std::string& cmMakefile::GetSafeDefinition(const std::string& name) const
  2059. {
  2060. return this->GetDefinition(name);
  2061. }
  2062. std::vector<std::string> cmMakefile::GetDefinitions() const
  2063. {
  2064. std::vector<std::string> res = this->StateSnapshot.ClosureKeys();
  2065. cm::append(res, this->GetState()->GetCacheEntryKeys());
  2066. std::sort(res.begin(), res.end());
  2067. return res;
  2068. }
  2069. const std::string& cmMakefile::ExpandVariablesInString(
  2070. std::string& source) const
  2071. {
  2072. return this->ExpandVariablesInString(source, false, false);
  2073. }
  2074. const std::string& cmMakefile::ExpandVariablesInString(
  2075. std::string& source, bool escapeQuotes, bool noEscapes, bool atOnly,
  2076. const char* filename, long line, bool removeEmpty, bool replaceAt) const
  2077. {
  2078. // Sanity check the @ONLY mode.
  2079. if (atOnly && (!noEscapes || !removeEmpty)) {
  2080. // This case should never be called. At-only is for
  2081. // configure-file/string which always does no escapes.
  2082. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2083. "ExpandVariablesInString @ONLY called "
  2084. "on something with escapes.");
  2085. return source;
  2086. }
  2087. std::string errorstr;
  2088. MessageType mtype = this->ExpandVariablesInStringImpl(
  2089. errorstr, source, escapeQuotes, noEscapes, atOnly, filename, line,
  2090. replaceAt);
  2091. if (mtype != MessageType::LOG) {
  2092. if (mtype == MessageType::FATAL_ERROR) {
  2093. cmSystemTools::SetFatalErrorOccurred();
  2094. }
  2095. this->IssueMessage(mtype, errorstr);
  2096. }
  2097. return source;
  2098. }
  2099. enum t_domain
  2100. {
  2101. NORMAL,
  2102. ENVIRONMENT,
  2103. CACHE
  2104. };
  2105. struct t_lookup
  2106. {
  2107. t_domain domain = NORMAL;
  2108. size_t loc = 0;
  2109. };
  2110. bool cmMakefile::IsProjectFile(const char* filename) const
  2111. {
  2112. return cmSystemTools::IsSubDirectory(filename, this->GetHomeDirectory()) ||
  2113. (cmSystemTools::IsSubDirectory(filename, this->GetHomeOutputDirectory()) &&
  2114. !cmSystemTools::IsSubDirectory(filename, "/CMakeFiles"));
  2115. }
  2116. size_t cmMakefile::GetRecursionDepthLimit() const
  2117. {
  2118. size_t depth = CMake_DEFAULT_RECURSION_LIMIT;
  2119. if (cmValue depthStr =
  2120. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2121. unsigned long depthUL;
  2122. if (cmStrToULong(depthStr.GetCStr(), &depthUL)) {
  2123. depth = depthUL;
  2124. }
  2125. } else if (cm::optional<std::string> depthEnv =
  2126. cmSystemTools::GetEnvVar("CMAKE_MAXIMUM_RECURSION_DEPTH")) {
  2127. unsigned long depthUL;
  2128. if (cmStrToULong(*depthEnv, &depthUL)) {
  2129. depth = depthUL;
  2130. }
  2131. }
  2132. return depth;
  2133. }
  2134. size_t cmMakefile::GetRecursionDepth() const
  2135. {
  2136. return this->RecursionDepth;
  2137. }
  2138. void cmMakefile::SetRecursionDepth(size_t recursionDepth)
  2139. {
  2140. this->RecursionDepth = recursionDepth;
  2141. }
  2142. std::string cmMakefile::NewDeferId() const
  2143. {
  2144. return this->GetGlobalGenerator()->NewDeferId();
  2145. }
  2146. bool cmMakefile::DeferCall(std::string id, std::string file,
  2147. cmListFileFunction lff)
  2148. {
  2149. if (!this->Defer) {
  2150. return false;
  2151. }
  2152. this->Defer->Commands.emplace_back(
  2153. DeferCommand{ std::move(id), std::move(file), std::move(lff) });
  2154. return true;
  2155. }
  2156. bool cmMakefile::DeferCancelCall(std::string const& id)
  2157. {
  2158. if (!this->Defer) {
  2159. return false;
  2160. }
  2161. for (DeferCommand& dc : this->Defer->Commands) {
  2162. if (dc.Id == id) {
  2163. dc.Id.clear();
  2164. }
  2165. }
  2166. return true;
  2167. }
  2168. cm::optional<std::string> cmMakefile::DeferGetCallIds() const
  2169. {
  2170. cm::optional<std::string> ids;
  2171. if (this->Defer) {
  2172. ids = cmList::to_string(
  2173. cmMakeRange(this->Defer->Commands)
  2174. .filter([](DeferCommand const& dc) -> bool { return !dc.Id.empty(); })
  2175. .transform(
  2176. [](DeferCommand const& dc) -> std::string const& { return dc.Id; }));
  2177. }
  2178. return ids;
  2179. }
  2180. cm::optional<std::string> cmMakefile::DeferGetCall(std::string const& id) const
  2181. {
  2182. cm::optional<std::string> call;
  2183. if (this->Defer) {
  2184. std::string tmp;
  2185. for (DeferCommand const& dc : this->Defer->Commands) {
  2186. if (dc.Id == id) {
  2187. tmp = dc.Command.OriginalName();
  2188. for (cmListFileArgument const& arg : dc.Command.Arguments()) {
  2189. tmp = cmStrCat(tmp, ';', arg.Value);
  2190. }
  2191. break;
  2192. }
  2193. }
  2194. call = std::move(tmp);
  2195. }
  2196. return call;
  2197. }
  2198. MessageType cmMakefile::ExpandVariablesInStringImpl(
  2199. std::string& errorstr, std::string& source, bool escapeQuotes,
  2200. bool noEscapes, bool atOnly, const char* filename, long line,
  2201. bool replaceAt) const
  2202. {
  2203. // This method replaces ${VAR} and @VAR@ where VAR is looked up
  2204. // with GetDefinition(), if not found in the map, nothing is expanded.
  2205. // It also supports the $ENV{VAR} syntax where VAR is looked up in
  2206. // the current environment variables.
  2207. const char* in = source.c_str();
  2208. const char* last = in;
  2209. std::string result;
  2210. result.reserve(source.size());
  2211. std::vector<t_lookup> openstack;
  2212. bool error = false;
  2213. bool done = false;
  2214. MessageType mtype = MessageType::LOG;
  2215. cmState* state = this->GetCMakeInstance()->GetState();
  2216. static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
  2217. do {
  2218. char inc = *in;
  2219. switch (inc) {
  2220. case '}':
  2221. if (!openstack.empty()) {
  2222. t_lookup var = openstack.back();
  2223. openstack.pop_back();
  2224. result.append(last, in - last);
  2225. std::string const& lookup = result.substr(var.loc);
  2226. cmValue value = nullptr;
  2227. std::string varresult;
  2228. std::string svalue;
  2229. switch (var.domain) {
  2230. case NORMAL:
  2231. if (filename && lookup == lineVar) {
  2232. cmListFileContext const& top = this->Backtrace.Top();
  2233. if (top.DeferId) {
  2234. varresult = cmStrCat("DEFERRED:"_s, *top.DeferId);
  2235. } else {
  2236. varresult = std::to_string(line);
  2237. }
  2238. } else {
  2239. value = this->GetDefinition(lookup);
  2240. }
  2241. break;
  2242. case ENVIRONMENT:
  2243. if (cmSystemTools::GetEnv(lookup, svalue)) {
  2244. value = cmValue(svalue);
  2245. }
  2246. break;
  2247. case CACHE:
  2248. value = state->GetCacheEntryValue(lookup);
  2249. break;
  2250. }
  2251. // Get the string we're meant to append to.
  2252. if (value) {
  2253. if (escapeQuotes) {
  2254. varresult = cmEscapeQuotes(*value);
  2255. } else {
  2256. varresult = *value;
  2257. }
  2258. } else {
  2259. this->MaybeWarnUninitialized(lookup, filename);
  2260. }
  2261. result.replace(var.loc, result.size() - var.loc, varresult);
  2262. // Start looking from here on out.
  2263. last = in + 1;
  2264. }
  2265. break;
  2266. case '$':
  2267. if (!atOnly) {
  2268. t_lookup lookup;
  2269. const char* next = in + 1;
  2270. const char* start = nullptr;
  2271. char nextc = *next;
  2272. if (nextc == '{') {
  2273. // Looking for a variable.
  2274. start = in + 2;
  2275. lookup.domain = NORMAL;
  2276. } else if (nextc == '<') {
  2277. } else if (!nextc) {
  2278. result.append(last, next - last);
  2279. last = next;
  2280. } else if (cmHasLiteralPrefix(next, "ENV{")) {
  2281. // Looking for an environment variable.
  2282. start = in + 5;
  2283. lookup.domain = ENVIRONMENT;
  2284. } else if (cmHasLiteralPrefix(next, "CACHE{")) {
  2285. // Looking for a cache variable.
  2286. start = in + 7;
  2287. lookup.domain = CACHE;
  2288. } else {
  2289. if (this->cmNamedCurly.find(next)) {
  2290. errorstr = "Syntax $" +
  2291. std::string(next, this->cmNamedCurly.end()) +
  2292. "{} is not supported. Only ${}, $ENV{}, "
  2293. "and $CACHE{} are allowed.";
  2294. mtype = MessageType::FATAL_ERROR;
  2295. error = true;
  2296. }
  2297. }
  2298. if (start) {
  2299. result.append(last, in - last);
  2300. last = start;
  2301. in = start - 1;
  2302. lookup.loc = result.size();
  2303. openstack.push_back(lookup);
  2304. }
  2305. break;
  2306. }
  2307. CM_FALLTHROUGH;
  2308. case '\\':
  2309. if (!noEscapes) {
  2310. const char* next = in + 1;
  2311. char nextc = *next;
  2312. if (nextc == 't') {
  2313. result.append(last, in - last);
  2314. result.push_back('\t');
  2315. last = next + 1;
  2316. } else if (nextc == 'n') {
  2317. result.append(last, in - last);
  2318. result.push_back('\n');
  2319. last = next + 1;
  2320. } else if (nextc == 'r') {
  2321. result.append(last, in - last);
  2322. result.push_back('\r');
  2323. last = next + 1;
  2324. } else if (nextc == ';' && openstack.empty()) {
  2325. // Handled in ExpandListArgument; pass the backslash literally.
  2326. } else if (isalnum(nextc) || nextc == '\0') {
  2327. errorstr += "Invalid character escape '\\";
  2328. if (nextc) {
  2329. errorstr += nextc;
  2330. errorstr += "'.";
  2331. } else {
  2332. errorstr += "' (at end of input).";
  2333. }
  2334. error = true;
  2335. } else {
  2336. // Take what we've found so far, skipping the escape character.
  2337. result.append(last, in - last);
  2338. // Start tracking from the next character.
  2339. last = in + 1;
  2340. }
  2341. // Skip the next character since it was escaped, but don't read past
  2342. // the end of the string.
  2343. if (*last) {
  2344. ++in;
  2345. }
  2346. }
  2347. break;
  2348. case '\n':
  2349. // Onto the next line.
  2350. ++line;
  2351. break;
  2352. case '\0':
  2353. done = true;
  2354. break;
  2355. case '@':
  2356. if (replaceAt) {
  2357. const char* nextAt = strchr(in + 1, '@');
  2358. if (nextAt && nextAt != in + 1 &&
  2359. nextAt ==
  2360. in + 1 +
  2361. std::strspn(in + 1,
  2362. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2363. "abcdefghijklmnopqrstuvwxyz"
  2364. "0123456789/_.+-")) {
  2365. std::string variable(in + 1, nextAt - in - 1);
  2366. std::string varresult;
  2367. if (filename && variable == lineVar) {
  2368. varresult = std::to_string(line);
  2369. } else {
  2370. cmValue def = this->GetDefinition(variable);
  2371. if (def) {
  2372. varresult = *def;
  2373. } else {
  2374. this->MaybeWarnUninitialized(variable, filename);
  2375. }
  2376. }
  2377. if (escapeQuotes) {
  2378. varresult = cmEscapeQuotes(varresult);
  2379. }
  2380. // Skip over the variable.
  2381. result.append(last, in - last);
  2382. result.append(varresult);
  2383. in = nextAt;
  2384. last = in + 1;
  2385. break;
  2386. }
  2387. }
  2388. // Failed to find a valid @ expansion; treat it as literal.
  2389. CM_FALLTHROUGH;
  2390. default: {
  2391. if (!openstack.empty() &&
  2392. !(isalnum(inc) || inc == '_' || inc == '/' || inc == '.' ||
  2393. inc == '+' || inc == '-')) {
  2394. errorstr += "Invalid character ('";
  2395. errorstr += inc;
  2396. result.append(last, in - last);
  2397. errorstr += cmStrCat("') in a variable name: '",
  2398. result.substr(openstack.back().loc), '\'');
  2399. mtype = MessageType::FATAL_ERROR;
  2400. error = true;
  2401. }
  2402. break;
  2403. }
  2404. }
  2405. // Look at the next character.
  2406. } while (!error && !done && *++in);
  2407. // Check for open variable references yet.
  2408. if (!error && !openstack.empty()) {
  2409. errorstr += "There is an unterminated variable reference.";
  2410. error = true;
  2411. }
  2412. if (error) {
  2413. std::string e = "Syntax error in cmake code ";
  2414. if (filename) {
  2415. // This filename and line number may be more specific than the
  2416. // command context because one command invocation can have
  2417. // arguments on multiple lines.
  2418. e += cmStrCat("at\n ", filename, ':', line, '\n');
  2419. }
  2420. errorstr = cmStrCat(e, "when parsing string\n ", source, '\n', errorstr);
  2421. mtype = MessageType::FATAL_ERROR;
  2422. } else {
  2423. // Append the rest of the unchanged part of the string.
  2424. result.append(last);
  2425. source = result;
  2426. }
  2427. return mtype;
  2428. }
  2429. void cmMakefile::RemoveVariablesInString(std::string& source,
  2430. bool atOnly) const
  2431. {
  2432. if (!atOnly) {
  2433. cmsys::RegularExpression var("(\\${[A-Za-z_0-9]*})");
  2434. while (var.find(source)) {
  2435. source.erase(var.start(), var.end() - var.start());
  2436. }
  2437. }
  2438. if (!atOnly) {
  2439. cmsys::RegularExpression varb("(\\$ENV{[A-Za-z_0-9]*})");
  2440. while (varb.find(source)) {
  2441. source.erase(varb.start(), varb.end() - varb.start());
  2442. }
  2443. }
  2444. cmsys::RegularExpression var2("(@[A-Za-z_0-9]*@)");
  2445. while (var2.find(source)) {
  2446. source.erase(var2.start(), var2.end() - var2.start());
  2447. }
  2448. }
  2449. void cmMakefile::InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault)
  2450. {
  2451. if (this->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  2452. return;
  2453. }
  2454. std::string initConfigs;
  2455. if (this->GetCMakeInstance()->GetIsInTryCompile() ||
  2456. !cmSystemTools::GetEnv("CMAKE_CONFIGURATION_TYPES", initConfigs)) {
  2457. initConfigs = genDefault;
  2458. }
  2459. this->AddCacheDefinition(
  2460. "CMAKE_CONFIGURATION_TYPES", initConfigs,
  2461. "Semicolon separated list of supported configuration types, "
  2462. "only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
  2463. "anything else will be ignored.",
  2464. cmStateEnums::STRING);
  2465. }
  2466. std::string cmMakefile::GetDefaultConfiguration() const
  2467. {
  2468. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2469. return std::string{};
  2470. }
  2471. return this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2472. }
  2473. std::vector<std::string> cmMakefile::GetGeneratorConfigs(
  2474. GeneratorConfigQuery mode) const
  2475. {
  2476. cmList configs;
  2477. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2478. configs.assign(this->GetDefinition("CMAKE_CONFIGURATION_TYPES"));
  2479. } else if (mode != cmMakefile::OnlyMultiConfig) {
  2480. const std::string& buildType = this->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2481. if (!buildType.empty()) {
  2482. configs.emplace_back(buildType);
  2483. }
  2484. }
  2485. if (mode == cmMakefile::IncludeEmptyConfig && configs.empty()) {
  2486. configs.emplace_back();
  2487. }
  2488. return std::move(configs.data());
  2489. }
  2490. bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
  2491. cmExecutionStatus& status)
  2492. {
  2493. // if there are no blockers get out of here
  2494. if (this->FunctionBlockers.empty()) {
  2495. return false;
  2496. }
  2497. return this->FunctionBlockers.top()->IsFunctionBlocked(lff, status);
  2498. }
  2499. void cmMakefile::PushFunctionBlockerBarrier()
  2500. {
  2501. this->FunctionBlockerBarriers.push_back(this->FunctionBlockers.size());
  2502. }
  2503. void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
  2504. {
  2505. // Remove any extra entries pushed on the barrier.
  2506. FunctionBlockersType::size_type barrier =
  2507. this->FunctionBlockerBarriers.back();
  2508. while (this->FunctionBlockers.size() > barrier) {
  2509. std::unique_ptr<cmFunctionBlocker> fb(
  2510. std::move(this->FunctionBlockers.top()));
  2511. this->FunctionBlockers.pop();
  2512. if (reportError) {
  2513. // Report the context in which the unclosed block was opened.
  2514. cmListFileContext const& lfc = fb->GetStartingContext();
  2515. std::ostringstream e;
  2516. /* clang-format off */
  2517. e << "A logical block opening on the line\n"
  2518. " " << lfc << "\n"
  2519. "is not closed.";
  2520. /* clang-format on */
  2521. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2522. reportError = false;
  2523. }
  2524. }
  2525. // Remove the barrier.
  2526. this->FunctionBlockerBarriers.pop_back();
  2527. }
  2528. void cmMakefile::PushLoopBlock()
  2529. {
  2530. assert(!this->LoopBlockCounter.empty());
  2531. this->LoopBlockCounter.top()++;
  2532. }
  2533. void cmMakefile::PopLoopBlock()
  2534. {
  2535. assert(!this->LoopBlockCounter.empty());
  2536. assert(this->LoopBlockCounter.top() > 0);
  2537. this->LoopBlockCounter.top()--;
  2538. }
  2539. void cmMakefile::PushLoopBlockBarrier()
  2540. {
  2541. this->LoopBlockCounter.push(0);
  2542. }
  2543. void cmMakefile::PopLoopBlockBarrier()
  2544. {
  2545. assert(!this->LoopBlockCounter.empty());
  2546. assert(this->LoopBlockCounter.top() == 0);
  2547. this->LoopBlockCounter.pop();
  2548. }
  2549. bool cmMakefile::IsLoopBlock() const
  2550. {
  2551. assert(!this->LoopBlockCounter.empty());
  2552. return !this->LoopBlockCounter.empty() && this->LoopBlockCounter.top() > 0;
  2553. }
  2554. bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  2555. std::vector<std::string>& outArgs) const
  2556. {
  2557. std::string const& filename = this->GetBacktrace().Top().FilePath;
  2558. std::string value;
  2559. outArgs.reserve(inArgs.size());
  2560. for (cmListFileArgument const& i : inArgs) {
  2561. // No expansion in a bracket argument.
  2562. if (i.Delim == cmListFileArgument::Bracket) {
  2563. outArgs.push_back(i.Value);
  2564. continue;
  2565. }
  2566. // Expand the variables in the argument.
  2567. value = i.Value;
  2568. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  2569. i.Line, false, false);
  2570. // If the argument is quoted, it should be one argument.
  2571. // Otherwise, it may be a list of arguments.
  2572. if (i.Delim == cmListFileArgument::Quoted) {
  2573. outArgs.push_back(value);
  2574. } else {
  2575. cmExpandList(value, outArgs);
  2576. }
  2577. }
  2578. return !cmSystemTools::GetFatalErrorOccurred();
  2579. }
  2580. bool cmMakefile::ExpandArguments(
  2581. std::vector<cmListFileArgument> const& inArgs,
  2582. std::vector<cmExpandedCommandArgument>& outArgs) const
  2583. {
  2584. std::string const& filename = this->GetBacktrace().Top().FilePath;
  2585. std::string value;
  2586. outArgs.reserve(inArgs.size());
  2587. for (cmListFileArgument const& i : inArgs) {
  2588. // No expansion in a bracket argument.
  2589. if (i.Delim == cmListFileArgument::Bracket) {
  2590. outArgs.emplace_back(i.Value, true);
  2591. continue;
  2592. }
  2593. // Expand the variables in the argument.
  2594. value = i.Value;
  2595. this->ExpandVariablesInString(value, false, false, false, filename.c_str(),
  2596. i.Line, false, false);
  2597. // If the argument is quoted, it should be one argument.
  2598. // Otherwise, it may be a list of arguments.
  2599. if (i.Delim == cmListFileArgument::Quoted) {
  2600. outArgs.emplace_back(value, true);
  2601. } else {
  2602. cmList stringArgs{ value };
  2603. for (std::string const& stringArg : stringArgs) {
  2604. outArgs.emplace_back(stringArg, false);
  2605. }
  2606. }
  2607. }
  2608. return !cmSystemTools::GetFatalErrorOccurred();
  2609. }
  2610. void cmMakefile::AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb)
  2611. {
  2612. if (!this->ExecutionStatusStack.empty()) {
  2613. // Record the context in which the blocker is created.
  2614. fb->SetStartingContext(this->Backtrace.Top());
  2615. }
  2616. this->FunctionBlockers.push(std::move(fb));
  2617. }
  2618. std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker()
  2619. {
  2620. assert(!this->FunctionBlockers.empty());
  2621. assert(this->FunctionBlockerBarriers.empty() ||
  2622. this->FunctionBlockers.size() > this->FunctionBlockerBarriers.back());
  2623. auto b = std::move(this->FunctionBlockers.top());
  2624. this->FunctionBlockers.pop();
  2625. return b;
  2626. }
  2627. std::string const& cmMakefile::GetHomeDirectory() const
  2628. {
  2629. return this->GetCMakeInstance()->GetHomeDirectory();
  2630. }
  2631. std::string const& cmMakefile::GetHomeOutputDirectory() const
  2632. {
  2633. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2634. }
  2635. void cmMakefile::SetScriptModeFile(std::string const& scriptfile)
  2636. {
  2637. this->AddDefinition("CMAKE_SCRIPT_MODE_FILE", scriptfile);
  2638. }
  2639. void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
  2640. {
  2641. this->AddDefinition("CMAKE_ARGC", std::to_string(args.size()));
  2642. for (auto i = 0u; i < args.size(); ++i) {
  2643. this->AddDefinition(cmStrCat("CMAKE_ARGV", i), args[i]);
  2644. }
  2645. }
  2646. cmSourceFile* cmMakefile::GetSource(const std::string& sourceName,
  2647. cmSourceFileLocationKind kind) const
  2648. {
  2649. // First check "Known" paths (avoids the creation of cmSourceFileLocation)
  2650. if (kind == cmSourceFileLocationKind::Known) {
  2651. auto sfsi = this->KnownFileSearchIndex.find(sourceName);
  2652. if (sfsi != this->KnownFileSearchIndex.end()) {
  2653. return sfsi->second;
  2654. }
  2655. }
  2656. cmSourceFileLocation sfl(this, sourceName, kind);
  2657. auto name = this->GetCMakeInstance()->StripExtension(sfl.GetName());
  2658. #if defined(_WIN32) || defined(__APPLE__)
  2659. name = cmSystemTools::LowerCase(name);
  2660. #endif
  2661. auto sfsi = this->SourceFileSearchIndex.find(name);
  2662. if (sfsi != this->SourceFileSearchIndex.end()) {
  2663. for (auto* sf : sfsi->second) {
  2664. if (sf->Matches(sfl)) {
  2665. return sf;
  2666. }
  2667. }
  2668. }
  2669. return nullptr;
  2670. }
  2671. cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
  2672. bool generated,
  2673. cmSourceFileLocationKind kind)
  2674. {
  2675. auto sf = cm::make_unique<cmSourceFile>(this, sourceName, generated, kind);
  2676. auto name =
  2677. this->GetCMakeInstance()->StripExtension(sf->GetLocation().GetName());
  2678. #if defined(_WIN32) || defined(__APPLE__)
  2679. name = cmSystemTools::LowerCase(name);
  2680. #endif
  2681. this->SourceFileSearchIndex[name].push_back(sf.get());
  2682. // for "Known" paths add direct lookup (used for faster lookup in GetSource)
  2683. if (kind == cmSourceFileLocationKind::Known) {
  2684. this->KnownFileSearchIndex[sourceName] = sf.get();
  2685. }
  2686. this->SourceFiles.push_back(std::move(sf));
  2687. return this->SourceFiles.back().get();
  2688. }
  2689. cmSourceFile* cmMakefile::GetOrCreateSource(const std::string& sourceName,
  2690. bool generated,
  2691. cmSourceFileLocationKind kind)
  2692. {
  2693. if (cmSourceFile* esf = this->GetSource(sourceName, kind)) {
  2694. return esf;
  2695. }
  2696. return this->CreateSource(sourceName, generated, kind);
  2697. }
  2698. cmSourceFile* cmMakefile::GetOrCreateGeneratedSource(
  2699. const std::string& sourceName)
  2700. {
  2701. cmSourceFile* sf =
  2702. this->GetOrCreateSource(sourceName, true, cmSourceFileLocationKind::Known);
  2703. sf->MarkAsGenerated(); // In case we did not create the source file.
  2704. return sf;
  2705. }
  2706. void cmMakefile::CreateGeneratedOutputs(
  2707. const std::vector<std::string>& outputs)
  2708. {
  2709. for (std::string const& o : outputs) {
  2710. if (cmGeneratorExpression::Find(o) == std::string::npos) {
  2711. this->GetOrCreateGeneratedSource(o);
  2712. }
  2713. }
  2714. }
  2715. void cmMakefile::AddTargetObject(std::string const& tgtName,
  2716. std::string const& objFile)
  2717. {
  2718. cmSourceFile* sf =
  2719. this->GetOrCreateSource(objFile, true, cmSourceFileLocationKind::Known);
  2720. sf->SetObjectLibrary(tgtName);
  2721. sf->SetProperty("EXTERNAL_OBJECT", "1");
  2722. // TODO: Compute a language for this object based on the associated source
  2723. // file that compiles to it. Needs a policy as it likely affects link
  2724. // language selection if done unconditionally.
  2725. #if !defined(CMAKE_BOOTSTRAP)
  2726. this->SourceGroups[this->ObjectLibrariesSourceGroupIndex].AddGroupFile(
  2727. sf->ResolveFullPath());
  2728. #endif
  2729. }
  2730. void cmMakefile::EnableLanguage(std::vector<std::string> const& languages,
  2731. bool optional)
  2732. {
  2733. if (this->DeferRunning) {
  2734. this->IssueMessage(
  2735. MessageType::FATAL_ERROR,
  2736. "Languages may not be enabled during deferred execution.");
  2737. return;
  2738. }
  2739. if (const char* def = this->GetGlobalGenerator()->GetCMakeCFGIntDir()) {
  2740. this->AddDefinition("CMAKE_CFG_INTDIR", def);
  2741. }
  2742. std::vector<std::string> unique_languages;
  2743. {
  2744. std::vector<std::string> duplicate_languages;
  2745. for (std::string const& language : languages) {
  2746. if (!cm::contains(unique_languages, language)) {
  2747. unique_languages.push_back(language);
  2748. } else if (!cm::contains(duplicate_languages, language)) {
  2749. duplicate_languages.push_back(language);
  2750. }
  2751. }
  2752. if (!duplicate_languages.empty()) {
  2753. auto quantity = duplicate_languages.size() == 1 ? " has"_s : "s have"_s;
  2754. this->IssueMessage(
  2755. MessageType::AUTHOR_WARNING,
  2756. cmStrCat("Languages to be enabled may not be specified more "
  2757. "than once at the same time. The following language",
  2758. quantity, " been specified multiple times: ",
  2759. cmJoin(duplicate_languages, ", ")));
  2760. }
  2761. }
  2762. // If RC is explicitly listed we need to do it after other languages.
  2763. // On some platforms we enable RC implicitly while enabling others.
  2764. // Do not let that look like recursive enable_language(RC).
  2765. std::vector<std::string> languages_without_RC;
  2766. std::vector<std::string> languages_for_RC;
  2767. languages_without_RC.reserve(unique_languages.size());
  2768. for (std::string const& language : unique_languages) {
  2769. if (language == "RC"_s) {
  2770. languages_for_RC.push_back(language);
  2771. } else {
  2772. languages_without_RC.push_back(language);
  2773. }
  2774. }
  2775. if (!languages_without_RC.empty()) {
  2776. this->GetGlobalGenerator()->EnableLanguage(languages_without_RC, this,
  2777. optional);
  2778. }
  2779. if (!languages_for_RC.empty()) {
  2780. this->GetGlobalGenerator()->EnableLanguage(languages_for_RC, this,
  2781. optional);
  2782. }
  2783. }
  2784. int cmMakefile::TryCompile(const std::string& srcdir,
  2785. const std::string& bindir,
  2786. const std::string& projectName,
  2787. const std::string& targetName, bool fast, int jobs,
  2788. const std::vector<std::string>* cmakeArgs,
  2789. std::string& output)
  2790. {
  2791. this->IsSourceFileTryCompile = fast;
  2792. // does the binary directory exist ? If not create it...
  2793. if (!cmSystemTools::FileIsDirectory(bindir)) {
  2794. cmSystemTools::MakeDirectory(bindir);
  2795. }
  2796. // change to the tests directory and run cmake
  2797. // use the cmake object instead of calling cmake
  2798. cmWorkingDirectory workdir(bindir);
  2799. if (workdir.Failed()) {
  2800. this->IssueMessage(MessageType::FATAL_ERROR, workdir.GetError());
  2801. cmSystemTools::SetFatalErrorOccurred();
  2802. this->IsSourceFileTryCompile = false;
  2803. return 1;
  2804. }
  2805. // make sure the same generator is used
  2806. // use this program as the cmake to be run, it should not
  2807. // be run that way but the cmake object requires a valid path
  2808. cmake cm(cmake::RoleProject, cmState::Project,
  2809. cmState::ProjectKind::TryCompile);
  2810. auto gg = cm.CreateGlobalGenerator(this->GetGlobalGenerator()->GetName());
  2811. if (!gg) {
  2812. this->IssueMessage(MessageType::INTERNAL_ERROR,
  2813. "Global generator '" +
  2814. this->GetGlobalGenerator()->GetName() +
  2815. "' could not be created.");
  2816. cmSystemTools::SetFatalErrorOccurred();
  2817. this->IsSourceFileTryCompile = false;
  2818. return 1;
  2819. }
  2820. gg->RecursionDepth = this->RecursionDepth;
  2821. cm.SetGlobalGenerator(std::move(gg));
  2822. // copy trace state
  2823. cm.SetTraceRedirect(this->GetCMakeInstance());
  2824. // do a configure
  2825. cm.SetHomeDirectory(srcdir);
  2826. cm.SetHomeOutputDirectory(bindir);
  2827. cm.SetGeneratorInstance(this->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE"));
  2828. cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
  2829. cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
  2830. cm.LoadCache();
  2831. if (!cm.GetGlobalGenerator()->IsMultiConfig()) {
  2832. if (cmValue config =
  2833. this->GetDefinition("CMAKE_TRY_COMPILE_CONFIGURATION")) {
  2834. // Tell the single-configuration generator which one to use.
  2835. // Add this before the user-provided CMake arguments in case
  2836. // one of the arguments is -DCMAKE_BUILD_TYPE=...
  2837. cm.AddCacheEntry("CMAKE_BUILD_TYPE", config, "Build configuration",
  2838. cmStateEnums::STRING);
  2839. }
  2840. }
  2841. cmValue recursionDepth =
  2842. this->GetDefinition("CMAKE_MAXIMUM_RECURSION_DEPTH");
  2843. if (recursionDepth) {
  2844. cm.AddCacheEntry("CMAKE_MAXIMUM_RECURSION_DEPTH", recursionDepth,
  2845. "Maximum recursion depth", cmStateEnums::STRING);
  2846. }
  2847. // if cmake args were provided then pass them in
  2848. if (cmakeArgs) {
  2849. // FIXME: Workaround to ignore unused CLI variables in try-compile.
  2850. //
  2851. // Ideally we should use SetArgs for options like --no-warn-unused-cli.
  2852. // However, there is a subtle problem when certain arguments are passed to
  2853. // a macro wrapping around try_compile or try_run that does not escape
  2854. // semicolons in its parameters but just passes ${ARGV} or ${ARGN}. In
  2855. // this case a list argument like "-DVAR=a;b" gets split into multiple
  2856. // cmake arguments "-DVAR=a" and "b". Currently SetCacheArgs ignores
  2857. // argument "b" and uses just "-DVAR=a", leading to a subtle bug in that
  2858. // the try_compile or try_run does not get the proper value of VAR. If we
  2859. // call SetArgs here then it would treat "b" as the source directory and
  2860. // cause an error such as "The source directory .../CMakeFiles/CMakeTmp/b
  2861. // does not exist", thus breaking the try_compile or try_run completely.
  2862. //
  2863. // Strictly speaking the bug is in the wrapper macro because the CMake
  2864. // language has always flattened nested lists and the macro should escape
  2865. // the semicolons in its arguments before forwarding them. However, this
  2866. // bug is so subtle that projects typically work anyway, usually because
  2867. // the value VAR=a is sufficient for the try_compile or try_run to get the
  2868. // correct result. Calling SetArgs here would break such projects that
  2869. // previously built. Instead we work around the issue by never reporting
  2870. // unused arguments and ignoring options such as --no-warn-unused-cli.
  2871. cm.SetWarnUnusedCli(false);
  2872. // cm.SetArgs(*cmakeArgs, true);
  2873. cm.SetCacheArgs(*cmakeArgs);
  2874. }
  2875. // to save time we pass the EnableLanguage info directly
  2876. cm.GetGlobalGenerator()->EnableLanguagesFromGenerator(
  2877. this->GetGlobalGenerator(), this);
  2878. if (this->IsOn("CMAKE_SUPPRESS_DEVELOPER_WARNINGS")) {
  2879. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "TRUE", "",
  2880. cmStateEnums::INTERNAL);
  2881. } else {
  2882. cm.AddCacheEntry("CMAKE_SUPPRESS_DEVELOPER_WARNINGS", "FALSE", "",
  2883. cmStateEnums::INTERNAL);
  2884. }
  2885. if (cm.Configure() != 0) {
  2886. this->IssueMessage(MessageType::FATAL_ERROR,
  2887. "Failed to configure test project build system.");
  2888. cmSystemTools::SetFatalErrorOccurred();
  2889. this->IsSourceFileTryCompile = false;
  2890. return 1;
  2891. }
  2892. if (cm.Generate() != 0) {
  2893. this->IssueMessage(MessageType::FATAL_ERROR,
  2894. "Failed to generate test project build system.");
  2895. cmSystemTools::SetFatalErrorOccurred();
  2896. this->IsSourceFileTryCompile = false;
  2897. return 1;
  2898. }
  2899. // finally call the generator to actually build the resulting project
  2900. int ret = this->GetGlobalGenerator()->TryCompile(
  2901. jobs, srcdir, bindir, projectName, targetName, fast, output, this);
  2902. this->IsSourceFileTryCompile = false;
  2903. return ret;
  2904. }
  2905. bool cmMakefile::GetIsSourceFileTryCompile() const
  2906. {
  2907. return this->IsSourceFileTryCompile;
  2908. }
  2909. cmake* cmMakefile::GetCMakeInstance() const
  2910. {
  2911. return this->GlobalGenerator->GetCMakeInstance();
  2912. }
  2913. cmMessenger* cmMakefile::GetMessenger() const
  2914. {
  2915. return this->GetCMakeInstance()->GetMessenger();
  2916. }
  2917. cmGlobalGenerator* cmMakefile::GetGlobalGenerator() const
  2918. {
  2919. return this->GlobalGenerator;
  2920. }
  2921. #ifndef CMAKE_BOOTSTRAP
  2922. cmVariableWatch* cmMakefile::GetVariableWatch() const
  2923. {
  2924. if (this->GetCMakeInstance() &&
  2925. this->GetCMakeInstance()->GetVariableWatch()) {
  2926. return this->GetCMakeInstance()->GetVariableWatch();
  2927. }
  2928. return nullptr;
  2929. }
  2930. #endif
  2931. cmState* cmMakefile::GetState() const
  2932. {
  2933. return this->GetCMakeInstance()->GetState();
  2934. }
  2935. void cmMakefile::DisplayStatus(const std::string& message, float s) const
  2936. {
  2937. cmake* cm = this->GetCMakeInstance();
  2938. if (cm->GetWorkingMode() == cmake::FIND_PACKAGE_MODE) {
  2939. // don't output any STATUS message in FIND_PACKAGE_MODE, since they will
  2940. // directly be fed to the compiler, which will be confused.
  2941. return;
  2942. }
  2943. cm->UpdateProgress(message, s);
  2944. #ifdef CMake_ENABLE_DEBUGGER
  2945. if (cm->GetDebugAdapter()) {
  2946. cm->GetDebugAdapter()->OnMessageOutput(MessageType::MESSAGE, message);
  2947. }
  2948. #endif
  2949. }
  2950. std::string cmMakefile::GetModulesFile(cm::string_view filename, bool& system,
  2951. bool debug,
  2952. std::string& debugBuffer) const
  2953. {
  2954. std::string result;
  2955. std::string moduleInCMakeRoot;
  2956. std::string moduleInCMakeModulePath;
  2957. // Always search in CMAKE_MODULE_PATH:
  2958. cmValue cmakeModulePath = this->GetDefinition("CMAKE_MODULE_PATH");
  2959. if (cmakeModulePath) {
  2960. cmList modulePath{ *cmakeModulePath };
  2961. // Look through the possible module directories.
  2962. for (std::string itempl : modulePath) {
  2963. cmSystemTools::ConvertToUnixSlashes(itempl);
  2964. itempl += "/";
  2965. itempl += filename;
  2966. if (cmSystemTools::FileExists(itempl)) {
  2967. moduleInCMakeModulePath = itempl;
  2968. break;
  2969. }
  2970. if (debug) {
  2971. debugBuffer = cmStrCat(debugBuffer, " ", itempl, '\n');
  2972. }
  2973. }
  2974. }
  2975. // Always search in the standard modules location.
  2976. moduleInCMakeRoot =
  2977. cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/", filename);
  2978. cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
  2979. if (!cmSystemTools::FileExists(moduleInCMakeRoot)) {
  2980. if (debug) {
  2981. debugBuffer = cmStrCat(debugBuffer, " ", moduleInCMakeRoot, '\n');
  2982. }
  2983. moduleInCMakeRoot.clear();
  2984. }
  2985. // Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
  2986. // from which we are being called is located itself in CMAKE_ROOT, then
  2987. // prefer results from CMAKE_ROOT depending on the policy setting.
  2988. if (!moduleInCMakeModulePath.empty() && !moduleInCMakeRoot.empty()) {
  2989. cmValue currentFile = this->GetDefinition("CMAKE_CURRENT_LIST_FILE");
  2990. std::string mods = cmStrCat(cmSystemTools::GetCMakeRoot(), "/Modules/");
  2991. if (currentFile && cmSystemTools::IsSubDirectory(*currentFile, mods)) {
  2992. system = true;
  2993. result = moduleInCMakeRoot;
  2994. } else {
  2995. system = false;
  2996. result = moduleInCMakeModulePath;
  2997. }
  2998. } else if (!moduleInCMakeModulePath.empty()) {
  2999. system = false;
  3000. result = moduleInCMakeModulePath;
  3001. } else {
  3002. system = true;
  3003. result = moduleInCMakeRoot;
  3004. }
  3005. return result;
  3006. }
  3007. void cmMakefile::ConfigureString(const std::string& input, std::string& output,
  3008. bool atOnly, bool escapeQuotes) const
  3009. {
  3010. // Split input to handle one line at a time.
  3011. std::string::const_iterator lineStart = input.begin();
  3012. while (lineStart != input.end()) {
  3013. // Find the end of this line.
  3014. std::string::const_iterator lineEnd = lineStart;
  3015. while (lineEnd != input.end() && *lineEnd != '\n') {
  3016. ++lineEnd;
  3017. }
  3018. // Copy the line.
  3019. std::string line(lineStart, lineEnd);
  3020. // Skip the newline character.
  3021. bool haveNewline = (lineEnd != input.end());
  3022. if (haveNewline) {
  3023. ++lineEnd;
  3024. }
  3025. // Replace #cmakedefine instances.
  3026. if (this->cmDefineRegex.find(line)) {
  3027. cmValue def = this->GetDefinition(this->cmDefineRegex.match(2));
  3028. if (!def.IsOff()) {
  3029. const std::string indentation = this->cmDefineRegex.match(1);
  3030. cmSystemTools::ReplaceString(line,
  3031. cmStrCat('#', indentation, "cmakedefine"),
  3032. cmStrCat('#', indentation, "define"));
  3033. output += line;
  3034. } else {
  3035. output += "/* #undef ";
  3036. output += this->cmDefineRegex.match(2);
  3037. output += " */";
  3038. }
  3039. } else if (this->cmDefine01Regex.find(line)) {
  3040. const std::string indentation = this->cmDefine01Regex.match(1);
  3041. cmValue def = this->GetDefinition(this->cmDefine01Regex.match(2));
  3042. cmSystemTools::ReplaceString(line,
  3043. cmStrCat('#', indentation, "cmakedefine01"),
  3044. cmStrCat('#', indentation, "define"));
  3045. output += line;
  3046. if (!def.IsOff()) {
  3047. output += " 1";
  3048. } else {
  3049. output += " 0";
  3050. }
  3051. } else {
  3052. output += line;
  3053. }
  3054. if (haveNewline) {
  3055. output += '\n';
  3056. }
  3057. // Move to the next line.
  3058. lineStart = lineEnd;
  3059. }
  3060. // Perform variable replacements.
  3061. const char* filename = nullptr;
  3062. long lineNumber = -1;
  3063. if (!this->Backtrace.Empty()) {
  3064. const auto& currentTrace = this->Backtrace.Top();
  3065. filename = currentTrace.FilePath.c_str();
  3066. lineNumber = currentTrace.Line;
  3067. }
  3068. this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, filename,
  3069. lineNumber, true, true);
  3070. }
  3071. int cmMakefile::ConfigureFile(const std::string& infile,
  3072. const std::string& outfile, bool copyonly,
  3073. bool atOnly, bool escapeQuotes,
  3074. mode_t permissions, cmNewLineStyle newLine)
  3075. {
  3076. int res = 1;
  3077. if (!this->CanIWriteThisFile(outfile)) {
  3078. cmSystemTools::Error(cmStrCat("Attempt to write file: ", outfile,
  3079. " into a source directory."));
  3080. return 0;
  3081. }
  3082. if (!cmSystemTools::FileExists(infile)) {
  3083. cmSystemTools::Error(cmStrCat("File ", infile, " does not exist."));
  3084. return 0;
  3085. }
  3086. std::string soutfile = outfile;
  3087. const std::string& sinfile = infile;
  3088. this->AddCMakeDependFile(sinfile);
  3089. cmSystemTools::ConvertToUnixSlashes(soutfile);
  3090. // Re-generate if non-temporary outputs are missing.
  3091. // when we finalize the configuration we will remove all
  3092. // output files that now don't exist.
  3093. this->AddCMakeOutputFile(soutfile);
  3094. if (permissions == 0) {
  3095. cmSystemTools::GetPermissions(sinfile, permissions);
  3096. }
  3097. std::string::size_type pos = soutfile.rfind('/');
  3098. if (pos != std::string::npos) {
  3099. std::string path = soutfile.substr(0, pos);
  3100. cmSystemTools::MakeDirectory(path);
  3101. }
  3102. if (copyonly) {
  3103. const auto copy_status =
  3104. cmSystemTools::CopyFileIfDifferent(sinfile, soutfile);
  3105. if (!copy_status) {
  3106. this->IssueMessage(
  3107. MessageType::FATAL_ERROR,
  3108. cmStrCat("Fail to copy ",
  3109. copy_status.Path == cmsys::SystemTools::CopyStatus::SourcePath
  3110. ? "source"
  3111. : "destination",
  3112. "file: ", copy_status.GetString()));
  3113. res = 0;
  3114. } else {
  3115. const auto status = cmSystemTools::SetPermissions(soutfile, permissions);
  3116. if (!status) {
  3117. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3118. res = 0;
  3119. }
  3120. }
  3121. return res;
  3122. }
  3123. std::string newLineCharacters;
  3124. std::ios::openmode omode = std::ios::out | std::ios::trunc;
  3125. if (newLine.IsValid()) {
  3126. newLineCharacters = newLine.GetCharacters();
  3127. omode |= std::ios::binary;
  3128. } else {
  3129. newLineCharacters = "\n";
  3130. }
  3131. std::string tempOutputFile = cmStrCat(soutfile, ".tmp");
  3132. cmsys::ofstream fout(tempOutputFile.c_str(), omode);
  3133. if (!fout) {
  3134. cmSystemTools::Error("Could not open file for write in copy operation " +
  3135. tempOutputFile);
  3136. cmSystemTools::ReportLastSystemError("");
  3137. return 0;
  3138. }
  3139. cmsys::ifstream fin(sinfile.c_str());
  3140. if (!fin) {
  3141. cmSystemTools::Error("Could not open file for read in copy operation " +
  3142. sinfile);
  3143. return 0;
  3144. }
  3145. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  3146. if (bom != cmsys::FStream::BOM_None && bom != cmsys::FStream::BOM_UTF8) {
  3147. this->IssueMessage(
  3148. MessageType::FATAL_ERROR,
  3149. cmStrCat("File starts with a Byte-Order-Mark that is not UTF-8:\n ",
  3150. sinfile));
  3151. return 0;
  3152. }
  3153. // rewind to copy BOM to output file
  3154. fin.seekg(0);
  3155. // now copy input to output and expand variables in the
  3156. // input file at the same time
  3157. std::string inLine;
  3158. std::string outLine;
  3159. while (cmSystemTools::GetLineFromStream(fin, inLine)) {
  3160. outLine.clear();
  3161. this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
  3162. fout << outLine << newLineCharacters;
  3163. }
  3164. // close the files before attempting to copy
  3165. fin.close();
  3166. fout.close();
  3167. auto status = cmSystemTools::MoveFileIfDifferent(tempOutputFile, soutfile);
  3168. if (!status) {
  3169. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3170. res = 0;
  3171. } else {
  3172. status = cmSystemTools::SetPermissions(soutfile, permissions);
  3173. if (!status) {
  3174. this->IssueMessage(MessageType::FATAL_ERROR, status.GetString());
  3175. res = 0;
  3176. }
  3177. }
  3178. return res;
  3179. }
  3180. void cmMakefile::SetProperty(const std::string& prop, cmValue value)
  3181. {
  3182. this->StateSnapshot.GetDirectory().SetProperty(prop, value, this->Backtrace);
  3183. }
  3184. void cmMakefile::AppendProperty(const std::string& prop,
  3185. const std::string& value, bool asString)
  3186. {
  3187. this->StateSnapshot.GetDirectory().AppendProperty(prop, value, asString,
  3188. this->Backtrace);
  3189. }
  3190. cmValue cmMakefile::GetProperty(const std::string& prop) const
  3191. {
  3192. // Check for computed properties.
  3193. static std::string output;
  3194. if (prop == "TESTS"_s) {
  3195. std::vector<std::string> keys;
  3196. // get list of keys
  3197. const auto* t = this;
  3198. std::transform(
  3199. t->Tests.begin(), t->Tests.end(), std::back_inserter(keys),
  3200. [](decltype(t->Tests)::value_type const& pair) { return pair.first; });
  3201. output = cmList::to_string(keys);
  3202. return cmValue(output);
  3203. }
  3204. return this->StateSnapshot.GetDirectory().GetProperty(prop);
  3205. }
  3206. cmValue cmMakefile::GetProperty(const std::string& prop, bool chain) const
  3207. {
  3208. return this->StateSnapshot.GetDirectory().GetProperty(prop, chain);
  3209. }
  3210. bool cmMakefile::GetPropertyAsBool(const std::string& prop) const
  3211. {
  3212. return this->GetProperty(prop).IsOn();
  3213. }
  3214. std::vector<std::string> cmMakefile::GetPropertyKeys() const
  3215. {
  3216. return this->StateSnapshot.GetDirectory().GetPropertyKeys();
  3217. }
  3218. cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
  3219. {
  3220. auto i = this->Targets.find(name);
  3221. if (i != this->Targets.end()) {
  3222. return &i->second;
  3223. }
  3224. return nullptr;
  3225. }
  3226. cmTest* cmMakefile::CreateTest(const std::string& testName)
  3227. {
  3228. cmTest* test = this->GetTest(testName);
  3229. if (test) {
  3230. return test;
  3231. }
  3232. auto newTest = cm::make_unique<cmTest>(this);
  3233. test = newTest.get();
  3234. newTest->SetName(testName);
  3235. this->Tests[testName] = std::move(newTest);
  3236. return test;
  3237. }
  3238. cmTest* cmMakefile::GetTest(const std::string& testName) const
  3239. {
  3240. auto mi = this->Tests.find(testName);
  3241. if (mi != this->Tests.end()) {
  3242. return mi->second.get();
  3243. }
  3244. return nullptr;
  3245. }
  3246. void cmMakefile::GetTests(const std::string& config,
  3247. std::vector<cmTest*>& tests) const
  3248. {
  3249. for (const auto& generator : this->GetTestGenerators()) {
  3250. if (generator->TestsForConfig(config)) {
  3251. tests.push_back(generator->GetTest());
  3252. }
  3253. }
  3254. }
  3255. void cmMakefile::AddCMakeDependFilesFromUser()
  3256. {
  3257. cmList deps;
  3258. if (cmValue deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
  3259. deps.assign(*deps_str);
  3260. }
  3261. for (auto const& dep : deps) {
  3262. if (cmSystemTools::FileIsFullPath(dep)) {
  3263. this->AddCMakeDependFile(dep);
  3264. } else {
  3265. std::string f = cmStrCat(this->GetCurrentSourceDirectory(), '/', dep);
  3266. this->AddCMakeDependFile(f);
  3267. }
  3268. }
  3269. }
  3270. std::string cmMakefile::FormatListFileStack() const
  3271. {
  3272. std::vector<std::string> listFiles;
  3273. for (auto snp = this->StateSnapshot; snp.IsValid();
  3274. snp = snp.GetCallStackParent()) {
  3275. listFiles.emplace_back(snp.GetExecutionListFile());
  3276. }
  3277. if (listFiles.empty()) {
  3278. return {};
  3279. }
  3280. auto depth = 1;
  3281. std::transform(listFiles.begin(), listFiles.end(), listFiles.begin(),
  3282. [&depth](const std::string& file) {
  3283. return cmStrCat('[', depth++, "]\t", file);
  3284. });
  3285. return cmJoinStrings(cmMakeRange(listFiles.rbegin(), listFiles.rend()),
  3286. "\n "_s, {});
  3287. }
  3288. void cmMakefile::PushScope()
  3289. {
  3290. this->StateSnapshot =
  3291. this->GetState()->CreateVariableScopeSnapshot(this->StateSnapshot);
  3292. this->PushLoopBlockBarrier();
  3293. #if !defined(CMAKE_BOOTSTRAP)
  3294. this->GetGlobalGenerator()->GetFileLockPool().PushFunctionScope();
  3295. #endif
  3296. }
  3297. void cmMakefile::PopScope()
  3298. {
  3299. #if !defined(CMAKE_BOOTSTRAP)
  3300. this->GetGlobalGenerator()->GetFileLockPool().PopFunctionScope();
  3301. #endif
  3302. this->PopLoopBlockBarrier();
  3303. this->PopSnapshot();
  3304. }
  3305. void cmMakefile::RaiseScope(const std::string& var, const char* varDef)
  3306. {
  3307. if (var.empty()) {
  3308. return;
  3309. }
  3310. if (!this->StateSnapshot.RaiseScope(var, varDef)) {
  3311. this->IssueMessage(
  3312. MessageType::AUTHOR_WARNING,
  3313. cmStrCat("Cannot set \"", var, "\": current scope has no parent."));
  3314. return;
  3315. }
  3316. #ifndef CMAKE_BOOTSTRAP
  3317. cmVariableWatch* vv = this->GetVariableWatch();
  3318. if (vv) {
  3319. vv->VariableAccessed(var, cmVariableWatch::VARIABLE_MODIFIED_ACCESS,
  3320. varDef, this);
  3321. }
  3322. #endif
  3323. }
  3324. void cmMakefile::RaiseScope(const std::vector<std::string>& variables)
  3325. {
  3326. for (auto const& varName : variables) {
  3327. if (this->IsNormalDefinitionSet(varName)) {
  3328. this->RaiseScope(varName, this->GetDefinition(varName));
  3329. } else {
  3330. // unset variable in parent scope
  3331. this->RaiseScope(varName, nullptr);
  3332. }
  3333. }
  3334. }
  3335. cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
  3336. cmStateEnums::TargetType type,
  3337. bool global)
  3338. {
  3339. // Create the target.
  3340. std::unique_ptr<cmTarget> target(
  3341. new cmTarget(name, type,
  3342. global ? cmTarget::Visibility::ImportedGlobally
  3343. : cmTarget::Visibility::Imported,
  3344. this, cmTarget::PerConfig::Yes));
  3345. // Add to the set of available imported targets.
  3346. this->ImportedTargets[name] = target.get();
  3347. this->GetGlobalGenerator()->IndexTarget(target.get());
  3348. this->GetStateSnapshot().GetDirectory().AddImportedTargetName(name);
  3349. // Transfer ownership to this cmMakefile object.
  3350. this->ImportedTargetsOwned.push_back(std::move(target));
  3351. return this->ImportedTargetsOwned.back().get();
  3352. }
  3353. cmTarget* cmMakefile::FindTargetToUse(const std::string& name,
  3354. bool excludeAliases) const
  3355. {
  3356. // Look for an imported target. These take priority because they
  3357. // are more local in scope and do not have to be globally unique.
  3358. auto targetName = name;
  3359. if (!excludeAliases) {
  3360. // Look for local alias targets.
  3361. auto alias = this->AliasTargets.find(name);
  3362. if (alias != this->AliasTargets.end()) {
  3363. targetName = alias->second;
  3364. }
  3365. }
  3366. auto imported = this->ImportedTargets.find(targetName);
  3367. if (imported != this->ImportedTargets.end()) {
  3368. return imported->second;
  3369. }
  3370. // Look for a target built in this directory.
  3371. if (cmTarget* t = this->FindLocalNonAliasTarget(name)) {
  3372. return t;
  3373. }
  3374. // Look for a target built in this project.
  3375. return this->GetGlobalGenerator()->FindTarget(name, excludeAliases);
  3376. }
  3377. bool cmMakefile::IsAlias(const std::string& name) const
  3378. {
  3379. if (cm::contains(this->AliasTargets, name)) {
  3380. return true;
  3381. }
  3382. return this->GetGlobalGenerator()->IsAlias(name);
  3383. }
  3384. bool cmMakefile::EnforceUniqueName(std::string const& name, std::string& msg,
  3385. bool isCustom) const
  3386. {
  3387. if (this->IsAlias(name)) {
  3388. msg = cmStrCat("cannot create target \"", name,
  3389. "\" because an alias with the same name already exists.");
  3390. return false;
  3391. }
  3392. if (cmTarget* existing = this->FindTargetToUse(name)) {
  3393. // The name given conflicts with an existing target. Produce an
  3394. // error in a compatible way.
  3395. if (existing->IsImported()) {
  3396. // Imported targets were not supported in previous versions.
  3397. // This is new code, so we can make it an error.
  3398. msg = cmStrCat(
  3399. "cannot create target \"", name,
  3400. "\" because an imported target with the same name already exists.");
  3401. return false;
  3402. }
  3403. // The conflict is with a non-imported target.
  3404. // Allow this if the user has requested support.
  3405. cmake* cm = this->GetCMakeInstance();
  3406. if (isCustom && existing->GetType() == cmStateEnums::UTILITY &&
  3407. this != existing->GetMakefile() &&
  3408. cm->GetState()->GetGlobalPropertyAsBool(
  3409. "ALLOW_DUPLICATE_CUSTOM_TARGETS")) {
  3410. return true;
  3411. }
  3412. // Produce an error that tells the user how to work around the
  3413. // problem.
  3414. std::ostringstream e;
  3415. e << "cannot create target \"" << name
  3416. << "\" because another target with the same name already exists. "
  3417. "The existing target is ";
  3418. switch (existing->GetType()) {
  3419. case cmStateEnums::EXECUTABLE:
  3420. e << "an executable ";
  3421. break;
  3422. case cmStateEnums::STATIC_LIBRARY:
  3423. e << "a static library ";
  3424. break;
  3425. case cmStateEnums::SHARED_LIBRARY:
  3426. e << "a shared library ";
  3427. break;
  3428. case cmStateEnums::MODULE_LIBRARY:
  3429. e << "a module library ";
  3430. break;
  3431. case cmStateEnums::UTILITY:
  3432. e << "a custom target ";
  3433. break;
  3434. case cmStateEnums::INTERFACE_LIBRARY:
  3435. e << "an interface library ";
  3436. break;
  3437. default:
  3438. break;
  3439. }
  3440. e << "created in source directory \""
  3441. << existing->GetMakefile()->GetCurrentSourceDirectory()
  3442. << "\". "
  3443. "See documentation for policy CMP0002 for more details.";
  3444. msg = e.str();
  3445. return false;
  3446. }
  3447. return true;
  3448. }
  3449. bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
  3450. const std::string& binPath) const
  3451. {
  3452. // Make sure the binary directory is unique.
  3453. cmGlobalGenerator* gg = this->GetGlobalGenerator();
  3454. if (gg->BinaryDirectoryIsNew(binPath)) {
  3455. return true;
  3456. }
  3457. this->IssueMessage(MessageType::FATAL_ERROR,
  3458. cmStrCat("The binary directory\n"
  3459. " ",
  3460. binPath,
  3461. "\n"
  3462. "is already used to build a source directory. "
  3463. "It cannot be used to build source directory\n"
  3464. " ",
  3465. srcPath,
  3466. "\n"
  3467. "Specify a unique binary directory name."));
  3468. return false;
  3469. }
  3470. static std::string const matchVariables[] = {
  3471. "CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
  3472. "CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
  3473. "CMAKE_MATCH_8", "CMAKE_MATCH_9"
  3474. };
  3475. static std::string const nMatchesVariable = "CMAKE_MATCH_COUNT";
  3476. void cmMakefile::ClearMatches()
  3477. {
  3478. cmValue nMatchesStr = this->GetDefinition(nMatchesVariable);
  3479. if (!nMatchesStr) {
  3480. return;
  3481. }
  3482. int nMatches = atoi(nMatchesStr->c_str());
  3483. for (int i = 0; i <= nMatches; i++) {
  3484. std::string const& var = matchVariables[i];
  3485. std::string const& s = this->GetSafeDefinition(var);
  3486. if (!s.empty()) {
  3487. this->AddDefinition(var, "");
  3488. this->MarkVariableAsUsed(var);
  3489. }
  3490. }
  3491. this->AddDefinition(nMatchesVariable, "0");
  3492. this->MarkVariableAsUsed(nMatchesVariable);
  3493. }
  3494. void cmMakefile::StoreMatches(cmsys::RegularExpression& re)
  3495. {
  3496. char highest = 0;
  3497. for (int i = 0; i < 10; i++) {
  3498. std::string const& m = re.match(i);
  3499. if (!m.empty()) {
  3500. std::string const& var = matchVariables[i];
  3501. this->AddDefinition(var, m);
  3502. this->MarkVariableAsUsed(var);
  3503. highest = static_cast<char>('0' + i);
  3504. }
  3505. }
  3506. char nMatches[] = { highest, '\0' };
  3507. this->AddDefinition(nMatchesVariable, nMatches);
  3508. this->MarkVariableAsUsed(nMatchesVariable);
  3509. }
  3510. cmStateSnapshot cmMakefile::GetStateSnapshot() const
  3511. {
  3512. return this->StateSnapshot;
  3513. }
  3514. const char* cmMakefile::GetDefineFlagsCMP0059() const
  3515. {
  3516. return this->DefineFlagsOrig.c_str();
  3517. }
  3518. cmPolicies::PolicyStatus cmMakefile::GetPolicyStatus(cmPolicies::PolicyID id,
  3519. bool parent_scope) const
  3520. {
  3521. return this->StateSnapshot.GetPolicy(id, parent_scope);
  3522. }
  3523. bool cmMakefile::PolicyOptionalWarningEnabled(std::string const& var) const
  3524. {
  3525. // Check for an explicit CMAKE_POLICY_WARNING_CMP<NNNN> setting.
  3526. if (cmValue val = this->GetDefinition(var)) {
  3527. return val.IsOn();
  3528. }
  3529. // Enable optional policy warnings with --debug-output, --trace,
  3530. // or --trace-expand.
  3531. cmake* cm = this->GetCMakeInstance();
  3532. return cm->GetDebugOutput() || cm->GetTrace();
  3533. }
  3534. bool cmMakefile::SetPolicy(const char* id, cmPolicies::PolicyStatus status)
  3535. {
  3536. cmPolicies::PolicyID pid;
  3537. if (!cmPolicies::GetPolicyID(id, /* out */ pid)) {
  3538. this->IssueMessage(
  3539. MessageType::FATAL_ERROR,
  3540. cmStrCat("Policy \"", id, "\" is not known to this version of CMake."));
  3541. return false;
  3542. }
  3543. return this->SetPolicy(pid, status);
  3544. }
  3545. bool cmMakefile::SetPolicy(cmPolicies::PolicyID id,
  3546. cmPolicies::PolicyStatus status)
  3547. {
  3548. // A removed policy may be set only to NEW.
  3549. if (cmPolicies::IsRemoved(id) && status != cmPolicies::NEW) {
  3550. std::string msg = cmPolicies::GetRemovedPolicyError(id);
  3551. this->IssueMessage(MessageType::FATAL_ERROR, msg);
  3552. return false;
  3553. }
  3554. // Deprecate old policies.
  3555. if (status == cmPolicies::OLD && id <= cmPolicies::CMP0139 &&
  3556. !(this->GetCMakeInstance()->GetIsInTryCompile() &&
  3557. (
  3558. // Policies set by cmCoreTryCompile::TryCompileCode.
  3559. id == cmPolicies::CMP0065 || id == cmPolicies::CMP0083 ||
  3560. id == cmPolicies::CMP0091 || id == cmPolicies::CMP0104 ||
  3561. id == cmPolicies::CMP0123 || id == cmPolicies::CMP0126 ||
  3562. id == cmPolicies::CMP0128 || id == cmPolicies::CMP0136)) &&
  3563. (!this->IsSet("CMAKE_WARN_DEPRECATED") ||
  3564. this->IsOn("CMAKE_WARN_DEPRECATED"))) {
  3565. this->IssueMessage(MessageType::DEPRECATION_WARNING,
  3566. cmPolicies::GetPolicyDeprecatedWarning(id));
  3567. }
  3568. this->StateSnapshot.SetPolicy(id, status);
  3569. return true;
  3570. }
  3571. cmMakefile::PolicyPushPop::PolicyPushPop(cmMakefile* m)
  3572. : Makefile(m)
  3573. {
  3574. this->Makefile->PushPolicy();
  3575. }
  3576. cmMakefile::PolicyPushPop::~PolicyPushPop()
  3577. {
  3578. this->Makefile->PopPolicy();
  3579. }
  3580. void cmMakefile::PushPolicy(bool weak, cmPolicies::PolicyMap const& pm)
  3581. {
  3582. this->StateSnapshot.PushPolicy(pm, weak);
  3583. }
  3584. void cmMakefile::PopPolicy()
  3585. {
  3586. if (!this->StateSnapshot.PopPolicy()) {
  3587. this->IssueMessage(MessageType::FATAL_ERROR,
  3588. "cmake_policy POP without matching PUSH");
  3589. }
  3590. }
  3591. void cmMakefile::PopSnapshot(bool reportError)
  3592. {
  3593. // cmStateSnapshot manages nested policy scopes within it.
  3594. // Since the scope corresponding to the snapshot is closing,
  3595. // reject any still-open nested policy scopes with an error.
  3596. while (this->StateSnapshot.CanPopPolicyScope()) {
  3597. if (reportError) {
  3598. this->IssueMessage(MessageType::FATAL_ERROR,
  3599. "cmake_policy PUSH without matching POP");
  3600. reportError = false;
  3601. }
  3602. this->PopPolicy();
  3603. }
  3604. this->StateSnapshot = this->GetState()->Pop(this->StateSnapshot);
  3605. assert(this->StateSnapshot.IsValid());
  3606. }
  3607. bool cmMakefile::SetPolicyVersion(std::string const& version_min,
  3608. std::string const& version_max)
  3609. {
  3610. return cmPolicies::ApplyPolicyVersion(this, version_min, version_max,
  3611. cmPolicies::WarnCompat::On);
  3612. }
  3613. cmMakefile::VariablePushPop::VariablePushPop(cmMakefile* m)
  3614. : Makefile(m)
  3615. {
  3616. this->Makefile->StateSnapshot =
  3617. this->Makefile->GetState()->CreateVariableScopeSnapshot(
  3618. this->Makefile->StateSnapshot);
  3619. }
  3620. cmMakefile::VariablePushPop::~VariablePushPop()
  3621. {
  3622. this->Makefile->PopSnapshot();
  3623. }
  3624. bool cmMakefile::HasCMP0054AlreadyBeenReported(
  3625. cmListFileContext const& context) const
  3626. {
  3627. return !this->CMP0054ReportedIds.insert(context).second;
  3628. }
  3629. void cmMakefile::RecordPolicies(cmPolicies::PolicyMap& pm) const
  3630. {
  3631. /* Record the setting of every policy. */
  3632. using PolicyID = cmPolicies::PolicyID;
  3633. for (PolicyID pid = cmPolicies::CMP0000; pid != cmPolicies::CMPCOUNT;
  3634. pid = static_cast<PolicyID>(pid + 1)) {
  3635. pm.Set(pid, this->GetPolicyStatus(pid));
  3636. }
  3637. }
  3638. bool cmMakefile::IgnoreErrorsCMP0061() const
  3639. {
  3640. bool ignoreErrors = true;
  3641. switch (this->GetPolicyStatus(cmPolicies::CMP0061)) {
  3642. case cmPolicies::WARN:
  3643. // No warning for this policy!
  3644. CM_FALLTHROUGH;
  3645. case cmPolicies::OLD:
  3646. break;
  3647. case cmPolicies::NEW:
  3648. ignoreErrors = false;
  3649. break;
  3650. }
  3651. return ignoreErrors;
  3652. }
  3653. cmMakefile::FunctionPushPop::FunctionPushPop(cmMakefile* mf,
  3654. const std::string& fileName,
  3655. cmPolicies::PolicyMap const& pm)
  3656. : Makefile(mf)
  3657. {
  3658. this->Makefile->PushFunctionScope(fileName, pm);
  3659. }
  3660. cmMakefile::FunctionPushPop::~FunctionPushPop()
  3661. {
  3662. this->Makefile->PopFunctionScope(this->ReportError);
  3663. }
  3664. cmMakefile::MacroPushPop::MacroPushPop(cmMakefile* mf,
  3665. const std::string& fileName,
  3666. const cmPolicies::PolicyMap& pm)
  3667. : Makefile(mf)
  3668. {
  3669. this->Makefile->PushMacroScope(fileName, pm);
  3670. }
  3671. cmMakefile::MacroPushPop::~MacroPushPop()
  3672. {
  3673. this->Makefile->PopMacroScope(this->ReportError);
  3674. }
  3675. cmMakefile::FindPackageStackRAII::FindPackageStackRAII(cmMakefile* mf,
  3676. std::string const& name)
  3677. : Makefile(mf)
  3678. {
  3679. this->Makefile->FindPackageStack =
  3680. this->Makefile->FindPackageStack.Push(cmFindPackageCall{
  3681. name,
  3682. this->Makefile->FindPackageStackNextIndex,
  3683. });
  3684. this->Makefile->FindPackageStackNextIndex++;
  3685. }
  3686. cmMakefile::FindPackageStackRAII::~FindPackageStackRAII()
  3687. {
  3688. this->Makefile->FindPackageStackNextIndex =
  3689. this->Makefile->FindPackageStack.Top().Index + 1;
  3690. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  3691. if (!this->Makefile->FindPackageStack.Empty()) {
  3692. auto top = this->Makefile->FindPackageStack.Top();
  3693. this->Makefile->FindPackageStack = this->Makefile->FindPackageStack.Pop();
  3694. top.Index = this->Makefile->FindPackageStackNextIndex;
  3695. this->Makefile->FindPackageStackNextIndex++;
  3696. this->Makefile->FindPackageStack =
  3697. this->Makefile->FindPackageStack.Push(top);
  3698. }
  3699. }
  3700. cmMakefile::DebugFindPkgRAII::DebugFindPkgRAII(cmMakefile* mf,
  3701. std::string const& pkg)
  3702. : Makefile(mf)
  3703. , OldValue(this->Makefile->DebugFindPkg)
  3704. {
  3705. this->Makefile->DebugFindPkg =
  3706. this->Makefile->GetCMakeInstance()->GetDebugFindPkgOutput(pkg);
  3707. }
  3708. cmMakefile::DebugFindPkgRAII::~DebugFindPkgRAII()
  3709. {
  3710. this->Makefile->DebugFindPkg = this->OldValue;
  3711. }
  3712. bool cmMakefile::GetDebugFindPkgMode() const
  3713. {
  3714. return this->DebugFindPkg;
  3715. }