source: rtems_waf/rtems.py @ c0d52d5

Last change on this file since c0d52d5 was c0d52d5, checked in by Chris Johns <chrisj@…>, on 08/12/18 at 01:57:31

Change RTEMS path check from bin to share/rtems<version>.

There is no bin directory anymore with RTEMS 5 so the test fails. Check
for the share/rtems<version> directory.

Closes #3500.

  • Property mode set to 100644
File size: 29.8 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    env = None
93    contexts = []
94    try:
95        import waflib.Options
96        import waflib.ConfigSet
97
98        #
99        # Load the configuation set from the lock file.
100        #
101        env = waflib.ConfigSet.ConfigSet()
102        env.load(waflib.Options.lockfile)
103
104        #
105        # Check the tools, architectures and bsps.
106        #
107        rtems_version, rtems_path, rtems_tools, archs, arch_bsps = \
108            check_options(ctx,
109                          env.options['prefix'],
110                          env.options['rtems_tools'],
111                          env.options['rtems_path'],
112                          env.options['rtems_version'],
113                          env.options['rtems_archs'],
114                          env.options['rtems_bsps'])
115
116        #
117        # Update the contexts for all the bsps.
118        #
119        from waflib.Build import BuildContext, CleanContext, \
120            InstallContext, UninstallContext
121        for x in arch_bsps:
122            for y in (BuildContext, CleanContext, InstallContext, UninstallContext):
123                name = y.__name__.replace('Context','').lower()
124                class context(y):
125                    cmd = name + '-' + x
126                    variant = x
127                contexts += [context]
128
129        #
130        # Transform the command to per BSP commands.
131        #
132        commands = []
133        for cmd in waflib.Options.commands:
134            if cmd in ['build', 'clean', 'install']:
135                for x in arch_bsps:
136                    commands += [cmd + '-' + x]
137            else:
138                commands += [cmd]
139        waflib.Options.commands = commands
140    except:
141        pass
142
143    if bsp_init:
144        bsp_init(ctx, env, contexts)
145
146def configure(conf, bsp_configure = None):
147    #
148    # Check the environment for any flags.
149    #
150    for f in ['CC', 'CXX', 'AS', 'LD', 'AR', 'LINK_CC', 'LINK_CXX',
151              'CPPFLAGS', 'CFLAGS', 'CXXFLAGS', 'ASFLAGS', 'LINKFLAGS', 'LIB'
152              'WFLAGS', 'RFLAGS', 'MFLAGS', 'IFLAGS']:
153        if f in os.environ:
154            conf.msg('Environment variable set', f, color = 'RED')
155
156    #
157    # Handle the configurable commands options.
158    #
159    if conf.options.show_commands:
160        show_commands = 'yes'
161    else:
162        show_commands = 'no'
163    if rtems_long_commands and windows:
164        long_commands = 'yes'
165    else:
166        long_commands = 'no'
167
168    rtems_version, rtems_path, rtems_tools, archs, arch_bsps = \
169        check_options(conf,
170                      conf.options.prefix,
171                      conf.options.rtems_tools,
172                      conf.options.rtems_path,
173                      conf.options.rtems_version,
174                      conf.options.rtems_archs,
175                      conf.options.rtems_bsps)
176
177    if rtems_tools is None:
178        conf.fatal('RTEMS tools not found.')
179
180    _log_header(conf)
181
182    conf.msg('RTEMS Version', rtems_version, 'YELLOW')
183    conf.msg('Architectures', ', '.join(archs), 'YELLOW')
184
185    tools = {}
186    env = conf.env.derive()
187
188    for ab in arch_bsps:
189        conf.setenv(ab, env)
190
191        conf.msg('Board Support Package', ab, 'YELLOW')
192
193        #
194        # Show and long commands support.
195        #
196        conf.env.SHOW_COMMANDS = show_commands
197        conf.env.LONG_COMMANDS = long_commands
198
199        conf.msg('Show commands', show_commands)
200        conf.msg('Long commands', long_commands)
201
202        arch = _arch_from_arch_bsp(ab)
203        bsp  = _bsp_from_arch_bsp(ab)
204
205        conf.env.ARCH_BSP = '%s/%s' % (arch.split('-')[0], bsp)
206
207        conf.env.RTEMS_PATH = rtems_path
208        conf.env.RTEMS_VERSION = rtems_version
209        conf.env.RTEMS_ARCH_BSP = ab
210        conf.env.RTEMS_ARCH = arch.split('-')[0]
211        conf.env.RTEMS_ARCH_RTEMS = arch
212        conf.env.RTEMS_BSP = bsp
213
214        tools = _find_tools(conf, arch, rtems_tools, tools)
215        for t in tools[arch]:
216            conf.env[t] = tools[arch][t]
217
218        conf.load('gcc')
219        conf.load('g++')
220        conf.load('gas')
221
222        #
223        # Get the version of the tools being used.
224        #
225        rtems_cc = conf.env.CC[0]
226        try:
227            import waflib.Context
228            out = conf.cmd_and_log([rtems_cc, '--version'],
229                                   output = waflib.Context.STDOUT)
230        except Exception as e:
231            conf.fatal('CC version not found: %s' % (e.stderr))
232        #
233        # First line is the version
234        #
235        vline = out.split('\n')[0]
236        conf.msg('Compiler version (%s)' % (os.path.basename(rtems_cc)),
237                                            ' '.join(vline.split()[2:]))
238
239        flags = _load_flags(conf, ab, rtems_path)
240
241        cflags = _filter_flags('cflags', flags['CFLAGS'],
242                               arch, rtems_path)
243        ldflags = _filter_flags('ldflags', flags['LDFLAGS'],
244                               arch, rtems_path)
245
246        conf.env.CFLAGS    = cflags['cflags']
247        conf.env.CXXFLAGS  = cflags['cflags']
248        conf.env.ASFLAGS   = cflags['cflags']
249        conf.env.WFLAGS    = cflags['warnings']
250        conf.env.RFLAGS    = cflags['specs']
251        conf.env.MFLAGS    = cflags['machines']
252        conf.env.IFLAGS    = cflags['includes']
253        conf.env.LINKFLAGS = cflags['cflags'] + ldflags['ldflags']
254        conf.env.LIB       = flags['LIB']
255        conf.env.LIBPATH   = ldflags['libpath']
256
257        conf.env.RTRACE_WRAPPER_ST = '-W %s'
258
259        #
260        # Checks for various RTEMS features.
261        #
262        conf.multicheck({ 'header_name': 'rtems/score/cpuopts.h'},
263                        msg = 'Checking for RTEMS CPU options header',
264                        mandatory = True)
265        load_cpuopts(conf, ab, rtems_path)
266        conf.multicheck({ 'header_name': 'rtems.h'},
267                        msg = 'Checking for RTEMS header',
268                        mandatory = True)
269
270        #
271        # Add tweaks.
272        #
273        tweaks(conf, ab)
274
275        #
276        # If the user has supplied a BSP specific configure function
277        # call it.
278        #
279        if bsp_configure:
280            bsp_configure(conf, ab)
281
282        conf.setenv('', env)
283
284    conf.env.RTEMS_TOOLS = rtems_tools
285    conf.env.ARCHS = archs
286    conf.env.ARCH_BSPS = arch_bsps
287
288    conf.env.SHOW_COMMANDS = show_commands
289    conf.env.LONG_COMMANDS = long_commands
290
291def build(bld):
292    if bld.env.SHOW_COMMANDS == 'yes':
293        output_command_line()
294    if bld.env.LONG_COMMANDS == 'yes':
295        long_command_line()
296
297def load_cpuopts(conf, arch_bsp, rtems_path):
298    options = ['RTEMS_DEBUG',
299               'RTEMS_MULTIPROCESSING',
300               'RTEMS_NEWLIB',
301               'RTEMS_POSIX_API',
302               'RTEMS_SMP',
303               'RTEMS_NETWORKING']
304    for opt in options:
305        enabled = check_opt(conf, opt, 'rtems/score/cpuopts.h', arch_bsp, rtems_path)
306        if enabled:
307            conf.env[opt] = 'Yes'
308        else:
309            conf.env[opt] = 'No'
310
311def check_opt(conf, opt, header, arch_bsp, rtems_path):
312    code  = '#include <%s>%s' % (header, os.linesep)
313    code += '#ifndef %s%s' % (opt, os.linesep)
314    code += ' #error %s is not defined%s' % (opt, os.linesep)
315    code += '#endif%s' % (os.linesep)
316    code += '#if %s%s' % (opt, os.linesep)
317    code += ' /* %s is true */%s' % (opt, os.linesep)
318    code += '#else%s' % (os.linesep)
319    code += ' #error %s is false%s' % (opt, os.linesep)
320    code += '#endif%s' % (os.linesep)
321    code += 'int main() { return 0; }%s' % (os.linesep)
322    try:
323        conf.check_cc(fragment = code,
324                      execute = False,
325                      define_ret = False,
326                      msg = 'Checking for %s' % (opt))
327    except conf.errors.WafError:
328        return False;
329    return True
330
331def tweaks(conf, arch_bsp):
332    #
333    # Hack to work around NIOS2 naming.
334    #
335    if conf.env.RTEMS_ARCH in ['nios2']:
336        conf.env.OBJCOPY_FLAGS = ['-O', 'elf32-littlenios2']
337    elif conf.env.RTEMS_ARCH in ['arm']:
338        conf.env.OBJCOPY_FLAGS = ['-I', 'binary', '-O', 'elf32-littlearm']
339    else:
340        conf.env.OBJCOPY_FLAGS = ['-O', 'elf32-' + conf.env.RTEMS_ARCH]
341
342    #
343    # Check for a i386 PC bsp.
344    #
345    if re.match('i386-.*-pc[3456]86', arch_bsp) is not None:
346        conf.env.LINKFLAGS += ['-Wl,-Ttext,0x00100000']
347
348    if '-ffunction-sections' in conf.env.CFLAGS:
349      conf.env.LINKFLAGS += ['-Wl,--gc-sections']
350
351def check_options(ctx, prefix, rtems_tools, rtems_path, rtems_version, rtems_archs, rtems_bsps):
352    #
353    # Set defaults
354    #
355    if rtems_version is None:
356        if rtems_default_version is None:
357            m = re.compile('[^0-9.]*([0-9.]+)$').match(prefix)
358            if m:
359                rtems_version = m.group(1)
360            else:
361                ctx.fatal('RTEMS version cannot derived from prefix: ' + prefix)
362        else:
363            rtems_version = rtems_default_version
364    if rtems_path is None:
365        rtems_path = prefix
366    if rtems_tools is None:
367        rtems_tools = rtems_path
368
369    #
370    # Check the paths are valid.
371    #
372    if not os.path.exists(rtems_path):
373        ctx.fatal('RTEMS path not found.')
374    if os.path.exists(os.path.join(rtems_path, 'lib', 'pkgconfig')):
375        rtems_config = None
376    elif os.path.exists(os.path.join(rtems_path, 'rtems-config')):
377        rtems_config = os.path.join(rtems_path, 'rtems-config')
378    else:
379        ctx.fatal('RTEMS path is not valid. No lib/pkgconfig or rtems-config found.')
380    rtems_share_rtems_version = os.path.join(rtems_path, 'share', 'rtems' + rtems_version)
381    if not os.path.exists(os.path.join(rtems_share_rtems_version)):
382        ctx.fatal('RTEMS path is not valid, "%s" not found.' % (rtems_share_rtems_version))
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, 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        if not isinstance(kw['cwd'], str):
582            kw['cwd'] = str(kw['cwd'])
583        Logs.debug('runner_env: kw=%s' % kw)
584        try:
585            if self.logger:
586                self.logger.info(cmd)
587                kw['stdout'] = kw['stderr'] = subprocess.PIPE
588                p = subprocess.Popen(cmd, **kw)
589                (out, err) = p.communicate()
590                if out:
591                    self.logger.debug('out: %s' % out.decode(sys.stdout.encoding or 'iso8859-1'))
592                if err:
593                    self.logger.error('err: %s' % err.decode(sys.stdout.encoding or 'iso8859-1'))
594                return p.returncode
595            else:
596                p = subprocess.Popen(cmd, **kw)
597                return p.wait()
598        except OSError:
599            return -1
600    Context.exec_command = exec_command
601
602    # Change the outputs for tasks too
603    from waflib.Task import Task
604    def display(self):
605        return '' # no output on empty strings
606
607    Task.__str__ = display
608
609#
610# From the extras. Use this to support long command lines.
611#
612def long_command_line():
613    def exec_command(self, cmd, **kw):
614        # workaround for command line length limit:
615        # http://support.microsoft.com/kb/830473
616        import tempfile
617        tmp = None
618        try:
619            if not isinstance(cmd, str) and len(str(cmd)) > 8192:
620                (fd, tmp) = tempfile.mkstemp(dir=self.generator.bld.bldnode.abspath())
621                flat = ['"%s"' % x.replace('\\', '\\\\').replace('"', '\\"') for x in cmd[1:]]
622                try:
623                    os.write(fd, ' '.join(flat).encode())
624                finally:
625                    if tmp:
626                        os.close(fd)
627                # Line may be very long:
628                # Logs.debug('runner:' + ' '.join(flat))
629                cmd = [cmd[0], '@' + tmp]
630            ret = super(self.__class__, self).exec_command(cmd, **kw)
631        finally:
632            if tmp:
633                os.remove(tmp)
634        return ret
635    for k in 'c cxx cprogram cxxprogram cshlib cxxshlib cstlib cxxstlib'.split():
636        cls = Task.classes.get(k)
637        if cls:
638            derived_class = type(k, (cls,), {})
639            derived_class.exec_command = exec_command
640            if hasattr(cls, 'hcode'):
641                derived_class.hcode = cls.hcode
642
643def _find_tools(conf, arch, paths, tools):
644    if arch not in tools:
645        arch_tools = {}
646        arch_tools['CC']          = conf.find_program([arch + '-gcc'], path_list = paths)
647        arch_tools['CXX']         = conf.find_program([arch + '-g++'], path_list = paths)
648        arch_tools['LINK_CC']     = arch_tools['CC']
649        arch_tools['LINK_CXX']    = arch_tools['CXX']
650        arch_tools['AS']          = conf.find_program([arch + '-gcc'], path_list = paths)
651        arch_tools['LD']          = conf.find_program([arch + '-ld'],  path_list = paths)
652        arch_tools['AR']          = conf.find_program([arch + '-ar'], path_list = paths)
653        arch_tools['NM']          = conf.find_program([arch + '-nm'], path_list = paths)
654        arch_tools['OBJDUMP']     = conf.find_program([arch + '-objdump'], path_list = paths)
655        arch_tools['OBJCOPY']     = conf.find_program([arch + '-objcopy'], path_list = paths)
656        arch_tools['READELF']     = conf.find_program([arch + '-readelf'], path_list = paths)
657        arch_tools['STRIP']       = conf.find_program([arch + '-strip'], path_list = paths)
658        arch_tools['RTEMS_LD']    = conf.find_program(['rtems-ld'], path_list = paths,
659                                                      mandatory = False)
660        arch_tools['RTEMS_TLD']   = conf.find_program(['rtems-tld'], path_list = paths,
661                                                      mandatory = False)
662        arch_tools['RTEMS_BIN2C'] = conf.find_program(['rtems-bin2c'], path_list = paths,
663                                                      mandatory = False)
664        arch_tools['TAR']         = conf.find_program(['tar'], mandatory = False)
665        tools[arch] = arch_tools
666    return tools
667
668def _find_installed_archs(config, path, version):
669    archs = []
670    if config is None:
671        for d in os.listdir(path):
672            if d.endswith('-rtems' + version):
673                archs += [d]
674    else:
675        a = subprocess.check_output([config, '--list-format', '"%(arch)s"'])
676        a = a[:-1].replace('"', '')
677        archs = set(a.split())
678        archs = ['%s-rtems%s' % (x, version) for x in archs]
679    archs.sort()
680    return archs
681
682def _check_archs(config, req, path, version):
683    installed = _find_installed_archs(config, path, version)
684    archs = []
685    for a in req.split(','):
686        arch = a + '-rtems' + version
687        if arch in installed:
688            archs += [arch]
689    archs.sort()
690    return archs
691
692def _find_installed_arch_bsps(config, path, archs, version):
693    arch_bsps = []
694    if config is None:
695        for f in os.listdir(_pkgconfig_path(path)):
696            if f.endswith('.pc'):
697                if _arch_from_arch_bsp(f[:-3]) in archs:
698                    arch_bsps += [f[:-3]]
699    else:
700        ab = subprocess.check_output([config, '--list-format'])
701        ab = ab[:-1].replace('"', '')
702        ab = ab.replace('/', '-rtems%s-' % (version))
703        arch_bsps = [x for x in set(ab.split())]
704    arch_bsps.sort()
705    return arch_bsps
706
707def _check_arch_bsps(req, config, path, archs, version):
708    archs_bsps = []
709    for ab in req.split(','):
710        abl = ab.split('/')
711        if len(abl) != 2:
712            return []
713        found = False
714        for arch in archs:
715            a = '%s-rtems%s' % (abl[0], version)
716            if a == arch:
717                found = True
718                break
719        if not found:
720            return []
721        archs_bsps += ['%s-%s' % (a, abl[1])]
722    if len(archs_bsps) == 0:
723        return []
724    installed = _find_installed_arch_bsps(config, path, archs, version)
725    bsps = []
726    for b in archs_bsps:
727        if b in installed:
728            bsps += [b]
729    bsps.sort()
730    return bsps
731
732def _arch_from_arch_bsp(arch_bsp):
733    return '-'.join(arch_bsp.split('-')[:2])
734
735def _bsp_from_arch_bsp(arch_bsp):
736    return '-'.join(arch_bsp.split('-')[2:])
737
738def _pkgconfig_path(path):
739    return os.path.join(path, 'lib', 'pkgconfig')
740
741def _load_flags(conf, arch_bsp, path):
742    if not os.path.exists(path):
743        ctx.fatal('RTEMS path not found.')
744    if os.path.exists(_pkgconfig_path(path)):
745        pc = os.path.join(_pkgconfig_path(path), arch_bsp + '.pc')
746        conf.to_log('Opening and load pkgconfig: ' + pc)
747        pkg = pkgconfig.package(pc)
748        config = None
749    elif os.path.exists(os.path.join(path, 'rtems-config')):
750        config = os.path.join(path, 'rtems-config')
751        pkg = None
752    flags = {}
753    _log_header(conf)
754    flags['CFLAGS'] = _load_flags_set('CFLAGS', arch_bsp, conf, config, pkg)
755    flags['LDFLAGS'] = _load_flags_set('LDFLAGS', arch_bsp, conf, config, pkg)
756    flags['LIB'] = _load_flags_set('LIB', arch_bsp, conf, config, pkg)
757    return flags
758
759def _load_flags_set(flags, arch_bsp, conf, config, pkg):
760    conf.to_log('%s ->' % flags)
761    if pkg is not None:
762        flagstr = ''
763        try:
764            flagstr = pkg.get(flags)
765        except pkgconfig.error as e:
766            conf.to_log('pkconfig warning: ' + e.msg)
767        conf.to_log('  ' + flagstr)
768    else:
769        flags_map = { 'CFLAGS': '--cflags',
770                      'LDFLAGS': '--ldflags',
771                      'LIB': '--libs' }
772        ab = arch_bsp.split('-')
773        #conf.check_cfg(path = config,
774        #               package = '',
775        #               uselib_store = 'rtems',
776        #               args = '--bsp %s/%s %s' % (ab[0], ab[2], flags_map[flags]))
777        #print conf.env
778        #print '%r' % conf
779        #flagstr = '-l -c'
780        flagstr = subprocess.check_output([config, '--bsp', '%s/%s' % (ab[0], ab[2]), flags_map[flags]])
781        #print flags, ">>>>", flagstr
782        if flags == 'CFLAGS':
783            flagstr += ' -DWAF_BUILD=1'
784        if flags == 'LIB':
785            flagstr = 'rtemscpu rtemsbsp c rtemscpu rtemsbsp'
786    return flagstr.split()
787
788def _filter_flags(label, flags, arch, rtems_path):
789
790    flag_groups = \
791        [ { 'key': 'warnings', 'path': False, 'flags': { '-W': 1 }, 'cflags': False, 'lflags': False },
792          { 'key': 'includes', 'path': True,  'flags': { '-I': 1, '-isystem': 2, '-sysroot': 2 } },
793          { 'key': 'libpath',  'path': True,  'flags': { '-L': 1 } },
794          { 'key': 'machines', 'path': True,  'flags': { '-O': 1, '-m': 1, '-f': 1 } },
795          { 'key': 'specs',    'path': True,  'flags': { '-q': 1, '-B': 2, '--specs': 2 } } ]
796
797    flags = _strip_cflags(flags)
798
799    _flags = { label: [] }
800    for fg in flag_groups:
801        _flags[fg['key']] = []
802
803    iflags = iter(flags)
804    for opt in iflags:
805        in_label = True
806        opts = []
807        for fg in flag_groups:
808            key = fg['key']
809            for flag in fg['flags']:
810                if opt.startswith(flag):
811                    opt_count = fg['flags'][flag]
812                    if opt_count > 1:
813                        if opt != flag:
814                            opt_count -= 1
815                            if fg['path'] and arch in opt:
816                                opt = '%s%s/%s' % (flag, rtems_path,
817                                                   opt[opt.find(arch):])
818                    opts += [opt]
819                    for c in range(1, opt_count):
820                        opt = next(iflags)
821                        if fg['path'] and arch in opt:
822                            opt = '%s%s/%s' % (f, rtems_path,
823                                               opt[opt.find(arch):])
824                        opts += [opt]
825                    _flags[key] += opts
826                    if label in fg and not fg[label]:
827                        in_label = False
828                    break
829            if in_label:
830                _flags[label] += opts
831    return _flags
832
833def _strip_cflags(cflags):
834    _cflags = []
835    for o in cflags:
836        if o.startswith('-O'):
837            pass
838        elif o.startswith('-g'):
839            pass
840        else:
841            _cflags += [o]
842    return _cflags
843
844def _log_header(conf):
845    conf.to_log('-----------------------------------------')
846
847from waflib import Task
848from waflib import TaskGen
849from waflib import Utils
850from waflib import Node
851from waflib.Tools.ccroot import link_task, USELIB_VARS
852
853USELIB_VARS['rap'] = set(['RTEMS_LINKFLAGS'])
854USELIB_VARS['rtrace'] = set(['RTRACE_FLAGS', 'RTRACE_CFG', 'RTRACE_WRAPPER', 'RTRACE_LINKCMDS'])
855
856class rap(link_task):
857    "Link object files into a RTEMS application"
858    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}'
859    ext_out = ['.rap']
860    vars    = ['RTEMS_LINKFLAGS', 'LINKDEPS']
861    inst_to = '${BINDIR}'
862
863class rtrace(link_task):
864    "Link object files into a RTEMS trace application"
865    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}'
866    ext_out = ['.texe']
867    vars    = ['RTRACE_FLAGS', 'RTRACE_CFG', 'RTRACE_WRAPER', 'RTRACE_LINKFLAGS', 'LINKDEPS']
868    inst_to = '${BINDIR}'
869    color = 'PINK'
Note: See TracBrowser for help on using the repository browser.