GetPrerequisites.cmake 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. GetPrerequisites
  5. ----------------
  6. Functions to analyze and list executable file prerequisites.
  7. This module provides functions to list the .dll, .dylib or .so files
  8. that an executable or shared library file depends on. (Its
  9. prerequisites.)
  10. It uses various tools to obtain the list of required shared library
  11. files:
  12. ::
  13. dumpbin (Windows)
  14. objdump (MinGW on Windows)
  15. ldd (Linux/Unix)
  16. otool (Mac OSX)
  17. The following functions are provided by this module:
  18. ::
  19. get_prerequisites
  20. list_prerequisites
  21. list_prerequisites_by_glob
  22. gp_append_unique
  23. is_file_executable
  24. gp_item_default_embedded_path
  25. (projects can override with gp_item_default_embedded_path_override)
  26. gp_resolve_item
  27. (projects can override with gp_resolve_item_override)
  28. gp_resolved_file_type
  29. (projects can override with gp_resolved_file_type_override)
  30. gp_file_type
  31. Requires CMake 2.6 or greater because it uses function, break, return
  32. and PARENT_SCOPE.
  33. ::
  34. GET_PREREQUISITES(<target> <prerequisites_var> <exclude_system> <recurse>
  35. <exepath> <dirs> [<rpaths>])
  36. Get the list of shared library files required by <target>. The list
  37. in the variable named <prerequisites_var> should be empty on first
  38. entry to this function. On exit, <prerequisites_var> will contain the
  39. list of required shared library files.
  40. <target> is the full path to an executable file. <prerequisites_var>
  41. is the name of a CMake variable to contain the results.
  42. <exclude_system> must be 0 or 1 indicating whether to include or
  43. exclude "system" prerequisites. If <recurse> is set to 1 all
  44. prerequisites will be found recursively, if set to 0 only direct
  45. prerequisites are listed. <exepath> is the path to the top level
  46. executable used for @executable_path replacment on the Mac. <dirs> is
  47. a list of paths where libraries might be found: these paths are
  48. searched first when a target without any path info is given. Then
  49. standard system locations are also searched: PATH, Framework
  50. locations, /usr/lib...
  51. The variable GET_PREREQUISITES_VERBOSE can be set to true to enable verbose
  52. output.
  53. ::
  54. LIST_PREREQUISITES(<target> [<recurse> [<exclude_system> [<verbose>]]])
  55. Print a message listing the prerequisites of <target>.
  56. <target> is the name of a shared library or executable target or the
  57. full path to a shared library or executable file. If <recurse> is set
  58. to 1 all prerequisites will be found recursively, if set to 0 only
  59. direct prerequisites are listed. <exclude_system> must be 0 or 1
  60. indicating whether to include or exclude "system" prerequisites. With
  61. <verbose> set to 0 only the full path names of the prerequisites are
  62. printed, set to 1 extra informatin will be displayed.
  63. ::
  64. LIST_PREREQUISITES_BY_GLOB(<glob_arg> <glob_exp>)
  65. Print the prerequisites of shared library and executable files
  66. matching a globbing pattern. <glob_arg> is GLOB or GLOB_RECURSE and
  67. <glob_exp> is a globbing expression used with "file(GLOB" or
  68. "file(GLOB_RECURSE" to retrieve a list of matching files. If a
  69. matching file is executable, its prerequisites are listed.
  70. Any additional (optional) arguments provided are passed along as the
  71. optional arguments to the list_prerequisites calls.
  72. ::
  73. GP_APPEND_UNIQUE(<list_var> <value>)
  74. Append <value> to the list variable <list_var> only if the value is
  75. not already in the list.
  76. ::
  77. IS_FILE_EXECUTABLE(<file> <result_var>)
  78. Return 1 in <result_var> if <file> is a binary executable, 0
  79. otherwise.
  80. ::
  81. GP_ITEM_DEFAULT_EMBEDDED_PATH(<item> <default_embedded_path_var>)
  82. Return the path that others should refer to the item by when the item
  83. is embedded inside a bundle.
  84. Override on a per-project basis by providing a project-specific
  85. gp_item_default_embedded_path_override function.
  86. ::
  87. GP_RESOLVE_ITEM(<context> <item> <exepath> <dirs> <resolved_item_var>
  88. [<rpaths>])
  89. Resolve an item into an existing full path file.
  90. Override on a per-project basis by providing a project-specific
  91. gp_resolve_item_override function.
  92. ::
  93. GP_RESOLVED_FILE_TYPE(<original_file> <file> <exepath> <dirs> <type_var>
  94. [<rpaths>])
  95. Return the type of <file> with respect to <original_file>. String
  96. describing type of prerequisite is returned in variable named
  97. <type_var>.
  98. Use <exepath> and <dirs> if necessary to resolve non-absolute <file>
  99. values -- but only for non-embedded items.
  100. Possible types are:
  101. ::
  102. system
  103. local
  104. embedded
  105. other
  106. Override on a per-project basis by providing a project-specific
  107. gp_resolved_file_type_override function.
  108. ::
  109. GP_FILE_TYPE(<original_file> <file> <type_var>)
  110. Return the type of <file> with respect to <original_file>. String
  111. describing type of prerequisite is returned in variable named
  112. <type_var>.
  113. Possible types are:
  114. ::
  115. system
  116. local
  117. embedded
  118. other
  119. #]=======================================================================]
  120. function(gp_append_unique list_var value)
  121. set(contains 0)
  122. foreach(item ${${list_var}})
  123. if(item STREQUAL "${value}")
  124. set(contains 1)
  125. break()
  126. endif()
  127. endforeach()
  128. if(NOT contains)
  129. set(${list_var} ${${list_var}} "${value}" PARENT_SCOPE)
  130. endif()
  131. endfunction()
  132. function(is_file_executable file result_var)
  133. #
  134. # A file is not executable until proven otherwise:
  135. #
  136. set(${result_var} 0 PARENT_SCOPE)
  137. get_filename_component(file_full "${file}" ABSOLUTE)
  138. string(TOLOWER "${file_full}" file_full_lower)
  139. # If file name ends in .exe on Windows, *assume* executable:
  140. #
  141. if(WIN32 AND NOT UNIX)
  142. if("${file_full_lower}" MATCHES "\\.exe$")
  143. set(${result_var} 1 PARENT_SCOPE)
  144. return()
  145. endif()
  146. # A clause could be added here that uses output or return value of dumpbin
  147. # to determine ${result_var}. In 99%+? practical cases, the exe name
  148. # match will be sufficient...
  149. #
  150. endif()
  151. # Use the information returned from the Unix shell command "file" to
  152. # determine if ${file_full} should be considered an executable file...
  153. #
  154. # If the file command's output contains "executable" and does *not* contain
  155. # "text" then it is likely an executable suitable for prerequisite analysis
  156. # via the get_prerequisites macro.
  157. #
  158. if(UNIX)
  159. if(NOT file_cmd)
  160. find_program(file_cmd "file")
  161. mark_as_advanced(file_cmd)
  162. endif()
  163. if(file_cmd)
  164. execute_process(COMMAND "${file_cmd}" "${file_full}"
  165. RESULT_VARIABLE file_rv
  166. OUTPUT_VARIABLE file_ov
  167. ERROR_VARIABLE file_ev
  168. OUTPUT_STRIP_TRAILING_WHITESPACE
  169. )
  170. if(NOT file_rv STREQUAL "0")
  171. message(FATAL_ERROR "${file_cmd} failed: ${file_rv}\n${file_ev}")
  172. endif()
  173. # Replace the name of the file in the output with a placeholder token
  174. # (the string " _file_full_ ") so that just in case the path name of
  175. # the file contains the word "text" or "executable" we are not fooled
  176. # into thinking "the wrong thing" because the file name matches the
  177. # other 'file' command output we are looking for...
  178. #
  179. string(REPLACE "${file_full}" " _file_full_ " file_ov "${file_ov}")
  180. string(TOLOWER "${file_ov}" file_ov)
  181. #message(STATUS "file_ov='${file_ov}'")
  182. if("${file_ov}" MATCHES "executable")
  183. #message(STATUS "executable!")
  184. if("${file_ov}" MATCHES "text")
  185. #message(STATUS "but text, so *not* a binary executable!")
  186. else()
  187. set(${result_var} 1 PARENT_SCOPE)
  188. return()
  189. endif()
  190. endif()
  191. # Also detect position independent executables on Linux,
  192. # where "file" gives "shared object ... (uses shared libraries)"
  193. if("${file_ov}" MATCHES "shared object.*\(uses shared libs\)")
  194. set(${result_var} 1 PARENT_SCOPE)
  195. return()
  196. endif()
  197. # "file" version 5.22 does not print "(used shared libraries)"
  198. # but uses "interpreter"
  199. if("${file_ov}" MATCHES "shared object.*interpreter")
  200. set(${result_var} 1 PARENT_SCOPE)
  201. return()
  202. endif()
  203. else()
  204. message(STATUS "warning: No 'file' command, skipping execute_process...")
  205. endif()
  206. endif()
  207. endfunction()
  208. function(gp_item_default_embedded_path item default_embedded_path_var)
  209. # On Windows and Linux, "embed" prerequisites in the same directory
  210. # as the executable by default:
  211. #
  212. set(path "@executable_path")
  213. # On the Mac, relative to the executable depending on the type
  214. # of the thing we are embedding:
  215. #
  216. if(APPLE)
  217. #
  218. # The assumption here is that all executables in the bundle will be
  219. # in same-level-directories inside the bundle. The parent directory
  220. # of an executable inside the bundle should be MacOS or a sibling of
  221. # MacOS and all embedded paths returned from here will begin with
  222. # "@executable_path/../" and will work from all executables in all
  223. # such same-level-directories inside the bundle.
  224. #
  225. # By default, embed things right next to the main bundle executable:
  226. #
  227. set(path "@executable_path/../../Contents/MacOS")
  228. # Embed frameworks and .dylibs in the embedded "Frameworks" directory
  229. # (sibling of MacOS):
  230. #
  231. if(item MATCHES "[^/]+\\.framework/" OR item MATCHES "\\.dylib$")
  232. set(path "@executable_path/../Frameworks")
  233. endif()
  234. endif()
  235. # Provide a hook so that projects can override the default embedded location
  236. # of any given library by whatever logic they choose:
  237. #
  238. if(COMMAND gp_item_default_embedded_path_override)
  239. gp_item_default_embedded_path_override("${item}" path)
  240. endif()
  241. set(${default_embedded_path_var} "${path}" PARENT_SCOPE)
  242. endfunction()
  243. function(gp_resolve_item context item exepath dirs resolved_item_var)
  244. set(resolved 0)
  245. set(resolved_item "${item}")
  246. if(ARGC GREATER 5)
  247. set(rpaths "${ARGV5}")
  248. else()
  249. set(rpaths "")
  250. endif()
  251. # Is it already resolved?
  252. #
  253. if(IS_ABSOLUTE "${resolved_item}" AND EXISTS "${resolved_item}")
  254. set(resolved 1)
  255. endif()
  256. if(NOT resolved)
  257. if(item MATCHES "^@executable_path")
  258. #
  259. # @executable_path references are assumed relative to exepath
  260. #
  261. string(REPLACE "@executable_path" "${exepath}" ri "${item}")
  262. get_filename_component(ri "${ri}" ABSOLUTE)
  263. if(EXISTS "${ri}")
  264. #message(STATUS "info: embedded item exists (${ri})")
  265. set(resolved 1)
  266. set(resolved_item "${ri}")
  267. else()
  268. message(STATUS "warning: embedded item does not exist '${ri}'")
  269. endif()
  270. endif()
  271. endif()
  272. if(NOT resolved)
  273. if(item MATCHES "^@loader_path")
  274. #
  275. # @loader_path references are assumed relative to the
  276. # PATH of the given "context" (presumably another library)
  277. #
  278. get_filename_component(contextpath "${context}" PATH)
  279. string(REPLACE "@loader_path" "${contextpath}" ri "${item}")
  280. get_filename_component(ri "${ri}" ABSOLUTE)
  281. if(EXISTS "${ri}")
  282. #message(STATUS "info: embedded item exists (${ri})")
  283. set(resolved 1)
  284. set(resolved_item "${ri}")
  285. else()
  286. message(STATUS "warning: embedded item does not exist '${ri}'")
  287. endif()
  288. endif()
  289. endif()
  290. if(NOT resolved)
  291. if(item MATCHES "^@rpath")
  292. #
  293. # @rpath references are relative to the paths built into the binaries with -rpath
  294. # We handle this case like we do for other Unixes
  295. #
  296. string(REPLACE "@rpath/" "" norpath_item "${item}")
  297. set(ri "ri-NOTFOUND")
  298. find_file(ri "${norpath_item}" ${exepath} ${dirs} ${rpaths} NO_DEFAULT_PATH)
  299. if(ri)
  300. #message(STATUS "info: 'find_file' in exepath/dirs/rpaths (${ri})")
  301. set(resolved 1)
  302. set(resolved_item "${ri}")
  303. set(ri "ri-NOTFOUND")
  304. endif()
  305. endif()
  306. endif()
  307. if(NOT resolved)
  308. set(ri "ri-NOTFOUND")
  309. find_file(ri "${item}" ${exepath} ${dirs} NO_DEFAULT_PATH)
  310. find_file(ri "${item}" ${exepath} ${dirs} /usr/lib)
  311. get_filename_component(basename_item "${item}" NAME)
  312. find_file(ri "${basename_item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  313. find_file(ri "${basename_item}" PATHS /usr/lib)
  314. if(ri)
  315. #message(STATUS "info: 'find_file' in exepath/dirs (${ri})")
  316. set(resolved 1)
  317. set(resolved_item "${ri}")
  318. set(ri "ri-NOTFOUND")
  319. endif()
  320. endif()
  321. if(NOT resolved)
  322. if(item MATCHES "[^/]+\\.framework/")
  323. set(fw "fw-NOTFOUND")
  324. find_file(fw "${item}"
  325. "~/Library/Frameworks"
  326. "/Library/Frameworks"
  327. "/System/Library/Frameworks"
  328. )
  329. if(fw)
  330. #message(STATUS "info: 'find_file' found framework (${fw})")
  331. set(resolved 1)
  332. set(resolved_item "${fw}")
  333. set(fw "fw-NOTFOUND")
  334. endif()
  335. endif()
  336. endif()
  337. # Using find_program on Windows will find dll files that are in the PATH.
  338. # (Converting simple file names into full path names if found.)
  339. #
  340. if(WIN32 AND NOT UNIX)
  341. if(NOT resolved)
  342. set(ri "ri-NOTFOUND")
  343. find_program(ri "${item}" PATHS ${exepath} ${dirs} NO_DEFAULT_PATH)
  344. find_program(ri "${item}" PATHS ${exepath} ${dirs})
  345. if(ri)
  346. #message(STATUS "info: 'find_program' in exepath/dirs (${ri})")
  347. set(resolved 1)
  348. set(resolved_item "${ri}")
  349. set(ri "ri-NOTFOUND")
  350. endif()
  351. endif()
  352. endif()
  353. # Provide a hook so that projects can override item resolution
  354. # by whatever logic they choose:
  355. #
  356. if(COMMAND gp_resolve_item_override)
  357. gp_resolve_item_override("${context}" "${item}" "${exepath}" "${dirs}" resolved_item resolved)
  358. endif()
  359. if(NOT resolved)
  360. message(STATUS "
  361. warning: cannot resolve item '${item}'
  362. possible problems:
  363. need more directories?
  364. need to use InstallRequiredSystemLibraries?
  365. run in install tree instead of build tree?
  366. ")
  367. # message(STATUS "
  368. #******************************************************************************
  369. #warning: cannot resolve item '${item}'
  370. #
  371. # possible problems:
  372. # need more directories?
  373. # need to use InstallRequiredSystemLibraries?
  374. # run in install tree instead of build tree?
  375. #
  376. # context='${context}'
  377. # item='${item}'
  378. # exepath='${exepath}'
  379. # dirs='${dirs}'
  380. # resolved_item_var='${resolved_item_var}'
  381. #******************************************************************************
  382. #")
  383. endif()
  384. set(${resolved_item_var} "${resolved_item}" PARENT_SCOPE)
  385. endfunction()
  386. function(gp_resolved_file_type original_file file exepath dirs type_var)
  387. if(ARGC GREATER 5)
  388. set(rpaths "${ARGV5}")
  389. else()
  390. set(rpaths "")
  391. endif()
  392. #message(STATUS "**")
  393. if(NOT IS_ABSOLUTE "${original_file}")
  394. message(STATUS "warning: gp_resolved_file_type expects absolute full path for first arg original_file")
  395. endif()
  396. if(IS_ABSOLUTE "${original_file}")
  397. get_filename_component(original_file "${original_file}" ABSOLUTE) # canonicalize path
  398. endif()
  399. set(is_embedded 0)
  400. set(is_local 0)
  401. set(is_system 0)
  402. set(resolved_file "${file}")
  403. if("${file}" MATCHES "^@(executable|loader)_path")
  404. set(is_embedded 1)
  405. endif()
  406. if(NOT is_embedded)
  407. if(NOT IS_ABSOLUTE "${file}")
  408. gp_resolve_item("${original_file}" "${file}" "${exepath}" "${dirs}" resolved_file "${rpaths}")
  409. endif()
  410. if(IS_ABSOLUTE "${resolved_file}")
  411. get_filename_component(resolved_file "${resolved_file}" ABSOLUTE) # canonicalize path
  412. endif()
  413. string(TOLOWER "${original_file}" original_lower)
  414. string(TOLOWER "${resolved_file}" lower)
  415. if(UNIX)
  416. if(resolved_file MATCHES "^(/lib/|/lib32/|/libx32/|/lib64/|/usr/lib/|/usr/lib32/|/usr/libx32/|/usr/lib64/|/usr/X11R6/|/usr/bin/)")
  417. set(is_system 1)
  418. endif()
  419. endif()
  420. if(APPLE)
  421. if(resolved_file MATCHES "^(/System/Library/|/usr/lib/)")
  422. set(is_system 1)
  423. endif()
  424. endif()
  425. if(WIN32)
  426. string(TOLOWER "$ENV{SystemRoot}" sysroot)
  427. file(TO_CMAKE_PATH "${sysroot}" sysroot)
  428. string(TOLOWER "$ENV{windir}" windir)
  429. file(TO_CMAKE_PATH "${windir}" windir)
  430. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-)[^/]+dll)")
  431. set(is_system 1)
  432. endif()
  433. if(UNIX)
  434. # if cygwin, we can get the properly formed windows paths from cygpath
  435. find_program(CYGPATH_EXECUTABLE cygpath)
  436. if(CYGPATH_EXECUTABLE)
  437. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -W
  438. RESULT_VARIABLE env_rv
  439. OUTPUT_VARIABLE env_windir
  440. ERROR_VARIABLE env_ev
  441. OUTPUT_STRIP_TRAILING_WHITESPACE)
  442. if(NOT env_rv STREQUAL "0")
  443. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -W failed: ${env_rv}\n${env_ev}")
  444. endif()
  445. execute_process(COMMAND ${CYGPATH_EXECUTABLE} -S
  446. RESULT_VARIABLE env_rv
  447. OUTPUT_VARIABLE env_sysdir
  448. ERROR_VARIABLE env_ev
  449. OUTPUT_STRIP_TRAILING_WHITESPACE)
  450. if(NOT env_rv STREQUAL "0")
  451. message(FATAL_ERROR "${CYGPATH_EXECUTABLE} -S failed: ${env_rv}\n${env_ev}")
  452. endif()
  453. string(TOLOWER "${env_windir}" windir)
  454. string(TOLOWER "${env_sysdir}" sysroot)
  455. if(lower MATCHES "^(${sysroot}/sys(tem|wow)|${windir}/sys(tem|wow)|(.*/)*(msvc|api-ms-win-)[^/]+dll)")
  456. set(is_system 1)
  457. endif()
  458. endif()
  459. endif()
  460. endif()
  461. if(NOT is_system)
  462. get_filename_component(original_path "${original_lower}" PATH)
  463. get_filename_component(path "${lower}" PATH)
  464. if(original_path STREQUAL path)
  465. set(is_local 1)
  466. else()
  467. string(LENGTH "${original_path}/" original_length)
  468. string(LENGTH "${lower}" path_length)
  469. if(${path_length} GREATER ${original_length})
  470. string(SUBSTRING "${lower}" 0 ${original_length} path)
  471. if("${original_path}/" STREQUAL path)
  472. set(is_embedded 1)
  473. endif()
  474. endif()
  475. endif()
  476. endif()
  477. endif()
  478. # Return type string based on computed booleans:
  479. #
  480. set(type "other")
  481. if(is_system)
  482. set(type "system")
  483. elseif(is_embedded)
  484. set(type "embedded")
  485. elseif(is_local)
  486. set(type "local")
  487. endif()
  488. #message(STATUS "gp_resolved_file_type: '${file}' '${resolved_file}'")
  489. #message(STATUS " type: '${type}'")
  490. if(NOT is_embedded)
  491. if(NOT IS_ABSOLUTE "${resolved_file}")
  492. if(lower MATCHES "^(msvc|api-ms-win-)[^/]+dll" AND is_system)
  493. message(STATUS "info: non-absolute msvc file '${file}' returning type '${type}'")
  494. else()
  495. message(STATUS "warning: gp_resolved_file_type non-absolute file '${file}' returning type '${type}' -- possibly incorrect")
  496. endif()
  497. endif()
  498. endif()
  499. # Provide a hook so that projects can override the decision on whether a
  500. # library belongs to the system or not by whatever logic they choose:
  501. #
  502. if(COMMAND gp_resolved_file_type_override)
  503. gp_resolved_file_type_override("${resolved_file}" type)
  504. endif()
  505. set(${type_var} "${type}" PARENT_SCOPE)
  506. #message(STATUS "**")
  507. endfunction()
  508. function(gp_file_type original_file file type_var)
  509. if(NOT IS_ABSOLUTE "${original_file}")
  510. message(STATUS "warning: gp_file_type expects absolute full path for first arg original_file")
  511. endif()
  512. get_filename_component(exepath "${original_file}" PATH)
  513. set(type "")
  514. gp_resolved_file_type("${original_file}" "${file}" "${exepath}" "" type)
  515. set(${type_var} "${type}" PARENT_SCOPE)
  516. endfunction()
  517. function(get_prerequisites target prerequisites_var exclude_system recurse exepath dirs)
  518. set(verbose 0)
  519. set(eol_char "E")
  520. if(ARGC GREATER 6)
  521. set(rpaths "${ARGV6}")
  522. else()
  523. set(rpaths "")
  524. endif()
  525. if(GET_PREREQUISITES_VERBOSE)
  526. set(verbose 1)
  527. endif()
  528. if(NOT IS_ABSOLUTE "${target}")
  529. message("warning: target '${target}' is not absolute...")
  530. endif()
  531. if(NOT EXISTS "${target}")
  532. message("warning: target '${target}' does not exist...")
  533. return()
  534. endif()
  535. # Check for a script by extension (.bat,.sh,...) or if the file starts with "#!" (shebang)
  536. file(READ ${target} file_contents LIMIT 5)
  537. if(target MATCHES "\\.(bat|c?sh|bash|ksh|cmd)$" OR file_contents MATCHES "^#!")
  538. message(STATUS "GetPrequisites(${target}) : ignoring script file")
  539. # Clear var
  540. set(${prerequisites_var} "" PARENT_SCOPE)
  541. return()
  542. endif()
  543. set(gp_cmd_paths ${gp_cmd_paths}
  544. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\14.0;InstallDir]/../../VC/bin"
  545. "$ENV{VS140COMNTOOLS}/../../VC/bin"
  546. "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin"
  547. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\12.0;InstallDir]/../../VC/bin"
  548. "$ENV{VS120COMNTOOLS}/../../VC/bin"
  549. "C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin"
  550. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0;InstallDir]/../../VC/bin"
  551. "$ENV{VS110COMNTOOLS}/../../VC/bin"
  552. "C:/Program Files (x86)/Microsoft Visual Studio 11.0/VC/bin"
  553. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\10.0;InstallDir]/../../VC/bin"
  554. "$ENV{VS100COMNTOOLS}/../../VC/bin"
  555. "C:/Program Files (x86)/Microsoft Visual Studio 10.0/VC/bin"
  556. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0;InstallDir]/../../VC/bin"
  557. "$ENV{VS90COMNTOOLS}/../../VC/bin"
  558. "C:/Program Files/Microsoft Visual Studio 9.0/VC/bin"
  559. "C:/Program Files (x86)/Microsoft Visual Studio 9.0/VC/bin"
  560. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]/../../VC/bin"
  561. "$ENV{VS80COMNTOOLS}/../../VC/bin"
  562. "C:/Program Files/Microsoft Visual Studio 8/VC/BIN"
  563. "C:/Program Files (x86)/Microsoft Visual Studio 8/VC/BIN"
  564. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\7.1;InstallDir]/../../VC7/bin"
  565. "$ENV{VS71COMNTOOLS}/../../VC7/bin"
  566. "C:/Program Files/Microsoft Visual Studio .NET 2003/VC7/BIN"
  567. "C:/Program Files (x86)/Microsoft Visual Studio .NET 2003/VC7/BIN"
  568. )
  569. # <setup-gp_tool-vars>
  570. #
  571. # Try to choose the right tool by default. Caller can set gp_tool prior to
  572. # calling this function to force using a different tool.
  573. #
  574. if(NOT gp_tool)
  575. set(gp_tool "ldd")
  576. if(APPLE)
  577. set(gp_tool "otool")
  578. endif()
  579. if(WIN32 AND NOT UNIX) # This is how to check for cygwin, har!
  580. find_program(gp_dumpbin "dumpbin" PATHS ${gp_cmd_paths})
  581. if(gp_dumpbin)
  582. set(gp_tool "dumpbin")
  583. else() # Try harder. Maybe we're on MinGW
  584. set(gp_tool "objdump")
  585. endif()
  586. endif()
  587. endif()
  588. find_program(gp_cmd ${gp_tool} PATHS ${gp_cmd_paths})
  589. if(NOT gp_cmd)
  590. message(STATUS "warning: could not find '${gp_tool}' - cannot analyze prerequisites...")
  591. return()
  592. endif()
  593. set(gp_cmd_maybe_filter) # optional command to pre-filter gp_tool results
  594. if(gp_tool MATCHES "ldd$")
  595. set(gp_cmd_args "")
  596. set(gp_regex "^[\t ]*[^\t ]+ => ([^\t\(]+) .*${eol_char}$")
  597. set(gp_regex_error "not found${eol_char}$")
  598. set(gp_regex_fallback "^[\t ]*([^\t ]+) => ([^\t ]+).*${eol_char}$")
  599. set(gp_regex_cmp_count 1)
  600. elseif(gp_tool MATCHES "otool$")
  601. set(gp_cmd_args "-L")
  602. set(gp_regex "^\t([^\t]+) \\(compatibility version ([0-9]+.[0-9]+.[0-9]+), current version ([0-9]+.[0-9]+.[0-9]+)\\)${eol_char}$")
  603. set(gp_regex_error "")
  604. set(gp_regex_fallback "")
  605. set(gp_regex_cmp_count 3)
  606. elseif(gp_tool MATCHES "dumpbin$")
  607. set(gp_cmd_args "/dependents")
  608. set(gp_regex "^ ([^ ].*[Dd][Ll][Ll])${eol_char}$")
  609. set(gp_regex_error "")
  610. set(gp_regex_fallback "")
  611. set(gp_regex_cmp_count 1)
  612. elseif(gp_tool MATCHES "objdump$")
  613. set(gp_cmd_args "-p")
  614. set(gp_regex "^\t*DLL Name: (.*\\.[Dd][Ll][Ll])${eol_char}$")
  615. set(gp_regex_error "")
  616. set(gp_regex_fallback "")
  617. set(gp_regex_cmp_count 1)
  618. # objdump generates copious output so we create a grep filter to pre-filter results
  619. if(WIN32)
  620. find_program(gp_grep_cmd findstr)
  621. else()
  622. find_program(gp_grep_cmd grep)
  623. endif()
  624. if(gp_grep_cmd)
  625. set(gp_cmd_maybe_filter COMMAND ${gp_grep_cmd} "-a" "^[[:blank:]]*DLL Name: ")
  626. endif()
  627. else()
  628. message(STATUS "warning: gp_tool='${gp_tool}' is an unknown tool...")
  629. message(STATUS "CMake function get_prerequisites needs more code to handle '${gp_tool}'")
  630. message(STATUS "Valid gp_tool values are dumpbin, ldd, objdump and otool.")
  631. return()
  632. endif()
  633. if(gp_tool MATCHES "dumpbin$")
  634. # When running dumpbin, it also needs the "Common7/IDE" directory in the
  635. # PATH. It will already be in the PATH if being run from a Visual Studio
  636. # command prompt. Add it to the PATH here in case we are running from a
  637. # different command prompt.
  638. #
  639. get_filename_component(gp_cmd_dir "${gp_cmd}" PATH)
  640. get_filename_component(gp_cmd_dlls_dir "${gp_cmd_dir}/../../Common7/IDE" ABSOLUTE)
  641. # Use cmake paths as a user may have a PATH element ending with a backslash.
  642. # This will escape the list delimiter and create havoc!
  643. if(EXISTS "${gp_cmd_dlls_dir}")
  644. # only add to the path if it is not already in the path
  645. set(gp_found_cmd_dlls_dir 0)
  646. file(TO_CMAKE_PATH "$ENV{PATH}" env_path)
  647. foreach(gp_env_path_element ${env_path})
  648. if(gp_env_path_element STREQUAL gp_cmd_dlls_dir)
  649. set(gp_found_cmd_dlls_dir 1)
  650. endif()
  651. endforeach()
  652. if(NOT gp_found_cmd_dlls_dir)
  653. file(TO_NATIVE_PATH "${gp_cmd_dlls_dir}" gp_cmd_dlls_dir)
  654. set(ENV{PATH} "$ENV{PATH};${gp_cmd_dlls_dir}")
  655. endif()
  656. endif()
  657. endif()
  658. #
  659. # </setup-gp_tool-vars>
  660. if(gp_tool MATCHES "ldd$")
  661. set(old_ld_env "$ENV{LD_LIBRARY_PATH}")
  662. set(new_ld_env "${exepath}")
  663. foreach(dir ${dirs})
  664. string(APPEND new_ld_env ":${dir}")
  665. endforeach()
  666. set(ENV{LD_LIBRARY_PATH} "${new_ld_env}:$ENV{LD_LIBRARY_PATH}")
  667. endif()
  668. # Track new prerequisites at each new level of recursion. Start with an
  669. # empty list at each level:
  670. #
  671. set(unseen_prereqs)
  672. # Run gp_cmd on the target:
  673. #
  674. execute_process(
  675. COMMAND ${gp_cmd} ${gp_cmd_args} ${target}
  676. ${gp_cmd_maybe_filter}
  677. RESULT_VARIABLE gp_rv
  678. OUTPUT_VARIABLE gp_cmd_ov
  679. ERROR_VARIABLE gp_ev
  680. )
  681. if(gp_tool MATCHES "dumpbin$")
  682. # Exclude delay load dependencies under windows (they are listed in dumpbin output after the message below)
  683. string(FIND "${gp_cmd_ov}" "Image has the following delay load dependencies" gp_delayload_pos)
  684. if (${gp_delayload_pos} GREATER -1)
  685. string(SUBSTRING "${gp_cmd_ov}" 0 ${gp_delayload_pos} gp_cmd_ov_no_delayload_deps)
  686. string(SUBSTRING "${gp_cmd_ov}" ${gp_delayload_pos} -1 gp_cmd_ov_delayload_deps)
  687. if (verbose)
  688. message(STATUS "GetPrequisites(${target}) : ignoring the following delay load dependencies :\n ${gp_cmd_ov_delayload_deps}")
  689. endif()
  690. set(gp_cmd_ov ${gp_cmd_ov_no_delayload_deps})
  691. endif()
  692. endif()
  693. if(NOT gp_rv STREQUAL "0")
  694. if(gp_tool MATCHES "dumpbin$")
  695. # dumpbin error messages seem to go to stdout
  696. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}\n${gp_cmd_ov}")
  697. else()
  698. message(FATAL_ERROR "${gp_cmd} failed: ${gp_rv}\n${gp_ev}")
  699. endif()
  700. endif()
  701. if(gp_tool MATCHES "ldd$")
  702. set(ENV{LD_LIBRARY_PATH} "${old_ld_env}")
  703. endif()
  704. if(verbose)
  705. message(STATUS "<RawOutput cmd='${gp_cmd} ${gp_cmd_args} ${target}'>")
  706. message(STATUS "gp_cmd_ov='${gp_cmd_ov}'")
  707. message(STATUS "</RawOutput>")
  708. endif()
  709. get_filename_component(target_dir "${target}" PATH)
  710. # Convert to a list of lines:
  711. #
  712. string(REPLACE ";" "\\;" candidates "${gp_cmd_ov}")
  713. string(REPLACE "\n" "${eol_char};" candidates "${candidates}")
  714. # check for install id and remove it from list, since otool -L can include a
  715. # reference to itself
  716. set(gp_install_id)
  717. if(gp_tool MATCHES "otool$")
  718. execute_process(
  719. COMMAND ${gp_cmd} -D ${target}
  720. RESULT_VARIABLE otool_rv
  721. OUTPUT_VARIABLE gp_install_id_ov
  722. ERROR_VARIABLE otool_ev
  723. )
  724. if(NOT otool_rv STREQUAL "0")
  725. message(FATAL_ERROR "otool -D failed: ${otool_rv}\n${otool_ev}")
  726. endif()
  727. # second line is install name
  728. string(REGEX REPLACE ".*:\n" "" gp_install_id "${gp_install_id_ov}")
  729. if(gp_install_id)
  730. # trim
  731. string(REGEX MATCH "[^\n ].*[^\n ]" gp_install_id "${gp_install_id}")
  732. #message("INSTALL ID is \"${gp_install_id}\"")
  733. endif()
  734. endif()
  735. # Analyze each line for file names that match the regular expression:
  736. #
  737. foreach(candidate ${candidates})
  738. if("${candidate}" MATCHES "${gp_regex}")
  739. # Extract information from each candidate:
  740. if(gp_regex_error AND "${candidate}" MATCHES "${gp_regex_error}")
  741. string(REGEX REPLACE "${gp_regex_fallback}" "\\1" raw_item "${candidate}")
  742. else()
  743. string(REGEX REPLACE "${gp_regex}" "\\1" raw_item "${candidate}")
  744. endif()
  745. if(gp_regex_cmp_count GREATER 1)
  746. string(REGEX REPLACE "${gp_regex}" "\\2" raw_compat_version "${candidate}")
  747. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" compat_major_version "${raw_compat_version}")
  748. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" compat_minor_version "${raw_compat_version}")
  749. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" compat_patch_version "${raw_compat_version}")
  750. endif()
  751. if(gp_regex_cmp_count GREATER 2)
  752. string(REGEX REPLACE "${gp_regex}" "\\3" raw_current_version "${candidate}")
  753. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\1" current_major_version "${raw_current_version}")
  754. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\2" current_minor_version "${raw_current_version}")
  755. string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$" "\\3" current_patch_version "${raw_current_version}")
  756. endif()
  757. # Use the raw_item as the list entries returned by this function. Use the
  758. # gp_resolve_item function to resolve it to an actual full path file if
  759. # necessary.
  760. #
  761. set(item "${raw_item}")
  762. # Add each item unless it is excluded:
  763. #
  764. set(add_item 1)
  765. if(item STREQUAL gp_install_id)
  766. set(add_item 0)
  767. endif()
  768. if(add_item AND ${exclude_system})
  769. set(type "")
  770. gp_resolved_file_type("${target}" "${item}" "${exepath}" "${dirs}" type "${rpaths}")
  771. if(type STREQUAL "system")
  772. set(add_item 0)
  773. endif()
  774. endif()
  775. if(add_item)
  776. list(LENGTH ${prerequisites_var} list_length_before_append)
  777. gp_append_unique(${prerequisites_var} "${item}")
  778. list(LENGTH ${prerequisites_var} list_length_after_append)
  779. if(${recurse})
  780. # If item was really added, this is the first time we have seen it.
  781. # Add it to unseen_prereqs so that we can recursively add *its*
  782. # prerequisites...
  783. #
  784. # But first: resolve its name to an absolute full path name such
  785. # that the analysis tools can simply accept it as input.
  786. #
  787. if(NOT list_length_before_append EQUAL list_length_after_append)
  788. gp_resolve_item("${target}" "${item}" "${exepath}" "${dirs}" resolved_item "${rpaths}")
  789. if(EXISTS "${resolved_item}")
  790. # Recurse only if we could resolve the item.
  791. # Otherwise the prerequisites_var list will be cleared
  792. set(unseen_prereqs ${unseen_prereqs} "${resolved_item}")
  793. endif()
  794. endif()
  795. endif()
  796. endif()
  797. else()
  798. if(verbose)
  799. message(STATUS "ignoring non-matching line: '${candidate}'")
  800. endif()
  801. endif()
  802. endforeach()
  803. list(LENGTH ${prerequisites_var} prerequisites_var_length)
  804. if(prerequisites_var_length GREATER 0)
  805. list(SORT ${prerequisites_var})
  806. endif()
  807. if(${recurse})
  808. set(more_inputs ${unseen_prereqs})
  809. foreach(input ${more_inputs})
  810. get_prerequisites("${input}" ${prerequisites_var} ${exclude_system} ${recurse} "${exepath}" "${dirs}" "${rpaths}")
  811. endforeach()
  812. endif()
  813. set(${prerequisites_var} ${${prerequisites_var}} PARENT_SCOPE)
  814. endfunction()
  815. function(list_prerequisites target)
  816. if(ARGC GREATER 1 AND NOT "${ARGV1}" STREQUAL "")
  817. set(all "${ARGV1}")
  818. else()
  819. set(all 1)
  820. endif()
  821. if(ARGC GREATER 2 AND NOT "${ARGV2}" STREQUAL "")
  822. set(exclude_system "${ARGV2}")
  823. else()
  824. set(exclude_system 0)
  825. endif()
  826. if(ARGC GREATER 3 AND NOT "${ARGV3}" STREQUAL "")
  827. set(verbose "${ARGV3}")
  828. else()
  829. set(verbose 0)
  830. endif()
  831. set(count 0)
  832. set(count_str "")
  833. set(print_count "${verbose}")
  834. set(print_prerequisite_type "${verbose}")
  835. set(print_target "${verbose}")
  836. set(type_str "")
  837. get_filename_component(exepath "${target}" PATH)
  838. set(prereqs "")
  839. get_prerequisites("${target}" prereqs ${exclude_system} ${all} "${exepath}" "")
  840. if(print_target)
  841. message(STATUS "File '${target}' depends on:")
  842. endif()
  843. foreach(d ${prereqs})
  844. math(EXPR count "${count} + 1")
  845. if(print_count)
  846. set(count_str "${count}. ")
  847. endif()
  848. if(print_prerequisite_type)
  849. gp_file_type("${target}" "${d}" type)
  850. set(type_str " (${type})")
  851. endif()
  852. message(STATUS "${count_str}${d}${type_str}")
  853. endforeach()
  854. endfunction()
  855. function(list_prerequisites_by_glob glob_arg glob_exp)
  856. message(STATUS "=============================================================================")
  857. message(STATUS "List prerequisites of executables matching ${glob_arg} '${glob_exp}'")
  858. message(STATUS "")
  859. file(${glob_arg} file_list ${glob_exp})
  860. foreach(f ${file_list})
  861. is_file_executable("${f}" is_f_executable)
  862. if(is_f_executable)
  863. message(STATUS "=============================================================================")
  864. list_prerequisites("${f}" ${ARGN})
  865. message(STATUS "")
  866. endif()
  867. endforeach()
  868. endfunction()