cmLocalGenerator.cxx 132 KB

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