Ejemplo n.º 1
0
def autobuild_documentation(tile):
    """Generate documentation for this module using a combination of sphinx and breathe"""

    docdir = os.path.join('#doc')
    docfile = os.path.join(docdir, 'conf.py')
    outdir = os.path.join('build', 'output', 'doc', tile.unique_id)
    outfile = os.path.join(outdir, '%s.timestamp' % tile.unique_id)

    env = Environment(ENV=os.environ, tools=[])

    # Only build doxygen documentation if we have C firmware to build from
    if os.path.exists('firmware'):
        autobuild_doxygen(tile)
        env.Depends(outfile, 'doxygen')

    # There is no /dev/null on Windows
    # Also disable color output on Windows since it seems to leave powershell
    # in a weird state.
    if platform.system() == 'Windows':
        action = 'sphinx-build --no-color -b html %s %s > NUL' % (docdir[1:],
                                                                  outdir)
    else:
        action = 'sphinx-build -b html %s %s > /dev/null' % (docdir[1:],
                                                             outdir)

    env.Command(outfile,
                docfile,
                action=env.Action(action, "Building Component Documentation"))
    Alias('documentation', outdir)
    env.Clean(outfile, outdir)
Ejemplo n.º 2
0
def autobuild_python_scripts(scripts_dir):
    """Calls a list of python scripts required for the build
    
        Args:
            scripts (list(dict)): Dictionary of scripts with their arguments

            Ex.
            scripts[0] = {
                'script_path': 'example_script_1.py',
                'args': [es1_arg1, es1_arg2, es1_arg3]
            }
            scripts[1] = {
                'script_path': 'example_script_2.py',
                'args': [es2_arg1, es2_arg2]
            }
    """

    env = Environment(tools=[])
    script_target_output = 'build/test/output/'
    scripts_source = []
    scripts_target = []

    for script in os.listdir(scripts_dir):
        scripts_source.append(os.path.join(scripts_dir, script))
        scripts_target.append(
            os.path.join(script_target_output, script + '.log'))

    target = env.Command(scripts_target,
                         scripts_source,
                         action=env.Action(run_python_scripts,
                                           "Running python scripts"))
    env.AlwaysBuild(target)
Ejemplo n.º 3
0
    def __init__(self, build_root=None):
        if build_root == None:
            self.projpath = Dir('#build')
        else:
            self.projpath = str(build_root)

        #print('projpath', build_root)
        self.__help_texts = {
            "global_vars": "",
            "options": '',
            'local_vars': ''
        }
        self.dummyenv = {}

        self.def_env_file = "global.vars"
        self.defvars = None
        self.opts = None

        self.AddOptions()
        self.AddVariables()

        self.defenv = Environment(variables=self.defvars,
                                  ENV={'PATH': environ['PATH']})

        self.Check()
Ejemplo n.º 4
0
def autobuild_doxygen(tile):
    """Generate documentation for firmware in this module using doxygen"""

    iotile = IOTile('.')

    doxydir = os.path.join('build', 'doc')
    doxyfile = os.path.join(doxydir, 'doxygen.txt')

    outfile = os.path.join(doxydir, '%s.timestamp' % tile.unique_id)
    env = Environment(ENV=os.environ, tools=[])
    env['IOTILE'] = iotile

    # There is no /dev/null on Windows
    if platform.system() == 'Windows':
        action = 'doxygen %s > NUL' % doxyfile
    else:
        action = 'doxygen %s > /dev/null' % doxyfile

    Alias('doxygen', doxydir)
    env.Clean(outfile, doxydir)

    inputfile = doxygen_source_path()

    env.Command(doxyfile,
                inputfile,
                action=env.Action(
                    lambda target, source, env: generate_doxygen_file(
                        str(target[0]), iotile),
                    "Creating Doxygen Config File"))
    env.Command(outfile,
                doxyfile,
                action=env.Action(action, "Building Firmware Documentation"))
Ejemplo n.º 5
0
def configure(env):
    env.use_ptrcall = True

    if env['platform'] == 'windows':
        if env['bits'] == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_path = os.getenv('MONO32_PREFIX')
            else:
                mono_path = os.path.join(get_program_files_32(), 'Mono')
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_path = os.getenv('MONO64_PREFIX')
            else:
                mono_path = os.path.join(get_program_files_64(), 'Mono')

        env.Append(LIBPATH=os.path.join(mono_path, 'lib'))
        env.Append(CPPPATH=os.path.join(mono_path, 'include', 'mono-2.0'))

        mono_lib = 'monosgen-2.0'

        if os.getenv("VCINSTALLDIR"):
            env.Append(LINKFLAGS=mono_lib + Environment()['LIBSUFFIX'])
        else:
            env.Append(LIBS=mono_lib)
    else:
        env.ParseConfig('pkg-config mono-2 --cflags --libs')
        env.Append(LINKFLAGS='-rdynamic')
def createEnvironment(tools, mingw_mode, msvc_version, target_arch):
    from SCons.Script import Environment  # pylint: disable=I0021,import-error

    args = {}

    # If we are on Windows, and MinGW is not enforced, lets see if we can
    # find "cl.exe", and if we do, disable automatic scan.
    if (os.name == "nt" and not mingw_mode
            and (getExecutablePath("cl", env=None) is not None
                 or getExecutablePath("gcc", env=None) is not None)):
        args["MSVC_USE_SCRIPT"] = False

    return Environment(
        # We want the outside environment to be passed through.
        ENV=os.environ,
        # Extra tools configuration for scons.
        tools=tools,
        # The shared libraries should not be named "lib...", because CPython
        # requires the filename "module_name.so" to load it.
        SHLIBPREFIX="",
        # Under windows, specify the target architecture is needed for Scons
        # to pick up MSVC.
        TARGET_ARCH=target_arch,
        MSVC_VERSION=msvc_version,
        **args)
Ejemplo n.º 7
0
    def __init__(self, src_dir, build_dir, common_construct_vars, bt_cv_pairs):
        """
        src_dir                 source directory
        build_dir               build directory
        common_construct_vars   {construction var : value}
                                Common construction vars for all build versions.
        bt_cv_pairs             [(build type name, construction vars)]
                                Type of construction vars is the same as common_construct_vars
        """
        self.src_dir = src_dir
        self.build_dir = build_dir
        self.static_lib_dirs, self.app_main_srcs = fs.dirs_c_cpp_sources(
            src_dir)

        self.common_env = Environment(**common_construct_vars)
        self.__add_build_vars(self.common_env,
                              map(lambda (n, _): n, bt_cv_pairs))

        # { build type name : construct vars map }
        # construct vars map { construction var : value }
        self.__bt_cv_map = dict(bt_cv_pairs)

        # { static lib dir : [c/c++ sources] }
        self.__static_lib_srcs_map = {}
        for each in self.static_lib_dirs:
            self.__static_lib_srcs_map[each] = fs.c_cpp_sources(each)
        pass
Ejemplo n.º 8
0
def autobuild_python_test(path):
    """Add pytest unit tests to be built as part of build/test/output."""

    env = Environment(tools=[])
    target = env.Command(['build/test/output/pytest.log'], [path],
                         action=env.Action(run_pytest,
                                           "Running python unit tests"))
    env.AlwaysBuild(target)
Ejemplo n.º 9
0
def get_sgf_checksum(file_name=None, sensorgraph=None):
    """Returns the device checksum from a sensorgraph file"""

    env = Environment(tools=[])

    env.Command([os.path.join('build', 'output', file_name)], [sensorgraph],
                action=Action(_get_sgf_checksum_action,
                              "Building SGF Checksum file at $TARGET"))
Ejemplo n.º 10
0
def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
    tmpenv = Environment()
    tmpenv.AppendENVPath('PKG_CONFIG_PATH', os.getenv('PKG_CONFIG_PATH'))
    tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')
    for hint_dir in tmpenv['LIBPATH']:
        name_found = find_file_in_dir(hint_dir, mono_lib_names, prefix='lib', extension=sharedlib_ext)
        if name_found and os.path.isdir(os.path.join(hint_dir, '..', 'include', 'mono-2.0')):
            return os.path.join(hint_dir, '..')
    return ''
Ejemplo n.º 11
0
def build_trub_records(file_name,
                       slot_assignments=None,
                       os_info=None,
                       sensor_graph=None,
                       app_info=None,
                       use_safeupdate=False):
    """Build a trub script based on the records received for each slot.

    slot_assignments should be a list of tuples in the following form:
    ("slot X" or "controller", firmware_image_name, record_type, args)

    The output of this autobuild action will be a trub script in
    build/output/<file_name> that assigns the given firmware to each slot in
    the order specified in the slot_assignments list.

    Args:
        file_name (str): The name of the output file that we should create.
            This file name should end in .trub
        slot_assignments (list of (str, str, str, list)): The tuple contains
            (slot name, firmware file, record type, args)
        os_info (tuple(int, str)): A tuple of OS version tag and X.Y version
            number that will be set as part of the OTA script if included. Optional.
        sensor_graph (str): Name of sgf file. Optional.
        app_info (tuple(int, str)): A tuple of App version tag and X.Y version
            number that will be set as part of the OTA script if included. Optional.
        use_safeupdate (bool): Enables safe firmware update
    """

    resolver = ProductResolver.Create()
    env = Environment(tools=[])
    files = []
    records = []

    if slot_assignments is not None:
        slots = [_parse_slot_assignment(x) for x in slot_assignments]
        files = [
            ensure_image_is_hex(
                resolver.find_unique("firmware_image", x[1]).full_path)
            for x in slot_assignments
        ]
        env['SLOTS'] = slots
    else:
        env['SLOTS'] = None

    env['USE_SAFEUPDATE'] = use_safeupdate
    env['OS_INFO'] = os_info
    env['APP_INFO'] = app_info
    env['UPDATE_SENSORGRAPH'] = False

    if sensor_graph is not None:
        files.append(sensor_graph)
        env['UPDATE_SENSORGRAPH'] = True

    env.Command([os.path.join('build', 'output', file_name)],
                files,
                action=Action(_build_records_action,
                              "Building TRUB script at $TARGET"))
Ejemplo n.º 12
0
def pkgconfig_try_find_mono_root(mono_lib_names, sharedlib_ext):
    tmpenv = Environment()
    tmpenv.AppendENVPath("PKG_CONFIG_PATH", os.getenv("PKG_CONFIG_PATH"))
    tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L")
    for hint_dir in tmpenv["LIBPATH"]:
        name_found = find_name_in_dir_files(hint_dir, mono_lib_names, prefixes=["lib"], extensions=[sharedlib_ext])
        if name_found and os.path.isdir(os.path.join(hint_dir, "..", "include", "mono-2.0")):
            return os.path.join(hint_dir, "..")
    return ""
Ejemplo n.º 13
0
def _internal_data(variables_cache_file):
    mydata = {
        # 2 my own env variables are added in function read_vars_from_cache and then
        # their values are set in function save_vars_to_cache
        'env': Environment(),
        'new_env_call': lambda **kwargs: Environment(**kwargs),

        # This is a SCons.Variables.Variables class object for reading from /
        # writing to the variables cache file
        # Changed by calling method "Add" in function read_vars_from_cache
        'scons_var_obj': Variables(variables_cache_file),
        'arguments': ARGUMENTS,
        'command_line_targets': COMMAND_LINE_TARGETS,

        # A class for appending values to environment variables (as lists)
        'clvar': SCons.Util.CLVar
    }
    return mydata
Ejemplo n.º 14
0
def createEnvironment(mingw_mode, msvc_version, target_arch, experimental):
    from SCons.Script import Environment  # pylint: disable=I0021,import-error

    args = {}

    if msvc_version == "list":
        import SCons.Tool.MSCommon.vc  # pylint: disable=I0021,import-error

        scons_logger.sysexit(
            "Installed MSVC versions are %s." % ",".join(
                repr(v) for v in SCons.Tool.MSCommon.vc.get_installed_vcs()), )
    # If we are on Windows, and MinGW is not enforced, lets see if we can
    # find "cl.exe", and if we do, disable automatic scan.
    if (os.name == "nt" and not mingw_mode and msvc_version is None
            and msvc_version != "latest"
            and (getExecutablePath("cl", env=None) is not None)):
        args["MSVC_USE_SCRIPT"] = False

    if mingw_mode:
        # Force usage of MinGW64, not using MSVC tools.
        tools = ["mingw"]

        # This code would be running anyway, make it do not thing by monkey patching.
        import SCons.Tool.MSCommon.vc  # pylint: disable=I0021,import-error

        SCons.Tool.MSCommon.vc.msvc_setup_env = lambda *args: None
    else:
        # Everything else should use default, that is MSVC tools, but not MinGW64.
        tools = ["default"]

    env = Environment(
        # We want the outside environment to be passed through.
        ENV=os.environ,
        # Extra tools configuration for scons.
        tools=tools,
        # The shared libraries should not be named "lib...", because CPython
        # requires the filename "module_name.so" to load it.
        SHLIBPREFIX="",
        # Under windows, specify the target architecture is needed for Scons
        # to pick up MSVC.
        TARGET_ARCH=target_arch,
        # The MSVC version might be fixed by the user.
        MSVC_VERSION=msvc_version if msvc_version != "latest" else None,
        **args)

    _enableExperimentalSettings(env, experimental)

    return env
Ejemplo n.º 15
0
def combine_trub_scripts(trub_scripts_list, out_file):
    """Combines trub scripts, processed from first to last"""

    resolver = ProductResolver.Create()

    files = [
        resolver.find_unique("trub_script", x).full_path
        for x in trub_scripts_list
    ]

    env = Environment(tools=[])

    env.Command([os.path.join('build', 'output', out_file)],
                files,
                action=Action(_combine_trub_scripts_action,
                              "Combining TRUB scripts at $TARGET"))
Ejemplo n.º 16
0
def autobuild_bootstrap_file(file_name, image_list):
    """Combine multiple firmware images into a single bootstrap hex file.

    The files listed in image_list must be products of either this tile or any
    dependency tile and should correspond exactly with the base name listed on
    the products section of the module_settings.json file of the corresponding
    tile.  They must be listed as firmware_image type products.

    This function keeps a global map of all of the intermediate files that it
    has had to create so that we don't try to build them multiple times.

    Args:
        file_name(str): Full name of the output bootstrap hex file.
        image_list(list of str): List of files that will be combined into a
            single hex file that will be used to flash a chip.
    """

    family = utilities.get_family('module_settings.json')
    target = family.platform_independent_target()
    resolver = ProductResolver.Create()

    env = Environment(tools=[])

    output_dir = target.build_dirs()['output']
    build_dir = target.build_dirs()['build']

    build_output_name = os.path.join(build_dir, file_name)
    full_output_name = os.path.join(output_dir, file_name)

    processed_input_images = []

    for image_name in image_list:
        image_info = resolver.find_unique('firmware_image', image_name)
        image_path = image_info.full_path

        hex_path = arm.ensure_image_is_hex(image_path)
        processed_input_images.append(hex_path)

    env.Command(
        build_output_name,
        processed_input_images,
        action=Action(
            arm.merge_hex_executables,
            "Merging %d hex files into $TARGET" % len(processed_input_images)))
    env.Command(full_output_name, build_output_name,
                Copy("$TARGET", "$SOURCE"))
Ejemplo n.º 17
0
def autobuild_release(family=None):
    """Copy necessary files into build/output so that this component can be used by others

    Args:
        family (ArchitectureGroup): The architecture group that we are targeting.  If not
            provided, it is assumed that we are building in the current directory and the
            module_settings.json file is read to create an ArchitectureGroup
    """

    if family is None:
        family = utilities.get_family('module_settings.json')

    env = Environment(tools=[])
    env['TILE'] = family.tile

    target = env.Command(['#build/output/module_settings.json'],
                         ['#module_settings.json'],
                         action=env.Action(create_release_settings_action,
                                           "Creating release manifest"))
    env.AlwaysBuild(target)

    # Copy over release notes if they exist
    if os.path.exists('RELEASE.md'):
        env.Command(['build/output/RELEASE.md'], ['RELEASE.md'],
                    Copy("$TARGET", "$SOURCE"))

    # Now copy across the build products that are not copied automatically
    copy_include_dirs(family.tile)
    copy_tilebus_definitions(family.tile)
    copy_dependency_docs(family.tile)
    copy_linker_scripts(family.tile)

    # Allow users to specify a hide_dependency_images flag that does not copy over all firmware images
    if not family.tile.settings.get('hide_dependency_images', False):
        copy_dependency_images(family.tile)

    copy_extra_files(family.tile)
    build_python_distribution(family.tile)
Ejemplo n.º 18
0
def configure(env):
    env.use_ptrcall = True
    env.add_module_version_string('mono')

    envvars = Variables()
    envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
    envvars.Add(
        PathVariable('mono_assemblies_output_dir',
                     'Path to the assemblies output directory', '#bin',
                     custom_path_is_dir_create))
    envvars.Update(env)

    bits = env['bits']

    mono_static = env['mono_static']
    assemblies_output_dir = Dir(env['mono_assemblies_output_dir']).abspath

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    if env['platform'] == 'windows':
        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError('Mono installation directory not found')

        mono_version = mono_root_try_find_mono_version(mono_root)
        configure_for_mono_version(env, mono_version)

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        if mono_static:
            lib_suffix = Environment()['LIBSUFFIX']

            if env.msvc:
                mono_static_lib_name = 'libmono-static-sgen'
            else:
                mono_static_lib_name = 'libmonosgen-2.0'

            if not os.path.isfile(
                    os.path.join(mono_lib_path,
                                 mono_static_lib_name + lib_suffix)):
                raise RuntimeError('Could not find static mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix)

                env.Append(LINKFLAGS='Mincore' + lib_suffix)
                env.Append(LINKFLAGS='msvcrt' + lib_suffix)
                env.Append(LINKFLAGS='LIBCMT' + lib_suffix)
                env.Append(LINKFLAGS='Psapi' + lib_suffix)
            else:
                env.Append(LINKFLAGS=os.path.join(
                    mono_lib_path, mono_static_lib_name + lib_suffix))

                env.Append(LIBS='psapi')
                env.Append(LIBS='version')
        else:
            mono_lib_name = find_file_in_dir(mono_lib_path,
                                             mono_lib_names,
                                             extension='.lib')

            if not mono_lib_name:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_lib_name +
                           Environment()['LIBSUFFIX'])
            else:
                env.Append(LIBS=mono_lib_name)

            mono_bin_path = os.path.join(mono_root, 'bin')

            mono_dll_name = find_file_in_dir(mono_bin_path,
                                             mono_lib_names,
                                             extension='.dll')

            if not mono_dll_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   mono_bin_path)

            copy_file(mono_bin_path, 'bin', mono_dll_name + '.dll')

        copy_file(os.path.join(mono_lib_path, 'mono', '4.5'),
                  assemblies_output_dir, 'mscorlib.dll')
    else:
        sharedlib_ext = '.dylib' if sys.platform == 'darwin' else '.so'

        mono_root = ''
        mono_lib_path = ''

        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')

        # We can't use pkg-config to link mono statically,
        # but we can still use it to find the mono root directory
        if not mono_root and mono_static:
            mono_root = pkgconfig_try_find_mono_root(mono_lib_names,
                                                     sharedlib_ext)
            if not mono_root:
                raise RuntimeError(
                    'Building with mono_static=yes, but failed to find the mono prefix with pkg-config. Specify one manually'
                )

        if mono_root:
            mono_version = mono_root_try_find_mono_version(mono_root)
            configure_for_mono_version(env, mono_version)

            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=mono_lib_path)
            env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path,
                                        mono_lib_names,
                                        prefix='lib',
                                        extension='.a')

            if not mono_lib:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            env.Append(CPPFLAGS=['-D_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path,
                                             'lib' + mono_lib + '.a')

                if sys.platform == 'darwin':
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                elif sys.platform == 'linux' or sys.platform == 'linux2':
                    env.Append(LINKFLAGS=[
                        '-Wl,-whole-archive', mono_lib_file,
                        '-Wl,-no-whole-archive'
                    ])
                else:
                    raise RuntimeError(
                        'mono-static: Not supported on this platform')
            else:
                env.Append(LIBS=[mono_lib])

            if sys.platform == 'darwin':
                env.Append(LIBS=['iconv', 'pthread'])
            elif sys.platform == 'linux' or sys.platform == 'linux2':
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

            if not mono_static:
                mono_so_name = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefix='lib',
                                                extension=sharedlib_ext)

                if not mono_so_name:
                    raise RuntimeError(
                        'Could not find mono shared library in: ' +
                        mono_lib_path)

                copy_file(mono_lib_path, 'bin',
                          'lib' + mono_so_name + sharedlib_ext)

            copy_file(os.path.join(mono_lib_path, 'mono', '4.5'),
                      assemblies_output_dir, 'mscorlib.dll')
        else:
            assert not mono_static

            mono_version = pkgconfig_try_find_mono_version()
            configure_for_mono_version(env, mono_version)

            env.ParseConfig('pkg-config monosgen-2 --cflags --libs')

            mono_lib_path = ''
            mono_so_name = ''
            mono_prefix = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

            tmpenv = Environment()
            tmpenv.AppendENVPath('PKG_CONFIG_PATH',
                                 os.getenv('PKG_CONFIG_PATH'))
            tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')

            for hint_dir in tmpenv['LIBPATH']:
                name_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefix='lib',
                                              extension=sharedlib_ext)
                if name_found:
                    mono_lib_path = hint_dir
                    mono_so_name = name_found
                    break

            if not mono_so_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   str(tmpenv['LIBPATH']))

            copy_file(mono_lib_path, 'bin',
                      'lib' + mono_so_name + sharedlib_ext)
            copy_file(os.path.join(mono_prefix, 'lib', 'mono', '4.5'),
                      assemblies_output_dir, 'mscorlib.dll')

        env.Append(LINKFLAGS='-rdynamic')
Ejemplo n.º 19
0
def configure(env):
    env.use_ptrcall = True

    envvars = Variables()
    envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
    envvars.Update(env)

    mono_static = env['mono_static']

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    if env['platform'] == 'windows':
        if mono_static:
            raise RuntimeError('mono-static: Not supported on Windows')

        if env['bits'] == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir()
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir()

        if mono_root is None:
            raise RuntimeError('Mono installation directory not found')

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        mono_lib_name = find_file_in_dir(mono_lib_path, mono_lib_names, extension='.lib')

        if mono_lib_name is None:
            raise RuntimeError('Could not find mono library in: ' + mono_lib_path)

        if os.getenv('VCINSTALLDIR'):
            env.Append(LINKFLAGS=mono_lib_name + Environment()['LIBSUFFIX'])
        else:
            env.Append(LIBS=mono_lib_name)

        mono_bin_path = os.path.join(mono_root, 'bin')

        mono_dll_name = find_file_in_dir(mono_bin_path, mono_lib_names, extension='.dll')

        mono_dll_src = os.path.join(mono_bin_path, mono_dll_name + '.dll')
        mono_dll_dst = os.path.join('bin', mono_dll_name + '.dll')
        copy_mono_dll = True

        if not os.path.isdir('bin'):
            os.mkdir('bin')
        elif os.path.exists(mono_dll_dst):
            copy_mono_dll = False

        if copy_mono_dll:
            copyfile(mono_dll_src, mono_dll_dst)
    else:
        mono_root = None

        if env['bits'] == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')

        if mono_root is not None:
            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=mono_lib_path)
            env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path, mono_lib_names, prefix='lib', extension='.a')

            if mono_lib is None:
                raise RuntimeError('Could not find mono library in: ' + mono_lib_path)

            env.Append(CPPFLAGS=['-D_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path, 'lib' + mono_lib + '.a')

                if sys.platform == "darwin":
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                elif sys.platform == "linux" or sys.platform == "linux2":
                    env.Append(LINKFLAGS=['-Wl,-whole-archive', mono_lib_file, '-Wl,-no-whole-archive'])
                else:
                    raise RuntimeError('mono-static: Not supported on this platform')
            else:
                env.Append(LIBS=[mono_lib])

            if sys.platform == "darwin":
                env.Append(LIBS=['iconv', 'pthread'])
            elif sys.platform == "linux" or sys.platform == "linux2":
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

        else:
            if mono_static:
                raise RuntimeError('mono-static: Not supported with pkg-config. Specify a mono prefix manually')

            env.ParseConfig('pkg-config monosgen-2 --cflags --libs')

        env.Append(LINKFLAGS='-rdynamic')
Ejemplo n.º 20
0
def configure(env, env_mono):
    bits = env['bits']
    is_android = env['platform'] == 'android'
    is_javascript = env['platform'] == 'javascript'

    tools_enabled = env['tools']
    mono_static = env['mono_static']
    copy_mono_root = env['copy_mono_root']

    mono_prefix = env['mono_prefix']

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    is_travis = os.environ.get('TRAVIS') == 'true'

    if is_travis:
        # Travis CI may have a Mono version lower than 5.12
        env_mono.Append(CPPDEFINES=['NO_PENDING_EXCEPTIONS'])

    if is_android and not env['android_arch'] in android_arch_dirs:
        raise RuntimeError(
            'This module does not support the specified \'android_arch\': ' +
            env['android_arch'])

    if tools_enabled and not module_supports_tools_on(env['platform']):
        # TODO:
        # Android: We have to add the data directory to the apk, concretely the Api and Tools folders.
        raise RuntimeError(
            'This module does not currently support building for this platform with tools enabled'
        )

    if is_android and mono_static:
        # Android: When static linking and doing something that requires libmono-native, we get a dlopen error as libmono-native seems to depend on libmonosgen-2.0
        raise RuntimeError(
            'Statically linking Mono is not currently supported on this platform'
        )

    if is_javascript:
        mono_static = True

    if not mono_prefix and (os.getenv('MONO32_PREFIX')
                            or os.getenv('MONO64_PREFIX')):
        print(
            "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the 'mono_prefix' SCons parameter instead"
        )

    if env['platform'] == 'windows':
        mono_root = mono_prefix

        if not mono_root and os.name == 'nt':
            mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        print('Found Mono root directory: ' + mono_root)

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env_mono.Prepend(
            CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        lib_suffix = Environment()['LIBSUFFIX']

        if mono_static:
            if env.msvc:
                mono_static_lib_name = 'libmono-static-sgen'
            else:
                mono_static_lib_name = 'libmonosgen-2.0'

            if not os.path.isfile(
                    os.path.join(mono_lib_path,
                                 mono_static_lib_name + lib_suffix)):
                raise RuntimeError('Could not find static mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix)

                env.Append(LINKFLAGS='Mincore' + lib_suffix)
                env.Append(LINKFLAGS='msvcrt' + lib_suffix)
                env.Append(LINKFLAGS='LIBCMT' + lib_suffix)
                env.Append(LINKFLAGS='Psapi' + lib_suffix)
            else:
                env.Append(LINKFLAGS=os.path.join(
                    mono_lib_path, mono_static_lib_name + lib_suffix))

                env.Append(LIBS=['psapi'])
                env.Append(LIBS=['version'])
        else:
            mono_lib_name = find_file_in_dir(mono_lib_path,
                                             mono_lib_names,
                                             extension=lib_suffix)

            if not mono_lib_name:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_lib_name + lib_suffix)
            else:
                env.Append(LIBS=[mono_lib_name])

            mono_bin_path = os.path.join(mono_root, 'bin')

            mono_dll_name = find_file_in_dir(mono_bin_path,
                                             mono_lib_names,
                                             extension='.dll')

            if not mono_dll_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   mono_bin_path)

            copy_file(mono_bin_path, '#bin', mono_dll_name + '.dll')
    else:
        is_apple = (sys.platform == 'darwin' or "osxcross" in env)

        sharedlib_ext = '.dylib' if is_apple else '.so'

        mono_root = mono_prefix
        mono_lib_path = ''
        mono_so_name = ''

        if not mono_root and (is_android or is_javascript):
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        if not mono_root and is_apple:
            # Try with some known directories under OSX
            hint_dirs = [
                '/Library/Frameworks/Mono.framework/Versions/Current',
                '/usr/local/var/homebrew/linked/mono'
            ]
            for hint_dir in hint_dirs:
                if os.path.isdir(hint_dir):
                    mono_root = hint_dir
                    break

        # We can't use pkg-config to link mono statically,
        # but we can still use it to find the mono root directory
        if not mono_root and mono_static:
            mono_root = pkgconfig_try_find_mono_root(mono_lib_names,
                                                     sharedlib_ext)
            if not mono_root:
                raise RuntimeError("Building with mono_static=yes, but failed to find the mono prefix with pkg-config; " + \
                    "specify one manually with the 'mono_prefix' SCons parameter")

        if mono_root:
            print('Found Mono root directory: ' + mono_root)

            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=[mono_lib_path])
            env_mono.Prepend(
                CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path,
                                        mono_lib_names,
                                        prefix='lib',
                                        extension='.a')

            if not mono_lib:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            env_mono.Append(CPPDEFINES=['_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path,
                                             'lib' + mono_lib + '.a')

                if is_apple:
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                else:
                    assert is_desktop(
                        env['platform']) or is_android or is_javascript
                    env.Append(LINKFLAGS=[
                        '-Wl,-whole-archive', mono_lib_file,
                        '-Wl,-no-whole-archive'
                    ])

                if is_javascript:
                    env.Append(LIBS=[
                        'mono-icall-table', 'mono-native', 'mono-ilgen',
                        'mono-ee-interp'
                    ])

                    wasm_src_dir = os.path.join(mono_root, 'src')
                    if not os.path.isdir(wasm_src_dir):
                        raise RuntimeError(
                            'Could not find mono wasm src directory')

                    # Ideally this should be defined only for 'driver.c', but I can't fight scons for another 2 hours
                    env_mono.Append(CPPDEFINES=['CORE_BINDINGS'])

                    env_mono.add_source_files(env.modules_sources, [
                        os.path.join(wasm_src_dir, 'driver.c'),
                        os.path.join(wasm_src_dir, 'zlib-helper.c'),
                        os.path.join(wasm_src_dir, 'corebindings.c')
                    ])

                    env.Append(LINKFLAGS=[
                        '--js-library',
                        os.path.join(wasm_src_dir,
                                     'library_mono.js'), '--js-library',
                        os.path.join(wasm_src_dir, 'binding_support.js'),
                        '--js-library',
                        os.path.join(wasm_src_dir, 'dotnet_support.js')
                    ])
            else:
                env.Append(LIBS=[mono_lib])

            if is_apple:
                env.Append(LIBS=['iconv', 'pthread'])
            elif is_android:
                pass  # Nothing
            elif is_javascript:
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])
            else:
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

            if not mono_static:
                mono_so_name = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefix='lib',
                                                extension=sharedlib_ext)

                if not mono_so_name:
                    raise RuntimeError(
                        'Could not find mono shared library in: ' +
                        mono_lib_path)

                copy_file(mono_lib_path, '#bin',
                          'lib' + mono_so_name + sharedlib_ext)
        else:
            assert not mono_static

            # TODO: Add option to force using pkg-config
            print('Mono root directory not found. Using pkg-config instead')

            env.ParseConfig('pkg-config monosgen-2 --libs')
            env_mono.ParseConfig('pkg-config monosgen-2 --cflags')

            tmpenv = Environment()
            tmpenv.AppendENVPath('PKG_CONFIG_PATH',
                                 os.getenv('PKG_CONFIG_PATH'))
            tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')

            for hint_dir in tmpenv['LIBPATH']:
                name_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefix='lib',
                                              extension=sharedlib_ext)
                if name_found:
                    mono_lib_path = hint_dir
                    mono_so_name = name_found
                    break

            if not mono_so_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   str(tmpenv['LIBPATH']))

        if not mono_static:
            libs_output_dir = get_android_out_dir(
                env) if is_android else '#bin'
            copy_file(mono_lib_path, libs_output_dir,
                      'lib' + mono_so_name + sharedlib_ext)

        env.Append(LINKFLAGS='-rdynamic')

    if not tools_enabled:
        if is_desktop(env['platform']):
            if not mono_root:
                mono_root = subprocess.check_output(
                    ['pkg-config', 'mono-2',
                     '--variable=prefix']).decode('utf8').strip()

            make_template_dir(env, mono_root)
        elif is_android:
            # Compress Android Mono Config
            from . import make_android_mono_config
            config_file_path = os.path.join(mono_root, 'etc', 'mono', 'config')
            make_android_mono_config.generate_compressed_config(
                config_file_path, 'mono_gd/')

            # Copy the required shared libraries
            copy_mono_shared_libs(env, mono_root, None)
        elif is_javascript:
            pass  # No data directory for this platform

    if copy_mono_root:
        if not mono_root:
            mono_root = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

        if tools_enabled:
            copy_mono_root_files(env, mono_root)
        else:
            print(
                "Ignoring option: 'copy_mono_root'; only available for builds with 'tools' enabled."
            )
Ejemplo n.º 21
0
def build_python_distribution(tile):
    """Gather support/data files to create python wheel distribution."""
    env = Environment(tools=[])

    builddir = os.path.join('build', 'python')
    packagedir = os.path.join(builddir, tile.support_distribution)
    outdir = os.path.join('build', 'output', 'python')
    outsrcdir = os.path.join(outdir, 'src')

    if not tile.has_wheel:
        return

    buildfiles = []
    datafiles = []

    pkg_init = os.path.join(packagedir, '__init__.py')

    # Make sure we always clean up the temporary python directory that we are creating
    # so that there are no weird build issues
    env.Command(pkg_init, [], [
        Delete(builddir),
        Mkdir(builddir),
        Mkdir(packagedir),
        Touch(pkg_init)
        ])

    # Make sure build/output/python/src exists
    # We create a timestamp placeholder file so that other people can depend
    # on this directory and we always delete it so that we reclean everything
    # up and don't have any old files.
    outsrcnode = env.Command(os.path.join(outsrcdir, ".timestamp"), [], [
        Delete(outsrcdir),
        Mkdir(outsrcdir),
        Touch(os.path.join(outsrcdir, ".timestamp"))])


    for outpath, inpath in iter_support_files(tile):
        outfile = os.path.join(outsrcdir, outpath)
        buildfile = os.path.join(packagedir, outpath)

        target = env.Command(outfile, inpath, Copy("$TARGET", "$SOURCE"))
        env.Depends(target, outsrcnode)

        target = env.Command(buildfile, inpath, Copy("$TARGET", "$SOURCE"))
        env.Depends(target, pkg_init)

        if 'data' in os.path.normpath(buildfile).split(os.sep):
            datafile = os.path.join(tile.support_distribution, outpath)
            datafiles.append(datafile)

        buildfiles.append(buildfile)

    # Create setup.py file and then use that to build a python wheel and an sdist
    env['TILE'] = tile
    env['datafiles'] = datafiles
    support_sdist = "%s-%s.tar.gz" % (tile.support_distribution, tile.parsed_version.pep440_string())
    wheel_output = os.path.join('build', 'python', 'dist', tile.support_wheel)
    sdist_output = os.path.join('build', 'python', 'dist', support_sdist)

    env.Clean(os.path.join(outdir, tile.support_wheel), os.path.join('build', 'python'))
    env.Command([os.path.join(builddir, 'setup.py'), os.path.join(builddir, 'MANIFEST.in'),
                wheel_output], ['module_settings.json'] + buildfiles,
                action=Action(generate_setup_and_manifest, "Building python distribution"))

    env.Depends(sdist_output, wheel_output)
    env.Command([os.path.join(outdir, tile.support_wheel)], [wheel_output], Copy("$TARGET", "$SOURCE"))
    env.Command([os.path.join(outdir, support_sdist)], [sdist_output], Copy("$TARGET", "$SOURCE"))

    # Also copy over all dependency wheels as well
    wheels = find_dependency_wheels(tile)

    if "python_universal" in tile.settings:
        required_version = "py2.py3"
    else:
        required_version = "py3" if sys.version_info[0] == 3 else "py2"

    for wheel in wheels:
        wheel_name = os.path.basename(wheel)
        wheel_basename = '-'.join(wheel.split('-')[:-3])
        wheel_pattern = wheel_basename + "-*" + required_version + '*'

        wheel_source = glob.glob(wheel_pattern)
        wheel_real = glob.glob(wheel_basename + '*')

        if wheel_source:
            env.Command([os.path.join(outdir, wheel_name)], [wheel_source[0]], Copy("$TARGET", "$SOURCE"))
        else:
            print("This package is set up to require", required_version)
            print("Dependency version appears to be", wheel_real[0].split('/')[-1])
            raise BuildError("dependent wheel not built with compatible python version")
Ejemplo n.º 22
0
def configure(env, env_mono):
    bits = env['bits']
    is_android = env['platform'] == 'android'

    tools_enabled = env['tools']
    mono_static = env['mono_static']
    copy_mono_root = env['copy_mono_root']

    mono_prefix = env['mono_prefix']

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    if is_android and not env['android_arch'] in android_arch_dirs:
        raise RuntimeError(
            'This module does not support for the specified \'android_arch\': '
            + env['android_arch'])

    if is_android and tools_enabled:
        # TODO: Implement this. We have to add the data directory to the apk, concretely the Api and Tools folders.
        raise RuntimeError(
            'This module does not currently support building for android with tools enabled'
        )

    if (os.getenv('MONO32_PREFIX')
            or os.getenv('MONO64_PREFIX')) and not mono_prefix:
        print(
            "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the 'mono_prefix' SCons parameter instead"
        )

    if env['platform'] == 'windows':
        mono_root = mono_prefix

        if not mono_root and os.name == 'nt':
            mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        print('Found Mono root directory: ' + mono_root)

        mono_version = mono_root_try_find_mono_version(mono_root)
        configure_for_mono_version(env_mono, mono_version)

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env_mono.Prepend(
            CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        if mono_static:
            lib_suffix = Environment()['LIBSUFFIX']

            if env.msvc:
                mono_static_lib_name = 'libmono-static-sgen'
            else:
                mono_static_lib_name = 'libmonosgen-2.0'

            if not os.path.isfile(
                    os.path.join(mono_lib_path,
                                 mono_static_lib_name + lib_suffix)):
                raise RuntimeError('Could not find static mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix)

                env.Append(LINKFLAGS='Mincore' + lib_suffix)
                env.Append(LINKFLAGS='msvcrt' + lib_suffix)
                env.Append(LINKFLAGS='LIBCMT' + lib_suffix)
                env.Append(LINKFLAGS='Psapi' + lib_suffix)
            else:
                env.Append(LINKFLAGS=os.path.join(
                    mono_lib_path, mono_static_lib_name + lib_suffix))

                env.Append(LIBS='psapi')
                env.Append(LIBS='version')
        else:
            mono_lib_name = find_file_in_dir(mono_lib_path,
                                             mono_lib_names,
                                             extension='.lib')

            if not mono_lib_name:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_lib_name +
                           Environment()['LIBSUFFIX'])
            else:
                env.Append(LIBS=mono_lib_name)

            mono_bin_path = os.path.join(mono_root, 'bin')

            mono_dll_name = find_file_in_dir(mono_bin_path,
                                             mono_lib_names,
                                             extension='.dll')

            if not mono_dll_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   mono_bin_path)

            copy_file(mono_bin_path, '#bin', mono_dll_name + '.dll')
    else:
        is_apple = (sys.platform == 'darwin' or "osxcross" in env)

        sharedlib_ext = '.dylib' if is_apple else '.so'

        mono_root = mono_prefix
        mono_lib_path = ''
        mono_so_name = ''

        if not mono_root and is_android:
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        if not mono_root and is_apple:
            # Try with some known directories under OSX
            hint_dirs = [
                '/Library/Frameworks/Mono.framework/Versions/Current',
                '/usr/local/var/homebrew/linked/mono'
            ]
            for hint_dir in hint_dirs:
                if os.path.isdir(hint_dir):
                    mono_root = hint_dir
                    break

        # We can't use pkg-config to link mono statically,
        # but we can still use it to find the mono root directory
        if not mono_root and mono_static:
            mono_root = pkgconfig_try_find_mono_root(mono_lib_names,
                                                     sharedlib_ext)
            if not mono_root:
                raise RuntimeError("Building with mono_static=yes, but failed to find the mono prefix with pkg-config; " + \
                    "specify one manually with the 'mono_prefix' SCons parameter")

        if mono_root:
            print('Found Mono root directory: ' + mono_root)

            mono_version = mono_root_try_find_mono_version(mono_root)
            configure_for_mono_version(env_mono, mono_version)

            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=mono_lib_path)
            env_mono.Prepend(
                CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path,
                                        mono_lib_names,
                                        prefix='lib',
                                        extension='.a')

            if not mono_lib:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            env_mono.Append(CPPFLAGS=['-D_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path,
                                             'lib' + mono_lib + '.a')

                if is_apple:
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                else:
                    env.Append(LINKFLAGS=[
                        '-Wl,-whole-archive', mono_lib_file,
                        '-Wl,-no-whole-archive'
                    ])
            else:
                env.Append(LIBS=[mono_lib])

            if is_apple:
                env.Append(LIBS=['iconv', 'pthread'])
            elif is_android:
                env.Append(LIBS=['m', 'dl'])
            else:
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

            if not mono_static:
                mono_so_name = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefix='lib',
                                                extension=sharedlib_ext)

                if not mono_so_name:
                    raise RuntimeError(
                        'Could not find mono shared library in: ' +
                        mono_lib_path)

                copy_file(mono_lib_path, '#bin',
                          'lib' + mono_so_name + sharedlib_ext)
        else:
            assert not mono_static

            # TODO: Add option to force using pkg-config
            print('Mono root directory not found. Using pkg-config instead')

            mono_version = pkgconfig_try_find_mono_version()
            configure_for_mono_version(env_mono, mono_version)

            env.ParseConfig('pkg-config monosgen-2 --libs')
            env_mono.ParseConfig('pkg-config monosgen-2 --cflags')

            tmpenv = Environment()
            tmpenv.AppendENVPath('PKG_CONFIG_PATH',
                                 os.getenv('PKG_CONFIG_PATH'))
            tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')

            for hint_dir in tmpenv['LIBPATH']:
                name_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefix='lib',
                                              extension=sharedlib_ext)
                if name_found:
                    mono_lib_path = hint_dir
                    mono_so_name = name_found
                    break

            if not mono_so_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   str(tmpenv['LIBPATH']))

        if not mono_static:
            libs_output_dir = get_android_out_dir(
                env) if is_android else '#bin'
            copy_file(mono_lib_path, libs_output_dir,
                      'lib' + mono_so_name + sharedlib_ext)

        env.Append(LINKFLAGS='-rdynamic')

    if not tools_enabled and not is_android:
        if not mono_root:
            mono_root = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

        make_template_dir(env, mono_root)

    if copy_mono_root:
        if not mono_root:
            mono_root = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

        if tools_enabled:
            copy_mono_root_files(env, mono_root)
        else:
            print(
                "Ignoring option: 'copy_mono_root'. Only available for builds with 'tools' enabled."
            )
Ejemplo n.º 23
0
def configure(env):
    env.use_ptrcall = True
    env.add_module_version_string('mono')

    envvars = Variables()
    envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
    envvars.Add(
        BoolVariable(
            'copy_mono_root',
            'Make a copy of the mono installation directory to bundle with the editor',
            False))
    envvars.Update(env)

    bits = env['bits']

    tools_enabled = env['tools']
    mono_static = env['mono_static']
    copy_mono_root = env['copy_mono_root']

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    if env['platform'] == 'windows':
        mono_root = ''

        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError('Mono installation directory not found')

        print('Found Mono root directory: ' + mono_root)

        mono_version = mono_root_try_find_mono_version(mono_root)
        configure_for_mono_version(env, mono_version)

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        if mono_static:
            lib_suffix = Environment()['LIBSUFFIX']

            if env.msvc:
                mono_static_lib_name = 'libmono-static-sgen'
            else:
                mono_static_lib_name = 'libmonosgen-2.0'

            if not os.path.isfile(
                    os.path.join(mono_lib_path,
                                 mono_static_lib_name + lib_suffix)):
                raise RuntimeError('Could not find static mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_static_lib_name + lib_suffix)

                env.Append(LINKFLAGS='Mincore' + lib_suffix)
                env.Append(LINKFLAGS='msvcrt' + lib_suffix)
                env.Append(LINKFLAGS='LIBCMT' + lib_suffix)
                env.Append(LINKFLAGS='Psapi' + lib_suffix)
            else:
                env.Append(LINKFLAGS=os.path.join(
                    mono_lib_path, mono_static_lib_name + lib_suffix))

                env.Append(LIBS='psapi')
                env.Append(LIBS='version')
        else:
            mono_lib_name = find_file_in_dir(mono_lib_path,
                                             mono_lib_names,
                                             extension='.lib')

            if not mono_lib_name:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_lib_name +
                           Environment()['LIBSUFFIX'])
            else:
                env.Append(LIBS=mono_lib_name)

            mono_bin_path = os.path.join(mono_root, 'bin')

            mono_dll_name = find_file_in_dir(mono_bin_path,
                                             mono_lib_names,
                                             extension='.dll')

            if not mono_dll_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   mono_bin_path)

            copy_file(mono_bin_path, 'bin', mono_dll_name + '.dll')
    else:
        is_apple = (sys.platform == 'darwin' or "osxcross" in env)

        sharedlib_ext = '.dylib' if is_apple else '.so'

        mono_root = ''
        mono_lib_path = ''

        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')

        if not mono_root and is_apple:
            # Try with some known directories under OSX
            hint_dirs = [
                '/Library/Frameworks/Mono.framework/Versions/Current',
                '/usr/local/var/homebrew/linked/mono'
            ]
            for hint_dir in hint_dirs:
                if os.path.isdir(hint_dir):
                    mono_root = hint_dir
                    break

        # We can't use pkg-config to link mono statically,
        # but we can still use it to find the mono root directory
        if not mono_root and mono_static:
            mono_root = pkgconfig_try_find_mono_root(mono_lib_names,
                                                     sharedlib_ext)
            if not mono_root:
                raise RuntimeError(
                    'Building with mono_static=yes, but failed to find the mono prefix with pkg-config. Specify one manually'
                )

        if mono_root:
            print('Found Mono root directory: ' + mono_root)

            mono_version = mono_root_try_find_mono_version(mono_root)
            configure_for_mono_version(env, mono_version)

            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=mono_lib_path)
            env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path,
                                        mono_lib_names,
                                        prefix='lib',
                                        extension='.a')

            if not mono_lib:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            env.Append(CPPFLAGS=['-D_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path,
                                             'lib' + mono_lib + '.a')

                if is_apple:
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                else:
                    env.Append(LINKFLAGS=[
                        '-Wl,-whole-archive', mono_lib_file,
                        '-Wl,-no-whole-archive'
                    ])
            else:
                env.Append(LIBS=[mono_lib])

            if is_apple:
                env.Append(LIBS=['iconv', 'pthread'])
            else:
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

            if not mono_static:
                mono_so_name = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefix='lib',
                                                extension=sharedlib_ext)

                if not mono_so_name:
                    raise RuntimeError(
                        'Could not find mono shared library in: ' +
                        mono_lib_path)

                copy_file(mono_lib_path, 'bin',
                          'lib' + mono_so_name + sharedlib_ext)
        else:
            assert not mono_static

            # TODO: Add option to force using pkg-config
            print('Mono root directory not found. Using pkg-config instead')

            mono_version = pkgconfig_try_find_mono_version()
            configure_for_mono_version(env, mono_version)

            env.ParseConfig('pkg-config monosgen-2 --cflags --libs')

            mono_lib_path = ''
            mono_so_name = ''

            tmpenv = Environment()
            tmpenv.AppendENVPath('PKG_CONFIG_PATH',
                                 os.getenv('PKG_CONFIG_PATH'))
            tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')

            for hint_dir in tmpenv['LIBPATH']:
                name_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefix='lib',
                                              extension=sharedlib_ext)
                if name_found:
                    mono_lib_path = hint_dir
                    mono_so_name = name_found
                    break

            if not mono_so_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   str(tmpenv['LIBPATH']))

            copy_file(mono_lib_path, 'bin',
                      'lib' + mono_so_name + sharedlib_ext)

        env.Append(LINKFLAGS='-rdynamic')

    if not tools_enabled:
        if not mono_root:
            mono_root = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

        make_template_dir(env, mono_root)

    if copy_mono_root:
        if not mono_root:
            mono_root = subprocess.check_output(
                ['pkg-config', 'mono-2',
                 '--variable=prefix']).decode('utf8').strip()

        if tools_enabled:
            copy_mono_root_files(env, mono_root)
        else:
            print(
                "Ignoring option: 'copy_mono_root'. Only available for builds with 'tools' enabled."
            )
Ejemplo n.º 24
0
def configure(env, env_mono):
    bits = env["bits"]
    is_android = env["platform"] == "android"
    is_javascript = env["platform"] == "javascript"
    is_ios = env["platform"] == "iphone"
    is_ios_sim = is_ios and env["arch"] in ["x86", "x86_64"]

    tools_enabled = env["tools"]
    mono_static = env["mono_static"]
    copy_mono_root = env["copy_mono_root"]

    mono_prefix = env["mono_prefix"]

    mono_lib_names = ["mono-2.0-sgen", "monosgen-2.0"]

    is_travis = os.environ.get("TRAVIS") == "true"

    if is_travis:
        # Travis CI may have a Mono version lower than 5.12
        env_mono.Append(CPPDEFINES=["NO_PENDING_EXCEPTIONS"])

    if is_android and not env["android_arch"] in android_arch_dirs:
        raise RuntimeError(
            "This module does not support the specified 'android_arch': " +
            env["android_arch"])

    if tools_enabled and not module_supports_tools_on(env["platform"]):
        # TODO:
        # Android: We have to add the data directory to the apk, concretely the Api and Tools folders.
        raise RuntimeError(
            "This module does not currently support building for this platform with tools enabled"
        )

    if is_android and mono_static:
        # FIXME: When static linking and doing something that requires libmono-native, we get a dlopen error as 'libmono-native'
        # seems to depend on 'libmonosgen-2.0'. Could be fixed by re-directing to '__Internal' with a dllmap or in the dlopen hook.
        raise RuntimeError(
            "Statically linking Mono is not currently supported for this platform"
        )

    if not mono_static and (is_javascript or is_ios):
        raise RuntimeError(
            "Dynamically linking Mono is not currently supported for this platform"
        )

    if not mono_prefix and (os.getenv("MONO32_PREFIX")
                            or os.getenv("MONO64_PREFIX")):
        print(
            "WARNING: The environment variables 'MONO32_PREFIX' and 'MONO64_PREFIX' are deprecated; use the"
            " 'mono_prefix' SCons parameter instead")

    # Although we don't support building with tools for any platform where we currently use static AOT,
    # if these are supported in the future, we won't be using static AOT for them as that would be
    # too restrictive for the editor. These builds would probably be made to only use the interpreter.
    mono_aot_static = (is_ios and not is_ios_sim) and not env["tools"]

    # Static AOT is only supported on the root domain
    mono_single_appdomain = mono_aot_static

    if mono_single_appdomain:
        env_mono.Append(CPPDEFINES=["GD_MONO_SINGLE_APPDOMAIN"])

    if (env["tools"]
            or env["target"] != "release") and not mono_single_appdomain:
        env_mono.Append(CPPDEFINES=["GD_MONO_HOT_RELOAD"])

    if env["platform"] == "windows":
        mono_root = mono_prefix

        if not mono_root and os.name == "nt":
            mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        print("Found Mono root directory: " + mono_root)

        mono_lib_path = os.path.join(mono_root, "lib")

        env.Append(LIBPATH=mono_lib_path)
        env_mono.Prepend(
            CPPPATH=os.path.join(mono_root, "include", "mono-2.0"))

        lib_suffixes = [".lib"]

        if not env.msvc:
            # MingW supports both '.a' and '.lib'
            lib_suffixes.insert(0, ".a")

        if mono_static:
            if env.msvc:
                mono_static_lib_name = "libmono-static-sgen"
            else:
                mono_static_lib_name = "libmonosgen-2.0"

            mono_static_lib_file = find_file_in_dir(mono_lib_path,
                                                    [mono_static_lib_name],
                                                    extensions=lib_suffixes)

            if not mono_static_lib_file:
                raise RuntimeError("Could not find static mono library in: " +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_static_lib_file)

                env.Append(LINKFLAGS="Mincore.lib")
                env.Append(LINKFLAGS="msvcrt.lib")
                env.Append(LINKFLAGS="LIBCMT.lib")
                env.Append(LINKFLAGS="Psapi.lib")
            else:
                mono_static_lib_file_path = os.path.join(
                    mono_lib_path, mono_static_lib_file)
                env.Append(LINKFLAGS=[
                    "-Wl,-whole-archive", mono_static_lib_file_path,
                    "-Wl,-no-whole-archive"
                ])

                env.Append(LIBS=["psapi"])
                env.Append(LIBS=["version"])
        else:
            mono_lib_file = find_file_in_dir(mono_lib_path,
                                             mono_lib_names,
                                             extensions=lib_suffixes)

            if not mono_lib_file:
                raise RuntimeError("Could not find mono library in: " +
                                   mono_lib_path)

            if env.msvc:
                env.Append(LINKFLAGS=mono_lib_file)
            else:
                mono_lib_file_path = os.path.join(mono_lib_path, mono_lib_file)
                env.Append(LINKFLAGS=mono_lib_file_path)

            mono_bin_path = os.path.join(mono_root, "bin")

            mono_dll_file = find_file_in_dir(mono_bin_path,
                                             mono_lib_names,
                                             prefixes=["", "lib"],
                                             extensions=[".dll"])

            if not mono_dll_file:
                raise RuntimeError("Could not find mono shared library in: " +
                                   mono_bin_path)

            copy_file(mono_bin_path, "#bin", mono_dll_file)
    else:
        is_apple = env["platform"] in ["osx", "iphone"]
        is_macos = is_apple and not is_ios

        sharedlib_ext = ".dylib" if is_apple else ".so"

        mono_root = mono_prefix
        mono_lib_path = ""
        mono_so_file = ""

        if not mono_root and (is_android or is_javascript or is_ios):
            raise RuntimeError(
                "Mono installation directory not found; specify one manually with the 'mono_prefix' SCons parameter"
            )

        if not mono_root and is_macos:
            # Try with some known directories under OSX
            hint_dirs = [
                "/Library/Frameworks/Mono.framework/Versions/Current",
                "/usr/local/var/homebrew/linked/mono"
            ]
            for hint_dir in hint_dirs:
                if os.path.isdir(hint_dir):
                    mono_root = hint_dir
                    break

        # We can't use pkg-config to link mono statically,
        # but we can still use it to find the mono root directory
        if not mono_root and mono_static:
            mono_root = pkgconfig_try_find_mono_root(mono_lib_names,
                                                     sharedlib_ext)
            if not mono_root:
                raise RuntimeError(
                    "Building with mono_static=yes, but failed to find the mono prefix with pkg-config; "
                    +
                    "specify one manually with the 'mono_prefix' SCons parameter"
                )

        if is_ios and not is_ios_sim:
            env_mono.Append(CPPDEFINES=["IOS_DEVICE"])

        if mono_root:
            print("Found Mono root directory: " + mono_root)

            mono_lib_path = os.path.join(mono_root, "lib")

            env.Append(LIBPATH=[mono_lib_path])
            env_mono.Prepend(
                CPPPATH=os.path.join(mono_root, "include", "mono-2.0"))

            mono_lib = find_name_in_dir_files(mono_lib_path,
                                              mono_lib_names,
                                              prefixes=["lib"],
                                              extensions=[".a"])

            if not mono_lib:
                raise RuntimeError("Could not find mono library in: " +
                                   mono_lib_path)

            env_mono.Append(CPPDEFINES=["_REENTRANT"])

            if mono_static:
                env.Append(LINKFLAGS=["-rdynamic"])

                mono_lib_file = os.path.join(mono_lib_path,
                                             "lib" + mono_lib + ".a")

                if is_apple:
                    if is_macos:
                        env.Append(
                            LINKFLAGS=["-Wl,-force_load," + mono_lib_file])
                    else:
                        arch = env["arch"]

                        def copy_mono_lib(libname_wo_ext):
                            copy_file(
                                mono_lib_path, "#bin", libname_wo_ext + ".a",
                                "%s.iphone.%s.a" % (libname_wo_ext, arch))

                        # Copy Mono libraries to the output folder. These are meant to be bundled with
                        # the export templates and added to the Xcode project when exporting a game.
                        copy_mono_lib("lib" + mono_lib)
                        copy_mono_lib("libmono-native")
                        copy_mono_lib("libmono-profiler-log")

                        if not is_ios_sim:
                            copy_mono_lib("libmono-ee-interp")
                            copy_mono_lib("libmono-icall-table")
                            copy_mono_lib("libmono-ilgen")
                else:
                    assert is_desktop(
                        env["platform"]) or is_android or is_javascript
                    env.Append(LINKFLAGS=[
                        "-Wl,-whole-archive", mono_lib_file,
                        "-Wl,-no-whole-archive"
                    ])

                if is_javascript:
                    env.Append(LIBS=[
                        "mono-icall-table", "mono-native", "mono-ilgen",
                        "mono-ee-interp"
                    ])

                    wasm_src_dir = os.path.join(mono_root, "src")
                    if not os.path.isdir(wasm_src_dir):
                        raise RuntimeError(
                            "Could not find mono wasm src directory")

                    # Ideally this should be defined only for 'driver.c', but I can't fight scons for another 2 hours
                    env_mono.Append(CPPDEFINES=["CORE_BINDINGS"])

                    env_mono.add_source_files(
                        env.modules_sources,
                        [
                            os.path.join(wasm_src_dir, "driver.c"),
                            os.path.join(wasm_src_dir, "zlib-helper.c"),
                            os.path.join(wasm_src_dir, "corebindings.c"),
                        ],
                    )

                    env.Append(LINKFLAGS=[
                        "--js-library",
                        os.path.join(wasm_src_dir, "library_mono.js"),
                        "--js-library",
                        os.path.join(wasm_src_dir, "binding_support.js"),
                        "--js-library",
                        os.path.join(wasm_src_dir, "dotnet_support.js"),
                    ])
            else:
                env.Append(LIBS=[mono_lib])

            if is_macos:
                env.Append(LIBS=["iconv", "pthread"])
            elif is_android:
                pass  # Nothing
            elif is_ios:
                pass  # Nothing, linking is delegated to the exported Xcode project
            elif is_javascript:
                env.Append(LIBS=["m", "rt", "dl", "pthread"])
            else:
                env.Append(LIBS=["m", "rt", "dl", "pthread"])

            if not mono_static:
                mono_so_file = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefixes=["lib"],
                                                extensions=[sharedlib_ext])

                if not mono_so_file:
                    raise RuntimeError(
                        "Could not find mono shared library in: " +
                        mono_lib_path)
        else:
            assert not mono_static

            # TODO: Add option to force using pkg-config
            print("Mono root directory not found. Using pkg-config instead")

            env.ParseConfig("pkg-config monosgen-2 --libs")
            env_mono.ParseConfig("pkg-config monosgen-2 --cflags")

            tmpenv = Environment()
            tmpenv.AppendENVPath("PKG_CONFIG_PATH",
                                 os.getenv("PKG_CONFIG_PATH"))
            tmpenv.ParseConfig("pkg-config monosgen-2 --libs-only-L")

            for hint_dir in tmpenv["LIBPATH"]:
                file_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefixes=["lib"],
                                              extensions=[sharedlib_ext])
                if file_found:
                    mono_lib_path = hint_dir
                    mono_so_file = file_found
                    break

            if not mono_so_file:
                raise RuntimeError("Could not find mono shared library in: " +
                                   str(tmpenv["LIBPATH"]))

        if not mono_static:
            libs_output_dir = get_android_out_dir(
                env) if is_android else "#bin"
            copy_file(mono_lib_path, libs_output_dir, mono_so_file)

    if not tools_enabled:
        if is_desktop(env["platform"]):
            if not mono_root:
                mono_root = (subprocess.check_output(
                    ["pkg-config", "mono-2",
                     "--variable=prefix"]).decode("utf8").strip())

            make_template_dir(env, mono_root)
        elif is_android:
            # Compress Android Mono Config
            from . import make_android_mono_config

            module_dir = os.getcwd()
            config_file_path = os.path.join(module_dir, "build_scripts",
                                            "mono_android_config.xml")
            make_android_mono_config.generate_compressed_config(
                config_file_path, "mono_gd/")

            # Copy the required shared libraries
            copy_mono_shared_libs(env, mono_root, None)
        elif is_javascript:
            pass  # No data directory for this platform
        elif is_ios:
            pass  # No data directory for this platform

    if copy_mono_root:
        if not mono_root:
            mono_root = subprocess.check_output(
                ["pkg-config", "mono-2",
                 "--variable=prefix"]).decode("utf8").strip()

        if tools_enabled:
            copy_mono_root_files(env, mono_root)
        else:
            print(
                "Ignoring option: 'copy_mono_root'; only available for builds with 'tools' enabled."
            )
Ejemplo n.º 25
0
def configure(env):
    env.use_ptrcall = True
    env.add_module_version_string("mono")

    envvars = Variables()
    envvars.Add(BoolVariable('mono_static', 'Statically link mono', False))
    envvars.Update(env)

    bits = env['bits']

    mono_static = env['mono_static']

    mono_lib_names = ['mono-2.0-sgen', 'monosgen-2.0']

    if env['platform'] == 'windows':
        if mono_static:
            raise RuntimeError('mono-static: Not supported on Windows')

        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')
            elif os.name == 'nt':
                mono_root = monoreg.find_mono_root_dir(bits)

        if not mono_root:
            raise RuntimeError('Mono installation directory not found')

        mono_lib_path = os.path.join(mono_root, 'lib')

        env.Append(LIBPATH=mono_lib_path)
        env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

        mono_lib_name = find_file_in_dir(mono_lib_path,
                                         mono_lib_names,
                                         extension='.lib')

        if not mono_lib_name:
            raise RuntimeError('Could not find mono library in: ' +
                               mono_lib_path)

        if os.getenv('VCINSTALLDIR'):
            env.Append(LINKFLAGS=mono_lib_name + Environment()['LIBSUFFIX'])
        else:
            env.Append(LIBS=mono_lib_name)

        mono_bin_path = os.path.join(mono_root, 'bin')

        mono_dll_name = find_file_in_dir(mono_bin_path,
                                         mono_lib_names,
                                         extension='.dll')

        if not mono_dll_name:
            raise RuntimeError('Could not find mono shared library in: ' +
                               mono_bin_path)

        copy_file_no_replace(mono_bin_path, 'bin', mono_dll_name + '.dll')
    else:
        sharedlib_ext = '.dylib' if sys.platform == 'darwin' else '.so'

        mono_root = ''

        if bits == '32':
            if os.getenv('MONO32_PREFIX'):
                mono_root = os.getenv('MONO32_PREFIX')
        else:
            if os.getenv('MONO64_PREFIX'):
                mono_root = os.getenv('MONO64_PREFIX')

        if mono_root:
            mono_lib_path = os.path.join(mono_root, 'lib')

            env.Append(LIBPATH=mono_lib_path)
            env.Append(CPPPATH=os.path.join(mono_root, 'include', 'mono-2.0'))

            mono_lib = find_file_in_dir(mono_lib_path,
                                        mono_lib_names,
                                        prefix='lib',
                                        extension='.a')

            if not mono_lib:
                raise RuntimeError('Could not find mono library in: ' +
                                   mono_lib_path)

            env.Append(CPPFLAGS=['-D_REENTRANT'])

            if mono_static:
                mono_lib_file = os.path.join(mono_lib_path,
                                             'lib' + mono_lib + '.a')

                if sys.platform == "darwin":
                    env.Append(LINKFLAGS=['-Wl,-force_load,' + mono_lib_file])
                elif sys.platform == "linux" or sys.platform == "linux2":
                    env.Append(LINKFLAGS=[
                        '-Wl,-whole-archive', mono_lib_file,
                        '-Wl,-no-whole-archive'
                    ])
                else:
                    raise RuntimeError(
                        'mono-static: Not supported on this platform')
            else:
                env.Append(LIBS=[mono_lib])

            if sys.platform == "darwin":
                env.Append(LIBS=['iconv', 'pthread'])
            elif sys.platform == "linux" or sys.platform == "linux2":
                env.Append(LIBS=['m', 'rt', 'dl', 'pthread'])

            if not mono_static:
                mono_so_name = find_file_in_dir(mono_lib_path,
                                                mono_lib_names,
                                                prefix='lib',
                                                extension=sharedlib_ext)

                if not mono_so_name:
                    raise RuntimeError(
                        'Could not find mono shared library in: ' +
                        mono_lib_path)

                copy_file_no_replace(mono_lib_path, 'bin',
                                     'lib' + mono_so_name + sharedlib_ext)
        else:
            if mono_static:
                raise RuntimeError(
                    'mono-static: Not supported with pkg-config. Specify a mono prefix manually'
                )

            env.ParseConfig('pkg-config monosgen-2 --cflags --libs')

            mono_lib_path = ''
            mono_so_name = ''

            tmpenv = Environment()
            tmpenv.ParseConfig('pkg-config monosgen-2 --libs-only-L')

            for hint_dir in tmpenv['LIBPATH']:
                name_found = find_file_in_dir(hint_dir,
                                              mono_lib_names,
                                              prefix='lib',
                                              extension=sharedlib_ext)
                if name_found:
                    mono_lib_path = hint_dir
                    mono_so_name = name_found
                    break

            if not mono_so_name:
                raise RuntimeError('Could not find mono shared library in: ' +
                                   str(tmpenv['LIBPATH']))

            copy_file_no_replace(mono_lib_path, 'bin',
                                 'lib' + mono_so_name + sharedlib_ext)

        env.Append(LINKFLAGS='-rdynamic')
Ejemplo n.º 26
0
    def __init__(self):

        #----------------------------------------------------------------------
        # Setup default environment, checking command line options

        env = Environment(ENV=os.environ, LIBPATH=[], LIBS=[])

        env['NS_ON_CYGWIN'] = False
        env['NS_ON_LINUX'] = False
        env['NS_ON_MAC'] = False
        env['NS_ON_WINDOWS'] = False

        # Check options
        env['NS_BUILD_STATIC'] = GetOption("build_static")
        env['NS_COMPILER'] = GetOption("compiler")
        env['NS_CONFIG_DEBUG'] = GetOption("config_debug")
        env['NS_DEBUG_BUILD'] = GetOption("debug_build")
        env['NS_DISABLE_64'] = GetOption("disable_64")
        env['NS_DISABLE_CUDA'] = not GetOption("enable_cuda")
        env['NS_DISABLE_LIBAO'] = GetOption("disable_libao")
        env['NS_DISABLE_LIBPORTAUDIO'] = GetOption("disable_libportaudio")
        env['NS_DISABLE_OPENMP'] = GetOption("disable_openmp")
        env['NS_DISABLE_PYTHON'] = GetOption("disable_python")
        env['NS_EXTRA_WARNINGS'] = GetOption("extra_warnings")

        # There was a bug in either openMP or matplotlib that caused
        # segmentation faults when used together, last tried in 2010.
        if "setup_builder.py" in COMMAND_LINE_TARGETS:
            env['NS_DISABLE_OPENMP'] = True

        env['NS_HAVE_BOOST'] = False
        env['NS_HAVE_CPP11'] = False
        env['NS_HAVE_CUDA'] = False
        env['NS_HAVE_LIBAO'] = False
        env['NS_HAVE_LIBPORTAUDIO'] = False
        env['NS_HAVE_OPENMP'] = False
        env['NS_HAVE_PYLAB_C_API'] = False
        env['NS_HAVE_PYTHON_H'] = False

        env['NSOUND_PLATFORM_OS'] = 'Unknown'

        # Boost header
        boost_prefix = GetOption("boost_prefix")

        if boost_prefix:
            if os.path.isdir(boost_prefix):
                env.AppendUnique(CPPPATH=[boost_prefix])

        #----------------------------------------------------------------------
        # Setup installer prefixes

        prefix = GetOption("prefix")

        if prefix is None:
            prefix = os.path.dirname(os.path.realpath(__file__))

        env['NS_BINDIR'] = os.path.join(prefix, "bin")
        env['NS_LIBDIR'] = os.path.join(prefix, "lib")

        #----------------------------------------------------------------------
        # Add local tools

        env.Tool('ImportPythonConfig')
        env.Tool('AcGenerateFile')

        if env['NS_COMPILER']:
            env['NS_COMPILER'] = env['NS_COMPILER'].lower()

            compiler = env['NS_COMPILER']

            if compiler in ['gcc', 'g++']:
                env.Tool(compiler)

            elif compiler in ['mingw']:
                env.Tool(compiler)

            elif compiler in ['clang', 'clang++']:
                env.Tool('g++')
                env['CXX'] = 'clang++'

        #----------------------------------------------------------------------
        # Supress command output?

        if not GetOption('verbose'):
            env['ARCOMSTR'] = "Archiving $TARGET"
            env['CCCOMSTR'] = "Compiling $SOURCE"
            env['CXXCOMSTR'] = env['CCCOMSTR']
            env['LINKCOMSTR'] = "Linking   $TARGET"
            env['PYTHONSETUPCOMSTR'] = "Building Python Extension with $SOURCE"
            env['RANLIBCOMSTR'] = "Indexing  $TARGET"
            env['SHCCCOMSTR'] = env['CCCOMSTR']
            env['SHCXXCOMSTR'] = env['CCCOMSTR']
            env['SHLINKCOMSTR'] = env['LINKCOMSTR']
            env['LDMODULECOMSTR'] = env['LINKCOMSTR']
            env['SWIGGENCOMSTR'] = "Generating SWIG interface $TARGET"

        else:
            print("")
            print("CXXFLAGS = %s" % env['CXXFLAGS'])
            print("LINKFLAGS = %s" % env['LINKFLAGS'])
            print("LIBPATH = %s" % env['LIBPATH'])
            print("LIBS = %s" % env['LIBS'])
            print("LINKFLAGS = %s" % env['LINKFLAGS'])
            print("")

        self.env = env
        self._orig_env = env

        #----------------------------------------------------------------------
        # Platform specific customization

        self._customize_environment()

        #----------------------------------------------------------------------
        # Insert python config into environment
        if self.env['HAVE_PYTHON_CONFIG']:

            cpppath = self.env['PYTHON_CONFIG']['CPPPATH']
            libpath = self.env['PYTHON_CONFIG']['LIBPATH']
            libs = self.env['PYTHON_CONFIG']['LIBS']

            self.env.AppendUnique(CPPPATH=cpppath, LIBPATH=libpath, LIBS=libs)

            self.add_to_rpath(libpath)

        SConfBase.__init__(self, env)
Ejemplo n.º 27
0
        env.AppendUnique(CPPPATH=[env['SPATIALITEDIR'] + '/include'])
        env.AppendUnique(LIBPATH=[env['SPATIALITEDIR'] + '/lib'])

    # other tools we need
    env.Require(['qtcore', 'qtgui', 'sqlitedb'])
    env.AppendLibrary('spatialite')
    env.AppendLibrary('geos')
    env.AppendLibrary('geos_c')
    env.AppendLibrary('proj')
    if (env['PLATFORM'] != 'posix'):
        env.AppendLibrary('iconv')
    if (env['PLATFORM'] == 'win32'):
        env.AppendLibrary('freexl')


env = Environment(tools=['default', 'doxygen'])

options = env.GlobalVariables()
options.AddVariables(
    PathVariable('SPATIALITEDIR', 'SpatiaLite installation root.', None))

env.Require(build_spatialdb)

sources = env.Split("""
   SpatiaLiteDB.cpp
""")

headers = env.Split("""
   SpatiaLiteDB.h
""")
Ejemplo n.º 28
0
# -- Target for calculating the time (.rpt)
# rpt = env.Time(asc)
t = env.Alias('time', env.Time('time.rpt', asc))

# -------------------- Simulation ------------------
# -- Constructor para generar simulacion: icarus Verilog
iverilog = Builder(action='iverilog -o $TARGET $SOURCES ',
                   suffix='.out',
                   src_suffix='.v')

vcd = Builder(action=' $SOURCE', suffix='.vcd', src_suffix='.out')

simenv = Environment(BUILDERS={
    'IVerilog': iverilog,
    'VCD': vcd
},
                     ENV=os.environ)

out = simenv.IVerilog(TARGET_SIM, src_sim)
vcd_file = simenv.VCD(SIMULNAME, out)

waves = simenv.Alias(
    'sim', vcd_file,
    'gtkwave ' + join(env['PROJECT_DIR'], "%s " % vcd_file[0]) +
    join(env['PROJECTSRC_DIR'], SIMULNAME) + '.gtkw')
AlwaysBuild(waves)

Default([binf])

# -- These is for cleaning the files generated using the alias targets
Ejemplo n.º 29
0
def autobuild_shiparchive(src_file):
    """Create a ship file archive containing a yaml_file and its dependencies.

    If yaml_file depends on any build products as external files, it must
    be a jinja2 template that references the file using the find_product
    filter so that we can figure out where those build products are going
    and create the right dependency graph.

    Args:
        src_file (str): The path to the input yaml file template.  This
            file path must end .yaml.tpl and is rendered into a .yaml
            file and then packaged into a .ship file along with any
            products that are referenced in it.
    """

    if not src_file.endswith('.tpl'):
        raise BuildError("You must pass a .tpl file to autobuild_shiparchive",
                         src_file=src_file)

    env = Environment(tools=[])

    family = ArchitectureGroup('module_settings.json')
    target = family.platform_independent_target()
    resolver = ProductResolver.Create()

    #Parse through build_step products to see what needs to imported
    custom_steps = []
    for build_step in family.tile.find_products('build_step'):
        full_file_name = build_step.split(":")[0]
        basename = os.path.splitext(os.path.basename(full_file_name))[0]
        folder = os.path.dirname(full_file_name)

        fileobj, pathname, description = imp.find_module(basename, [folder])
        mod = imp.load_module(basename, fileobj, pathname, description)
        full_file_name, class_name = build_step.split(":")
        custom_steps.append((class_name, getattr(mod, class_name)))
    env['CUSTOM_STEPS'] = custom_steps

    env["RESOLVER"] = resolver

    base_name, tpl_name = _find_basename(src_file)
    yaml_name = tpl_name[:-4]
    ship_name = yaml_name[:-5] + ".ship"

    output_dir = target.build_dirs()['output']
    build_dir = os.path.join(target.build_dirs()['build'], base_name)
    tpl_path = os.path.join(build_dir, tpl_name)
    yaml_path = os.path.join(build_dir, yaml_name)
    ship_path = os.path.join(build_dir, ship_name)
    output_path = os.path.join(output_dir, ship_name)

    # We want to build up all related files in
    # <build_dir>/<ship archive_folder>/
    # - First copy the template yaml over
    # - Then render the template yaml
    # - Then find all products referenced in the template yaml and copy them
    # - over
    # - Then build a .ship archive
    # - Then copy that archive into output_dir

    ship_deps = [yaml_path]

    env.Command([tpl_path], [src_file], Copy("$TARGET", "$SOURCE"))

    prod_deps = _find_product_dependencies(src_file, resolver)

    env.Command([yaml_path], [tpl_path],
                action=Action(template_shipfile_action, "Rendering $TARGET"))

    for prod in prod_deps:
        dest_file = os.path.join(build_dir, prod.short_name)
        ship_deps.append(dest_file)
        env.Command([dest_file], [prod.full_path], Copy("$TARGET", "$SOURCE"))

    env.Command([ship_path], [ship_deps],
                action=Action(create_shipfile,
                              "Archiving Ship Recipe $TARGET"))
    env.Command([output_path], [ship_path], Copy("$TARGET", "$SOURCE"))
Ejemplo n.º 30
0
def getEnvironment(defaultDebug: bool = True,
                   libraries: bool = True,
                   stdlib: str = "c++17",
                   useSan=True,
                   customVariables=None):
    variables = Script.Variables()
    variables.AddVariables(
        BoolVariable(
            "debug",
            "Build with the debug flag and reduced optimization. `export LUNASCONS_DEBUG=true` to default debug to true",
            os.getenv("LUNASCONS_DEBUG",
                      "False").lower() in ["true", "1", "yes"]),
        BoolVariable("systemCompiler",
                     "Whether to use CXX/CC from the environment variables.",
                     True),
        ("profile", "Which profile to use for Conan, if Conan is enabled",
         "default"), ("settings", "Settings for Conan.", None),
        ("options", "Options for Conan", None),
        ("buildDir",
         "Build directory. Defaults to build/. This variable CANNOT be empty",
         "build/"),
        ("dynamic",
         "(Windows only!) Whether to use /MT or /MD. False for MT, true for MD",
         False), BoolVariable("coverage", "Adds the --coverage option", False))

    if (customVariables != None):
        if (type(customVariables) is not list):
            raise RuntimeError("customVariables has to be a list")
        for variable in customVariables:
            variables.Add(variable)

    envVars = {"PATH": os.environ["PATH"]}
    if "TEMP" in os.environ:
        envVars["TEMP"] = os.environ["TEMP"]

    tools = []
    if "windows" in platform.platform().lower():
        if "CXX" in os.environ and os.environ["CXX"] in ["clang++", "g++"]:
            tools.append("mingw")  # Preliminary MinGW mitigation
        else:
            tools = None
    else:
        tools = None
    env = Environment(variables=variables, ENV=envVars, tools=tools)

    (compiler, argType) = getCompiler(env)
    print("Detected compiler: {}. Running debug: {}".format(
        compiler, env["debug"]))

    if "TERM" in os.environ:
        env["ENV"]["TERM"] = os.environ["TERM"]

    if (env["PLATFORM"] == "win32" and compiler != "clang-cl"
            and compiler != "msvc"):
        print("Forcing MinGW mode")
        # We also need to normalize the compiler afterwards.
        # MinGW forces GCC
        CXX = env["CXX"]
        CC = env["CC"]
        Tool("mingw")(env)
        env["CXX"] = CXX
        env["CC"] = CC

    path = env["buildDir"]
    if (path == ""):
        raise RuntimeError("buildDir cannot be empty.")
    print("Building in {}".format(path))

    compileFlags = ""

    if (argType == ZEnvFile.CompilerType.POSIX):
        compileFlags += "-std=" + stdlib + " -pedantic -Wall -Wextra -Wno-c++11-narrowing"
        if env["debug"] == True:
            compileFlags += " -g -O0 "
            if env["coverage"] == True:
                compileFlags += " --coverage "
                env.Append(LINKFLAGS=["--coverage"])

        else:
            compileFlags += " -O3 "
    else:
        # Note to self: /W4 and /Wall spews out warnings for dependencies. Roughly equivalent to -Wall -Wextra on stereoids
        compileFlags += "/std:" + stdlib + " /W3 /EHsc /FS "
        if env["debug"] == True:
            env.Append(LINKFLAGS=["/DEBUG"])
            env.Append(
                CXXFLAGS=["/MTd" if not env["dynamic"] else "MDd", "/Zi"])
        else:
            compileFlags += " /O2 " + ("/MT"
                                       if not env["dynamic"] else "/MD") + " "
    env.Append(CXXFLAGS=compileFlags.split(" "))

    zEnv = ZEnvFile.ZEnv(env, path, env["debug"], compiler, argType, variables)
    if env["debug"] == True and useSan:
        if argType == ZEnvFile.CompilerType.POSIX:
            zEnv.environment.Append(CXXFLAGS=["-fsanitize=undefined"])

        if env["PLATFORM"] != "win32":
            zEnv.environment.Append(LINKFLAGS=["-fsanitize=undefined"])
        elif (compiler != "msvc"):
            print(
                "WARNING: Windows detected. MinGW doesn't have libubsan. Using crash instead (-fsanitize-undefined-trap-on-error)"
            )
            zEnv.environment.Append(
                CXXFLAGS=["-fsanitize-undefined-trap-on-error"])
    return zEnv