cmFindPackageCommand.cxx 69 KB

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