source: rtems_waf/rtems.py @ eb6ff97

Last change on this file since eb6ff97 was eb6ff97, checked in by Chris Johns <chrisj@…>, on 06/16/16 at 04:53:33

Fix the root_filesystem tar command on Windows.

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