summaryrefslogtreecommitdiffstats
path: root/rtemstoolkit/rtems.py
blob: 30c8c16eefe5182b4c2eec200d2179cb35284e24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#
# RTEMS Tools Project (http://www.rtems.org/)
# Copyright 2016-2018 Chris Johns (chrisj@rtems.org)
# All rights reserved.
#
# This file is part of the RTEMS Tools package in 'rtems-tools'.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

from __future__ import print_function

import copy
import os
import re
import sys
import textwrap

from rtemstoolkit import configuration as configuration_
from rtemstoolkit import error
from rtemstoolkit import path
from rtemstoolkit import textbox

#
# The default path we install RTEMS under
#
_prefix_path = '/opt/rtems'

def default_prefix():
    from rtemstoolkit import version
    return path.join(_prefix_path, version.version())

def clean_windows_path():
    '''On Windows MSYS2 prepends a path to itself to the environment path. This
    means the RTEMS specific automake is not found and which breaks the
    bootstrap. We need to remove the prepended path. Also remove any ACLOCAL
    paths from the environment.

    '''
    if os.name == 'nt':
        cspath = os.environ['PATH'].split(os.pathsep)
        if 'msys' in cspath[0] and cspath[0].endswith('bin'):
            os.environ['PATH'] = os.pathsep.join(cspath[1:])

def configuration_path(prog = None):
    '''Return the path the configuration data path for RTEMS. The path is relative
    to the installed executable. Mangage the installed package and the in source
    tree when running from within the rtems-tools repo.
    Note:
     1. This code assumes the executable is wrapped and not using 'env'.
     2. Ok to directly call os.path.
    '''
    if prog is None:
        if len(sys.argv) == 1:
            exec_name = sys.argv[0]
        else:
            exec_name = sys.argv[1]
    else:
        exec_name = prog
    exec_name = os.path.abspath(exec_name)
    for top in [os.path.dirname(os.path.dirname(exec_name)),
                os.path.dirname(exec_name)]:
        config_path = path.join(top, 'share', 'rtems', 'config')
        if path.exists(config_path):
            break
        config_path = path.join(top, 'config')
        if path.exists(config_path):
            break
        config_path = None
    return config_path

def configuration_file(config, prog = None):
    '''Return the path to a configuration file for RTEMS. The path is relative to
    the installed executable or we are testing and running from within the
    rtems-tools repo.

    '''
    return path.join(configuration_path(prog = prog), config)

def bsp_configuration_file(prog = None):
    '''Return the path to the BSP configuration file for RTEMS. The path is
    relative to the installed executable or we are testing and running from
    within the rtems-tools repo.

    '''
    return configuration_file('rtems-bsps.ini', prog = prog)

class configuration:

    def __init__(self):
        self.config = configuration_.configuration(raw = False)
        self.archs = { }
        self.profiles = { }

    def __str__(self):
        s = self.name + os.linesep
        s += 'Archs:' + os.linesep + \
             pprint.pformat(self.archs, indent = 1, width = 80) + os.linesep
        s += 'Profiles:' + os.linesep + \
             pprint.pformat(self.profiles, indent = 1, width = 80) + os.linesep
        return s

    def _build_options(self, build, nesting = 0):
        if ':' in build:
            section, name = build.split(':', 1)
            opts = [self.config.get_item(section, name)]
            return opts
        builds = self.builds_['builds']
        if build not in builds:
            raise error.general('build %s not found' % (build))
        if nesting > 20:
            raise error.general('nesting build %s' % (build))
        options = []
        for option in self.builds_['builds'][build]:
            if ':' in option:
                section, name = option.split(':', 1)
                opts = [self.config.get_item(section, name)]
            else:
                opts = self._build_options(option, nesting + 1)
            for opt in opts:
                if opt not in options:
                    options += [opt]
        return options

    def load(self, name, build):
        self.config.load(name)
        archs = []
        self.profiles['profiles'] = \
            self.config.comma_list('profiles', 'profiles', err = False)
        if len(self.profiles['profiles']) == 0:
            self.profiles['profiles'] = ['tier-%d' % (t) for t in range(1,4)]
        for p in self.profiles['profiles']:
            profile = {}
            profile['name'] = p
            profile['archs'] = self.config.comma_list(profile['name'], 'archs', err = False)
            archs += profile['archs']
            for arch in profile['archs']:
                bsps = 'bsps_%s' % (arch)
                profile[bsps] = self.config.comma_list(profile['name'], bsps)
            self.profiles[profile['name']] = profile
        invalid_chars = re.compile(r'[^a-zA-Z0-9_-]')
        for a in set(archs):
            if len(invalid_chars.findall(a)) != 0:
                raise error.general('invalid character(s) in arch name: %s' % (a))
            arch = {}
            arch['excludes'] = {}
            for exclude in self.config.comma_list(a, 'exclude', err = False):
                arch['excludes'][exclude] = ['all']
            for i in self.config.get_items(a, False):
                if i[0].startswith('exclude-'):
                    exclude = i[0][len('exclude-'):]
                    if exclude not in arch['excludes']:
                        arch['excludes'][exclude] = []
                    arch['excludes'][exclude] += \
                        sorted(set([b.strip() for b in i[1].split(',')]))
            arch['bsps'] = self.config.comma_list(a, 'bsps', err = False)
            for b in arch['bsps']:
                if len(invalid_chars.findall(b)) != 0:
                    raise error.general('invalid character(s) in BSP name: %s' % (b))
                arch[b] = {}
                arch[b]['bspopts'] = \
                    self.config.comma_list(a, 'bspopts_%s' % (b), err = False)
            self.archs[a] = arch
        builds = {}
        builds['default'] = self.config.get_item('builds', 'default')
        if build is None:
            build = builds['default']
        builds['config'] = { }
        for config in self.config.get_items('config'):
            builds['config'][config[0]] = config[1]
        builds['build'] = build
        builds_ = self.config.get_item_names('builds')
        builds['builds'] = {}
        for build in builds_:
            build_builds = self.config.comma_list('builds', build)
            has_config = False
            has_build = False
            for b in build_builds:
                if ':' in b:
                    if has_build:
                        raise error.general('config and build in build: %s' % (build))
                    has_config = True
                else:
                    if has_config:
                        raise error.general('config and build in build: %s' % (build))
                    has_build = True
            builds['builds'][build] = build_builds
        self.builds_ = builds

    def configs(self):
        return sorted(list(self.builds_['config'].keys()))

    def config_flags(self, config):
        if config not in self.builds_['config']:
            raise error.general('config entry not found: %s' % (config))
        return self.builds_['config'][config]

    def build(self):
        return self.builds_['build']

    def builds(self):
        if self.builds_['build'] in self.builds_['builds']:
            build = copy.copy(self.builds_['builds'][self.builds_['build']])
            if ':' in build[0]:
                return [self.builds_['build']]
            return build
        return None

    def build_options(self, build):
        return ' '.join(self._build_options(build))

    def excludes(self, arch, bsp):
        return list(set(self.arch_excludes(arch) + self.bsp_excludes(arch, bsp)))

    def exclude_options(self, arch, bsp):
        return ' '.join([self.config_flags('no-' + e) for e in self.excludes(arch, bsp)])

    def archs(self):
        return sorted(list(self.archs.keys()))

    def arch_present(self, arch):
        return arch in self.archs

    def arch_excludes(self, arch):
        excludes = list(self.archs[arch]['excludes'].keys())
        for exclude in self.archs[arch]['excludes']:
            if 'all' not in self.archs[arch]['excludes'][exclude]:
                excludes.remove(exclude)
        return sorted(excludes)

    def arch_bsps(self, arch):
        return sorted(self.archs[arch]['bsps'])

    def bsp_present(self, arch, bsp):
        return bsp in self.archs[arch]['bsps']

    def bsp_excludes(self, arch, bsp):
        excludes = list(self.archs[arch]['excludes'].keys())
        for exclude in self.archs[arch]['excludes']:
            if 'all' not in self.archs[arch]['excludes'][exclude] and \
               bsp not in self.archs[arch]['excludes'][exclude]:
                excludes.remove(exclude)
        return sorted(excludes)

    def bspopts(self, arch, bsp):
        if arch not in self.archs:
            raise error.general('invalid architecture: %s' % (arch))
        if bsp not in self.archs[arch]:
            raise error.general('invalid BSP: %s' % (bsp))
        return self.archs[arch][bsp]['bspopts']

    def profile_present(self, profile):
        return profile in self.profiles

    def profile_archs(self, profile):
        if profile not in self.profiles:
            raise error.general('invalid profile: %s' % (profile))
        return self.profiles[profile]['archs']

    def profile_arch_bsps(self, profile, arch):
        if profile not in self.profiles:
            raise error.general('invalid profile: %s' % (profile))
        if 'bsps_%s' % (arch) not in self.profiles[profile]:
            raise error.general('invalid profile arch: %s' % (arch))
        return ['%s/%s' % (arch, bsp) for bsp in self.profiles[profile]['bsps_%s' % (arch)]]

    def report(self, profiles = True, builds = True, architectures = True):
        width = 70
        cols_1 = [width]
        cols_2 = [10, width - 10]
        s = textbox.line(cols_1, line = '=', marker = '+', indent = 1)
        s1 = ' File(s)'
        for f in self.config.files():
            colon = ':'
            for l in textwrap.wrap(f, width = cols_2[1] - 3):
                s += textbox.row(cols_2, [s1, ' ' + l], marker = colon, indent = 1)
                colon = ' '
                s1 = ' ' * len(s1)
        s += textbox.line(cols_1, marker = '+', indent = 1)
        s += os.linesep
        if profiles:
            s += textbox.line(cols_1, line = '=', marker = '+', indent = 1)
            profiles = sorted(self.profiles['profiles'])
            archs = []
            bsps = []
            for profile in profiles:
                archs += self.profiles[profile]['archs']
                for arch in sorted(self.profiles[profile]['archs']):
                    bsps += self.profiles[profile]['bsps_%s' % (arch)]
            archs = len(set(archs))
            bsps = len(set(bsps))
            s += textbox.row(cols_1,
                             [' Profiles : %d (archs:%d, bsps:%d)' % \
                              (len(profiles), archs, bsps)],
                             indent = 1)
            for profile in profiles:
                textbox.row(cols_2,
                            [profile, self.profiles[profile]['name']],
                            indent = 1)
            s += textbox.line(cols_1, marker = '+', indent = 1)
            for profile in profiles:
                s += textbox.row(cols_1, [' %s' % (profile)], indent = 1)
                profile = self.profiles[profile]
                archs = sorted(profile['archs'])
                for arch in archs:
                    arch_bsps = ', '.join(profile['bsps_%s' % (arch)])
                    if len(arch_bsps) > 0:
                        s += textbox.line(cols_2, marker = '+', indent = 1)
                        s1 = ' ' + arch
                        for l in textwrap.wrap(arch_bsps,
                                               width = cols_2[1] - 3):
                            s += textbox.row(cols_2, [s1, ' ' + l], indent = 1)
                            s1 = ' ' * len(s1)
                s += textbox.line(cols_2, marker = '+', indent = 1)
            s += os.linesep
        if builds:
            s += textbox.line(cols_1, line = '=', marker = '+', indent = 1)
            s += textbox.row(cols_1,
                             [' Builds:  %s (default)' % (self.builds_['default'])],
                             indent = 1)
            builds = self.builds_['builds']
            bsize = 0
            for build in builds:
                if len(build) > bsize:
                    bsize = len(build)
            cols_b = [bsize + 2, width - bsize - 2]
            s += textbox.line(cols_b, marker = '+', indent = 1)
            for build in builds:
                s1 = ' ' + build
                for l in textwrap.wrap(', '.join(builds[build]),
                                       width = cols_b[1] - 3):
                    s += textbox.row(cols_b, [s1, ' ' + l], indent = 1)
                    s1 = ' ' * len(s1)
                s += textbox.line(cols_b, marker = '+', indent = 1)
            configs = self.builds_['config']
            s += textbox.row(cols_1,
                             [' Configure Options: %d' % (len(configs))],
                             indent = 1)
            csize = 0
            for config in configs:
                if len(config) > csize:
                    csize = len(config)
            cols_c = [csize + 3, width - csize - 3]
            s += textbox.line(cols_c, marker = '+', indent = 1)
            for config in configs:
                s1 = ' ' + config
                for l in textwrap.wrap(configs[config], width = cols_c[1] - 3):
                    s += textbox.row(cols_c, [s1, ' ' + l], indent = 1)
                    s1 = ' ' * len(s1)
                s += textbox.line(cols_c, marker = '+', indent = 1)
            s += os.linesep
        if architectures:
            s += textbox.line(cols_1, line = '=', marker = '+', indent = 1)
            archs = sorted(list(self.archs.keys()))
            bsps = 0
            asize = 0
            for arch in archs:
                if len(arch) > asize:
                    asize = len(arch)
                bsps += len(self.archs[arch]['bsps'])
            s += textbox.row(cols_1,
                             [' Architectures : %d (bsps: %d)' % (len(archs), bsps)],
                             indent = 1)
            cols_a = [asize + 2, width - asize - 2]
            s += textbox.line(cols_a, marker = '+', indent = 1)
            for arch in archs:
                s += textbox.row(cols_a,
                                 [' ' + arch, ' %d' % (len(self.archs[arch]['bsps']))],
                                 indent = 1)
            s += textbox.line(cols_a, marker = '+', indent = 1)
            for archn in archs:
                arch = self.archs[archn]
                if len(arch['bsps']) > 0:
                    bsize = 0
                    for bsp in arch['bsps']:
                        if len(bsp) > bsize:
                            bsize = len(bsp)
                    cols_b = [bsize + 3, width - bsize - 3]
                    s += textbox.row(cols_1, [' ' + archn + ':'], indent = 1)
                    s += textbox.line(cols_b, marker = '+', indent = 1)
                    for bsp in arch['bsps']:
                        s1 = ' ' + bsp
                        bspopts = ' '.join(arch[bsp]['bspopts'])
                        if len(bspopts):
                            for l in textwrap.wrap('bopt: ' + bspopts,
                                                   width = cols_b[1] - 3):
                                s += textbox.row(cols_b, [s1, ' ' + l], indent = 1)
                                s1 = ' ' * len(s1)
                        excludes = []
                        for exclude in arch['excludes']:
                            if 'all' in arch['excludes'][exclude] or \
                               bsp in arch['excludes'][exclude]:
                                excludes += [exclude]
                        excludes = ', '.join(excludes)
                        if len(excludes):
                            for l in textwrap.wrap('ex: ' + excludes,
                                                   width = cols_b[1] - 3):
                                s += textbox.row(cols_b, [s1, ' ' + l], indent = 1)
                                s1 = ' ' * len(s1)
                        if len(bspopts) == 0 and len(excludes) == 0:
                            s += textbox.row(cols_b, [s1, ' '], indent = 1)
                    s += textbox.line(cols_b, marker = '+', indent = 1)
            s += os.linesep
        return s