source: rtems-libbsd/waf_generator.py @ 269b559

55-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 269b559 was 32ceb14, checked in by Chris Johns <chrisj@…>, on 06/16/16 at 03:32:28

Add support for long command lines and fix some shell rules on Windows.

  • Property mode set to 100755
File size: 23.9 KB
Line 
1#
2#  Copyright (c) 2015-2016 Chris Johns <chrisj@rtems.org>. All rights reserved.
3#
4#  Copyright (c) 2009-2015 embedded brains GmbH.  All rights reserved.
5#
6#   embedded brains GmbH
7#   Dornierstr. 4
8#   82178 Puchheim
9#   Germany
10#   <info@embedded-brains.de>
11#
12#  Copyright (c) 2012 OAR Corporation. All rights reserved.
13#
14#  Redistribution and use in source and binary forms, with or without
15#  modification, are permitted provided that the following conditions
16#  are met:
17#  1. Redistributions of source code must retain the above copyright
18#     notice, this list of conditions and the following disclaimer.
19#  2. Redistributions in binary form must reproduce the above copyright
20#     notice, this list of conditions and the following disclaimer in the
21#     documentation and/or other materials provided with the distribution.
22#
23#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
35from __future__ import print_function
36
37import os
38import sys
39import tempfile
40
41import builder
42
43trace = False
44
45data = { }
46
47def _addFiles(name, files):
48    if type(files) is not list:
49        files = [files]
50    if name not in data:
51        data[name] = []
52    data[name] += files
53
54def _cflagsIncludes(cflags, includes):
55    if type(cflags) is not list:
56        if cflags is not None:
57            _cflags = cflags.split(' ')
58        else:
59            _cflags = [None]
60    else:
61        _cflags = cflags
62    if type(includes) is not list:
63        _includes = [includes]
64    else:
65        _includes = includes
66    return _cflags, _includes
67
68class SourceFileFragmentComposer(builder.BuildSystemFragmentComposer):
69
70    def __init__(self, cflags = "default", includes = None):
71        self.cflags, self.includes = _cflagsIncludes(cflags, includes)
72
73    def compose(self, path):
74        if None in self.includes:
75            return ['sources', self.cflags], [path], self.cflags, self.includes
76        return ['sources', self.cflags + self.includes], [path], self.cflags, self.includes
77
78class TestFragementComposer(builder.BuildSystemFragmentComposer):
79
80    def __init__(self, testName, fileFragments, runTest = True, netTest = False):
81        self.testName = testName
82        self.fileFragments = fileFragments
83        self.runTest = runTest
84        self.netTest = netTest
85
86    def compose(self, path):
87        return ['tests', self.testName], { 'files': self.fileFragments,
88                                           'run': self.runTest,
89                                           'net': self.netTest }
90
91class KVMSymbolsFragmentComposer(builder.BuildSystemFragmentComposer):
92
93    def compose(self, path):
94        return ['KVMSymbols', 'files'], [path], self.includes
95
96class RPCGENFragmentComposer(builder.BuildSystemFragmentComposer):
97
98    def compose(self, path):
99        return ['RPCGen', 'files'], [path]
100
101class RouteKeywordsFragmentComposer(builder.BuildSystemFragmentComposer):
102
103    def compose(self, path):
104        return ['RouteKeywords', 'files'], [path]
105
106class LexFragmentComposer(builder.BuildSystemFragmentComposer):
107
108    def __init__(self, sym, dep, cflags = None, includes = None):
109        self.sym = sym
110        self.dep = dep
111        self.cflags, self.includes = _cflagsIncludes(cflags, includes)
112
113    def compose(self, path):
114        d = { 'file': path,
115              'sym': self.sym,
116              'dep': self.dep }
117        if None not in self.cflags:
118            d['cflags'] = self.cflags
119        if None not in self.includes:
120            d['includes'] = self.includes
121        return ['lex', path], d
122
123class YaccFragmentComposer(builder.BuildSystemFragmentComposer):
124
125    def __init__(self, sym, header, cflags = None, includes = None):
126        self.sym = sym
127        self.header = header
128        self.cflags, self.includes = _cflagsIncludes(cflags, includes)
129
130    def compose(self, path):
131        d = { 'file': path,
132              'sym': self.sym,
133              'header': self.header }
134        if None not in self.cflags:
135            d['cflags'] = self.cflags
136        if None not in self.includes:
137            d['includes'] = self.includes
138        return ['yacc', path], d
139
140# Module Manager - Collection of Modules
141class ModuleManager(builder.ModuleManager):
142
143    def restart(self):
144        self.script = ''
145
146    def add(self, line = ''):
147        self.script += line + os.linesep
148
149    def write(self):
150        name = os.path.join(builder.RTEMS_DIR, 'libbsd_waf.py')
151        converter = builder.Converter()
152        converter.convert(name, name, srcContents = self.script)
153
154    def setGenerators(self):
155        self.generator['convert'] = builder.Converter
156        self.generator['no-convert'] = builder.NoConverter
157
158        self.generator['file'] = builder.File
159
160        self.generator['path'] = builder.PathComposer
161        self.generator['freebsd-path'] = builder.FreeBSDPathComposer
162        self.generator['rtems-path'] = builder.RTEMSPathComposer
163        self.generator['cpu-path'] = builder.CPUDependentPathComposer
164        self.generator['target-src-cpu--path'] = builder.TargetSourceCPUDependentPathComposer
165
166        self.generator['source'] = SourceFileFragmentComposer
167        self.generator['test'] = TestFragementComposer
168        self.generator['kvm-symbols'] = KVMSymbolsFragmentComposer
169        self.generator['rpc-gen'] = RPCGENFragmentComposer
170        self.generator['route-keywords'] = RouteKeywordsFragmentComposer
171        self.generator['lex'] = LexFragmentComposer
172        self.generator['yacc'] = YaccFragmentComposer
173
174    def generate(self, rtems_version):
175
176        def _sourceList(lhs, files, append = False):
177            if append:
178                adder = '+'
179                adderSpace = ' '
180            else:
181                adder = ''
182                adderSpace = ''
183            ll = len(lhs)
184            if len(files) == 1:
185                self.add('%s %s= [%r]' % (lhs, adder, files[0]))
186            elif len(files) == 2:
187                self.add('%s %s= [%r,' % (lhs, adder, files[0]))
188                self.add('%s %s   %r]' % (' ' * ll, adderSpace, files[-1]))
189            elif len(files) > 0:
190                self.add('%s %s= [%r,' % (lhs, adder, files[0]))
191                for f in files[1:-1]:
192                    self.add('%s %s   %r,' % (' ' * ll, adderSpace, f))
193                self.add('%s %s   %r]' % (' ' * ll, adderSpace, files[-1]))
194
195        def _dataInsert(data, cpu, frag):
196            #
197            # The default handler returns an empty string. Skip it.
198            #
199            if type(frag) is not str:
200                # Start at the top of the tree
201                d = data
202                path = frag[0]
203                if path[0] not in d:
204                    d[path[0]] = {}
205                # Select the sub-part of the tree as the compile options
206                # specialise how files are built.
207                d = d[path[0]]
208                if type(path[1]) is list:
209                    p = ' '.join(path[1])
210                else:
211                    p = path[1]
212                if p not in d:
213                    d[p] = {}
214                d = d[p]
215                if cpu not in d:
216                    d[cpu] = []
217                if type(frag[1]) is list:
218                    d[cpu] += frag[1]
219                else:
220                    d[cpu] = frag[1]
221                if len(frag) > 3:
222                    if 'cflags' not in d[cpu]:
223                        d['cflags'] = []
224                    d['cflags'] += frag[2]
225                if len(frag) >= 3 and None not in frag[-1]:
226                    if 'includes' not in d[cpu]:
227                        d['includes'] = []
228                    d['includes'] += frag[-1]
229
230        data = { }
231
232        for mn in self.getModules():
233            m = self[mn]
234            if m.conditionalOn == "none":
235                for f in m.files:
236                    _dataInsert(data, 'all', f.getFragment())
237            for cpu, files in sorted(m.cpuDependentSourceFiles.items()):
238                for f in files:
239                    _dataInsert(data, cpu, f.getFragment())
240
241        if trace:
242            import pprint
243            pprint.pprint(data)
244
245        self.restart()
246
247        self.add('#')
248        self.add('# RTEMS Project (https://www.rtems.org)')
249        self.add('#')
250        self.add('# Generated waf script. Do not edit, run ./freebsd-to-rtems.py -m')
251        self.add('#')
252        self.add('# To use see README.waf shipped with this file.')
253        self.add('#')
254        self.add('')
255        self.add('from __future__ import print_function')
256        self.add('')
257        self.add('import os')
258        self.add('import os.path')
259        # Import check done in the top level wscript file.
260        self.add('import rtems_waf.rtems as rtems')
261        self.add('')
262        self.add('windows = os.name == "nt"')
263        self.add('')
264        self.add('if windows:')
265        self.add('    host_shell = "sh -c "')
266        self.add('else:')
267        self.add('    host_shell = ""')
268        self.add('')
269        self.add('def init(ctx):')
270        self.add('    pass')
271        self.add('')
272        self.add('def options(opt):')
273        self.add('    pass')
274        self.add('')
275        self.add('def bsp_configure(conf, arch_bsp):')
276        self.add('    pass')
277        self.add('')
278        self.add('def configure(conf):')
279        self.add('    pass')
280        self.add('')
281        self.add('def build(bld):')
282        self.add('    # C/C++ flags')
283        self.add('    common_flags = []')
284        for f in builder.commonFlags():
285            self.add('    common_flags += ["%s"]' % (f))
286        self.add('    if bld.env.WARNINGS:')
287        for f in builder.commonWarnings():
288            self.add('        common_flags += ["%s"]' % (f))
289        self.add('    else:')
290        for f in builder.commonNoWarnings():
291            self.add('        common_flags += ["%s"]' % (f))
292        self.add('    cflags = %r + common_flags' % (builder.cflags()))
293        self.add('    cxxflags = %r + common_flags' % (builder.cxxflags()))
294        self.add('')
295        self.add('    # Defines')
296        self.add('    defines = []')
297        self.add('    if len(bld.env.FREEBSD_OPTIONS) > 0:')
298        self.add('        for o in bld.env.FREEBSD_OPTIONS.split(","):')
299        self.add('            defines += ["%s=1" % (o.strip().upper())]')
300        self.add('')
301        self.add('    # Include paths')
302        self.add('    includes = []')
303        self.add('    for i in %r:' % (builder.cpuIncludes()))
304        self.add('        includes += ["%s" % (i[2:].replace("@CPU@", bld.get_env()["RTEMS_ARCH"]))]')
305        self.add('    if bld.get_env()["RTEMS_ARCH"] == "i386":')
306        self.add('        for i in %r:' % (builder.cpuIncludes()))
307        self.add('            includes += ["%s" % (i[2:].replace("@CPU@", "x86"))]')
308        for i in builder.includes():
309            self.add('    includes += ["%s"]' % (i[2:]))
310        self.add('')
311        self.add('    # Collect the libbsd uses')
312        self.add('    libbsd_use = []')
313        self.add('')
314
315        #
316        # Support the existing Makefile based network configuration file.
317        #
318        self.add('    # Network test configuration')
319        self.add('    if not os.path.exists(bld.env.NET_CONFIG):')
320        self.add('        bld.fatal("network configuraiton \'%s\' not found" % (bld.env.NET_CONFIG))')
321        self.add('    net_cfg_self_ip = None')
322        self.add('    net_cfg_netmask = None')
323        self.add('    net_cfg_peer_ip = None')
324        self.add('    net_cfg_gateway_ip = None')
325        self.add('    net_tap_interface = None')
326        self.add('    try:')
327        self.add('        net_cfg_lines = open(bld.env.NET_CONFIG).readlines()')
328        self.add('    except:')
329        self.add('        bld.fatal("network configuraiton \'%s\' read failed" % (bld.env.NET_CONFIG))')
330        self.add('    lc = 0')
331        self.add('    for l in net_cfg_lines:')
332        self.add('        lc += 1')
333        self.add('        if l.strip().startswith("NET_CFG_"):')
334        self.add('            ls = l.split("=")')
335        self.add('            if len(ls) != 2:')
336        self.add('                bld.fatal("network configuraiton \'%s\' parse error: %d: %s" % ' + \
337                 '(bld.env.NET_CONFIG, lc, l))')
338        self.add('            lhs = ls[0].strip()')
339        self.add('            rhs = ls[1].strip()')
340        self.add('            if lhs == "NET_CFG_SELF_IP":')
341        self.add('                net_cfg_self_ip = rhs')
342        self.add('            if lhs == "NET_CFG_NETMASK":')
343        self.add('                net_cfg_netmask = rhs')
344        self.add('            if lhs == "NET_CFG_PEER_IP":')
345        self.add('                net_cfg_peer_ip = rhs')
346        self.add('            if lhs == "NET_CFG_GATEWAY_IP":')
347        self.add('                net_cfg_gateway_ip = rhs')
348        self.add('            if lhs == "NET_TAP_INTERFACE":')
349        self.add('                net_tap_interface = rhs')
350        self.add('    bld(target = "testsuite/include/rtems/bsd/test/network-config.h",')
351        self.add('        source = "testsuite/include/rtems/bsd/test/network-config.h.in",')
352        self.add('        rule = "sed -e \'s/@NET_CFG_SELF_IP@/%s/\' ' + \
353                 '-e \'s/@NET_CFG_NETMASK@/%s/\' ' + \
354                 '-e \'s/@NET_CFG_PEER_IP@/%s/\' ' + \
355                 '-e \'s/@NET_CFG_GATEWAY_IP@/%s/\' < ${SRC} > ${TGT}" % ' + \
356                 '(net_cfg_self_ip, net_cfg_netmask, net_cfg_peer_ip, net_cfg_gateway_ip),')
357        self.add('        update_outputs = True)')
358        self.add('')
359
360        #
361        # Add the specific rule based builders for generating files.
362        #
363        if 'KVMSymbols' in data:
364            kvmsymbols = data['KVMSymbols']
365            if 'includes' in kvmsymbols['files']:
366                includes = kvmsymbols['files']['includes']
367            else:
368                includes = []
369            self.add('    # KVM Symbols')
370            self.add('    bld(target = "%s",' % (kvmsymbols['files']['all'][0]))
371            self.add('        source = "rtemsbsd/rtems/generate_kvm_symbols",')
372            self.add('        rule = host_shell + "./${SRC} > ${TGT}",')
373            self.add('        update_outputs = True)')
374            self.add('    bld.objects(target = "kvmsymbols",')
375            self.add('                features = "c",')
376            self.add('                cflags = cflags,')
377            self.add('                includes = %r + includes,' % (includes))
378            self.add('                source = "%s")' % (kvmsymbols['files']['all'][0]))
379            self.add('    libbsd_use += ["kvmsymbols"]')
380            self.add('')
381
382        self.add('    bld.add_group()')
383
384        if 'RPCGen' in data:
385            rpcgen = data['RPCGen']
386            rpcname = rpcgen['files']['all'][0][:-2]
387            self.add('    # RPC Generation')
388            self.add('    if bld.env.AUTO_REGEN:')
389            self.add('        bld(target = "%s.h",' % (rpcname))
390            self.add('            source = "%s.x",' % (rpcname))
391            self.add('            rule = host_shell + "${RPCGEN} -h -o ${TGT} ${SRC}")')
392            self.add('')
393
394        if 'RouteKeywords' in data:
395            routekw = data['RouteKeywords']
396            rkwname = routekw['files']['all'][0]
397            self.add('    # Route keywords')
398            self.add('    if bld.env.AUTO_REGEN:')
399            self.add('        rkw_rule = host_shell + "cat ${SRC} | ' + \
400                     'awk \'BEGIN { r = 0 } { if (NF == 1) ' + \
401                     'printf \\"#define\\\\tK_%%s\\\\t%%d\\\\n\\\\t{\\\\\\"%%s\\\\\\", K_%%s},\\\\n\\", ' + \
402                     'toupper($1), ++r, $1, toupper($1)}\' > ${TGT}"')
403            self.add('        bld(target = "%s.h",' % (rkwname))
404            self.add('            source = "%s",' % (rkwname))
405            self.add('            rule = rkw_rule)')
406            self.add('')
407
408        if 'lex' in data:
409            lexes = data['lex']
410            self.add('    # Lex')
411            for l in sorted(lexes.keys()):
412                lex = lexes[l]['all']
413                if 'cflags' in lex:
414                    lexDefines = [d[2:] for d in lex['cflags']]
415                else:
416                    lexDefines = []
417                if 'includes' in lex:
418                    lexIncludes = lex['includes']
419                else:
420                    lexIncludes = []
421                self.add('    if bld.env.AUTO_REGEN:')
422                self.add('        bld(target = "%s.c",' % (lex['file'][:-2]))
423                self.add('            source = "%s",' % (lex['file']))
424                self.add('            rule = host_shell + "${LEX} -P %s -t ${SRC} | ' % (lex['sym']) + \
425                         'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' > ${TGT}")')
426                self.add('    bld.objects(target = "lex_%s",' % (lex['sym']))
427                self.add('                features = "c",')
428                self.add('                cflags = cflags,')
429                self.add('                includes = %r + includes,' % (lexIncludes))
430                self.add('                defines = defines + %r,' % (lexDefines))
431                self.add('                source = "%s.c")' % (lex['file'][:-2]))
432                self.add('    libbsd_use += ["lex_%s"]' % (lex['sym']))
433                self.add('')
434
435        if 'yacc' in data:
436            yaccs = data['yacc']
437            self.add('    # Yacc')
438            for y in sorted(yaccs.keys()):
439                yacc = yaccs[y]['all']
440                yaccFile = yacc['file']
441                if yacc['sym'] is not None:
442                    yaccSym = yacc['sym']
443                else:
444                    yaccSym = os.path.basename(yaccFile)[:-2]
445                yaccHeader = '%s/%s' % (os.path.dirname(yaccFile), yacc['header'])
446                if 'cflags' in yacc:
447                    yaccDefines = [d[2:] for d in yacc['cflags']]
448                else:
449                    yaccDefines = []
450                if 'includes' in yacc:
451                    yaccIncludes = yacc['includes']
452                else:
453                    yaccIncludes = []
454                self.add('    if bld.env.AUTO_REGEN:')
455                self.add('        bld(target = "%s.c",' % (yaccFile[:-2]))
456                self.add('            source = "%s",' % (yaccFile))
457                self.add('            rule = host_shell + "${YACC} -b %s -d -p %s ${SRC} && ' % \
458                         (yaccSym, yaccSym) + \
459                         'sed -e \'/YY_BUF_SIZE/s/16384/1024/\' < %s.tab.c > ${TGT} && ' % (yaccSym) + \
460                         'rm -f %s.tab.c && mv %s.tab.h %s")' % (yaccSym, yaccSym, yaccHeader))
461                self.add('    bld.objects(target = "yacc_%s",' % (yaccSym))
462                self.add('                features = "c",')
463                self.add('                cflags = cflags,')
464                self.add('                includes = %r + includes,' % (yaccIncludes))
465                self.add('                defines = defines + %r,' % (yaccDefines))
466                self.add('                source = "%s.c")' % (yaccFile[:-2]))
467                self.add('    libbsd_use += ["yacc_%s"]' % (yaccSym))
468            self.add('')
469
470        #
471        # We have 'm' different sets of flags and there can be 'n' cpus
472        # specific files for those flags.
473        #
474        objs = 0
475        self.add('    # Objects built with different CFLAGS')
476        for flags in sorted(data['sources']):
477            if flags is not 'default':
478                objs += 1
479                _sourceList('    objs%02d_source' % objs, sorted(data['sources'][flags]['all']))
480                archs = sorted(data['sources'][flags])
481                for arch in archs:
482                    if arch not in ['all', 'cflags', 'includes']:
483                        self.add('    if bld.get_env()["RTEMS_ARCH"] == "%s":' % arch)
484                        _sourceList('        objs%02d_source' % objs,
485                                    sorted(data['sources'][flags][arch]),
486                                    append = True)
487                if 'cflags' in data['sources'][flags]:
488                    defines = [d[2:] for d in data['sources'][flags]['cflags']]
489                else:
490                    defines = []
491                if 'includes' in data['sources'][flags]:
492                    includes = data['sources'][flags]['includes']
493                else:
494                    includes = []
495                self.add('    bld.objects(target = "objs%02d",' % (objs))
496                self.add('                features = "c",')
497                self.add('                cflags = cflags,')
498                self.add('                includes = %r + includes,' % (includes))
499                self.add('                defines = defines + %r,' % (defines))
500                self.add('                source = objs%02d_source)' % objs)
501                self.add('    libbsd_use += ["objs%02d"]' % (objs))
502                self.add('')
503
504        #
505        # We hold the 'default' cflags set of files to the end to create the
506        # static library with.
507        #
508        _sourceList('    source', sorted(data['sources']['default']['all']))
509        archs = sorted(data['sources']['default'])
510        for arch in archs:
511            if arch is not 'all':
512                self.add('    if bld.get_env()["RTEMS_ARCH"] == "%s":' % arch)
513                _sourceList('        source',
514                            sorted(data['sources']['default'][arch]),
515                            append = True)
516        self.add('    bld.stlib(target = "bsd",')
517        self.add('              features = "c cxx",')
518        self.add('              cflags = cflags,')
519        self.add('              cxxflags = cxxflags,')
520        self.add('              includes = includes,')
521        self.add('              defines = defines,')
522        self.add('              source = source,')
523        self.add('              use = libbsd_use)')
524        self.add('')
525
526        #
527        # Head file collector.
528        #
529        self.add('    # Installs.    ')
530        self.add('    bld.install_files("${PREFIX}/" + rtems.arch_bsp_lib_path(bld.env.RTEMS_VERSION, bld.env.RTEMS_ARCH_BSP), ["libbsd.a"])')
531        headerPaths = builder.headerPaths()
532        self.add('    header_paths = [%s,' % (str(headerPaths[0])))
533        for hp in headerPaths[1:-1]:
534            self.add('                     %s,' % (str(hp)))
535        self.add('                     %s]' % (str(headerPaths[-1])))
536        self.add('    for headers in header_paths:')
537        self.add('        ipath = os.path.join(rtems.arch_bsp_include_path(bld.env.RTEMS_VERSION, bld.env.RTEMS_ARCH_BSP), headers[2])')
538        self.add('        start_dir = bld.path.find_dir(headers[0])')
539        self.add('        bld.install_files("${PREFIX}/" + ipath,')
540        self.add('                          start_dir.ant_glob("**/" + headers[1]),')
541        self.add('                          cwd = start_dir,')
542        self.add('                          relative_trick = True)')
543        self.add('')
544
545        self.add('    # Tests')
546        tests = data['tests']
547        for testName in sorted(tests):
548            files = ['testsuite/%s/%s.c' % (testName, f) for f in  data['tests'][testName]['all']['files']]
549            _sourceList('    test_%s' % (testName), sorted(files))
550            self.add('    bld.program(target = "%s.exe",' % (testName))
551            self.add('                features = "cprogram",')
552            self.add('                cflags = cflags,')
553            self.add('                includes = includes,')
554            self.add('                source = test_%s,' % (testName))
555            self.add('                use = ["bsd"],')
556            self.add('                lib = ["m", "z"],')
557            self.add('                install_path = None)')
558            self.add('')
559
560        self.write()
Note: See TracBrowser for help on using the repository browser.