2 # Copyright 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.
6 """Downloads, builds (with instrumentation) and installs shared libraries."""
16 class ScopedChangeDirectory(object):
17 """Changes current working directory and restores it back automatically."""
19 def __init__(self
, path
):
24 self
.old_path
= os
.getcwd()
28 def __exit__(self
, exc_type
, exc_value
, traceback
):
29 os
.chdir(self
.old_path
)
32 def get_script_absolute_path():
33 return os
.path
.dirname(os
.path
.abspath(__file__
))
36 def get_package_build_dependencies(package
):
37 command
= 'apt-get -s build-dep %s | grep Inst | cut -d " " -f 2' % package
38 command_result
= subprocess
.Popen(command
, stdout
=subprocess
.PIPE
,
40 if command_result
.wait():
41 raise Exception('Failed to determine build dependencies for %s' % package
)
42 build_dependencies
= [l
.strip() for l
in command_result
.stdout
]
43 return build_dependencies
46 def check_package_build_dependencies(package
):
47 build_dependencies
= get_package_build_dependencies(package
)
48 if len(build_dependencies
):
49 print >> sys
.stderr
, 'Please, install build-dependencies for %s' % package
50 print >> sys
.stderr
, 'One-liner for APT:'
51 print >> sys
.stderr
, 'sudo apt-get -y --no-remove build-dep %s' % package
55 def shell_call(command
, verbose
=False, environment
=None):
56 """ Wrapper on subprocess.Popen
58 Calls command with specific environment and verbosity using
62 command: Command to run in shell.
63 verbose: If False, hides all stdout and stderr in case of successful build.
64 Otherwise, always prints stdout and stderr.
65 environment: Parameter 'env' for subprocess.Popen.
71 Exception: if return code after call is not zero.
73 child
= subprocess
.Popen(
74 command
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
,
75 env
=environment
, shell
=True)
76 stdout
, stderr
= child
.communicate()
77 if verbose
or child
.returncode
:
80 raise Exception('Failed to run: %s' % command
)
83 def run_shell_commands(commands
, verbose
=False, environment
=None):
84 for command
in commands
:
85 shell_call(command
, verbose
, environment
)
88 def destdir_configure_make_install(parsed_arguments
, environment
,
90 configure_command
= './configure %s' % parsed_arguments
.extra_configure_flags
91 configure_command
+= ' --libdir=/lib/'
92 # Installing to a temporary directory allows us to safely clean up the .la
94 destdir
= '%s/debian/instrumented_build' % os
.getcwd()
95 # Some makefiles use BUILDROOT instead of DESTDIR.
96 make_command
= 'make DESTDIR=%s BUILDROOT=%s' % (destdir
, destdir
)
99 '%s -j%s' % (make_command
, parsed_arguments
.jobs
),
100 # Parallel install is flaky for some packages.
101 '%s install -j1' % make_command
,
102 # Kill the .la files. They contain absolute paths, and will cause build
103 # errors in dependent libraries.
104 'rm %s/lib/*.la -f' % destdir
,
105 # Now move the contents of the temporary destdir to their final place.
106 'cp %s/* %s/ -rdf' % (destdir
, install_prefix
)],
107 parsed_arguments
.verbose
, environment
)
110 def nss_make_and_copy(parsed_arguments
, environment
, install_prefix
):
111 # NSS uses a build system that's different from configure/make/install. All
112 # flags must be passed as arguments to make.
114 # Do an optimized build.
115 make_args
.append('BUILD_OPT=1')
116 # Set USE_64=1 on x86_64 systems.
117 if platform
.architecture()[0] == '64bit':
118 make_args
.append('USE_64=1')
119 # Passing C(XX)FLAGS overrides the defaults, and EXTRA_C(XX)FLAGS is not
120 # supported. Append our extra flags to CC/CXX.
121 make_args
.append('CC="%s %s"' % (environment
['CC'], environment
['CFLAGS']))
122 make_args
.append('CXX="%s %s"' %
123 (environment
['CXX'], environment
['CXXFLAGS']))
124 # We need to override ZDEFS_FLAGS at least to prevent -Wl,-z,defs.
125 # Might as well use this to pass the linker flags, since ZDEF_FLAGS is always
126 # added during linking on Linux.
127 make_args
.append('ZDEFS_FLAG="-Wl,-z,nodefs %s"' % environment
['LDFLAGS'])
128 make_args
.append('NSPR_INCLUDE_DIR=/usr/include/nspr')
129 make_args
.append('NSPR_LIB_DIR=%s/lib' % install_prefix
)
130 make_args
.append('NSS_ENABLE_ECC=1')
131 with
ScopedChangeDirectory('nss') as cd_nss
:
132 # -j is not supported
133 shell_call('make %s' % ' '.join(make_args
), parsed_arguments
.verbose
,
135 # 'make install' is not supported. Copy the DSOs manually.
136 install_dir
= '%s/lib/' % install_prefix
137 for (dirpath
, dirnames
, filenames
) in os
.walk('./lib/'):
138 for filename
in filenames
:
139 if filename
.endswith('.so'):
140 full_path
= os
.path
.join(dirpath
, filename
)
141 if parsed_arguments
.verbose
:
142 print 'download_build_install.py: installing %s' % full_path
143 shutil
.copy(full_path
, install_dir
)
146 def libcap2_make_install(parsed_arguments
, environment
, install_prefix
):
147 # libcap2 doesn't come with a configure script
149 '%s="%s"' % (name
, environment
[name
])
150 for name
in['CC', 'CXX', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS']]
151 shell_call('make -j%s %s' % (parsed_arguments
.jobs
, ' '.join(make_args
)),
152 parsed_arguments
.verbose
, environment
)
154 'DESTDIR=%s' % install_prefix
,
155 # Do not install in lib64/.
157 # Skip a step that requires sudo.
160 shell_call('make -j%s install %s' %
161 (parsed_arguments
.jobs
, ' '.join(install_args
)),
162 parsed_arguments
.verbose
, environment
)
165 def libpci3_make_install(parsed_arguments
, environment
, install_prefix
):
166 # pciutils doesn't have a configure script
167 # This build script follows debian/rules.
169 # `make install' will create a "$(DESTDIR)-udeb" directory alongside destdir.
170 # We don't want that in our product dir, so we use an intermediate directory.
171 destdir
= '%s/debian/pciutils' % os
.getcwd()
173 '%s="%s"' % (name
, environment
[name
])
174 for name
in['CC', 'CXX', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS']]
175 make_args
.append('SHARED=yes')
180 'IDSDIR=/usr/share/misc',
182 install_args
= ['DESTDIR=%s' % destdir
]
184 'mkdir -p %s-udeb/usr/bin' % destdir
,
185 'make -j%s %s' % (parsed_arguments
.jobs
, ' '.join(make_args
+ paths
)),
186 'make -j%s %s install' % (
187 parsed_arguments
.jobs
,
188 ' '.join(install_args
+ paths
))],
189 parsed_arguments
.verbose
, environment
)
190 # Now move the contents of the temporary destdir to their final place.
192 'cp %s/* %s/ -rd' % (destdir
, install_prefix
),
193 'install -m 644 lib/libpci.so* %s/lib/' % install_prefix
,
194 'ln -sf libpci.so.3.1.8 %s/lib/libpci.so.3' % install_prefix
],
195 parsed_arguments
.verbose
, environment
)
198 def build_and_install(parsed_arguments
, environment
, install_prefix
):
199 if parsed_arguments
.build_method
== 'destdir':
200 destdir_configure_make_install(
201 parsed_arguments
, environment
, install_prefix
)
202 elif parsed_arguments
.build_method
== 'custom_nss':
203 nss_make_and_copy(parsed_arguments
, environment
, install_prefix
)
204 elif parsed_arguments
.build_method
== 'custom_libcap':
205 libcap2_make_install(parsed_arguments
, environment
, install_prefix
)
206 elif parsed_arguments
.build_method
== 'custom_libpci3':
207 libpci3_make_install(parsed_arguments
, environment
, install_prefix
)
208 elif parsed_arguments
.build_method
== 'custom_libappindicator1':
209 environment
['CSC'] = '/usr/bin/mono-csc'
210 destdir_configure_make_install(
211 parsed_arguments
, environment
, install_prefix
)
213 raise Exception('Unrecognized build method: %s' %
214 parsed_arguments
.build_method
)
216 def unescape_flags(s
):
217 # GYP escapes the build flags as if they are going to be inserted directly
218 # into the command line. Since we pass them via CFLAGS/LDFLAGS, we must drop
219 # the double quotes accordingly.
220 return ' '.join(shlex
.split(s
))
222 def download_build_install(parsed_arguments
):
223 environment
= os
.environ
.copy()
224 # The CC/CXX environment variables take precedence over the command line
226 if 'CC' not in environment
and parsed_arguments
.cc
:
227 environment
['CC'] = parsed_arguments
.cc
228 if 'CXX' not in environment
and parsed_arguments
.cxx
:
229 environment
['CXX'] = parsed_arguments
.cxx
231 product_directory
= os
.path
.normpath('%s/%s' % (
232 get_script_absolute_path(),
233 parsed_arguments
.product_directory
))
235 cflags
= unescape_flags(parsed_arguments
.cflags
)
236 if parsed_arguments
.sanitizer_blacklist
:
237 cflags
+= ' -fsanitize-blacklist=%s/%s' % (
239 parsed_arguments
.sanitizer_blacklist
)
240 environment
['CFLAGS'] = cflags
241 environment
['CXXFLAGS'] = cflags
243 install_prefix
= '%s/instrumented_libraries/%s' % (
245 parsed_arguments
.sanitizer_type
)
247 ldflags
= unescape_flags(parsed_arguments
.ldflags
)
248 # Make sure the linker searches the instrumented libraries dir for
249 # library dependencies.
250 environment
['LDFLAGS'] = '%s -L%s/lib' % (ldflags
, install_prefix
)
252 package_directory
= '%s/%s' % (parsed_arguments
.intermediate_directory
,
253 parsed_arguments
.package
)
255 # Clobber by default, unless the developer wants to hack on the package's
257 clobber
= (environment
.get('INSTRUMENTED_LIBRARIES_NO_CLOBBER', '') != '1')
259 download_source
= True
260 if os
.path
.exists(package_directory
):
262 shell_call('rm -rf %s' % package_directory
, parsed_arguments
.verbose
)
264 download_source
= False
266 os
.makedirs(package_directory
)
268 with
ScopedChangeDirectory(package_directory
) as cd_package
:
270 shell_call('apt-get source %s' % parsed_arguments
.package
,
271 parsed_arguments
.verbose
)
272 # There should be exactly one subdirectory after downloading a package.
273 subdirectories
= [d
for d
in os
.listdir('.') if os
.path
.isdir(d
)]
274 if len(subdirectories
) != 1:
275 raise Exception('apt-get source %s must create exactly one subdirectory.'
276 % parsed_arguments
.package
)
277 with
ScopedChangeDirectory(subdirectories
[0]):
278 # Here we are in the package directory.
280 # Patch/run_before_build steps are only done once.
281 if parsed_arguments
.patch
:
283 'patch -p1 -i %s/%s' %
284 (os
.path
.relpath(cd_package
.old_path
),
285 parsed_arguments
.patch
),
286 parsed_arguments
.verbose
)
287 if parsed_arguments
.run_before_build
:
290 (os
.path
.relpath(cd_package
.old_path
),
291 parsed_arguments
.run_before_build
),
292 parsed_arguments
.verbose
)
294 build_and_install(parsed_arguments
, environment
, install_prefix
)
295 except Exception as exception
:
297 print 'Failed to build package %s.' % parsed_arguments
.package
298 print ('Probably, some of its dependencies are not installed: %s' %
299 ' '.join(get_package_build_dependencies(parsed_arguments
.package
)))
302 # Touch a txt file to indicate package is installed.
303 open('%s/%s.txt' % (install_prefix
, parsed_arguments
.package
), 'w').close()
305 # Remove downloaded package and generated temporary build files.
306 # Failed builds intentionally skip this step, in order to aid in tracking down
309 shell_call('rm -rf %s' % package_directory
, parsed_arguments
.verbose
)
312 argument_parser
= argparse
.ArgumentParser(
313 description
='Download, build and install instrumented package')
315 argument_parser
.add_argument('-j', '--jobs', type=int, default
=1)
316 argument_parser
.add_argument('-p', '--package', required
=True)
317 argument_parser
.add_argument(
318 '-i', '--product-directory', default
='.',
319 help='Relative path to the directory with chrome binaries')
320 argument_parser
.add_argument(
321 '-m', '--intermediate-directory', default
='.',
322 help='Relative path to the directory for temporary build files')
323 argument_parser
.add_argument('--extra-configure-flags', default
='')
324 argument_parser
.add_argument('--cflags', default
='')
325 argument_parser
.add_argument('--ldflags', default
='')
326 argument_parser
.add_argument('-s', '--sanitizer-type', required
=True,
327 choices
=['asan', 'msan', 'tsan'])
328 argument_parser
.add_argument('-v', '--verbose', action
='store_true')
329 argument_parser
.add_argument('--check-build-deps', action
='store_true')
330 argument_parser
.add_argument('--cc')
331 argument_parser
.add_argument('--cxx')
332 argument_parser
.add_argument('--patch', default
='')
333 # This should be a shell script to run before building specific libraries.
334 # This will be run after applying the patch above.
335 argument_parser
.add_argument('--run-before-build', default
='')
336 argument_parser
.add_argument('--build-method', default
='destdir')
337 argument_parser
.add_argument('--sanitizer-blacklist', default
='')
339 # Ignore all empty arguments because in several cases gyp passes them to the
340 # script, but ArgumentParser treats them as positional arguments instead of
341 # ignoring (and doesn't have such options).
342 parsed_arguments
= argument_parser
.parse_args(
343 [arg
for arg
in sys
.argv
[1:] if len(arg
) != 0])
344 # Ensure current working directory is this script directory.
345 os
.chdir(get_script_absolute_path())
346 # Ensure all build dependencies are installed.
347 if parsed_arguments
.check_build_deps
:
348 check_package_build_dependencies(parsed_arguments
.package
)
350 download_build_install(parsed_arguments
)
353 if __name__
== '__main__':