cmFindPackageCommand.cxx 70 KB

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