source: rtems_waf/rtems.py @ 93e5545

Last change on this file since 93e5545 was 93e5545, checked in by Chris Johns <chrisj@…>, on 05/11/16 at 02:21:24

Pass through commands we do not expand.

  • Property mode set to 100644
File size: 27.0 KB
Line 
1#
2# Copyright 2012-2016 Chris Johns (chrisj@rtems.org)
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are met:
6
7# 1. Redistributions of source code must retain the above copyright notice, this
8# list of conditions and the following disclaimer.
9
10# 2. Redistributions in binary form must reproduce the above copyright notice,
11# this list of conditions and the following disclaimer in the documentation
12# and/or other materials provided with the distribution.
13
14# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
25#
26# RTEMS support for applications.
27#
28
29import copy
30import os
31import os.path
32from . import pkgconfig
33import re
34import subprocess
35
36rtems_default_version = None
37rtems_filters = None
38
39def options(opt):
40    opt.add_option('--rtems',
41                   default = None,
42                   dest = 'rtems_path',
43                   help = 'Path to an installed RTEMS (defaults to prefix).')
44    opt.add_option('--rtems-tools',
45                   default = None,
46                   dest = 'rtems_tools',
47                   help = 'Path to RTEMS tools (defaults to path to installed RTEMS).')
48    opt.add_option('--rtems-version',
49                   default = None,
50                   dest = 'rtems_version',
51                   help = 'RTEMS version (default is derived from prefix).')
52    opt.add_option('--rtems-archs',
53                   default = 'all',
54                   dest = 'rtems_archs',
55                   help = 'List of RTEMS architectures to build.')
56    opt.add_option('--rtems-bsps',
57                   default = 'all',
58                   dest = 'rtems_bsps',
59                   help = 'List of BSPs to build.')
60    opt.add_option('--show-commands',
61                   action = 'store_true',
62                   default = False,
63                   dest = 'show_commands',
64                   help = 'Print the commands as strings.')
65
66def init(ctx, filters = None, version = None):
67    global rtems_filters
68    global rtems_default_version
69
70    #
71    # Set the RTEMS filter to the context.
72    #
73    rtems_filters = filters
74
75    #
76    # Set the default version, can be overridden.
77    #
78    rtems_default_version = version
79
80    try:
81        import waflib.Options
82        import waflib.ConfigSet
83
84        #
85        # Load the configuation set from the lock file.
86        #
87        env = waflib.ConfigSet.ConfigSet()
88        env.load(waflib.Options.lockfile)
89
90        #
91        # Check the tools, architectures and bsps.
92        #
93        rtems_version, rtems_path, rtems_bin, rtems_tools, archs, arch_bsps = \
94            check_options(ctx,
95                          env.options['prefix'],
96                          env.options['rtems_tools'],
97                          env.options['rtems_path'],
98                          env.options['rtems_version'],
99                          env.options['rtems_archs'],
100                          env.options['rtems_bsps'])
101
102        #
103        # Update the contextes for all the bsps.
104        #
105        from waflib.Build import BuildContext, CleanContext, \
106            InstallContext, UninstallContext
107        for x in arch_bsps:
108            for y in (BuildContext, CleanContext, InstallContext, UninstallContext):
109                name = y.__name__.replace('Context','').lower()
110                class context(y):
111                    cmd = name + '-' + x
112                    variant = x
113
114        #
115        # Transform the command to per BSP commands.
116        #
117        commands = []
118        for cmd in waflib.Options.commands:
119            if cmd in ['build', 'clean', 'install']:
120                for x in arch_bsps:
121                    commands += [cmd + '-' + x]
122            else:
123                commands += [cmd]
124        waflib.Options.commands = commands
125    except:
126        pass
127
128def configure(conf, bsp_configure = None):
129    #
130    # Check the environment for any flags.
131    #
132    for f in ['CC', 'CXX', 'AS', 'LD', 'AR', 'LINK_CC', 'LINK_CXX',
133              'CPPFLAGS', 'CFLAGS', 'CXXFLAGS', 'ASFLAGS', 'LINKFLAGS', 'LIB'
134              'WFLAGS', 'RFLAGS', 'MFLAGS', 'IFLAGS']:
135        if f in os.environ:
136            conf.msg('Environment variable set', f, color = 'RED')
137
138    #
139    # Handle the show commands option.
140    #
141    if conf.options.show_commands:
142        show_commands = 'yes'
143    else:
144        show_commands = 'no'
145
146    rtems_version, rtems_path, rtems_bin, rtems_tools, archs, arch_bsps = \
147        check_options(conf,
148                      conf.options.prefix,
149                      conf.options.rtems_tools,
150                      conf.options.rtems_path,
151                      conf.options.rtems_version,
152                      conf.options.rtems_archs,
153                      conf.options.rtems_bsps)
154
155    if rtems_tools is None:
156        conf.fatal('RTEMS tools not found.')
157
158    _log_header(conf)
159
160    conf.msg('RTEMS Version', rtems_version, 'YELLOW')
161    conf.msg('Architectures', ', '.join(archs), 'YELLOW')
162
163    tools = {}
164    env = conf.env.derive()
165
166    for ab in arch_bsps:
167        conf.setenv(ab, env)
168
169        conf.msg('Board Support Package', ab, 'YELLOW')
170
171        arch = _arch_from_arch_bsp(ab)
172        bsp  = _bsp_from_arch_bsp(ab)
173
174        conf.env.ARCH_BSP = '%s/%s' % (arch.split('-')[0], bsp)
175
176        conf.env.RTEMS_PATH = rtems_path
177        conf.env.RTEMS_VERSION = rtems_version
178        conf.env.RTEMS_ARCH_BSP = ab
179        conf.env.RTEMS_ARCH = arch.split('-')[0]
180        conf.env.RTEMS_ARCH_RTEMS = arch
181        conf.env.RTEMS_BSP = bsp
182
183        tools = _find_tools(conf, arch, [rtems_bin] + rtems_tools, tools)
184        for t in tools[arch]:
185            conf.env[t] = tools[arch][t]
186
187        conf.load('gcc')
188        conf.load('g++')
189        conf.load('gas')
190
191        #
192        # Get the version of the tools being used.
193        #
194        rtems_cc = conf.env.CC[0]
195        try:
196            import waflib.Context
197            out = conf.cmd_and_log([rtems_cc, '--version'],
198                                   output = waflib.Context.STDOUT)
199        except Exception as e:
200            conf.fatal('CC version not found: %s' % (e.stderr))
201        #
202        # First line is the version
203        #
204        vline = out.split('\n')[0]
205        conf.msg('Compiler version (%s)' % (os.path.basename(rtems_cc)),
206                                            ' '.join(vline.split()[2:]))
207
208        flags = _load_flags(conf, ab, rtems_path)
209
210        cflags = _filter_flags('cflags', flags['CFLAGS'],
211                               arch, rtems_path)
212        ldflags = _filter_flags('ldflags', flags['LDFLAGS'],
213                               arch, rtems_path)
214
215        conf.env.CFLAGS    = cflags['cflags']
216        conf.env.CXXFLAGS  = conf.env.CFLAGS
217        conf.env.ASFLAGS   = cflags['cflags']
218        conf.env.WFLAGS    = cflags['warnings']
219        conf.env.RFLAGS    = cflags['specs']
220        conf.env.MFLAGS    = cflags['machines']
221        conf.env.IFLAGS    = cflags['includes']
222        conf.env.LINKFLAGS = cflags['cflags'] + ldflags['ldflags']
223        conf.env.LIB       = flags['LIB']
224
225        conf.env.RTRACE_WRAPPER_ST = '-W %s'
226
227        #
228        # Checks for various RTEMS features.
229        #
230        conf.multicheck({ 'header_name': 'rtems/score/cpuopts.h'},
231                        msg = 'Checking for RTEMS CPU options header',
232                        mandatory = True)
233        load_cpuopts(conf, ab, rtems_path)
234        if conf.env['RTEMS_SMP'] == 'Yes':
235            conf.env.CXXFLAGS += ['-std=gnu++11']
236        conf.multicheck({ 'header_name': 'rtems.h'},
237                        msg = 'Checking for RTEMS header',
238                        mandatory = True)
239
240        #
241        # Add tweaks.
242        #
243        tweaks(conf, ab)
244
245        #
246        # If the user has supplied a BSP specific configure function
247        # call it.
248        #
249        if bsp_configure:
250            bsp_configure(conf, ab)
251
252        #
253        # Show commands support the user can supply.
254        #
255        conf.env.SHOW_COMMANDS = show_commands
256
257        conf.setenv('', env)
258
259    conf.env.RTEMS_TOOLS = rtems_tools
260    conf.env.ARCHS = archs
261    conf.env.ARCH_BSPS = arch_bsps
262
263    conf.env.SHOW_COMMANDS = show_commands
264
265def build(bld):
266    if bld.env.SHOW_COMMANDS == 'yes':
267        output_command_line()
268
269def load_cpuopts(conf, arch_bsp, rtems_path):
270    options = ['RTEMS_DEBUG',
271               'RTEMS_MULTIPROCESSING',
272               'RTEMS_NEWLIB',
273               'RTEMS_POSIX_API',
274               'RTEMS_SMP',
275               'RTEMS_NETWORKING']
276    for opt in options:
277        enabled = check_opt(conf, opt, 'rtems/score/cpuopts.h', arch_bsp, rtems_path)
278        if enabled:
279            conf.env[opt] = 'Yes'
280        else:
281            conf.env[opt] = 'No'
282
283def check_opt(conf, opt, header, arch_bsp, rtems_path):
284    code  = '#include <%s>%s' % (header, os.linesep)
285    code += '#ifndef %s%s' % (opt, os.linesep)
286    code += ' #error %s is not defined%s' % (opt, os.linesep)
287    code += '#endif%s' % (os.linesep)
288    code += '#if %s%s' % (opt, os.linesep)
289    code += ' /* %s is true */%s' % (opt, os.linesep)
290    code += '#else%s' % (os.linesep)
291    code += ' #error %s is false%s' % (opt, os.linesep)
292    code += '#endif%s' % (os.linesep)
293    code += 'int main() { return 0; }%s' % (os.linesep)
294    try:
295        conf.check_cc(fragment = code,
296                      execute = False,
297                      define_ret = False,
298                      msg = 'Checking for %s' % (opt))
299    except conf.errors.WafError:
300        return False;
301    return True
302
303def tweaks(conf, arch_bsp):
304    #
305    # Hack to work around NIOS2 naming.
306    #
307    if conf.env.RTEMS_ARCH in ['nios2']:
308        conf.env.OBJCOPY_FLAGS = ['-O', 'elf32-littlenios2']
309    elif conf.env.RTEMS_ARCH in ['arm']:
310        conf.env.OBJCOPY_FLAGS = ['-I', 'binary', '-O', 'elf32-littlearm']
311    else:
312        conf.env.OBJCOPY_FLAGS = ['-O', 'elf32-' + conf.env.RTEMS_ARCH]
313
314    #
315    # Check for a i386 PC bsp.
316    #
317    if re.match('i386-.*-pc[3456]86', arch_bsp) is not None:
318        conf.env.LINKFLAGS += ['-Wl,-Ttext,0x00100000']
319
320    if '-ffunction-sections' in conf.env.CFLAGS:
321      conf.env.LINKFLAGS += ['-Wl,--gc-sections']
322
323def check_options(ctx, prefix, rtems_tools, rtems_path, rtems_version, rtems_archs, rtems_bsps):
324    #
325    # Set defaults
326    #
327    if rtems_version is None:
328        if rtems_default_version is None:
329            m = re.compile('[^0-9.]*([0-9.]+)$').match(prefix)
330            if m:
331                rtems_version = m.group(1)
332            else:
333                ctx.fatal('RTEMS version cannot derived from prefix: ' + prefix)
334        else:
335            rtems_version = rtems_default_version
336    if rtems_path is None:
337        rtems_path = prefix
338    if rtems_tools is None:
339        rtems_tools = rtems_path
340
341    #
342    # Check the paths are valid.
343    #
344    if not os.path.exists(rtems_path):
345        ctx.fatal('RTEMS path not found.')
346    if os.path.exists(os.path.join(rtems_path, 'lib', 'pkgconfig')):
347        rtems_config = None
348    elif os.path.exists(os.path.join(rtems_path, 'rtems-config')):
349        rtems_config = os.path.join(rtems_path, 'rtems-config')
350    else:
351        ctx.fatal('RTEMS path is not valid. No lib/pkgconfig or rtems-config found.')
352    if os.path.exists(os.path.join(rtems_path, 'bin')):
353        rtems_bin = os.path.join(rtems_path, 'bin')
354    else:
355        ctx.fatal('RTEMS path is not valid. No bin directory found.')
356
357    #
358    # We can more than one path to tools. This happens when testing different
359    # versions.
360    #
361    rt = rtems_tools.split(',')
362    tools = []
363    for path in rt:
364        if not os.path.exists(path):
365            ctx.fatal('RTEMS tools path not found: ' + path)
366        if not os.path.exists(os.path.join(path, 'bin')):
367            ctx.fatal('RTEMS tools path does not contain a \'bin\' directory: ' + path)
368        tools += [os.path.join(path, 'bin')]
369
370    #
371    # Filter the tools.
372    #
373    tools = filter(ctx, 'tools', tools)
374
375    #
376    # Match the archs requested against the ones found. If the user
377    # wants all (default) set all used.
378    #
379    if rtems_archs == 'all':
380        archs = _find_installed_archs(rtems_config, rtems_path, rtems_version)
381    else:
382        archs = _check_archs(rtems_config, rtems_archs, rtems_path, rtems_version)
383
384    #
385    # Filter the architectures.
386    #
387    archs = filter(ctx, 'archs', archs)
388
389    #
390    # We some.
391    #
392    if len(archs) == 0:
393        ctx.fatal('Could not find any architectures')
394
395    #
396    # Get the list of valid BSPs. This process filters the architectures
397    # to those referenced by the BSPs.
398    #
399    if rtems_bsps == 'all':
400        arch_bsps = _find_installed_arch_bsps(rtems_config, rtems_path, archs, rtems_version)
401    else:
402        arch_bsps = _check_arch_bsps(rtems_bsps, rtems_config, rtems_path, archs, rtems_version)
403
404    if len(arch_bsps) == 0:
405        ctx.fatal('No valid arch/bsps found')
406
407    #
408    # Filter the bsps.
409    #
410    arch_bsps = filter(ctx, 'bsps', arch_bsps)
411
412    return rtems_version, rtems_path, rtems_bin, tools, archs, arch_bsps
413
414def check_env(ctx, var):
415    if var in ctx.env and len(ctx.env[var]) != 0:
416        return True
417    return False
418
419def check(ctx, option):
420    if option in ctx.env:
421        return ctx.env[option] == 'Yes'
422    return False
423
424def check_debug(ctx):
425    return check(ctx, 'RTEMS_DEBUG')
426
427def check_multiprocessing(ctx):
428    return check(ctx, 'RTEMS_MULTIPROCESSING')
429
430def check_newlib(ctx):
431    return check(ctx, 'RTEMS_NEWLIB')
432
433def check_posix(ctx):
434    return check(ctx, 'RTEMS_POSIX_API')
435
436def check_smp(ctx):
437    return check(ctx, 'RTEMS_SMP')
438
439def check_networking(ctx):
440    return check(ctx, 'RTEMS_NETWORKING')
441
442def arch(arch_bsp):
443    """ Given an arch/bsp return the architecture."""
444    return _arch_from_arch_bsp(arch_bsp).split('-')[0]
445
446def bsp(arch_bsp):
447    """ Given an arch/bsp return the BSP."""
448    return _bsp_from_arch_bsp(arch_bsp)
449
450def arch_bsps(ctx):
451    """ Return the list of arch/bsps we are building."""
452    return ctx.env.ARCH_BSPS
453
454def arch_bsp_env(ctx, arch_bsp):
455    return ctx.env_of_name(arch_bsp).derive()
456
457def filter(ctx, filter, items):
458    if rtems_filters is None:
459        return items
460    if type(rtems_filters) is not dict:
461        ctx.fatal("Invalid RTEMS filter type, " \
462                  "ie { 'tools': { 'in': [], 'out': [] }, 'arch': {}, 'bsps': {} }")
463    if filter not in rtems_filters:
464        return items
465    items_in = []
466    items_out = []
467    if 'in' in rtems_filters[filter]:
468        items_in = copy.copy(rtems_filters[filter]['in'])
469    if 'out' in rtems_filters[filter]:
470        items_out = copy.copy(rtems_filters[filter]['out'])
471    filtered_items = []
472    for i in items:
473        item = i
474        ab = '%s/%s' % (arch(item), bsp(item))
475        for inre in items_in:
476            if re.compile(inre).match(ab):
477                items_in.remove(inre)
478                filtered_items += [item]
479                item = None
480                break
481        if item is not None:
482            for outre in items_out:
483                if re.compile(outre).match(ab):
484                    item = None
485                    break
486        if item is not None:
487            filtered_items += [item]
488    if len(items_in) != 0:
489        ctx.fatal('Following %s not found: %s' % (filter, ', '.join(items_in)))
490    return sorted(filtered_items)
491
492def arch_rtems_version(version, arch):
493    """ Return the RTEMS architecture path, ie sparc-rtems4.11."""
494    return '%s-rtems%s' % (arch, version)
495
496def arch_bsp_path(version, arch_bsp):
497    """ Return the BSP path."""
498    return '%s/%s' % (arch_rtems_version(version, arch(arch_bsp)), bsp(arch_bsp))
499
500def arch_bsp_include_path(version, arch_bsp):
501    """ Return the BSP include path."""
502    return '%s/lib/include' % (arch_bsp_path(version, arch_bsp))
503
504def arch_bsp_lib_path(version, arch_bsp):
505    """ Return the BSP library path. """
506    return '%s/lib' % (arch_bsp_path(version, arch_bsp))
507
508def library_path(library, cc, cflags):
509    cmd = cc + cflags + ['-print-file-name=%s' % library]
510    a = subprocess.check_output(cmd)
511    lib = os.path.abspath(a.strip())
512    if os.path.exists(lib):
513        return os.path.dirname(lib)
514    return None
515
516def clone_tasks(bld):
517    if bld.cmd == 'build':
518        for obj in bld.all_task_gen[:]:
519            for x in arch_bsp:
520                cloned_obj = obj.clone(x)
521                kind = Options.options.build_kind
522                if kind.find(x) < 0:
523                    cloned_obj.posted = True
524            obj.posted = True
525
526#
527# From the demos. Use this to get the command to cut+paste to play.
528#
529def output_command_line():
530    # first, display strings, people like them
531    from waflib import Utils, Logs
532    from waflib.Context import Context
533    def exec_command(self, cmd, **kw):
534        subprocess = Utils.subprocess
535        kw['shell'] = isinstance(cmd, str)
536        if isinstance(cmd, str):
537            Logs.info('%s' % cmd)
538        else:
539            Logs.info('%s' % ' '.join(cmd)) # here is the change
540        Logs.debug('runner_env: kw=%s' % kw)
541        try:
542            if self.logger:
543                self.logger.info(cmd)
544                kw['stdout'] = kw['stderr'] = subprocess.PIPE
545                p = subprocess.Popen(cmd, **kw)
546                (out, err) = p.communicate()
547                if out:
548                    self.logger.debug('out: %s' % out.decode(sys.stdout.encoding or 'iso8859-1'))
549                if err:
550                    self.logger.error('err: %s' % err.decode(sys.stdout.encoding or 'iso8859-1'))
551                return p.returncode
552            else:
553                p = subprocess.Popen(cmd, **kw)
554                return p.wait()
555        except OSError:
556            return -1
557    Context.exec_command = exec_command
558
559    # Change the outputs for tasks too
560    from waflib.Task import Task
561    def display(self):
562        return '' # no output on empty strings
563
564    Task.__str__ = display
565
566def _find_tools(conf, arch, paths, tools):
567    if arch not in tools:
568        arch_tools = {}
569        arch_tools['CC']          = conf.find_program([arch + '-gcc'], path_list = paths)
570        arch_tools['CXX']         = conf.find_program([arch + '-g++'], path_list = paths)
571        arch_tools['LINK_CC']     = arch_tools['CC']
572        arch_tools['LINK_CXX']    = arch_tools['CXX']
573        arch_tools['AS']          = conf.find_program([arch + '-gcc'], path_list = paths)
574        arch_tools['LD']          = conf.find_program([arch + '-ld'],  path_list = paths)
575        arch_tools['AR']          = conf.find_program([arch + '-ar'], path_list = paths)
576        arch_tools['NM']          = conf.find_program([arch + '-nm'], path_list = paths)
577        arch_tools['OBJDUMP']     = conf.find_program([arch + '-objdump'], path_list = paths)
578        arch_tools['OBJCOPY']     = conf.find_program([arch + '-objcopy'], path_list = paths)
579        arch_tools['READELF']     = conf.find_program([arch + '-readelf'], path_list = paths)
580        arch_tools['STRIP']       = conf.find_program([arch + '-strip'], path_list = paths)
581        arch_tools['RTEMS_LD']    = conf.find_program(['rtems-ld'], path_list = paths,
582                                                      mandatory = False)
583        arch_tools['RTEMS_TLD']   = conf.find_program(['rtems-tld'], path_list = paths,
584                                                      mandatory = False)
585        arch_tools['RTEMS_BIN2C'] = conf.find_program(['rtems-bin2c'], path_list = paths,
586                                                      mandatory = False)
587        arch_tools['TAR']         = conf.find_program(['tar'], mandatory = False)
588        tools[arch] = arch_tools
589    return tools
590
591def _find_installed_archs(config, path, version):
592    archs = []
593    if config is None:
594        for d in os.listdir(path):
595            if d.endswith('-rtems' + version):
596                archs += [d]
597    else:
598        a = subprocess.check_output([config, '--list-format', '"%(arch)s"'])
599        a = a[:-1].replace('"', '')
600        archs = set(a.split())
601        archs = ['%s-rtems%s' % (x, version) for x in archs]
602    archs.sort()
603    return archs
604
605def _check_archs(config, req, path, version):
606    installed = _find_installed_archs(config, path, version)
607    archs = []
608    for a in req.split(','):
609        arch = a + '-rtems' + version
610        if arch in installed:
611            archs += [arch]
612    archs.sort()
613    return archs
614
615def _find_installed_arch_bsps(config, path, archs, version):
616    arch_bsps = []
617    if config is None:
618        for f in os.listdir(_pkgconfig_path(path)):
619            if f.endswith('.pc'):
620                if _arch_from_arch_bsp(f[:-3]) in archs:
621                    arch_bsps += [f[:-3]]
622    else:
623        ab = subprocess.check_output([config, '--list-format'])
624        ab = ab[:-1].replace('"', '')
625        ab = ab.replace('/', '-rtems%s-' % (version))
626        arch_bsps = [x for x in set(ab.split())]
627    arch_bsps.sort()
628    return arch_bsps
629
630def _check_arch_bsps(req, config, path, archs, version):
631    archs_bsps = []
632    for ab in req.split(','):
633        abl = ab.split('/')
634        if len(abl) != 2:
635            return []
636        found = False
637        for arch in archs:
638            a = '%s-rtems%s' % (abl[0], version)
639            if a == arch:
640                found = True
641                break
642        if not found:
643            return []
644        archs_bsps += ['%s-%s' % (a, abl[1])]
645    if len(archs_bsps) == 0:
646        return []
647    installed = _find_installed_arch_bsps(config, path, archs, version)
648    bsps = []
649    for b in archs_bsps:
650        if b in installed:
651            bsps += [b]
652    bsps.sort()
653    return bsps
654
655def _arch_from_arch_bsp(arch_bsp):
656    return '-'.join(arch_bsp.split('-')[:2])
657
658def _bsp_from_arch_bsp(arch_bsp):
659    return '-'.join(arch_bsp.split('-')[2:])
660
661def _pkgconfig_path(path):
662    return os.path.join(path, 'lib', 'pkgconfig')
663
664def _load_flags(conf, arch_bsp, path):
665    if not os.path.exists(path):
666        ctx.fatal('RTEMS path not found.')
667    if os.path.exists(_pkgconfig_path(path)):
668        pc = os.path.join(_pkgconfig_path(path), arch_bsp + '.pc')
669        conf.to_log('Opening and load pkgconfig: ' + pc)
670        pkg = pkgconfig.package(pc)
671        config = None
672    elif os.path.exists(os.path.join(path, 'rtems-config')):
673        config = os.path.join(path, 'rtems-config')
674        pkg = None
675    flags = {}
676    _log_header(conf)
677    flags['CFLAGS'] = _load_flags_set('CFLAGS', arch_bsp, conf, config, pkg)
678    flags['LDFLAGS'] = _load_flags_set('LDFLAGS', arch_bsp, conf, config, pkg)
679    flags['LIB'] = _load_flags_set('LIB', arch_bsp, conf, config, pkg)
680    return flags
681
682def _load_flags_set(flags, arch_bsp, conf, config, pkg):
683    conf.to_log('%s ->' % flags)
684    if pkg is not None:
685        flagstr = ''
686        try:
687            flagstr = pkg.get(flags)
688        except pkgconfig.error as e:
689            conf.to_log('pkconfig warning: ' + e.msg)
690        conf.to_log('  ' + flagstr)
691    else:
692        flags_map = { 'CFLAGS': '--cflags',
693                      'LDFLAGS': '--ldflags',
694                      'LIB': '--libs' }
695        ab = arch_bsp.split('-')
696        #conf.check_cfg(path = config,
697        #               package = '',
698        #               uselib_store = 'rtems',
699        #               args = '--bsp %s/%s %s' % (ab[0], ab[2], flags_map[flags]))
700        #print conf.env
701        #print '%r' % conf
702        #flagstr = '-l -c'
703        flagstr = subprocess.check_output([config, '--bsp', '%s/%s' % (ab[0], ab[2]), flags_map[flags]])
704        #print flags, ">>>>", flagstr
705        if flags == 'CFLAGS':
706            flagstr += ' -DWAF_BUILD=1'
707        if flags == 'LIB':
708            flagstr = 'rtemscpu rtemsbsp c rtemscpu rtemsbsp'
709    return flagstr.split()
710
711def _filter_flags(label, flags, arch, rtems_path):
712
713    flag_groups = \
714        [ { 'key': 'warnings', 'path': False, 'flags': { '-W': 1 }, 'cflags': False, 'lflags': False },
715          { 'key': 'includes', 'path': True,  'flags': { '-I': 1, '-isystem': 2, '-sysroot': 2 } },
716          { 'key': 'machines', 'path': True,  'flags': { '-O': 1, '-m': 1, '-f': 1 } },
717          { 'key': 'specs',    'path': True,  'flags': { '-q': 1, '-B': 2, '--specs': 2 } } ]
718
719    flags = _strip_cflags(flags)
720
721    _flags = { label: [] }
722    for fg in flag_groups:
723        _flags[fg['key']] = []
724
725    iflags = iter(flags)
726    for opt in iflags:
727        in_label = True
728        opts = []
729        for fg in flag_groups:
730            key = fg['key']
731            for flag in fg['flags']:
732                if opt.startswith(flag):
733                    opt_count = fg['flags'][flag]
734                    if opt_count > 1:
735                        if opt != flag:
736                            opt_count -= 1
737                            if fg['path'] and arch in opt:
738                                opt = '%s%s/%s' % (flag, rtems_path,
739                                                   opt[opt.find(arch):])
740                    opts += [opt]
741                    for c in range(1, opt_count):
742                        opt = next(iflags)
743                        if fg['path'] and arch in opt:
744                            opt = '%s%s/%s' % (f, rtems_path,
745                                               opt[opt.find(arch):])
746                        opts += [opt]
747                    _flags[key] += opts
748                    if label in fg and not fg[label]:
749                        in_label = False
750                    break
751            if in_label:
752                _flags[label] += opts
753    return _flags
754
755def _strip_cflags(cflags):
756    _cflags = []
757    for o in cflags:
758        if o.startswith('-O'):
759            pass
760        elif o.startswith('-g'):
761            pass
762        else:
763            _cflags += [o]
764    return _cflags
765
766def _log_header(conf):
767    conf.to_log('-----------------------------------------')
768
769from waflib import Task
770from waflib import TaskGen
771from waflib import Utils
772from waflib import Node
773from waflib.Tools.ccroot import link_task, USELIB_VARS
774
775USELIB_VARS['rap'] = set(['RTEMS_LINKFLAGS'])
776USELIB_VARS['rtrace'] = set(['RTRACE_FLAGS', 'RTRACE_CFG', 'RTRACE_WRAPPER', 'RTRACE_LINKCMDS'])
777
778class rap(link_task):
779    "Link object files into a RTEMS application"
780    run_str = '${RTEMS_LD} ${RTEMS_LINKFLAGS} --cc ${CC} ${SRC} -o ${TGT[0].abspath()} ${STLIB_MARKER} ${STLIBPATH_ST:STLIBPATH} ${STLIB_ST:STLIB} ${LIBPATH_ST:LIBPATH} ${LIB_ST:LIB}'
781    ext_out = ['.rap']
782    vars    = ['RTEMS_LINKFLAGS', 'LINKDEPS']
783    inst_to = '${BINDIR}'
784
785class rtrace(link_task):
786    "Link object files into a RTEMS trace application"
787    run_str = '${RTEMS_TLD} ${RTACE_FLAGS} ${RTRACE_WRAPPER_ST:RTRACE_WRAPPER} -C ${RTRACE_CFG} -r ${RTEMS_PATH} -B ${ARCH_BSP} -c ${CC} -l ${CC} -- ${SRC} ${LINKFLAGS} ${RTRACE_LINKFLAGS} -o ${TGT[0].abspath()} ${STLIB_MARKER} ${STLIBPATH_ST:STLIBPATH} ${STLIB_ST:STLIB} ${LIBPATH_ST:LIBPATH} ${LIB_ST:LIB}'
788    ext_out = ['.texe']
789    vars    = ['RTRACE_FLAGS', 'RTRACE_CFG', 'RTRACE_WRAPER', 'RTRACE_LINKFLAGS', 'LINKDEPS']
790    inst_to = '${BINDIR}'
791    color = 'PINK'
Note: See TracBrowser for help on using the repository browser.