pkg-config.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #!/usr/bin/env python
  2. # Copyright (c) 2013 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. from __future__ import print_function
  6. import json
  7. import os
  8. import subprocess
  9. import sys
  10. import re
  11. from optparse import OptionParser
  12. # This script runs pkg-config, optionally filtering out some results, and
  13. # returns the result.
  14. #
  15. # The result will be [ <includes>, <cflags>, <libs>, <lib_dirs>, <ldflags> ]
  16. # where each member is itself a list of strings.
  17. #
  18. # You can filter out matches using "-v <regexp>" where all results from
  19. # pkgconfig matching the given regular expression will be ignored. You can
  20. # specify more than one regular expression my specifying "-v" more than once.
  21. #
  22. # You can specify a sysroot using "-s <sysroot>" where sysroot is the absolute
  23. # system path to the sysroot used for compiling. This script will attempt to
  24. # generate correct paths for the sysroot.
  25. #
  26. # When using a sysroot, you must also specify the architecture via
  27. # "-a <arch>" where arch is either "x86" or "x64".
  28. #
  29. # CrOS systemroots place pkgconfig files at <systemroot>/usr/share/pkgconfig
  30. # and one of <systemroot>/usr/lib/pkgconfig or <systemroot>/usr/lib64/pkgconfig
  31. # depending on whether the systemroot is for a 32 or 64 bit architecture. They
  32. # specify the 'lib' or 'lib64' of the pkgconfig path by defining the
  33. # 'system_libdir' variable in the args.gn file. pkg_config.gni communicates this
  34. # variable to this script with the "--system_libdir <system_libdir>" flag. If no
  35. # flag is provided, then pkgconfig files are assumed to come from
  36. # <systemroot>/usr/lib/pkgconfig.
  37. #
  38. # Additionally, you can specify the option --atleast-version. This will skip
  39. # the normal outputting of a dictionary and instead print true or false,
  40. # depending on the return value of pkg-config for the given package.
  41. def SetConfigPath(options):
  42. """Set the PKG_CONFIG_LIBDIR environment variable.
  43. This takes into account any sysroot and architecture specification from the
  44. options on the given command line.
  45. """
  46. sysroot = options.sysroot
  47. assert sysroot
  48. # Compute the library path name based on the architecture.
  49. arch = options.arch
  50. if sysroot and not arch:
  51. print("You must specify an architecture via -a if using a sysroot.")
  52. sys.exit(1)
  53. libdir = sysroot + '/usr/' + options.system_libdir + '/pkgconfig'
  54. libdir += ':' + sysroot + '/usr/share/pkgconfig'
  55. libdir += ':' + sysroot + '/usr/' + options.system_libdir + '/riscv64-linux-gnu/pkgconfig'
  56. os.environ['PKG_CONFIG_LIBDIR'] = libdir
  57. return libdir
  58. def GetPkgConfigPrefixToStrip(options, args):
  59. """Returns the prefix from pkg-config where packages are installed.
  60. This returned prefix is the one that should be stripped from the beginning of
  61. directory names to take into account sysroots.
  62. """
  63. # Some sysroots, like the Chromium OS ones, may generate paths that are not
  64. # relative to the sysroot. For example,
  65. # /path/to/chroot/build/x86-generic/usr/lib/pkgconfig/pkg.pc may have all
  66. # paths relative to /path/to/chroot (i.e. prefix=/build/x86-generic/usr)
  67. # instead of relative to /path/to/chroot/build/x86-generic (i.e prefix=/usr).
  68. # To support this correctly, it's necessary to extract the prefix to strip
  69. # from pkg-config's |prefix| variable.
  70. prefix = subprocess.check_output([options.pkg_config,
  71. "--variable=prefix"] + args, env=os.environ).decode('utf-8')
  72. if prefix[-4] == '/usr':
  73. return prefix[4:]
  74. return prefix
  75. def MatchesAnyRegexp(flag, list_of_regexps):
  76. """Returns true if the first argument matches any regular expression in the
  77. given list."""
  78. for regexp in list_of_regexps:
  79. if regexp.search(flag) != None:
  80. return True
  81. return False
  82. def RewritePath(path, strip_prefix, sysroot):
  83. """Rewrites a path by stripping the prefix and prepending the sysroot."""
  84. if os.path.isabs(path) and not path.startswith(sysroot):
  85. if path.startswith(strip_prefix):
  86. path = path[len(strip_prefix):]
  87. path = path.lstrip('/')
  88. return os.path.join(sysroot, path)
  89. else:
  90. return path
  91. def main():
  92. # If this is run on non-Linux platforms, just return nothing and indicate
  93. # success. This allows us to "kind of emulate" a Linux build from other
  94. # platforms.
  95. if "linux" not in sys.platform:
  96. print("[[],[],[],[],[]]")
  97. return 0
  98. parser = OptionParser()
  99. parser.add_option('-d', '--debug', action='store_true')
  100. parser.add_option('-p', action='store', dest='pkg_config', type='string',
  101. default='pkg-config')
  102. parser.add_option('-v', action='append', dest='strip_out', type='string')
  103. parser.add_option('-s', action='store', dest='sysroot', type='string')
  104. parser.add_option('-a', action='store', dest='arch', type='string')
  105. parser.add_option('--system_libdir', action='store', dest='system_libdir',
  106. type='string', default='lib')
  107. parser.add_option('--atleast-version', action='store',
  108. dest='atleast_version', type='string')
  109. parser.add_option('--libdir', action='store_true', dest='libdir')
  110. parser.add_option('--dridriverdir', action='store_true', dest='dridriverdir')
  111. parser.add_option('--version-as-components', action='store_true',
  112. dest='version_as_components')
  113. (options, args) = parser.parse_args()
  114. # Make a list of regular expressions to strip out.
  115. strip_out = []
  116. if options.strip_out != None:
  117. for regexp in options.strip_out:
  118. strip_out.append(re.compile(regexp))
  119. if options.sysroot:
  120. libdir = SetConfigPath(options)
  121. if options.debug:
  122. sys.stderr.write('PKG_CONFIG_LIBDIR=%s\n' % libdir)
  123. prefix = GetPkgConfigPrefixToStrip(options, args)
  124. else:
  125. prefix = ''
  126. if options.atleast_version:
  127. # When asking for the return value, just run pkg-config and print the return
  128. # value, no need to do other work.
  129. if not subprocess.call([options.pkg_config,
  130. "--atleast-version=" + options.atleast_version] +
  131. args):
  132. print("true")
  133. else:
  134. print("false")
  135. return 0
  136. if options.version_as_components:
  137. cmd = [options.pkg_config, "--modversion"] + args
  138. try:
  139. version_string = subprocess.check_output(cmd).decode('utf-8')
  140. except:
  141. sys.stderr.write('Error from pkg-config.\n')
  142. return 1
  143. print(json.dumps(list(map(int, version_string.strip().split(".")))))
  144. return 0
  145. if options.libdir:
  146. cmd = [options.pkg_config, "--variable=libdir"] + args
  147. if options.debug:
  148. sys.stderr.write('Running: %s\n' % cmd)
  149. try:
  150. libdir = subprocess.check_output(cmd).decode('utf-8')
  151. except:
  152. print("Error from pkg-config.")
  153. return 1
  154. sys.stdout.write(libdir.strip())
  155. return 0
  156. if options.dridriverdir:
  157. cmd = [options.pkg_config, "--variable=dridriverdir"] + args
  158. if options.debug:
  159. sys.stderr.write('Running: %s\n' % cmd)
  160. try:
  161. dridriverdir = subprocess.check_output(cmd).decode('utf-8')
  162. except:
  163. print("Error from pkg-config.")
  164. return 1
  165. sys.stdout.write(dridriverdir.strip())
  166. return
  167. cmd = [options.pkg_config, "--cflags", "--libs"] + args
  168. if options.debug:
  169. sys.stderr.write('Running: %s\n' % ' '.join(cmd))
  170. try:
  171. flag_string = subprocess.check_output(cmd).decode('utf-8')
  172. except:
  173. sys.stderr.write('Could not run pkg-config.\n')
  174. return 1
  175. # For now just split on spaces to get the args out. This will break if
  176. # pkgconfig returns quoted things with spaces in them, but that doesn't seem
  177. # to happen in practice.
  178. all_flags = flag_string.strip().split(' ')
  179. sysroot = options.sysroot
  180. if not sysroot:
  181. sysroot = ''
  182. includes = []
  183. cflags = []
  184. libs = []
  185. lib_dirs = []
  186. for flag in all_flags[:]:
  187. if len(flag) == 0 or MatchesAnyRegexp(flag, strip_out):
  188. continue;
  189. if flag[:2] == '-l':
  190. libs.append(RewritePath(flag[2:], prefix, sysroot))
  191. elif flag[:2] == '-L':
  192. lib_dirs.append(RewritePath(flag[2:], prefix, sysroot))
  193. elif flag[:2] == '-I':
  194. includes.append(RewritePath(flag[2:], prefix, sysroot))
  195. elif flag[:3] == '-Wl':
  196. # Don't allow libraries to control ld flags. These should be specified
  197. # only in build files.
  198. pass
  199. elif flag == '-pthread':
  200. # Many libs specify "-pthread" which we don't need since we always include
  201. # this anyway. Removing it here prevents a bunch of duplicate inclusions
  202. # on the command line.
  203. pass
  204. else:
  205. cflags.append(flag)
  206. # Output a GN array, the first one is the cflags, the second are the libs. The
  207. # JSON formatter prints GN compatible lists when everything is a list of
  208. # strings.
  209. print(json.dumps([includes, cflags, libs, lib_dirs]))
  210. return 0
  211. if __name__ == '__main__':
  212. sys.exit(main())