Esempio n. 1
0
def check_sanity():
    """
    Test if development headers and library for rgw is available by compiling a dummy C program.
    """
    CEPH_SRC_DIR = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        '..',
        '..'
    )

    tmp_dir = tempfile.mkdtemp(dir=os.environ.get('TMPDIR', os.path.dirname(__file__)))
    tmp_file = os.path.join(tmp_dir, 'rgw_dummy.c')

    with open(tmp_file, 'w') as fp:
        dummy_prog = textwrap.dedent("""
        #include <stddef.h>
        #include "rados/rgw_file.h"

        int main(void) {
            rgwfile_version(NULL, NULL, NULL);
            return 0;
        }
        """)
        fp.write(dummy_prog)

    compiler = new_compiler()
    customize_compiler(compiler)

    if {'MAKEFLAGS', 'MFLAGS', 'MAKELEVEL'}.issubset(set(os.environ.keys())):
        # The setup.py has been invoked by a top-level Ceph make.
        # Set the appropriate CFLAGS and LDFLAGS

        compiler.set_include_dirs([os.path.join(CEPH_SRC_DIR, 'include')])
        compiler.set_library_dirs([os.environ.get('CEPH_LIBDIR')])

    try:
        compiler.define_macro('_FILE_OFFSET_BITS', '64')

        link_objects = compiler.compile(
            sources=[tmp_file],
            output_dir=tmp_dir,
        )

        compiler.link_executable(
            objects=link_objects,
            output_progname=os.path.join(tmp_dir, 'rgw_dummy'),
            libraries=['rgw', 'rados'],
            output_dir=tmp_dir,
        )

    except CompileError:
        print('\nCompile Error: RGW development headers not found', file=sys.stderr)
        return False
    except LinkError:
        print('\nLink Error: RGW library not found', file=sys.stderr)
        return False
    else:
        return True
    finally:
        shutil.rmtree(tmp_dir)
Esempio n. 2
0
File: setup.py Progetto: mbr/githome
    def run(self):
        cc = new_compiler()
        customize_compiler(cc)
        o_files = cc.compile(['githome/gh_client.c'])
        cc.link_executable(o_files, 'githome/gh_client')

        install.run(self)  # run normal build command
Esempio n. 3
0
def CCompiler_customize(self, dist, debug = False, need_cxx=0):
    # See FCompiler.customize for suggested usage.
    log.info('customize %s' % (self.__class__.__name__))
    customize_compiler(self)
    if need_cxx:
        # In general, distutils uses -Wstrict-prototypes, but this option is
        # not valid for C++ code, only for C.  Remove it if it's there to
        # avoid a spurious warning on every compilation.  All the default
        # options used by distutils can be extracted with:

        # from distutils import sysconfig
        # sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
        # 'CCSHARED', 'LDSHARED', 'SO')
        saferemove(self.compiler_so,'-Wstrict-prototypes')
        
        if debug:
            saferemove(self.compiler_so,'-DNDEBUG')
            safereplace(self.compiler_so,['-O','-O1','-O2','-O3'],'-O0')
        else:
            saferemove(self.compiler_so,'-g')
            safereplace(self.compiler_so,['-O','-O0','-O1','-O2'],'-O3')

        if hasattr(self,'compiler') and 'cc' in self.compiler[0]:
            if not self.compiler_cxx:
                if self.compiler[0].startswith('gcc'):
                    a, b = 'gcc', 'g++'
                else:
                    a, b = 'cc', 'c++'
                self.compiler_cxx = [self.compiler[0].replace(a,b)]\
                                    + self.compiler[1:]
        else:
            if hasattr(self,'compiler'):
                log.warn("#### %s #######" % (self.compiler,))
            log.warn('Missing compiler_cxx fix for '+self.__class__.__name__)
    return
Esempio n. 4
0
File: setup.py Progetto: zjc5415/pyq
    def run(self):
        for exe in self.distribution.executables:
            exe.include_dirs.append(get_python_inc())
            compiler = new_compiler(  # compiler=self.compiler,
                verbose=self.verbose,
                dry_run=self.dry_run,
                force=self.force)
            customize_compiler(compiler)
            compiler.set_include_dirs(exe.include_dirs)
            for (name, value) in exe.define_macros:
                compiler.define_macro(name, value)

            objects = compiler.compile(exe.sources, output_dir=self.build_temp)

            # This is a hack copied from distutils.commands.build_exe (where it is also called
            # a hack).
            self._build_objects = objects[:]

            library_dirs = [os.path.join(sys.exec_prefix, 'lib')]

            exe_path = join(self.build_lib, exe.name.split('.')[-1])

            compiler.link(CCompiler.EXECUTABLE,
                          objects=objects,
                          output_filename=exe_path,
                          library_dirs=library_dirs,
                          libraries=exe.libraries
                          )
def CCompiler_customize(self, dist, need_cxx=0):
    # See FCompiler.customize for suggested usage.
    log.info('customize %s' % (self.__class__.__name__))
    customize_compiler(self)
    if need_cxx:
        # In general, distutils uses -Wstrict-prototypes, but this option is
        # not valid for C++ code, only for C.  Remove it if it's there to
        # avoid a spurious warning on every compilation.  All the default
        # options used by distutils can be extracted with:

        # from distutils import sysconfig
        # sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
        # 'CCSHARED', 'LDSHARED', 'SO')
        print "compiler options1:", self.compiler_so
        try:
            self.compiler_so.remove('-Wstrict-prototypes')
        except (AttributeError, ValueError):
            pass
        print "compiler options2:", self.compiler_so
        if hasattr(self,'compiler') and self.compiler[0].find('cc')>=0:
            if not self.compiler_cxx:
                if self.compiler[0].startswith('gcc'):
                    a, b = 'gcc', 'g++'
                else:
                    a, b = 'cc', 'c++'
                self.compiler_cxx = [self.compiler[0].replace(a,b)]\
                                    + self.compiler[1:]
        else:
            if hasattr(self,'compiler'):
                 log.warn("#### %s #######" % (self.compiler,))
            log.warn('Missing compiler_cxx fix for '+self.__class__.__name__)
    return
Esempio n. 6
0
 def __init__(self):
     self.debug = False
     self._compiler = new_compiler()
     customize_compiler(self._compiler)
     self._build_ext = build_ext(Distribution())
     self._build_ext.finalize_options()
     self._py_lib_dirs = self._build_ext.library_dirs
Esempio n. 7
0
    def _setup_extensions(self):
        ext = {e.name: e for e in self.extensions}

        compiler = new_compiler(compiler=self.compiler)
        customize_compiler(compiler)

        def add_dependency(ext, name):
            add_ext_pkg_config_dep(ext, compiler.compiler_type, name)

        def add_pycairo(ext):
            ext.include_dirs += [get_pycairo_include_dir()]

        gi_ext = ext["gi._gi"]
        add_dependency(gi_ext, "glib-2.0")
        add_dependency(gi_ext, "gio-2.0")
        add_dependency(gi_ext, "gobject-introspection-1.0")
        add_dependency(gi_ext, "libffi")
        add_ext_compiler_flags(gi_ext, compiler)

        if WITH_CAIRO:
            gi_cairo_ext = ext["gi._gi_cairo"]
            add_dependency(gi_cairo_ext, "glib-2.0")
            add_dependency(gi_cairo_ext, "gio-2.0")
            add_dependency(gi_cairo_ext, "gobject-introspection-1.0")
            add_dependency(gi_cairo_ext, "libffi")
            add_dependency(gi_cairo_ext, "cairo")
            add_dependency(gi_cairo_ext, "cairo-gobject")
            add_pycairo(gi_cairo_ext)
            add_ext_compiler_flags(gi_cairo_ext, compiler)
Esempio n. 8
0
def _have_sqlite_extension_support():
    import shutil
    import tempfile
    from distutils.ccompiler import new_compiler
    from distutils.sysconfig import customize_compiler

    libraries = ['sqlite3']
    c_code = ('#include <sqlite3.h>\n\n'
              'int main(int argc, char **argv) { return 0; }')
    tmp_dir = tempfile.mkdtemp(prefix='tmp_pw_sqlite3_')
    bin_file = os.path.join(tmp_dir, 'test_pw_sqlite3')
    src_file = bin_file + '.c'
    with open(src_file, 'w') as fh:
        fh.write(c_code)

    compiler = new_compiler()
    customize_compiler(compiler)
    success = False
    try:
        compiler.link_executable(
            compiler.compile([src_file], output_dir=tmp_dir),
            bin_file,
            libraries=['sqlite3'])
    except CCompilerError:
        print('unable to compile sqlite3 C extensions - missing headers?')
    except DistutilsExecError:
        print('unable to compile sqlite3 C extensions - no c compiler?')
    except DistutilsPlatformError:
        print('unable to compile sqlite3 C extensions - platform error')
    else:
        success = True
    shutil.rmtree(tmp_dir)
    return success
Esempio n. 9
0
def get_cxxflags():
    from distutils.ccompiler import new_compiler
    from distutils.sysconfig import customize_compiler
    from distutils import sysconfig
    from platform import system
    if system() == DARWIN_KEY:
        CXX_FLAGS["gcc"] = CXX_FLAGS["gcc-mac"]
        CXX_FLAGS["cc"] = CXX_FLAGS["clang"]
        CXX_FLAGS["c++"] = CXX_FLAGS["clang"]
    elif system() == LINUX_KEY:
        CXX_FLAGS["gcc"] = CXX_FLAGS["gcc-linux"]
        CXX_FLAGS["cc"] = CXX_FLAGS["gcc"]
        CXX_FLAGS["c++"] = CXX_FLAGS["gcc"]
    else:
        raise UnsupportedCompilerException("System: %s is not supported by HOPE" % system())
    
    sysconfig.get_config_vars() #init vars
    compiler = new_compiler()
    customize_compiler(compiler)
    compiler_name = compiler.compiler[0].split("/")[-1]
    
    _check_version(compiler_name, compiler.compiler[0])
    
    for name, flags in CXX_FLAGS.items():
        if compiler_name.startswith(name):
            return flags
    raise UnsupportedCompilerException("Unknown compiler: {0}".format(compiler_name))
Esempio n. 10
0
def get_preprocessor():
    # findout which compiler to use
    from distutils.sysconfig import customize_compiler

    compiler_name = distutils.ccompiler.get_default_compiler()
    compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
    try:
        customize_compiler(compiler)
    except AttributeError as e:
        print("Warning: failed customizing compiler ({:s})".format(repr(e)))

    if hasattr(compiler, "initialize"):
        try:
            compiler.initialize()
        except ValueError as e:
            print("Warning: failed initializing compiler ({:s})".format(repr(e)))

    cpp_cmd = None
    if hasattr(compiler, "preprocessor"):  # for unixccompiler
        cpp_cmd = compiler.preprocessor
    elif hasattr(compiler, "compiler"):  # for ccompiler
        cpp_cmd = compiler.compiler.split()
        cpp_cmd += ["-E"]
    elif hasattr(compiler, "cc"):  # for msvccompiler
        cpp_cmd = compiler.cc.split()
        cpp_cmd += ["-E"]

    if not cpp_cmd:
        print("Warning: could not guess preprocessor, using env's CC")
        cpp_cmd = os.environ.get("CC", "cc").split()
        cpp_cmd += ["-E"]

    return cpp_cmd
Esempio n. 11
0
    def test_run(self):
        pkg_dir, dist = self.create_dist()
        cmd = build_clib(dist)

        foo_c = os.path.join(pkg_dir, 'foo.c')
        self.write_file(foo_c, 'int main(void) { return 1;}\n')
        cmd.libraries = [('foo', {'sources': [foo_c]})]

        build_temp = os.path.join(pkg_dir, 'build')
        os.mkdir(build_temp)
        cmd.build_temp = build_temp
        cmd.build_clib = build_temp

        # before we run the command, we want to make sure
        # all commands are present on the system
        # by creating a compiler and checking its executables
        from distutils.ccompiler import new_compiler
        from distutils.sysconfig import customize_compiler

        compiler = new_compiler()
        customize_compiler(compiler)
        for ccmd in compiler.executables.values():
            if ccmd is None:
                continue
            if find_executable(ccmd[0]) is None:
                self.skipTest('The %r command is not found' % ccmd[0])

        # this should work
        cmd.run()

        # let's check the result
        self.assertIn('libfoo.a', os.listdir(build_temp))
Esempio n. 12
0
def customize_compiler(compiler, lang=None, mpicc=None, mpicxx=None, mpild=None):
    """ Implements the compiler configuration. """

    # Unix specific compilation customization
    assert compiler.compiler_type == 'unix'

    sysconfig.customize_compiler(compiler)

    ld = compiler.linker_exe
    for envvar in ('LDFLAGS', 'CFLAGS', 'CPPFLAGS'):
        if envvar in os.environ:
            ld += split_quoted(os.environ[envvar])

    # Compiler command overriding
    if mpicc:
        fix_compiler_cmd(compiler.compiler, mpicc)
        if lang in ('c', None):
            fix_compiler_cmd(compiler.compiler_so, mpicc)

    if mpicxx:
        fix_compiler_cmd(compiler.compiler_cxx, mpicxx)
        if lang == 'c++':
            fix_compiler_cmd(compiler.compiler_so, mpicxx)

    if mpild:
        for ld in [compiler.linker_so, compiler.linker_exe]:
            fix_linker_cmd(ld, mpild)

    badcxxflags = ['-Wimplicit', '-Wstrict-prototypes']
    for flag in badcxxflags:
        while flag in compiler.compiler_cxx:
            compiler.compiler_cxx.remove(flag)
        if lang == 'c++':
            while flag in compiler.compiler_so:
                compiler.compiler_so.remove(flag)
Esempio n. 13
0
    def setup_shlib_compiler(self):
        compiler = self.shlib_compiler = new_compiler(compiler=self.compiler, dry_run=self.dry_run, force=self.force)
        if sys.platform == 'darwin':
            tmp = _config_vars.copy()
            try:
                _config_vars['LDSHARED'] = 'gcc -Wl,-x -dynamiclib -undefined dynamic_lookup'
                _config_vars['CCSHARED'] = ' -dynamiclib'
                _config_vars['SO'] = '.dylib'
                customize_compiler(compiler)
            finally:
                _config_vars.clear()
                _config_vars.update(tmp)

        else:
            customize_compiler(compiler)
        if self.include_dirs is not None:
            compiler.set_include_dirs(self.include_dirs)
        if self.define is not None:
            for name, value in self.define:
                compiler.define_macro(name, value)

        if self.undef is not None:
            for macro in self.undef:
                compiler.undefine_macro(macro)

        if self.libraries is not None:
            compiler.set_libraries(self.libraries)
        if self.library_dirs is not None:
            compiler.set_library_dirs(self.library_dirs)
        if self.rpath is not None:
            compiler.set_runtime_library_dirs(self.rpath)
        if self.link_objects is not None:
            compiler.set_link_objects(self.link_objects)
        compiler.link_shared_object = link_shared_object.__get__(compiler)
        return
Esempio n. 14
0
def test_compilation(cfile, compiler=None, **compiler_attrs):
    """Test simple compilation with given settings"""
    if compiler is None or isinstance(compiler, str):
        cc = ccompiler.new_compiler(compiler=compiler)
        customize_compiler(cc)
        if cc.compiler_type == 'mingw32':
            customize_mingw(cc)
    else:
        cc = compiler

    for name, val in compiler_attrs.items():
        setattr(cc, name, val)

    efile, ext = os.path.splitext(cfile)

    cpreargs = lpreargs = None
    if sys.platform == 'darwin':
        # use appropriate arch for compiler
        if platform.architecture()[0]=='32bit':
            if platform.processor() == 'powerpc':
                cpu = 'ppc'
            else:
                cpu = 'i386'
            cpreargs = ['-arch', cpu]
            lpreargs = ['-arch', cpu, '-undefined', 'dynamic_lookup']
        else:
            # allow for missing UB arch, since it will still work:
            lpreargs = ['-undefined', 'dynamic_lookup']
    extra = compiler_attrs.get('extra_compile_args', None)

    objs = cc.compile([cfile],extra_preargs=cpreargs, extra_postargs=extra)
    cc.link_executable(objs, efile, extra_preargs=lpreargs)
    return efile
Esempio n. 15
0
def CCompiler_customize(self, dist, need_cxx=0):
    """
    Do any platform-specific customization of a compiler instance.

    This method calls `distutils.sysconfig.customize_compiler` for
    platform-specific customization, as well as optionally remove a flag
    to suppress spurious warnings in case C++ code is being compiled.

    Parameters
    ----------
    dist : object
        This parameter is not used for anything.
    need_cxx : bool, optional
        Whether or not C++ has to be compiled. If so (True), the
        ``"-Wstrict-prototypes"`` option is removed to prevent spurious
        warnings. Default is False.

    Returns
    -------
    None

    Notes
    -----
    All the default options used by distutils can be extracted with::

      from distutils import sysconfig
      sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
                                'CCSHARED', 'LDSHARED', 'SO')

    """
    # See FCompiler.customize for suggested usage.
    log.info('customize %s' % (self.__class__.__name__))
    customize_compiler(self)
    if need_cxx:
        # In general, distutils uses -Wstrict-prototypes, but this option is
        # not valid for C++ code, only for C.  Remove it if it's there to
        # avoid a spurious warning on every compilation.  All the default
        # options used by distutils can be extracted with:

        # from distutils import sysconfig
        # sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
        # 'CCSHARED', 'LDSHARED', 'SO')
        try:
            self.compiler_so.remove('-Wstrict-prototypes')
        except (AttributeError, ValueError):
            pass

        if hasattr(self,'compiler') and 'cc' in self.compiler[0]:
            if not self.compiler_cxx:
                if self.compiler[0].startswith('gcc'):
                    a, b = 'gcc', 'g++'
                else:
                    a, b = 'cc', 'c++'
                self.compiler_cxx = [self.compiler[0].replace(a,b)]\
                                    + self.compiler[1:]
        else:
            if hasattr(self,'compiler'):
                log.warn("#### %s #######" % (self.compiler,))
            log.warn('Missing compiler_cxx fix for '+self.__class__.__name__)
    return
Esempio n. 16
0
 def __init__(self, debug=False):
     self._compiler = new_compiler()
     log.set_threshold(log.DEBUG if debug else log.INFO)
     customize_compiler(self._compiler)
     self._build_ext = build_ext(Distribution())
     self._build_ext.finalize_options()
     self._py_lib_dirs = self._build_ext.library_dirs
Esempio n. 17
0
    def run(self):
        from distutils.ccompiler import new_compiler
        if not self.extensions:
            return
        # Setup the CCompiler object that we'll use to do all the
        # compiling and linking
        self.compiler = new_compiler(compiler=self.compiler,
                                     verbose=self.verbose,
                                     dry_run=self.dry_run,
                                     force=self.force)
        customize_compiler(self.compiler)
         # And make sure that any compile/link-related options (which might
        # come from the command-line or from the setup script) are set in
        # that CCompiler object -- that way, they automatically apply to
        # all compiling and linking done here.
        if self.include_dirs is not None:
            self.compiler.set_include_dirs(self.include_dirs)
        if self.define is not None:
            # 'define' option is a list of (name,value) tuples
            for (name, value) in self.define:
                self.compiler.define_macro(name, value)
        if self.undef is not None:
            for macro in self.undef:
                self.compiler.undefine_macro(macro)
        if self.libraries is not None:
            self.compiler.set_libraries(self.libraries)
        if self.library_dirs is not None:
            self.compiler.set_library_dirs(self.library_dirs)
        if self.rpath is not None:
            self.compiler.set_runtime_library_dirs(self.rpath)
        if self.link_objects is not None:
            self.compiler.set_link_objects(self.link_objects)

        # Now actually compile and link everything.
        self.build_extensions()
Esempio n. 18
0
    def customize_compiler(self):
        # make sure AR gets caught
        class compiler:
            compiler_type = 'unix'

            def set_executables(self, **kw):
                self.exes = kw

        sysconfig_vars = {
            'AR': 'sc_ar',
            'CC': 'sc_cc',
            'CXX': 'sc_cxx',
            'ARFLAGS': '--sc-arflags',
            'CFLAGS': '--sc-cflags',
            'CCSHARED': '--sc-ccshared',
            'LDSHARED': 'sc_ldshared',
            'SHLIB_SUFFIX': 'sc_shutil_suffix',
        }

        comp = compiler()
        with contextlib.ExitStack() as cm:
            for key, value in sysconfig_vars.items():
                cm.enter_context(swap_item(sysconfig._config_vars, key, value))
            sysconfig.customize_compiler(comp)

        return comp
Esempio n. 19
0
    def run(self):
        from distutils.ccompiler import new_compiler
        if not self.extensions:
            return
        else:
            if self.distribution.has_c_libraries():
                build_clib = self.get_finalized_command('build_clib')
                self.libraries.extend(build_clib.get_library_names() or [])
                self.library_dirs.append(build_clib.build_clib)
            self.compiler = new_compiler(compiler=self.compiler, verbose=self.verbose, dry_run=self.dry_run, force=self.force)
            customize_compiler(self.compiler)
            if os.name == 'nt' and self.plat_name != get_platform():
                self.compiler.initialize(self.plat_name)
            if self.include_dirs is not None:
                self.compiler.set_include_dirs(self.include_dirs)
            if self.define is not None:
                for name, value in self.define:
                    self.compiler.define_macro(name, value)

            if self.undef is not None:
                for macro in self.undef:
                    self.compiler.undefine_macro(macro)

            if self.libraries is not None:
                self.compiler.set_libraries(self.libraries)
            if self.library_dirs is not None:
                self.compiler.set_library_dirs(self.library_dirs)
            if self.rpath is not None:
                self.compiler.set_runtime_library_dirs(self.rpath)
            if self.link_objects is not None:
                self.compiler.set_link_objects(self.link_objects)
            self.build_extensions()
            return
Esempio n. 20
0
 def build_extensions(self):
     customize_compiler(self.compiler)
     try:
         self.compiler.compiler_so.remove("-Wstrict-prototypes")
     except (AttributeError, ValueError):
         pass
     build_ext.build_extensions(self)
Esempio n. 21
0
    def run (self):

        from distutils.ccompiler import new_compiler

        # 'self.extensions', as supplied by setup.py, is a list of
        # Extension instances.  See the documentation for Extension (in
        # distutils.extension) for details.
        #
        # For backwards compatibility with Distutils 0.8.2 and earlier, we
        # also allow the 'extensions' list to be a list of tuples:
        #    (ext_name, build_info)
        # where build_info is a dictionary containing everything that
        # Extension instances do except the name, with a few things being
        # differently named.  We convert these 2-tuples to Extension
        # instances as needed.

        if not self.extensions:
            return

        # If we were asked to build any C/C++ libraries, make sure that the
        # directory where we put them is in the library search path for
        # linking extensions.
        if self.distribution.has_c_libraries():
            build_clib = self.get_finalized_command('build_clib')
            self.libraries.extend(build_clib.get_library_names() or [])
            self.library_dirs.append(build_clib.build_clib)

        # Setup the CCompiler object that we'll use to do all the
        # compiling and linking
        self.compiler = new_compiler(compiler=self.compiler,
                                     verbose=self.verbose,
                                     dry_run=self.dry_run,
                                     force=self.force)
        customize_compiler(self.compiler)

        # And make sure that any compile/link-related options (which might
        # come from the command-line or from the setup script) are set in
        # that CCompiler object -- that way, they automatically apply to
        # all compiling and linking done here.
        if self.include_dirs is not None:
            self.compiler.set_include_dirs(self.include_dirs)
        if self.define is not None:
            # 'define' option is a list of (name,value) tuples
            for (name,value) in self.define:
                self.compiler.define_macro(name, value)
        if self.undef is not None:
            for macro in self.undef:
                self.compiler.undefine_macro(macro)
        if self.libraries is not None:
            self.compiler.set_libraries(self.libraries)
        if self.library_dirs is not None:
            self.compiler.set_library_dirs(self.library_dirs)
        if self.rpath is not None:
            self.compiler.set_runtime_library_dirs(self.rpath)
        if self.link_objects is not None:
            self.compiler.set_link_objects(self.link_objects)

        # Now actually compile and link everything.
        self.build_extensions()
Esempio n. 22
0
def check_sanity():
    """
    Test if development headers and library for cephfs is available by compiling a dummy C program.
    """
    CEPH_SRC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")

    tmp_dir = tempfile.mkdtemp(dir=os.environ.get("TMPDIR", os.path.dirname(__file__)))
    tmp_file = os.path.join(tmp_dir, "cephfs_dummy.c")

    with open(tmp_file, "w") as fp:
        dummy_prog = textwrap.dedent(
            """
        #include <stddef.h>
        #include "cephfs/libcephfs.h"

        int main(void) {
            struct ceph_mount_info *cmount = NULL;
            ceph_init(cmount);
            return 0;
        }
        """
        )
        fp.write(dummy_prog)

    compiler = new_compiler()
    customize_compiler(compiler)

    if {"MAKEFLAGS", "MFLAGS", "MAKELEVEL"}.issubset(set(os.environ.keys())):
        # The setup.py has been invoked by a top-level Ceph make.
        # Set the appropriate CFLAGS and LDFLAGS

        compiler.set_library_dirs([os.environ.get("CEPH_LIBDIR")])

    try:
        compiler.define_macro("_FILE_OFFSET_BITS", "64")

        link_objects = compiler.compile(
            sources=[tmp_file],
            output_dir=tmp_dir,
            extra_preargs=["-iquote{path}".format(path=os.path.join(CEPH_SRC_DIR, "include"))],
        )

        compiler.link_executable(
            objects=link_objects,
            output_progname=os.path.join(tmp_dir, "cephfs_dummy"),
            libraries=["cephfs", "rados"],
            output_dir=tmp_dir,
        )

    except CompileError:
        print("\nCompile Error: Ceph FS development headers not found", file=sys.stderr)
        return False
    except LinkError:
        print("\nLink Error: Ceph FS library not found", file=sys.stderr)
        return False
    else:
        return True
    finally:
        shutil.rmtree(tmp_dir)
Esempio n. 23
0
def prepare_extra_c_file(info):
    c_file = info['filename']
    compile_args = info.get('compile_args', [])
    cc = new_compiler(verbose=3)
    customize_compiler(cc)
    [o_file] = cc.compile([c_file], '.',
                         extra_postargs=compile_args)
    return o_file
Esempio n. 24
0
    def build_libraries(self, libraries):
        customize_compiler(self.compiler)

        try:
            self.compiler.compiler_so.remove("-Wstrict-prototypes")
        except (AttributeError, ValueError):
            pass

        build_clib.build_libraries(self, libraries)
Esempio n. 25
0
 def build_extensions(self):
     # remove annoying flag which causes warning for c++ sources
     # https://stackoverflow.com/a/36293331/351771
     customize_compiler(self.compiler)
     try:
         self.compiler.compiler_so.remove("-Wstrict-prototypes")
     except (AttributeError, ValueError):
         pass
     distutils.command.build_ext.build_ext.build_extensions(self)
Esempio n. 26
0
def detect_zmq(basedir, compiler=None, **compiler_attrs):
    """Compile, link & execute a test program, in empty directory `basedir`.
    
    The C compiler will be updated with any keywords given via setattr.
    
    Parameters
    ----------
    
    basedir : path
        The location where the test program will be compiled and run
    compiler : str
        The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32')
    **compiler_attrs : dict
        Any extra compiler attributes, which will be set via ``setattr(cc)``.
    
    Returns
    -------
    
    A dict of properties for zmq compilation, with the following two keys:
    
    vers : tuple
        The ZMQ version as a tuple of ints, e.g. (2,2,0)
    settings : dict
        The compiler options used to compile the test function, e.g. `include_dirs`,
        `library_dirs`, `libs`, etc.
    """
    
    cfile = pjoin(basedir, 'vers.c')
    shutil.copy(pjoin(os.path.dirname(__file__), 'vers.c'), cfile)
    
    # check if we need to link against Realtime Extensions library
    if sys.platform.startswith('linux'):
        cc = ccompiler.new_compiler(compiler=compiler)
        customize_compiler(cc)
        cc.output_dir = basedir
        if not cc.has_function('timer_create'):
            compiler_attrs['libraries'].append('rt')
    
    cc = get_compiler(compiler=compiler, **compiler_attrs)
    efile = test_compilation(cfile, compiler=cc, **compiler_attrs)
    patch_lib_paths(efile, cc.library_dirs)
    
    rc, so, se = get_output_error([efile])
    if rc:
        msg = "Error running version detection script:\n%s\n%s" % (so,se)
        logging.error(msg)
        raise IOError(msg)

    handlers = {'vers':  lambda val: tuple(int(v) for v in val.split('.'))}

    props = {}
    for line in (x for x in so.split('\n') if x):
        key, val = line.split(':')
        props[key] = handlers[key](val)

    return props
Esempio n. 27
0
 def __init__(self, lang_ext="c"):
     ccompiler = new_compiler()
     customize_compiler(ccompiler)
     self.ccompiler = ccompiler
     self.macros = []
     self.include_dirs = []
     self.default_lang_ext = lang_ext
     self.header_availability = {}
     self.type_availability = {}
     self.decl_availability = {}
Esempio n. 28
0
 def _detect_sse3(self):
     "Does this compiler support SSE3 intrinsics?"
     compiler = new_compiler()
     customize_compiler(compiler)
     self._print_support_start('SSE3')
     result = self.hasfunction(compiler, '__m128 v; _mm_hadd_ps(v,v)',
                        include='<pmmintrin.h>',
                        extra_postargs=['-msse3'])
     self._print_support_end('SSE3', result)
     return result
Esempio n. 29
0
 def _detect_sse41(self):
     "Does this compiler support SSE4.1 intrinsics?"
     compiler = new_compiler()
     customize_compiler(compiler)
     self._print_support_start('SSE4.1')
     result = self.hasfunction(compiler, '__m128 v; _mm_round_ps(v,0x00)',
                        include='<smmintrin.h>',
                        extra_postargs=['-msse4'])
     self._print_support_end('SSE4.1', result)
     return result
Esempio n. 30
0
 def build_extensions(self):
     customize_compiler(self.compiler)
     try:
         self.compiler.compiler_so.remove("-Wstrict-prototypes")
     except (AttributeError, ValueError):
         pass
     lto_flags=["-flto", "-flto-partition=none", "-fuse-linker-plugin",
                "-ffat-lto-objects"]
     self.compiler.compiler_so = [f for f in self.compiler.compiler_so if f not in lto_flags]
     build_ext.build_extensions(self)