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