cmFindPackageCommand.cxx 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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 "cmFindPackageCommand.h"
  4. #include "cmSystemTools.h"
  5. #include "cmsys/Directory.hxx"
  6. #include "cmsys/FStream.hxx"
  7. #include "cmsys/Glob.hxx"
  8. #include "cmsys/RegularExpression.hxx"
  9. #include "cmsys/String.h"
  10. #include <algorithm>
  11. #include <assert.h>
  12. #include <deque>
  13. #include <functional>
  14. #include <iterator>
  15. #include <sstream>
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <utility>
  19. #include "cm_memory.hxx"
  20. #include "cmAlgorithms.h"
  21. #include "cmMakefile.h"
  22. #include "cmMessageType.h"
  23. #include "cmPolicies.h"
  24. #include "cmRange.h"
  25. #include "cmSearchPath.h"
  26. #include "cmState.h"
  27. #include "cmStateTypes.h"
  28. #include "cmStringAlgorithms.h"
  29. #include "cmVersion.h"
  30. #if defined(__HAIKU__)
  31. # include <FindDirectory.h>
  32. # include <StorageDefs.h>
  33. #endif
  34. class cmExecutionStatus;
  35. class cmFileList;
  36. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  37. "PACKAGE_REGISTRY");
  38. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  39. "BUILDS");
  40. cmFindPackageCommand::PathLabel
  41. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  42. struct StrverscmpGreater
  43. {
  44. bool operator()(const std::string& lhs, const std::string& rhs) const
  45. {
  46. return cmSystemTools::strverscmp(lhs, rhs) > 0;
  47. }
  48. };
  49. struct StrverscmpLesser
  50. {
  51. bool operator()(const std::string& lhs, const std::string& rhs) const
  52. {
  53. return cmSystemTools::strverscmp(lhs, rhs) < 0;
  54. }
  55. };
  56. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  57. std::vector<std::string>::iterator end,
  58. SortOrderType order, SortDirectionType dir)
  59. {
  60. if (order == Name_order) {
  61. if (dir == Dec) {
  62. std::sort(begin, end, std::greater<std::string>());
  63. } else {
  64. std::sort(begin, end);
  65. }
  66. } else if (order == Natural)
  67. // natural order uses letters and numbers (contiguous numbers digit are
  68. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  69. {
  70. if (dir == Dec) {
  71. std::sort(begin, end, StrverscmpGreater());
  72. } else {
  73. std::sort(begin, end, StrverscmpLesser());
  74. }
  75. }
  76. // else do not sort
  77. }
  78. cmFindPackageCommand::cmFindPackageCommand()
  79. {
  80. this->CMakePathName = "PACKAGE";
  81. this->Quiet = false;
  82. this->Required = false;
  83. this->NoUserRegistry = false;
  84. this->NoSystemRegistry = false;
  85. this->UseConfigFiles = true;
  86. this->UseFindModules = true;
  87. this->DebugMode = false;
  88. this->UseLib32Paths = false;
  89. this->UseLib64Paths = false;
  90. this->UseLibx32Paths = false;
  91. this->UseRealPath = false;
  92. this->PolicyScope = true;
  93. this->VersionMajor = 0;
  94. this->VersionMinor = 0;
  95. this->VersionPatch = 0;
  96. this->VersionTweak = 0;
  97. this->VersionCount = 0;
  98. this->VersionExact = false;
  99. this->VersionFoundMajor = 0;
  100. this->VersionFoundMinor = 0;
  101. this->VersionFoundPatch = 0;
  102. this->VersionFoundTweak = 0;
  103. this->VersionFoundCount = 0;
  104. this->RequiredCMakeVersion = 0;
  105. this->SortOrder = None;
  106. this->SortDirection = Asc;
  107. this->AppendSearchPathGroups();
  108. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  109. }
  110. void cmFindPackageCommand::AppendSearchPathGroups()
  111. {
  112. std::vector<cmFindCommon::PathLabel>* labels;
  113. // Update the All group with new paths
  114. labels = &this->PathGroupLabelMap[PathGroup::All];
  115. labels->insert(
  116. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  117. PathLabel::UserRegistry);
  118. labels->insert(
  119. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  120. PathLabel::Builds);
  121. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  122. PathLabel::SystemRegistry);
  123. // Create the new path objects
  124. this->LabeledPaths.insert(
  125. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  126. this->LabeledPaths.insert(
  127. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  128. this->LabeledPaths.insert(
  129. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  130. }
  131. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
  132. cmExecutionStatus&)
  133. {
  134. if (args.empty()) {
  135. this->SetError("called with incorrect number of arguments");
  136. return false;
  137. }
  138. // Lookup required version of CMake.
  139. if (const char* rv =
  140. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  141. unsigned int v[3] = { 0, 0, 0 };
  142. sscanf(rv, "%u.%u.%u", &v[0], &v[1], &v[2]);
  143. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  144. }
  145. // Check for debug mode.
  146. this->DebugMode = this->Makefile->IsOn("CMAKE_FIND_DEBUG_MODE");
  147. // Lookup target architecture, if any.
  148. if (const char* arch =
  149. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  150. this->LibraryArchitecture = arch;
  151. }
  152. // Lookup whether lib32 paths should be used.
  153. if (this->Makefile->PlatformIs32Bit() &&
  154. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  155. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  156. this->UseLib32Paths = true;
  157. }
  158. // Lookup whether lib64 paths should be used.
  159. if (this->Makefile->PlatformIs64Bit() &&
  160. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  161. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  162. this->UseLib64Paths = true;
  163. }
  164. // Lookup whether libx32 paths should be used.
  165. if (this->Makefile->PlatformIsx32() &&
  166. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  167. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  168. this->UseLibx32Paths = true;
  169. }
  170. // Check if User Package Registry should be disabled
  171. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  172. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  173. if (const char* def =
  174. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  175. this->NoUserRegistry = !cmIsOn(def);
  176. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  177. this->NoUserRegistry = true;
  178. }
  179. // Check if System Package Registry should be disabled
  180. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  181. this->NoSystemRegistry = true;
  182. }
  183. // Check whether we should resolve symlinks when finding packages
  184. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  185. this->UseRealPath = true;
  186. }
  187. // Check if Sorting should be enabled
  188. if (const char* so =
  189. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  190. if (strcmp(so, "NAME") == 0) {
  191. this->SortOrder = Name_order;
  192. } else if (strcmp(so, "NATURAL") == 0) {
  193. this->SortOrder = Natural;
  194. } else {
  195. this->SortOrder = None;
  196. }
  197. }
  198. if (const char* sd =
  199. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  200. this->SortDirection = strcmp(sd, "ASC") == 0 ? Asc : Dec;
  201. }
  202. // Find what search path locations have been enabled/disable
  203. this->SelectDefaultSearchModes();
  204. // Find the current root path mode.
  205. this->SelectDefaultRootPathMode();
  206. // Find the current bundle/framework search policy.
  207. this->SelectDefaultMacMode();
  208. // Record options.
  209. this->Name = args[0];
  210. std::string components;
  211. const char* components_sep = "";
  212. std::set<std::string> requiredComponents;
  213. std::set<std::string> optionalComponents;
  214. // Always search directly in a generated path.
  215. this->SearchPathSuffixes.emplace_back();
  216. // Parse the arguments.
  217. enum Doing
  218. {
  219. DoingNone,
  220. DoingComponents,
  221. DoingOptionalComponents,
  222. DoingNames,
  223. DoingPaths,
  224. DoingPathSuffixes,
  225. DoingConfigs,
  226. DoingHints
  227. };
  228. Doing doing = DoingNone;
  229. cmsys::RegularExpression version("^[0-9.]+$");
  230. bool haveVersion = false;
  231. std::set<unsigned int> configArgs;
  232. std::set<unsigned int> moduleArgs;
  233. for (unsigned int i = 1; i < args.size(); ++i) {
  234. if (args[i] == "QUIET") {
  235. this->Quiet = true;
  236. doing = DoingNone;
  237. } else if (args[i] == "EXACT") {
  238. this->VersionExact = true;
  239. doing = DoingNone;
  240. } else if (args[i] == "MODULE") {
  241. moduleArgs.insert(i);
  242. doing = DoingNone;
  243. } else if (args[i] == "CONFIG") {
  244. configArgs.insert(i);
  245. doing = DoingNone;
  246. } else if (args[i] == "NO_MODULE") {
  247. configArgs.insert(i);
  248. doing = DoingNone;
  249. } else if (args[i] == "REQUIRED") {
  250. this->Required = true;
  251. doing = DoingComponents;
  252. } else if (args[i] == "COMPONENTS") {
  253. doing = DoingComponents;
  254. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  255. doing = DoingOptionalComponents;
  256. } else if (args[i] == "NAMES") {
  257. configArgs.insert(i);
  258. doing = DoingNames;
  259. } else if (args[i] == "PATHS") {
  260. configArgs.insert(i);
  261. doing = DoingPaths;
  262. } else if (args[i] == "HINTS") {
  263. configArgs.insert(i);
  264. doing = DoingHints;
  265. } else if (args[i] == "PATH_SUFFIXES") {
  266. configArgs.insert(i);
  267. doing = DoingPathSuffixes;
  268. } else if (args[i] == "CONFIGS") {
  269. configArgs.insert(i);
  270. doing = DoingConfigs;
  271. } else if (args[i] == "NO_POLICY_SCOPE") {
  272. this->PolicyScope = false;
  273. doing = DoingNone;
  274. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  275. this->NoUserRegistry = true;
  276. configArgs.insert(i);
  277. doing = DoingNone;
  278. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  279. this->NoSystemRegistry = true;
  280. configArgs.insert(i);
  281. doing = DoingNone;
  282. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  283. // Ignore legacy option.
  284. configArgs.insert(i);
  285. doing = DoingNone;
  286. } else if (this->CheckCommonArgument(args[i])) {
  287. configArgs.insert(i);
  288. doing = DoingNone;
  289. } else if ((doing == DoingComponents) ||
  290. (doing == DoingOptionalComponents)) {
  291. // Set a variable telling the find script whether this component
  292. // is required.
  293. const char* isRequired = "1";
  294. if (doing == DoingOptionalComponents) {
  295. isRequired = "0";
  296. optionalComponents.insert(args[i]);
  297. } else {
  298. requiredComponents.insert(args[i]);
  299. }
  300. std::string req_var = this->Name + "_FIND_REQUIRED_" + args[i];
  301. this->AddFindDefinition(req_var, isRequired);
  302. // Append to the list of required components.
  303. components += components_sep;
  304. components += args[i];
  305. components_sep = ";";
  306. } else if (doing == DoingNames) {
  307. this->Names.push_back(args[i]);
  308. } else if (doing == DoingPaths) {
  309. this->UserGuessArgs.push_back(args[i]);
  310. } else if (doing == DoingHints) {
  311. this->UserHintsArgs.push_back(args[i]);
  312. } else if (doing == DoingPathSuffixes) {
  313. this->AddPathSuffix(args[i]);
  314. } else if (doing == DoingConfigs) {
  315. if (args[i].find_first_of(":/\\") != std::string::npos ||
  316. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  317. std::ostringstream e;
  318. e << "given CONFIGS option followed by invalid file name \"" << args[i]
  319. << "\". The names given must be file names without "
  320. << "a path and with a \".cmake\" extension.";
  321. this->SetError(e.str());
  322. return false;
  323. }
  324. this->Configs.push_back(args[i]);
  325. } else if (!haveVersion && version.find(args[i])) {
  326. haveVersion = true;
  327. this->Version = args[i];
  328. } else {
  329. std::ostringstream e;
  330. e << "called with invalid argument \"" << args[i] << "\"";
  331. this->SetError(e.str());
  332. return false;
  333. }
  334. }
  335. std::vector<std::string> doubledComponents;
  336. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  337. optionalComponents.begin(), optionalComponents.end(),
  338. std::back_inserter(doubledComponents));
  339. if (!doubledComponents.empty()) {
  340. std::ostringstream e;
  341. e << "called with components that are both required and optional:\n";
  342. e << cmWrap(" ", doubledComponents, "", "\n") << "\n";
  343. this->SetError(e.str());
  344. return false;
  345. }
  346. // Maybe choose one mode exclusively.
  347. this->UseFindModules = configArgs.empty();
  348. this->UseConfigFiles = moduleArgs.empty();
  349. if (!this->UseFindModules && !this->UseConfigFiles) {
  350. std::ostringstream e;
  351. e << "given options exclusive to Module mode:\n";
  352. for (unsigned int si : moduleArgs) {
  353. e << " " << args[si] << "\n";
  354. }
  355. e << "and options exclusive to Config mode:\n";
  356. for (unsigned int si : configArgs) {
  357. e << " " << args[si] << "\n";
  358. }
  359. e << "The options are incompatible.";
  360. this->SetError(e.str());
  361. return false;
  362. }
  363. // Ignore EXACT with no version.
  364. if (this->Version.empty() && this->VersionExact) {
  365. this->VersionExact = false;
  366. this->Makefile->IssueMessage(
  367. MessageType::AUTHOR_WARNING,
  368. "Ignoring EXACT since no version is requested.");
  369. }
  370. if (this->Version.empty() || components.empty()) {
  371. // Check whether we are recursing inside "Find<name>.cmake" within
  372. // another find_package(<name>) call.
  373. std::string mod = cmStrCat(this->Name, "_FIND_MODULE");
  374. if (this->Makefile->IsOn(mod)) {
  375. if (this->Version.empty()) {
  376. // Get version information from the outer call if necessary.
  377. // Requested version string.
  378. std::string ver = cmStrCat(this->Name, "_FIND_VERSION");
  379. this->Version = this->Makefile->GetSafeDefinition(ver);
  380. // Whether an exact version is required.
  381. std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  382. this->VersionExact = this->Makefile->IsOn(exact);
  383. }
  384. if (components.empty()) {
  385. std::string components_var = this->Name + "_FIND_COMPONENTS";
  386. components = this->Makefile->GetSafeDefinition(components_var);
  387. }
  388. }
  389. }
  390. if (!this->Version.empty()) {
  391. // Try to parse the version number and store the results that were
  392. // successfully parsed.
  393. unsigned int parsed_major;
  394. unsigned int parsed_minor;
  395. unsigned int parsed_patch;
  396. unsigned int parsed_tweak;
  397. this->VersionCount =
  398. sscanf(this->Version.c_str(), "%u.%u.%u.%u", &parsed_major,
  399. &parsed_minor, &parsed_patch, &parsed_tweak);
  400. switch (this->VersionCount) {
  401. case 4:
  402. this->VersionTweak = parsed_tweak;
  403. CM_FALLTHROUGH;
  404. case 3:
  405. this->VersionPatch = parsed_patch;
  406. CM_FALLTHROUGH;
  407. case 2:
  408. this->VersionMinor = parsed_minor;
  409. CM_FALLTHROUGH;
  410. case 1:
  411. this->VersionMajor = parsed_major;
  412. CM_FALLTHROUGH;
  413. default:
  414. break;
  415. }
  416. }
  417. std::string disableFindPackageVar =
  418. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  419. if (this->Makefile->IsOn(disableFindPackageVar)) {
  420. if (this->Required) {
  421. std::ostringstream e;
  422. e << "for module " << this->Name << " called with REQUIRED, but "
  423. << disableFindPackageVar
  424. << " is enabled. A REQUIRED package cannot be disabled.";
  425. this->SetError(e.str());
  426. return false;
  427. }
  428. return true;
  429. }
  430. {
  431. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  432. this->Makefile->FindPackageRootPathStack.emplace_back();
  433. std::vector<std::string>& rootPaths =
  434. this->Makefile->FindPackageRootPathStack.back();
  435. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  436. // subject to CMP0074.
  437. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  438. case cmPolicies::WARN:
  439. this->Makefile->MaybeWarnCMP0074(this->Name);
  440. CM_FALLTHROUGH;
  441. case cmPolicies::OLD:
  442. // OLD behavior is to ignore the <pkg>_ROOT variables.
  443. break;
  444. case cmPolicies::REQUIRED_IF_USED:
  445. case cmPolicies::REQUIRED_ALWAYS:
  446. this->Makefile->IssueMessage(
  447. MessageType::FATAL_ERROR,
  448. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  449. break;
  450. case cmPolicies::NEW: {
  451. // NEW behavior is to honor the <pkg>_ROOT variables.
  452. std::string const rootVar = this->Name + "_ROOT";
  453. if (const char* pkgRoot = this->Makefile->GetDefinition(rootVar)) {
  454. cmExpandList(pkgRoot, rootPaths, false);
  455. }
  456. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  457. } break;
  458. }
  459. }
  460. this->SetModuleVariables(components);
  461. // See if there is a Find<PackageName>.cmake module.
  462. bool loadedPackage = false;
  463. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  464. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  465. loadedPackage = true;
  466. } else {
  467. if (this->FindPackageUsingModuleMode()) {
  468. loadedPackage = true;
  469. } else {
  470. // The package was not loaded. Report errors.
  471. if (HandlePackageMode(HandlePackageModeType::Module)) {
  472. loadedPackage = true;
  473. }
  474. }
  475. }
  476. } else {
  477. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  478. loadedPackage = true;
  479. } else {
  480. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  481. // implicitly assumed)
  482. if (this->UseFindModules && this->UseConfigFiles &&
  483. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  484. std::ostringstream aw;
  485. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  486. aw << "find_package called without either MODULE or CONFIG option "
  487. "and "
  488. "no Find"
  489. << this->Name
  490. << ".cmake module is in CMAKE_MODULE_PATH. "
  491. "Add MODULE to exclusively request Module mode and fail if "
  492. "Find"
  493. << this->Name
  494. << ".cmake is missing. "
  495. "Add CONFIG to exclusively request Config mode and search for "
  496. "a "
  497. "package configuration file provided by "
  498. << this->Name << " (" << this->Name << "Config.cmake or "
  499. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  500. } else {
  501. aw << "find_package called without NO_MODULE option and no "
  502. "Find"
  503. << this->Name
  504. << ".cmake module is in CMAKE_MODULE_PATH. "
  505. "Add NO_MODULE to exclusively request Config mode and search "
  506. "for a "
  507. "package configuration file provided by "
  508. << this->Name << " (" << this->Name << "Config.cmake or "
  509. << cmSystemTools::LowerCase(this->Name)
  510. << "-config.cmake). "
  511. "Otherwise make Find"
  512. << this->Name
  513. << ".cmake available in "
  514. "CMAKE_MODULE_PATH.";
  515. }
  516. aw << "\n"
  517. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  518. "warning.)";
  519. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  520. }
  521. if (this->FindPackageUsingConfigMode()) {
  522. loadedPackage = true;
  523. }
  524. }
  525. }
  526. this->AppendSuccessInformation();
  527. return loadedPackage;
  528. }
  529. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  530. {
  531. bool foundModule = false;
  532. if (!this->FindModule(foundModule)) {
  533. return false;
  534. }
  535. return foundModule;
  536. }
  537. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  538. {
  539. this->Variable = cmStrCat(this->Name, "_DIR");
  540. // Add the default name.
  541. if (this->Names.empty()) {
  542. this->Names.push_back(this->Name);
  543. }
  544. // Add the default configs.
  545. if (this->Configs.empty()) {
  546. for (std::string const& n : this->Names) {
  547. std::string config = cmStrCat(n, "Config.cmake");
  548. this->Configs.push_back(config);
  549. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  550. this->Configs.push_back(std::move(config));
  551. }
  552. }
  553. // get igonored paths from vars and reroot them.
  554. std::vector<std::string> ignored;
  555. this->GetIgnoredPaths(ignored);
  556. this->RerootPaths(ignored);
  557. // Construct a set of ignored paths
  558. this->IgnoredPaths.clear();
  559. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  560. // Find and load the package.
  561. return this->HandlePackageMode(HandlePackageModeType::Config);
  562. }
  563. void cmFindPackageCommand::SetModuleVariables(const std::string& components)
  564. {
  565. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name.c_str());
  566. // Store the list of components.
  567. std::string components_var = this->Name + "_FIND_COMPONENTS";
  568. this->AddFindDefinition(components_var, components.c_str());
  569. if (this->Quiet) {
  570. // Tell the module that is about to be read that it should find
  571. // quietly.
  572. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  573. this->AddFindDefinition(quietly, "1");
  574. }
  575. if (this->Required) {
  576. // Tell the module that is about to be read that it should report
  577. // a fatal error if the package is not found.
  578. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  579. this->AddFindDefinition(req, "1");
  580. }
  581. if (!this->Version.empty()) {
  582. // Tell the module that is about to be read what version of the
  583. // package has been requested.
  584. std::string ver = cmStrCat(this->Name, "_FIND_VERSION");
  585. this->AddFindDefinition(ver, this->Version.c_str());
  586. char buf[64];
  587. sprintf(buf, "%u", this->VersionMajor);
  588. this->AddFindDefinition(ver + "_MAJOR", buf);
  589. sprintf(buf, "%u", this->VersionMinor);
  590. this->AddFindDefinition(ver + "_MINOR", buf);
  591. sprintf(buf, "%u", this->VersionPatch);
  592. this->AddFindDefinition(ver + "_PATCH", buf);
  593. sprintf(buf, "%u", this->VersionTweak);
  594. this->AddFindDefinition(ver + "_TWEAK", buf);
  595. sprintf(buf, "%u", this->VersionCount);
  596. this->AddFindDefinition(ver + "_COUNT", buf);
  597. // Tell the module whether an exact version has been requested.
  598. std::string exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  599. this->AddFindDefinition(exact, this->VersionExact ? "1" : "0");
  600. }
  601. }
  602. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  603. const char* val)
  604. {
  605. if (const char* old = this->Makefile->GetDefinition(var)) {
  606. this->OriginalDefs[var].exists = true;
  607. this->OriginalDefs[var].value = old;
  608. } else {
  609. this->OriginalDefs[var].exists = false;
  610. }
  611. if (val) {
  612. this->Makefile->AddDefinition(var, val);
  613. }
  614. }
  615. void cmFindPackageCommand::RestoreFindDefinitions()
  616. {
  617. for (auto const& i : this->OriginalDefs) {
  618. OriginalDef const& od = i.second;
  619. if (od.exists) {
  620. this->Makefile->AddDefinition(i.first, od.value);
  621. } else {
  622. this->Makefile->RemoveDefinition(i.first);
  623. }
  624. }
  625. }
  626. bool cmFindPackageCommand::FindModule(bool& found)
  627. {
  628. std::string module = cmStrCat("Find", this->Name, ".cmake");
  629. bool system = false;
  630. std::string mfile = this->Makefile->GetModulesFile(module, system);
  631. if (!mfile.empty()) {
  632. if (system) {
  633. auto it = this->DeprecatedFindModules.find(this->Name);
  634. if (it != this->DeprecatedFindModules.end()) {
  635. cmPolicies::PolicyStatus status =
  636. this->Makefile->GetPolicyStatus(it->second);
  637. switch (status) {
  638. case cmPolicies::WARN: {
  639. std::ostringstream e;
  640. e << cmPolicies::GetPolicyWarning(it->second) << "\n";
  641. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  642. CM_FALLTHROUGH;
  643. }
  644. case cmPolicies::OLD:
  645. break;
  646. case cmPolicies::REQUIRED_IF_USED:
  647. case cmPolicies::REQUIRED_ALWAYS:
  648. case cmPolicies::NEW:
  649. return true;
  650. }
  651. }
  652. }
  653. // Load the module we found, and set "<name>_FIND_MODULE" to true
  654. // while inside it.
  655. found = true;
  656. std::string var = cmStrCat(this->Name, "_FIND_MODULE");
  657. this->Makefile->AddDefinition(var, "1");
  658. bool result = this->ReadListFile(mfile, DoPolicyScope);
  659. this->Makefile->RemoveDefinition(var);
  660. return result;
  661. }
  662. return true;
  663. }
  664. bool cmFindPackageCommand::HandlePackageMode(
  665. HandlePackageModeType handlePackageModeType)
  666. {
  667. this->ConsideredConfigs.clear();
  668. // Try to find the config file.
  669. const char* def = this->Makefile->GetDefinition(this->Variable);
  670. // Try to load the config file if the directory is known
  671. bool fileFound = false;
  672. if (this->UseConfigFiles) {
  673. if (!cmIsOff(def)) {
  674. // Get the directory from the variable value.
  675. std::string dir = def;
  676. cmSystemTools::ConvertToUnixSlashes(dir);
  677. // Treat relative paths with respect to the current source dir.
  678. if (!cmSystemTools::FileIsFullPath(dir)) {
  679. dir = "/" + dir;
  680. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  681. }
  682. // The file location was cached. Look for the correct file.
  683. std::string file;
  684. if (this->FindConfigFile(dir, file)) {
  685. this->FileFound = file;
  686. fileFound = true;
  687. }
  688. def = this->Makefile->GetDefinition(this->Variable);
  689. }
  690. // Search for the config file if it is not already found.
  691. if (cmIsOff(def) || !fileFound) {
  692. fileFound = this->FindConfig();
  693. }
  694. // Sanity check.
  695. if (fileFound && this->FileFound.empty()) {
  696. this->Makefile->IssueMessage(
  697. MessageType::INTERNAL_ERROR,
  698. "fileFound is true but FileFound is empty!");
  699. fileFound = false;
  700. }
  701. }
  702. std::string foundVar = cmStrCat(this->Name, "_FOUND");
  703. std::string notFoundMessageVar = cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  704. std::string notFoundMessage;
  705. // If the directory for the config file was found, try to read the file.
  706. bool result = true;
  707. bool found = false;
  708. bool configFileSetFOUNDFalse = false;
  709. if (fileFound) {
  710. if (this->Makefile->IsDefinitionSet(foundVar) &&
  711. !this->Makefile->IsOn(foundVar)) {
  712. // by removing Foo_FOUND here if it is FALSE, we don't really change
  713. // the situation for the Config file which is about to be included,
  714. // but we make it possible to detect later on whether the Config file
  715. // has set Foo_FOUND to FALSE itself:
  716. this->Makefile->RemoveDefinition(foundVar);
  717. }
  718. this->Makefile->RemoveDefinition(notFoundMessageVar);
  719. // Set the version variables before loading the config file.
  720. // It may override them.
  721. this->StoreVersionFound();
  722. // Parse the configuration file.
  723. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  724. // The package has been found.
  725. found = true;
  726. // Check whether the Config file has set Foo_FOUND to FALSE:
  727. if (this->Makefile->IsDefinitionSet(foundVar) &&
  728. !this->Makefile->IsOn(foundVar)) {
  729. // we get here if the Config file has set Foo_FOUND actively to FALSE
  730. found = false;
  731. configFileSetFOUNDFalse = true;
  732. notFoundMessage =
  733. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  734. }
  735. } else {
  736. // The configuration file is invalid.
  737. result = false;
  738. }
  739. }
  740. if (this->UseFindModules && !found &&
  741. handlePackageModeType == HandlePackageModeType::Config &&
  742. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  743. // Config mode failed. Allow Module case.
  744. result = false;
  745. }
  746. // package not found
  747. if (result && !found) {
  748. // warn if package required or neither quiet nor in config mode
  749. if (this->Required ||
  750. !(this->Quiet ||
  751. (this->UseConfigFiles && !this->UseFindModules &&
  752. this->ConsideredConfigs.empty()))) {
  753. // The variable is not set.
  754. std::ostringstream e;
  755. std::ostringstream aw;
  756. if (configFileSetFOUNDFalse) {
  757. /* clang-format off */
  758. e << "Found package configuration file:\n"
  759. " " << this->FileFound << "\n"
  760. "but it set " << foundVar << " to FALSE so package \"" <<
  761. this->Name << "\" is considered to be NOT FOUND.";
  762. /* clang-format on */
  763. if (!notFoundMessage.empty()) {
  764. e << " Reason given by package: \n" << notFoundMessage << "\n";
  765. }
  766. }
  767. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  768. // have been found, but they didn't have appropriate versions.
  769. else if (!this->ConsideredConfigs.empty()) {
  770. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  771. e << "Could not find a configuration file for package \"" << this->Name
  772. << "\" that "
  773. << (this->VersionExact ? "exactly matches" : "is compatible with")
  774. << " requested version \"" << this->Version << "\".\n"
  775. << "The following configuration files were considered but not "
  776. "accepted:\n";
  777. for (ConfigFileInfo const& info :
  778. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  779. e << " " << info.filename << ", version: " << info.version << "\n";
  780. }
  781. } else {
  782. std::string requestedVersionString;
  783. if (!this->Version.empty()) {
  784. requestedVersionString =
  785. cmStrCat(" (requested version ", this->Version, ')');
  786. }
  787. if (this->UseConfigFiles) {
  788. if (this->UseFindModules) {
  789. e << "By not providing \"Find" << this->Name
  790. << ".cmake\" in "
  791. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  792. "package configuration file provided by \""
  793. << this->Name
  794. << "\", "
  795. "but CMake did not find one.\n";
  796. }
  797. if (this->Configs.size() == 1) {
  798. e << "Could not find a package configuration file named \""
  799. << this->Configs[0] << "\" provided by package \"" << this->Name
  800. << "\"" << requestedVersionString << ".\n";
  801. } else {
  802. e << "Could not find a package configuration file provided by \""
  803. << this->Name << "\"" << requestedVersionString
  804. << " with any of the following names:\n"
  805. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  806. }
  807. e << "Add the installation prefix of \"" << this->Name
  808. << "\" to "
  809. "CMAKE_PREFIX_PATH or set \""
  810. << this->Variable
  811. << "\" to a "
  812. "directory containing one of the above files. "
  813. "If \""
  814. << this->Name
  815. << "\" provides a separate development "
  816. "package or SDK, be sure it has been installed.";
  817. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  818. {
  819. e << "No \"Find" << this->Name << ".cmake\" found in "
  820. << "CMAKE_MODULE_PATH.";
  821. aw
  822. << "Find" << this->Name
  823. << ".cmake must either be part of this "
  824. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  825. "it points to the correct location inside its source tree.\n"
  826. "Or it must be installed by a package which has already been "
  827. "found via find_package(). In this case make sure that "
  828. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  829. "contain the location where that package has installed "
  830. "Find"
  831. << this->Name
  832. << ".cmake. This must be a location "
  833. "provided by that package. This error in general means that "
  834. "the buildsystem of this project is relying on a Find-module "
  835. "without ensuring that it is actually available.\n";
  836. }
  837. }
  838. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  839. : MessageType::WARNING,
  840. e.str());
  841. if (this->Required) {
  842. cmSystemTools::SetFatalErrorOccured();
  843. }
  844. if (!aw.str().empty()) {
  845. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  846. }
  847. }
  848. // output result if in config mode but not in quiet mode
  849. else if (!this->Quiet) {
  850. std::ostringstream aw;
  851. aw << "Could NOT find " << this->Name << " (missing: " << this->Name
  852. << "_DIR)";
  853. this->Makefile->DisplayStatus(aw.str(), -1);
  854. }
  855. }
  856. // Set a variable marking whether the package was found.
  857. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  858. // Set a variable naming the configuration file that was found.
  859. std::string fileVar = cmStrCat(this->Name, "_CONFIG");
  860. if (found) {
  861. this->Makefile->AddDefinition(fileVar, this->FileFound);
  862. } else {
  863. this->Makefile->RemoveDefinition(fileVar);
  864. }
  865. std::string consideredConfigsVar =
  866. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  867. std::string consideredVersionsVar =
  868. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  869. std::string consideredConfigFiles;
  870. std::string consideredVersions;
  871. const char* sep = "";
  872. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  873. consideredConfigFiles += sep;
  874. consideredVersions += sep;
  875. consideredConfigFiles += i.filename;
  876. consideredVersions += i.version;
  877. sep = ";";
  878. }
  879. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  880. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  881. return result;
  882. }
  883. bool cmFindPackageCommand::FindConfig()
  884. {
  885. // Compute the set of search prefixes.
  886. this->ComputePrefixes();
  887. // Look for the project's configuration file.
  888. bool found = false;
  889. // Search for frameworks.
  890. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  891. found = this->FindFrameworkConfig();
  892. }
  893. // Search for apps.
  894. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  895. found = this->FindAppBundleConfig();
  896. }
  897. // Search prefixes.
  898. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  899. found = this->FindPrefixedConfig();
  900. }
  901. // Search for frameworks.
  902. if (!found && this->SearchFrameworkLast) {
  903. found = this->FindFrameworkConfig();
  904. }
  905. // Search for apps.
  906. if (!found && this->SearchAppBundleLast) {
  907. found = this->FindAppBundleConfig();
  908. }
  909. // Store the entry in the cache so it can be set by the user.
  910. std::string init;
  911. if (found) {
  912. init = cmSystemTools::GetFilenamePath(this->FileFound);
  913. } else {
  914. init = this->Variable + "-NOTFOUND";
  915. }
  916. std::string help =
  917. cmStrCat("The directory containing a CMake configuration file for ",
  918. this->Name, '.');
  919. // We force the value since we do not get here if it was already set.
  920. this->Makefile->AddCacheDefinition(this->Variable, init.c_str(),
  921. help.c_str(), cmStateEnums::PATH, true);
  922. return found;
  923. }
  924. bool cmFindPackageCommand::FindPrefixedConfig()
  925. {
  926. std::vector<std::string> const& prefixes = this->SearchPaths;
  927. for (std::string const& p : prefixes) {
  928. if (this->SearchPrefix(p)) {
  929. return true;
  930. }
  931. }
  932. return false;
  933. }
  934. bool cmFindPackageCommand::FindFrameworkConfig()
  935. {
  936. std::vector<std::string> const& prefixes = this->SearchPaths;
  937. for (std::string const& p : prefixes) {
  938. if (this->SearchFrameworkPrefix(p)) {
  939. return true;
  940. }
  941. }
  942. return false;
  943. }
  944. bool cmFindPackageCommand::FindAppBundleConfig()
  945. {
  946. std::vector<std::string> const& prefixes = this->SearchPaths;
  947. for (std::string const& p : prefixes) {
  948. if (this->SearchAppBundlePrefix(p)) {
  949. return true;
  950. }
  951. }
  952. return false;
  953. }
  954. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  955. PolicyScopeRule psr)
  956. {
  957. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  958. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  959. return true;
  960. }
  961. std::string e = cmStrCat("Error reading CMake code from \"", f, "\".");
  962. this->SetError(e);
  963. return false;
  964. }
  965. void cmFindPackageCommand::AppendToFoundProperty(bool found)
  966. {
  967. std::vector<std::string> foundContents;
  968. const char* foundProp =
  969. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  970. if (foundProp && *foundProp) {
  971. std::string tmp = foundProp;
  972. cmExpandList(tmp, foundContents, false);
  973. auto nameIt =
  974. std::find(foundContents.begin(), foundContents.end(), this->Name);
  975. if (nameIt != foundContents.end()) {
  976. foundContents.erase(nameIt);
  977. }
  978. }
  979. std::vector<std::string> notFoundContents;
  980. const char* notFoundProp =
  981. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  982. if (notFoundProp && *notFoundProp) {
  983. std::string tmp = notFoundProp;
  984. cmExpandList(tmp, notFoundContents, false);
  985. auto nameIt =
  986. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  987. if (nameIt != notFoundContents.end()) {
  988. notFoundContents.erase(nameIt);
  989. }
  990. }
  991. if (found) {
  992. foundContents.push_back(this->Name);
  993. } else {
  994. notFoundContents.push_back(this->Name);
  995. }
  996. std::string tmp = cmJoin(foundContents, ";");
  997. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  998. tmp = cmJoin(notFoundContents, ";");
  999. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1000. tmp.c_str());
  1001. }
  1002. void cmFindPackageCommand::AppendSuccessInformation()
  1003. {
  1004. {
  1005. std::string transitivePropName =
  1006. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1007. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1008. }
  1009. std::string found = cmStrCat(this->Name, "_FOUND");
  1010. std::string upperFound = cmSystemTools::UpperCase(found);
  1011. const char* upperResult = this->Makefile->GetDefinition(upperFound);
  1012. const char* result = this->Makefile->GetDefinition(found);
  1013. bool packageFound = ((cmIsOn(result)) || (cmIsOn(upperResult)));
  1014. this->AppendToFoundProperty(packageFound);
  1015. // Record whether the find was quiet or not, so this can be used
  1016. // e.g. in FeatureSummary.cmake
  1017. std::string quietInfoPropName = cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1018. this->Makefile->GetState()->SetGlobalProperty(
  1019. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1020. // set a global property to record the required version of this package
  1021. std::string versionInfoPropName =
  1022. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1023. std::string versionInfo;
  1024. if (!this->Version.empty()) {
  1025. versionInfo =
  1026. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1027. }
  1028. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1029. versionInfo.c_str());
  1030. if (this->Required) {
  1031. std::string requiredInfoPropName =
  1032. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1033. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1034. "REQUIRED");
  1035. }
  1036. // Restore original state of "_FIND_" variables we set.
  1037. this->RestoreFindDefinitions();
  1038. // Pop the package stack
  1039. this->Makefile->FindPackageRootPathStack.pop_back();
  1040. }
  1041. void cmFindPackageCommand::ComputePrefixes()
  1042. {
  1043. if (!this->NoDefaultPath) {
  1044. if (!this->NoPackageRootPath) {
  1045. this->FillPrefixesPackageRoot();
  1046. }
  1047. if (!this->NoCMakePath) {
  1048. this->FillPrefixesCMakeVariable();
  1049. }
  1050. if (!this->NoCMakeEnvironmentPath) {
  1051. this->FillPrefixesCMakeEnvironment();
  1052. }
  1053. }
  1054. this->FillPrefixesUserHints();
  1055. if (!this->NoDefaultPath) {
  1056. if (!this->NoSystemEnvironmentPath) {
  1057. this->FillPrefixesSystemEnvironment();
  1058. }
  1059. if (!this->NoUserRegistry) {
  1060. this->FillPrefixesUserRegistry();
  1061. }
  1062. if (!this->NoCMakeSystemPath) {
  1063. this->FillPrefixesCMakeSystemVariable();
  1064. }
  1065. if (!this->NoSystemRegistry) {
  1066. this->FillPrefixesSystemRegistry();
  1067. }
  1068. }
  1069. this->FillPrefixesUserGuess();
  1070. this->ComputeFinalPaths();
  1071. }
  1072. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1073. {
  1074. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1075. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1076. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  1077. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1078. ++pkgPaths) {
  1079. for (std::string const& path : *pkgPaths) {
  1080. paths.AddPath(path);
  1081. }
  1082. }
  1083. }
  1084. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1085. {
  1086. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1087. // Check the environment variable with the same name as the cache
  1088. // entry.
  1089. paths.AddEnvPath(this->Variable);
  1090. // And now the general CMake environment variables
  1091. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1092. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1093. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1094. }
  1095. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1096. {
  1097. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1098. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1099. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1100. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1101. }
  1102. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1103. {
  1104. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1105. // Use the system search path to generate prefixes.
  1106. // Relative paths are interpreted with respect to the current
  1107. // working directory.
  1108. std::vector<std::string> tmp;
  1109. cmSystemTools::GetPath(tmp);
  1110. for (std::string const& i : tmp) {
  1111. // If the path is a PREFIX/bin case then add its parent instead.
  1112. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1113. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1114. } else {
  1115. paths.AddPath(i);
  1116. }
  1117. }
  1118. }
  1119. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1120. {
  1121. #if defined(_WIN32) && !defined(__CYGWIN__)
  1122. this->LoadPackageRegistryWinUser();
  1123. #elif defined(__HAIKU__)
  1124. char dir[B_PATH_NAME_LENGTH];
  1125. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1126. B_OK) {
  1127. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  1128. this->LoadPackageRegistryDir(fname,
  1129. this->LabeledPaths[PathLabel::UserRegistry]);
  1130. }
  1131. #else
  1132. std::string dir;
  1133. if (cmSystemTools::GetEnv("HOME", dir)) {
  1134. dir += "/.cmake/packages/";
  1135. dir += this->Name;
  1136. this->LoadPackageRegistryDir(dir,
  1137. this->LabeledPaths[PathLabel::UserRegistry]);
  1138. }
  1139. #endif
  1140. }
  1141. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1142. {
  1143. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1144. return;
  1145. }
  1146. #if defined(_WIN32) && !defined(__CYGWIN__)
  1147. this->LoadPackageRegistryWinSystem();
  1148. #endif
  1149. }
  1150. #if defined(_WIN32) && !defined(__CYGWIN__)
  1151. # include <windows.h>
  1152. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  1153. # if !defined(KEY_WOW64_32KEY)
  1154. # define KEY_WOW64_32KEY 0x0200
  1155. # endif
  1156. # if !defined(KEY_WOW64_64KEY)
  1157. # define KEY_WOW64_64KEY 0x0100
  1158. # endif
  1159. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1160. {
  1161. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1162. this->LoadPackageRegistryWin(true, 0,
  1163. this->LabeledPaths[PathLabel::UserRegistry]);
  1164. }
  1165. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1166. {
  1167. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1168. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1169. // Prefer the target platform view first.
  1170. if (this->Makefile->PlatformIs64Bit()) {
  1171. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1172. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1173. } else {
  1174. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1175. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1176. }
  1177. }
  1178. void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
  1179. cmSearchPath& outPaths)
  1180. {
  1181. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1182. key += cmsys::Encoding::ToWide(this->Name);
  1183. std::set<std::wstring> bad;
  1184. HKEY hKey;
  1185. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1186. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1187. DWORD valueType = REG_NONE;
  1188. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1189. std::vector<wchar_t> data(512);
  1190. bool done = false;
  1191. DWORD index = 0;
  1192. while (!done) {
  1193. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1194. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1195. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1196. (BYTE*)&data[0], &dataSize)) {
  1197. case ERROR_SUCCESS:
  1198. ++index;
  1199. if (valueType == REG_SZ) {
  1200. data[dataSize] = 0;
  1201. if (!this->CheckPackageRegistryEntry(
  1202. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1203. // The entry is invalid.
  1204. bad.insert(name);
  1205. }
  1206. }
  1207. break;
  1208. case ERROR_MORE_DATA:
  1209. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1210. break;
  1211. case ERROR_NO_MORE_ITEMS:
  1212. default:
  1213. done = true;
  1214. break;
  1215. }
  1216. }
  1217. RegCloseKey(hKey);
  1218. }
  1219. // Remove bad values if possible.
  1220. if (user && !bad.empty() &&
  1221. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1222. &hKey) == ERROR_SUCCESS) {
  1223. for (std::wstring const& v : bad) {
  1224. RegDeleteValueW(hKey, v.c_str());
  1225. }
  1226. RegCloseKey(hKey);
  1227. }
  1228. }
  1229. #else
  1230. class cmFindPackageCommandHoldFile
  1231. {
  1232. const char* File;
  1233. public:
  1234. cmFindPackageCommandHoldFile(const char* f)
  1235. : File(f)
  1236. {
  1237. }
  1238. ~cmFindPackageCommandHoldFile()
  1239. {
  1240. if (this->File) {
  1241. cmSystemTools::RemoveFile(this->File);
  1242. }
  1243. }
  1244. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  1245. cmFindPackageCommandHoldFile& operator=(
  1246. const cmFindPackageCommandHoldFile&) = delete;
  1247. void Release() { this->File = nullptr; }
  1248. };
  1249. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1250. cmSearchPath& outPaths)
  1251. {
  1252. cmsys::Directory files;
  1253. if (!files.Load(dir)) {
  1254. return;
  1255. }
  1256. std::string fname;
  1257. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1258. fname = cmStrCat(dir, '/', files.GetFile(i));
  1259. if (!cmSystemTools::FileIsDirectory(fname)) {
  1260. // Hold this file hostage until it behaves.
  1261. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1262. // Load the file.
  1263. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1264. std::string fentry;
  1265. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1266. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1267. // The file references an existing package, so release it.
  1268. holdFile.Release();
  1269. }
  1270. }
  1271. }
  1272. // TODO: Wipe out the directory if it is empty.
  1273. }
  1274. #endif
  1275. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1276. cmSearchPath& outPaths)
  1277. {
  1278. // Parse the content of one package registry entry.
  1279. if (cmSystemTools::FileIsFullPath(fname)) {
  1280. // The first line in the stream is the full path to a file or
  1281. // directory containing the package.
  1282. if (cmSystemTools::FileExists(fname)) {
  1283. // The path exists. Look for the package here.
  1284. if (!cmSystemTools::FileIsDirectory(fname)) {
  1285. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1286. } else {
  1287. outPaths.AddPath(fname);
  1288. }
  1289. return true;
  1290. }
  1291. // The path does not exist. Assume the stream content is
  1292. // associated with an old package that no longer exists, and
  1293. // delete it to keep the package registry clean.
  1294. return false;
  1295. }
  1296. // The first line in the stream is not the full path to a file or
  1297. // directory. Assume the stream content was created by a future
  1298. // version of CMake that uses a different format, and leave it.
  1299. return true;
  1300. }
  1301. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1302. {
  1303. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1304. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1305. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1306. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1307. }
  1308. void cmFindPackageCommand::FillPrefixesUserGuess()
  1309. {
  1310. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1311. for (std::string const& p : this->UserGuessArgs) {
  1312. paths.AddUserPath(p);
  1313. }
  1314. }
  1315. void cmFindPackageCommand::FillPrefixesUserHints()
  1316. {
  1317. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  1318. for (std::string const& p : this->UserHintsArgs) {
  1319. paths.AddUserPath(p);
  1320. }
  1321. }
  1322. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  1323. {
  1324. assert(!dir.empty() && dir.back() == '/');
  1325. // Check each path suffix on this directory.
  1326. for (std::string const& s : this->SearchPathSuffixes) {
  1327. std::string d = dir;
  1328. if (!s.empty()) {
  1329. d += s;
  1330. d += "/";
  1331. }
  1332. if (this->CheckDirectory(d)) {
  1333. return true;
  1334. }
  1335. }
  1336. return false;
  1337. }
  1338. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  1339. {
  1340. assert(!dir.empty() && dir.back() == '/');
  1341. // Look for the file in this directory.
  1342. std::string d = dir.substr(0, dir.size() - 1);
  1343. if (this->FindConfigFile(d, this->FileFound)) {
  1344. // Remove duplicate slashes.
  1345. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  1346. return true;
  1347. }
  1348. return false;
  1349. }
  1350. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  1351. std::string& file)
  1352. {
  1353. if (this->IgnoredPaths.count(dir)) {
  1354. return false;
  1355. }
  1356. for (std::string const& c : this->Configs) {
  1357. file = cmStrCat(dir, '/', c);
  1358. if (this->DebugMode) {
  1359. fprintf(stderr, "Checking file [%s]\n", file.c_str());
  1360. }
  1361. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  1362. // Allow resolving symlinks when the config file is found through a link
  1363. if (this->UseRealPath) {
  1364. file = cmSystemTools::GetRealPath(file);
  1365. }
  1366. return true;
  1367. }
  1368. }
  1369. return false;
  1370. }
  1371. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  1372. {
  1373. bool result = false; // by default, assume the version is not ok.
  1374. bool haveResult = false;
  1375. std::string version = "unknown";
  1376. // Get the filename without the .cmake extension.
  1377. std::string::size_type pos = config_file.rfind('.');
  1378. std::string version_file_base = config_file.substr(0, pos);
  1379. // Look for foo-config-version.cmake
  1380. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  1381. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1382. result = this->CheckVersionFile(version_file, version);
  1383. haveResult = true;
  1384. }
  1385. // Look for fooConfigVersion.cmake
  1386. version_file = cmStrCat(version_file_base, "Version.cmake");
  1387. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  1388. result = this->CheckVersionFile(version_file, version);
  1389. haveResult = true;
  1390. }
  1391. // If no version was requested a versionless package is acceptable.
  1392. if (!haveResult && this->Version.empty()) {
  1393. result = true;
  1394. }
  1395. ConfigFileInfo configFileInfo;
  1396. configFileInfo.filename = config_file;
  1397. configFileInfo.version = version;
  1398. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  1399. return result;
  1400. }
  1401. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  1402. std::string& result_version)
  1403. {
  1404. // The version file will be loaded in an isolated scope.
  1405. cmMakefile::ScopePushPop varScope(this->Makefile);
  1406. cmMakefile::PolicyPushPop polScope(this->Makefile);
  1407. static_cast<void>(varScope);
  1408. static_cast<void>(polScope);
  1409. // Clear the output variables.
  1410. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  1411. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  1412. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  1413. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  1414. // Set the input variables.
  1415. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  1416. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION", this->Version);
  1417. char buf[64];
  1418. sprintf(buf, "%u", this->VersionMajor);
  1419. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MAJOR", buf);
  1420. sprintf(buf, "%u", this->VersionMinor);
  1421. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_MINOR", buf);
  1422. sprintf(buf, "%u", this->VersionPatch);
  1423. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_PATCH", buf);
  1424. sprintf(buf, "%u", this->VersionTweak);
  1425. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_TWEAK", buf);
  1426. sprintf(buf, "%u", this->VersionCount);
  1427. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COUNT", buf);
  1428. // Load the version check file. Pass NoPolicyScope because we do
  1429. // our own policy push/pop independent of CMP0011.
  1430. bool suitable = false;
  1431. if (this->ReadListFile(version_file, NoPolicyScope)) {
  1432. // Check the output variables.
  1433. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  1434. bool unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  1435. if (!okay && !this->VersionExact) {
  1436. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  1437. }
  1438. // The package is suitable if the version is okay and not
  1439. // explicitly unsuitable.
  1440. suitable = !unsuitable && (okay || this->Version.empty());
  1441. if (suitable) {
  1442. // Get the version found.
  1443. this->VersionFound =
  1444. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1445. // Try to parse the version number and store the results that were
  1446. // successfully parsed.
  1447. unsigned int parsed_major;
  1448. unsigned int parsed_minor;
  1449. unsigned int parsed_patch;
  1450. unsigned int parsed_tweak;
  1451. this->VersionFoundCount =
  1452. sscanf(this->VersionFound.c_str(), "%u.%u.%u.%u", &parsed_major,
  1453. &parsed_minor, &parsed_patch, &parsed_tweak);
  1454. switch (this->VersionFoundCount) {
  1455. case 4:
  1456. this->VersionFoundTweak = parsed_tweak;
  1457. CM_FALLTHROUGH;
  1458. case 3:
  1459. this->VersionFoundPatch = parsed_patch;
  1460. CM_FALLTHROUGH;
  1461. case 2:
  1462. this->VersionFoundMinor = parsed_minor;
  1463. CM_FALLTHROUGH;
  1464. case 1:
  1465. this->VersionFoundMajor = parsed_major;
  1466. CM_FALLTHROUGH;
  1467. default:
  1468. break;
  1469. }
  1470. }
  1471. }
  1472. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  1473. if (result_version.empty()) {
  1474. result_version = "unknown";
  1475. }
  1476. // Succeed if the version is suitable.
  1477. return suitable;
  1478. }
  1479. void cmFindPackageCommand::StoreVersionFound()
  1480. {
  1481. // Store the whole version string.
  1482. std::string ver = cmStrCat(this->Name, "_VERSION");
  1483. if (this->VersionFound.empty()) {
  1484. this->Makefile->RemoveDefinition(ver);
  1485. } else {
  1486. this->Makefile->AddDefinition(ver, this->VersionFound);
  1487. }
  1488. // Store the version components.
  1489. char buf[64];
  1490. sprintf(buf, "%u", this->VersionFoundMajor);
  1491. this->Makefile->AddDefinition(ver + "_MAJOR", buf);
  1492. sprintf(buf, "%u", this->VersionFoundMinor);
  1493. this->Makefile->AddDefinition(ver + "_MINOR", buf);
  1494. sprintf(buf, "%u", this->VersionFoundPatch);
  1495. this->Makefile->AddDefinition(ver + "_PATCH", buf);
  1496. sprintf(buf, "%u", this->VersionFoundTweak);
  1497. this->Makefile->AddDefinition(ver + "_TWEAK", buf);
  1498. sprintf(buf, "%u", this->VersionFoundCount);
  1499. this->Makefile->AddDefinition(ver + "_COUNT", buf);
  1500. }
  1501. class cmFileListGeneratorBase
  1502. {
  1503. public:
  1504. virtual ~cmFileListGeneratorBase() = default;
  1505. protected:
  1506. bool Consider(std::string const& fullPath, cmFileList& listing);
  1507. private:
  1508. bool Search(cmFileList&);
  1509. virtual bool Search(std::string const& parent, cmFileList&) = 0;
  1510. virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
  1511. friend class cmFileList;
  1512. cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
  1513. std::unique_ptr<cmFileListGeneratorBase> Next;
  1514. };
  1515. class cmFileList
  1516. {
  1517. public:
  1518. virtual ~cmFileList() = default;
  1519. cmFileList& operator/(cmFileListGeneratorBase const& rhs)
  1520. {
  1521. if (this->Last) {
  1522. this->Last = this->Last->SetNext(rhs);
  1523. } else {
  1524. this->First = rhs.Clone();
  1525. this->Last = this->First.get();
  1526. }
  1527. return *this;
  1528. }
  1529. bool Search()
  1530. {
  1531. if (this->First) {
  1532. return this->First->Search(*this);
  1533. }
  1534. return false;
  1535. }
  1536. private:
  1537. virtual bool Visit(std::string const& fullPath) = 0;
  1538. friend class cmFileListGeneratorBase;
  1539. std::unique_ptr<cmFileListGeneratorBase> First;
  1540. cmFileListGeneratorBase* Last = nullptr;
  1541. };
  1542. class cmFindPackageFileList : public cmFileList
  1543. {
  1544. public:
  1545. cmFindPackageFileList(cmFindPackageCommand* fpc, bool use_suffixes = true)
  1546. : FPC(fpc)
  1547. , UseSuffixes(use_suffixes)
  1548. {
  1549. }
  1550. private:
  1551. bool Visit(std::string const& fullPath) override
  1552. {
  1553. if (this->UseSuffixes) {
  1554. return this->FPC->SearchDirectory(fullPath);
  1555. }
  1556. return this->FPC->CheckDirectory(fullPath);
  1557. }
  1558. cmFindPackageCommand* FPC;
  1559. bool UseSuffixes;
  1560. };
  1561. bool cmFileListGeneratorBase::Search(cmFileList& listing)
  1562. {
  1563. return this->Search("", listing);
  1564. }
  1565. cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
  1566. cmFileListGeneratorBase const& next)
  1567. {
  1568. this->Next = next.Clone();
  1569. return this->Next.get();
  1570. }
  1571. bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
  1572. cmFileList& listing)
  1573. {
  1574. if (this->Next) {
  1575. return this->Next->Search(fullPath + "/", listing);
  1576. }
  1577. return listing.Visit(fullPath + "/");
  1578. }
  1579. class cmFileListGeneratorFixed : public cmFileListGeneratorBase
  1580. {
  1581. public:
  1582. cmFileListGeneratorFixed(std::string str)
  1583. : String(std::move(str))
  1584. {
  1585. }
  1586. cmFileListGeneratorFixed(cmFileListGeneratorFixed const& r)
  1587. : String(r.String)
  1588. {
  1589. }
  1590. private:
  1591. std::string String;
  1592. bool Search(std::string const& parent, cmFileList& lister) override
  1593. {
  1594. std::string fullPath = parent + this->String;
  1595. return this->Consider(fullPath, lister);
  1596. }
  1597. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1598. {
  1599. std::unique_ptr<cmFileListGeneratorBase> g(
  1600. new cmFileListGeneratorFixed(*this));
  1601. return g;
  1602. }
  1603. };
  1604. class cmFileListGeneratorEnumerate : public cmFileListGeneratorBase
  1605. {
  1606. public:
  1607. cmFileListGeneratorEnumerate(std::vector<std::string> const& v)
  1608. : Vector(v)
  1609. {
  1610. }
  1611. cmFileListGeneratorEnumerate(cmFileListGeneratorEnumerate const& r)
  1612. : Vector(r.Vector)
  1613. {
  1614. }
  1615. private:
  1616. std::vector<std::string> const& Vector;
  1617. bool Search(std::string const& parent, cmFileList& lister) override
  1618. {
  1619. for (std::string const& i : this->Vector) {
  1620. if (this->Consider(parent + i, lister)) {
  1621. return true;
  1622. }
  1623. }
  1624. return false;
  1625. }
  1626. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1627. {
  1628. std::unique_ptr<cmFileListGeneratorBase> g(
  1629. new cmFileListGeneratorEnumerate(*this));
  1630. return g;
  1631. }
  1632. };
  1633. class cmFileListGeneratorProject : public cmFileListGeneratorBase
  1634. {
  1635. public:
  1636. cmFileListGeneratorProject(std::vector<std::string> const& names,
  1637. cmFindPackageCommand::SortOrderType so,
  1638. cmFindPackageCommand::SortDirectionType sd)
  1639. : Names(names)
  1640. {
  1641. this->SetSort(so, sd);
  1642. }
  1643. cmFileListGeneratorProject(cmFileListGeneratorProject const& r)
  1644. : Names(r.Names)
  1645. {
  1646. this->SetSort(r.SortOrder, r.SortDirection);
  1647. }
  1648. void SetSort(cmFindPackageCommand::SortOrderType o,
  1649. cmFindPackageCommand::SortDirectionType d)
  1650. {
  1651. SortOrder = o;
  1652. SortDirection = d;
  1653. }
  1654. protected:
  1655. // sort parameters
  1656. cmFindPackageCommand::SortOrderType SortOrder;
  1657. cmFindPackageCommand::SortDirectionType SortDirection;
  1658. private:
  1659. std::vector<std::string> const& Names;
  1660. bool Search(std::string const& parent, cmFileList& lister) override
  1661. {
  1662. // Construct a list of matches.
  1663. std::vector<std::string> matches;
  1664. cmsys::Directory d;
  1665. d.Load(parent);
  1666. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1667. const char* fname = d.GetFile(i);
  1668. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1669. continue;
  1670. }
  1671. for (std::string const& n : this->Names) {
  1672. if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
  1673. matches.emplace_back(fname);
  1674. }
  1675. }
  1676. }
  1677. // before testing the matches check if there is a specific sorting order to
  1678. // perform
  1679. if (this->SortOrder != cmFindPackageCommand::None) {
  1680. cmFindPackageCommand::Sort(matches.begin(), matches.end(), SortOrder,
  1681. SortDirection);
  1682. }
  1683. for (std::string const& i : matches) {
  1684. if (this->Consider(parent + i, lister)) {
  1685. return true;
  1686. }
  1687. }
  1688. return false;
  1689. }
  1690. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1691. {
  1692. std::unique_ptr<cmFileListGeneratorBase> g(
  1693. new cmFileListGeneratorProject(*this));
  1694. return g;
  1695. }
  1696. };
  1697. class cmFileListGeneratorMacProject : public cmFileListGeneratorBase
  1698. {
  1699. public:
  1700. cmFileListGeneratorMacProject(std::vector<std::string> const& names,
  1701. const char* ext)
  1702. : Names(names)
  1703. , Extension(ext)
  1704. {
  1705. }
  1706. cmFileListGeneratorMacProject(cmFileListGeneratorMacProject const& r)
  1707. : Names(r.Names)
  1708. , Extension(r.Extension)
  1709. {
  1710. }
  1711. private:
  1712. std::vector<std::string> const& Names;
  1713. std::string Extension;
  1714. bool Search(std::string const& parent, cmFileList& lister) override
  1715. {
  1716. // Construct a list of matches.
  1717. std::vector<std::string> matches;
  1718. cmsys::Directory d;
  1719. d.Load(parent);
  1720. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1721. const char* fname = d.GetFile(i);
  1722. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1723. continue;
  1724. }
  1725. for (std::string name : this->Names) {
  1726. name += this->Extension;
  1727. if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
  1728. matches.emplace_back(fname);
  1729. }
  1730. }
  1731. }
  1732. for (std::string const& i : matches) {
  1733. if (this->Consider(parent + i, lister)) {
  1734. return true;
  1735. }
  1736. }
  1737. return false;
  1738. }
  1739. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1740. {
  1741. std::unique_ptr<cmFileListGeneratorBase> g(
  1742. new cmFileListGeneratorMacProject(*this));
  1743. return g;
  1744. }
  1745. };
  1746. class cmFileListGeneratorCaseInsensitive : public cmFileListGeneratorBase
  1747. {
  1748. public:
  1749. cmFileListGeneratorCaseInsensitive(std::string str)
  1750. : String(std::move(str))
  1751. {
  1752. }
  1753. cmFileListGeneratorCaseInsensitive(
  1754. cmFileListGeneratorCaseInsensitive const& r)
  1755. : String(r.String)
  1756. {
  1757. }
  1758. private:
  1759. std::string String;
  1760. bool Search(std::string const& parent, cmFileList& lister) override
  1761. {
  1762. // Look for matching files.
  1763. std::vector<std::string> matches;
  1764. cmsys::Directory d;
  1765. d.Load(parent);
  1766. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  1767. const char* fname = d.GetFile(i);
  1768. if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
  1769. continue;
  1770. }
  1771. if (cmsysString_strcasecmp(fname, this->String.c_str()) == 0) {
  1772. if (this->Consider(parent + fname, lister)) {
  1773. return true;
  1774. }
  1775. }
  1776. }
  1777. return false;
  1778. }
  1779. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1780. {
  1781. std::unique_ptr<cmFileListGeneratorBase> g(
  1782. new cmFileListGeneratorCaseInsensitive(*this));
  1783. return g;
  1784. }
  1785. };
  1786. class cmFileListGeneratorGlob : public cmFileListGeneratorBase
  1787. {
  1788. public:
  1789. cmFileListGeneratorGlob(std::string str)
  1790. : Pattern(std::move(str))
  1791. {
  1792. }
  1793. cmFileListGeneratorGlob(cmFileListGeneratorGlob const& r)
  1794. : Pattern(r.Pattern)
  1795. {
  1796. }
  1797. private:
  1798. std::string Pattern;
  1799. bool Search(std::string const& parent, cmFileList& lister) override
  1800. {
  1801. // Glob the set of matching files.
  1802. std::string expr = cmStrCat(parent, this->Pattern);
  1803. cmsys::Glob g;
  1804. if (!g.FindFiles(expr)) {
  1805. return false;
  1806. }
  1807. std::vector<std::string> const& files = g.GetFiles();
  1808. // Look for directories among the matches.
  1809. for (std::string const& f : files) {
  1810. if (cmSystemTools::FileIsDirectory(f)) {
  1811. if (this->Consider(f, lister)) {
  1812. return true;
  1813. }
  1814. }
  1815. }
  1816. return false;
  1817. }
  1818. std::unique_ptr<cmFileListGeneratorBase> Clone() const override
  1819. {
  1820. return cm::make_unique<cmFileListGeneratorGlob>(*this);
  1821. }
  1822. };
  1823. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  1824. {
  1825. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1826. if (this->DebugMode) {
  1827. fprintf(stderr, "Checking prefix [%s]\n", prefix_in.c_str());
  1828. }
  1829. // Skip this if the prefix does not exist.
  1830. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  1831. return false;
  1832. }
  1833. // PREFIX/ (useful on windows or in build trees)
  1834. if (this->SearchDirectory(prefix_in)) {
  1835. return true;
  1836. }
  1837. // Strip the trailing slash because the path generator is about to
  1838. // add one.
  1839. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1840. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  1841. {
  1842. cmFindPackageFileList lister(this);
  1843. lister / cmFileListGeneratorFixed(prefix) /
  1844. cmFileListGeneratorCaseInsensitive("cmake");
  1845. if (lister.Search()) {
  1846. return true;
  1847. }
  1848. }
  1849. // PREFIX/(Foo|foo|FOO).*/
  1850. {
  1851. cmFindPackageFileList lister(this);
  1852. lister / cmFileListGeneratorFixed(prefix) /
  1853. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1854. this->SortDirection);
  1855. if (lister.Search()) {
  1856. return true;
  1857. }
  1858. }
  1859. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  1860. {
  1861. cmFindPackageFileList lister(this);
  1862. lister / cmFileListGeneratorFixed(prefix) /
  1863. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1864. this->SortDirection) /
  1865. cmFileListGeneratorCaseInsensitive("cmake");
  1866. if (lister.Search()) {
  1867. return true;
  1868. }
  1869. }
  1870. // Construct list of common install locations (lib and share).
  1871. std::vector<std::string> common;
  1872. if (!this->LibraryArchitecture.empty()) {
  1873. common.push_back("lib/" + this->LibraryArchitecture);
  1874. }
  1875. if (this->UseLib32Paths) {
  1876. common.emplace_back("lib32");
  1877. }
  1878. if (this->UseLib64Paths) {
  1879. common.emplace_back("lib64");
  1880. }
  1881. if (this->UseLibx32Paths) {
  1882. common.emplace_back("libx32");
  1883. }
  1884. common.emplace_back("lib");
  1885. common.emplace_back("share");
  1886. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1887. {
  1888. cmFindPackageFileList lister(this);
  1889. lister / cmFileListGeneratorFixed(prefix) /
  1890. cmFileListGeneratorEnumerate(common) /
  1891. cmFileListGeneratorFixed("cmake") /
  1892. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1893. this->SortDirection);
  1894. if (lister.Search()) {
  1895. return true;
  1896. }
  1897. }
  1898. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1899. {
  1900. cmFindPackageFileList lister(this);
  1901. lister / cmFileListGeneratorFixed(prefix) /
  1902. cmFileListGeneratorEnumerate(common) /
  1903. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1904. this->SortDirection);
  1905. if (lister.Search()) {
  1906. return true;
  1907. }
  1908. }
  1909. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1910. {
  1911. cmFindPackageFileList lister(this);
  1912. lister / cmFileListGeneratorFixed(prefix) /
  1913. cmFileListGeneratorEnumerate(common) /
  1914. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1915. this->SortDirection) /
  1916. cmFileListGeneratorCaseInsensitive("cmake");
  1917. if (lister.Search()) {
  1918. return true;
  1919. }
  1920. }
  1921. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  1922. {
  1923. cmFindPackageFileList lister(this);
  1924. lister / cmFileListGeneratorFixed(prefix) /
  1925. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1926. this->SortDirection) /
  1927. cmFileListGeneratorEnumerate(common) /
  1928. cmFileListGeneratorFixed("cmake") /
  1929. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1930. this->SortDirection);
  1931. if (lister.Search()) {
  1932. return true;
  1933. }
  1934. }
  1935. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  1936. {
  1937. cmFindPackageFileList lister(this);
  1938. lister / cmFileListGeneratorFixed(prefix) /
  1939. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1940. this->SortDirection) /
  1941. cmFileListGeneratorEnumerate(common) /
  1942. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1943. this->SortDirection);
  1944. if (lister.Search()) {
  1945. return true;
  1946. }
  1947. }
  1948. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  1949. {
  1950. cmFindPackageFileList lister(this);
  1951. lister / cmFileListGeneratorFixed(prefix) /
  1952. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1953. this->SortDirection) /
  1954. cmFileListGeneratorEnumerate(common) /
  1955. cmFileListGeneratorProject(this->Names, this->SortOrder,
  1956. this->SortDirection) /
  1957. cmFileListGeneratorCaseInsensitive("cmake");
  1958. if (lister.Search()) {
  1959. return true;
  1960. }
  1961. }
  1962. return false;
  1963. }
  1964. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  1965. {
  1966. assert(!prefix_in.empty() && prefix_in.back() == '/');
  1967. if (this->DebugMode) {
  1968. fprintf(stderr, "Checking framework prefix [%s]\n", prefix_in.c_str());
  1969. }
  1970. // Strip the trailing slash because the path generator is about to
  1971. // add one.
  1972. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  1973. // <prefix>/Foo.framework/Resources/
  1974. {
  1975. cmFindPackageFileList lister(this);
  1976. lister / cmFileListGeneratorFixed(prefix) /
  1977. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1978. cmFileListGeneratorFixed("Resources");
  1979. if (lister.Search()) {
  1980. return true;
  1981. }
  1982. }
  1983. // <prefix>/Foo.framework/Resources/CMake/
  1984. {
  1985. cmFindPackageFileList lister(this);
  1986. lister / cmFileListGeneratorFixed(prefix) /
  1987. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1988. cmFileListGeneratorFixed("Resources") /
  1989. cmFileListGeneratorCaseInsensitive("cmake");
  1990. if (lister.Search()) {
  1991. return true;
  1992. }
  1993. }
  1994. // <prefix>/Foo.framework/Versions/*/Resources/
  1995. {
  1996. cmFindPackageFileList lister(this);
  1997. lister / cmFileListGeneratorFixed(prefix) /
  1998. cmFileListGeneratorMacProject(this->Names, ".framework") /
  1999. cmFileListGeneratorFixed("Versions") /
  2000. cmFileListGeneratorGlob("*/Resources");
  2001. if (lister.Search()) {
  2002. return true;
  2003. }
  2004. }
  2005. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2006. {
  2007. cmFindPackageFileList lister(this);
  2008. lister / cmFileListGeneratorFixed(prefix) /
  2009. cmFileListGeneratorMacProject(this->Names, ".framework") /
  2010. cmFileListGeneratorFixed("Versions") /
  2011. cmFileListGeneratorGlob("*/Resources") /
  2012. cmFileListGeneratorCaseInsensitive("cmake");
  2013. if (lister.Search()) {
  2014. return true;
  2015. }
  2016. }
  2017. return false;
  2018. }
  2019. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2020. {
  2021. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2022. if (this->DebugMode) {
  2023. fprintf(stderr, "Checking bundle prefix [%s]\n", prefix_in.c_str());
  2024. }
  2025. // Strip the trailing slash because the path generator is about to
  2026. // add one.
  2027. std::string prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2028. // <prefix>/Foo.app/Contents/Resources
  2029. {
  2030. cmFindPackageFileList lister(this);
  2031. lister / cmFileListGeneratorFixed(prefix) /
  2032. cmFileListGeneratorMacProject(this->Names, ".app") /
  2033. cmFileListGeneratorFixed("Contents/Resources");
  2034. if (lister.Search()) {
  2035. return true;
  2036. }
  2037. }
  2038. // <prefix>/Foo.app/Contents/Resources/CMake
  2039. {
  2040. cmFindPackageFileList lister(this);
  2041. lister / cmFileListGeneratorFixed(prefix) /
  2042. cmFileListGeneratorMacProject(this->Names, ".app") /
  2043. cmFileListGeneratorFixed("Contents/Resources") /
  2044. cmFileListGeneratorCaseInsensitive("cmake");
  2045. if (lister.Search()) {
  2046. return true;
  2047. }
  2048. }
  2049. return false;
  2050. }
  2051. // TODO: Debug cmsys::Glob double slash problem.