cmLocalGenerator.cxx 133 KB

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