cmLocalGenerator.cxx 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804
  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 "cmLocalGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <cstdlib>
  8. #include <cstring>
  9. #include <initializer_list>
  10. #include <iterator>
  11. #include <sstream>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <vector>
  15. #include <cm/memory>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmAlgorithms.h"
  20. #include "cmComputeLinkInformation.h"
  21. #include "cmCustomCommand.h"
  22. #include "cmCustomCommandGenerator.h"
  23. #include "cmCustomCommandLines.h"
  24. #include "cmCustomCommandTypes.h"
  25. #include "cmGeneratedFileStream.h"
  26. #include "cmGeneratorExpression.h"
  27. #include "cmGeneratorExpressionEvaluationFile.h"
  28. #include "cmGeneratorTarget.h"
  29. #include "cmGlobalGenerator.h"
  30. #include "cmInstallGenerator.h"
  31. #include "cmInstallScriptGenerator.h"
  32. #include "cmInstallTargetGenerator.h"
  33. #include "cmLinkLineComputer.h"
  34. #include "cmLinkLineDeviceComputer.h"
  35. #include "cmMakefile.h"
  36. #include "cmRulePlaceholderExpander.h"
  37. #include "cmSourceFile.h"
  38. #include "cmSourceFileLocation.h"
  39. #include "cmSourceFileLocationKind.h"
  40. #include "cmState.h"
  41. #include "cmStateDirectory.h"
  42. #include "cmStateTypes.h"
  43. #include "cmStringAlgorithms.h"
  44. #include "cmSystemTools.h"
  45. #include "cmTarget.h"
  46. #include "cmTestGenerator.h"
  47. #include "cmVersion.h"
  48. #include "cmake.h"
  49. #if !defined(CMAKE_BOOTSTRAP)
  50. # define CM_LG_ENCODE_OBJECT_NAMES
  51. # include "cmCryptoHash.h"
  52. #endif
  53. #if defined(__HAIKU__)
  54. # include <FindDirectory.h>
  55. # include <StorageDefs.h>
  56. #endif
  57. // List of variables that are replaced when
  58. // rules are expanced. These variables are
  59. // replaced in the form <var> with GetSafeDefinition(var).
  60. // ${LANG} is replaced in the variable first with all enabled
  61. // languages.
  62. static auto ruleReplaceVars = { "CMAKE_${LANG}_COMPILER",
  63. "CMAKE_SHARED_LIBRARY_CREATE_${LANG}_FLAGS",
  64. "CMAKE_SHARED_MODULE_CREATE_${LANG}_FLAGS",
  65. "CMAKE_SHARED_MODULE_${LANG}_FLAGS",
  66. "CMAKE_SHARED_LIBRARY_${LANG}_FLAGS",
  67. "CMAKE_${LANG}_LINK_FLAGS",
  68. "CMAKE_SHARED_LIBRARY_SONAME_${LANG}_FLAG",
  69. "CMAKE_${LANG}_ARCHIVE",
  70. "CMAKE_AR",
  71. "CMAKE_CURRENT_SOURCE_DIR",
  72. "CMAKE_CURRENT_BINARY_DIR",
  73. "CMAKE_RANLIB",
  74. "CMAKE_LINKER",
  75. "CMAKE_MT",
  76. "CMAKE_CUDA_HOST_COMPILER",
  77. "CMAKE_CUDA_HOST_LINK_LAUNCHER",
  78. "CMAKE_CL_SHOWINCLUDES_PREFIX" };
  79. cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
  80. : cmOutputConverter(makefile->GetStateSnapshot())
  81. , StateSnapshot(makefile->GetStateSnapshot())
  82. , DirectoryBacktrace(makefile->GetBacktrace())
  83. {
  84. this->GlobalGenerator = gg;
  85. this->Makefile = makefile;
  86. this->AliasTargets = makefile->GetAliasTargets();
  87. this->EmitUniversalBinaryFlags = true;
  88. this->BackwardsCompatibility = 0;
  89. this->BackwardsCompatibilityFinal = false;
  90. this->ComputeObjectMaxPath();
  91. // Canonicalize entries of the CPATH environment variable the same
  92. // way detection of CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES does.
  93. {
  94. std::vector<std::string> cpath;
  95. cmSystemTools::GetPath(cpath, "CPATH");
  96. for (std::string& cp : cpath) {
  97. if (cmSystemTools::FileIsFullPath(cp)) {
  98. cp = cmSystemTools::CollapseFullPath(cp);
  99. this->EnvCPATH.emplace(std::move(cp));
  100. }
  101. }
  102. }
  103. std::vector<std::string> enabledLanguages =
  104. this->GetState()->GetEnabledLanguages();
  105. if (const char* sysrootCompile =
  106. this->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
  107. this->CompilerSysroot = sysrootCompile;
  108. } else {
  109. this->CompilerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  110. }
  111. if (const char* sysrootLink =
  112. this->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
  113. this->LinkerSysroot = sysrootLink;
  114. } else {
  115. this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
  116. }
  117. for (std::string const& lang : enabledLanguages) {
  118. if (lang == "NONE") {
  119. continue;
  120. }
  121. this->Compilers["CMAKE_" + lang + "_COMPILER"] = lang;
  122. this->VariableMappings["CMAKE_" + lang + "_COMPILER"] =
  123. this->Makefile->GetSafeDefinition("CMAKE_" + lang + "_COMPILER");
  124. std::string const& compilerArg1 = "CMAKE_" + lang + "_COMPILER_ARG1";
  125. std::string const& compilerTarget = "CMAKE_" + lang + "_COMPILER_TARGET";
  126. std::string const& compilerOptionTarget =
  127. "CMAKE_" + lang + "_COMPILE_OPTIONS_TARGET";
  128. std::string const& compilerExternalToolchain =
  129. "CMAKE_" + lang + "_COMPILER_EXTERNAL_TOOLCHAIN";
  130. std::string const& compilerOptionExternalToolchain =
  131. "CMAKE_" + lang + "_COMPILE_OPTIONS_EXTERNAL_TOOLCHAIN";
  132. std::string const& compilerOptionSysroot =
  133. "CMAKE_" + lang + "_COMPILE_OPTIONS_SYSROOT";
  134. this->VariableMappings[compilerArg1] =
  135. this->Makefile->GetSafeDefinition(compilerArg1);
  136. this->VariableMappings[compilerTarget] =
  137. this->Makefile->GetSafeDefinition(compilerTarget);
  138. this->VariableMappings[compilerOptionTarget] =
  139. this->Makefile->GetSafeDefinition(compilerOptionTarget);
  140. this->VariableMappings[compilerExternalToolchain] =
  141. this->Makefile->GetSafeDefinition(compilerExternalToolchain);
  142. this->VariableMappings[compilerOptionExternalToolchain] =
  143. this->Makefile->GetSafeDefinition(compilerOptionExternalToolchain);
  144. this->VariableMappings[compilerOptionSysroot] =
  145. this->Makefile->GetSafeDefinition(compilerOptionSysroot);
  146. for (std::string replaceVar : ruleReplaceVars) {
  147. if (replaceVar.find("${LANG}") != std::string::npos) {
  148. cmSystemTools::ReplaceString(replaceVar, "${LANG}", lang);
  149. }
  150. this->VariableMappings[replaceVar] =
  151. this->Makefile->GetSafeDefinition(replaceVar);
  152. }
  153. }
  154. }
  155. cmRulePlaceholderExpander* cmLocalGenerator::CreateRulePlaceholderExpander()
  156. const
  157. {
  158. return new cmRulePlaceholderExpander(this->Compilers, this->VariableMappings,
  159. this->CompilerSysroot,
  160. this->LinkerSysroot);
  161. }
  162. cmLocalGenerator::~cmLocalGenerator() = default;
  163. void cmLocalGenerator::IssueMessage(MessageType t,
  164. std::string const& text) const
  165. {
  166. this->GetCMakeInstance()->IssueMessage(t, text, this->DirectoryBacktrace);
  167. }
  168. void cmLocalGenerator::ComputeObjectMaxPath()
  169. {
  170. // Choose a maximum object file name length.
  171. #if defined(_WIN32) || defined(__CYGWIN__)
  172. this->ObjectPathMax = 250;
  173. #else
  174. this->ObjectPathMax = 1000;
  175. #endif
  176. const char* plen = this->Makefile->GetDefinition("CMAKE_OBJECT_PATH_MAX");
  177. if (plen && *plen) {
  178. unsigned int pmax;
  179. if (sscanf(plen, "%u", &pmax) == 1) {
  180. if (pmax >= 128) {
  181. this->ObjectPathMax = pmax;
  182. } else {
  183. std::ostringstream w;
  184. w << "CMAKE_OBJECT_PATH_MAX is set to " << pmax
  185. << ", which is less than the minimum of 128. "
  186. << "The value will be ignored.";
  187. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  188. }
  189. } else {
  190. std::ostringstream w;
  191. w << "CMAKE_OBJECT_PATH_MAX is set to \"" << plen
  192. << "\", which fails to parse as a positive integer. "
  193. << "The value will be ignored.";
  194. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  195. }
  196. }
  197. this->ObjectMaxPathViolations.clear();
  198. }
  199. static void MoveSystemIncludesToEnd(std::vector<std::string>& includeDirs,
  200. const std::string& config,
  201. const std::string& lang,
  202. const cmGeneratorTarget* target)
  203. {
  204. if (!target) {
  205. return;
  206. }
  207. std::stable_sort(
  208. includeDirs.begin(), includeDirs.end(),
  209. [&target, &config, &lang](std::string const& a, std::string const& b) {
  210. return !target->IsSystemIncludeDirectory(a, config, lang) &&
  211. target->IsSystemIncludeDirectory(b, config, lang);
  212. });
  213. }
  214. static void MoveSystemIncludesToEnd(std::vector<BT<std::string>>& includeDirs,
  215. const std::string& config,
  216. const std::string& lang,
  217. const cmGeneratorTarget* target)
  218. {
  219. if (!target) {
  220. return;
  221. }
  222. std::stable_sort(includeDirs.begin(), includeDirs.end(),
  223. [target, &config, &lang](BT<std::string> const& a,
  224. BT<std::string> const& b) {
  225. return !target->IsSystemIncludeDirectory(a.Value, config,
  226. lang) &&
  227. target->IsSystemIncludeDirectory(b.Value, config, lang);
  228. });
  229. }
  230. void cmLocalGenerator::TraceDependencies()
  231. {
  232. // Generate the rule files for each target.
  233. const auto& targets = this->GetGeneratorTargets();
  234. for (const auto& target : targets) {
  235. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  236. continue;
  237. }
  238. target->TraceDependencies();
  239. }
  240. }
  241. void cmLocalGenerator::GenerateTestFiles()
  242. {
  243. if (!this->Makefile->IsOn("CMAKE_TESTING_ENABLED")) {
  244. return;
  245. }
  246. // Compute the set of configurations.
  247. std::vector<std::string> configurationTypes;
  248. const std::string& config =
  249. this->Makefile->GetConfigurations(configurationTypes, false);
  250. std::string file =
  251. cmStrCat(this->StateSnapshot.GetDirectory().GetCurrentBinary(),
  252. "/CTestTestfile.cmake");
  253. cmGeneratedFileStream fout(file);
  254. fout.SetCopyIfDifferent(true);
  255. fout << "# CMake generated Testfile for " << std::endl
  256. << "# Source directory: "
  257. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  258. << "# Build directory: "
  259. << this->StateSnapshot.GetDirectory().GetCurrentBinary() << std::endl
  260. << "# " << std::endl
  261. << "# This file includes the relevant testing commands "
  262. << "required for " << std::endl
  263. << "# testing this directory and lists subdirectories to "
  264. << "be tested as well." << std::endl;
  265. const char* testIncludeFile =
  266. this->Makefile->GetProperty("TEST_INCLUDE_FILE");
  267. if (testIncludeFile) {
  268. fout << "include(\"" << testIncludeFile << "\")" << std::endl;
  269. }
  270. const char* testIncludeFiles =
  271. this->Makefile->GetProperty("TEST_INCLUDE_FILES");
  272. if (testIncludeFiles) {
  273. std::vector<std::string> includesList = cmExpandedList(testIncludeFiles);
  274. for (std::string const& i : includesList) {
  275. fout << "include(\"" << i << "\")" << std::endl;
  276. }
  277. }
  278. // Ask each test generator to write its code.
  279. for (const auto& tester : this->Makefile->GetTestGenerators()) {
  280. tester->Compute(this);
  281. tester->Generate(fout, config, configurationTypes);
  282. }
  283. using vec_t = std::vector<cmStateSnapshot>;
  284. vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
  285. std::string parentBinDir = this->GetCurrentBinaryDirectory();
  286. for (cmStateSnapshot const& i : children) {
  287. // TODO: Use add_subdirectory instead?
  288. std::string outP = i.GetDirectory().GetCurrentBinary();
  289. outP = this->MaybeConvertToRelativePath(parentBinDir, outP);
  290. outP = cmOutputConverter::EscapeForCMake(outP);
  291. fout << "subdirs(" << outP << ")" << std::endl;
  292. }
  293. // Add directory labels property
  294. const char* directoryLabels =
  295. this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
  296. const char* labels = this->Makefile->GetProperty("LABELS");
  297. if (labels || directoryLabels) {
  298. fout << "set_directory_properties(PROPERTIES LABELS ";
  299. if (labels) {
  300. fout << cmOutputConverter::EscapeForCMake(labels);
  301. }
  302. if (labels && directoryLabels) {
  303. fout << ";";
  304. }
  305. if (directoryLabels) {
  306. fout << cmOutputConverter::EscapeForCMake(directoryLabels);
  307. }
  308. fout << ")" << std::endl;
  309. }
  310. }
  311. void cmLocalGenerator::CreateEvaluationFileOutputs()
  312. {
  313. std::vector<std::string> const& configs =
  314. this->Makefile->GetGeneratorConfigs();
  315. for (std::string const& c : configs) {
  316. this->CreateEvaluationFileOutputs(c);
  317. }
  318. }
  319. void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
  320. {
  321. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  322. geef->CreateOutputFile(this, config);
  323. }
  324. }
  325. void cmLocalGenerator::ProcessEvaluationFiles(
  326. std::vector<std::string>& generatedFiles)
  327. {
  328. for (const auto& geef : this->Makefile->GetEvaluationFiles()) {
  329. geef->Generate(this);
  330. if (cmSystemTools::GetFatalErrorOccured()) {
  331. return;
  332. }
  333. std::vector<std::string> files = geef->GetFiles();
  334. std::sort(files.begin(), files.end());
  335. std::vector<std::string> intersection;
  336. std::set_intersection(files.begin(), files.end(), generatedFiles.begin(),
  337. generatedFiles.end(),
  338. std::back_inserter(intersection));
  339. if (!intersection.empty()) {
  340. cmSystemTools::Error("Files to be generated by multiple different "
  341. "commands: " +
  342. cmWrap('"', intersection, '"', " "));
  343. return;
  344. }
  345. cm::append(generatedFiles, files);
  346. std::inplace_merge(generatedFiles.begin(),
  347. generatedFiles.end() - files.size(),
  348. generatedFiles.end());
  349. }
  350. }
  351. void cmLocalGenerator::GenerateInstallRules()
  352. {
  353. // Compute the install prefix.
  354. const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
  355. #if defined(_WIN32) && !defined(__CYGWIN__)
  356. std::string prefix_win32;
  357. if (!prefix) {
  358. if (!cmSystemTools::GetEnv("SystemDrive", prefix_win32)) {
  359. prefix_win32 = "C:";
  360. }
  361. const char* project_name = this->Makefile->GetDefinition("PROJECT_NAME");
  362. if (project_name && project_name[0]) {
  363. prefix_win32 += "/Program Files/";
  364. prefix_win32 += project_name;
  365. } else {
  366. prefix_win32 += "/InstalledCMakeProject";
  367. }
  368. prefix = prefix_win32.c_str();
  369. }
  370. #elif defined(__HAIKU__)
  371. char dir[B_PATH_NAME_LENGTH];
  372. if (!prefix) {
  373. if (find_directory(B_SYSTEM_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  374. B_OK) {
  375. prefix = dir;
  376. } else {
  377. prefix = "/boot/system";
  378. }
  379. }
  380. #else
  381. if (!prefix) {
  382. prefix = "/usr/local";
  383. }
  384. #endif
  385. if (const char* stagingPrefix =
  386. this->Makefile->GetDefinition("CMAKE_STAGING_PREFIX")) {
  387. prefix = stagingPrefix;
  388. }
  389. // Compute the set of configurations.
  390. std::vector<std::string> configurationTypes;
  391. const std::string& config =
  392. this->Makefile->GetConfigurations(configurationTypes, false);
  393. // Choose a default install configuration.
  394. std::string default_config = config;
  395. const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
  396. "DEBUG", nullptr };
  397. for (const char** c = default_order; *c && default_config.empty(); ++c) {
  398. for (std::string const& configurationType : configurationTypes) {
  399. if (cmSystemTools::UpperCase(configurationType) == *c) {
  400. default_config = configurationType;
  401. }
  402. }
  403. }
  404. if (default_config.empty() && !configurationTypes.empty()) {
  405. default_config = configurationTypes[0];
  406. }
  407. // Create the install script file.
  408. std::string file = this->StateSnapshot.GetDirectory().GetCurrentBinary();
  409. std::string homedir = this->GetState()->GetBinaryDirectory();
  410. int toplevel_install = 0;
  411. if (file == homedir) {
  412. toplevel_install = 1;
  413. }
  414. file += "/cmake_install.cmake";
  415. cmGeneratedFileStream fout(file);
  416. fout.SetCopyIfDifferent(true);
  417. // Write the header.
  418. fout << "# Install script for directory: "
  419. << this->StateSnapshot.GetDirectory().GetCurrentSource() << std::endl
  420. << std::endl;
  421. fout << "# Set the install prefix" << std::endl
  422. << "if(NOT DEFINED CMAKE_INSTALL_PREFIX)" << std::endl
  423. << " set(CMAKE_INSTALL_PREFIX \"" << prefix << "\")" << std::endl
  424. << "endif()" << std::endl
  425. << R"(string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX )"
  426. << "\"${CMAKE_INSTALL_PREFIX}\")" << std::endl
  427. << std::endl;
  428. // Write support code for generating per-configuration install rules.
  429. /* clang-format off */
  430. fout <<
  431. "# Set the install configuration name.\n"
  432. "if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)\n"
  433. " if(BUILD_TYPE)\n"
  434. " string(REGEX REPLACE \"^[^A-Za-z0-9_]+\" \"\"\n"
  435. " CMAKE_INSTALL_CONFIG_NAME \"${BUILD_TYPE}\")\n"
  436. " else()\n"
  437. " set(CMAKE_INSTALL_CONFIG_NAME \"" << default_config << "\")\n"
  438. " endif()\n"
  439. " message(STATUS \"Install configuration: "
  440. "\\\"${CMAKE_INSTALL_CONFIG_NAME}\\\"\")\n"
  441. "endif()\n"
  442. "\n";
  443. /* clang-format on */
  444. // Write support code for dealing with component-specific installs.
  445. /* clang-format off */
  446. fout <<
  447. "# Set the component getting installed.\n"
  448. "if(NOT CMAKE_INSTALL_COMPONENT)\n"
  449. " if(COMPONENT)\n"
  450. " message(STATUS \"Install component: \\\"${COMPONENT}\\\"\")\n"
  451. " set(CMAKE_INSTALL_COMPONENT \"${COMPONENT}\")\n"
  452. " else()\n"
  453. " set(CMAKE_INSTALL_COMPONENT)\n"
  454. " endif()\n"
  455. "endif()\n"
  456. "\n";
  457. /* clang-format on */
  458. // Copy user-specified install options to the install code.
  459. if (const char* so_no_exe =
  460. this->Makefile->GetDefinition("CMAKE_INSTALL_SO_NO_EXE")) {
  461. /* clang-format off */
  462. fout <<
  463. "# Install shared libraries without execute permission?\n"
  464. "if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)\n"
  465. " set(CMAKE_INSTALL_SO_NO_EXE \"" << so_no_exe << "\")\n"
  466. "endif()\n"
  467. "\n";
  468. /* clang-format on */
  469. }
  470. // Copy cmake cross compile state to install code.
  471. if (const char* crosscompiling =
  472. this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
  473. /* clang-format off */
  474. fout <<
  475. "# Is this installation the result of a crosscompile?\n"
  476. "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
  477. " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
  478. "endif()\n"
  479. "\n";
  480. /* clang-format on */
  481. }
  482. // Write default directory permissions.
  483. if (const char* defaultDirPermissions = this->Makefile->GetDefinition(
  484. "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS")) {
  485. /* clang-format off */
  486. fout <<
  487. "# Set default install directory permissions.\n"
  488. "if(NOT DEFINED CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS)\n"
  489. " set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS \""
  490. << defaultDirPermissions << "\")\n"
  491. "endif()\n"
  492. "\n";
  493. /* clang-format on */
  494. }
  495. // Ask each install generator to write its code.
  496. cmPolicies::PolicyStatus status = this->GetPolicyStatus(cmPolicies::CMP0082);
  497. auto const& installers = this->Makefile->GetInstallGenerators();
  498. bool haveSubdirectoryInstall = false;
  499. bool haveInstallAfterSubdirectory = false;
  500. if (status == cmPolicies::WARN) {
  501. for (const auto& installer : installers) {
  502. installer->CheckCMP0082(haveSubdirectoryInstall,
  503. haveInstallAfterSubdirectory);
  504. installer->Generate(fout, config, configurationTypes);
  505. }
  506. } else {
  507. for (const auto& installer : installers) {
  508. installer->Generate(fout, config, configurationTypes);
  509. }
  510. }
  511. // Write rules from old-style specification stored in targets.
  512. this->GenerateTargetInstallRules(fout, config, configurationTypes);
  513. // Include install scripts from subdirectories.
  514. switch (status) {
  515. case cmPolicies::WARN:
  516. if (haveInstallAfterSubdirectory &&
  517. this->Makefile->PolicyOptionalWarningEnabled(
  518. "CMAKE_POLICY_WARNING_CMP0082")) {
  519. std::ostringstream e;
  520. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0082) << "\n";
  521. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  522. }
  523. CM_FALLTHROUGH;
  524. case cmPolicies::OLD: {
  525. std::vector<cmStateSnapshot> children =
  526. this->Makefile->GetStateSnapshot().GetChildren();
  527. if (!children.empty()) {
  528. fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
  529. fout << " # Include the install script for each subdirectory.\n";
  530. for (cmStateSnapshot const& c : children) {
  531. if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  532. std::string odir = c.GetDirectory().GetCurrentBinary();
  533. cmSystemTools::ConvertToUnixSlashes(odir);
  534. fout << " include(\"" << odir << "/cmake_install.cmake\")"
  535. << std::endl;
  536. }
  537. }
  538. fout << "\n";
  539. fout << "endif()\n\n";
  540. }
  541. } break;
  542. case cmPolicies::REQUIRED_IF_USED:
  543. case cmPolicies::REQUIRED_ALWAYS:
  544. case cmPolicies::NEW:
  545. // NEW behavior is handled in
  546. // cmInstallSubdirectoryGenerator::GenerateScript()
  547. break;
  548. }
  549. // Record the install manifest.
  550. if (toplevel_install) {
  551. /* clang-format off */
  552. fout <<
  553. "if(CMAKE_INSTALL_COMPONENT)\n"
  554. " set(CMAKE_INSTALL_MANIFEST \"install_manifest_"
  555. "${CMAKE_INSTALL_COMPONENT}.txt\")\n"
  556. "else()\n"
  557. " set(CMAKE_INSTALL_MANIFEST \"install_manifest.txt\")\n"
  558. "endif()\n"
  559. "\n"
  560. "string(REPLACE \";\" \"\\n\" CMAKE_INSTALL_MANIFEST_CONTENT\n"
  561. " \"${CMAKE_INSTALL_MANIFEST_FILES}\")\n"
  562. "file(WRITE \"" << homedir << "/${CMAKE_INSTALL_MANIFEST}\"\n"
  563. " \"${CMAKE_INSTALL_MANIFEST_CONTENT}\")\n";
  564. /* clang-format on */
  565. }
  566. }
  567. void cmLocalGenerator::AddGeneratorTarget(
  568. std::unique_ptr<cmGeneratorTarget> gt)
  569. {
  570. cmGeneratorTarget* gt_ptr = gt.get();
  571. this->GeneratorTargets.push_back(std::move(gt));
  572. this->GeneratorTargetSearchIndex.emplace(gt_ptr->GetName(), gt_ptr);
  573. this->GlobalGenerator->IndexGeneratorTarget(gt_ptr);
  574. }
  575. void cmLocalGenerator::AddImportedGeneratorTarget(cmGeneratorTarget* gt)
  576. {
  577. this->ImportedGeneratorTargets.emplace(gt->GetName(), gt);
  578. this->GlobalGenerator->IndexGeneratorTarget(gt);
  579. }
  580. void cmLocalGenerator::AddOwnedImportedGeneratorTarget(
  581. std::unique_ptr<cmGeneratorTarget> gt)
  582. {
  583. this->OwnedImportedGeneratorTargets.push_back(std::move(gt));
  584. }
  585. cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
  586. const std::string& name) const
  587. {
  588. auto ti = this->GeneratorTargetSearchIndex.find(name);
  589. if (ti != this->GeneratorTargetSearchIndex.end()) {
  590. return ti->second;
  591. }
  592. return nullptr;
  593. }
  594. void cmLocalGenerator::ComputeTargetManifest()
  595. {
  596. // Collect the set of configuration types.
  597. std::vector<std::string> configNames;
  598. this->Makefile->GetConfigurations(configNames);
  599. if (configNames.empty()) {
  600. configNames.emplace_back();
  601. }
  602. // Add our targets to the manifest for each configuration.
  603. const auto& targets = this->GetGeneratorTargets();
  604. for (const auto& target : targets) {
  605. if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  606. continue;
  607. }
  608. for (std::string const& c : configNames) {
  609. target->ComputeTargetManifest(c);
  610. }
  611. }
  612. }
  613. bool cmLocalGenerator::ComputeTargetCompileFeatures()
  614. {
  615. // Collect the set of configuration types.
  616. std::vector<std::string> configNames;
  617. this->Makefile->GetConfigurations(configNames);
  618. if (configNames.empty()) {
  619. configNames.emplace_back();
  620. }
  621. using LanguagePair = std::pair<std::string, std::string>;
  622. std::vector<LanguagePair> pairedLanguages{ { "OBJC", "C" },
  623. { "OBJCXX", "CXX" },
  624. { "CUDA", "CXX" } };
  625. std::set<LanguagePair> inferredEnabledLanguages;
  626. for (auto const& lang : pairedLanguages) {
  627. if (this->Makefile->GetState()->GetLanguageEnabled(lang.first)) {
  628. inferredEnabledLanguages.insert(lang);
  629. }
  630. }
  631. // Process compile features of all targets.
  632. const auto& targets = this->GetGeneratorTargets();
  633. for (const auto& target : targets) {
  634. for (std::string const& c : configNames) {
  635. if (!target->ComputeCompileFeatures(c)) {
  636. return false;
  637. }
  638. }
  639. // Now that C/C++ _STANDARD values have been computed
  640. // set the values to ObjC/ObjCXX _STANDARD variables
  641. if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  642. auto copyStandardToObjLang = [&](LanguagePair const& lang) -> bool {
  643. if (!target->GetProperty(cmStrCat(lang.first, "_STANDARD"))) {
  644. auto* standard =
  645. target->GetProperty(cmStrCat(lang.second, "_STANDARD"));
  646. if (!standard) {
  647. standard = this->Makefile->GetDefinition(
  648. cmStrCat("CMAKE_", lang.second, "_STANDARD_DEFAULT"));
  649. }
  650. target->Target->SetProperty(cmStrCat(lang.first, "_STANDARD"),
  651. standard);
  652. return true;
  653. }
  654. return false;
  655. };
  656. auto copyPropertyToObjLang = [&](LanguagePair const& lang,
  657. const char* property) {
  658. if (!target->GetProperty(cmStrCat(lang.first, property)) &&
  659. target->GetProperty(cmStrCat(lang.second, property))) {
  660. target->Target->SetProperty(
  661. cmStrCat(lang.first, property),
  662. target->GetProperty(cmStrCat(lang.second, property)));
  663. }
  664. };
  665. for (auto const& lang : pairedLanguages) {
  666. if (copyStandardToObjLang(lang)) {
  667. copyPropertyToObjLang(lang, "_STANDARD_REQUIRED");
  668. copyPropertyToObjLang(lang, "_EXTENSIONS");
  669. }
  670. }
  671. if (const char* standard = target->GetProperty("CUDA_STANDARD")) {
  672. if (std::string{ standard } == "98") {
  673. target->Target->SetProperty("CUDA_STANDARD", "03");
  674. }
  675. }
  676. }
  677. }
  678. return true;
  679. }
  680. bool cmLocalGenerator::IsRootMakefile() const
  681. {
  682. return !this->StateSnapshot.GetBuildsystemDirectoryParent().IsValid();
  683. }
  684. cmState* cmLocalGenerator::GetState() const
  685. {
  686. return this->GlobalGenerator->GetCMakeInstance()->GetState();
  687. }
  688. cmStateSnapshot cmLocalGenerator::GetStateSnapshot() const
  689. {
  690. return this->Makefile->GetStateSnapshot();
  691. }
  692. const char* cmLocalGenerator::GetRuleLauncher(cmGeneratorTarget* target,
  693. const std::string& prop)
  694. {
  695. if (target) {
  696. return target->GetProperty(prop);
  697. }
  698. return this->Makefile->GetProperty(prop);
  699. }
  700. std::string cmLocalGenerator::ConvertToIncludeReference(
  701. std::string const& path, OutputFormat format, bool forceFullPaths)
  702. {
  703. static_cast<void>(forceFullPaths);
  704. return this->ConvertToOutputForExisting(path, format);
  705. }
  706. std::string cmLocalGenerator::GetIncludeFlags(
  707. const std::vector<std::string>& includeDirs, cmGeneratorTarget* target,
  708. const std::string& lang, bool forceFullPaths, bool forResponseFile,
  709. const std::string& config)
  710. {
  711. if (lang.empty()) {
  712. return "";
  713. }
  714. std::vector<std::string> includes = includeDirs;
  715. MoveSystemIncludesToEnd(includes, config, lang, target);
  716. OutputFormat shellFormat = forResponseFile ? RESPONSE : SHELL;
  717. std::ostringstream includeFlags;
  718. std::string const& includeFlag =
  719. this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_", lang));
  720. const char* sep =
  721. this->Makefile->GetDefinition(cmStrCat("CMAKE_INCLUDE_FLAG_SEP_", lang));
  722. bool quotePaths = false;
  723. if (this->Makefile->GetDefinition("CMAKE_QUOTE_INCLUDE_PATHS")) {
  724. quotePaths = true;
  725. }
  726. bool repeatFlag = true;
  727. // should the include flag be repeated like ie. -IA -IB
  728. if (!sep) {
  729. sep = " ";
  730. } else {
  731. // if there is a separator then the flag is not repeated but is only
  732. // given once i.e. -classpath a:b:c
  733. repeatFlag = false;
  734. }
  735. // Support special system include flag if it is available and the
  736. // normal flag is repeated for each directory.
  737. const char* sysIncludeFlag = nullptr;
  738. if (repeatFlag) {
  739. sysIncludeFlag = this->Makefile->GetDefinition(
  740. cmStrCat("CMAKE_INCLUDE_SYSTEM_FLAG_", lang));
  741. }
  742. const char* fwSearchFlag = this->Makefile->GetDefinition(
  743. cmStrCat("CMAKE_", lang, "_FRAMEWORK_SEARCH_FLAG"));
  744. const char* sysFwSearchFlag = this->Makefile->GetDefinition(
  745. cmStrCat("CMAKE_", lang, "_SYSTEM_FRAMEWORK_SEARCH_FLAG"));
  746. bool flagUsed = false;
  747. std::set<std::string> emitted;
  748. #ifdef __APPLE__
  749. emitted.insert("/System/Library/Frameworks");
  750. #endif
  751. for (std::string const& i : includes) {
  752. if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
  753. cmSystemTools::IsPathToFramework(i)) {
  754. std::string const frameworkDir =
  755. cmSystemTools::CollapseFullPath(cmStrCat(i, "/../"));
  756. if (emitted.insert(frameworkDir).second) {
  757. if (sysFwSearchFlag && target &&
  758. target->IsSystemIncludeDirectory(i, config, lang)) {
  759. includeFlags << sysFwSearchFlag;
  760. } else {
  761. includeFlags << fwSearchFlag;
  762. }
  763. includeFlags << this->ConvertToOutputFormat(frameworkDir, shellFormat)
  764. << " ";
  765. }
  766. continue;
  767. }
  768. if (!flagUsed || repeatFlag) {
  769. if (sysIncludeFlag && target &&
  770. target->IsSystemIncludeDirectory(i, config, lang)) {
  771. includeFlags << sysIncludeFlag;
  772. } else {
  773. includeFlags << includeFlag;
  774. }
  775. flagUsed = true;
  776. }
  777. std::string includePath =
  778. this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
  779. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  780. includeFlags << "\"";
  781. }
  782. includeFlags << includePath;
  783. if (quotePaths && !includePath.empty() && includePath.front() != '\"') {
  784. includeFlags << "\"";
  785. }
  786. includeFlags << sep;
  787. }
  788. std::string flags = includeFlags.str();
  789. // remove trailing separators
  790. if ((sep[0] != ' ') && !flags.empty() && flags.back() == sep[0]) {
  791. flags.back() = ' ';
  792. }
  793. return flags;
  794. }
  795. void cmLocalGenerator::AddCompileOptions(std::string& flags,
  796. cmGeneratorTarget* target,
  797. const std::string& lang,
  798. const std::string& config)
  799. {
  800. std::vector<BT<std::string>> tmpFlags;
  801. this->AddCompileOptions(tmpFlags, target, lang, config);
  802. this->AppendFlags(flags, tmpFlags);
  803. }
  804. void cmLocalGenerator::AddCompileOptions(std::vector<BT<std::string>>& flags,
  805. cmGeneratorTarget* target,
  806. const std::string& lang,
  807. const std::string& config)
  808. {
  809. std::string langFlagRegexVar = std::string("CMAKE_") + lang + "_FLAG_REGEX";
  810. if (const char* langFlagRegexStr =
  811. this->Makefile->GetDefinition(langFlagRegexVar)) {
  812. // Filter flags acceptable to this language.
  813. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  814. std::vector<std::string> opts;
  815. cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
  816. // Re-escape these flags since COMPILE_FLAGS were already parsed
  817. // as a command line above.
  818. std::string compileOpts;
  819. this->AppendCompileOptions(compileOpts, opts, langFlagRegexStr);
  820. if (!compileOpts.empty()) {
  821. flags.emplace_back(std::move(compileOpts));
  822. }
  823. }
  824. std::vector<BT<std::string>> targetCompileOpts =
  825. target->GetCompileOptions(config, lang);
  826. // COMPILE_OPTIONS are escaped.
  827. this->AppendCompileOptions(flags, targetCompileOpts, langFlagRegexStr);
  828. } else {
  829. // Use all flags.
  830. if (const char* targetFlags = target->GetProperty("COMPILE_FLAGS")) {
  831. // COMPILE_FLAGS are not escaped for historical reasons.
  832. std::string compileFlags;
  833. this->AppendFlags(compileFlags, targetFlags);
  834. if (!compileFlags.empty()) {
  835. flags.emplace_back(std::move(compileFlags));
  836. }
  837. }
  838. std::vector<BT<std::string>> targetCompileOpts =
  839. target->GetCompileOptions(config, lang);
  840. // COMPILE_OPTIONS are escaped.
  841. this->AppendCompileOptions(flags, targetCompileOpts);
  842. }
  843. for (auto const& it : target->GetMaxLanguageStandards()) {
  844. const char* standard = target->GetProperty(it.first + "_STANDARD");
  845. if (!standard) {
  846. continue;
  847. }
  848. if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
  849. std::ostringstream e;
  850. e << "The COMPILE_FEATURES property of target \"" << target->GetName()
  851. << "\" was evaluated when computing the link "
  852. "implementation, and the \""
  853. << it.first << "_STANDARD\" was \"" << it.second
  854. << "\" for that computation. Computing the "
  855. "COMPILE_FEATURES based on the link implementation resulted in a "
  856. "higher \""
  857. << it.first << "_STANDARD\" \"" << standard
  858. << "\". "
  859. "This is not permitted. The COMPILE_FEATURES may not both depend "
  860. "on "
  861. "and be depended on by the link implementation."
  862. << std::endl;
  863. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  864. return;
  865. }
  866. }
  867. std::string compReqFlag;
  868. this->AddCompilerRequirementFlag(compReqFlag, target, lang);
  869. if (!compReqFlag.empty()) {
  870. flags.emplace_back(std::move(compReqFlag));
  871. }
  872. // Add compile flag for the MSVC compiler only.
  873. cmMakefile* mf = this->GetMakefile();
  874. if (const char* jmc =
  875. mf->GetDefinition("CMAKE_" + lang + "_COMPILE_OPTIONS_JMC")) {
  876. // Handle Just My Code debugging flags, /JMC.
  877. // If the target is a Managed C++ one, /JMC is not compatible.
  878. if (target->GetManagedType(config) !=
  879. cmGeneratorTarget::ManagedType::Managed) {
  880. // add /JMC flags if target property VS_JUST_MY_CODE_DEBUGGING is set
  881. // to ON
  882. if (char const* jmcExprGen =
  883. target->GetProperty("VS_JUST_MY_CODE_DEBUGGING")) {
  884. std::string isJMCEnabled =
  885. cmGeneratorExpression::Evaluate(jmcExprGen, this, config);
  886. if (cmIsOn(isJMCEnabled)) {
  887. std::vector<std::string> optVec = cmExpandedList(jmc);
  888. std::string jmcFlags;
  889. this->AppendCompileOptions(jmcFlags, optVec);
  890. if (!jmcFlags.empty()) {
  891. flags.emplace_back(std::move(jmcFlags));
  892. }
  893. }
  894. }
  895. }
  896. }
  897. }
  898. cmTarget* cmLocalGenerator::AddCustomCommandToTarget(
  899. const std::string& target, const std::vector<std::string>& byproducts,
  900. const std::vector<std::string>& depends,
  901. const cmCustomCommandLines& commandLines, cmCustomCommandType type,
  902. const char* comment, const char* workingDir, bool escapeOldStyle,
  903. bool uses_terminal, const std::string& depfile, const std::string& job_pool,
  904. bool command_expand_lists, cmObjectLibraryCommands objLibCommands)
  905. {
  906. cmTarget* t = this->Makefile->GetCustomCommandTarget(
  907. target, objLibCommands, this->DirectoryBacktrace);
  908. if (!t) {
  909. return nullptr;
  910. }
  911. detail::AddCustomCommandToTarget(
  912. *this, this->DirectoryBacktrace, cmCommandOrigin::Generator, t, byproducts,
  913. depends, commandLines, type, comment, workingDir, escapeOldStyle,
  914. uses_terminal, depfile, job_pool, command_expand_lists);
  915. return t;
  916. }
  917. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  918. const std::string& output, const std::vector<std::string>& depends,
  919. const std::string& main_dependency, const cmCustomCommandLines& commandLines,
  920. const char* comment, const char* workingDir, bool replace,
  921. bool escapeOldStyle, bool uses_terminal, bool command_expand_lists,
  922. const std::string& depfile, const std::string& job_pool)
  923. {
  924. std::vector<std::string> no_byproducts;
  925. cmImplicitDependsList no_implicit_depends;
  926. return this->AddCustomCommandToOutput(
  927. { output }, no_byproducts, depends, main_dependency, no_implicit_depends,
  928. commandLines, comment, workingDir, replace, escapeOldStyle, uses_terminal,
  929. command_expand_lists, depfile, job_pool);
  930. }
  931. cmSourceFile* cmLocalGenerator::AddCustomCommandToOutput(
  932. const std::vector<std::string>& outputs,
  933. const std::vector<std::string>& byproducts,
  934. const std::vector<std::string>& depends, const std::string& main_dependency,
  935. const cmImplicitDependsList& implicit_depends,
  936. const cmCustomCommandLines& commandLines, const char* comment,
  937. const char* workingDir, bool replace, bool escapeOldStyle,
  938. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  939. const std::string& job_pool)
  940. {
  941. // Make sure there is at least one output.
  942. if (outputs.empty()) {
  943. cmSystemTools::Error("Attempt to add a custom rule with no output!");
  944. return nullptr;
  945. }
  946. return detail::AddCustomCommandToOutput(
  947. *this, this->DirectoryBacktrace, cmCommandOrigin::Generator, outputs,
  948. byproducts, depends, main_dependency, implicit_depends, commandLines,
  949. comment, workingDir, replace, escapeOldStyle, uses_terminal,
  950. command_expand_lists, depfile, job_pool);
  951. }
  952. cmTarget* cmLocalGenerator::AddUtilityCommand(
  953. const std::string& utilityName, bool excludeFromAll, const char* workingDir,
  954. const std::vector<std::string>& byproducts,
  955. const std::vector<std::string>& depends,
  956. const cmCustomCommandLines& commandLines, bool escapeOldStyle,
  957. const char* comment, bool uses_terminal, bool command_expand_lists,
  958. const std::string& job_pool)
  959. {
  960. cmTarget* target =
  961. this->Makefile->AddNewUtilityTarget(utilityName, excludeFromAll);
  962. target->SetIsGeneratorProvided(true);
  963. if (commandLines.empty() && depends.empty()) {
  964. return target;
  965. }
  966. detail::AddUtilityCommand(
  967. *this, this->DirectoryBacktrace, cmCommandOrigin::Generator, target,
  968. this->Makefile->GetUtilityOutput(target), workingDir, byproducts, depends,
  969. commandLines, escapeOldStyle, comment, uses_terminal, command_expand_lists,
  970. job_pool);
  971. return target;
  972. }
  973. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectoriesImplicit(
  974. cmGeneratorTarget const* target, std::string const& lang,
  975. std::string const& config, bool stripImplicitDirs,
  976. bool appendAllImplicitDirs) const
  977. {
  978. std::vector<BT<std::string>> result;
  979. // Do not repeat an include path.
  980. std::set<std::string> emitted;
  981. auto emitDir = [&result, &emitted](std::string const& dir) {
  982. if (emitted.insert(dir).second) {
  983. result.emplace_back(dir);
  984. }
  985. };
  986. auto emitBT = [&result, &emitted](BT<std::string> const& dir) {
  987. if (emitted.insert(dir.Value).second) {
  988. result.emplace_back(dir);
  989. }
  990. };
  991. // When automatic include directories are requested for a build then
  992. // include the source and binary directories at the beginning of the
  993. // include path to approximate include file behavior for an
  994. // in-source build. This does not account for the case of a source
  995. // file in a subdirectory of the current source directory but we
  996. // cannot fix this because not all native build tools support
  997. // per-source-file include paths.
  998. if (this->Makefile->IsOn("CMAKE_INCLUDE_CURRENT_DIR")) {
  999. // Current binary directory
  1000. emitDir(this->StateSnapshot.GetDirectory().GetCurrentBinary());
  1001. // Current source directory
  1002. emitDir(this->StateSnapshot.GetDirectory().GetCurrentSource());
  1003. }
  1004. if (!target) {
  1005. return result;
  1006. }
  1007. // Standard include directories to be added unconditionally at the end.
  1008. // These are intended to simulate additional implicit include directories.
  1009. std::vector<std::string> userStandardDirs;
  1010. {
  1011. std::string const value = this->Makefile->GetSafeDefinition(
  1012. cmStrCat("CMAKE_", lang, "_STANDARD_INCLUDE_DIRECTORIES"));
  1013. cmExpandList(value, userStandardDirs);
  1014. for (std::string& usd : userStandardDirs) {
  1015. cmSystemTools::ConvertToUnixSlashes(usd);
  1016. }
  1017. }
  1018. // Implicit include directories
  1019. std::vector<std::string> implicitDirs;
  1020. std::set<std::string> implicitSet;
  1021. // Include directories to be excluded as if they were implicit.
  1022. std::set<std::string> implicitExclude;
  1023. {
  1024. // Raw list of implicit include directories
  1025. // Start with "standard" directories that we unconditionally add below.
  1026. std::vector<std::string> impDirVec = userStandardDirs;
  1027. // Load implicit include directories for this language.
  1028. // We ignore this for Fortran because:
  1029. // * There are no standard library headers to avoid overriding.
  1030. // * Compilers like gfortran do not search their own implicit include
  1031. // directories for modules ('.mod' files).
  1032. if (lang != "Fortran") {
  1033. const char* value = this->Makefile->GetDefinition(
  1034. cmStrCat("CMAKE_", lang, "_IMPLICIT_INCLUDE_DIRECTORIES"));
  1035. if (value != nullptr) {
  1036. size_t const impDirVecOldSize = impDirVec.size();
  1037. cmExpandList(value, impDirVec);
  1038. // FIXME: Use cmRange with 'advance()' when it supports non-const.
  1039. for (size_t i = impDirVecOldSize; i < impDirVec.size(); ++i) {
  1040. cmSystemTools::ConvertToUnixSlashes(impDirVec[i]);
  1041. }
  1042. }
  1043. }
  1044. // The Platform/UnixPaths module used to hard-code /usr/include for C, CXX,
  1045. // and CUDA in CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES, but those
  1046. // variables are now computed. On macOS the /usr/include directory is
  1047. // inside the platform SDK so the computed value does not contain it
  1048. // directly. In this case adding -I/usr/include can hide SDK headers so we
  1049. // must still exclude it.
  1050. if ((lang == "C" || lang == "CXX" || lang == "CUDA") &&
  1051. !cmContains(impDirVec, "/usr/include") &&
  1052. std::find_if(impDirVec.begin(), impDirVec.end(),
  1053. [](std::string const& d) {
  1054. return cmHasLiteralSuffix(d, "/usr/include");
  1055. }) != impDirVec.end()) {
  1056. // Only exclude this hard coded path for backwards compatibility.
  1057. implicitExclude.emplace("/usr/include");
  1058. }
  1059. for (std::string const& i : impDirVec) {
  1060. if (implicitSet.insert(cmSystemTools::GetRealPath(i)).second) {
  1061. implicitDirs.emplace_back(i);
  1062. }
  1063. }
  1064. }
  1065. // Checks if this is not an excluded (implicit) include directory.
  1066. auto notExcluded = [this, &implicitSet, &implicitExclude,
  1067. &lang](std::string const& dir) {
  1068. return (
  1069. // Do not exclude directories that are not in an excluded set.
  1070. ((!cmContains(implicitSet, cmSystemTools::GetRealPath(dir))) &&
  1071. (!cmContains(implicitExclude, dir)))
  1072. // Do not exclude entries of the CPATH environment variable even though
  1073. // they are implicitly searched by the compiler. They are meant to be
  1074. // user-specified directories that can be re-ordered or converted to
  1075. // -isystem without breaking real compiler builtin headers.
  1076. || ((lang == "C" || lang == "CXX") && cmContains(this->EnvCPATH, dir)));
  1077. };
  1078. // Get the target-specific include directories.
  1079. std::vector<BT<std::string>> userDirs =
  1080. target->GetIncludeDirectories(config, lang);
  1081. // Support putting all the in-project include directories first if
  1082. // it is requested by the project.
  1083. if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
  1084. std::string const& topSourceDir = this->GetState()->GetSourceDirectory();
  1085. std::string const& topBinaryDir = this->GetState()->GetBinaryDirectory();
  1086. for (BT<std::string> const& udr : userDirs) {
  1087. // Emit this directory only if it is a subdirectory of the
  1088. // top-level source or binary tree.
  1089. if (cmSystemTools::ComparePath(udr.Value, topSourceDir) ||
  1090. cmSystemTools::ComparePath(udr.Value, topBinaryDir) ||
  1091. cmSystemTools::IsSubDirectory(udr.Value, topSourceDir) ||
  1092. cmSystemTools::IsSubDirectory(udr.Value, topBinaryDir)) {
  1093. if (notExcluded(udr.Value)) {
  1094. emitBT(udr);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. // Emit remaining non implicit user direcories.
  1100. for (BT<std::string> const& udr : userDirs) {
  1101. if (notExcluded(udr.Value)) {
  1102. emitBT(udr);
  1103. }
  1104. }
  1105. // Sort result
  1106. MoveSystemIncludesToEnd(result, config, lang, target);
  1107. // Append standard include directories for this language.
  1108. userDirs.reserve(userDirs.size() + userStandardDirs.size());
  1109. for (std::string& usd : userStandardDirs) {
  1110. emitDir(usd);
  1111. userDirs.emplace_back(std::move(usd));
  1112. }
  1113. // Append compiler implicit include directories
  1114. if (!stripImplicitDirs) {
  1115. // Append implicit directories that were requested by the user only
  1116. for (BT<std::string> const& udr : userDirs) {
  1117. if (cmContains(implicitSet, cmSystemTools::GetRealPath(udr.Value))) {
  1118. emitBT(udr);
  1119. }
  1120. }
  1121. // Append remaining implicit directories (on demand)
  1122. if (appendAllImplicitDirs) {
  1123. for (std::string& imd : implicitDirs) {
  1124. emitDir(imd);
  1125. }
  1126. }
  1127. }
  1128. return result;
  1129. }
  1130. void cmLocalGenerator::GetIncludeDirectoriesImplicit(
  1131. std::vector<std::string>& dirs, cmGeneratorTarget const* target,
  1132. const std::string& lang, const std::string& config, bool stripImplicitDirs,
  1133. bool appendAllImplicitDirs) const
  1134. {
  1135. std::vector<BT<std::string>> tmp = this->GetIncludeDirectoriesImplicit(
  1136. target, lang, config, stripImplicitDirs, appendAllImplicitDirs);
  1137. dirs.reserve(dirs.size() + tmp.size());
  1138. for (BT<std::string>& v : tmp) {
  1139. dirs.emplace_back(std::move(v.Value));
  1140. }
  1141. }
  1142. std::vector<BT<std::string>> cmLocalGenerator::GetIncludeDirectories(
  1143. cmGeneratorTarget const* target, std::string const& lang,
  1144. std::string const& config) const
  1145. {
  1146. return this->GetIncludeDirectoriesImplicit(target, lang, config);
  1147. }
  1148. void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
  1149. cmGeneratorTarget const* target,
  1150. const std::string& lang,
  1151. const std::string& config) const
  1152. {
  1153. this->GetIncludeDirectoriesImplicit(dirs, target, lang, config);
  1154. }
  1155. void cmLocalGenerator::GetStaticLibraryFlags(std::string& flags,
  1156. std::string const& config,
  1157. std::string const& linkLanguage,
  1158. cmGeneratorTarget* target)
  1159. {
  1160. std::vector<BT<std::string>> tmpFlags =
  1161. this->GetStaticLibraryFlags(config, linkLanguage, target);
  1162. this->AppendFlags(flags, tmpFlags);
  1163. }
  1164. std::vector<BT<std::string>> cmLocalGenerator::GetStaticLibraryFlags(
  1165. std::string const& config, std::string const& linkLanguage,
  1166. cmGeneratorTarget* target)
  1167. {
  1168. std::vector<BT<std::string>> flags;
  1169. if (linkLanguage != "Swift") {
  1170. std::string staticLibFlags;
  1171. this->AppendFlags(
  1172. staticLibFlags,
  1173. this->Makefile->GetSafeDefinition("CMAKE_STATIC_LINKER_FLAGS"));
  1174. if (!config.empty()) {
  1175. std::string name = "CMAKE_STATIC_LINKER_FLAGS_" + config;
  1176. this->AppendFlags(staticLibFlags,
  1177. this->Makefile->GetSafeDefinition(name));
  1178. }
  1179. if (!staticLibFlags.empty()) {
  1180. flags.emplace_back(std::move(staticLibFlags));
  1181. }
  1182. }
  1183. std::string staticLibFlags;
  1184. this->AppendFlags(staticLibFlags,
  1185. target->GetSafeProperty("STATIC_LIBRARY_FLAGS"));
  1186. if (!config.empty()) {
  1187. std::string name = "STATIC_LIBRARY_FLAGS_" + config;
  1188. this->AppendFlags(staticLibFlags, target->GetSafeProperty(name));
  1189. }
  1190. if (!staticLibFlags.empty()) {
  1191. flags.emplace_back(std::move(staticLibFlags));
  1192. }
  1193. std::vector<BT<std::string>> staticLibOpts =
  1194. target->GetStaticLibraryLinkOptions(config, linkLanguage);
  1195. // STATIC_LIBRARY_OPTIONS are escaped.
  1196. this->AppendCompileOptions(flags, staticLibOpts);
  1197. return flags;
  1198. }
  1199. void cmLocalGenerator::GetTargetFlags(
  1200. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1201. std::string& linkLibs, std::string& flags, std::string& linkFlags,
  1202. std::string& frameworkPath, std::string& linkPath, cmGeneratorTarget* target)
  1203. {
  1204. std::vector<BT<std::string>> linkFlagsList;
  1205. std::vector<BT<std::string>> linkPathList;
  1206. std::vector<BT<std::string>> linkLibsList;
  1207. this->GetTargetFlags(linkLineComputer, config, linkLibsList, flags,
  1208. linkFlagsList, frameworkPath, linkPathList, target);
  1209. this->AppendFlags(linkFlags, linkFlagsList);
  1210. this->AppendFlags(linkPath, linkPathList);
  1211. this->AppendFlags(linkLibs, linkLibsList);
  1212. }
  1213. void cmLocalGenerator::GetTargetFlags(
  1214. cmLinkLineComputer* linkLineComputer, const std::string& config,
  1215. std::vector<BT<std::string>>& linkLibs, std::string& flags,
  1216. std::vector<BT<std::string>>& linkFlags, std::string& frameworkPath,
  1217. std::vector<BT<std::string>>& linkPath, cmGeneratorTarget* target)
  1218. {
  1219. const std::string buildType = cmSystemTools::UpperCase(config);
  1220. cmComputeLinkInformation* pcli = target->GetLinkInformation(config);
  1221. const char* libraryLinkVariable =
  1222. "CMAKE_SHARED_LINKER_FLAGS"; // default to shared library
  1223. const std::string linkLanguage =
  1224. linkLineComputer->GetLinkerLanguage(target, buildType);
  1225. switch (target->GetType()) {
  1226. case cmStateEnums::STATIC_LIBRARY:
  1227. linkFlags = this->GetStaticLibraryFlags(buildType, linkLanguage, target);
  1228. if (pcli && dynamic_cast<cmLinkLineDeviceComputer*>(linkLineComputer)) {
  1229. // Compute the required cuda device link libraries when
  1230. // resolving cuda device symbols
  1231. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1232. frameworkPath, linkPath);
  1233. }
  1234. break;
  1235. case cmStateEnums::MODULE_LIBRARY:
  1236. libraryLinkVariable = "CMAKE_MODULE_LINKER_FLAGS";
  1237. CM_FALLTHROUGH;
  1238. case cmStateEnums::SHARED_LIBRARY: {
  1239. std::string sharedLibFlags;
  1240. if (linkLanguage != "Swift") {
  1241. sharedLibFlags = cmStrCat(
  1242. this->Makefile->GetSafeDefinition(libraryLinkVariable), ' ');
  1243. if (!buildType.empty()) {
  1244. std::string build = cmStrCat(libraryLinkVariable, '_', buildType);
  1245. sharedLibFlags += this->Makefile->GetSafeDefinition(build);
  1246. sharedLibFlags += " ";
  1247. }
  1248. if (this->Makefile->IsOn("WIN32") &&
  1249. !(this->Makefile->IsOn("CYGWIN") ||
  1250. this->Makefile->IsOn("MINGW"))) {
  1251. std::vector<cmSourceFile*> sources;
  1252. target->GetSourceFiles(sources, buildType);
  1253. std::string defFlag =
  1254. this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  1255. for (cmSourceFile* sf : sources) {
  1256. if (sf->GetExtension() == "def") {
  1257. sharedLibFlags += defFlag;
  1258. sharedLibFlags += this->ConvertToOutputFormat(
  1259. cmSystemTools::CollapseFullPath(sf->ResolveFullPath()), SHELL);
  1260. sharedLibFlags += " ";
  1261. }
  1262. }
  1263. }
  1264. }
  1265. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1266. if (targetLinkFlags) {
  1267. sharedLibFlags += targetLinkFlags;
  1268. sharedLibFlags += " ";
  1269. }
  1270. if (!buildType.empty()) {
  1271. targetLinkFlags =
  1272. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1273. if (targetLinkFlags) {
  1274. sharedLibFlags += targetLinkFlags;
  1275. sharedLibFlags += " ";
  1276. }
  1277. }
  1278. if (!sharedLibFlags.empty()) {
  1279. linkFlags.emplace_back(std::move(sharedLibFlags));
  1280. }
  1281. std::vector<BT<std::string>> linkOpts =
  1282. target->GetLinkOptions(config, linkLanguage);
  1283. // LINK_OPTIONS are escaped.
  1284. this->AppendCompileOptions(linkFlags, linkOpts);
  1285. if (pcli) {
  1286. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1287. frameworkPath, linkPath);
  1288. }
  1289. } break;
  1290. case cmStateEnums::EXECUTABLE: {
  1291. std::string exeFlags;
  1292. if (linkLanguage != "Swift") {
  1293. exeFlags = this->Makefile->GetSafeDefinition("CMAKE_EXE_LINKER_FLAGS");
  1294. exeFlags += " ";
  1295. if (!buildType.empty()) {
  1296. exeFlags += this->Makefile->GetSafeDefinition(
  1297. cmStrCat("CMAKE_EXE_LINKER_FLAGS_", buildType));
  1298. exeFlags += " ";
  1299. }
  1300. if (linkLanguage.empty()) {
  1301. cmSystemTools::Error(
  1302. "CMake can not determine linker language for target: " +
  1303. target->GetName());
  1304. return;
  1305. }
  1306. if (target->GetPropertyAsBool("WIN32_EXECUTABLE")) {
  1307. exeFlags +=
  1308. this->Makefile->GetSafeDefinition("CMAKE_CREATE_WIN32_EXE");
  1309. exeFlags += " ";
  1310. } else {
  1311. exeFlags +=
  1312. this->Makefile->GetSafeDefinition("CMAKE_CREATE_CONSOLE_EXE");
  1313. exeFlags += " ";
  1314. }
  1315. if (target->IsExecutableWithExports()) {
  1316. exeFlags += this->Makefile->GetSafeDefinition(
  1317. cmStrCat("CMAKE_EXE_EXPORTS_", linkLanguage, "_FLAG"));
  1318. exeFlags += " ";
  1319. }
  1320. }
  1321. this->AddLanguageFlagsForLinking(flags, target, linkLanguage, buildType);
  1322. if (pcli) {
  1323. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibs,
  1324. frameworkPath, linkPath);
  1325. }
  1326. if (cmIsOn(this->Makefile->GetDefinition("BUILD_SHARED_LIBS"))) {
  1327. std::string sFlagVar = std::string("CMAKE_SHARED_BUILD_") +
  1328. linkLanguage + std::string("_FLAGS");
  1329. exeFlags += this->Makefile->GetSafeDefinition(sFlagVar);
  1330. exeFlags += " ";
  1331. }
  1332. std::string cmp0065Flags =
  1333. this->GetLinkLibsCMP0065(linkLanguage, *target);
  1334. if (!cmp0065Flags.empty()) {
  1335. exeFlags += cmp0065Flags;
  1336. exeFlags += " ";
  1337. }
  1338. const char* targetLinkFlags = target->GetProperty("LINK_FLAGS");
  1339. if (targetLinkFlags) {
  1340. exeFlags += targetLinkFlags;
  1341. exeFlags += " ";
  1342. }
  1343. if (!buildType.empty()) {
  1344. targetLinkFlags =
  1345. target->GetProperty(cmStrCat("LINK_FLAGS_", buildType));
  1346. if (targetLinkFlags) {
  1347. exeFlags += targetLinkFlags;
  1348. exeFlags += " ";
  1349. }
  1350. }
  1351. if (!exeFlags.empty()) {
  1352. linkFlags.emplace_back(std::move(exeFlags));
  1353. }
  1354. std::vector<BT<std::string>> linkOpts =
  1355. target->GetLinkOptions(config, linkLanguage);
  1356. // LINK_OPTIONS are escaped.
  1357. this->AppendCompileOptions(linkFlags, linkOpts);
  1358. } break;
  1359. default:
  1360. break;
  1361. }
  1362. std::string extraLinkFlags;
  1363. this->AppendPositionIndependentLinkerFlags(extraLinkFlags, target, config,
  1364. linkLanguage);
  1365. this->AppendIPOLinkerFlags(extraLinkFlags, target, config, linkLanguage);
  1366. if (!extraLinkFlags.empty()) {
  1367. linkFlags.emplace_back(std::move(extraLinkFlags));
  1368. }
  1369. }
  1370. void cmLocalGenerator::GetTargetCompileFlags(cmGeneratorTarget* target,
  1371. std::string const& config,
  1372. std::string const& lang,
  1373. std::string& flags)
  1374. {
  1375. std::vector<BT<std::string>> tmpFlags =
  1376. this->GetTargetCompileFlags(target, config, lang);
  1377. this->AppendFlags(flags, tmpFlags);
  1378. }
  1379. std::vector<BT<std::string>> cmLocalGenerator::GetTargetCompileFlags(
  1380. cmGeneratorTarget* target, std::string const& config,
  1381. std::string const& lang)
  1382. {
  1383. std::vector<BT<std::string>> flags;
  1384. std::string compileFlags;
  1385. cmMakefile* mf = this->GetMakefile();
  1386. // Add language-specific flags.
  1387. this->AddLanguageFlags(compileFlags, target, lang, config);
  1388. if (target->IsIPOEnabled(lang, config)) {
  1389. this->AppendFeatureOptions(compileFlags, lang, "IPO");
  1390. }
  1391. this->AddArchitectureFlags(compileFlags, target, lang, config);
  1392. if (lang == "Fortran") {
  1393. this->AppendFlags(compileFlags,
  1394. this->GetTargetFortranFlags(target, config));
  1395. }
  1396. this->AddCMP0018Flags(compileFlags, target, lang, config);
  1397. this->AddVisibilityPresetFlags(compileFlags, target, lang);
  1398. this->AppendFlags(compileFlags, mf->GetDefineFlags());
  1399. this->AppendFlags(compileFlags,
  1400. this->GetFrameworkFlags(lang, config, target));
  1401. if (!compileFlags.empty()) {
  1402. flags.emplace_back(std::move(compileFlags));
  1403. }
  1404. this->AddCompileOptions(flags, target, lang, config);
  1405. return flags;
  1406. }
  1407. static std::string GetFrameworkFlags(const std::string& lang,
  1408. const std::string& config,
  1409. cmGeneratorTarget* target)
  1410. {
  1411. cmLocalGenerator* lg = target->GetLocalGenerator();
  1412. cmMakefile* mf = lg->GetMakefile();
  1413. if (!mf->IsOn("APPLE")) {
  1414. return std::string();
  1415. }
  1416. std::string fwSearchFlagVar = "CMAKE_" + lang + "_FRAMEWORK_SEARCH_FLAG";
  1417. const char* fwSearchFlag = mf->GetDefinition(fwSearchFlagVar);
  1418. if (!(fwSearchFlag && *fwSearchFlag)) {
  1419. return std::string();
  1420. }
  1421. std::set<std::string> emitted;
  1422. #ifdef __APPLE__ /* don't insert this when crosscompiling e.g. to iphone */
  1423. emitted.insert("/System/Library/Frameworks");
  1424. #endif
  1425. std::vector<std::string> includes;
  1426. lg->GetIncludeDirectories(includes, target, "C", config);
  1427. // check all include directories for frameworks as this
  1428. // will already have added a -F for the framework
  1429. for (std::string const& include : includes) {
  1430. if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
  1431. std::string frameworkDir = cmStrCat(include, "/../");
  1432. frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
  1433. emitted.insert(frameworkDir);
  1434. }
  1435. }
  1436. std::string flags;
  1437. if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
  1438. std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
  1439. for (std::string const& framework : frameworks) {
  1440. if (emitted.insert(framework).second) {
  1441. flags += fwSearchFlag;
  1442. flags +=
  1443. lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
  1444. flags += " ";
  1445. }
  1446. }
  1447. }
  1448. return flags;
  1449. }
  1450. std::string cmLocalGenerator::GetFrameworkFlags(std::string const& l,
  1451. std::string const& config,
  1452. cmGeneratorTarget* target)
  1453. {
  1454. return ::GetFrameworkFlags(l, config, target);
  1455. }
  1456. void cmLocalGenerator::GetTargetDefines(cmGeneratorTarget const* target,
  1457. std::string const& config,
  1458. std::string const& lang,
  1459. std::set<std::string>& defines) const
  1460. {
  1461. std::set<BT<std::string>> tmp = this->GetTargetDefines(target, config, lang);
  1462. for (BT<std::string> const& v : tmp) {
  1463. defines.emplace(v.Value);
  1464. }
  1465. }
  1466. std::set<BT<std::string>> cmLocalGenerator::GetTargetDefines(
  1467. cmGeneratorTarget const* target, std::string const& config,
  1468. std::string const& lang) const
  1469. {
  1470. std::set<BT<std::string>> defines;
  1471. // Add the export symbol definition for shared library objects.
  1472. if (const std::string* exportMacro = target->GetExportMacro()) {
  1473. this->AppendDefines(defines, *exportMacro);
  1474. }
  1475. // Add preprocessor definitions for this target and configuration.
  1476. std::vector<BT<std::string>> targetDefines =
  1477. target->GetCompileDefinitions(config, lang);
  1478. this->AppendDefines(defines, targetDefines);
  1479. return defines;
  1480. }
  1481. std::string cmLocalGenerator::GetTargetFortranFlags(
  1482. cmGeneratorTarget const* /*unused*/, std::string const& /*unused*/)
  1483. {
  1484. // Implemented by specific generators that override this.
  1485. return std::string();
  1486. }
  1487. /**
  1488. * Output the linking rules on a command line. For executables,
  1489. * targetLibrary should be a NULL pointer. For libraries, it should point
  1490. * to the name of the library. This will not link a library against itself.
  1491. */
  1492. void cmLocalGenerator::OutputLinkLibraries(
  1493. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1494. std::string& linkLibraries, std::string& frameworkPath,
  1495. std::string& linkPath)
  1496. {
  1497. std::vector<BT<std::string>> linkLibrariesList;
  1498. std::vector<BT<std::string>> linkPathList;
  1499. this->OutputLinkLibraries(pcli, linkLineComputer, linkLibrariesList,
  1500. frameworkPath, linkPathList);
  1501. pcli->AppendValues(linkLibraries, linkLibrariesList);
  1502. pcli->AppendValues(linkPath, linkPathList);
  1503. }
  1504. void cmLocalGenerator::OutputLinkLibraries(
  1505. cmComputeLinkInformation* pcli, cmLinkLineComputer* linkLineComputer,
  1506. std::vector<BT<std::string>>& linkLibraries, std::string& frameworkPath,
  1507. std::vector<BT<std::string>>& linkPath)
  1508. {
  1509. cmComputeLinkInformation& cli = *pcli;
  1510. std::string linkLanguage = cli.GetLinkLanguage();
  1511. std::string libPathFlag;
  1512. if (const char* value = this->Makefile->GetDefinition(
  1513. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_FLAG")) {
  1514. libPathFlag = value;
  1515. } else {
  1516. libPathFlag =
  1517. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_FLAG");
  1518. }
  1519. std::string libPathTerminator;
  1520. if (const char* value = this->Makefile->GetDefinition(
  1521. "CMAKE_" + cli.GetLinkLanguage() + "_LIBRARY_PATH_TERMINATOR")) {
  1522. libPathTerminator = value;
  1523. } else {
  1524. libPathTerminator =
  1525. this->Makefile->GetRequiredDefinition("CMAKE_LIBRARY_PATH_TERMINATOR");
  1526. }
  1527. // Add standard libraries for this language.
  1528. std::string stdLibString = this->Makefile->GetSafeDefinition(
  1529. cmStrCat("CMAKE_", cli.GetLinkLanguage(), "_STANDARD_LIBRARIES"));
  1530. // Append the framework search path flags.
  1531. std::string fwSearchFlag = this->Makefile->GetSafeDefinition(
  1532. cmStrCat("CMAKE_", linkLanguage, "_FRAMEWORK_SEARCH_FLAG"));
  1533. frameworkPath = linkLineComputer->ComputeFrameworkPath(cli, fwSearchFlag);
  1534. linkLineComputer->ComputeLinkPath(cli, libPathFlag, libPathTerminator,
  1535. linkPath);
  1536. linkLineComputer->ComputeLinkLibraries(cli, stdLibString, linkLibraries);
  1537. }
  1538. std::string cmLocalGenerator::GetLinkLibsCMP0065(
  1539. std::string const& linkLanguage, cmGeneratorTarget& tgt) const
  1540. {
  1541. std::string linkFlags;
  1542. // Flags to link an executable to shared libraries.
  1543. if (tgt.GetType() == cmStateEnums::EXECUTABLE &&
  1544. this->StateSnapshot.GetState()->GetGlobalPropertyAsBool(
  1545. "TARGET_SUPPORTS_SHARED_LIBS")) {
  1546. bool add_shlib_flags = false;
  1547. switch (tgt.GetPolicyStatusCMP0065()) {
  1548. case cmPolicies::WARN:
  1549. if (!tgt.GetPropertyAsBool("ENABLE_EXPORTS") &&
  1550. this->Makefile->PolicyOptionalWarningEnabled(
  1551. "CMAKE_POLICY_WARNING_CMP0065")) {
  1552. std::ostringstream w;
  1553. /* clang-format off */
  1554. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0065) << "\n"
  1555. "For compatibility with older versions of CMake, "
  1556. "additional flags may be added to export symbols on all "
  1557. "executables regardless of their ENABLE_EXPORTS property.";
  1558. /* clang-format on */
  1559. this->IssueMessage(MessageType::AUTHOR_WARNING, w.str());
  1560. }
  1561. CM_FALLTHROUGH;
  1562. case cmPolicies::OLD:
  1563. // OLD behavior is to always add the flags, except on AIX where
  1564. // we compute symbol exports if ENABLE_EXPORTS is on.
  1565. add_shlib_flags =
  1566. !(tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS"));
  1567. break;
  1568. case cmPolicies::REQUIRED_IF_USED:
  1569. case cmPolicies::REQUIRED_ALWAYS:
  1570. this->IssueMessage(
  1571. MessageType::FATAL_ERROR,
  1572. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0065));
  1573. CM_FALLTHROUGH;
  1574. case cmPolicies::NEW:
  1575. // NEW behavior is to only add the flags if ENABLE_EXPORTS is on,
  1576. // except on AIX where we compute symbol exports.
  1577. add_shlib_flags =
  1578. !tgt.Target->IsAIX() && tgt.GetPropertyAsBool("ENABLE_EXPORTS");
  1579. break;
  1580. }
  1581. if (add_shlib_flags) {
  1582. linkFlags = this->Makefile->GetSafeDefinition(
  1583. cmStrCat("CMAKE_SHARED_LIBRARY_LINK_", linkLanguage, "_FLAGS"));
  1584. }
  1585. }
  1586. return linkFlags;
  1587. }
  1588. void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
  1589. cmGeneratorTarget const* target,
  1590. const std::string& lang,
  1591. const std::string& config)
  1592. {
  1593. // Only add Apple specific flags on Apple platforms
  1594. if (this->Makefile->IsOn("APPLE") && this->EmitUniversalBinaryFlags) {
  1595. std::vector<std::string> archs;
  1596. target->GetAppleArchs(config, archs);
  1597. if (!archs.empty() && !lang.empty() &&
  1598. (lang[0] == 'C' || lang[0] == 'F' || lang[0] == 'O')) {
  1599. for (std::string const& arch : archs) {
  1600. flags += " -arch ";
  1601. flags += arch;
  1602. }
  1603. }
  1604. const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
  1605. if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
  1606. sysroot = nullptr;
  1607. }
  1608. std::string sysrootFlagVar =
  1609. std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
  1610. const char* sysrootFlag = this->Makefile->GetDefinition(sysrootFlagVar);
  1611. if (sysrootFlag && *sysrootFlag) {
  1612. std::vector<std::string> arch_sysroots;
  1613. if (const char* arch_sysroots_str =
  1614. this->Makefile->GetDefinition("CMAKE_APPLE_ARCH_SYSROOTS")) {
  1615. cmExpandList(std::string(arch_sysroots_str), arch_sysroots, true);
  1616. }
  1617. if (!arch_sysroots.empty()) {
  1618. assert(arch_sysroots.size() == archs.size());
  1619. for (size_t i = 0; i < archs.size(); ++i) {
  1620. if (arch_sysroots[i].empty()) {
  1621. continue;
  1622. }
  1623. flags += " -Xarch_" + archs[i] + " ";
  1624. // Combine sysroot flag and path to work with -Xarch
  1625. std::string arch_sysroot = sysrootFlag + arch_sysroots[i];
  1626. flags += this->ConvertToOutputFormat(arch_sysroot, SHELL);
  1627. }
  1628. } else if (sysroot && *sysroot) {
  1629. flags += " ";
  1630. flags += sysrootFlag;
  1631. flags += " ";
  1632. flags += this->ConvertToOutputFormat(sysroot, SHELL);
  1633. }
  1634. }
  1635. const char* deploymentTarget =
  1636. this->Makefile->GetDefinition("CMAKE_OSX_DEPLOYMENT_TARGET");
  1637. std::string deploymentTargetFlagVar =
  1638. std::string("CMAKE_") + lang + "_OSX_DEPLOYMENT_TARGET_FLAG";
  1639. const char* deploymentTargetFlag =
  1640. this->Makefile->GetDefinition(deploymentTargetFlagVar);
  1641. if (deploymentTargetFlag && *deploymentTargetFlag && deploymentTarget &&
  1642. *deploymentTarget) {
  1643. flags += " ";
  1644. flags += deploymentTargetFlag;
  1645. flags += deploymentTarget;
  1646. }
  1647. }
  1648. }
  1649. void cmLocalGenerator::AddLanguageFlags(std::string& flags,
  1650. cmGeneratorTarget const* target,
  1651. const std::string& lang,
  1652. const std::string& config)
  1653. {
  1654. // Add language-specific flags.
  1655. this->AddConfigVariableFlags(flags, cmStrCat("CMAKE_", lang, "_FLAGS"),
  1656. config);
  1657. if (lang == "Swift") {
  1658. if (const char* v = target->GetProperty("Swift_LANGUAGE_VERSION")) {
  1659. if (cmSystemTools::VersionCompare(
  1660. cmSystemTools::OP_GREATER_EQUAL,
  1661. this->Makefile->GetDefinition("CMAKE_Swift_COMPILER_VERSION"),
  1662. "4.2")) {
  1663. this->AppendFlags(flags, "-swift-version " + std::string(v));
  1664. }
  1665. }
  1666. }
  1667. // Add MSVC runtime library flags. This is activated by the presence
  1668. // of a default selection whether or not it is overridden by a property.
  1669. const char* msvcRuntimeLibraryDefault =
  1670. this->Makefile->GetDefinition("CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT");
  1671. if (msvcRuntimeLibraryDefault && *msvcRuntimeLibraryDefault) {
  1672. const char* msvcRuntimeLibraryValue =
  1673. target->GetProperty("MSVC_RUNTIME_LIBRARY");
  1674. if (!msvcRuntimeLibraryValue) {
  1675. msvcRuntimeLibraryValue = msvcRuntimeLibraryDefault;
  1676. }
  1677. std::string const msvcRuntimeLibrary = cmGeneratorExpression::Evaluate(
  1678. msvcRuntimeLibraryValue, this, config, target);
  1679. if (!msvcRuntimeLibrary.empty()) {
  1680. if (const char* msvcRuntimeLibraryOptions =
  1681. this->Makefile->GetDefinition(
  1682. "CMAKE_" + lang + "_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_" +
  1683. msvcRuntimeLibrary)) {
  1684. this->AppendCompileOptions(flags, msvcRuntimeLibraryOptions);
  1685. } else if ((this->Makefile->GetSafeDefinition(
  1686. "CMAKE_" + lang + "_COMPILER_ID") == "MSVC" ||
  1687. this->Makefile->GetSafeDefinition(
  1688. "CMAKE_" + lang + "_SIMULATE_ID") == "MSVC") &&
  1689. !cmSystemTools::GetErrorOccuredFlag()) {
  1690. // The compiler uses the MSVC ABI so it needs a known runtime library.
  1691. this->IssueMessage(MessageType::FATAL_ERROR,
  1692. "MSVC_RUNTIME_LIBRARY value '" +
  1693. msvcRuntimeLibrary + "' not known for this " +
  1694. lang + " compiler.");
  1695. }
  1696. }
  1697. }
  1698. }
  1699. void cmLocalGenerator::AddLanguageFlagsForLinking(
  1700. std::string& flags, cmGeneratorTarget const* target, const std::string& lang,
  1701. const std::string& config)
  1702. {
  1703. if (this->Makefile->IsOn("CMAKE_" + lang +
  1704. "_LINK_WITH_STANDARD_COMPILE_OPTION")) {
  1705. // This toolchain requires use of the language standard flag
  1706. // when linking in order to use the matching standard library.
  1707. // FIXME: If CMake gains an abstraction for standard library
  1708. // selection, this will have to be reconciled with it.
  1709. this->AddCompilerRequirementFlag(flags, target, lang);
  1710. }
  1711. this->AddLanguageFlags(flags, target, lang, config);
  1712. if (target->IsIPOEnabled(lang, config)) {
  1713. this->AppendFeatureOptions(flags, lang, "IPO");
  1714. }
  1715. }
  1716. cmGeneratorTarget* cmLocalGenerator::FindGeneratorTargetToUse(
  1717. const std::string& name) const
  1718. {
  1719. auto imported = this->ImportedGeneratorTargets.find(name);
  1720. if (imported != this->ImportedGeneratorTargets.end()) {
  1721. return imported->second;
  1722. }
  1723. if (cmGeneratorTarget* t = this->FindLocalNonAliasGeneratorTarget(name)) {
  1724. return t;
  1725. }
  1726. return this->GetGlobalGenerator()->FindGeneratorTarget(name);
  1727. }
  1728. bool cmLocalGenerator::GetRealDependency(const std::string& inName,
  1729. const std::string& config,
  1730. std::string& dep)
  1731. {
  1732. // Older CMake code may specify the dependency using the target
  1733. // output file rather than the target name. Such code would have
  1734. // been written before there was support for target properties that
  1735. // modify the name so stripping down to just the file name should
  1736. // produce the target name in this case.
  1737. std::string name = cmSystemTools::GetFilenameName(inName);
  1738. // If the input name is the empty string, there is no real
  1739. // dependency. Short-circuit the other checks:
  1740. if (name.empty()) {
  1741. return false;
  1742. }
  1743. if (cmSystemTools::GetFilenameLastExtension(name) == ".exe") {
  1744. name = cmSystemTools::GetFilenameWithoutLastExtension(name);
  1745. }
  1746. // Look for a CMake target with the given name.
  1747. if (cmGeneratorTarget* target = this->FindGeneratorTargetToUse(name)) {
  1748. // make sure it is not just a coincidence that the target name
  1749. // found is part of the inName
  1750. if (cmSystemTools::FileIsFullPath(inName)) {
  1751. std::string tLocation;
  1752. if (target->GetType() >= cmStateEnums::EXECUTABLE &&
  1753. target->GetType() <= cmStateEnums::MODULE_LIBRARY) {
  1754. tLocation = target->GetLocation(config);
  1755. tLocation = cmSystemTools::GetFilenamePath(tLocation);
  1756. tLocation = cmSystemTools::CollapseFullPath(tLocation);
  1757. }
  1758. std::string depLocation =
  1759. cmSystemTools::GetFilenamePath(std::string(inName));
  1760. depLocation = cmSystemTools::CollapseFullPath(depLocation);
  1761. if (depLocation != tLocation) {
  1762. // it is a full path to a depend that has the same name
  1763. // as a target but is in a different location so do not use
  1764. // the target as the depend
  1765. dep = inName;
  1766. return true;
  1767. }
  1768. }
  1769. switch (target->GetType()) {
  1770. case cmStateEnums::EXECUTABLE:
  1771. case cmStateEnums::STATIC_LIBRARY:
  1772. case cmStateEnums::SHARED_LIBRARY:
  1773. case cmStateEnums::MODULE_LIBRARY:
  1774. case cmStateEnums::UNKNOWN_LIBRARY:
  1775. dep = target->GetLocation(config);
  1776. return true;
  1777. case cmStateEnums::OBJECT_LIBRARY:
  1778. // An object library has no single file on which to depend.
  1779. // This was listed to get the target-level dependency.
  1780. return false;
  1781. case cmStateEnums::INTERFACE_LIBRARY:
  1782. // An interface library has no file on which to depend.
  1783. // This was listed to get the target-level dependency.
  1784. return false;
  1785. case cmStateEnums::UTILITY:
  1786. case cmStateEnums::GLOBAL_TARGET:
  1787. // A utility target has no file on which to depend. This was listed
  1788. // only to get the target-level dependency.
  1789. return false;
  1790. }
  1791. }
  1792. // The name was not that of a CMake target. It must name a file.
  1793. if (cmSystemTools::FileIsFullPath(inName)) {
  1794. // This is a full path. Return it as given.
  1795. dep = inName;
  1796. return true;
  1797. }
  1798. // Check for a source file in this directory that matches the
  1799. // dependency.
  1800. if (cmSourceFile* sf = this->Makefile->GetSource(inName)) {
  1801. dep = sf->ResolveFullPath();
  1802. return true;
  1803. }
  1804. // Treat the name as relative to the source directory in which it
  1805. // was given.
  1806. dep = cmStrCat(this->GetCurrentSourceDirectory(), '/', inName);
  1807. // If the in-source path does not exist, assume it instead lives in the
  1808. // binary directory.
  1809. if (!cmSystemTools::FileExists(dep)) {
  1810. dep = cmStrCat(this->GetCurrentBinaryDirectory(), '/', inName);
  1811. }
  1812. return true;
  1813. }
  1814. void cmLocalGenerator::AddSharedFlags(std::string& flags,
  1815. const std::string& lang, bool shared)
  1816. {
  1817. std::string flagsVar;
  1818. // Add flags for dealing with shared libraries for this language.
  1819. if (shared) {
  1820. this->AppendFlags(flags,
  1821. this->Makefile->GetSafeDefinition(
  1822. cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS")));
  1823. }
  1824. }
  1825. void cmLocalGenerator::AddCompilerRequirementFlag(
  1826. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  1827. {
  1828. if (lang.empty()) {
  1829. return;
  1830. }
  1831. const char* defaultStd =
  1832. this->Makefile->GetDefinition("CMAKE_" + lang + "_STANDARD_DEFAULT");
  1833. if (!defaultStd || !*defaultStd) {
  1834. // This compiler has no notion of language standard levels.
  1835. return;
  1836. }
  1837. std::string extProp = lang + "_EXTENSIONS";
  1838. bool ext = true;
  1839. if (const char* extPropValue = target->GetProperty(extProp)) {
  1840. if (cmIsOff(extPropValue)) {
  1841. ext = false;
  1842. }
  1843. }
  1844. std::string stdProp = lang + "_STANDARD";
  1845. const char* standardProp = target->GetProperty(stdProp);
  1846. if (!standardProp) {
  1847. if (ext) {
  1848. // No language standard is specified and extensions are not disabled.
  1849. // Check if this compiler needs a flag to enable extensions.
  1850. std::string const option_flag =
  1851. "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
  1852. if (const char* opt =
  1853. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1854. std::vector<std::string> optVec = cmExpandedList(opt);
  1855. for (std::string const& i : optVec) {
  1856. this->AppendFlagEscape(flags, i);
  1857. }
  1858. }
  1859. }
  1860. return;
  1861. }
  1862. std::string const type = ext ? "EXTENSION" : "STANDARD";
  1863. if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
  1864. std::string option_flag =
  1865. "CMAKE_" + lang + standardProp + "_" + type + "_COMPILE_OPTION";
  1866. const char* opt =
  1867. target->Target->GetMakefile()->GetDefinition(option_flag);
  1868. if (!opt) {
  1869. std::ostringstream e;
  1870. e << "Target \"" << target->GetName()
  1871. << "\" requires the language "
  1872. "dialect \""
  1873. << lang << standardProp << "\" "
  1874. << (ext ? "(with compiler extensions)" : "")
  1875. << ", but CMake "
  1876. "does not know the compile flags to use to enable it.";
  1877. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  1878. } else {
  1879. std::vector<std::string> optVec = cmExpandedList(opt);
  1880. for (std::string const& i : optVec) {
  1881. this->AppendFlagEscape(flags, i);
  1882. }
  1883. }
  1884. return;
  1885. }
  1886. static std::map<std::string, std::vector<std::string>> langStdMap;
  1887. if (langStdMap.empty()) {
  1888. // Maintain sorted order, most recent first.
  1889. langStdMap["CXX"].emplace_back("20");
  1890. langStdMap["CXX"].emplace_back("17");
  1891. langStdMap["CXX"].emplace_back("14");
  1892. langStdMap["CXX"].emplace_back("11");
  1893. langStdMap["CXX"].emplace_back("98");
  1894. langStdMap["OBJCXX"].emplace_back("20");
  1895. langStdMap["OBJCXX"].emplace_back("17");
  1896. langStdMap["OBJCXX"].emplace_back("14");
  1897. langStdMap["OBJCXX"].emplace_back("11");
  1898. langStdMap["OBJCXX"].emplace_back("98");
  1899. langStdMap["C"].emplace_back("11");
  1900. langStdMap["C"].emplace_back("99");
  1901. langStdMap["C"].emplace_back("90");
  1902. langStdMap["OBJC"].emplace_back("11");
  1903. langStdMap["OBJC"].emplace_back("99");
  1904. langStdMap["OBJC"].emplace_back("90");
  1905. langStdMap["CUDA"].emplace_back("20");
  1906. langStdMap["CUDA"].emplace_back("17");
  1907. langStdMap["CUDA"].emplace_back("14");
  1908. langStdMap["CUDA"].emplace_back("11");
  1909. langStdMap["CUDA"].emplace_back("03");
  1910. }
  1911. std::string standard(standardProp);
  1912. if (lang == "CUDA" && standard == "98") {
  1913. standard = "03";
  1914. }
  1915. std::vector<std::string>& stds = langStdMap[lang];
  1916. auto stdIt = std::find(stds.begin(), stds.end(), standard);
  1917. if (stdIt == stds.end()) {
  1918. std::string e =
  1919. lang + "_STANDARD is set to invalid value '" + standard + "'";
  1920. this->GetGlobalGenerator()->GetCMakeInstance()->IssueMessage(
  1921. MessageType::FATAL_ERROR, e, target->GetBacktrace());
  1922. return;
  1923. }
  1924. auto defaultStdIt = std::find(stds.begin(), stds.end(), defaultStd);
  1925. if (defaultStdIt == stds.end()) {
  1926. std::string e = "CMAKE_" + lang +
  1927. "_STANDARD_DEFAULT is set to invalid value '" + std::string(defaultStd) +
  1928. "'";
  1929. this->IssueMessage(MessageType::INTERNAL_ERROR, e);
  1930. return;
  1931. }
  1932. // If the standard requested is older than the compiler's default
  1933. // then we need to use a flag to change it. The comparison is
  1934. // greater-or-equal because the standards are stored in backward
  1935. // chronological order.
  1936. if (stdIt >= defaultStdIt) {
  1937. std::string option_flag =
  1938. "CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
  1939. std::string const& opt =
  1940. target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
  1941. std::vector<std::string> optVec = cmExpandedList(opt);
  1942. for (std::string const& i : optVec) {
  1943. this->AppendFlagEscape(flags, i);
  1944. }
  1945. return;
  1946. }
  1947. // The standard requested is at least as new as the compiler's default,
  1948. // and the standard request is not required. Decay to the newest standard
  1949. // for which a flag is defined.
  1950. for (; stdIt < defaultStdIt; ++stdIt) {
  1951. std::string option_flag =
  1952. cmStrCat("CMAKE_", lang, *stdIt, "_", type, "_COMPILE_OPTION");
  1953. if (const char* opt =
  1954. target->Target->GetMakefile()->GetDefinition(option_flag)) {
  1955. std::vector<std::string> optVec = cmExpandedList(opt);
  1956. for (std::string const& i : optVec) {
  1957. this->AppendFlagEscape(flags, i);
  1958. }
  1959. return;
  1960. }
  1961. }
  1962. }
  1963. static void AddVisibilityCompileOption(std::string& flags,
  1964. cmGeneratorTarget const* target,
  1965. cmLocalGenerator* lg,
  1966. const std::string& lang,
  1967. std::string* warnCMP0063)
  1968. {
  1969. std::string compileOption = "CMAKE_" + lang + "_COMPILE_OPTIONS_VISIBILITY";
  1970. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  1971. if (!opt) {
  1972. return;
  1973. }
  1974. std::string flagDefine = lang + "_VISIBILITY_PRESET";
  1975. const char* prop = target->GetProperty(flagDefine);
  1976. if (!prop) {
  1977. return;
  1978. }
  1979. if (warnCMP0063) {
  1980. *warnCMP0063 += " " + flagDefine + "\n";
  1981. return;
  1982. }
  1983. if (strcmp(prop, "hidden") != 0 && strcmp(prop, "default") != 0 &&
  1984. strcmp(prop, "protected") != 0 && strcmp(prop, "internal") != 0) {
  1985. std::ostringstream e;
  1986. e << "Target " << target->GetName() << " uses unsupported value \"" << prop
  1987. << "\" for " << flagDefine << "."
  1988. << " The supported values are: default, hidden, protected, and "
  1989. "internal.";
  1990. cmSystemTools::Error(e.str());
  1991. return;
  1992. }
  1993. std::string option = std::string(opt) + prop;
  1994. lg->AppendFlags(flags, option);
  1995. }
  1996. static void AddInlineVisibilityCompileOption(std::string& flags,
  1997. cmGeneratorTarget const* target,
  1998. cmLocalGenerator* lg,
  1999. std::string* warnCMP0063,
  2000. const std::string& lang)
  2001. {
  2002. std::string compileOption =
  2003. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN");
  2004. const char* opt = lg->GetMakefile()->GetDefinition(compileOption);
  2005. if (!opt) {
  2006. return;
  2007. }
  2008. bool prop = target->GetPropertyAsBool("VISIBILITY_INLINES_HIDDEN");
  2009. if (!prop) {
  2010. return;
  2011. }
  2012. if (warnCMP0063) {
  2013. *warnCMP0063 += " VISIBILITY_INLINES_HIDDEN\n";
  2014. return;
  2015. }
  2016. lg->AppendFlags(flags, opt);
  2017. }
  2018. void cmLocalGenerator::AddVisibilityPresetFlags(
  2019. std::string& flags, cmGeneratorTarget const* target, const std::string& lang)
  2020. {
  2021. if (lang.empty()) {
  2022. return;
  2023. }
  2024. std::string warnCMP0063;
  2025. std::string* pWarnCMP0063 = nullptr;
  2026. if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
  2027. target->GetType() != cmStateEnums::MODULE_LIBRARY &&
  2028. !target->IsExecutableWithExports()) {
  2029. switch (target->GetPolicyStatusCMP0063()) {
  2030. case cmPolicies::OLD:
  2031. return;
  2032. case cmPolicies::WARN:
  2033. pWarnCMP0063 = &warnCMP0063;
  2034. break;
  2035. default:
  2036. break;
  2037. }
  2038. }
  2039. AddVisibilityCompileOption(flags, target, this, lang, pWarnCMP0063);
  2040. if (lang == "CXX" || lang == "OBJCXX") {
  2041. AddInlineVisibilityCompileOption(flags, target, this, pWarnCMP0063, lang);
  2042. }
  2043. if (!warnCMP0063.empty() && this->WarnCMP0063.insert(target).second) {
  2044. std::ostringstream w;
  2045. /* clang-format off */
  2046. w <<
  2047. cmPolicies::GetPolicyWarning(cmPolicies::CMP0063) << "\n"
  2048. "Target \"" << target->GetName() << "\" of "
  2049. "type \"" << cmState::GetTargetTypeName(target->GetType()) << "\" "
  2050. "has the following visibility properties set for " << lang << ":\n" <<
  2051. warnCMP0063 <<
  2052. "For compatibility CMake is not honoring them for this target.";
  2053. /* clang-format on */
  2054. target->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
  2055. MessageType::AUTHOR_WARNING, w.str(), target->GetBacktrace());
  2056. }
  2057. }
  2058. void cmLocalGenerator::AddCMP0018Flags(std::string& flags,
  2059. cmGeneratorTarget const* target,
  2060. std::string const& lang,
  2061. const std::string& config)
  2062. {
  2063. int targetType = target->GetType();
  2064. bool shared = ((targetType == cmStateEnums::SHARED_LIBRARY) ||
  2065. (targetType == cmStateEnums::MODULE_LIBRARY));
  2066. if (this->GetShouldUseOldFlags(shared, lang)) {
  2067. this->AddSharedFlags(flags, lang, shared);
  2068. } else {
  2069. if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
  2070. if (target->GetPropertyAsBool("POSITION_INDEPENDENT_CODE")) {
  2071. this->AddPositionIndependentFlags(flags, lang, targetType);
  2072. }
  2073. return;
  2074. }
  2075. if (target->GetLinkInterfaceDependentBoolProperty(
  2076. "POSITION_INDEPENDENT_CODE", config)) {
  2077. this->AddPositionIndependentFlags(flags, lang, targetType);
  2078. }
  2079. if (shared) {
  2080. this->AppendFeatureOptions(flags, lang, "DLL");
  2081. }
  2082. }
  2083. }
  2084. bool cmLocalGenerator::GetShouldUseOldFlags(bool shared,
  2085. const std::string& lang) const
  2086. {
  2087. std::string originalFlags =
  2088. this->GlobalGenerator->GetSharedLibFlagsForLanguage(lang);
  2089. if (shared) {
  2090. std::string flagsVar = cmStrCat("CMAKE_SHARED_LIBRARY_", lang, "_FLAGS");
  2091. std::string const& flags = this->Makefile->GetSafeDefinition(flagsVar);
  2092. if (flags != originalFlags) {
  2093. switch (this->GetPolicyStatus(cmPolicies::CMP0018)) {
  2094. case cmPolicies::WARN: {
  2095. std::ostringstream e;
  2096. e << "Variable " << flagsVar
  2097. << " has been modified. CMake "
  2098. "will ignore the POSITION_INDEPENDENT_CODE target property for "
  2099. "shared libraries and will use the "
  2100. << flagsVar
  2101. << " variable "
  2102. "instead. This may cause errors if the original content of "
  2103. << flagsVar << " was removed.\n"
  2104. << cmPolicies::GetPolicyWarning(cmPolicies::CMP0018);
  2105. this->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  2106. CM_FALLTHROUGH;
  2107. }
  2108. case cmPolicies::OLD:
  2109. return true;
  2110. case cmPolicies::REQUIRED_IF_USED:
  2111. case cmPolicies::REQUIRED_ALWAYS:
  2112. case cmPolicies::NEW:
  2113. return false;
  2114. }
  2115. }
  2116. }
  2117. return false;
  2118. }
  2119. void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
  2120. std::string const& lang,
  2121. int targetType)
  2122. {
  2123. std::string picFlags;
  2124. if (targetType == cmStateEnums::EXECUTABLE) {
  2125. picFlags = this->Makefile->GetSafeDefinition(
  2126. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIE"));
  2127. }
  2128. if (picFlags.empty()) {
  2129. picFlags = this->Makefile->GetSafeDefinition(
  2130. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_PIC"));
  2131. }
  2132. if (!picFlags.empty()) {
  2133. std::vector<std::string> options = cmExpandedList(picFlags);
  2134. for (std::string const& o : options) {
  2135. this->AppendFlagEscape(flags, o);
  2136. }
  2137. }
  2138. }
  2139. void cmLocalGenerator::AddConfigVariableFlags(std::string& flags,
  2140. const std::string& var,
  2141. const std::string& config)
  2142. {
  2143. // Add the flags from the variable itself.
  2144. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(var));
  2145. // Add the flags from the build-type specific variable.
  2146. if (!config.empty()) {
  2147. const std::string flagsVar =
  2148. cmStrCat(var, '_', cmSystemTools::UpperCase(config));
  2149. this->AppendFlags(flags, this->Makefile->GetSafeDefinition(flagsVar));
  2150. }
  2151. }
  2152. void cmLocalGenerator::AppendFlags(std::string& flags,
  2153. const std::string& newFlags) const
  2154. {
  2155. if (!newFlags.empty()) {
  2156. if (!flags.empty()) {
  2157. flags += " ";
  2158. }
  2159. flags += newFlags;
  2160. }
  2161. }
  2162. void cmLocalGenerator::AppendFlags(
  2163. std::string& flags, const std::vector<BT<std::string>>& newFlags) const
  2164. {
  2165. for (BT<std::string> const& flag : newFlags) {
  2166. this->AppendFlags(flags, flag.Value);
  2167. }
  2168. }
  2169. void cmLocalGenerator::AppendFlagEscape(std::string& flags,
  2170. const std::string& rawFlag) const
  2171. {
  2172. this->AppendFlags(
  2173. flags,
  2174. this->EscapeForShell(rawFlag, false, false, false, this->IsNinjaMulti()));
  2175. }
  2176. void cmLocalGenerator::AddPchDependencies(cmGeneratorTarget* target)
  2177. {
  2178. // FIXME: Handle all configurations in multi-config generators.
  2179. std::string config;
  2180. if (!this->GetGlobalGenerator()->IsMultiConfig()) {
  2181. config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2182. }
  2183. const std::string buildType = cmSystemTools::UpperCase(config);
  2184. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2185. std::vector<cmSourceFile*> sources;
  2186. target->GetSourceFiles(sources, buildType);
  2187. for (const std::string& lang : { "C", "CXX", "OBJC", "OBJCXX" }) {
  2188. auto langSources =
  2189. std::count_if(sources.begin(), sources.end(), [lang](cmSourceFile* sf) {
  2190. return lang == sf->GetLanguage() &&
  2191. !sf->GetProperty("SKIP_PRECOMPILE_HEADERS");
  2192. });
  2193. if (langSources == 0) {
  2194. continue;
  2195. }
  2196. const std::string pchSource = target->GetPchSource(config, lang);
  2197. const std::string pchHeader = target->GetPchHeader(config, lang);
  2198. if (pchSource.empty() || pchHeader.empty()) {
  2199. continue;
  2200. }
  2201. const std::string pchExtension =
  2202. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2203. if (pchExtension.empty()) {
  2204. continue;
  2205. }
  2206. const char* pchReuseFrom =
  2207. target->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2208. auto pch_sf = this->Makefile->GetOrCreateSource(
  2209. pchSource, false, cmSourceFileLocationKind::Known);
  2210. if (!this->GetGlobalGenerator()->IsXcode()) {
  2211. if (!pchReuseFrom) {
  2212. target->AddSource(pchSource, true);
  2213. }
  2214. const std::string pchFile = target->GetPchFile(config, lang);
  2215. // Exclude the pch files from linking
  2216. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2217. if (!pchReuseFrom) {
  2218. pch_sf->SetProperty("OBJECT_OUTPUTS", pchFile.c_str());
  2219. } else {
  2220. auto reuseTarget =
  2221. this->GlobalGenerator->FindGeneratorTarget(pchReuseFrom);
  2222. if (this->Makefile->IsOn("CMAKE_PCH_COPY_COMPILE_PDB")) {
  2223. const std::string pdb_prefix =
  2224. this->GetGlobalGenerator()->IsMultiConfig()
  2225. ? cmStrCat(this->GlobalGenerator->GetCMakeCFGIntDir(), "/")
  2226. : "";
  2227. const std::string target_compile_pdb_dir = cmStrCat(
  2228. target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2229. target->GetName(), ".dir/");
  2230. const std::string copy_script =
  2231. cmStrCat(target_compile_pdb_dir, "copy_idb_pdb.cmake");
  2232. cmGeneratedFileStream file(copy_script);
  2233. file << "# CMake generated file\n";
  2234. for (auto extension : { ".pdb", ".idb" }) {
  2235. const std::string from_file = cmStrCat(
  2236. reuseTarget->GetLocalGenerator()->GetCurrentBinaryDirectory(),
  2237. "/", pchReuseFrom, ".dir/${PDB_PREFIX}", pchReuseFrom,
  2238. extension);
  2239. const std::string to_dir = cmStrCat(
  2240. target->GetLocalGenerator()->GetCurrentBinaryDirectory(), "/",
  2241. target->GetName(), ".dir/${PDB_PREFIX}");
  2242. const std::string to_file =
  2243. cmStrCat(to_dir, pchReuseFrom, extension);
  2244. std::string dest_file = to_file;
  2245. const std::string prefix = target->GetSafeProperty("PREFIX");
  2246. if (!prefix.empty()) {
  2247. dest_file = cmStrCat(to_dir, prefix, pchReuseFrom, extension);
  2248. }
  2249. file << "if (EXISTS \"" << from_file << "\" AND \"" << from_file
  2250. << "\" IS_NEWER_THAN \"" << dest_file << "\")\n";
  2251. file << " file(COPY \"" << from_file << "\""
  2252. << " DESTINATION \"" << to_dir << "\")\n";
  2253. if (!prefix.empty()) {
  2254. file << " file(REMOVE \"" << dest_file << "\")\n";
  2255. file << " file(RENAME \"" << to_file << "\" \"" << dest_file
  2256. << "\")\n";
  2257. }
  2258. file << "endif()\n";
  2259. }
  2260. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  2261. { cmSystemTools::GetCMakeCommand(),
  2262. cmStrCat("-DPDB_PREFIX=", pdb_prefix), "-P", copy_script });
  2263. const std::string no_main_dependency;
  2264. const std::vector<std::string> no_deps;
  2265. const char* no_message = "";
  2266. const char* no_current_dir = nullptr;
  2267. std::vector<std::string> no_byproducts;
  2268. std::vector<std::string> outputs;
  2269. outputs.push_back(cmStrCat(target_compile_pdb_dir, pdb_prefix,
  2270. pchReuseFrom, ".pdb"));
  2271. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2272. this->AddCustomCommandToTarget(
  2273. target->GetName(), outputs, no_deps, commandLines,
  2274. cmCustomCommandType::PRE_BUILD, no_message, no_current_dir);
  2275. } else {
  2276. cmImplicitDependsList no_implicit_depends;
  2277. cmSourceFile* copy_rule = this->AddCustomCommandToOutput(
  2278. outputs, no_byproducts, no_deps, no_main_dependency,
  2279. no_implicit_depends, commandLines, no_message, no_current_dir);
  2280. if (copy_rule) {
  2281. target->AddSource(copy_rule->ResolveFullPath());
  2282. }
  2283. }
  2284. target->Target->SetProperty("COMPILE_PDB_OUTPUT_DIRECTORY",
  2285. target_compile_pdb_dir);
  2286. }
  2287. std::string pchSourceObj =
  2288. reuseTarget->GetPchFileObject(config, lang);
  2289. // Link to the pch object file
  2290. target->Target->AppendProperty(
  2291. "LINK_FLAGS",
  2292. cmStrCat(" ", this->ConvertToOutputFormat(pchSourceObj, SHELL)),
  2293. true);
  2294. }
  2295. } else {
  2296. pch_sf->SetProperty("PCH_EXTENSION", pchExtension.c_str());
  2297. }
  2298. // Add pchHeader to source files, which will
  2299. // be grouped as "Precompile Header File"
  2300. auto pchHeader_sf = this->Makefile->GetOrCreateSource(
  2301. pchHeader, false, cmSourceFileLocationKind::Known);
  2302. std::string err;
  2303. pchHeader_sf->ResolveFullPath(&err);
  2304. target->AddSource(pchHeader);
  2305. }
  2306. }
  2307. }
  2308. void cmLocalGenerator::AddUnityBuild(cmGeneratorTarget* target)
  2309. {
  2310. if (!target->GetPropertyAsBool("UNITY_BUILD")) {
  2311. return;
  2312. }
  2313. // FIXME: Handle all configurations in multi-config generators.
  2314. std::string config;
  2315. if (!this->GetGlobalGenerator()->IsMultiConfig()) {
  2316. config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  2317. }
  2318. const std::string buildType = cmSystemTools::UpperCase(config);
  2319. std::string filename_base =
  2320. cmStrCat(this->GetCurrentBinaryDirectory(), "/CMakeFiles/",
  2321. target->GetName(), ".dir/Unity/");
  2322. // FIXME: Refactor collection of sources to not evaluate object libraries.
  2323. std::vector<cmSourceFile*> sources;
  2324. target->GetSourceFiles(sources, buildType);
  2325. auto batchSizeString = target->GetProperty("UNITY_BUILD_BATCH_SIZE");
  2326. const size_t unityBatchSize =
  2327. static_cast<size_t>(std::atoi(batchSizeString));
  2328. auto beforeInclude = target->GetProperty("UNITY_BUILD_CODE_BEFORE_INCLUDE");
  2329. auto afterInclude = target->GetProperty("UNITY_BUILD_CODE_AFTER_INCLUDE");
  2330. for (std::string lang : { "C", "CXX" }) {
  2331. std::vector<cmSourceFile*> filtered_sources;
  2332. std::copy_if(sources.begin(), sources.end(),
  2333. std::back_inserter(filtered_sources), [&](cmSourceFile* sf) {
  2334. return sf->GetLanguage() == lang &&
  2335. !sf->GetPropertyAsBool("SKIP_UNITY_BUILD_INCLUSION") &&
  2336. !sf->GetPropertyAsBool("HEADER_FILE_ONLY") &&
  2337. !sf->GetProperty("COMPILE_OPTIONS") &&
  2338. !sf->GetProperty("COMPILE_DEFINITIONS") &&
  2339. !sf->GetProperty("COMPILE_FLAGS") &&
  2340. !sf->GetProperty("INCLUDE_DIRECTORIES");
  2341. });
  2342. size_t batchSize = unityBatchSize;
  2343. if (unityBatchSize == 0) {
  2344. batchSize = filtered_sources.size();
  2345. }
  2346. for (size_t itemsLeft = filtered_sources.size(), chunk, batch = 0;
  2347. itemsLeft > 0; itemsLeft -= chunk, ++batch) {
  2348. chunk = std::min(itemsLeft, batchSize);
  2349. std::string filename = cmStrCat(filename_base, "unity_", batch,
  2350. (lang == "C") ? "_c.c" : "_cxx.cxx");
  2351. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2352. {
  2353. size_t begin = batch * batchSize;
  2354. size_t end = begin + chunk;
  2355. cmGeneratedFileStream file(
  2356. filename_tmp, false,
  2357. this->GetGlobalGenerator()->GetMakefileEncoding());
  2358. file << "/* generated by CMake */\n\n";
  2359. for (; begin != end; ++begin) {
  2360. cmSourceFile* sf = filtered_sources[begin];
  2361. target->AddSourceFileToUnityBatch(sf->ResolveFullPath());
  2362. sf->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2363. if (beforeInclude) {
  2364. file << beforeInclude << "\n";
  2365. }
  2366. file << "#include \"" << sf->ResolveFullPath() << "\"\n";
  2367. if (afterInclude) {
  2368. file << afterInclude << "\n";
  2369. }
  2370. }
  2371. }
  2372. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2373. target->AddSource(filename, true);
  2374. auto unity = this->Makefile->GetOrCreateSource(filename);
  2375. unity->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "ON");
  2376. unity->SetProperty("UNITY_SOURCE_FILE", filename.c_str());
  2377. }
  2378. }
  2379. }
  2380. void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
  2381. cmGeneratorTarget* target,
  2382. const std::string& config,
  2383. const std::string& lang)
  2384. {
  2385. if (!target->IsIPOEnabled(lang, config)) {
  2386. return;
  2387. }
  2388. switch (target->GetType()) {
  2389. case cmStateEnums::EXECUTABLE:
  2390. case cmStateEnums::SHARED_LIBRARY:
  2391. case cmStateEnums::MODULE_LIBRARY:
  2392. break;
  2393. default:
  2394. return;
  2395. }
  2396. const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
  2397. const char* rawFlagsList = this->Makefile->GetDefinition(name);
  2398. if (rawFlagsList == nullptr) {
  2399. return;
  2400. }
  2401. std::vector<std::string> flagsList = cmExpandedList(rawFlagsList);
  2402. for (std::string const& o : flagsList) {
  2403. this->AppendFlagEscape(flags, o);
  2404. }
  2405. }
  2406. void cmLocalGenerator::AppendPositionIndependentLinkerFlags(
  2407. std::string& flags, cmGeneratorTarget* target, const std::string& config,
  2408. const std::string& lang)
  2409. {
  2410. // For now, only EXECUTABLE is concerned
  2411. if (target->GetType() != cmStateEnums::EXECUTABLE) {
  2412. return;
  2413. }
  2414. const char* PICValue = target->GetLinkPIEProperty(config);
  2415. if (PICValue == nullptr) {
  2416. // POSITION_INDEPENDENT_CODE is not set
  2417. return;
  2418. }
  2419. const std::string mode = cmIsOn(PICValue) ? "PIE" : "NO_PIE";
  2420. std::string supported = "CMAKE_" + lang + "_LINK_" + mode + "_SUPPORTED";
  2421. if (cmIsOff(this->Makefile->GetDefinition(supported))) {
  2422. return;
  2423. }
  2424. std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_" + mode;
  2425. auto pieFlags = this->Makefile->GetSafeDefinition(name);
  2426. if (pieFlags.empty()) {
  2427. return;
  2428. }
  2429. std::vector<std::string> flagsList = cmExpandedList(pieFlags);
  2430. for (const auto& flag : flagsList) {
  2431. this->AppendFlagEscape(flags, flag);
  2432. }
  2433. }
  2434. void cmLocalGenerator::AppendCompileOptions(std::string& options,
  2435. const char* options_list,
  2436. const char* regex) const
  2437. {
  2438. // Short-circuit if there are no options.
  2439. if (!options_list) {
  2440. return;
  2441. }
  2442. // Expand the list of options.
  2443. std::vector<std::string> options_vec = cmExpandedList(options_list);
  2444. this->AppendCompileOptions(options, options_vec, regex);
  2445. }
  2446. void cmLocalGenerator::AppendCompileOptions(
  2447. std::string& options, const std::vector<std::string>& options_vec,
  2448. const char* regex) const
  2449. {
  2450. if (regex != nullptr) {
  2451. // Filter flags upon specified reges.
  2452. cmsys::RegularExpression r(regex);
  2453. for (std::string const& opt : options_vec) {
  2454. if (r.find(opt)) {
  2455. this->AppendFlagEscape(options, opt);
  2456. }
  2457. }
  2458. } else {
  2459. for (std::string const& opt : options_vec) {
  2460. this->AppendFlagEscape(options, opt);
  2461. }
  2462. }
  2463. }
  2464. void cmLocalGenerator::AppendCompileOptions(
  2465. std::vector<BT<std::string>>& options,
  2466. const std::vector<BT<std::string>>& options_vec, const char* regex) const
  2467. {
  2468. if (regex != nullptr) {
  2469. // Filter flags upon specified regular expressions.
  2470. cmsys::RegularExpression r(regex);
  2471. for (BT<std::string> const& opt : options_vec) {
  2472. if (r.find(opt.Value)) {
  2473. std::string flag;
  2474. this->AppendFlagEscape(flag, opt.Value);
  2475. options.emplace_back(std::move(flag), opt.Backtrace);
  2476. }
  2477. }
  2478. } else {
  2479. for (BT<std::string> const& opt : options_vec) {
  2480. std::string flag;
  2481. this->AppendFlagEscape(flag, opt.Value);
  2482. options.emplace_back(std::move(flag), opt.Backtrace);
  2483. }
  2484. }
  2485. }
  2486. void cmLocalGenerator::AppendIncludeDirectories(
  2487. std::vector<std::string>& includes, const char* includes_list,
  2488. const cmSourceFile& sourceFile) const
  2489. {
  2490. // Short-circuit if there are no includes.
  2491. if (!includes_list) {
  2492. return;
  2493. }
  2494. // Expand the list of includes.
  2495. std::vector<std::string> includes_vec = cmExpandedList(includes_list);
  2496. this->AppendIncludeDirectories(includes, includes_vec, sourceFile);
  2497. }
  2498. void cmLocalGenerator::AppendIncludeDirectories(
  2499. std::vector<std::string>& includes,
  2500. const std::vector<std::string>& includes_vec,
  2501. const cmSourceFile& sourceFile) const
  2502. {
  2503. std::unordered_set<std::string> uniqueIncludes;
  2504. for (const std::string& include : includes_vec) {
  2505. if (!cmSystemTools::FileIsFullPath(include)) {
  2506. std::ostringstream e;
  2507. e << "Found relative path while evaluating include directories of "
  2508. "\""
  2509. << sourceFile.GetLocation().GetName() << "\":\n \"" << include
  2510. << "\"\n";
  2511. this->IssueMessage(MessageType::FATAL_ERROR, e.str());
  2512. return;
  2513. }
  2514. std::string inc = include;
  2515. if (!cmIsOff(inc)) {
  2516. cmSystemTools::ConvertToUnixSlashes(inc);
  2517. }
  2518. if (uniqueIncludes.insert(inc).second) {
  2519. includes.push_back(std::move(inc));
  2520. }
  2521. }
  2522. }
  2523. void cmLocalGenerator::AppendDefines(std::set<std::string>& defines,
  2524. std::string const& defines_list) const
  2525. {
  2526. std::set<BT<std::string>> tmp;
  2527. this->AppendDefines(tmp, ExpandListWithBacktrace(defines_list));
  2528. for (BT<std::string> const& i : tmp) {
  2529. defines.emplace(i.Value);
  2530. }
  2531. }
  2532. void cmLocalGenerator::AppendDefines(std::set<BT<std::string>>& defines,
  2533. std::string const& defines_list) const
  2534. {
  2535. // Short-circuit if there are no definitions.
  2536. if (defines_list.empty()) {
  2537. return;
  2538. }
  2539. // Expand the list of definitions.
  2540. this->AppendDefines(defines, ExpandListWithBacktrace(defines_list));
  2541. }
  2542. void cmLocalGenerator::AppendDefines(
  2543. std::set<BT<std::string>>& defines,
  2544. const std::vector<BT<std::string>>& defines_vec) const
  2545. {
  2546. for (BT<std::string> const& d : defines_vec) {
  2547. // Skip unsupported definitions.
  2548. if (!this->CheckDefinition(d.Value)) {
  2549. continue;
  2550. }
  2551. defines.insert(d);
  2552. }
  2553. }
  2554. void cmLocalGenerator::JoinDefines(const std::set<std::string>& defines,
  2555. std::string& definesString,
  2556. const std::string& lang)
  2557. {
  2558. // Lookup the define flag for the current language.
  2559. std::string dflag = "-D";
  2560. if (!lang.empty()) {
  2561. const char* df =
  2562. this->Makefile->GetDefinition(cmStrCat("CMAKE_", lang, "_DEFINE_FLAG"));
  2563. if (df && *df) {
  2564. dflag = df;
  2565. }
  2566. }
  2567. const char* itemSeparator = definesString.empty() ? "" : " ";
  2568. for (std::string const& define : defines) {
  2569. // Append the definition with proper escaping.
  2570. std::string def = dflag;
  2571. if (this->GetState()->UseWatcomWMake()) {
  2572. // The Watcom compiler does its own command line parsing instead
  2573. // of using the windows shell rules. Definitions are one of
  2574. // -DNAME
  2575. // -DNAME=<cpp-token>
  2576. // -DNAME="c-string with spaces and other characters(?@#$)"
  2577. //
  2578. // Watcom will properly parse each of these cases from the
  2579. // command line without any escapes. However we still have to
  2580. // get the '$' and '#' characters through WMake as '$$' and
  2581. // '$#'.
  2582. for (const char* c = define.c_str(); *c; ++c) {
  2583. if (*c == '$' || *c == '#') {
  2584. def += '$';
  2585. }
  2586. def += *c;
  2587. }
  2588. } else {
  2589. // Make the definition appear properly on the command line. Use
  2590. // -DNAME="value" instead of -D"NAME=value" for historical reasons.
  2591. std::string::size_type eq = define.find('=');
  2592. def += define.substr(0, eq);
  2593. if (eq != std::string::npos) {
  2594. def += "=";
  2595. def += this->EscapeForShell(define.substr(eq + 1), true);
  2596. }
  2597. }
  2598. definesString += itemSeparator;
  2599. itemSeparator = " ";
  2600. definesString += def;
  2601. }
  2602. }
  2603. void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
  2604. const std::string& lang,
  2605. const char* feature)
  2606. {
  2607. const char* optionList = this->Makefile->GetDefinition(
  2608. cmStrCat("CMAKE_", lang, "_COMPILE_OPTIONS_", feature));
  2609. if (optionList != nullptr) {
  2610. std::vector<std::string> options = cmExpandedList(optionList);
  2611. for (std::string const& o : options) {
  2612. this->AppendFlagEscape(flags, o);
  2613. }
  2614. }
  2615. }
  2616. const char* cmLocalGenerator::GetFeature(const std::string& feature,
  2617. const std::string& config)
  2618. {
  2619. std::string featureName = feature;
  2620. // TODO: Define accumulation policy for features (prepend, append, replace).
  2621. // Currently we always replace.
  2622. if (!config.empty()) {
  2623. featureName += "_";
  2624. featureName += cmSystemTools::UpperCase(config);
  2625. }
  2626. cmStateSnapshot snp = this->StateSnapshot;
  2627. while (snp.IsValid()) {
  2628. if (const char* value = snp.GetDirectory().GetProperty(featureName)) {
  2629. return value;
  2630. }
  2631. snp = snp.GetBuildsystemDirectoryParent();
  2632. }
  2633. return nullptr;
  2634. }
  2635. std::string cmLocalGenerator::GetProjectName() const
  2636. {
  2637. return this->StateSnapshot.GetProjectName();
  2638. }
  2639. std::string cmLocalGenerator::ConstructComment(
  2640. cmCustomCommandGenerator const& ccg, const char* default_comment)
  2641. {
  2642. // Check for a comment provided with the command.
  2643. if (ccg.GetComment()) {
  2644. return ccg.GetComment();
  2645. }
  2646. // Construct a reasonable default comment if possible.
  2647. if (!ccg.GetOutputs().empty()) {
  2648. std::string comment;
  2649. comment = "Generating ";
  2650. const char* sep = "";
  2651. std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
  2652. for (std::string const& o : ccg.GetOutputs()) {
  2653. comment += sep;
  2654. comment += this->MaybeConvertToRelativePath(currentBinaryDir, o);
  2655. sep = ", ";
  2656. }
  2657. return comment;
  2658. }
  2659. // Otherwise use the provided default.
  2660. return default_comment;
  2661. }
  2662. class cmInstallTargetGeneratorLocal : public cmInstallTargetGenerator
  2663. {
  2664. public:
  2665. cmInstallTargetGeneratorLocal(cmLocalGenerator* lg, std::string const& t,
  2666. const char* dest, bool implib)
  2667. : cmInstallTargetGenerator(
  2668. t, dest, implib, "", std::vector<std::string>(), "Unspecified",
  2669. cmInstallGenerator::SelectMessageLevel(lg->GetMakefile()), false,
  2670. false)
  2671. {
  2672. this->Compute(lg);
  2673. }
  2674. };
  2675. void cmLocalGenerator::GenerateTargetInstallRules(
  2676. std::ostream& os, const std::string& config,
  2677. std::vector<std::string> const& configurationTypes)
  2678. {
  2679. // Convert the old-style install specification from each target to
  2680. // an install generator and run it.
  2681. const auto& tgts = this->GetGeneratorTargets();
  2682. for (const auto& l : tgts) {
  2683. if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  2684. continue;
  2685. }
  2686. // Include the user-specified pre-install script for this target.
  2687. if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
  2688. cmInstallScriptGenerator g(preinstall, false, nullptr, false);
  2689. g.Generate(os, config, configurationTypes);
  2690. }
  2691. // Install this target if a destination is given.
  2692. if (!l->Target->GetInstallPath().empty()) {
  2693. // Compute the full install destination. Note that converting
  2694. // to unix slashes also removes any trailing slash.
  2695. // We also skip over the leading slash given by the user.
  2696. std::string destination = l->Target->GetInstallPath().substr(1);
  2697. cmSystemTools::ConvertToUnixSlashes(destination);
  2698. if (destination.empty()) {
  2699. destination = ".";
  2700. }
  2701. // Generate the proper install generator for this target type.
  2702. switch (l->GetType()) {
  2703. case cmStateEnums::EXECUTABLE:
  2704. case cmStateEnums::STATIC_LIBRARY:
  2705. case cmStateEnums::MODULE_LIBRARY: {
  2706. // Use a target install generator.
  2707. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2708. destination.c_str(), false);
  2709. g.Generate(os, config, configurationTypes);
  2710. } break;
  2711. case cmStateEnums::SHARED_LIBRARY: {
  2712. #if defined(_WIN32) || defined(__CYGWIN__)
  2713. // Special code to handle DLL. Install the import library
  2714. // to the normal destination and the DLL to the runtime
  2715. // destination.
  2716. cmInstallTargetGeneratorLocal g1(this, l->GetName(),
  2717. destination.c_str(), true);
  2718. g1.Generate(os, config, configurationTypes);
  2719. // We also skip over the leading slash given by the user.
  2720. destination = l->Target->GetRuntimeInstallPath().substr(1);
  2721. cmSystemTools::ConvertToUnixSlashes(destination);
  2722. cmInstallTargetGeneratorLocal g2(this, l->GetName(),
  2723. destination.c_str(), false);
  2724. g2.Generate(os, config, configurationTypes);
  2725. #else
  2726. // Use a target install generator.
  2727. cmInstallTargetGeneratorLocal g(this, l->GetName(),
  2728. destination.c_str(), false);
  2729. g.Generate(os, config, configurationTypes);
  2730. #endif
  2731. } break;
  2732. default:
  2733. break;
  2734. }
  2735. }
  2736. // Include the user-specified post-install script for this target.
  2737. if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
  2738. cmInstallScriptGenerator g(postinstall, false, nullptr, false);
  2739. g.Generate(os, config, configurationTypes);
  2740. }
  2741. }
  2742. }
  2743. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2744. static bool cmLocalGeneratorShortenObjectName(std::string& objName,
  2745. std::string::size_type max_len)
  2746. {
  2747. // Replace the beginning of the path portion of the object name with
  2748. // its own md5 sum.
  2749. std::string::size_type pos =
  2750. objName.find('/', objName.size() - max_len + 32);
  2751. if (pos != std::string::npos) {
  2752. cmCryptoHash md5(cmCryptoHash::AlgoMD5);
  2753. std::string md5name = cmStrCat(md5.HashString(objName.substr(0, pos)),
  2754. cm::string_view(objName).substr(pos));
  2755. objName = md5name;
  2756. // The object name is now short enough.
  2757. return true;
  2758. }
  2759. // The object name could not be shortened enough.
  2760. return false;
  2761. }
  2762. bool cmLocalGeneratorCheckObjectName(std::string& objName,
  2763. std::string::size_type dir_len,
  2764. std::string::size_type max_total_len)
  2765. {
  2766. // Enforce the maximum file name length if possible.
  2767. std::string::size_type max_obj_len = max_total_len;
  2768. if (dir_len < max_total_len) {
  2769. max_obj_len = max_total_len - dir_len;
  2770. if (objName.size() > max_obj_len) {
  2771. // The current object file name is too long. Try to shorten it.
  2772. return cmLocalGeneratorShortenObjectName(objName, max_obj_len);
  2773. }
  2774. // The object file name is short enough.
  2775. return true;
  2776. }
  2777. // The build directory in which the object will be stored is
  2778. // already too deep.
  2779. return false;
  2780. }
  2781. #endif
  2782. std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
  2783. const std::string& sin, std::string const& dir_max)
  2784. {
  2785. // Look for an existing mapped name for this object file.
  2786. auto it = this->UniqueObjectNamesMap.find(sin);
  2787. // If no entry exists create one.
  2788. if (it == this->UniqueObjectNamesMap.end()) {
  2789. // Start with the original name.
  2790. std::string ssin = sin;
  2791. // Avoid full paths by removing leading slashes.
  2792. ssin.erase(0, ssin.find_first_not_of('/'));
  2793. // Avoid full paths by removing colons.
  2794. std::replace(ssin.begin(), ssin.end(), ':', '_');
  2795. // Avoid relative paths that go up the tree.
  2796. cmSystemTools::ReplaceString(ssin, "../", "__/");
  2797. // Avoid spaces.
  2798. std::replace(ssin.begin(), ssin.end(), ' ', '_');
  2799. // Mangle the name if necessary.
  2800. if (this->Makefile->IsOn("CMAKE_MANGLE_OBJECT_FILE_NAMES")) {
  2801. bool done;
  2802. int cc = 0;
  2803. char rpstr[100];
  2804. sprintf(rpstr, "_p_");
  2805. cmSystemTools::ReplaceString(ssin, "+", rpstr);
  2806. std::string sssin = sin;
  2807. do {
  2808. done = true;
  2809. for (it = this->UniqueObjectNamesMap.begin();
  2810. it != this->UniqueObjectNamesMap.end(); ++it) {
  2811. if (it->second == ssin) {
  2812. done = false;
  2813. }
  2814. }
  2815. if (done) {
  2816. break;
  2817. }
  2818. sssin = ssin;
  2819. cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
  2820. sprintf(rpstr, "_p%d_", cc++);
  2821. } while (!done);
  2822. }
  2823. #if defined(CM_LG_ENCODE_OBJECT_NAMES)
  2824. if (!cmLocalGeneratorCheckObjectName(ssin, dir_max.size(),
  2825. this->ObjectPathMax)) {
  2826. // Warn if this is the first time the path has been seen.
  2827. if (this->ObjectMaxPathViolations.insert(dir_max).second) {
  2828. std::ostringstream m;
  2829. /* clang-format off */
  2830. m << "The object file directory\n"
  2831. << " " << dir_max << "\n"
  2832. << "has " << dir_max.size() << " characters. "
  2833. << "The maximum full path to an object file is "
  2834. << this->ObjectPathMax << " characters "
  2835. << "(see CMAKE_OBJECT_PATH_MAX). "
  2836. << "Object file\n"
  2837. << " " << ssin << "\n"
  2838. << "cannot be safely placed under this directory. "
  2839. << "The build may not work correctly.";
  2840. /* clang-format on */
  2841. this->IssueMessage(MessageType::WARNING, m.str());
  2842. }
  2843. }
  2844. #else
  2845. (void)dir_max;
  2846. #endif
  2847. // Insert the newly mapped object file name.
  2848. std::map<std::string, std::string>::value_type e(sin, ssin);
  2849. it = this->UniqueObjectNamesMap.insert(e).first;
  2850. }
  2851. // Return the map entry.
  2852. return it->second;
  2853. }
  2854. void cmLocalGenerator::ComputeObjectFilenames(
  2855. std::map<cmSourceFile const*, std::string>& /*unused*/,
  2856. cmGeneratorTarget const* /*unused*/)
  2857. {
  2858. }
  2859. bool cmLocalGenerator::IsWindowsShell() const
  2860. {
  2861. return this->GetState()->UseWindowsShell();
  2862. }
  2863. bool cmLocalGenerator::IsWatcomWMake() const
  2864. {
  2865. return this->GetState()->UseWatcomWMake();
  2866. }
  2867. bool cmLocalGenerator::IsMinGWMake() const
  2868. {
  2869. return this->GetState()->UseMinGWMake();
  2870. }
  2871. bool cmLocalGenerator::IsNMake() const
  2872. {
  2873. return this->GetState()->UseNMake();
  2874. }
  2875. bool cmLocalGenerator::IsNinjaMulti() const
  2876. {
  2877. return this->GetState()->UseNinjaMulti();
  2878. }
  2879. std::string cmLocalGenerator::GetObjectFileNameWithoutTarget(
  2880. const cmSourceFile& source, std::string const& dir_max,
  2881. bool* hasSourceExtension, char const* customOutputExtension)
  2882. {
  2883. // Construct the object file name using the full path to the source
  2884. // file which is its only unique identification.
  2885. std::string const& fullPath = source.GetFullPath();
  2886. // Try referencing the source relative to the source tree.
  2887. std::string relFromSource = this->MaybeConvertToRelativePath(
  2888. this->GetCurrentSourceDirectory(), fullPath);
  2889. assert(!relFromSource.empty());
  2890. bool relSource = !cmSystemTools::FileIsFullPath(relFromSource);
  2891. bool subSource = relSource && relFromSource[0] != '.';
  2892. // Try referencing the source relative to the binary tree.
  2893. std::string relFromBinary = this->MaybeConvertToRelativePath(
  2894. this->GetCurrentBinaryDirectory(), fullPath);
  2895. assert(!relFromBinary.empty());
  2896. bool relBinary = !cmSystemTools::FileIsFullPath(relFromBinary);
  2897. bool subBinary = relBinary && relFromBinary[0] != '.';
  2898. // Select a nice-looking reference to the source file to construct
  2899. // the object file name.
  2900. std::string objectName;
  2901. if ((relSource && !relBinary) || (subSource && !subBinary)) {
  2902. objectName = relFromSource;
  2903. } else if ((relBinary && !relSource) || (subBinary && !subSource)) {
  2904. objectName = relFromBinary;
  2905. } else if (relFromBinary.length() < relFromSource.length()) {
  2906. objectName = relFromBinary;
  2907. } else {
  2908. objectName = relFromSource;
  2909. }
  2910. // if it is still a full path check for the try compile case
  2911. // try compile never have in source sources, and should not
  2912. // have conflicting source file names in the same target
  2913. if (cmSystemTools::FileIsFullPath(objectName)) {
  2914. if (this->GetGlobalGenerator()->GetCMakeInstance()->GetIsInTryCompile()) {
  2915. objectName = cmSystemTools::GetFilenameName(source.GetFullPath());
  2916. }
  2917. }
  2918. // Ensure that for the CMakeFiles/<target>.dir/generated_source_file
  2919. // we don't end up having:
  2920. // CMakeFiles/<target>.dir/CMakeFiles/<target>.dir/generated_source_file.obj
  2921. const char* unitySourceFile = source.GetProperty("UNITY_SOURCE_FILE");
  2922. const char* pchExtension = source.GetProperty("PCH_EXTENSION");
  2923. if (unitySourceFile || pchExtension) {
  2924. if (pchExtension) {
  2925. customOutputExtension = pchExtension;
  2926. }
  2927. cmsys::RegularExpression var("(CMakeFiles/[^/]+.dir/)");
  2928. if (var.find(objectName)) {
  2929. objectName.erase(var.start(), var.end() - var.start());
  2930. }
  2931. }
  2932. // Replace the original source file extension with the object file
  2933. // extension.
  2934. bool keptSourceExtension = true;
  2935. if (!source.GetPropertyAsBool("KEEP_EXTENSION")) {
  2936. // Decide whether this language wants to replace the source
  2937. // extension with the object extension. For CMake 2.4
  2938. // compatibility do this by default.
  2939. bool replaceExt = this->NeedBackwardsCompatibility_2_4();
  2940. if (!replaceExt) {
  2941. std::string lang = source.GetLanguage();
  2942. if (!lang.empty()) {
  2943. replaceExt = this->Makefile->IsOn(
  2944. cmStrCat("CMAKE_", lang, "_OUTPUT_EXTENSION_REPLACE"));
  2945. }
  2946. }
  2947. // Remove the source extension if it is to be replaced.
  2948. if (replaceExt || customOutputExtension) {
  2949. keptSourceExtension = false;
  2950. std::string::size_type dot_pos = objectName.rfind('.');
  2951. if (dot_pos != std::string::npos) {
  2952. objectName = objectName.substr(0, dot_pos);
  2953. }
  2954. }
  2955. // Store the new extension.
  2956. if (customOutputExtension) {
  2957. objectName += customOutputExtension;
  2958. } else {
  2959. objectName += this->GlobalGenerator->GetLanguageOutputExtension(source);
  2960. }
  2961. }
  2962. if (hasSourceExtension) {
  2963. *hasSourceExtension = keptSourceExtension;
  2964. }
  2965. // Convert to a safe name.
  2966. return this->CreateSafeUniqueObjectFileName(objectName, dir_max);
  2967. }
  2968. std::string cmLocalGenerator::GetSourceFileLanguage(const cmSourceFile& source)
  2969. {
  2970. return source.GetLanguage();
  2971. }
  2972. cmake* cmLocalGenerator::GetCMakeInstance() const
  2973. {
  2974. return this->GlobalGenerator->GetCMakeInstance();
  2975. }
  2976. std::string const& cmLocalGenerator::GetSourceDirectory() const
  2977. {
  2978. return this->GetCMakeInstance()->GetHomeDirectory();
  2979. }
  2980. std::string const& cmLocalGenerator::GetBinaryDirectory() const
  2981. {
  2982. return this->GetCMakeInstance()->GetHomeOutputDirectory();
  2983. }
  2984. std::string const& cmLocalGenerator::GetCurrentBinaryDirectory() const
  2985. {
  2986. return this->StateSnapshot.GetDirectory().GetCurrentBinary();
  2987. }
  2988. std::string const& cmLocalGenerator::GetCurrentSourceDirectory() const
  2989. {
  2990. return this->StateSnapshot.GetDirectory().GetCurrentSource();
  2991. }
  2992. std::string cmLocalGenerator::MaybeConvertToRelativePath(
  2993. std::string const& local_path, std::string const& remote_path) const
  2994. {
  2995. return this->StateSnapshot.GetDirectory().ConvertToRelPathIfNotContained(
  2996. local_path, remote_path);
  2997. }
  2998. std::string cmLocalGenerator::GetTargetDirectory(
  2999. const cmGeneratorTarget* /*unused*/) const
  3000. {
  3001. cmSystemTools::Error("GetTargetDirectory"
  3002. " called on cmLocalGenerator");
  3003. return "";
  3004. }
  3005. KWIML_INT_uint64_t cmLocalGenerator::GetBackwardsCompatibility()
  3006. {
  3007. // The computed version may change until the project is fully
  3008. // configured.
  3009. if (!this->BackwardsCompatibilityFinal) {
  3010. unsigned int major = 0;
  3011. unsigned int minor = 0;
  3012. unsigned int patch = 0;
  3013. if (const char* value =
  3014. this->Makefile->GetDefinition("CMAKE_BACKWARDS_COMPATIBILITY")) {
  3015. switch (sscanf(value, "%u.%u.%u", &major, &minor, &patch)) {
  3016. case 2:
  3017. patch = 0;
  3018. break;
  3019. case 1:
  3020. minor = 0;
  3021. patch = 0;
  3022. break;
  3023. default:
  3024. break;
  3025. }
  3026. }
  3027. this->BackwardsCompatibility = CMake_VERSION_ENCODE(major, minor, patch);
  3028. this->BackwardsCompatibilityFinal = true;
  3029. }
  3030. return this->BackwardsCompatibility;
  3031. }
  3032. bool cmLocalGenerator::NeedBackwardsCompatibility_2_4()
  3033. {
  3034. // Check the policy to decide whether to pay attention to this
  3035. // variable.
  3036. switch (this->GetPolicyStatus(cmPolicies::CMP0001)) {
  3037. case cmPolicies::WARN:
  3038. // WARN is just OLD without warning because user code does not
  3039. // always affect whether this check is done.
  3040. case cmPolicies::OLD:
  3041. // Old behavior is to check the variable.
  3042. break;
  3043. case cmPolicies::NEW:
  3044. // New behavior is to ignore the variable.
  3045. return false;
  3046. case cmPolicies::REQUIRED_IF_USED:
  3047. case cmPolicies::REQUIRED_ALWAYS:
  3048. // This will never be the case because the only way to require
  3049. // the setting is to require the user to specify version policy
  3050. // 2.6 or higher. Once we add that requirement then this whole
  3051. // method can be removed anyway.
  3052. return false;
  3053. }
  3054. // Compatibility is needed if CMAKE_BACKWARDS_COMPATIBILITY is set
  3055. // equal to or lower than the given version.
  3056. KWIML_INT_uint64_t actual_compat = this->GetBackwardsCompatibility();
  3057. return (actual_compat && actual_compat <= CMake_VERSION_ENCODE(2, 4, 255));
  3058. }
  3059. cmPolicies::PolicyStatus cmLocalGenerator::GetPolicyStatus(
  3060. cmPolicies::PolicyID id) const
  3061. {
  3062. return this->Makefile->GetPolicyStatus(id);
  3063. }
  3064. bool cmLocalGenerator::CheckDefinition(std::string const& define) const
  3065. {
  3066. // Many compilers do not support -DNAME(arg)=sdf so we disable it.
  3067. std::string::size_type pos = define.find_first_of("(=");
  3068. if (pos != std::string::npos) {
  3069. if (define[pos] == '(') {
  3070. std::ostringstream e;
  3071. /* clang-format off */
  3072. e << "WARNING: Function-style preprocessor definitions may not be "
  3073. << "passed on the compiler command line because many compilers "
  3074. << "do not support it.\n"
  3075. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3076. << "Consider defining the macro in a (configured) header file.\n";
  3077. /* clang-format on */
  3078. cmSystemTools::Message(e.str());
  3079. return false;
  3080. }
  3081. }
  3082. // Many compilers do not support # in the value so we disable it.
  3083. if (define.find_first_of('#') != std::string::npos) {
  3084. std::ostringstream e;
  3085. /* clang-format off */
  3086. e << "WARNING: Preprocessor definitions containing '#' may not be "
  3087. << "passed on the compiler command line because many compilers "
  3088. << "do not support it.\n"
  3089. << "CMake is dropping a preprocessor definition: " << define << "\n"
  3090. << "Consider defining the macro in a (configured) header file.\n";
  3091. /* clang-format on */
  3092. cmSystemTools::Message(e.str());
  3093. return false;
  3094. }
  3095. // Assume it is supported.
  3096. return true;
  3097. }
  3098. static void cmLGInfoProp(cmMakefile* mf, cmGeneratorTarget* target,
  3099. const std::string& prop)
  3100. {
  3101. if (const char* val = target->GetProperty(prop)) {
  3102. mf->AddDefinition(prop, val);
  3103. }
  3104. }
  3105. void cmLocalGenerator::GenerateAppleInfoPList(cmGeneratorTarget* target,
  3106. const std::string& targetName,
  3107. const std::string& fname)
  3108. {
  3109. // Find the Info.plist template.
  3110. const char* in = target->GetProperty("MACOSX_BUNDLE_INFO_PLIST");
  3111. std::string inFile = (in && *in) ? in : "MacOSXBundleInfo.plist.in";
  3112. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3113. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3114. if (!inMod.empty()) {
  3115. inFile = inMod;
  3116. }
  3117. }
  3118. if (!cmSystemTools::FileExists(inFile, true)) {
  3119. std::ostringstream e;
  3120. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3121. << "\" could not be found.";
  3122. cmSystemTools::Error(e.str());
  3123. return;
  3124. }
  3125. // Convert target properties to variables in an isolated makefile
  3126. // scope to configure the file. If properties are set they will
  3127. // override user make variables. If not the configuration will fall
  3128. // back to the directory-level values set by the user.
  3129. cmMakefile* mf = this->Makefile;
  3130. cmMakefile::ScopePushPop varScope(mf);
  3131. mf->AddDefinition("MACOSX_BUNDLE_EXECUTABLE_NAME", targetName);
  3132. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_INFO_STRING");
  3133. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_ICON_FILE");
  3134. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_GUI_IDENTIFIER");
  3135. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_LONG_VERSION_STRING");
  3136. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_NAME");
  3137. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_SHORT_VERSION_STRING");
  3138. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_BUNDLE_VERSION");
  3139. cmLGInfoProp(mf, target, "MACOSX_BUNDLE_COPYRIGHT");
  3140. mf->ConfigureFile(inFile, fname, false, false, false);
  3141. }
  3142. void cmLocalGenerator::GenerateFrameworkInfoPList(
  3143. cmGeneratorTarget* target, const std::string& targetName,
  3144. const std::string& fname)
  3145. {
  3146. // Find the Info.plist template.
  3147. const char* in = target->GetProperty("MACOSX_FRAMEWORK_INFO_PLIST");
  3148. std::string inFile = (in && *in) ? in : "MacOSXFrameworkInfo.plist.in";
  3149. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3150. std::string inMod = this->Makefile->GetModulesFile(inFile);
  3151. if (!inMod.empty()) {
  3152. inFile = inMod;
  3153. }
  3154. }
  3155. if (!cmSystemTools::FileExists(inFile, true)) {
  3156. std::ostringstream e;
  3157. e << "Target " << target->GetName() << " Info.plist template \"" << inFile
  3158. << "\" could not be found.";
  3159. cmSystemTools::Error(e.str());
  3160. return;
  3161. }
  3162. // Convert target properties to variables in an isolated makefile
  3163. // scope to configure the file. If properties are set they will
  3164. // override user make variables. If not the configuration will fall
  3165. // back to the directory-level values set by the user.
  3166. cmMakefile* mf = this->Makefile;
  3167. cmMakefile::ScopePushPop varScope(mf);
  3168. mf->AddDefinition("MACOSX_FRAMEWORK_NAME", targetName);
  3169. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_ICON_FILE");
  3170. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_IDENTIFIER");
  3171. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_SHORT_VERSION_STRING");
  3172. cmLGInfoProp(mf, target, "MACOSX_FRAMEWORK_BUNDLE_VERSION");
  3173. mf->ConfigureFile(inFile, fname, false, false, false);
  3174. }
  3175. namespace {
  3176. void CreateGeneratedSource(cmLocalGenerator& lg, const std::string& output,
  3177. cmCommandOrigin origin,
  3178. const cmListFileBacktrace& lfbt)
  3179. {
  3180. if (cmGeneratorExpression::Find(output) == std::string::npos) {
  3181. // Outputs without generator expressions from the project are already
  3182. // created and marked as generated. Do not mark them again, because
  3183. // other commands might have overwritten the property.
  3184. if (origin == cmCommandOrigin::Generator) {
  3185. lg.GetMakefile()->GetOrCreateGeneratedSource(output);
  3186. }
  3187. } else {
  3188. lg.GetCMakeInstance()->IssueMessage(
  3189. MessageType::FATAL_ERROR,
  3190. "Generator expressions in custom command outputs are not implemented!",
  3191. lfbt);
  3192. }
  3193. }
  3194. void CreateGeneratedSources(cmLocalGenerator& lg,
  3195. const std::vector<std::string>& outputs,
  3196. cmCommandOrigin origin,
  3197. const cmListFileBacktrace& lfbt)
  3198. {
  3199. for (std::string const& o : outputs) {
  3200. CreateGeneratedSource(lg, o, origin, lfbt);
  3201. }
  3202. }
  3203. cmSourceFile* AddCustomCommand(
  3204. cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3205. const std::vector<std::string>& outputs,
  3206. const std::vector<std::string>& byproducts,
  3207. const std::vector<std::string>& depends, const std::string& main_dependency,
  3208. const cmImplicitDependsList& implicit_depends,
  3209. const cmCustomCommandLines& commandLines, const char* comment,
  3210. const char* workingDir, bool replace, bool escapeOldStyle,
  3211. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  3212. const std::string& job_pool)
  3213. {
  3214. cmMakefile* mf = lg.GetMakefile();
  3215. // Choose a source file on which to store the custom command.
  3216. cmSourceFile* file = nullptr;
  3217. if (!commandLines.empty() && !main_dependency.empty()) {
  3218. // The main dependency was specified. Use it unless a different
  3219. // custom command already used it.
  3220. file = mf->GetSource(main_dependency);
  3221. if (file && file->GetCustomCommand() && !replace) {
  3222. // The main dependency already has a custom command.
  3223. if (commandLines == file->GetCustomCommand()->GetCommandLines()) {
  3224. // The existing custom command is identical. Silently ignore
  3225. // the duplicate.
  3226. return file;
  3227. }
  3228. // The existing custom command is different. We need to
  3229. // generate a rule file for this new command.
  3230. file = nullptr;
  3231. } else if (!file) {
  3232. file = mf->CreateSource(main_dependency);
  3233. }
  3234. }
  3235. // Generate a rule file if the main dependency is not available.
  3236. if (!file) {
  3237. cmGlobalGenerator* gg = lg.GetGlobalGenerator();
  3238. // Construct a rule file associated with the first output produced.
  3239. std::string outName = gg->GenerateRuleFile(outputs[0]);
  3240. // Check if the rule file already exists.
  3241. file = mf->GetSource(outName, cmSourceFileLocationKind::Known);
  3242. if (file && file->GetCustomCommand() && !replace) {
  3243. // The rule file already exists.
  3244. if (commandLines != file->GetCustomCommand()->GetCommandLines()) {
  3245. lg.GetCMakeInstance()->IssueMessage(
  3246. MessageType::FATAL_ERROR,
  3247. cmStrCat("Attempt to add a custom rule to output\n ", outName,
  3248. "\nwhich already has a custom rule."),
  3249. lfbt);
  3250. }
  3251. return file;
  3252. }
  3253. // Create a cmSourceFile for the rule file.
  3254. if (!file) {
  3255. file = mf->CreateSource(outName, true, cmSourceFileLocationKind::Known);
  3256. }
  3257. file->SetProperty("__CMAKE_RULE", "1");
  3258. }
  3259. // Attach the custom command to the file.
  3260. if (file) {
  3261. // Construct a complete list of dependencies.
  3262. std::vector<std::string> depends2(depends);
  3263. if (!main_dependency.empty()) {
  3264. depends2.push_back(main_dependency);
  3265. }
  3266. std::unique_ptr<cmCustomCommand> cc = cm::make_unique<cmCustomCommand>(
  3267. outputs, byproducts, depends2, commandLines, lfbt, comment, workingDir);
  3268. cc->SetEscapeOldStyle(escapeOldStyle);
  3269. cc->SetEscapeAllowMakeVars(true);
  3270. cc->SetImplicitDepends(implicit_depends);
  3271. cc->SetUsesTerminal(uses_terminal);
  3272. cc->SetCommandExpandLists(command_expand_lists);
  3273. cc->SetDepfile(depfile);
  3274. cc->SetJobPool(job_pool);
  3275. file->SetCustomCommand(std::move(cc));
  3276. mf->AddSourceOutputs(file, outputs, byproducts);
  3277. }
  3278. return file;
  3279. }
  3280. }
  3281. namespace detail {
  3282. void AddCustomCommandToTarget(cmLocalGenerator& lg,
  3283. const cmListFileBacktrace& lfbt,
  3284. cmCommandOrigin origin, cmTarget* target,
  3285. const std::vector<std::string>& byproducts,
  3286. const std::vector<std::string>& depends,
  3287. const cmCustomCommandLines& commandLines,
  3288. cmCustomCommandType type, const char* comment,
  3289. const char* workingDir, bool escapeOldStyle,
  3290. bool uses_terminal, const std::string& depfile,
  3291. const std::string& job_pool,
  3292. bool command_expand_lists)
  3293. {
  3294. cmMakefile* mf = lg.GetMakefile();
  3295. // Always create the byproduct sources and mark them generated.
  3296. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3297. // Add the command to the appropriate build step for the target.
  3298. std::vector<std::string> no_output;
  3299. cmCustomCommand cc(no_output, byproducts, depends, commandLines, lfbt,
  3300. comment, workingDir);
  3301. cc.SetEscapeOldStyle(escapeOldStyle);
  3302. cc.SetEscapeAllowMakeVars(true);
  3303. cc.SetUsesTerminal(uses_terminal);
  3304. cc.SetCommandExpandLists(command_expand_lists);
  3305. cc.SetDepfile(depfile);
  3306. cc.SetJobPool(job_pool);
  3307. switch (type) {
  3308. case cmCustomCommandType::PRE_BUILD:
  3309. target->AddPreBuildCommand(std::move(cc));
  3310. break;
  3311. case cmCustomCommandType::PRE_LINK:
  3312. target->AddPreLinkCommand(std::move(cc));
  3313. break;
  3314. case cmCustomCommandType::POST_BUILD:
  3315. target->AddPostBuildCommand(std::move(cc));
  3316. break;
  3317. }
  3318. mf->AddTargetByproducts(target, byproducts);
  3319. }
  3320. cmSourceFile* AddCustomCommandToOutput(
  3321. cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3322. cmCommandOrigin origin, const std::vector<std::string>& outputs,
  3323. const std::vector<std::string>& byproducts,
  3324. const std::vector<std::string>& depends, const std::string& main_dependency,
  3325. const cmImplicitDependsList& implicit_depends,
  3326. const cmCustomCommandLines& commandLines, const char* comment,
  3327. const char* workingDir, bool replace, bool escapeOldStyle,
  3328. bool uses_terminal, bool command_expand_lists, const std::string& depfile,
  3329. const std::string& job_pool)
  3330. {
  3331. // Always create the output sources and mark them generated.
  3332. CreateGeneratedSources(lg, outputs, origin, lfbt);
  3333. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3334. return AddCustomCommand(
  3335. lg, lfbt, outputs, byproducts, depends, main_dependency, implicit_depends,
  3336. commandLines, comment, workingDir, replace, escapeOldStyle, uses_terminal,
  3337. command_expand_lists, depfile, job_pool);
  3338. }
  3339. void AppendCustomCommandToOutput(cmLocalGenerator& lg,
  3340. const cmListFileBacktrace& lfbt,
  3341. const std::string& output,
  3342. const std::vector<std::string>& depends,
  3343. const cmImplicitDependsList& implicit_depends,
  3344. const cmCustomCommandLines& commandLines)
  3345. {
  3346. // Lookup an existing command.
  3347. if (cmSourceFile* sf = lg.GetMakefile()->GetSourceFileWithOutput(output)) {
  3348. if (cmCustomCommand* cc = sf->GetCustomCommand()) {
  3349. cc->AppendCommands(commandLines);
  3350. cc->AppendDepends(depends);
  3351. cc->AppendImplicitDepends(implicit_depends);
  3352. return;
  3353. }
  3354. }
  3355. // No existing command found.
  3356. lg.GetCMakeInstance()->IssueMessage(
  3357. MessageType::FATAL_ERROR,
  3358. cmStrCat("Attempt to append to output\n ", output,
  3359. "\nwhich is not already a custom command output."),
  3360. lfbt);
  3361. }
  3362. void AddUtilityCommand(cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  3363. cmCommandOrigin origin, cmTarget* target,
  3364. const cmUtilityOutput& force, const char* workingDir,
  3365. const std::vector<std::string>& byproducts,
  3366. const std::vector<std::string>& depends,
  3367. const cmCustomCommandLines& commandLines,
  3368. bool escapeOldStyle, const char* comment,
  3369. bool uses_terminal, bool command_expand_lists,
  3370. const std::string& job_pool)
  3371. {
  3372. // Always create the byproduct sources and mark them generated.
  3373. CreateGeneratedSource(lg, force.Name, origin, lfbt);
  3374. CreateGeneratedSources(lg, byproducts, origin, lfbt);
  3375. // Use an empty comment to avoid generation of default comment.
  3376. if (!comment) {
  3377. comment = "";
  3378. }
  3379. std::string no_main_dependency;
  3380. cmImplicitDependsList no_implicit_depends;
  3381. cmSourceFile* rule = AddCustomCommand(
  3382. lg, lfbt, { force.Name }, byproducts, depends, no_main_dependency,
  3383. no_implicit_depends, commandLines, comment, workingDir, /*replace=*/false,
  3384. escapeOldStyle, uses_terminal, command_expand_lists, /*depfile=*/"",
  3385. job_pool);
  3386. if (rule) {
  3387. lg.GetMakefile()->AddTargetByproducts(target, byproducts);
  3388. }
  3389. if (!force.NameCMP0049.empty()) {
  3390. target->AddSource(force.NameCMP0049);
  3391. }
  3392. }
  3393. }