source: rtems_waf/rtems.py @ 4ef2f41

Last change on this file since 4ef2f41 was 4ef2f41, checked in by Christian Mauderer <christian.mauderer@…>, on 04/06/18 at 06:54:34

Add bsp_init hook.

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